text
string
size
int64
token_count
int64
# coding=utf-8 import inspect import sys from openfda.tests.api_test_helpers import * def test_nullified_records(): NULLIFIED = ['USA-FDACVM-2018-US-045311', 'USA-FDACVM-2018-US-048571', 'USA-FDACVM-2018-US-046672', 'USA-FDACVM-2017-US-070108', 'USA-FDACVM-2017-US-002864', 'USA-FDACVM-2017-US-002866...
5,333
2,510
import requests import re import json import datetime import os DATE_FORMAT = '%Y-%m-%d' DATA_PATH = 'rupodcast_lengths.json' def extract_hms(g): return float(g[0] or 0) * 60 + float(g[1]) + float(g[2]) / 60 def extract_rss(dur): g = dur.split(':') while len(g) < 3: g = [0] + g return floa...
6,972
2,710
from django.conf.urls import patterns, include, url from . import views urlpatterns = [ url(r'^$', views.rate_list, name='list'), url(r'^(?P<pk>\d+)/$', views.rate_as_field, name='as_field'), url(r'^suggestions/$', views.suggestions, name='suggestions'), url(r'^create/$', views.create_rate, name='creat...
557
222
# importing libraries import numpy as np import pandas as pd import random import torch def set_seeds(seed=1234): """[Set seeds for reproducibility.] Keyword Arguments: seed {int} -- [The seed value] (default: {1234}) """ np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) ...
1,100
415
from django.apps import AppConfig class TreatmentsConfig(AppConfig): name = 'treatments'
95
30
""" Alarm Clock - A simple clock where it plays a sound after X number of minutes/seconds or at a particular time. Dependencies: pyglet pip install pyglet """ import time import winsound import pyglet def play(hh, mm): not_alarmed = 1 while(not_alarmed): cur_time = list(time.loc...
1,602
559
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_in_serializers ------------------- Tests of the fields cooperation in the serializer interfaces for serialization, de-serialization, and validation. """ # Django settings: import os os.environ['DJANGO_SETTINGS_MODULE'] = __name__ from django.conf.global_sett...
3,107
944
# Copyright 2016-2020 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause import json class _ReframeJsonEncoder(json.JSONEncoder): def default(self, obj): if hasattr(obj, '__rfm_json_enc...
642
232
### Copyright 2014, MTA SZTAKI, www.sztaki.hu ### ### 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...
3,072
979
#!/usr/bin/env python3 import sys, re for line in iter(sys.stdin.readline, ''): if re.search('agent ', line): print(line.strip())
147
54
from haptyc import * from base64 import b64encode, b64decode import json class TestLogic(Transform): # # test_h1: Decodes base64, fuzzes using random_insert, Re-encodes base64 # Number of tests: 50 # @ApplyIteration(50) def test_h1(self, data, state): data = b64decode(data) ...
1,277
436
import re from flask import Flask, request app = Flask(__name__) def generate_whitelist(): whitelist = [] with open('/whitelist.txt', 'r') as f: for line in f.readlines(): if line.strip().endswith('d.wott.local'): whitelist.append(line.strip()) return whitelist def g...
1,271
429
from flask import Flask from flask_sqlalchemy import SQLAlchemy from pathlib import Path app = Flask(__name__) BASE_DIR = Path(__file__).resolve().parent DB_PATH = str(BASE_DIR / "one_to_many.sqlite") app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + DB_PATH app.config["SQLALCHEMY_COMMIT_ON_SUBMIT"] = True app...
1,676
735
from .create_model_view import CreateModelView from .delete_model_view import DeleteModelView from .detail_model_view import DetailModelView from .list_model_view import ListModelView from .update_model_view import UpdateModelView
231
62
import boto3 import logging import json def get_secret(secret): client = boto3.client('secretsmanager') logging.info(f'Retrieving secret {secret}') response = client.get_secret_value(SecretId=secret) logging.debug(f'Retrieved Secret ARN {response["ARN"]} VersionId {response["VersionId"]}') return ...
357
112
# Ported from JavaSript version to Python and Pygame Zero # Designed to work well with mu-editor environment. # # Original by Ben Eater at https://github.com/beneater/boids (MIT License) # No endorsement implied. import random HEIGHT = 600 # window height WIDTH = 700 # window width MARG...
4,204
1,576
import pandas as pd import sys from os import system sys.path.append('../final_project/') sys.path.append('../') def readNames(inputFile='new_poi_names.txt'): ''' A function to read names data from a file create by a data cache Returns: Returns a data frame that contains data from 'poi_names.txt' ...
507
164
# Copyright 2015 Open Source Robotics Foundation, 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 law...
1,270
396
import pathlib class ExporterConfig: def __init__(self, github_token, gitlab_token): self.github_token = github_token self.gitlab_token = gitlab_token class ConfigLoader: @classmethod def load(cls, cfg): """ Load and validate application configuration for GitHub and Git...
4,833
1,417
# Copyright 1999-2021 Alibaba Group Holding 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 a...
3,613
1,351
import cx_Freeze import sys base = None if sys.platform == 'win32': base = "Win32GUI" executables = [cx_Freeze.Executable("Speech_Recognizer.py", base=base, icon = "icon.ico")] cx_Freeze.setup( name = "Speech Recognizer", author = "Mayank Kumar Giri", options = {"build_exe":{"packages":...
620
215
import sys import numpy as np import os import math import chardet import io COMPARISON_ACCURACY = 1e-2 MAX_SCORE = 1.0 HALF_SCORE = 0.5 SUBMISSION_SCORE = 0.0 MESSAGES_SCORE = {} MESSAGES_SCORE[SUBMISSION_SCORE] = lambda value, value_to_get : \ 'Your submission output is good, but the solution ob...
7,101
2,433
'''https://leetcode.com/problems/max-consecutive-ones/''' class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: i, j = 0, 0 ans = 0 while j<len(nums): if nums[j]==0: ans = max(ans, j-i) i = j+1 j+=1 return m...
332
123
#!/usr/bin/env python from setuptools import setup LONG_DESCRIPTION = \ '''The program extracts regions of interest from Fasta or Genome Feature Format (GFF) genomes. This is done given a set of seed sequences given as nucleotide strings in a multi-line fasta file. The program can output fasta and GFF outputs or re...
1,508
448
from tests import test_bike from tests import test_curb
56
17
from pwn import * from pwnlib.elf import * ## Get the offset ## Should be @ ► 0x401260 <vuln+92> ret <0x6161617461616173> ## cyclic -c amd64 -l 0x61616174 ## 72 #payload = cyclic(100) #p = process('./tranquil') #gdb.attach(p, gdbscript=""" #continue #""") #print(p.readline()) #p.sendline(payload) #print(p.readl...
599
288
class Solution: def snakesAndLadders(self, board: List[List[int]]) -> int: n = len(board) q = collections.deque() q.append(1) visited = set() visited.add(1) step = 0 while q: size = len(q) for _ in range(size): num = q.p...
990
303
import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim class Generator: def __init__(self, learning_rate=1e-4, num_blocks=6): self.learning_rate = learning_rate self.num_blocks = num_blocks def pelu(self, x): with tf.variable_scope(x.op.name + '_activation', initializer=tf.c...
5,788
2,435
import nltk from .base import BaseTokenizer from typing import ( Tuple, Iterator, ) __all__ = ['NLTKTokenizer'] class NLTKTokenizer(BaseTokenizer): """NLTK-based Treebank tokenizer. Args: sentencizer (str): Name of sentencizer for text. chunker (str): Phrase chunker where 'noun' us...
10,337
3,303
from vcs import vtk_ui from vcs.colorpicker import ColorPicker from vcs.vtk_ui import behaviors from vcs.VCS_validation_functions import checkMarker import vtk import vcs.vcs2vtk from . import priority import sys class MarkerEditor( behaviors.ClickableMixin, behaviors.DraggableMixin, priority.PriorityEditor):...
10,185
3,155
from functools import wraps from typing import Any, Callable, TypeVar, cast from grpc import Call, RpcError from grpc.aio import AioRpcError from .exceptions import AioRequestError, RequestError from .logging import get_metadata_from_aio_error, get_metadata_from_call, log_error TFunc = TypeVar("TFunc", bound=Callabl...
3,608
974
# code for python reference dipole vector field controller # these functions require stuff #from mathFuns import * from numpy import * from math import * class refVec: # define the constructor def __init__(self, q_0, controller_flag): # Initialize controller state self.phi_prev = None sel...
4,049
1,522
import torch import torch.nn as nn from torchvision import transforms from torch.utils.data import DataLoader, TensorDataset, Dataset from torch.utils.data.sampler import SubsetRandomSampler from torch import optim import pandas as pd import sys sys.path.append('./proto') import trainer_pb2 import trainer_pb2_grpc impo...
7,066
2,435
from django.shortcuts import render from django.http import HttpResponse from django.template.loader import get_template from .models import Poll from time import timezone from datetime import date # Create your views here. def index(request): myTemplate = get_template('./index.html') print(myTemplate) r...
1,475
466
# -*- coding: utf-8 -*- import tensorflow as tf import time import input as ip import lm import config as cf import numpy as np def run_epoch(session, model, eval_op=None, verbose=False): start_time = time.time() costs = 0.0 iters = 0 state = session.run(model.initial_state) fetches = {"cost": mo...
3,644
1,215
# PIC Decompressor # By: Luke Staniscia #import used libraries/packages import math from PIL import Image, ImageOps, ImageEnhance import time def key0(x): return x[0] def key1(x): return (x[0]*maxBits + x[1])*1800 + int(x[2][2:],2) def sph2Cart(cord, precision = 3): az = cord[0] elev = cord[1] r = cord[2] az ...
9,312
3,926
import re def get_nested(dct, *keys): for key in keys: try: dct = dct[key] except (KeyError, TypeError): return None return dct def extract(string, pattern): found = re.search(pattern, string) if found: return found.group(0) else: return ''
320
100
import logging from copy import copy from typing import Callable, Dict, List, Union import numpy as np from scipy.linalg import solve_triangular from ..search_space import RealSpace, SearchSpace from ..utils import dynamic_penalty, get_logger, handle_box_constraint, set_bounds Vector = List[float] Matrix = List[Vect...
16,493
5,319
from . import db class User(db.Model): """ Data Model for User Account""" __tablename__ = 'Users'
114
36
#!/usr/bin/python # Copyright 2021 Northern.tech AS # # 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...
4,526
1,229
from invoke import task @task def no_docstring(): pass @task def one_line(): """foo """ @task def two_lines(): """foo bar """ @task def leading_whitespace(): """ foo """ @task(aliases=('a', 'b')) def with_aliases(): """foo """
276
106
from subprocess import PIPE from subprocess import Popen def run(command): assert (isinstance(command, list)), "Command must be a list" p = Popen(command, stdout=PIPE, stderr=PIPE) s, e = p.communicate() return s.decode('utf-8'), e.decode('utf-8'), p.returncode
280
96
import tensorflow as tf from tensorflow.keras.layers import Layer from debugprint import print_debug from .utils import get_mask_from_lengths class ParrotLoss(): def __init__(self, hparams): super(ParrotLoss, self).__init__() self.hidden_dim = hparams.encoder_embedding_dim self.mel_hidden_...
12,748
4,271
"""Markdown filters This file contains a collection of utility filters for dealing with markdown within Jinja templates. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import print_function import os import subprocess from io import TextIOWra...
2,509
771
import unittest import sys import inspect from unittest import mock import numpy as np import rsopt.libe_tools.simulation_functions.python_simulation_functions as pyfunc import rsopt.optimizer as opt radiamodule = mock.MagicMock() sys.modules["radia"] = radiamodule from rsopt.codes.radia.sim_functions import hybrid_und...
3,006
984
import datetime import json import os import random import re from urllib.parse import quote import lxml import pafy import requests import youtube_dl from bs4 import BeautifulSoup from django.conf import settings from django.core.files.storage import FileSystemStorage from django.http import (Http404, HttpResponse, H...
10,646
3,522
from spotdl import handle from spotdl import const from spotdl import downloader import os import sys const.args = handle.get_arguments(to_group=True) track = downloader.Downloader(raw_song=const.args.song[0]) track_title = track.refine_songname(track.content.title) track_filename = track_title + const.args.output_...
416
133
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
10,180
3,462
"""Tests for the cursor module.""" from __future__ import absolute_import from . import common from bearfield import cursor, Document, Field, Query class TestCursor(common.TestCase): """Test the Cursor class.""" class Document(Document): class Meta: connection = 'test' index = Fie...
2,047
612
from decimal import Decimal from math import e, factorial def combination(num, den): """ Find nCr or (n r), the Binomial Coefficients """ dec1 = dec2 = Decimal(1) if 0 <= den <= num: diff = num - den if num-diff < num-den: temp = diff other = den else...
1,417
518
# -*- coding: utf-8 -*- """Testing conf module.""" # third-party import pytest from falcon import testing from .app import app_hook, app_middleware @pytest.fixture def client_hook() -> testing.TestClient: """Create testing client fixture for hook app""" return testing.TestClient(app_hook) @pytest.fixture d...
471
147
from typing import List, Union import numpy as np from .Figure import Figure def create_position_pdf_plot(*, start_time_sec: np.float32, sampling_frequency: np.float32, pdf: np.ndarray, label: str): # Nt = pdf.shape[0] # Np = pdf.shape[1] A = pdf B = A / np.reshape(np.repeat(np.max(A, axis=1), A.shape...
1,574
559
# Connect files from configs import * # Arrays items = [] selectedItems = [] # Interface arrays buttons = [] surfaces = [] # Getting item def getItemById(ident): for item in items: if item.id == ident: return item # Removing item def removeItem(item): items.remove(item) # Removing items def removeItems(): ...
976
328
import os import markdown2 from forms import AddKeywordForm, SubscribeEmailForm, TimeWindowForm from flask import (flash, render_template, request, escape, redirect, url_for, session, abort) from flask_paginate import Pagination, get_page_parameter from parsing.notifications import send_email_subs_...
6,236
1,925
#!/usr/bin/env python # -*- encoding: utf-8 -*- import math from collections import OrderedDict from typing import Callable, Tuple import torch import torch.nn.functional as F from colossalai.communication import broadcast from colossalai.context import ParallelMode, seed from colossalai.core import global_context as...
46,895
12,663
#! /usr/bin/env python2.3 from wsgi_intercept.mechanoid_intercept import Browser from nose.tools import with_setup import wsgi_intercept from wsgi_intercept import test_wsgi_app ### _saved_debuglevel = None def install(port=80): _saved_debuglevel, wsgi_intercept.debuglevel = wsgi_intercept.debuglevel, 1 wsgi...
1,027
364
import click import pathlib import os from kneejerk.image_server import score_images_in_dir from kneejerk.data.saver import persist_scores, persist_metadata from kneejerk.data.transfer import segment_data_from_csv, transfer_normalized_image_data from kneejerk.data.utils import _get_classes, _get_max_image_dim, _ensure...
3,538
1,184
import sys, os, shutil, binascii, urllib.request, zipfile, ctypes, math, glob # Must be in game root folder. if not os.path.isfile('Ace7Game.exe'): wait = input('Ace7Game.exe not found in this folder. Press any key to close...') sys.exit(0) # Get resolution from OS. u32 = ctypes.windll.user32 u32.SetProcessDP...
7,277
3,126
# Tkinter is Python's de-facto standard GUI (Graphical User Interface) package. import tkinter as tk import keras as kr import numpy as np import matplotlib.pyplot as plt import math import sklearn.preprocessing as pre import gzip import PIL from PIL import Image, ImageDraw import os.path width = 280 height = 280 ce...
5,202
1,880
# python3 sort <http://github.com/Wind2esg/python3sort> # Copyright 2018 Wind2esg # Released under the MIT license <http://github.com/Wind2esg/python3sort/LICENSE> # Build a sorted range from 0 to i - 1, then try to find the position for the i item # Because it is sorted in the range, when finding, compare the i item ...
1,007
339
from django.urls import path from .views import OrganizationView, ServiceView, ServiceListView from registration import views app_name = "organization" urlpatterns = [ path('<org_name>/service/<ticket>/', ServiceView.as_view(), name='service_view_get'), path('<org_name>/service/', ServiceView.as_view(), name...
571
180
# -*- coding: utf-8 -*- """ Summarise Sound Scattering Layers (SSLs) @author: Roland Proud """ ## import packages import matplotlib.pyplot as plt import gzip import pickle import numpy as np from pyechoplot.plotting import plot_pseudo_SSL, save_png_plot, plot_Sv ## import pyechometrics modules from pyechometrics.met...
1,977
788
# ------------------------------------------------------------------------------ # CodeHawk Binary Analyzer # Author: Henny Sipma # ------------------------------------------------------------------------------ # The MIT License (MIT) # # Copyright (c) 2016-2020 Kestrel Technology LLC # Copyright (c) 2020 Henny Si...
10,334
3,127
import abc from Experiment import * class AEC : """ Abstract class defining an interface for performing active electrode compensation. """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def performAEC(self, experiment): """ This method should preprocess al...
534
143
from locust import ( constant, ) from locust.env import Environment, LoadTestShape from locust.user import ( User, task, ) from locust.user.task import TaskSet from .testcases import LocustTestCase from .fake_module1_for_env_test import MyUserWithSameName as MyUserWithSameName1 from .fake_module2_for_env_te...
6,126
1,773
from datasets.s3dis import S3DIS
33
12
import csv from io import BytesIO import pandas as pd from urllib.request import urlopen from zipfile import ZipFile def fetch_geds(url, subset=None): ''' Fetches the geds dataset from Canada's Open Data Portal Args: url: A string containing the url to the Canada Open Data Portal web ...
1,930
553
""" grid.py Module containing class for working with a street grid. """ import json import geojson import geopy.distance import shapely.geometry from geoql import geoql import geoleaflet import folium import rtree import networkx from tqdm import tqdm class Grid(): @staticmethod def prepare(file_segments, fi...
3,210
970
import os from tqdm import tqdm from joblib import Parallel, delayed try: import seaborn as sns except: pass import numpy as np import cv2 from lost_ds.util import get_fs from lost_ds.geometry.lost_geom import LOSTGeometries from lost_ds.functional.api import remove_empty def get_fontscale(fontscale, thic...
6,019
1,898
from collections import deque from PyQt5.QtCore import Qt from PyQt5.QtGui import QColor from PyQt5.QtWidgets import QGraphicsRectItem from cadnano.gui.palette import getNoPen from cadnano.proxies.cnenum import StrandType from .pathextras import PreXoverItem class PreXoverManager(QGraphicsRectItem): """Summary ...
16,638
5,163
import json import pytest import sysfacts @pytest.fixture(scope="module") def collected_data(): return sysfacts.collect_facts() def test_imports(): from sysfacts import collect_facts def test_return_type(collected_data): assert isinstance(collected_data, dict) def test_keys_are_present(collected_d...
782
261
def mergingLetters(s, t): #edge cases mergedStr = "" firstChar = list(s) secondChar = list(t) for i, ele in enumerate(secondChar): if i < len(firstChar): mergedStr = mergedStr + firstChar[i] print('first pointer', firstChar[i], mergedStr) if i < len(second...
521
169
''' decorators - decorators to help with flask applications ''' # standard from datetime import timedelta from functools import update_wrapper # pypi from flask import make_response, request, current_app def crossdomain(origin=None, methods=None, headers=None, max_age=21600, attach_to_all=True, ...
2,696
722
def secondarybase64_layer5(nearing_the_end_script): import base64 print("Secondary base64 encrypting") joe = (nearing_the_end_script) spliting = joe.encode('utf-8') spliting = base64.b64encode(spliting) spliting = spliting.decode('utf-8') split_strings = [] n = int((len(spliting))/20) for index in r...
631
260
from flask_wtf import FlaskForm from wtforms import PasswordField, SubmitField, StringField from wtforms.validators import DataRequired, Length class InstagramLoginForm(FlaskForm): username = StringField('Instagram Username', validators=[DataRequired(), ...
458
117
from flask import json from authlib.flask.oauth2.sqla import create_query_token_func from authlib.oauth2.rfc7662 import IntrospectionEndpoint from .models import db, User, Client, Token from .oauth2_server import TestCase from .oauth2_server import create_authorization_server query_token = create_query_token_func(db....
5,117
1,559
# Copyright 2020 Артём Воронов # # 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...
7,031
1,896
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2018 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Thin wrapper of Mojo's mojom_bindings_generator.py. To generate C++ files from mojom, it is necessary...
1,203
407
# NEEDS FIXING # -*- coding: UTF-8 -*- ####################################################################### # ---------------------------------------------------------------------------- # "THE BEER-WARE LICENSE" (Revision 42): # @tantrumdev wrote this file. As long as you retain this notice you # can do whate...
4,799
1,408
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import * class EmpresaCreateForm(forms.ModelForm): class Meta: model = Empresa fields = [ 'nombre', 'description', 'direccion...
2,362
650
"""test_connections.py""" import unittest import os from py_connect import ConnectionsHandler from py_connect import Board, Peripheral, SensorTypes cons_path = \ "/".join(os.path.abspath(__file__).split("/")[:-2]) + "/test_connections/" class TestConnection(unittest.TestCase): def test_gpio_connection(sel...
5,639
1,824
# This file is part of the P3IV Simulator (https://github.com/fzi-forschungszentrum-informatik/P3IV), # copyright by FZI Forschungszentrum Informatik, licensed under the BSD-3 license (see LICENSE file in main directory) import numpy as np import lanelet2.geometry from lanelet2.core import BasicPoint2d, LaneletSequenc...
4,624
1,381
import aiohttp_cors from aiohttp import web from common.utils.run_cmd import run class Tensorboard(web.View, aiohttp_cors.CorsViewMixin): async def get(self): print("Start") folder = self.request.query.get("folder") cmd_check = 'ps a' o, e = await run(cmd_check) print(cmd...
668
228
import pytest import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize('name', [ ('nodejs'), ]) def test_packages_are_installed(host, name): package = host.package(name)...
716
260
from .ranking import Triplet
28
9
""" created by Juechen Yang at 1/8/19 """ import os import pandas as pd def export_to_bed(gtf,intermediate_file_dir, lincRNA): if lincRNA: lincRNAIDs = pd.read_csv(os.path.join(intermediate_file_dir, 'intersect_total.txt'), names=['ids'], sep='\t') exons = gtf[(gtf.feature == 'exon') & (gtf.seqnam...
1,216
456
import glob import numpy as np import os import pandas as pd import yaml from dask_image.imread import imread from dlclabel import misc from itertools import groupby from napari.layers import Shapes from napari.plugins._builtins import napari_write_shapes from napari.types import LayerData from skimage.io import imsave...
8,767
2,817
""" 题目: 给定一个 32 位有符号整数,将整数中的数字进行反转。 示例 1: 输入: 123 输出: 321 示例 2: 输入: -123 输出: -321 示例 3: 输入: 120 输出: 21 注意: 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2**31, 2**31 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。 """ class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ if ...
537
337
from .. import dataclass # trigger the register in the dataclass package
74
17
"""Implementation of a branch on a repository.""" import typing as t from . import commit from .. import decorators from .. import models if t.TYPE_CHECKING: from .. import apps as tapps from .. import users as tusers from . import orgs class _Branch(models.GitHubCore): """A representation of a bran...
46,393
12,466
# -*- coding: utf-8 -*- import os.path from qgis.PyQt import uic from qgis.PyQt.QtWidgets import QFrame from buildings.utilities.layers import LayerRegistry # Get the path for the parent directory of this file. __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) FORM_CLASS, _ = ui...
696
241
import os import sys import re import emoji import string import time import winsound from bs4 import BeautifulSoup from rich.progress import track def clear(): os.system('cls' if os.name=='nt' else'clear') def BeautifulSoupOp(text): soup = BeautifulSoup(text.strip(),"html.parser") for tag in soup.find_all('a'):...
1,426
638
#!/usr/bin/env python2 # coding=utf-8 """ The default per-repository configuration """ import sys import json import string from os.path import exists, dirname from gitver.defines import CFGFILE from termcolors import term, bold default_config_text = """{ # automatically generated configuration file # # ...
3,749
1,097
# MIT License # # Copyright (c) [2020] [Angelo Ferrando] # # 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,...
3,153
1,036
from random import randint import re; import json class Passenger: def __init__(self, passengerId, passengerName, email, password, address, contact): self.passengerId = passengerId self.passengerName = passengerName self.email = email self.password = password self.address = ...
3,305
955
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import random from common import spi def main(): multiplexer_state = spi.parse_response(spi.query('multiplexer', 'get_outputs')) print("Current multiplexer state:") _print_state(multiplexer_state) print('') for i in range(len(multiplexer_state)): multipl...
1,379
529
# -*- coding: utf-8 -*- import pyjf print repr(u'使'.encode('euc-jp')) print repr(pyjf.sjistoeuc(u'使'.encode('sjis')))
118
59
import torch from torch.distributions import Uniform from rl_sandbox.constants import CPU class UniformPrior: def __init__(self, low, high, device=torch.device(CPU)): self.device = device self.dist = Uniform(low=low, high=high) def sample(self, num_samples): return self.dist.rsample...
437
144
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Rico Sennrich # Distributed under MIT license # take conll file, and bpe-segmented text, and produce factored output import sys import re from collections import namedtuple Word = namedtuple( 'Word', ['pos', 'word', 'lemma', 'tag', 'morph', 'head', 'f...
2,759
862
#!/usr/bin/python # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import pytest import os import json from mock import MagicMock, patch, mock_open from shared_code import utils def test_is_url_returns_true_when_url_passed_in(): #arrange input = "https://fake-url...
4,661
1,650