text string | size int64 | token_count int64 |
|---|---|---|
# import Drop7.Board as Board
import Drop7.Disk as Disk
def test_Is_Proper_Disk__Legal_Case(score, max_score):
"""Function is_proper_disk: given disk is proper disk."""
max_score.value += 1
try:
assert Disk.is_proper_disk(4, Disk.init_disk(Disk.VISIBLE, 4))
assert Disk.is_proper_disk(4, Dis... | 3,142 | 1,145 |
#!/usr/bin/python3
# Filename: maxSonarTTY.py
# Reads serial data from Maxbotix ultrasonic rangefinders
# Gracefully handles most common serial data glitches
# Use as an importable module with "import MaxSonarTTY"
# Returns an integer value representing distance to target in millimeters
from time import time
from ser... | 1,821 | 486 |
def estimator(data):
currentlyInfected = covid19ImpactEstimator(data['reportedCases'])
severeCurrentlyInfected = covid19ImpactEstimator(data['reportedCases'],
severe=True)
infectionsByRequestedTime = getInfectionsByRequestedTime(currentlyInfected,
... | 4,697 | 1,288 |
import sys
import os
import io
import gzip
import mock
import tempfile
import lumbermill.utils.DictUtils as DictUtils
from tests.ModuleBaseTestCase import ModuleBaseTestCase
from lumbermill.output import File
class TestFile(ModuleBaseTestCase):
def setUp(self):
super(TestFile, self).setUp(File.File(mock... | 2,577 | 779 |
#!/usr/bin/env python3
import argparse
import pickle
import time
import sys
from safe_gpu.safe_gpu import GPUOwner
from pero_ocr.decoding import confusion_networks
from pero_ocr.decoding.decoding_itf import prepare_dense_logits, construct_lm, get_ocr_charset, BLANK_SYMBOL
import pero_ocr.decoding.decoders as decoder... | 4,517 | 1,551 |
""" An in-memory content store with exact matching"""
import time
from PiCN.Packets import Content, Name
from PiCN.Layers.ICNLayer.ContentStore import BaseContentStore, ContentStoreEntry
class ContentStoreMemoryExact(BaseContentStore):
""" A in memory Content Store using exact matching"""
def __init__(self... | 1,608 | 448 |
from django_slack_oauth.models import SlackOAuthRequest
def register_token(request, api_data):
SlackOAuthRequest.objects.create(
associated_user=request.user,
access_token=api_data.pop('access_token'),
extras=api_data
)
return request, api_data | 279 | 89 |
from django.forms import ModelForm
# class add_money_form(ModelForm):
# class Meta:
# model = Transaction
# fields = ['transaction_user_2', 'transaction_amount']
| 185 | 55 |
"""
1429. First Unique Number
# https://leetcode.ca/all/1429.html
You have a queue of integers, you need to retrieve the first unique integer in the queue.
Implement the FirstUnique class:
FirstUnique(int[] nums) Initializes the object with the numbers in the queue.
int showFirstUnique() returns the value of the f... | 7,187 | 2,633 |
import os
from get_git.utils import make_request
GH_URL = 'https://api.github.com/graphql'
TOKEN=os.environ.get('GH_API_TOKEN')
class GithubClient:
def __init__(self, username):
self.username = username
def get_user(self):
query = """
{user(login:"%s") {
starredRepos... | 4,326 | 1,144 |
from __future__ import division, print_function, unicode_literals
from config import *
__all__ = ['Map', 'Vertex', 'Edge', 'State']
class State:
FREE = 0
CLOSED = 1
MANDATORY = 2
OPTIONAL = 3
class Square:
def __init__(self):
self._has_card = False
@property
... | 15,517 | 5,302 |
import numpy as np
import scipy.stats
def EI(predictor, training, test, fmax=None):
fmean = predictor.get_post_fmean(training, test)
fcov = predictor.get_post_fcov(training, test)
fstd = np.sqrt(fcov)
if fmax is None:
fmax = np.max(predictor.get_post_fmean(training, training))
temp1 = (f... | 1,035 | 386 |
import pandas as pd
import numpy as np
LOCAL_DIR = '/tmp/'
def main(**kwargs):
# Retrieve acampus from Xcom
ti = kwargs["ti"]
source = ti.xcom_pull(
task_ids="report_init_task")
campus_name = source["campus"]
# Read data file to create a data frame
df = pd.read_csv(LOCAL_DIR + camp... | 1,528 | 512 |
"""
Holds an OrgChecker object that runs checks at the organization level (instead of at the item level)
"""
class OrgChecker:
"""
An OrgChecker runs checks at the org level, as opposed to the item level. For example, checking whether there are
any items with the same title.
To use, instantiate and t... | 1,401 | 401 |
#!/usr/bin/python3
from datetime import datetime
import sys
def create_blog_post(title=""):
file_date = datetime.now().strftime("%Y-%m-%d")
file_name = file_date + "---" + title.replace(" ", "-") + ".md"
print(file_name)
try:
file = open("content/posts/" + file_name, "x")
except FileExists... | 994 | 344 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2017 The Procyon 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
#
# Un... | 1,436 | 443 |
from allennlp.common import Registrable
import torch
class Criterion(torch.nn.Module, Registrable):
"""
A `Criterion` is a `Module` that ...
"""
def __init__(self,
reduction: str = 'mean',
verbose: bool = False,) -> None:
super().__init__()
self.redu... | 693 | 210 |
# Form implementation generated from reading ui file 'generator.ui'
#
# Created by: PyQt6 UI code generator 6.2.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic6 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt6 import QtCore, QtGui, QtWidgets
class Ui_... | 2,180 | 699 |
# Sportradar APIs
# Copyright 2018 John W. Miller
# See LICENSE for details.
from sportradar.api import API
class NFL(API):
def __init__(self, api_key, format_='json', access_level='ot',
version=2, timeout=5, sleep_time=1.5):
super().__init__(api_key, format_, timeout, sleep_time)
... | 5,247 | 1,686 |
import torch
import os
from torch import Tensor
import torch.nn as nn
from fairseq import options, utils, checkpoint_utils
from fairseq.dataclass import ChoiceEnum, FairseqDataclass
from fairseq.models import (
transformer,
FairseqLanguageModel,
register_model,
register_model_architecture,
FairseqEn... | 4,767 | 1,481 |
from .ensembl import Ensembl
from .util import is_ensembl_id
##########
## Exon ##
##########
def get_exons(feature, feature_type):
exons = []
for exon_id in get_exon_ids(feature, feature_type):
exons.append(_query(exon_id, "exon", Ensembl().data.exon_by_id))
return exons
def get_exon_ids(featur... | 6,345 | 2,153 |
from MiGRIDS.InputHandler.readCsv import readCsv
def readAllTimeSeries(inputDict):
'''
Cycles through a list of files in the AVEC format and imports them into a single dataframe.
:param inputDict:
:return: pandas.DataFrame with data from all input files.
'''
df = None
for i in range(len(inp... | 1,113 | 315 |
import algosdk as ag
import pyteal as tl
import pytest
from algosdk.future.transaction import OnComplete
from algosdk.v2client.algod import AlgodClient
from algosdk.v2client.models.application_local_state import ApplicationLocalState
from algosdk.v2client.models.application_state_schema import ApplicationStateSchema
f... | 12,725 | 4,542 |
# Copyright (c) 2021 Kemal Kurniawan
from typing import Optional
import math
from einops import rearrange
from torch import BoolTensor, Tensor
from crf import DepTreeCRF, LinearCRF
def compute_aatrn_loss(
scores: Tensor,
aa_mask: BoolTensor,
mask: Optional[BoolTensor] = None,
projective: bool = Fal... | 6,191 | 2,276 |
from __future__ import unicode_literals
from django.db import models
from django.contrib.postgres.fields.jsonb import JSONField
from django.core.exceptions import ValidationError
import datapackage
import jsontableschema
from ledger.accounts.models import RevisionedMixin, EmailUser
from wildlifelicensing.apps.main.m... | 5,151 | 1,518 |
import os
import json
import logging
cwd = os.getcwd()
list_enemy = [file for file in os.listdir(cwd) if '.json' in file[-5:]]
for enemy in list_enemy:
try:
with open(cwd + '\\' + enemy, 'r') as f:
enemy_txt = f.read()
enemy_txt = enemy_txt.replace('offsetx','offsetX').... | 605 | 205 |
from tvm import testing
from tvm from tvm import topi
import tvm
import numpy as np
import torch
dim0 = 3
dim1 = 4
dim2 = 1
shape_size1 = [dim0, dim1, dim2]
shape_size2 = [dim0, dim1, dim2 * 8]
dtype = "float32"
cap0 = tvm.te.placeholder(shape_size1, dtype=dtype, name="cap0")
cap1 = tvm.te.placeholder(shape_size1, ... | 5,485 | 2,592 |
from controle_de_estoque.controllers import controllers
if __name__ == "__main__":
controllers.principal_controle()
| 121 | 37 |
from .connector import websocket_connector, http_connector
class DevtoolsProtocol(object):
def __init__(self):
self._http = http_connector.HttpConnector()
self.tab_socket = None
self.tab_target_id = None
@property
def browser_data(self):
return self._http.browser_data
... | 2,334 | 684 |
#
# PySNMP MIB module CISCO-IETF-PW-FR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-IETF-PW-FR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:43:46 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | 9,523 | 4,567 |
import sys
from os import path
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtGui as qtg
from PyQt5 import QtCore as qtc
class MainWindow(qtw.QMainWindow):
def __init__(self):
"""MainWindow constructor.
This widget will be our main window.
We'll define all the UI components in h... | 1,639 | 484 |
import tools
import frameworks
| 31 | 7 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Загружаем комплекты снаряжения (soldiers_pack)
from data.items import *
#----
# Лишённые индивидуальности заготовки солдат. Используются в squad_generation
metadict_chars = {}
#----
# Сельское ополчение (крестьяне и городская беднота):
metadict_chars['Commoner 1 lvl ... | 442,707 | 175,265 |
import numpy as np
import scipy as sp
import scipy.stats
import matplotlib.pyplot as plt
class GaussianMixture1D:
def __init__(self, mixture_probs, means, stds):
self.num_mixtures = len(mixture_probs)
self.mixture_probs = mixture_probs
self.means = means
self.stds = stds
def s... | 5,647 | 2,258 |
#
# PySNMP MIB module CIRCUIT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CIRCUIT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:49:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... | 37,416 | 13,165 |
# -*- coding:utf-8 -*-
# author: hpf
# create time: 2020/7/16 21:33
# file: shell_sort.py
# IDE: PyCharm
# 希尔排序(Shell Sort)是插入排序的一种。也称缩小增量排序,是直接插入排序算法的一种更高效的改进版本。
# 希尔排序是非稳定排序算法。该方法因DL.Shell于1959年提出而得名。 希尔排序是把记录按下标的一定增量分组,
# 对每组使用直接插入排序算法排序;随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止。
def shell_sort(alist):
n... | 904 | 633 |
import unittest
import srl
from srl.test import TestRL
class Test(unittest.TestCase):
def setUp(self) -> None:
self.tester = TestRL()
self.rl_config = srl.rl.rainbow.Config()
def test_sequence(self):
self.tester.play_sequence(self.rl_config)
def test_mp(self):
self.teste... | 4,273 | 1,636 |
def find_majority(a):
d = {}
l = len(a)
for i in a:
if i in d:
d[i] += 1
if d[i] > l / 2:
return i
else:
d[i] = 1
return
if __name__ == "__main__":
a = [2,2,3,7,5,7,7,7,4,7,2,7,4,5,6,7,7,8,6,7,7,8,10,12,29,30,19,10,7,7,7,7,7,7,7,... | 353 | 189 |
# Completely silly exercises, in real life use:
# Python lists: https://docs.python.org/3/tutorial/datastructures.html
import unittest
import logging
logging.basicConfig(level=logging.INFO)
# - DoublyLinkedListNode class.
class DoublyLinkedListNode:
value = None
previousNode = None
nextNode = None
... | 7,307 | 2,230 |
import socket
import threading
bind_ip = "0.0.0.0"
bind_port = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)
print "[*] Listening on %s:%d" % (bind_ip, bind_port)
# This is our client-handling thread
def handle_client(client_socket):
#... | 888 | 295 |
import setuptools
import site
import sys
# This is a workaround to allow --user and -e combined
# See https://github.com/pypa/pip/issues/7953
site.ENABLE_USER_SITE = "--user" in sys.argv[1:]
setuptools.setup()
| 210 | 76 |
#Guess program
n=18
a=0
y = 1
print("Number of guesses is limited to only 4 times")
while a<=3:
z=int(input("Enter your choice="))
if z>n:
print("Please less your number")
a+=1
elif z<n:
print("Please increase your number")
a += 1
else:
print("You win")
... | 466 | 165 |
"""
.. module:: soundsystem
:Platform: Unix, Windows
:Synopsis: Sound system
"""
import os
import pygame
import events
import ai
class SoundSystem(object):
"""Render system.
:Attributes:
- *evManager*: event manager
- *world*: game world
- *screen*: game screen
"""
... | 8,019 | 2,404 |
# -*- coding=utf-8 -*-
import django
import os
import sys
import datetime
import random
import time
os.environ['DJANGO_SETTINGS_MODULE'] = 'web.settings'
django.setup()
from web.other.models import BilibiliPlay
from .helper import bulk_create
def test_once_get():
start = time.time()
for i in range(0, 1000... | 2,227 | 778 |
# -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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... | 37,304 | 17,262 |
import json
from django.urls import reverse
from misago.acl.testutils import override_acl
from misago.categories.models import Category
from misago.threads import testutils
from misago.users.testutils import AuthenticatedUserTestCase
class ThreadPollApiTestCase(AuthenticatedUserTestCase):
def setUp(self):
... | 1,921 | 625 |
#!usr/bin/python
import __main__
| 33 | 14 |
#Helper method that implements the logic to look up an application.
def get_app(self, reference_app=None):
if reference_app is not None:
return reference_app
if self.app is not None:
return self.app
if current_app:
return current_app._get_current_object()
... | 457 | 125 |
import os
import re
import time
import demisto_client
from demisto_client.demisto_api.rest import ApiException
from demisto_sdk.commands.common.tools import LOG_COLORS, get_yaml, print_color
from demisto_sdk.commands.upload.uploader import Uploader
SUCCESS_RETURN_CODE = 0
ERROR_RETURN_CODE = 1
ENTRY_TYPE_ERROR = 4
... | 9,717 | 2,940 |
# Generated by Django 3.1.1 on 2020-10-24 14:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('records', '0016_auto_20201012_0943'),
]
operations = [
migrations.AddField(
model_name='purchaserecord',
name='imple... | 871 | 285 |
from datetime import datetime, timezone
from flycs_sdk.entities import Entity
from flycs_sdk.pipelines import Pipeline, PipelineKind
from flycs_sdk.transformations import Transformation
# Define your transformation SQL query using jinja template for the table name and define the list of table on which this transforma... | 1,030 | 336 |
import torch.nn.functional as F
import torch.nn as nn
import torch
import torchvision.transforms.functional as VF
from PIL import Image
import numpy as np
import os
from os.path import join
from collections import Counter
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
import math
from ct... | 13,252 | 5,521 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-01-09 09:43
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ciudadano', '0001_initial'),
]
operations = [
migrations.AddField(
... | 496 | 172 |
import pytry
import os
import random
import nengo
import nengo_extras
import numpy as np
import nengo_dl
import tensorflow as tf
import davis_tracking
class TrackingTrial(pytry.PlotTrial):
def params(self):
self.param('number of data sets to use', n_data=-1)
self.param('data directory', dataset_d... | 8,306 | 2,664 |
"""
...
"""
# Django
from django.conf import settings
# local Django
from apps.collection.models import Collection
from apps.collection.serializers import CollectionSlugSerializer
from apps.tests.fixtures import RepositoryTestCase
PAGE_SIZE = settings.REST_FRAMEWORK["PAGE_SIZE"]
class CollectionPublicListTest(Rep... | 1,337 | 395 |
import argparse
import logging
import os
from src.train import setup_top20, setup_ft, setup_bottom
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('fashion')
def main(data_path, ckpt_path, mt, train_bottom=False):
# Train on top-20 classes (train subsplit)
logger.info("Training on top-20 cl... | 2,033 | 732 |
#!/usr/bin/env python2.7
"""
Toil script to move TCGA data into an S3 bucket.
Dependencies
Curl: apt-get install curl
Docker: wget -qO- https://get.docker.com/ | sh
Toil: pip install toil
S3AM: pip install --pre s3am
"""
import argparse
import glob
import hashlib
import os
import shutil
import su... | 8,508 | 2,768 |
import time
import pytest
from elasticapm.utils import compat
cpu_psutil = pytest.importorskip("elasticapm.metrics.sets.cpu_psutil")
pytestmark = pytest.mark.psutil
def test_cpu_mem_from_psutil():
metricset = cpu_psutil.CPUMetricSet()
# do something that generates some CPU load
for i in compat.irange(1... | 1,885 | 627 |
"""
Day 11 - Seating
"""
from itertools import chain
import collections
def occupied_count(seating):
return ''.join(chain.from_iterable(seating)).count('#')
def adjacent_occupied(x, y, seating):
occupied = 0
# Above
for look_x in range(x - 1, x + 2):
for look_y in range(y - 1, y + 2):
... | 3,785 | 1,344 |
from scrapy.pipelines.files import FilesPipeline
class FirmwarePipeline(FilesPipeline):
def file_path(self, request, response=None, info=None):
return request.url.split('/')[-1]
class HpPipeline(FirmwarePipeline):
pass
class LinksysPipeline(FirmwarePipeline):
pass
class AvmPipeline(FirmwareP... | 388 | 132 |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | 2,843 | 1,197 |
# coding: utf-8
import flask
from google.appengine.ext import ndb
import auth
import config
import model
from main import app
###############################################################################
# Welcome
###############################################################################
@app.route('/')
def... | 3,343 | 1,067 |
from transformers import AlbertModel
from transformers import AlbertPreTrainedModel
import torch.nn as nn
import torch
import torch.nn.functional as F
class MUSTTransformerModel(AlbertPreTrainedModel):
def __init__(self, config, max_num_spans, max_seq_len):
super(MUSTTransformerModel, self).__init__(config)
... | 2,029 | 694 |
# STRINGS
# https://docs.python.org/3/tutorial/introduction.html#strings
s = str(42)
s # convert another data type into a string (casting)
s = 'I like you'
# examine a string
s[0] # returns 'I'
len(s) # returns 10
# string slicing like lists
s[0:7] # returns 'I like '
s[6:] # returns 'you'
s[-1] # returns... | 1,160 | 452 |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import errno
import six
import socket
import ssl
from abc import ABCMeta, abstractmethod
import logging
from threading import RLock
from ssl import SSLError
import datetime
import time
from . import compat
from .proto import Frame
f... | 11,809 | 3,338 |
import random
import time
#list of words
words = ("python", "india", "japan", "mother", "computer", "watch", "keyboard", "compass",
"bottle", "monitor", "switch", "shoes", "chain", "mobile", "coffee", "alfredo", "mouse",
"stomach", "tablet", "mojito", "halapeneos", "pizza", "nutella", "peanut", "broccoli")
n = 0
#d... | 2,795 | 973 |
# Bep Marketplace ELE
# Copyright (c) 2016-2021 Kolibri Solutions
# License: See LICENSE file or https://github.com/KolibriSolutions/BepMarketplace/blob/master/LICENSE
#
from django.urls import path
from . import views
app_name = 'tracking'
urlpatterns = [
path('user/login/', views.list_user_login, name='listu... | 639 | 218 |
from django.conf import settings
default_settings = {
'has_module_permission_false': False,
}
ADMIN_LOG_ENTRIES_SETTINGS = {}
def compute_settings():
for name, value in default_settings.items():
ADMIN_LOG_ENTRIES_SETTINGS[name] = value
if hasattr(settings, 'ADMIN_LOG_ENTRIES'):
ADMIN_LO... | 394 | 142 |
def reverse(n):
exp = 1
while n / 10 ** exp:
exp += 1
return sum((n % 10 ** a / 10 ** (a - 1)) * (10 ** b)
for a, b in zip(xrange(1, exp + 1), xrange(exp - 1, -1, -1)))
| 205 | 94 |
from lwrl.optimizers import MetaOptimizer
class MultistepOptimizer(MetaOptimizer):
def __init__(self, parameters, optimizer, num_steps=10):
self.num_steps = num_steps
super().__init__(parameters, optimizer)
def step(self, fn_loss, arguments, fn_reference, **kwargs):
arguments['referen... | 464 | 143 |
from saef.connections import ConnectionFormHelper
from ..models import Connection
from ..forms import ConnectionTypeForm
from saefportal.settings import MSG_SUCCESS_CONNECTION_UPDATE, MSG_SUCCESS_CONNECTION_VALID, \
MSG_ERROR_CONNECTION_INVALID, MSG_SUCCESS_CONNECTION_SAVED, MSG_ERROR_CONNECTION_SELECT_INVALID, \
... | 5,301 | 1,507 |
import os
import pydicom
import glob
import numpy as np
import nibabel as nib
from skimage import filters, morphology
from scipy.ndimage.morphology import binary_fill_holes
from scipy.ndimage import label
from dipy.segment.mask import median_otsu
def padvolume(volume):
"Applies a padding/cropping to a volume in or... | 6,206 | 2,673 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from aip import AipFace
from picamera import PiCamera
import urllib.request
import RPi.GPIO as GPIO
import base64
import time
import Main
#百度智能云人脸识别id、key
APP_ID = '*****'
API_KEY = '**********'
SECRET_KEY ='**********'
client = AipFace(APP_ID, API_KEY, SECRE... | 1,937 | 960 |
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
print(L[0:3]);
# L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3。即索引0,1,2,正好是3个元素。
# 如果第一个索引是0,还可以省略:
print(L[:3]);
# 类似的,既然Python支持L[-1]取倒数第一个元素,那么它同样支持倒数切片,试试:
print(L[-2:])
L = list(range(100))
# 前10个数,每两个取一个:
print(L[:10:2])
# 甚至什么都不写,只写[:]就可以原样复制一个list:
# ,tuple也可以用切片操作,只是操作的结果仍是t... | 2,939 | 1,809 |
#!/usr/local/bin/python2
import argparse
import requests
import feedparser
import time
import sys
import sqlite3
import datetime
# Command line args
parser = argparse.ArgumentParser(description='Provide HipChat integration url to post xkcd comics')
parser.add_argument('url', type=str, help='(string) a special url for ... | 4,986 | 1,602 |
# Leia 2 valores numéricos e um símbolo correspondente a uma das operações.
# soma (+), subtração(-), divisão(/) e multiplicação(*)
n1, n2, op = input().split()
n1 = int(n1)
n2 = int(n2)
if op == "+":
print(n1 + n2)
elif op == "-":
print(n1 - n2)
elif op == "/":
print(n1 / n2)
elif op == "*":... | 401 | 171 |
from ciphers.cipher_helper import get_character_map, flip_dict
class CaeserCipher:
def __init__(self, rotation: int = None):
self.default_character_map = get_character_map()
self.flipped_default_character_map = flip_dict(
self.default_character_map
)
if rotation:
... | 2,000 | 548 |
# Generated by Django 2.2.6 on 2019-10-14 13:19
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('instagram', '0019_profile_follow'),
]
operations = [
migrations.RemoveField(
model_name='profile',
name='follow',
),... | 327 | 112 |
# coding: utf-8
import re
from datetime import date
import boundaries
# Noting that the "union" merge strategy fails with:
#
# GEOS_ERROR: TopologyException: found non-noded intersection between
# LINESTRING (...) and LINESTRING (...)
#
# django.contrib.gis.geos.error.GEOSException: Could not initialize G... | 24,054 | 10,450 |
import difflib
import io
import click
from pdbfairy import utils
from pdbfairy.commands import find_interactions
@click.argument('pdb_file_1')
@click.argument('pdb_file_2')
@click.option('--max-distance', default=find_interactions.MAX_DISTANCE, help=(
"The distance in Angstroms under which atoms should "
"b... | 1,803 | 608 |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0022_add_meeting_info_on_office_hour_model'),
]
operations = [
migrations.AlterField(
model_name='mentorprogramofficehour... | 444 | 138 |
# 018 - Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo.
'''
from math import sin, cos, tan
ang = float(input('Digite um ângulo: '))
sen = sin(ang)
cos = cos(ang)
tan = tan(ang)
print('Ângulo de {}°: \n Seno = {:.2f} \n Cosseno = {:.2f} \n Tangente = {:.... | 1,085 | 445 |
import torch
from torch import nn
import torchvision
import torch.nn.functional as F
import time
import os
class BasicModule(torch.nn.Module):
"""
封装了nn.Module,主要是提供了save和load两个方法
"""
def __init__(self):
super(BasicModule, self).__init__()
self.model_name = str(type(self))
def load(... | 1,174 | 432 |
import math
result = [1] * 4355
list = []
flag = ''
def issub(strrr):
global list
cnt = 0
for dna in list:
if strrr in dna:
cnt = cnt + 1
return cnt
def tryy(strrr):
num = issub(strrr)
if num > 1:
for tmp in range(num):
result[tmp] = max(result[tmp], ... | 654 | 273 |
import random
from pyautonifty.constants import DRAWING_SIZE, YELLOW, BLACK, MAGENTA, BLUE
from pyautonifty.pos import Pos
from pyautonifty.drawing import Drawing
from pyautonifty.renderer import Renderer
def smiley_face(drawing):
# Set a background colour to be used for the drawing
background_colour = MAGEN... | 3,119 | 1,115 |
import json
import yaml
from jsonschema import validate
from cumulusci.utils.yaml import cumulusci_yml
class TestSchema:
def test_schema_validates(self, cumulusci_test_repo_root):
schemapath = (
cumulusci_test_repo_root / "cumulusci/schema/cumulusci.jsonschema.json"
)
with op... | 1,074 | 356 |
# -*- coding: utf-8 -*-
# Copyright (c) 2019-2020 Christiaan Frans Rademan <chris@fwiw.co.za>.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the ... | 7,650 | 2,121 |
#! /usr/bin/env python3
"A script to perform the linear regression and create the plot."
# Python program to
# demonstrate merging of
# two files
# Creating a list of filenames
filenames = ['A.591-search-immune-dmel-FlyBase_IDs.txt', 'B.432_search-defense-dmel-FlyBase_IDs.txt']
# Open file3 in write mode
with open(... | 739 | 249 |
all=['load']
| 13 | 7 |
# encoding: utf-8
import os
import pydoc
import inspect
import PySide
import vs
import sfm
import sfmApp
class SFMElement(object):
def __init__(self, element):
self._original = element
@property
def name(self):
return self._original.GetName()
@property
def attributes(self):
... | 10,996 | 3,216 |
# Generated by Django 2.2 on 2021-09-14 07:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('waterApp', '0013_gwlocationsdata_location'),
]
operations = [
migrations.CreateModel(
name='GwMonitoringKobo',
fields=... | 1,778 | 547 |
# graphs.py
# TODO: Import zeta function here or assume that the calling/loading program puts it into our global scope for us?
def func1(z):
# This, of course, is just the identity function.
return z
def func2(z):
return (1.0 - z)*(1.0 + z) | 255 | 83 |
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
from lightgbm import LGBMRegressor
def cv_index_list_to_df(d):
out_dict = {}
for group, index_list in d.items():
for index in index_list:
out_dict[index] = group
df = pd.DataFrame.from_dict(out_d... | 2,891 | 1,086 |
"""257. Binary Tree Paths"""
# 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
class Solution(object):
def binaryTreePaths(self, root):
"""
:type roo... | 2,301 | 703 |
"""A tasks package, used to support different tasks that the bot can execute.
Essentialy, one can define any kind of operation that the bot can perform over a type
of input data (audio, text, video and voice).
""" | 213 | 54 |
# -*- coding: utf-8 -*-
"""
@Datetime: 2018/10/23
@Author: Zhang Yafei
"""
from django.forms import ModelForm, forms
from crm import models
class EnrollmentForm(ModelForm):
def __new__(cls, *args, **kwargs):
# print('__new__',cls,args,kwargs)
for field_name in cls.base_fields:
file_ob... | 2,179 | 682 |
import uuid
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.db.models import Q
from BiSheServer import settings
from api.model_json import queryset_to_json
from user.models import UsersPerfer, UsersDetail, UserTag
# 用户api
class User:
def __init__(... | 3,911 | 1,432 |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
lib.py
"""
from string import printable as printable_chrs
from collections import namedtuple
from requests import get as re_get
from datetime import datetime
# Define constants
API_URL = "http://dailydota2.com/match-api"
Match = namedtuple("Match", ["timediff", "seri... | 1,777 | 574 |
import sys
if len(sys.argv) <= 1:
print("python vv_hash.py property_name")
exit(0)
propertyName = sys.argv[1]
if len(propertyName) == 0:
print("empty element name")
exit(0)
hashCode = 0
for i in range(0, len(propertyName)):
hashCode = (31 * hashCode + ord(propertyName[i])) & 0xFFFFFFFF
if has... | 417 | 166 |
"""Test COUNTER JR1 journal report (TSV)"""
def test_html(tsv_jr1):
assert [pub.html_total for pub in tsv_jr1.pubs] == [0, 15, 33, 0]
def test_pdf(tsv_jr1):
assert [pub.pdf_total for pub in tsv_jr1.pubs] == [32, 12, 855, 40]
| 237 | 124 |