text
string
size
int64
token_count
int64
from django.urls import path from . import views urlpatterns = [ path('search-card', views.patients_search_card), path('search-individual', views.patients_search_individual), path('search-l2-card', views.patients_search_l2_card), path('create-l2-individual-from-card', views.create_l2_individual_from_ca...
2,207
789
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2016-11-15 07:06 from __future__ import unicode_literals import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('resolwe_bio_kb', '0001_initial'), ] operation...
1,139
414
import os import sys import re import glob from setuptools import setup, find_packages # long_description: Take from README file with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as f: readme = f.read() # Version Number with open(os.path.join(os.path.dirname(__file__), 'xlwings', '__init__.py')) as...
3,014
1,024
import pytest from click.testing import CliRunner from secedgar.cli import daily, filing from secedgar.utils.exceptions import FilingTypeError def run_cli_command(cli, user_input, directory, catch_exceptions=False): runner = CliRunner() user_input = user_input + " --directory {}".format(directory) return ...
2,044
674
import os import numpy as np import matplotlib.pyplot as plt from matplotlib import gridspec nstep=200 nx=400 nv=3 u=np.zeros((nx,nv)) prim=np.zeros((nx,nv)) gam=5./3. dx=1./nx dt=1e-3 time=0 x=np.linspace(0,1,num=nx) def ptou(pri): u=np.zeros((nx,nv)) rho=pri[:,0] v=pri[:,1] prs=pri[:,2] mom=rho*v ...
2,013
1,071
import unittest from pluralizer import Pluralizer import re # Standard singular/plural matches. # # @type {Array} BASIC_TESTS = [ # Uncountables. ['firmware', 'firmware'], ['fish', 'fish'], ['media', 'media'], ['moose', 'moose'], ['police', 'police'], ['sheep', 'sheep'], ['series', 's...
22,179
8,558
# Copyright (c) 2017 LINE Corporation # These sources are released under the terms of the MIT license: see LICENSE import requests.sessions from django.db.models import F from promgen.version import __version__ from django.conf import settings # Wrappers around request api to ensure we always attach our user agent #...
1,988
616
import time import kubernetes import pytest from dagster_k8s.client import DagsterK8sError, WaitForPodState from dagster_k8s.utils import retrieve_pod_logs, wait_for_job_success, wait_for_pod from dagster_k8s_test_infra.helm import get_helm_test_namespace def construct_pod_spec(name, cmd): return kubernetes.clie...
5,478
1,529
# Generated by Django 3.1.6 on 2021-02-15 08:52 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Service', fields=[ ...
1,092
321
from PyQt5.QtCore import Qt, QStringListModel from PyQt5.QtWidgets import QLineEdit, QCompleter class TagNamesLineEdit(QLineEdit): def __init__(self, parent=None): super(QLineEdit, self).__init__(parent) self.cmp = None self.is_completer = True def setCompleter(self, completer): ...
2,088
648
# # importing all the modules at once # from .config import * # from .normalization import * # from .others import * # from .img_reg import * # from .transformation import * # from .visualization import * # importing the modules in a selective way import utils.config import utils.normalization import utils.misc import...
337
98
from celery import Celery from clients.dobie_client import send_data_to_dobie app = Celery('qualichain_mediator') app.config_from_object('settings', namespace='CELERY_') @app.task() def consume_messages_async(message): """ This task is used to received job posting text and feed DOBIE component """ e...
434
138
import json, math from ingest import ingest_json_body from housepy import config, log, strings, util def parse(request): log.info("ambit_geo.parse") sample = ingest_json_body(request) if sample is None: return sample, "Could not parse" data = {} for key, value in sample.items(): if...
1,174
335
#!/usr/bin/env python '''update gandi DNS domain entry, with LiveDNS v5 Cf. https://doc.livedns.gandi.net/#work-with-domains ''' import argparse import ipaddress import json import os from subprocess import check_output import requests parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '...
1,593
589
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from collections import deque from collections import defaultdict class Solution(object): def verticalOrder(self, ...
1,895
536
from __future__ import absolute_import from sentry.db.models import ( ArrayField, BoundedPositiveIntegerField, Model, FlexibleForeignKey, sane_repr ) from django.db import models from jsonfield import JSONField from django.utils import timezone from sentry.constants import ObjectStatus from django.utils.translatio...
3,750
1,130
from .BaseDriver import BaseDriver from ..OAuthUser import OAuthUser class FacebookDriver(BaseDriver): def get_default_scopes(self): return ["email"] def get_auth_url(self): return "https://www.facebook.com/dialog/oauth" def get_token_url(self): return "https://graph.facebook.com...
1,615
447
import pandas as pd import json import glob columns = ["Highlight","Title","Author","URL","Note","Location"] # for sample of the input json look at any json in the root of the `results` folder def convert_to_readwise_df(json_files): """Convert the internal json format to a readwise compatible dataframe Args:...
1,266
350
"""A collection of methods for determining whether a given spectrum is of high quality (likely to produce a high quality interpretation) """ from .heuristic import xrea from .isolation import CoIsolation, PrecursorPurityEstimator __all__ = [ "xrea", "CoIsolation", "PrecursorPurityEstimator" ]
303
92
from .item import Item class Message(Item): """ Message feature object in the rpi_animations package. """ def __init__(self, group, screen_animator) -> None: """ Initialise Message object with sprite group and screen object. Run initial setup methods. Args: group ...
3,855
1,064
import discord from discord.ext import commands from styrobot.util.contrib import info import random class BetterHelpCommand(commands.HelpCommand): async def send_embed(self, embed): embed.colour = discord.Colour.random() await self.get_destination().send(embed=embed) def blank_line(self, emb...
4,293
1,380
# Testing with threading and queue modules for Thread-based parallelism import threading, queue, time # The worker thread gets jobs off the queue. When the queue is empty, it # assumes there will be no more work and exits. # (Realistically workers will run until terminated.) def worker(): print('Running worker'...
1,527
467
import pytest from pymongo import MongoClient import app as flask_app test_database_name = 'spartatest' client = MongoClient('localhost', 27017) db = client.get_database(test_database_name) @pytest.fixture def app(): test_app = flask_app.create_app(test_database_name) # 제네레이터 문법(yield 구문까지만 실행하고 대기, #...
506
299
"""Tools to quickly create twitter threads.""" from .thread import Threader __version__ = "0.1.1"
98
30
# count numbers of pages from the Mediawiki history dumps import bz2 import subprocess import os from datetime import datetime inizio = datetime.now() dataset_folder = '/home/gandelli/dev/data/it/' totali = set() revisioni = set() revert = set() ns0 = set() for year in range(2001, 2021): dump_in = bz2.open(da...
1,080
377
import colorsys import cv2 from PIL import Image import pkg_resources from .LivescoreBase import LivescoreBase from .details import Alliance, OngoingMatchDetails class LivescoreCommon(LivescoreBase): def __init__(self, game_year, **kwargs): super(LivescoreCommon, self).__init__(game_year, **kwargs) ...
6,395
2,281
from postDB import Model, Column, types from datetime import datetime import utils class Challenge(Model): """ Challenge class to store the challenge details Database Attributes: Attributes stored in the `challenges` table. :param int id: The challenge Snowflake...
1,825
481
""" Commom settings to all applications """ A = 40.3 TECU = 1.0e16 C = 299792458 F1 = 1.57542e9 F2 = 1.22760e9 factor_1 = (F1 - F2) / (F1 + F2) / C factor_2 = (F1 * F2) / (F2 - F1) / C DIFF_TEC_MAX = 0.05 LIMIT_STD = 7.5 plot_it = True REQUIRED_VERSION = 3.01 CONSTELLATIONS = ['G', 'R'] COLUMNS_IN_RINEX = {'3.03': ...
1,004
520
from .channel_io import Channel, channel_entity_url
51
14
"""Test API utilities.""" import json from pytradfri.api.libcoap_api import APIFactory from pytradfri.gateway import Gateway def test_constructor_timeout_passed_to_subprocess(monkeypatch): """Test that original timeout is passed to subprocess.""" capture = {} def capture_args(*args, **kwargs): c...
1,009
320
# scrapes Townes van Zandt lyrics # sample code so I don't have to remember all of this stuff # the next time I want to source some verses from bs4 import BeautifulSoup as soup import requests import string punctuation_trans_table = str.maketrans("", "", string.punctuation) def strip_punctuation(s): return s.tr...
1,293
469
# coding=utf-8 """ 控制结构if elif else的研究 Version: 0.1 Author: huijz Date: 2020-08-24 """ # 例1:if的基本用法: flag = False name = 'huijz' if name == 'python': # 判断变量是否为 python flag = True # 条件成立时设置标志为真 print 'welcome boss' # 并输出欢迎信息 else: print name # 条件不成立时输出变量名称 # 例2:elif用法 num = 5 if num == 3: # 判断num的值 ...
895
520
from setuptools import setup from setuptools import find_packages setup( name="Jann", version="4.0.0", description="Jann is a Nearest Neighbour retrieval-based chatbot.", author="Kory Mathewson", author_email="korymath@gmail.com", license="MIT", url="https://github.com/korymath/jann", ...
445
151
# Copyright 2017 The Forseti Security Authors. 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 ap...
7,895
2,391
# ================================================================ # MIT License # Copyright (c) 2021 edwardyehuang (https://github.com/edwardyehuang) # ================================================================ import tensorflow as tf from iseg.metrics.seg_metric_wrapper import SegMetricWrapper from iseg.metri...
1,147
349
import math def lognormal_mean(m, stddev): """ compute mean of log x with mean and std. of x Args: m: mean of x stddev: standard deviation of x Returns: mean of log x """ return math.log(m) - (0.5 * math.log(1.0 + (stddev * stddev) / (m * m))) def lognormal_stdde...
1,436
568
#!/usr/bin/env python # Tag Highlighter: # Author: A. S. Budden <abudden _at_ gmail _dot_ com> # Copyright: Copyright (C) 2009-2013 A. S. Budden # Permission is hereby granted to use and distribute this code, # with or without modifications, provided that this copyright # notice is c...
5,720
1,492
""" Bayes sensor code split out from https://github.com/home-assistant/home-assistant/blob/dev/homeassistant/components/binary_sensor/bayesian.py This module is used to explore the sensor. """ from collections import OrderedDict from const import * def update_probability(prior, prob_true, prob_false): """Update ...
6,099
1,713
import os import glob import shutil import logging import matplotlib.pyplot as plt import numpy as np from scipy import ndimage, misc, signal, spatial from skimage.filters import gaussian, gabor_kernel import cv2 import math def mkdir(path): if not os.path.exists(path): os.makedirs(path) def re_mkdir(p...
27,212
11,193
from settings import VAR_DIR CACHE=VAR_DIR/'cache'
52
21
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #To suppress warnings thrown by tensorflow from time import sleep import numpy as np from cv2 import cv2 import pyautogui as pg import Sudoku_Core as SC import OCR s = 513//9 #Size of board//9 fs = 25 #Size of the final image def getBoard(): pg.click(266, 740) sl...
1,687
813
from app import db, login from flask_login import UserMixin from datetime import datetime from flask import url_for, redirect from werkzeug.security import generate_password_hash, check_password_hash class users(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True, autoinc...
3,570
1,131
# AUTOGENERATED! DO NOT EDIT! File to edit: source_nbs/12_top.ipynb (unless otherwise specified). __all__ = ['empty_tensor_handling_loss', 'nan_loss_handling', 'create_dummy_if_empty', 'BaseTop', 'SequenceLabel', 'Classification', 'PreTrain', 'Seq2Seq', 'MultiLabelClassification', 'MaskLM'] # Cell import l...
19,911
6,162
class Solution(object): def firstUniqChar(self, s): """ :type s: str :rtype: int """ dict_1 = {} for i in s: if i not in dict_1: dict_1[i] = 1 else: dict_1[i] += 1 print(dict_1) ...
447
139
import re def process_cancellation_code(code): regex_days_before = "^(([0-9]+)D)(([0-9]+)N|([0-9]+)P)" regex_no_show = "(([0-9]+)P|([0-9]+)N)" options = re.split("_", code) final = [] for option in options: days_match = re.match(regex_days_before, option) if days_match: ...
3,332
1,073
import re regex = re.compile('[^a-zA-Z]') def score_word(word, corpus=None): word = regex.sub('', word) # leave only alpha score = 0 consec_bonus = 2 for i, letter in enumerate(word): if letter.islower(): continue if i > 0 and word[i-1].upper(): score += conse...
1,163
371
import requests num_of_iter = 2 data = open('./assets/test.jpg', 'rb').read() for i in range(0, num_of_iter): res = requests.get( url='http://0.0.0.0:8000/recognition/object/boxes_names' ) print("\n RESPONSE GET boxes names for test number {}: \n {}" .format(i, res.__dict__)) res = req...
956
328
import argparse import os import torch import torch.nn as nn from torchtext.data import TabularDataset, BucketIterator from torchtext.data import Field from torchtext.vocab import Vectors, GloVe from tqdm import tqdm, trange import sys import os sys.path.insert(0, "../../pyfunctor") sys.path.insert(0, "../../model") f...
7,698
2,548
#!/usr/bin/env python from setuptools import setup, find_packages import sys try: import pypandoc readme = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): with open('README.md') as f: readme = f.read() install_requires = [ 'cachetools>=1.1.5', 'requests>=2.7.0', 'xm...
1,566
528
"""Extension for built-in Sass functionality.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from itertools import product import math import os.path from pathlib import PurePosixPath from six.moves import xrange ...
24,050
7,940
from pypy.module.cpyext.test.test_api import BaseApiTest class TestIterator(BaseApiTest): def test_check_iter(self, space, api): assert api.PyIter_Check(space.iter(space.wrap("a"))) assert api.PyIter_Check(space.iter(space.newlist([]))) assert not api.PyIter_Check(space.w_type) ass...
906
319
# coding=utf-8 # Copyright 2019 The Google Research Authors. # # 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 applicab...
21,407
7,337
# Copyright 2021 Internet Corporation for Assigned Names and Numbers. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at https://mozilla.org/MPL/2.0/. # # Developed by Sinodun IT (sinodun.com) # # Ag...
42,865
8,559
""" Module to train a simple MLP for demo. """ from jobman.tools import expand from jobman.tools import flatten import logging import nice_experiment import numpy as np from os import path from pylearn2.config import yaml_parse from pylearn2.neuroimaging_utils.datasets import MRI from pylearn2.neuroimaging_utils.data...
2,812
914
#Embedded file name: /Users/versonator/Jenkins/live/output/Live/mac_64_static/Release/python-bundle/MIDI Remote Scripts/_Framework/Layer.py u""" Module implementing a way to resource-based access to controls in an unified interface dynamic. """ from __future__ import absolute_import, print_function, unicode_literals fr...
6,199
1,709
# retrieve_exons_sequence_genomes.py # This script is to retrieve exons from sequenced genomes which are also present in the reference genome (A. thaliana). # To identify the contigs from the sequenced genomes, each contig has to be retrieved from A. thaliana first. # Then, for each sequence query of A. thaliana, the q...
1,529
555
import re class lexical(object): '''Lexical Features: Top Level domain (str) Number of dots in hostname (int) Average token length of hostname (float) Max token length of hostname (int) Average token length of path (float) Max token length of path (int) ''' def __init__(self): pass de...
1,136
395
import unittest from ....providers.aws.interactive import requires_replacement def generate_resource_change(replacement=True): resource_change = { "Action": "Modify", "Details": [], "LogicalResourceId": "Fake", "PhysicalResourceId": "arn:aws:fake", "Replacement": "True" if ...
992
270
from setuptools import setup, find_packages def readme(): with open('README.rst') as f: return f.read() setup( name='digicert-express', version='1.1dev2', description='Express Install for DigiCert, Inc.', long_description=readme(), classifiers=[ 'Development Status :: 3 - Alpha...
1,046
340
import argparse import json import numpy as np import os import torch import data_ import models import utils from matplotlib import cm, pyplot as plt from tensorboardX import SummaryWriter from torch import optim from torch.utils import data from tqdm import tqdm from utils import io parser = argparse.ArgumentPars...
11,392
3,731
import sys sys.path.append('../utils') from utils import * from doubly_linkedlist import * def link_chords(chordprogression): """ Chord progression is a sequences of chords. A valid linked_chords can be one of the following: 1: the chord name(str) in CHORD dict 2: the key(type Key) and a music ...
2,266
824
# coding: utf-8 #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #---------------------------------------------------------------------...
5,777
1,539
import argparse PROJROOTDIR = {'mac': '/Users/taehapark/SLAB/speedplusbaseline', 'linux': '/home/somrita/Documents/Satellite_Pose_Estimation/speedplusbaseline'} DATAROOTDIR = {'mac': '/Users/taehapark/SLAB/speedplus/data/datasets', 'linux': '/home/somrita/Documents/Satellite_Pose_Estim...
3,758
1,183
""" HyperOne HyperOne API # noqa: E501 The version of the OpenAPI document: 0.1.0 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from h1.api_client import ApiClient, Endpoint as _Endpoint from h1.model_utils import ( # noqa: F401 check_allowe...
118,963
28,842
from django.http import HttpResponse from django.utils.module_loading import import_string def pdf(request): """ Get form's number (decimal type: 101.15 - where "101" is form's group and "15"-number itsels). Can't use 1,2,3,4,5,6,7,8,9 for number itsels - which stands after the point. Bacause in datab...
811
300
#!/usr/bin/env python import PySimpleGUI as sg import cv2 import subprocess import shutil import os import sys # Demonstrates a number of PySimpleGUI features including: # Default element size # auto_size_buttons # Button # Dictionary return values # update of elements in form (Text, Input) def runCommand(cmd...
5,087
1,554
# # This is Seisflows # # See LICENCE file # ############################################################################### raise NotImplementedError
152
40
from data.objects.data import Data class Sample(Data): """ A way to sample from a dataset for testing purposes. """ def __init__(self, data, num = 100): self.data = data self.dataset_name = data.get_dataset_name() self.class_attr = data.get_class_attribute() self.positiv...
938
292
# -*- coding: utf-8 -*- from rest_framework import viewsets from rest_framework.permissions import IsAuthenticatedOrReadOnly from .models import Country, Event from .serializers import CountrySerializer, EventSerializer class CountryViewSet(viewsets.ModelViewSet): queryset = Country.objects.all() serializer...
572
159
# -*- coding: utf-8 -*- # Spearmint # # Academic and Non-Commercial Research Use Software License and Terms # of Use # # Spearmint is a software package to perform Bayesian optimization # according to specific algorithms (the “Software”). The Software is # designed to automatically run experiments (thus the code name ...
21,764
6,672
from machine import Pin, ADC from network import LoRa import socket from utime import sleep # Use a pin for a 'config' mode configPin = Pin('P21', Pin.IN, Pin.PULL_UP) # Create an ADC object adc = ADC() # vbatt pin: vbatt = adc.channel(attn=1, pin='P16') def battConversion(): adcVoltage = vbatt() voltage = ...
1,125
455
""" A Lake Winnipeg Basin Information Network (BIN) harvester for the SHARE project Example API request: http://130.179.67.140/api/3/action/package_search?q= (problematic) http://130.179.67.140/api/3/action/current_package_list_with_resources (currently using) It oddly returns 5 more datasets than all searchable ones ...
7,209
2,122
from dataclasses import dataclass from bindings.gmd.point_type import PointType __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class Point(PointType): """A Point is defined by a single coordinate tuple. The direct position of a point is specified by the pos element which is of type DirectPositi...
402
122
# Generated by Django 2.2.8 on 2020-04-13 09:12 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('exams', '0018_auto_20200412_1715'), ] operations = [ migrations.CreateModel( name='ExamChoice',...
1,050
343
# -*- coding: utf-8 -*- """Jacobian preconditioner. """ from root.config.main import * from scipy import sparse as spspa from tools.linear_algebra.preconditioners.base import Preconditioner class JacobiPreconditioner(Preconditioner): """""" def __init__(self, A): """""" super(JacobiPreconditio...
1,028
374
from django.contrib.sites.models import Site from django.db import models class Redirect(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=1024, blank=True, null=True) social_image = models.ImageField(null=True, blank=True) old_path = models.CharField(m...
904
287
# Copyright 2018 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
7,767
3,129
from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse from django.urls import reverse from django.utils.translation import gettext as _ from wagtail.admin import messages from wagtail.admin.views.pages.utils im...
2,074
614
import logging import os.path as path from typing import List, Optional, Tuple from psychopy import core, visual from bcipy.acquisition.marker_writer import NullMarkerWriter, MarkerWriter from bcipy.helpers.task import SPACE_CHAR from bcipy.helpers.stimuli import resize_image from bcipy.helpers.system_utils import ge...
14,783
4,160
#!/usr/bin/env python import pymysql #Python3 db = pymysql.connect("localhost","sips","root","zaijian" ) cursor = db.cursor() cursor.execute("SELECT VERSION()") data = cursor.fetchone() print ("Database version : %s " % data) db.close() def create_table(): db = pymysql.connect("localhost","sips","root","zaijian"...
932
360
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from...
14,363
4,691
# -*- coding: utf-8 -*- """ awsecommerceservice This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ class ItemLookupRequest(object): """Implementation of the 'ItemLookupRequest' model. TODO: type model description here. Attributes: condition (ConditionE...
4,203
1,090
from __future__ import absolute_import from __future__ import print_function from __future__ import division import numpy as np import cPickle as pickle from keras import backend as K from keras.utils import np_utils from keras.preprocessing import sequence from random import shuffle import itertools def load_datas...
6,372
1,904
from RegressaoLinear import RegressaoLinear planoCartesiano = { 0.5: 4.4, 2.8: 1.8, 4.2: 1.0, 6.7: 0.4, 8.3: 0.2 } regressaoLinear = RegressaoLinear(planoCartesiano) print(regressaoLinear.gerar_equacao())
217
110
import dash from dash import html from dash import dcc import dash_bootstrap_components as dbc from dash.dependencies import Input, Output from .layout import * from .plot import * # from layout import * # from plot import * app = dash.Dash( __name__, external_stylesheets=[dbc.themes.BOOTSTRAP, "/css/button.css"...
1,528
541
# Copyright 2018 MassOpenCloud. # # 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 agr...
3,035
965
# 搜索二叉树 from queue import Queue class Node(object): """节点""" def __init__(self, data): self.data = data self.node_left = None self.node_right = None class BinaryTree(object): def __init__(self): self.root = None def insert(tree, node): """插入节点""" if tree....
3,296
1,201
#empréstimos bancários. pegue o valor da casa, o salario da pessoa e em quanto tempo ela quer pagar. #se as parcelas ficarem acima de 30% do salario, negue o imprestimo. casa = float(input('Informe o valor da casa: R$')) salario = float(input('informe seu salario: R$')) tempo = int(input('Em quanto tempo planeja ...
703
272
#Integer division #You have a shop selling buns for $2.40 each. A customer comes in with $15, and would like to buy as many buns as possible. #Complete the code to calculate how many buns the customer can afford. #Note: Your customer won't be happy if you try to sell them part of a bun. #Print only the result, any o...
433
136
# ******************************************************************************************* # ******************************************************************************************* # # Name : test_maths.py # Purpose : Create lots of variables/arrays and arithmetic/bitwise. # Date : 10th June 2019 # Author...
1,708
649
# 所有的unicode字符 from collections import Counter import qa.regex_utils as regutil import re resource_path = "/media/tmxmall/a36811aa-0e87-4ba1-b14f-370134452449/data/medicine.txt" with open(resource_path, "r", encoding="utf8") as f: char_stream = f.read() char_dictionary = Counter(list(char_stream)) med_unicodes =...
19,191
10,359
from largest_product.py import largest_product import pytest def test_product_returns(): """test if return is a single product """ assert largest_product.largest([[2, 2]]) is 4 def test_returns_largest(): """ test if return is the largest of longer array """ assert largest_product.largest([[1, 3], [6...
622
213
# Copyright 2020 DeepMind Technologies Limited. 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 ...
4,086
1,403
#!/usr/bin/env python import boto3 import cv2 import numpy import os import base64 import gspread from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from httplib2 import Http from time import localtime, strftim...
7,827
2,156
# -*- coding: utf-8 -*- """Implicitly reference attributes of an object.""" from ast import Name, Assign, Load, Call, Lambda, With, Str, arg, \ Attribute, Subscript, Store, Del from macropy.core.quotes import macros, q, u, name, ast_literal from macropy.core.hquotes import macros, hq from macropy.core...
8,480
2,987
"""Handle exceptions generated from 'user' code""" import sys import traceback class InvalidCommand(Exception): """Invalid command line argument.""" def __init__(self, *args, **kwargs): self.not_found = kwargs.pop('not_found', None) super(InvalidCommand, self).__init__(*args, **kwargs) ...
2,935
837
# GUI used for quickly plotting BOSS spectra. Also allows overplotting of best-fit template as # determined by redmonster pipeline. Sort of a redmonster version of plotspec.pro, though currently # with less bells and whistles. # # Tim Hutchinson, University of Utah, April 2014 # Signifcantly updated by TH, October 20...
17,358
5,472
# An algorithm to reconstruct the queue. # Suppose you have a random list of people standing in a queue. # Each person is described by a pair of integers (h,k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. class Solution: de...
565
158
from django.db import models from django.utils.translation import gettext_lazy as _ class ClasseViagem(models.TextChoices): ECONOMICA = 'ECO', _('Econômica') EXECUTIVA = 'EXE', _('Executiva') PRIMEIRA_CLASSE = 'PRI', _('Primeira')
255
97
# -*- coding: utf-8 -*- """ This is part of HashBruteStation software Docs EN: http://hack4sec.pro/wiki/index.php/Hash_Brute_Station_en Docs RU: http://hack4sec.pro/wiki/index.php/Hash_Brute_Station License: MIT Copyright (c) Anton Kuzmin <http://anton-kuzmin.ru> (ru) <http://anton-kuzmin.pro> (en) Integration tests f...
9,046
3,342