text
string
size
int64
token_count
int64
# Copyright 2018-2019 Faculty Science Limited # # 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...
1,875
508
# Generated by Django 2.2 on 2019-05-15 16:43 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Map2011', fields=[ ('id', models.AutoField(au...
2,612
758
""" Module concerning Space objects """ # Python Libraries # First Party Imports class Space: """ Class holding logic for each individual surface upon which art can be hung. #TODO: more documentation """ def __init__( self, max_hor_dim: float = 0.0, min_hor_dim: float...
2,704
824
#!/usr/bin/python import sys import numpy as np import tensorflow as tf from memory import Memory, MultiMemory from qnet import * from layers import * from game import Game ## Load Parameters gamma = .99 #Discount factor. num_episodes = 10000 #Total number of episodes to train network for. test_episodes = 200 #Total...
5,443
1,922
import argparse from pathlib import Path import hydra from omegaconf import OmegaConf import torch from torch.utils.data import DataLoader from tqdm import tqdm from datasets.patched_datasets import PatchedMultiImageDataset, RandomAccessMultiImageDataset @torch.no_grad() def score_patches(loader, model, device, cfg)...
5,511
1,890
from configutator import ConfigMap, ArgMap, EnvMap, loadConfig import sys def test(param1: int, param2: str): """ This is a test :param param1: An integer :param param2: A string :return: Print the params """ print(param1, param2) if __name__ == '__main__': for argMap in loadConfig(sys...
375
129
from django.contrib import admin from .models import Brand, Product, Profile, Instagram, OrderItem,Order from django.utils.html import format_html # Register your models here. def make_published(modeladmin, request, queryset): queryset.update(name='Váy') make_published.short_description = "Mark selected stories as...
2,384
738
import calendar from datetime import date, datetime, timedelta from time import localtime from django.utils.translation import ugettext_lazy as _ def add_business_days(from_date, add_days): """ This is just used to add business days to a function. Should be moved to util. """ business_days_to_add = ad...
3,211
1,102
# Definition for singly-linked list. import unittest import math class TestClass(unittest.TestCase): def isPalindrome(self, x: int) -> bool: if(x<0): return False rx = self.reverseNum(x) return rx == x def reverseNum(self,x: int): rx = 0 while x>=1: ...
1,211
436
from typing import Any, Iterator, Optional import colorama DownloadedDocumentStream = Optional[Iterator[Any]] def get_truncated_text(text: str, limit: int) -> str: return text[:limit] + "..." if len(text) > limit else text def get_color_by_percentage(percentage: int) -> str: if percentage > 90: retu...
433
143
import os from DataBase.dados_filmes import * from DataBase.dados_aluguel import * def cadastrar_filme(): os.system('cls' if os.name == 'nt' else 'clear') nome = input('Digite o nome do filme: ') ano = input('Digite o ano de lançamento do filme: ') codigo = input('Digite o código do filme: ') filme...
2,771
1,045
''' delete pyc except salt-minion.pyc ''' from __future__ import print_function import os SRCDIR = r'c:\salt' def action(start_path): skipped = 0 deleted = 0 for dirpath, dirnames, filenames in os.walk(start_path): for f in filenames: fp = os.path.join(dirpath, f) if fp.en...
599
200
from win10toast import ToastNotifier import time def Notify(MessageTitle,MessageBody): toaster = ToastNotifier() toaster.show_toast(MessageTitle, MessageBody, icon_path="logo.ico", duration=3,threaded=True) from playsound import playsound playsound('Notifi...
387
116
import os import numpy as np import cPickle as pickle from datasets.dataset import Dataset class Cifar10(Dataset): """Implements the Dataset class to handle CIFAR-10. Attributes: y_dim: The dimension of label vectors (number of classes). split_data: A dictionary of { ...
2,883
919
import pytest import kaiju from kaiju.robotGrid import RobotGridNominal from kaiju import utils def test_collide(plot=False): # should make a grid rg = RobotGridNominal() collidedRobotIDs = [] for rid, r in rg.robotDict.items(): if r.holeID == "R-13C1": r.setAlphaBeta(90,0) coll...
759
310
""" psycopg -- PostgreSQL database adapter for Python """ # Copyright (C) 2020-2021 The Psycopg Team import logging from . import pq # noqa: F401 import early to stabilize side effects from . import types from . import postgres from .copy import Copy, AsyncCopy from ._enums import IsolationLevel from .cursor import...
2,839
861
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.Image('CSP/ERGo/1_0/US/topoDiversity') usTopographicDiversity = dataset.select('constant') usTopographicDiversityVis = { 'min': 0.0, 'max': 1.0, } Map.setCenter(-111.313, 39.724, 6) Map.addLaye...
434
181
""" cnn_to_mlp.py Converts CNNs to MLP networks Copyright (C) 2018, Akhilan Boopathy <akhilan@mit.edu> Lily Weng <twweng@mit.edu> Pin-Yu Chen <Pin-Yu.Chen@ibm.com> Sijia Liu <Sijia.Liu@ibm.com> Luca Daniel <dluca@mit.edu> """ from tenso...
6,139
2,362
''' Copyright 2014 by Adrian Oeftiger, oeftiger@cern.ch This module provides various numerical integration methods for Hamiltonian vector fields on (currently two-dimensional) phase space. The integrators are separated according to symplecticity. The method is_symple() is provided to check for symplecticity of a given...
5,328
1,968
import os import sys LIB_PATH = os.environ['LADYBUG_LIB_PATH'] sys.path.append(LIB_PATH) from water_plants_lib import WaterPlants ############### if __name__ == "__main__": water_plants = WaterPlants() water_plants.send_start_watering_packets()
256
98
from django.shortcuts import render # Create your views here. from rest_framework.views import APIView from rest_framework.viewsets import GenericViewSet from undp_admin.models import AboutUs, AdminLog, JOBS, LOG_STATUSES from undp_admin.serializers import AboutUsSerializer from utilities.mixins import ResponseViewMi...
2,055
615
from django.contrib import admin from .models import Pass, User, Organisation, Roles, Vehicle, Identity, Team from treebeard.admin import TreeAdmin from treebeard.forms import movenodeform_factory class AdminUserView(admin.ModelAdmin): model = User readonly_fields = ('user_id',) list_display = ...
2,681
871
import numpy as np import tensorflow as tf def parse_dataset(example_proto, img_size_h, img_size_w, img_size_d, dim_anno1, dim_anno2, dim_anno3, dtype_img=tf.float64): features = { 'inputs': tf.io.FixedLenFeature(shape=[], dtype=tf.string), 'annotations': tf.io.FixedLenFeature(shape=[dim_anno...
1,592
560
#this file does nothing except informing pypi that uci_janggi.py is a package
78
25
import json import logging from django.conf import settings from django.contrib.auth import authenticate from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden, JsonResponse from django.utils.decorators import method_decorator from django.views import View from django.views.decorators.csrf...
8,251
2,280
// Databricks notebook source // MAGIC %md // MAGIC // MAGIC W261 Final Project // MAGIC ------------------ // MAGIC ## Graph Centrality for Airline Delay Prediction // MAGIC // MAGIC #### Justin Trobec, Jeff Li, Sonya Chen, Karthik Srinivasan // MAGIC #### Spring 2021, Section 5 // MAGIC #### Group 25 // COMMAN...
40,435
15,831
class ColumnNames: """Used to record standard dataframe column names used throughout""" LOCATION_DANGER = "Danger" # Danger associated with a location LOCATION_NAME = "Location_Name" # Name of a location LOCATION_ID = "ID" # Unique ID for each location # Define the different types of activities...
2,715
961
fichier = open("/run/media/Thytu/TOSHIBA EXT/PoC/Smartshark/DS/ds_benign_cleaned_div_3.csv", "r") pos = 12 #pos to flatten def flat_line(line, target): index = 0 pos = 0 for l in line: pos += 1 if (l == ','): index += 1 if index == target: break; print(l...
382
153
from python.utils.cmd_exec import cmd_exec import json import logging from python.utils.path import Path, pcat from logging import DEBUG from python.utils.log import config_logging _logger = logging.getLogger(__name__) def setup_k8s_thirdparty(): list_path = Path.SCRIPTS_CONFIG_K8S_THIRD_PARTY_LIST _logger....
835
278
import os.path import glob import wandb import numpy as np from tensorflow.keras.callbacks import Callback class ValLog(Callback): def __init__(self, dataset=None, table="predictions", project="svg-attention6", run=""): super().__init__() self.dataset = dataset self.table_name = table ...
1,506
467
import anndata import numpy as np import pandas as pd DATA_TYPE_MODULE = 'module' DATA_TYPE_UNS_KEY = 'data_type' ADATA_MODULE_UNS_KEY = 'anndata_module' def get_base(adata): base = None if 'log1p' in adata.uns and adata.uns['log1p']['base'] is not None: base = adata.uns['log1p'][base] return bas...
12,680
3,998
#!/usr/bin/env python3 """ Template for SNAP Dash apps. """ import os import json import plotly.graph_objs as go import xarray as xr import dash import dash_core_components as dcc import dash_html_components as html import dash_dangerously_set_inner_html as ddsih import dash_table import pandas as pd import geopandas ...
23,612
8,992
# -*- coding: utf-8 -*- # Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net> # This program is free software: you can r...
15,298
4,824
# created at 2018-05-11 # updated at 2018-08-23 # support multi-faces now # By coneypo # Blog: http://www.cnblogs.com/AdaminXie # GitHub: https://github.com/coneypo/Dlib_face_recognition_from_camera import dlib # 人脸识别的库dlib import numpy as np # 数据处理的库numpy import cv2 # 图像处理的库OpenCv import pandas as p...
4,450
2,196
"""check_read_rom.py get ROMID of 1-wire device. assume only one 1-wire device on the bus. """ import tpow.usb9097 import tpow.device import cfg bus = tpow.usb9097.USB9097(cfg.com_port) # USB9097('COM3') id_little = tpow.device.read_rom(bus) id_big = [a for a in reversed(id_little)] print(" ".join(['%02X' % ord(a) ...
340
157
# coding=utf-8 import unittest from main.maincontroller import MainController import view_management """ UC TRUST_02: View the Details of a Certification Service CA RIA URL: https://jira.ria.ee/browse/XTKB-185 Depends on finishing other test(s): Requires helper scenarios: X-Road version: 6.16.0 """ class Xroad...
1,522
469
from venafi_codesigning_gitlab_integration.jarsigner_sign_command import JarsignerSignConfig from venafi_codesigning_gitlab_integration.jarsigner_sign_command import JarsignerSignCommand from venafi_codesigning_gitlab_integration import utils import pytest import logging import subprocess import os import re fake_tpp_...
8,002
2,732
# python dependencies import codecs import pickle import struct def pickle_string_to_obj(obj): return pickle.loads(codecs.decode(obj, "base64")) def get_encoded_obj(obj): return codecs.encode(pickle.dumps(obj), "base64").decode() def log_message(msg_type: str, message: str): """The default style of lo...
1,602
553
import requests def do_search(bookstore_url, params): return requests.get(url=bookstore_url, params=params)
138
40
# coding: utf-8 #Import the necessary Python modules import pandas as pd import folium from folium.plugins import TimestampedGeoJson from shapely.geometry import Point import os from datetime import datetime from branca.element import Template, MacroElement import html from scripts.location_map_constants import iLEAPP_...
4,568
1,442
"""Default init file for statistics package."""
48
11
# third party modules import pytest # user modules from BL_main.RandomNumber import Number, Numbers, InvalidArgumentExceptionOfNumber def test_NumberClass_InvalidException_underNumber(): ''' Test argument. under number. ''' with pytest.raises(InvalidArgumentExceptionOfNumber): Number.create(1) ...
1,096
320
#!/usr/bin/python3 import json import seaborn as sns from matplotlib import cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap import matplotlib.colors as colors from scipy.stats import spearmanr import pylab import scipy.cluster.hierarchy as sch from scipy.stats import pearsonr, friedmanchisqu...
6,185
2,168
# This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that ...
10,058
3,235
''' (c) Copyright 2013 Telefonica, I+D. Printed in Spain (Europe). All Rights Reserved. The copyright to the software program(s) is property of Telefonica I+D. The program(s) may be used and or copied only with the express written consent of Telefonica I+D or in accordance with the terms and conditions stipulated in t...
1,148
366
# -*- coding: utf-8 -*- #BEGIN_HEADER import logging import os import uuid import shutil from installed_clients.WorkspaceClient import Workspace from installed_clients.DataFileUtilClient import DataFileUtil from installed_clients.KBaseReportClient import KBaseReport from installed_clients.GenericsAPIClient import Gene...
9,669
3,010
import os import cv2 import glob import tqdm import argparse from skimage.filters import threshold_local import pytesseract import numpy as np import random def check_exist(path): try: if not os.path.exists(path): os.mkdir(path) except Exception: raise ("please check your folder again") pass def median_fil...
4,189
1,632
# __main__.py # Walker M. White (wmw2) # November 12, 2012 """__main__ module for Breakout This is the module with the application code. Make sure that this module is in a folder with the following files: breakout.py (the primary controller class) model.py (the model classes) game2d.py (the view ...
762
227
from pathlib import Path import git # The top-level path of this repository git_repo = git.Repo(__file__, search_parent_directories=True) git_root_dir = Path(git_repo.git.rev_parse("--show-toplevel")) # This should match the major.minor version list in .circleci/generate_circleci_config.py # Patch version should alwa...
394
146
from ...common.utils import patch; patch() import boto3 import urllib.request from .PaaS import PaaS from ..service import docker from ...common.consts import * COREOS_AMI_URL = "https://stable.release.core-os.net/amd64-usr/current/coreos_production_ami_hvm_{region}.txt" COREOS_USERNAME = "core" VM_TAG = [{"Resource...
2,808
825
# -*- coding: utf-8 -*- """ csrweb.api.resources ~~~~~~~~~~~~~~~~~~~~ API resources. :copyright: Copyright 2019 by Ed Beard. :license: MIT, see LICENSE file for more details. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode...
3,099
1,002
import unittest from wmsigner import Signer # Для запуска тестов эти данные должны быть заполнены signer = Signer(wmid='000000000000', keys='/home/egor/000000000000.kwm', password='**********') class TestWMSigner(unittest.TestCase): def test_equal(self): """ Получ...
1,084
483
import os, sys import csv import leancloud from leancloud import cloud import requests import re leancloud.init("ELXEVn8IoKWzNVU52gmYKnn6-gzGzoHsz", master_key="kYWSFq2AwQyBhujn5oIBo64n") data_info = {'id': 2017718538, 'user_name': 'js999986', 'first_name': '一手引流工作室', 'last_name': None, 'userName': None, 'url': None,...
676
369
import re import numpy as np class Submarine: def __init__(self) -> None: self.depth = 0 self.aim_depth = 0 self.gamma_rate = 0 self.epsilon_rate = 0 self.oxygen_generator_rate = 0 self.carbon_dioxide_scrubber = 0
273
100
from __future__ import print_function from pyspark import SparkContext from pyspark.mllib.classification import LogisticRegressionWithLBFGS, LogisticRegressionModel from pyspark.mllib.regression import LabeledPoint from pyspark.mllib.util import MLUtils #(' 101356, 101356, 32714, 32714, 5963, 10594, 21240, 34825, 5963...
1,729
611
import matplotlib.pyplot as plt import numpy as np x = np.linspace(-10, 10, 40) y1 = 10 * x + 50 y2 = x**2 plt.figure() plt.plot(x, y1, 'b-') plt.plot(x, y2, 'b--') plt.xlim((-20, 20)) plt.ylim((-60, 160)) plt.xlabel('I am x') plt.ylabel('I am y') plt.xticks(np.linspace(-20, 20, 5)) plt.yticks([0, 50, 100], [r'$bad$...
754
346
#!/usr/bin/env python # # # # Autor: Michela Negro, GSFC/CRESST/UMBC . # # On behalf of the Fermi-LAT Collaboration. ...
1,943
602
"""Tests Cloud models and Controllers""" import os import uuid import json from deepdiff import DeepDiff from pprint import pprint def unicode_to_str(data): if isinstance(data, dict): return {unicode_to_str(key): unicode_to_str(value) for key, value in data.iteritems()} elif isinstanc...
3,008
935
# $ANTLR 3.1 jed.g 2014-02-17 18:49:15 import sys from antlr3 import * from antlr3.compat import set, frozenset import os import sys from bitarray import bitarray # for convenience in actions HIDDEN = BaseRecognizer.HIDDEN # token types F=9 STAR=19 OTHER=5 C=18 L=11 N=12 J=10 V=15 ONE=7 Q=14 P=13 EOF=-1 ...
36,944
13,123
(a + b + c + d+ e+ f )
41
32
# -*- coding: utf-8 -*- """ --- Day 10: The Stars Align --- It's no use; your navigation system simply isn't capable of providing walking directions in the arctic circle, and certainly not in 1018. The Elves suggest an alternative. In times like these, North Pole rescue operations will arrange points of light in the s...
6,542
2,326
from django.conf.urls import url, include from django.contrib import admin from torrents import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^upload/$', views.upload, name='upload'), url(r'^browse/$', views.browse, name='browse'), ]
302
93
""" This is the main script to analyze projects without an NDA in place. Authors: Nikhil Kondabala, Alexandra Arntsen, Andrew Black, Barrett Goudeau, Nigel Swytink-Binnema, Nicolas Jolin Updated: 7/01/2021 Example command line execution: python TACT.py -in /Users/aearntsen/cfarsMASTER/CFARSPhase3/test/518Tower...
170,658
57,767
""" @Author : xiaotao @Email : 18773993654@163.com @Lost modifid : 2020/4/24 10:18 @Filename : LanguagePack.py @Description : @Software : PyCharm """ class RET: """ 语言类包 """ OK = "200" DBERR = "501" NODATA = "462" DATAEXIST = "433" DATAERR = "499" REQERR = "521" ...
1,343
686
from django.test import TestCase from django.contrib.auth import get_user_model from core import models def sample_user(email='test@londonappdev.com', password='testpass'): """Create a sample user""" return get_user_model().objects.create_user(email, password) class ModelTest(TestCase): def test_user_wi...
1,414
459
class TreeNode(object): def __str__(self): left = self.left.val if self.left else 'N' right = self.right.val if self.right else 'N' return "{left} {val} {right}".format(val=self.val, left=left, right=right) def __init__(self, val): self.val = val self.right = None ...
2,427
887
import subprocess import time proc = subprocess.Popen( ["ping", "-c", "10", "localhost"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) counter = 0 for line in iter(proc.stdout.readline, ''): print line progress.setPercentage( counter ) counter +=10
307
108
from get_earth import GetEarth # 835 , 1416 # p11 = (835, 1416) # p12 = (885,1516) # p1 = (886,1416) # p2 = (935,1516) # p1 = (885, 1415) # p2 = (890, 1420) # p1 = (890,1415) # p2 = (895,1420) # p1 = (835, 1416) # p2 = (885,1516) # start where you end it # p1 = (885, 1416) # p2 = (935,1516) # p1 = (835,1516) # ...
630
460
class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ # first pass: empty triangle tria = [ [0 for j in range(i+1)] for i in range(numRows) ] print(tria) # second pass: fill in value...
562
188
""" Solutions for day 12 of 2020's Advent of Code """ from typing import Tuple def _rotate_right(n, e) -> Tuple[int, int]: return -e, n def _rotate_left(n, e) -> Tuple[int, int]: return e, -n def part_a(data) -> int: """ Solution for part a Parameters ---------- data: str Return...
2,076
690
import _logging as logging logger = logging.logging() logger.DEBUG('TEST') logger.ERROR('TEST') logger.INFO('TEST') logger.WARNING('TEST')
138
42
class Stack(DataStructure, ABC): def __init__(self, ul, ur, ll, lr, aligned_edge, color=WHITE, text_color=WHITE, text_weight=NORMAL, font="Times New Roman"): super().__init__(ul, ur, ll, lr, aligned_edge, color, text_color, text_weight, font) self.empty = None def create_init(s...
3,786
1,273
#!/usr/bin/env python # coding: utf-8 # Reads in photometry from different sources, normalizes them, and puts them # onto a BJD time scale # Created 2021 Dec. 28 by E.S. import numpy as np import pandas as pd from astropy.time import Time import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler...
1,519
596
# Generated by Django 3.1.7 on 2021-03-08 09:39 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('djelectionguard', '0009_decentralized_default_false'), ] operations = [ migrations.RemoveField( model_name='contest', name='...
356
122
from history.tools import normalization, filter_by_mins, create_sample_row from history.models import Price, PredictionTest import time from history.tools import print_and_log def predict_v2(ticker,hidden_layers=15,NUM_MINUTES_BACK=1000,NUM_EPOCHS=1000,granularity_minutes=15,datasetinputs=5,learningrate=0.005,bias=F...
4,012
1,413
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 18 12:06:09 2018 @author: linkermann Wasserstein GAN simplified """ import os, sys sys.path.append(os.getcwd()) import tflib.save_images as imsaver import tflib.plot as plotter #import tflib.mnist as mnistloader import time import numpy as np impor...
16,129
6,010
from rl_teacher.segment_sampling import segments_from_rand_rollout, sample_segment_from_path, basic_segment_from_null_action import numpy as np class Selector(object): def __init__(self): print("Selector initialized") def select(self, segments): print("Selector.select()") return segmen...
2,786
817
# -*- coding: utf-8 -*- ########################################################################## # NSAp - Copyright (C) CEA, 2020 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html #...
9,474
2,932
import collections import flask_restplus from flask_restplus import fields from flask_restplus import reqparse from api import util api = util.build_api('alpha', __name__, url_prefix='/subparts/alpha') v1 = util.build_namespace(api, 'v1', description='Version 1') AlphaSpec = collections.namedtuple('Alpha', ['x_and_...
1,161
393
"""# Baseline classifier and regressor""" import numpy as np import pandas as pd from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin from sklearn.utils.multiclass import check_classification_targets from sklearn.utils.validation import _check_sample_weight class BaselineClassifier(ClassifierMixin...
4,612
1,399
import requests response = requests.get("https://cojeapi.honzajavorek.now.sh/movies") movies = response.json() for movie in movies: response = requests.get(movie['url']) movie_details = response.json() print(movie_details['name'], movie_details['year'])
268
86
""" Program to provide generic parsing for all files in user-specified directory. The program assumes the input files have been scrubbed, i.e., HTML, ASCII-encoded binary, and any other embedded document structures that are not intended to be analyzed have been deleted from the file. Dependencies: Pytho...
4,927
1,817
import sinput import keys class Volume: __volume = None def __init__(self, sync: int=0): if sync != False or self.__volume is None: self.sync(sync) def __constrain(self, val: int, min: int=0, max: int=100): return (min if val < min else (max if val > max else val)) def _...
1,542
525
import os from sklearn.model_selection import train_test_split import numpy as np from operator import itemgetter from math import log import random from gensim.summarization.summarizer import summarize from sklearn.naive_bayes import BernoulliNB from sklearn.metrics import accuracy_score from sklearn.metrics import co...
4,882
1,686
""" 295. Find Median from Data Stream https://leetcode.com/problems/find-median-from-data-stream/ Time complexity: O() Space complexity: O() Solution: """ from typing import List class MedianFinder: def __init__(self): """ initialize your data structure here. """ se...
785
280
from gql import gql, Client from gql.transport.requests import RequestsHTTPTransport import requests from datetime import datetime, timedelta, timezone import os from os.path import join, dirname from dotenv import load_dotenv dotenv_path = join(dirname(__file__), "../../", '.env') load_dotenv(dotenv_path) RASPI_URL ...
2,701
858
import requests import pandas as pd url = "http://comp.fnguide.com/SVO2/common/lookup_data.asp?mkt_gb=1&comp_gb=1" resp = requests.get(url) data = resp.json() df = pd.DataFrame(data=data) df.head()
199
82
import arcade from arcade.gui import UIImageButton, UIManager, UIToggle import game.constants as constants from game.gameview import GameView class MainView(arcade.View): """ View to show start screen. The responsibility of this class is to offer the user to either play or view the instructions Stereotype:...
7,316
2,080
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ---------------------------------------------...
2,711
861
# -*- coding: utf-8 -*- import json from watson_developer_cloud import NaturalLanguageUnderstandingV1 as nlu import watson_developer_cloud.natural_language_understanding.features.v1 \ as Features def concept_recog(path='./test.txt'): #with open(path, 'rt', encoding='utf-8') as f: # inputs = f.read() ...
1,162
401
import pytest from factor import modular_inverse, continued_fraction, approximate_fraction, is_prime def test_modular_inverse(): assert modular_inverse(a=1, N=2) == 1 assert modular_inverse(a=1, N=5) == 1 assert modular_inverse(a=2, N=5) == 3 assert modular_inverse(a=3, N=5) == 2 assert modular_i...
2,120
932
#!/usr/bin/env python3 import sys import os import zmq import time import logging from PyQt5 import QtWidgets as W, QtCore as C, QtGui as G from qtzevents.bus import Pub, Push from qtzevents.background import Background from images7.config import Config from images7.system import System from .grid import ThumbView ...
6,242
1,941
iphone_price = 5800 mac_price = 9000 coffee_price = 32 python_price = 80 bicyle_price = 1500 list = [] salary = int(input("Please input your salary:")) print("**********欢迎来到购物车系统**********") while True: print("1. iPhone 11 ————%d元" % iphone_price) print("2. Mac book ————%d" % mac_price) print("3. cof...
2,049
946
from model.contact import Contact import random def test_edit_some_contact(app, orm, check_ui): if len(orm.get_contact_list()) == 0: app.contact.create(Contact(firstname="St_Claus")) old_contacts = orm.get_contact_list() contact_for_edit = random.choice(old_contacts) contact = Contact(firstnam...
1,079
373
from pathlib import Path from typing import Sequence import tomlkit from .types import BaseReader, Distribution class MaturinReader(BaseReader): def __init__(self, path: Path): self.path = path def get_requires_for_build_sdist(self) -> Sequence[str]: return [] # TODO def get_requires_...
1,555
466
"""Implementation of TypedDict.""" import dataclasses from typing import Any, Dict, Set from pytype.abstract import abstract from pytype.abstract import abstract_utils from pytype.abstract import function from pytype.overlays import classgen from pytype.pytd import pytd @dataclasses.dataclass class TypedDictProper...
9,424
3,102
"""ESMValTool CMORizer for APHRODITE Monsoon Asia (APHRO-MA) data. Tier Tier 3: restricted dataset. Source http://aphrodite.st.hirosaki-u.ac.jp/download/ Last access 20200306 Download and processing instructions Register at http://aphrodite.st.hirosaki-u.ac.jp/download/create/ Download the ...
4,962
1,729
import sys import json from pathlib import Path from unittest.mock import patch import pytest from conftest import FakeFile, config @patch.object(sys, "argv", ["backup_utils", "-v"]) def test_version(capsys): from backup_utils import main, __version__ with pytest.raises(SystemExit): main() cap...
1,285
452
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from copy import deepcopy import mock import pytest from swagger_spec_compatibility.spec_utils import load_spec_from_spec_dict from swagger_spec_compatibility.util import Entit...
5,074
1,529
from logisimpy.circuit import Circuit, Wire from logisimpy.logic import AND, AND3, NOT, OR class MUX2x1(Circuit): """ 2x1 Multiplexer logic. The MUX element has two data inputs, one select input and one data output. If the select input is 0, the data from the first input is transfered to the outp...
4,997
2,606