text
string
size
int64
token_count
int64
# Copyright 2015 gRPC 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 applicable law or agreed to in writing...
1,918
590
#!/usr/bin/env python from airtable import Airtable import csv import os for var in ["AIRTABLE_API_KEY", "AIRTABLE_BASE_ID"]: if os.environ.get(var) is None: sys.exit(f"Must set {var} env var!") api_key = os.environ.get("AIRTABLE_API_KEY") base_id = os.environ.get("AIRTABLE_BASE_ID") airtable = Airtable...
604
224
""" # Utilities for interacting with NCBI EUtilities relating to PubMed """ __version__ = "0.0.1"
99
37
import json import sys import traceback from logging import Handler # Specific logging module for GCP, use json to serialize output -> work better for GKE # Can be used for further customization class GCPHandler(Handler): def emit(self, record): try: message = self.format(record) ...
945
265
""" A simple Top-Down Python expression parser. This parser is based on the "Simple Top-Down Parsing in Python" article by Fredrik Lundh (http://effbot.org/zone/simple-top-down-parsing.htm) These materials could be useful for understanding ideas behind the Top-Down approach: * Top Down Operator Precedence -- Dougla...
16,095
5,024
from copy import deepcopy N, M = map(int, input().split()) E = [[] for _ in range(N)] for i in range(M): x, y = map(lambda x:int(x)-1, input().split()) E[x].append(y) E[y].append(x) ans = 0 for mask in range(2**N): faction = '' for x in range(N): faction += '1' if mask&(1<<x) else '0' fl...
597
224
from django.urls import path from advisor.api.views import ( # api_advisor_view, api_advisor_view_post, ) app_name = 'advisor' urlpatterns = [ path('admin/advisor/', api_advisor_view_post, name="post"), # path('user/<int:id>/advisor/', api_advisor_view, name="detail"), ]
290
110
import box from typing import Text import yaml def load_config(config_path: Text) -> box.ConfigBox: """Loads yaml config in instance of box.ConfigBox. Args: config_path {Text}: path to config Returns: box.ConfigBox """ with open(config_path) as config_file: config = yaml....
405
125
import pandas as pd import numpy as np import networkx as nx import click import pickle from sklearn.preprocessing import LabelEncoder CONTEXT_SETTINGS = dict(help_option_names=['-h','--help'], max_content_width=90) @click.group(context_settings= CONTEXT_SETTINGS) @click.version_option(version='0.1') def visualize():...
3,835
1,373
import boto3 from botocore.exceptions import ClientError import datetime import pytest from moto import mock_sagemaker from moto.sts.models import ACCOUNT_ID FAKE_ROLE_ARN = "arn:aws:iam::{}:role/FakeRole".format(ACCOUNT_ID) TEST_REGION_NAME = "us-east-1" class MyProcessingJobModel(object): def __init__( ...
13,343
4,520
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'direction_sprite_widget.ui' # # Created: Wed Jul 30 18:37:40 2014 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUt...
7,853
2,597
import autopep8 import nbformat from coalib.bearlib.spacing.SpacingHelper import SpacingHelper from coalib.bears.LocalBear import LocalBear from dependency_management.requirements.PipRequirement import PipRequirement from coalib.results.Diff import Diff from coalib.results.Result import Result from coalib.settings.Set...
4,913
1,448
import nltk import string import argparse parser = argparse.ArgumentParser(description='.') parser.add_argument('-text', help='') parser.add_argument('-meta', help='') parser.add_argument('-output', help='') args = parser.parse_args() # parser.add_argument('-iter', dest='iter', type=int, # defaul...
1,043
441
from models.glow import Glow, GlowAdditive
43
15
from Logic.Classes.LogicDataTables import LogicDataTables from Logic.Data.DataManager import Writer from Logic.Data.DataManager import Reader class ChronosTextEntry: def decode(self: Reader): self.readInt() self.readString() def encode(self: Writer): self.writeInt(0) self.writ...
350
110
#!/usr/bin/env python3 from urllib.request import urlopen import sys # Get the animals def fetch_animals(url): """Get a list of lines (animals) from a given URL. Args: url: The URL of a utf-8 text Returns: A list of lines. """ with urlopen(url) as data: animals = [] ...
1,136
377
from collections import deque import numpy as np import os from abc import ABCMeta, abstractmethod import random random.seed(42) from common import config, VehicleState from helper import Helper INFO = """Average merging time: {} s Traffic flow: {} vehicle/s Average speed: {} km/h Average fuel consumptio...
19,762
7,180
# Crie um programa que leia uma frase qualquer e diga se ele é um palíndromo, desconsiderando os espaços. frase = str(input('Digite uma frase: ')).strip() palavras = frase.split() junto = ''.join(palavras) inverso = '' for c in range( len(junto)-1, -1, -1): inverso += junto[c] if inverso == junto: print('A fra...
387
152
import os import glob import json for f in glob.glob('/Users/sparky/Documents/solr_responses/solr_20150922_docs/*.json'): with open(f, 'r') as g: data = json.loads(g.read()) headers = data.get('response_headers', []) if not headers: continue headers = dict( (k.strip().lower(),...
562
197
import pytest import datetime import json import functools from urllib.parse import urlencode, parse_qs from descarteslabs.common.graft import client as graft_client from ... import types from .. import tile_url def test_url(): base = "foo" base_q = base + "?" url = functools.partial(tile_url.tile_url...
5,024
1,857
# Generated by Django 3.0.2 on 2020-01-31 20:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('collections', '0002_auto_20200109_1348'), ] operations = [ migrations.AlterField( model_name='collection', name='com...
1,112
326
#!/usr/bin/env python import rospy # python client library for ROS from violet_services.srv import WordCount # needed message type import sys # python functions, methods, etc. rospy.init_node('service_client') # initialize client node rospy...
908
246
# -*- coding: utf-8 -*- import os import torch from torch.autograd import Variable import numpy as np import scipy import matplotlib.pyplot as plt import cv2 import scipy.ndimage import shutil import scipy.misc as misc from PIL import Image def mkdirs(folders, erase=False): if type(folders) is not list: ...
8,249
2,849
#!/usr/bin/env python """Python-Pinboard Python script for downloading your saved stories and saved comments on Hacker News. """ __version__ = "1.1" __license__ = "BSD" __copyright__ = "Copyright 2013-2014, Luciano Fiandesio" __author__ = "Luciano Fiandesio <http://fiandes.io/> & John David Pressman <http://jdpressman...
9,882
2,934
import itertools def next_step(board, i, j): xMin = max(0, j - 1) xMax = min(board.shape[1] - 1, j +1) yMin = max(0, i - 1) yMax = min(board.shape[0] - 1, i +1) iteration = list(itertools.product(range(yMin, yMax + 1), range(xMin, xMax+1))) iteration.remove((i,j)) sum = 0; for (k, m) i...
558
230
""" Rapid Response block models """ from django.conf import settings from django.db import models from django.utils.encoding import python_2_unicode_compatible from jsonfield import JSONField from model_utils.models import TimeStampedModel from opaque_keys.edx.django.models import ( CourseKeyField, UsageKeyFi...
2,110
644
import abc from sched_slack_bot.model.reminder import Reminder class ReminderSender(abc.ABC): @abc.abstractmethod def send_reminder(self, reminder: Reminder) -> None: raise NotImplementedError("Not Implemented") @abc.abstractmethod def send_skip_message(self, reminder: Reminder) -> None: ...
371
116
from flask import render_template from app import app, html_generator import app.calculator.calculator as calc from app.route_helpers import units_from_form, options_from_form, options_list, flash_errors from app.forms import InputForm from collections import defaultdict @app.route('/', methods=['GET', 'POST']) @app....
1,987
577
from smalisca.core.smalisca_main import SmaliscaApp from smalisca.modules.module_smali_parser import SmaliParser from smalisca.core.smalisca_app import App from smalisca.core.smalisca_logging import log from smalisca.modules.module_sql_models import AppSQLModel import smalisca.core.smalisca_config as config import mul...
1,505
541
class_name = 'users_and_roles_tab' from qtpy import QtCore, QtGui, QtWidgets, uic import os import sys import re import pathlib import json from logzero import logger from modules.sumologic import SumoLogic from modules.shared import ShowTextDialog class users_and_roles_tab(QtWidgets.QWidget): def __init__(self...
31,373
8,343
from twarc import Twarc2, expansions from pathlib import Path import json import config import os import config appConfig = config.Config client = Twarc2(bearer_token=appConfig.bearer_token) file_path = Path(f"{appConfig.file_path}{appConfig.file_name}") def main(): # result params try: search_resul...
1,201
350
import re def find_indices(): return [m.start(0) for m in re.finditer(reg, content)] def find_content(): return re.findall(reg, content) if __name__ == "__main__": content = 'an example word:cat and word:dog' reg = r'word:\w' print(find_indices()) print(find_content())
300
110
#!/usr/bin/env python # -*- encoding: utf-8 -*- import pytest import torch import torch.distributed as dist import torch.multiprocessing as mp from colossalai.communication import (recv_backward, recv_forward, recv_tensor_meta, send_backward, ...
5,944
2,024
# # Functions for mining blocks # import itertools from javascript import require Vec3 = require('vec3').Vec3 from botlib import * from inventory import * from workarea import * class MineBot: needs_iron_pickaxe = ["Gold Ore", "Redstone Ore", "Diamond Ore", "Emerald Ore"] needs_diamond_pickaxe = ["Obsi...
23,622
7,743
import smart_imports smart_imports.all() class AccountPrototypeTests(utils_testcase.TestCase, personal_messages_helpers.Mixin): def setUp(self): super(AccountPrototypeTests, self).setUp() self.place_1, self.place_2, self.place_3 = game_logic.create_test_map() self.account = self.account...
16,667
5,485
inp = input().split(" ") adult = int(inp[0]) child = int(inp[1]) if adult == 0 and child == 0: print("0 0") quit() if adult == 0: print("Impossible") quit() min = 0 # К каждому взрослому один бесплатный ребенок => # "Платные дети" это разница между взрослыми и всеми детьми not_free_child = child - ad...
698
282
default_app_config = "tests.django.apps.MyAppConfig"
52
18
from setuptools import setup from os import path VERSION = '1.0.0' DESCRIPTION = 'Defichain Python Library' # Project URLs project_urls = { "Tracker": "https://github.com/eric-volz/DefichainPython", "Documentation": "https://docs.defichain-python.de" } this_directory = path.abspath(path.dirname(__file__)) wi...
1,440
469
# Copyright (c) 2018, NVIDIA CORPORATION. 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 appli...
4,936
2,062
show databases; show tables desc table名 use database名 delete from 库名.表名 where id=5; select * from 表名 where id=5; update 表名 set age=15,home='北京' where id=5
160
64
import multiprocessing from gensim.models.word2vec import Word2Vec def build_gensim_w2v_model(model_path, iter_tokens, size, window, min_count): """ Parameters ---------- model_path : string Path of Word2Vec model iter_tokens : iterator Iterator of documents, which are lists of wo...
604
199
import logging import os from copy import copy import requests from jinja2 import Environment, FileSystemLoader logger = logging.getLogger(__name__) absolute_path = os.path.split(os.path.abspath(__file__))[0] class TelegramNotifier: def __init__(self, chat_id, auth_key): self._auth_key = auth_key ...
2,945
880
import numpy import math from sklearn.metrics import mean_squared_error def root_mean_squared_error(y_true, y_pred): return math.sqrt(mean_squared_error(y_true, y_pred)) def mean_absolute_percentage_error(y_true, y_pred): return numpy.mean(numpy.abs((y_true - y_pred) / y_true)) * 100
295
112
''' 杨氏矩阵查找 在一个m行n列二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下 递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 ''' def get_value(l, r, c): return l[r][c] def find(l, x): m = len(l) - 1 n = len(l[0]) - 1 r = 0 c = n while c >= 0 and r <= m: value = get_value(l, r, c) if value == x: ...
446
276
#!/usr/bin/env python3 import json import time from run_common import AWSCli from run_common import print_message from run_create_codebuild_common import create_base_iam_policy from run_create_codebuild_common import create_iam_service_role from run_create_codebuild_common import create_managed_secret_iam_policy from ...
3,854
1,113
#!/usr/bin/env python """Configuration parameters for the test subsystem.""" import os from grr.lib import config_lib # Default for running in the current directory config_lib.DEFINE_constant_string( "Test.srcdir", os.path.normpath(os.path.dirname(__file__) + "/../.."), "The directory containing the source...
2,282
638
from django.urls import path urlpatterns=[ path('profile',views.profile, name='profile'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
224
68
import typing as t from pylogview import datefinder from pylogview.record import LogRecord if t.TYPE_CHECKING: from pylogview.window import Window class LogReader: __slots__ = [ "_window", "filename", "_lines", "records", "_record_prefix_length", "_fd", ...
8,940
2,354
x = int(input('Podaj pierwsza liczbe calkowita: ')) y = int(input('Podaj druga liczbe calkowita: ')) z = int(input('Podaj trzecia liczbe calkowita: ')) print() if x > 10: print(x) if y > 10: print(y) if z > 10: print(z)
235
107
from mailmerge import MailMerge import re import os.path from ElvantoAPIExtensions import Enums, Helpers from modules.__stub__ import ModuleStub class Module(ModuleStub): __VERSION__ = "1.0" __NAME__ = "bulletinGenerator_Kingsgrove" # __executeTime__ = "16:00" # __executeDay__ = "thursday" setting...
6,194
1,716
#!/usr/bin/env python ''' Simple script to execute shell command on lab router with Pexpect module. ''' import pexpect, sys, re from getpass import getpass def main(): ## Define variables ip_addr = '184.105.247.71' username = 'pyclass' port = 22 password = getpass() ## Set up connection with r...
1,434
450
"""Test class for MissingRequiredFieldError error.""" from django.test import SimpleTestCase from utils.errors.MissingRequiredFieldError import MissingRequiredFieldError class MissingRequiredFieldErrorTest(SimpleTestCase): """Test class for MissingRequiredFieldError error. Note: Tests to check if these were...
2,081
540
"""plot.py: Utility builder class for ML plots. Uses scikit-learn code samples and framework """ __author__ = "Mihai Matei" __license__ = "BSD" __email__ = "mihai.matei@my.fmi.unibuc.ro" import numpy as np import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import randomcolor im...
12,685
4,237
#! /usr/bin/env python # -*- coding: utf-8 -* import collections from census_data_downloader.core.tables import BaseTableConfig from census_data_downloader.core.decorators import register @register class MedianAgeDownloader(BaseTableConfig): PROCESSED_TABLE_NAME = 'medianage' UNIVERSE = "total population" ...
478
175
# Copyright 2018 Bloomberg Finance L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
3,791
1,246
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, os, time, serial, json import numpy as np import pyqtgraph as pg import pyqtgraph.console from PyQt5.QtCore import pyqtSignal, QObject from pyqtgraph.Qt import QtCore, QtGui from pyqtgraph.dockarea import * from icm.ui_clock import * from icm.ui_createfile ...
1,285
429
import dectate import pytest from kaybee.plugins.widgets.directive import WidgetDirective from kaybee.plugins.widgets.action import WidgetAction class Dummy: pass @pytest.fixture() def widgets_kb_app(): class widgets_kb_app(dectate.App): widget = dectate.directive(WidgetAction) yield widgets_k...
1,603
565
import hashlib import torch import torch.nn as nn class Model(nn.Module): """ Class representing sampleable neural network model """ def __init__(self, dtype=torch.float64, device='cpu'): super().__init__() self.dtype = dtype self.device = device def summary(self, hashsummary=False...
1,751
531
while True: try: dados = [] matriz = [] n = int(input()) for linha in range(0, n): for coluna in range(0, n): dados.append(0) matriz.append(dados[:]) dados.clear() # Numeros na diagonal for diagonal_principal in rang...
1,129
371
import os import time import random import scipy.sparse as sp import numpy as np import tensorflow as tf import argparse from models import SpHGAT from utils import process parser = argparse.ArgumentParser() parser.add_argument('--dataset', help='Dataset.', default='imdb', type=str) parser.add_argument('--epochs', he...
17,145
5,999
''' http://pythontutor.ru/lessons/ifelse/problems/minimum/ Даны два целых числа. Выведите значение наименьшего из них. ''' val_01 = int(input()) val_02 = int(input()) if val_01 > val_02: print(val_02) else: print(val_01)
230
105
from PyQt5.QtWidgets import QWidget, QMessageBox class uiLicenseWindow(QMessageBox): """ The MIT License (MIT) https://mit-license.org/ """ def __init__(self, parent: QWidget): super().__init__(parent) self.parent = parent self.title = "The MIT License (MIT)" #Hardcoded License self.license = "<pre><b>...
1,705
609
import sys import os class Console(object): """ Class responsible for handling input from the user """ def __init__(self): self.log_file = "log.txt" # initialize log with open(self.log_file, 'a') as file: file.write("** NEW LOG CREATED **\n") @staticmethod ...
2,021
550
import time import os servos = {} class ServoController: def __init__(self): os.system('sudo /home/pi/PiBits/ServoBlaster/user/servod') def setAngle(self, servo_id, degrees): if degrees > 90: degrees = 90 elif degrees < -90: degrees = -90 #http://www.raspberrypi.org/forums/viewtopic.php?f=44&t=36572...
766
361
from django import forms from .models import Problem class ProblemForm(forms.ModelForm): options = ( ('A', 'A'), ('B', 'B'), ('C', 'C'), ('D', 'D'), ) choice = forms.ChoiceField(choices=options) class Meta: model = Problem fields = '__all__' # exclude = ['answer'] widgets = { 'answer': forms.Hid...
728
287
#!/usr/bin/env python """ Create a spreadsheet with two tables, using some named ranges. """ import os from odfdo import Document, Table if __name__ == "__main__": document = Document('spreadsheet') body = document.body table = Table("First Table") body.append(table) # populate the table : for...
2,404
870
from django.apps import AppConfig class GmailBoxConfig(AppConfig): name = 'gmailbox'
91
29
#!/bin/python3 import math import os import random import re import sys # Complete the sockMerchant function below. def sockMerchant(n, ar): socks = {} for elem in ar: if elem in socks: socks[elem] += 1 else: socks[elem] = 1 return sum(elem // 2 for elem in socks.va...
724
294
from nltk.corpus.reader import CategorizedPlaintextCorpusReader from nltk.tokenize.casual import TweetTokenizer from nltk.classify.scikitlearn import SklearnClassifier from sklearn.naive_bayes import BernoulliNB, MultinomialNB from sklearn.svm import SVC, LinearSVC, NuSVC, LinearSVR, NuSVR from sklearn.linear_model im...
5,468
1,799
# # ⚠ Warning # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT # LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIA...
10,712
3,337
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : yag8009 # @FileName : md5_hede # @Time : 2020/3/18 import hashlib import time def md5_hede(md5data): md5 = hashlib.md5() # 使用MD5加密模式 md5.update(md5data.encode("utf8")) # 将参数字符串传入 sign = md5.hexdigest() return sign if __name__ == '__mai...
639
348
from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from .extensions import db class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) password = db.Column(db.Stri...
2,270
779
from __future__ import absolute_import, division, print_function import logging import sys from mesos.interface import Scheduler from .messages import Filters, decode, encode class SchedulerProxy(Scheduler): def __init__(self, scheduler): self.scheduler = scheduler def registered(self, driver, fr...
9,586
2,290
import numpy as np class NeuralNetwork: """ Class implementing a feed forawrd neural network. Object fields: layers = a tuple containing numbers of neurons in each layer, starting from the input layer L = depth of the NN, eg, with depth L there are L matrices W: W[1], ...,W[L] ac...
6,759
2,123
#============================================================================ # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distributed in the hope th...
3,350
1,050
import re class Luhn(object): def __init__(self, card_num): self.number = card_num def valid(self): if re.search("[^0-9 ]", self.number) or len(re.findall("[0-9]", self.number)) <= 1: return False else: digits = re.sub("[^0-9]", "", self.number) dig...
591
199
import numpy as np import scipy.linalg import argparse import time from contextlib import contextmanager def measureTime(f, nTrial=3): def f_timer(*args, **kwargs): times = list() for rep in range(nTrial): start = time.time() result = f(*args, **kwargs) end ...
3,342
1,401
from subprocess import run from actions.common import get_name_and_org, get_process_config from flask import request def set_status(): if not "id" in request.form and 'status' in request.form: return "Bad request", 400 id, status = request.form['id'], request.form['status'] if(id == 'bedrock-oss:server-upd...
1,450
471
import os import datetime from dateutil.parser import parse as dateutil_parser from jinja2 import Environment, PackageLoader from kinto_http import cli_utils from . import constants from .logger import logger JSON_DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ" COLLECTION_FORMAT = '/buckets/{bucket_id}/collections/{collection_i...
4,067
1,229
"""Make some fields on Chart and Table nullable We want to copy chart and table data across to these tables but have no way to add a classification for each one, so we'll have to live with some nulls in here. Revision ID: 2019_03_04_make_fields_nullable Revises: 2019_03_04_chart_table_settings Create Date: 2019-03-05...
2,270
806
"""Tests for channel API middleware""" from django.utils.functional import SimpleLazyObject from open_discussions.middleware.channel_api import ChannelApiMiddleware def test_channel_api_middleware( mocker, jwt_token, rf, user ): # pylint: disable=unused-argument """Tests that the middleware makes a channel ...
962
302
# query_strings.py ''' Since Sqlite queries are inserted as string in Python code, the queries can be stored here to save space in the modules where they are used. ''' delete_color_scheme = ''' DELETE FROM color_scheme WHERE color_scheme_id = ? ''' insert_color_scheme = ''' INSERT INT...
2,019
725
# Generated by Django 2.2.1 on 2019-05-14 13:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('travel', '0028_auto_20190514_1929'), ] operations = [ migrations.AlterField( model_name='user', name='uid', ...
428
179
#!/usr/bin/env python """, Mocked Ruby based Sensu server. Connects to the RabbitMQ instance and sends check requests as Sensu server would and waits for appropriate response. Fails the response is not received at all or in invalid format. """ import click import json import pika import signal import sys CI_TEST_RES...
2,027
640
from django.contrib import admin from .models import ContactForm class ContactFormAdmin(admin.ModelAdmin): class Meta: model = ContactForm admin.site.register(ContactForm, ContactFormAdmin)
205
54
""" HackerRank :: Reverse a singly-linked list https://www.hackerrank.com/challenges/reverse-a-linked-list/problem Complete the reverse function below. For your reference: SinglyLinkedListNode: int data SinglyLinkedListNode next """ def reverse(head): # head node value can be null # Keep track of p...
718
218
# Copyright (c) 2013 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. { 'variables': { 'chromium_code': 1, }, 'targets': [ { 'target_name': 'gfx', 'type': '<(component)', 'dependencies': [ ...
12,566
4,543
import numpy as np import h5py import os import sys from copy import deepcopy #handle .(period) and slash specially since it is part of path #replace with \period or \slash-forward when store, recover later #not using '\forward-slash' is because \f is a special character PERIOD='\period' SLASH='\slash-forward' ''' ...
2,191
857
import re import string from libs.dataset.core import SampleEntry, oov_replacement_vocabulary, letter_replacements __word_start_regex = f'[ \t\n]|^|[{string.punctuation}]' __word_end_regex = f'[ \t\n]|$|[{string.punctuation}]' def does_not_have_numbers(s: SampleEntry): return not any(char.isdigit() for char in s...
2,238
880
#!/usr/bin/env python3 from rc.clients import APIClient if __name__ == '__main__': """ Given a valid RFID attempts to lookup the User's ID. Then using that User ID, if it exists, get more information about the User. """ # If the bash variables RC_PUBLIC_KEY and RC_PRIVATE_KEY # are not set you need t...
733
244
""" 113 / 113 test cases passed. Runtime: 92 ms Memory Usage: 16.4 MB """ class Solution: def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: m, n = len(heights), len(heights[0]) def dfs(used, x, y): used[x][y] = True for xx, yy in [(x + 1, y), (x - 1, y),...
1,015
393
__all__ = ( 'LIST', 'GET', 'CREATE', 'UPDATE', 'REPLACE', 'DELETE', 'ALL', 'get_http_methods' ) LIST = 'list' GET = 'get' CREATE = 'create' REPLACE = 'replace' UPDATE = 'update' DELETE = 'delete' ALL = (LIST, GET, CREATE, UPDATE, REPLACE, DELETE) _http_methods = { LIST: ('get',), GET: ('get',), CREATE: (...
456
200
import unittest import silasdk from tests.test_config import ( app, eth_private_key, eth_private_key_4, instant_ach_handle, user_handle) class Test007CheckInstantAchTest(unittest.TestCase): def test_check_instant_ach(self): payload = { "user_handle": instant_ach_handle, "accou...
617
197
#!/usr/bin/env python from functions import convert name = "convert"
72
22
""" https://adventofcode.com/2021/day/10 """ from functools import reduce def read_input(filename): with open(filename, "r", encoding='utf-8') as file: return [l.rstrip() for l in file.readlines()] opening_map = { ")": "(", "]": "[", "}": "{", ">": "<" } closing_map = {v: k for k,v in opening_map.items()...
1,758
624
# Copyright 2021 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, ...
2,318
703
# -*- coding: utf-8 -*- """ Created on 2017/11/18 @author: MG """
67
41
#!/usr/bin/env python from itertools import groupby, tee import json, os files = [ ('hg38', 'http://hgdownload.soe.ucsc.edu/goldenPath/hg38/database/cytoBand.txt.gz'), ('hg19', 'http://hgdownload.soe.ucsc.edu/goldenPath/hg19/database/cytoBand.txt.gz'), ('hg18', 'http://hgdownload.soe.ucsc.edu/goldenPath/h...
1,099
457
"""Click parameter types for osxphotos CLI""" import datetime import os import pathlib import re import bitmath import click import pytimeparse2 from osxphotos.export_db_utils import export_db_get_version from osxphotos.photoinfo import PhotoInfoNone from osxphotos.phototemplate import PhotoTemplate, RenderOptions fr...
6,973
2,116
''' All of these views are predicated on the user already being logged in to valid session. djago_ag/views.py John Whelchel Summer 2013 These are the views for the Replica Gateway section of the administration site. They are all decorated with @authenticate to make sure that a user is logged in; if not, they are re...
26,229
7,748