text
string
size
int64
token_count
int64
''' 给定一个无向图graph,当这个图为二分图时返回true。 如果我们能将一个图的节点集合分割成两个独立的子集A和B,并使图中的每一条边的两个节点一个来自A集合,一个来自B集合,我们就将这个图称为二分图。 graph将会以邻接表方式给出,graph[i]表示图中与节点i相连的所有节点。每个节点都是一个在0到graph.length-1之间的整数。这图中没有自环和平行边: graph[i] 中不存在i,并且graph[i]中没有重复的值。 示例 1: 输入: [[1,3], [0,2], [1,3], [0,2]] 输出: true 解释: 无向图如下: 0----1 | | | | 3----2 我们可以将...
1,329
660
# -*- coding: utf-8 -*- """ Created on Tue Apr 17 06:44:47 2018 @author: Eleam Emmanuel """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.tree import DecisionTreeRegressor # importing the dataset dataset = pd.read_csv('Position_Salaries.csv') # take all the columns but leave the...
1,417
516
from django.apps import AppConfig from django.conf import settings from django.core import checks from django.template import engines from django.template.backends.django import DjangoTemplates from django.utils.text import capfirst from django.utils.translation import gettext_lazy as _ @checks.register() def check_c...
1,786
499
from itertools import product import numpy as np import pandas as pd import pytest from sklearn.metrics import matthews_corrcoef as sk_matthews_corrcoef from evalml.objectives import ( F1, MAPE, MSE, AccuracyBinary, AccuracyMulticlass, BalancedAccuracyBinary, BalancedAccuracyMulticlass, ...
20,671
9,086
import os import urllib.parse import eventlet import eventlet.green.socket # eventlet.monkey_patch() import eventlet.websocket import eventlet.wsgi import wspty.pipe from flask import Flask, request, redirect from wspty.EchoTerminal import EchoTerminal from wspty.EncodedTerminal import EncodedTerminal from wspty.Webso...
4,908
1,511
# -*- encoding: utf-8 -*- """ Unit test for roger_promote.py """ import tests.helper import unittest import os import os.path import pytest import requests from mockito import mock, Mock, when from cli.roger_promote import RogerPromote from cli.appconfig import AppConfig from cli.settings import Settings from cl...
3,406
1,077
import json import pandas as pd import requests def load_dump_covid_19_data(): COVID_19_BY_CITY_URL='https://raw.githubusercontent.com/wcota/covid19br/master/cases-brazil-cities-time.csv' by_city=(pd.read_csv(COVID_19_BY_CITY_URL) .query('country == "Brazil"') .drop(columns=['c...
7,097
2,274
import config as cfg import utils import native_code.executor as executor number_performed_tests = 0 expectations_correct = 0 expectations_wrong = 0 def reset_stats(): global number_performed_tests, expectations_correct, expectations_wrong number_performed_tests = 0 expectations_correct = 0 expecta...
5,976
1,715
from .one import * fruit = 'banana' colour = 'orange' sam['eggs'] = 'plenty' sam.pop('ham')
99
48
from django.urls import path, include from rest_framework_jwt.views import obtain_jwt_token from rest_framework.routers import DefaultRouter from .views import NoteViewSet app_name = 'api' router = DefaultRouter(trailing_slash=False) router.register('notes', NoteViewSet) urlpatterns = [ path('jwt-auth/', obtain...
371
118
from planning_framework import path import cv2 as cv import numpy as np import argparse import matplotlib.pyplot as plt parser = argparse.ArgumentParser(description="Path Planning Visualisation") parser.add_argument( "-n", "--n_heuristic", default=2, help="Heuristic for A* Algorithm (default = 2). 0 f...
2,387
977
n = int(input()) line = list(map(int, input().split())) l = {} res = "" for i, j in enumerate(line): l[j] = i+1 for k in range(n): res += str(l[k+1]) + " " print(res.rstrip())
186
82
import pandas as pd def main(): input = pd.read_csv('random_x.csv', header=None) x=input[0].tolist() y = [] for n in x: y.append(3*int(n)+6) df = pd.DataFrame(y) df.to_csv('output_y.csv', index=False, header=False) if __name__ == '__main__': main() print('generating y = 3x+6.....
323
131
import re from pkg_resources import parse_requirements import pathlib from setuptools import find_packages, setup README_FILE = 'README.md' REQUIREMENTS_FILE = 'requirements.txt' VERSION_FILE = 'mtg/_version.py' VERSION_REGEXP = r'^__version__ = \'(\d+\.\d+\.\d+)\'' r = re.search(VERSION_REGEXP, open(VERSION_FILE).r...
1,002
354
from __future__ import annotations from dataclasses import dataclass from avilla.core.platform import Base from avilla.core.resource import Resource, ResourceProvider @dataclass class ResourceMatchPrefix: resource_type: type[Resource] keypath: str | None = None platform: Base | None = None class Resou...
1,399
367
from skimage import data from skimage.filter.rank import median from skimage.morphology import disk from skimage.viewer import ImageViewer from skimage.viewer.widgets import Slider, OKCancelButtons, SaveButtons from skimage.viewer.plugins.base import Plugin def median_filter(image, radius): return median(image, s...
570
183
# Test the buoyancy package and the variable density flows between the lake # and the gwf model. This model has 4 layers and a lake incised within it. # The model is transient and has heads in the aquifer higher than the initial # stage in the lake. As the model runs, the lake and aquifer equalize and # should end up...
8,722
3,631
""" 功能:模拟掷骰子 版本:1.0 """ import random def roll_dice(): roll = random.randint(1, 6) return roll def main(): total_times = 100000 result_list = [0] * 6 for i in range(total_times): roll = roll_dice() result_list[roll-1] += 1 for i, x in enumerate(result_list): ...
441
201
import argparse import logging import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions def run(argv=None, save_main_session=True): """Dummy pipeline to test Python3 operator.""" parser = argparse.ArgumentParser() ...
759
248
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/11/30 下午3:02 # @Author : Matrix # @Github : https://github.com/blackmatrix7/ # @Blog : http://www.cnblogs.com/blackmatrix/ # @File : messages.py # @Software: PyCharm import json from ..foundation import * from json import JSONDecodeError __author__ = 'blackm...
1,727
668
from setuptools import setup, find_packages from os import path here = path.join(path.abspath(path.dirname(__file__)), 'garpix_page') with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='garpix_page', version='2.23.0', description='', long_desc...
1,412
488
# -*- coding: utf-8 -*- """ p2p-streams (c) 2014 enen92 fightnight This file contains the livestream addon engine. It is mostly based on divingmule work on livestreams addon! Functions: xml_lists_menu() -> main menu for the xml list category addlista() -> add a new list. It'll ask for local or rem...
20,225
6,221
from ric.RainItComposite import RainItComposite class Procedure(RainItComposite): def __init__(self): super().__init__() def get_pickle_form(self): return self
187
64
valor = int(input()) for i in range(valor+1): if(i%2 != 0): print(i)
81
36
#!/usr/bin/env python # ================================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # ================================================================ import sys import json import TE TE.Net.setAppTokenFromEnvName("TX_ACCESS_TOKEN") postPar...
889
293
# Copyright 2018 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 applicable law or a...
12,362
4,161
from flask import render_template, jsonify, Flask, redirect, url_for, request from app import app import random import os # import tensorflow as tf # import numpy as np # import sys # import spacy # nlp = spacy.load('en') # sys.path.insert(0, "/content/bert_experimental") # from bert_experimental.finetuning.text_pre...
2,177
799
# -*- coding: utf-8 -*- """ Complementary Filter ==================== Attitude quaternion obtained with gyroscope and accelerometer-magnetometer measurements, via complementary filter. First, the current orientation is estimated at time :math:`t`, from a previous orientation at time :math:`t-1`, and a given ...
11,710
4,095
# 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...
4,197
1,554
# -*- coding: utf-8 -*- # Copyright (c) 2016 Mirantis 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 ...
3,550
1,111
from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.utils.translation import ugettext_lazy as _ class Task(models.Model): CLOSE = 'cl' CANCEL = 'ca' LATER = 'la' UNDEFINED = 'un' CHOICES = ( ...
1,613
556
import numpy as np import hexy as hx def test_get_hex_line(): expected = [ [-3, 3, 0], [-2, 2, 0], [-1, 2, -1], [0, 2, -2], [1, 1, -2], ] start = np.array([-3, 3, 0]) end = np.array([1, 1, -2]) print(hx.get_hex_line(start, end)) ...
475
194
# propagate_2D_integral: Simplification of the Kirchhoff-Fresnel integral. TODO: Very slow and give some problems import numpy from wofry.propagator.wavefront2D.generic_wavefront import GenericWavefront2D from wofry.propagator.propagator import Propagator2D # TODO: check resulting amplitude normalization (fft and ...
6,747
1,988
# https://leetcode.com/problems/delete-and-earn/ class Solution: def deleteAndEarn(self, nums: list[int]) -> int: num_profits = dict() for num in nums: num_profits[num] = num_profits.get(num, 0) + num sorted_nums = sorted(num_profits.keys()) second_last_profit = 0 ...
842
282
# Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final mostre, os 10 primeiros termos dessa prograssão. primeiro = int(input("Primeiro Termo: ")) razao = int(input("Razão: ")) decimo = primeiro + (10 - 1) * razao for c in range(primeiro, decimo + razao, razao): print(f"{c}", end=" -> ") pr...
334
134
""" A :py:mod:`filter <tiddlyweb.filters>` type to limit a group of entities using a syntax similar to SQL Limit:: limit=<index>,<count> limit=<count> """ import itertools def limit_parse(count='0'): """ Parse the argument of a ``limit`` :py:mod:`filter <tiddlyweb.filters>` for a count and index...
884
280
""" Simple API to convert models between PyTorch and Keras (Conversions from Keras to PyTorch aren't implemented) """ from . import utility from . import tests from . import io_utils as utils import tensorflow def convert(model, input_shape, weights=True, quiet=True, i...
7,019
1,721
# -*- coding: utf-8 -*- """ Notifications ------------- Example showing how to add notifications to a characteristic and handle the responses. Updated on 2019-07-03 by hbldh <henrik.blidh@gmail.com> """ import sys import logging import asyncio import platform from bleak import BleakClient from bleak import _logger...
1,734
625
class BaseStorage(object): def get_rule(self, name): raise NotImplementedError() def get_ruleset(self, name): raise NotImplementedError()
163
50
#!/usr/bin/python import socket class Listener: def __init__(self,ip,port): listener = socket.socket(socket.AF_INET,socket.SOCK_STREAM) listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) #options to reuse sockets #listener.bind(("localhost",1234)) listener.bind((ip,port)) listener.listen(0) ...
820
312
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Convert Dialogflow history to spreadsheet User must manually copy the history from the browser and save this in a text file. This reads the textfile, parses the data, and saves it to a spreadsheet. Example training sample: USER サワディカ Nov 4, 11:19 PM AGENT No matc...
1,974
622
from django.shortcuts import render,redirect from .forms import usernameForm,DateForm,UsernameAndDateForm, DateForm_2 from django.contrib import messages from django.contrib.auth.models import User import cv2 import dlib import imutils from imutils import face_utils from imutils.video import VideoStream from imutils.fa...
25,176
10,631
import re import string DATA = '05.txt' def react(polymer): pairs = '|'.join([a + b + '|' + b + a for a, b in zip(string.ascii_lowercase, string.ascii_uppercase)]) length = len(polymer) while 1: polymer = re.sub(pairs, '', polymer) if len(polymer) == length: retu...
856
324
import abc import contextlib import os import sys from functools import partial from itertools import chain import fbuild import fbuild.db import fbuild.path import fbuild.temp from . import platform # ------------------------------------------------------------------------------ class MissingProgram(fbuild.ConfigFa...
11,873
3,407
import json import cherrypy import engine class WebServer(object): @cherrypy.expose def index(self): return open('public/index.html', encoding='utf-8') @cherrypy.expose class GetOptionsService(object): @cherrypy.tools.accept(media='text/plain') def GET(self): return json.dumps({ ...
1,746
479
from typing import Union from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.exception.error as errors from tuprolog.core import Term, Atom from tuprolog.solve import ExecutionContext, Signature ExistenceError = err...
1,897
614
from __future__ import annotations from typing import TYPE_CHECKING import pkg_resources from bs4 import BeautifulSoup from requests import session from cptk.scrape import PageInfo from cptk.scrape import Website from cptk.utils import cptkException if TYPE_CHECKING: from cptk.scrape import Problem class Inva...
2,421
699
import pybullet as p import pybullet_data import gym from gym import spaces from gym.utils import seeding import numpy as np from math import sqrt import random import time import math import cv2 import torch import os def random_crop(imgs, out): """ args: imgs: shape (B,C,H,W) ...
15,006
5,520
--- setup.py.orig 2019-07-02 19:13:39 UTC +++ setup.py @@ -465,9 +465,7 @@ class pil_build_ext(build_ext): _add_directory(include_dirs, "/usr/X11/include") elif ( - sys.platform.startswith("linux") - or sys.platform.startswith("gnu") - or sys.platform.startsw...
509
176
# Copyright 2019 Huawei Technologies Co., Ltd # # 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...
6,581
2,713
from abc import ABC from typing import Dict from redbot.core import Config from redbot.core.bot import Red from trainerdex.client import Client class MixinMeta(ABC): """ Base class for well behaved type hint detection with composite class. Basically, to keep developers sane when not all attributes are d...
486
137
import dash import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc import pandas as pd import numpy as np import altair as alt import vega_datasets alt.data_transformers.enable('default') alt.data_transformers.disable_max_rows() app = dash.Dash(__name__, assets_f...
7,044
2,078
# coding=utf-8 from .subspaces import *
40
15
import json import math from PIL import Image,ImageDraw import pandas as pd import glob import argparse import copy import numpy as np import matplotlib.pyplot as plt import pickle import cv2 from PIL import ImageEnhance import chainer from chainer.datasets import ConcatenatedDataset from chainer.data...
2,510
951
import os import pdb import warnings import numpy as np import torch import torch.nn as nn import torch.utils.data import torch.backends.cudnn import torch.optim as optim import dataloaders from utils.utils import AverageMeter from utils.loss import build_criterion from utils.metrics import Evaluator from utils.step_...
5,982
2,022
class Solution: # dictionary keys are tuples, storing results # structure of the tuple: # (level, prev_sum, val_to_include) # value is number of successful tuples def fourSumCount(self, A, B, C, D, prev_sum=0, level=0, sums={}): """ :type A: List[int] :type B: List[int] ...
1,883
592
# The MIT License (MIT) # Copyright (c) 2021 Tom J. Sun # 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, modify, ...
1,675
554
import re import six from smartfields.processors.base import ExternalFileProcessor from smartfields.utils import ProcessingError __all__ = [ 'FFMPEGProcessor' ] class FFMPEGProcessor(ExternalFileProcessor): duration_re = re.compile(r'Duration: (?P<hours>\d+):(?P<minutes>\d+):(?P<seconds>\d+)') progress_r...
1,788
536
## Program: VMTK ## Language: Python ## Date: January 12, 2018 ## Version: 1.4 ## Copyright (c) Richard Izzo, Luca Antiga, All rights reserved. ## See LICENSE file for details. ## This software is distributed WITHOUT ANY WARRANTY; without even ## the implied warranty of MERCHANTABILITY or FITNES...
2,192
761
from django import forms from nocaptcha_recaptcha.fields import NoReCaptchaField class NewsletterForm(forms.Form): email = forms.EmailField(label='Email', required=True, widget=forms.TextInput(attrs={ 'id': 'newsletter-email', ...
653
150
#! /bin/python3 # simple run menu import os import stat def is_file_executable(path): executable = stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH if not os.path.isfile(path): return False st = os.stat(path) mode = st.st_mode if not mode & executable: return False return True def get_files_in_dir(directory): i...
1,054
403
# Author: Jaakko Leppakangas <jaeilepp@student.jyu.fi> # Joan Massich <mailsik@gmail.com> # # License: BSD-3-Clause import os.path as op import numpy as np from numpy.testing import assert_array_equal import pytest from mne import pick_types from mne.datasets import testing from mne.io.tests.test_raw import...
1,792
656
import urllib.request, json import pandas as pd baseUrl = 'https://avoindata.eduskunta.fi/api/v1/tables/VaskiData' parameters = 'rows?columnName=Eduskuntatunnus&columnValue=LA%25&perPage=100' page = 0 df = '' while True: print(f'Fetching page number {page}') with urllib.request.urlopen(f'{baseUrl}/{parameters...
792
272
# -*- coding: utf-8 -*- """ Created on Mon Sep 20 16:15:37 2021 @author: em42363 """ # In[1]: Import functions ''' CatBoost is a high-performance open source library for gradient boosting on decision trees ''' from catboost import CatBoostRegressor from sklearn.model_selection import train_test_split import pandas a...
2,899
1,134
import logging from platform import system from tqdm import tqdm from multiprocessing import Lock loggers = {} # https://stackoverflow.com/questions/38543506/ class TqdmLoggingHandler(logging.Handler): def __init__(self, level=logging.NOTSET): super(TqdmLoggingHandler, self).__init__(level) def emit...
1,683
573
import cv2 import sys import playsound face_cascade = cv2.CascadeClassifier('cascades/haarcascade_frontalface_default.xml') # capture video using cv2 video_capture = cv2.VideoCapture(0) while True: # capture frame by frame, i.e, one by one ret, frame = video_capture.read() gray = cv2.cvtColor(frame...
1,243
431
# vim:set et sw=4 ts=4: import logging import sys import jmespath from . import sis, classes # logging logging.basicConfig(stream=sys.stdout, level=logging.WARNING) logger = logging.getLogger(__name__) # SIS endpoint enrollments_uri = "https://apis.berkeley.edu/sis/v2/enrollments" # apparently some courses have LA...
7,938
2,522
from flask import Flask, render_template, request, redirect, url_for from os.path import join from stego import Steganography app = Flask(__name__) UPLOAD_FOLDER = 'static/files/' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'} @app.route("/") def home(): return render_te...
1,913
611
from flatland.envs.agent_utils import RailAgentStatus from flatland.envs.malfunction_generators import malfunction_from_params, MalfunctionParameters from flatland.envs.observations import GlobalObsForRailEnv from flatland.envs.rail_env import RailEnv from flatland.envs.rail_generators import sparse_rail_generator from...
8,012
2,846
# -*- coding: utf-8 -*- # Generated by Django 2.2.4 on 2019-08-21 19:53 # this file is auto-generated so don't do flake8 on it # flake8: noqa from __future__ import absolute_import, unicode_literals from django.db import migrations, models import django.utils.timezone def copy_date_done_to_date_created(apps, schem...
1,480
455
"""Support for HTTP or web server issues."""
45
12
import torch.nn as nn from utils.BBBlayers import BBBConv2d, BBBLinearFactorial, FlattenLayer class BBB3Conv3FC(nn.Module): """ Simple Neural Network having 3 Convolution and 3 FC layers with Bayesian layers. """ def __init__(self, outputs, inputs): super(BBB3Conv3FC, self).__init__() ...
1,891
715
import os from tensorflow.contrib.learn.python.learn.datasets import base import numpy as np import IPython from subprocess import call from keras.preprocessing import image from influence.dataset import DataSet from influence.inception_v3 import preprocess_input BASE_DIR = 'data' # TODO: change def fill(X, Y, id...
8,657
3,073
# Copyright 2020 Carsten Blank # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
13,000
4,144
import OpenPNM import numpy as np import OpenPNM.Physics.models as pm class GenericLinearTransportTest: def setup_class(self): self.net = OpenPNM.Network.Cubic(shape=[5, 5, 5]) self.phase = OpenPNM.Phases.GenericPhase(network=self.net) Ps = self.net.Ps Ts = self.net.Ts self...
14,564
4,746
# MIT No Attribution # 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, modify, # merge, publish, distribute, sublicen...
2,370
749
# # Copyright (c) 2019-2022, NVIDIA CORPORATION. # # 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...
3,830
1,395
from optimizer.utils.intbounds import IntBounds class TestIntBounds(object): def test_make_gt(self): i0 = IntBounds() i1 = i0.make_gt(IntBounds(10, 10)) assert i1.lower == 11 def test_make_gt_already_bounded(self): i0 = IntBounds() i1 = i0.make_gt(IntBounds(10, 10))...
1,324
545
#!/usr/bin/env python from __future__ import print_function from __future__ import unicode_literals try: from unittest import mock except ImportError: import mock from tdclient import models from tdclient.test.test_helper import * def setup_function(function): unset_environ() def test_database(): c...
1,586
490
from setuptools import setup dependencies = [ 'numpy', 'scipy', 'scikit-learn', ] setup( name='fireTS', version='0.0.7', description='A python package for multi-variate time series prediction', long_description=open('README.md').read(), long_description_content_type="text/markdown", ...
558
191
# https://projecteuler.net/problem=19 def is_leap(year): if year%4 != 0: return False if year%100 == 0 and year%400 != 0: return False return True def year_days(year): if is_leap(year): return 366 return 365 def month_days(month, year): if month == 4 or month == 6 or m...
883
392
"""A simple address book.""" from ._tools import generate_uuid class AddressBook: """ A simple address book. """ def __init__(self): self._entries = [] def add_entry(self, entry): """Add an entry to the address book.""" self._entries.append(entry) def get_entries(sel...
1,652
466
import keras import numpy as np import pandas as pd import cv2 import os import json import pdb import argparse import math import copy from vis.visualization import visualize_cam, overlay, visualize_activation from vis.utils.utils import apply_modifications from shutil import rmtree import matplotlib.cm as cm from ma...
3,839
1,547
from libTask import Queue from common import configParams from common import common def main(): cp = configParams.ConfigParams("config.json") detectGeneralQueue = Queue.DQueue(cp, len(cp.detect_general_ids), cp.modelPath, common.GENERALDETECT_METHOD_ID, cp.GPUDevices, cp.detect_g...
530
184
class Config: ngram = 2 train_set = "data/rmrb.txt" modified_train_set = "data/rmrb_modified.txt" test_set = "" model_file = "" param_file = "" word_max_len = 10 proposals_keep_ratio = 1.0 use_re = 1 subseq_num = 15
235
118
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 13 18:52:28 2018 @author: amajidsinar """ from sklearn import datasets import matplotlib.pyplot as plt import numpy as np plt.style.use('seaborn-white') iris = datasets.load_iris() dataset = iris.data # only take 0th and 1th column for X data_kno...
1,417
558
import torch, torchvision import detectron2 from detectron2.utils.logger import setup_logger setup_logger() # import some common libraries import numpy as np import os, json, cv2, random # import some common detectron2 utilities from detectron2 import model_zoo from detectron2.engine import DefaultPredic...
2,135
758
"""AMQP Table Encoding/Decoding""" import struct import decimal import calendar from datetime import datetime from pika import exceptions from pika.compat import unicode_type, PY2, long, as_bytes def encode_short_string(pieces, value): """Encode a string value as short string and append it to pieces list ret...
8,916
2,697
from pylaas_core.abstract.abstract_service import AbstractService import time from pylaas_core.interface.technical.container_configurable_aware_interface import ContainerConfigurableAwareInterface class DummyConfigurable(AbstractService, ContainerConfigurableAwareInterface): def __init__(self) -> None: ...
528
144
from django.urls import reverse_lazy, reverse from django.utils.decorators import method_decorator from django.views.generic import ListView, DetailView, CreateView, DeleteView, UpdateView from .models import BlogPost from django.contrib.auth.decorators import login_required class BlogPostHomeView(ListView): mode...
1,076
318
#! /usr/bin/env python # ******************************************************************** # Software License Agreement (BSD License) # # Copyright (c) 2015, University of Colorado, Boulder # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted...
4,514
1,501
import numpy as np; import sys import matplotlib.pyplot as plt; from matplotlib import cm; from termcolor import colored; class Stats(): def __init__(self, param1_range, param2_range): self._total_times = 0; self._total_time = 0.0; self._wrong_answers = []; self._time_dict = {}; self._param1_rang...
3,509
1,330
from EasyLogin import EasyLogin from pprint import pprint def peptidecutter(oneprotein): a = EasyLogin(proxy="socks5://127.0.0.1:1080") #speed up by using proxy a.post("http://web.expasy.org/cgi-bin/peptide_cutter/peptidecutter.pl", "protein={}&enzyme_number=all_enzymes&special_enzyme=Chym&min_pr...
1,706
627
import unittest from .. import utils class TestUtils(unittest.TestCase): def setUp(self) -> None: self.pgn_string = ''' [Event "US Championship 1963/64"] [Site "New York, NY USA"] [Date "1964.01.01"] [EventDate "1963.??.??"] [Round "11"][Result "0-1"] [Whit...
1,333
544
# Copyright (c) 2016 Hitachi Data 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.0 # # U...
7,019
2,070
# This sample tests the type checker's reportUnnecessaryCast feature. from typing import cast, Union def foo(a: int): # This should generate an error if # reportUnnecessaryCast is enabled. b = cast(int, a) c: Union[int, str] = "hello" d = cast(int, c)
269
91
def execucoes(): return int(input()) def entradas(): return input().split(' ') def imprimir(v): print(v) def tamanho_a(a): return len(a) def tamanho_b(b): return len(b) def diferenca_tamanhos(a, b): return (len(a) <= len(b)) def analisar(e, i, s): a, b = e if(diferenca_tamanhos(a, ...
690
292
from http import HTTPStatus from typing import Iterable, Union, Mapping from flask import request from flask_restful import Resource, fields, marshal from metadata_service.proxy import get_proxy_client popular_table_fields = { 'database': fields.String, 'cluster': fields.String, 'schema': fields.String, ...
974
289
import requests import logging import cfscrape import os from manhwaDownloader.constants import CONSTANTS as CONST logging.basicConfig(level=logging.DEBUG) folderPath = os.path.join(CONST.OUTPUTPATH, 'serious-taste-of-forbbiden-fruit') logging.info(len([file for file in os.walk(folderPath)])) walkList = [file for fi...
470
159
# define custom R2 metrics for Keras backend from keras import backend as K def r2_keras(y_true, y_pred): SS_res = K.sum(K.square( y_true - y_pred )) SS_tot = K.sum(K.square( y_true - K.mean(y_true) ) ) return ( 1 - SS_res/(SS_tot + K.epsilon()) ) # base model architecture definition def model(): ...
11,708
4,126