index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
990,400 | ec725d8279ef89a0784234c7cbc2c8809b31493c | def num_ways(n, dp):
if n == 0:
return 0
if n == 1:
return 1
if n == 2:
return 2
if dp[n] == -1:
take_one_step = num_ways(n - 1, dp)
take_2steps = num_ways(n - 2, dp)
dp[n] = take_one_step + take_2steps
return dp[n]
|
990,401 | 983cf227b5f12c06a27b08905f31cb05498916ae | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# numpy.random随机数
# print np.random.random(3)
# print np.random.rand(3,4)
# print np.random.randn(3,4)
# 创建
s = pd.Series([1,2,6,np.nan,44,4])
dates = pd.date_range('20170406',periods = 6)
df = pd.Data... |
990,402 | f490716f71987696c511c768ee980082d9bc1501 | from itsdangerous import URLSafeTimedSerializer as usts
import base64
# generate verify key
class Token():
def __init__(self, security_key):
self.security_key = security_key
self.salt = base64.encodestring(security_key)
def generate_validate_token(self, username):
serializer = usts(se... |
990,403 | ca999f9ee62bf239db435101b3ef38c7a1db7fd9 | from typing import Tuple
import torch
import torch.nn
import torch.nn.functional as F
from torch import Tensor
def square(x: torch.Tensor) -> torch.Tensor:
return torch.pow(x, torch.tensor([2.0], device=x.device))
class LPBatchNorm1d(torch.nn.BatchNorm1d):
"""
"""
def __init__(self,
... |
990,404 | d9d963f52694b36d03074d36af899c0dec09bf8c | club_info = {'club_url': 'https://www.futbin.com///18/leagues/EFL%20League%20Two?page=1&club=346', 'club_logo': 'https://cdn.futbin.com/content/fifa18/img/clubs/346.png', 'club_name': 'Yeovil Town'}
players = {}
players['Bailey'] = {'player_url': 'https://www.futbin.com//18/player/8047/James Bailey', 'player_name': 'Ja... |
990,405 | 23e788a1aa2bac5f57ddf521ea207aebbb35d524 | #!/usr/bin/env python3
#
# This file is open source software, licensed to you under the terms
# of the Apache License, Version 2.0 (the "License"). See the NOTICE file
# distributed with this work for additional information regarding copyright
# ownership. You may not use this file except in compliance with the Licen... |
990,406 | 40e4e112c31e2fc69bdde9e0fbb3ce2daeb6778e |
howmany = 0
for num in range(264793, 803935 + 1):
n = str(num)
if any([n[0]==n[1] and n[1]!=n[2], n[1]==n[2] and n[2]!=n[3] and n[0]!=n[1], n[2]==n[3] and n[3]!=n[4] and n[1]!=n[2], n[3]==n[4] and n[4]!=n[5] and n[2]!=n[3], n[4]==n[5] and n[3]!=n[4]]):
if n[0]<=n[1] and n[1]<=n[2] and n[2]<=n[3] and n[... |
990,407 | 3cfc3df40cdb0322728fcbaf7db450eba4fadf80 | import json
import requests
from urllib.request import urlopen
from Forecast.Forecast import Forecast
from Actual.Actual import Actual
class Buienradar:
def __init__(self):
self.get_json_data()
def get_json_data(self):
url = 'https://api.buienradar.nl/data/public/2.0/jsonfeed'
... |
990,408 | 95b44ba00152ae08bdfae7abf18d92885f8489bf | ############################################################################################################
# TV Data source: nl_TVGids
# Notes:
# Provides Dutch tv data.
# Changelog:
# 15-11-06 Fix: get description regex
# 07-03-08 Updated & Fix for myTV v1.18
##################################################... |
990,409 | 02da39613270126c756cbe636b222bbba56efe0c | # -*- coding: utf-8 -*-
import requests
import json
userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"
header = {
'Accept': 'application/json, text/plain, */*',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0... |
990,410 | 68f42e9a437f8e6b21a93143dca6191b7f13fb0c | import subprocess
import time
import os
import pandas as pd
import numpy as np
import datetime
import pyautogui
pyautogui.PAUSE = 0.3
pyautogui.FAILSAFE = True
import configparser
config = configparser.ConfigParser()
config.read('config.cfg')
import argparse
def main():
subprocess.Popen("C:\Program Files\Forti... |
990,411 | 4c645efc5f72ba643ee4b32f21160adb312607cf | from collections import defaultdict
import torch
import numpy as np
from utils.utils import time_it
from algorithms.agents.base_agent import AgentTrain
class PPO(AgentTrain):
"""Proximal Policy Optimization implementation
This class contains core PPO methods:
several training epochs on one rollout,... |
990,412 | e3cbed7eca01956cbb86a1b44714102d82b060aa | # https://codeforces.com/problemset/problem/1099/A
w, h = map(int, input().split())
u1, d1 = map(int, input().split())
u2, d2 = map(int, input().split())
while h > 0:
w += h
if d1 == h:
w = max(w - u1, 0)
if d2 == h:
w = max(w - u2, 0)
h -= 1
print(w) |
990,413 | 971abbc55da014c655ed52d23df82bf594a19017 | # -*- coding:utf-8 -*-
from scrapy.selector import Selector
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.http import Request,FormRequest
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
host='http://www.zhihu.com'
... |
990,414 | b36fc8f4c98f1fdc2ff3b39b65469c7866fe6ddb | while True:
try:
n=int(raw_input())
num=[]
for i in range(n):
num= list(map(int, raw_input().split()))
break
except:
break
if 1 <=len(num)<=100000 :
odd,eve=[],[]
for i in range(n):
if i%2==0 and num[i]%2!=0:
odd.append(num[i])
elif i%2!=0 and num[i]%2==0:
o... |
990,415 | d1ec22d84e639f89dbf6f41b0465e09a98fa8494 | x=list(input())
y=list(input())
z=[]
for i in x:
if i in y:
z.append(i)
print(''.join(z))
|
990,416 | 9806b2ac736d31cef46eea61d00ad9746db36bb1 | x = 50
def func():
global x
x=55
print(f'Global X from function x = {x}')
print(f'X before calling func() with global X. x = {x}')
func()
print(f'X after func() x = {x}') |
990,417 | 193faf016735525faf99b1fe7be57402900f71d2 | """ Layer service """
from RWAPIMicroservicePython import request_to_microservice
from geetiles.errors import LayerNotFound
class LayerService(object):
@staticmethod
def execute(config):
response = request_to_microservice(config)
if not response or response.get('errors'):
raise ... |
990,418 | cec3c22fd636bedf4713d426b2825bb5e9a95593 | from cuneiform_ecc import *
def test_encode_eng():
s = "Open the door and enter the room but expect to be stifled by the sights and sound."
expected = "OPCENRTH_EDHOOBRARNDQENRTEXRTJHELROEOM_BUVTEXXPLECGTTLOBPESWTIAFLQEDHBYZTH_ESWIGOHT_SASNDQSOFUNGD_C"
actual = encode_eng(s)
assert actual == expecte... |
990,419 | 77f52a4f1b07d9b71bc50f571792bed7a88572ac | import os , sys
sys.path.append(os.getcwd())
import pytest
import fnvhash_c
import time
@pytest.mark.asyncio
async def test_convert():
assert fnvhash_c.convert_char_into_int(b'12\x00a') == fnvhash_c.convert_char_into_int('12\x00a') == 825360481
try:
fnvhash_c.convert_char_into_int('12345')
except E... |
990,420 | 50a6753ea87c01ed7964da06cec2e4ae5ce59c29 | """
Affine Transformations:
Preserve the # of vertices
Preserve the order of vertices
Scaling/Dilation
Translation
Rotation
Moving/Translation
(x,y)-T(2,3)->(x+2,y+3)
(x,y,z)-T(a,b,c)->(x+a,y+b,z+c)
|1 0 0 a||x| |x+a|
|0 1 0 b||y|-|y+b|
|0 0 1 c||z|-|z+c|
|0 0 0 1||1| | 1 |
Scalin... |
990,421 | 64d71ce2f65dd83cd8568be7dab91fab5ecd40ef | from __future__ import print_function, division, unicode_literals
import warnings
import os
import sys
from configobj import ConfigObj
os_release = ConfigObj('/etc/os-release')
ID = os_release['ID']
VERSION_ID = os_release['VERSION_ID']
IDS = [ID] + os_release['ID_LIKE'].split(' ')
def sys_path_append_match(dir_path... |
990,422 | 6b89c3a8885d7f7dd1bf25acadbde05059be49dd | #!/usr/bin/env python3
import dbxref.resolver
import requests
import logging
import json
import argparse
logger = logging.getLogger(__name__)
def main():
"""main()method for script usage"""
# AVAILABLE for implementation:
# 'go_terms', 'member_databases', 'integrated', 'entry_annotations', ''
#
#... |
990,423 | b7c36b7c3c5d222f4a88cad38a26f29c3417dc8d | import numpy as np
a1 = np.array([2,3,4])
print(a1)
a2 = np.random.randint(1,20,9).reshape(3,3)
print(a2)
print(a2) |
990,424 | a4b650fa33b5abec534edf52ed555bb822559329 | import cPickle
import os
import twitter # https://github.com/ianozsvald/python-twitter
# Usage:
# $ # setup CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET
# as environment variables
# $ python get_data.py # downloads friend and follower data to ./data
# Errors seen at runtime:
# raise URLError... |
990,425 | 144e409cba424880b03cc9137167f8b6416e65b7 | from MidoHelper import Note, InstrumentHelper, MidoHelper
from functools import reduce
import random
def getTransitionMatrix(seq, deg = 1):
'''
Get sequence of notes seq as input, calculate the Markov chain transition matrix of degree deg. Return it as dictionary cnt.
init is the frequency of notes i... |
990,426 | e13bce6acc27a9a11e330e8d5c05084475ce4dea | import numpy as np
import pandas as pd
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from PIL import Image
import PIL.ImageOps
X, Y = fetch_openml("mnist_784", version = 1, return_X_y = True)
X_train, X_test... |
990,427 | 3f2d5ee6a6fd5d154d56a927cb3964f55268c5d8 | import time
from indy import anoncreds, wallet
import json
import logging
from indy import blob_storage
from indy import pool
from src.utils import run_coroutine, path_home, PROTOCOL_VERSION
logger = logging.getLogger(__name__)
async def demo():
logger.info("Anoncreds Revocation sample -> started")
iss... |
990,428 | 008de82e089d5287bd54de8d48f6dd9a7aa099a8 | import re
# input_lines = '''\
# aaaaa-bbb-z-y-x-123[abxyz]
# a-b-c-d-e-f-g-h-987[abcde]
# not-a-real-room-404[oarel]
# totally-real-room-200[decoy]'''.splitlines()
input_lines=open('input.txt')
good =[]
for line in input_lines:
match = re.match(r'^([a-z-]+)([0-9]+)\[([a-z]+)\]', line)
name, sector, checksum... |
990,429 | cc9f1ac7003c67af0f6a4a5a7e3f0a6fc13e074d | import numpy as np
from math import floor
from transform import lerp
import numpy as np
import random
def make_vertex(vertices, n, x, y, height, width, centered=False):
if centered:
vertices[n][0] = x - (height + 1)/2
vertices[n][1] = y - (width + 1)/2
else:
vertices[n][0] = x
v... |
990,430 | a256679d9e2f55d07e47a4b10e487aec02429caa | N = int(input())
MAP = [input() for _ in range(N)]
# print(MAP)
def dfs(y,x,size):
if size == 0:
return
c = True
asdf = MAP[y][x]
for i in range(y,y+size):
for j in range(x,x+size):
if asdf != MAP[i][j]:
c = False
# print(c)
... |
990,431 | 7ec88f942593aa665758bb0bcc074713a2bbc528 | numbers = ["a","b","c","d","e"]
print(numbers[0],numbers[1], numbers[2], numbers[3], numbers[4]) |
990,432 | f43a5846e6cc53347b2f1e84b1c44d2bbeceb6be | from gip.third_party import get_image_size # NOQA
|
990,433 | 9f8d9ffe488f870bf70c762f02045ad1716754ae | import json
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.core.paginator import Paginator
# Create your views here.
from .models import *
'''
handle with the good
'''
def index(request):
typelist = TypeInfo.objects.all()
type00 = typelist[0].goodsinfo_set.or... |
990,434 | 3a4dea845ed180d01113039399bd8ce86cc374a8 | # coding: utf-8
import sys
from bisect import bisect_left, bisect_right
sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
R = ir()
target = [1200, 2800]
i = bisect_right(target, R)
answer = ['ABC', 'ARC', 'AGC'][i]
print(answer)
|
990,435 | f755643db0f9dcac454a5e7837f37e6a056454c0 | """ Main detector module which can be used for training and inferencing. """
from typing import List
import collections
import torch
import efficientnet, bifpn, retinanet_head
from third_party import (
postprocess,
regression,
anchors,
)
_MODEL_SCALES = {
# (resolution, backbone, bifpn channels, num... |
990,436 | ffb0aab7110c1349a7e2e7372b77d8be7d0295bd | # percol configuration file
percol.import_keymap({
"C-j" : lambda percol: percol.command.select_next(),
"C-k" : lambda percol: percol.command.select_previous()
})
|
990,437 | 666c12af0a4b0069ac76e669fa1eab6a0ded0765 | """Some useful pre-processing functions"""
import re
import os
from nltk.corpus import PlaintextCorpusReader
__author__ = ["Clément Besnier <clemsciences@aol.com>", ]
__license__ = "MIT License"
def remove_punctuations(text):
res = text
if re.match(r"[0-9]+\.", text) is None:
res = re.sub("[\-:?;.... |
990,438 | e1bde05e76f25fba1f4e8353659ba0e53cbcdc28 | ####Itertools####
from itertools import permutations, product, combinations_with_replacement, combinations
data = ['A', 'B', 'C']
##permutations##
result = list(permutations(data, 3))
print(result)
#result = [('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]
##prd... |
990,439 | 4e8973073db152fd867f8185ae7e80808f5c2c3d | from Handler import Verifycode, BaseHandler, Passport, Profile
from tornado.web import RequestHandler
import os
handler = [
(r'/api/pitcode', Verifycode.PicCodeHandler),
(r'/api/smscode', Verifycode.SMSCodeHandler),
(r'/api/register', Passport.RegisterHandler),
(r'/api/login', Passport.LoginHandler)... |
990,440 | a3992991afd406f454b8cfe74feb08c7a280ca19 |
# Script Name : noform.py
# Author : johnny trevisani
# Created : 20 Dec 2016
# Last Modified : 21 Dec 2016
# Version : 1.0
# Modifications : documentation for initial version
# Description : Prompt user for ratings
Bg = input ("BIGOTRY Rating (1-5):")
Of = input ("OFFENSIVENESS Rating... |
990,441 | 767ce4ad0c2a84790ea0e69b970e74bebce7d36b | """xmltramp: Make XML documents easily accessible."""
__version__ = "1.22"
__author__ = "Aaron Swartz"
__copyright__ = "(C) 2003 Aaron Swartz. GNU GPL 2"
class Element:
def __init__(self, name, attrs=None, children=None):
self._name = name
self._attrs = attrs or {}
self._dir = children or []
self._text = ''
... |
990,442 | 1a8071b36f28569ddd804c1af9096653ead0c2a1 | from typing import List
from collections import Counter,defaultdict
from math import *
from functools import reduce,lru_cache,total_ordering
import numpy as np
from heapq import *
from bisect import bisect_left,bisect_right
from itertools import count
import queue
class Solution:
def subsetsWithDup(self, nums: Lis... |
990,443 | 8b2fc40cf717aaacbb5f6568ba2dd38db7ae8ef5 | import pandas as pd
import sqlite3
from Prepare_file_10min_interval import process_dataframe_insert_10min_interval
def add_weather_data() :
# read csv file number of rows including the column name 2502762
df = pd.read_csv(r'D:/Server Code/Required_csvs'
r'/final_1.csv',
... |
990,444 | 9440b51b1dc66b81fd56c8761311550afed69fff | # Generated by Django 2.2.2 on 2019-06-24 14:39
from django.db import migrations
import wagtail.core.blocks
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('flexpage', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='fl... |
990,445 | 8a0e4e76f144ae0cd3bf5916da557bd4f97edeb0 | # Function to check wheter some account is registered in the bank
def exist(bank, account: int) -> bool:
if account < len(bank.getClients()) and account >= 0:
return True
else:
return False
class Bank:
def __init__(self) -> None:
self.clients = []
def getClients(self):
... |
990,446 | 74140a43e6f7ac7bc7cca289f1c620bf9b075db3 | # -*- coding: utf-8 -*-
from xml.dom.minidom import parseString
from langdetect import detect as language_detect
import pycountry
FILE_NAME_A = 'feed_a.xml'
FILE_NAME_B = 'feed_b.xml'
FILE_NAME_C = 'feed_c.xml'
DEFAULT_ENCODING = 'utf-8'
class BaseParser(object):
def __init__(self, file_name):
... |
990,447 | 5d0668602b312f808d0d83f93f81607c3e86b85d | #!/usr/bin/env python
import paho.mqtt.client as paho # pip install paho-mqtt
import time
import logging
import sys
import pigpio
from config import *
MQTT_PREFIX = 'gas'
FREQUENCY_S = 1
GAS_GPIO = 27
m3abs = 0.0
gpio = None
reed_state_old = 1
def read_state():
global m3abs
with open('local-gas-connector... |
990,448 | f5d1abb9f6297d222c56b3b297033bee812e57fb | """
As a henchman on Commander Lambda's space station, you're expected to be resourceful, smart, and a quick thinker. It's not easy building a doomsday device and capturing bunnies
at the same time, after all! In order to make sure that everyone working for her is sufficiently quick-witted, Commander Lambda has instal... |
990,449 | 3220560e50edbe6c223486c8adbcdda00bf2ddc3 | import torch.nn as nn
import torch
import math
import pdb
class ConvBasic(nn.Module):
def __init__(self, nIn, nOut, kernel=3, stride=1,
padding=1):
super(ConvBasic, self).__init__()
self.net = nn.Sequential(
nn.Conv2d(nIn, nOut, kernel_size=kernel, stride=stride,
... |
990,450 | c6321faa13d61951d91ace37c3b88272dd877587 | import numpy as np
import scipy.stats
import pytest
from astropy.io.fits import getdata
try:
import specutils
except ImportError:
HAS_SPECUTILS = False
else:
HAS_SPECUTILS = True
from skypy.galaxy.spectrum import dirichlet_coefficients, kcorrect_spectra
def test_sampling_coefficients():
alpha0 = n... |
990,451 | 821133fd95f0dff2c2014f09489c41f7d2b4f6d8 | Number Patter increasing - element removed at each level having maximum value
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Solution Code:
rows = int(input())
for num in range(1,rows+1):
for k in range(rows+1, num, -1):
print(rows-k+2,end = " ") # This line is the reason why, number has been started gettin printed from 1... |
990,452 | 71b885fcd2ba962ac1cfd630150c47aacc32a2d1 | import importlib
import sys
from pyfix.codec import Codec
from pyfix.journaler import DuplicateSeqNoError
from pyfix.message import FIXMessage, MessageDirection
from pyfix.session import *
from enum import Enum
from pyfix.event import FileDescriptorEventRegistration, EventType, TimerEventRegistration
class ... |
990,453 | fddf0eec2ad563cb37b7a7e9c026f5f983e79fb5 | import serial
import crc16
import constants
import time
SERIAL_READ_START = 0xAF
SERIAL_READ_END = 0xFE
SERIAL_SEND_START = 0xDE
SERIAL_SEND_END = 0xED
class SerialDispatcher():
def __init__(self):
self.callback_list = {}
self.interval_list = {}
self.initialized = False
def initialize... |
990,454 | 45c4e9f9332051e59693e45b83a0cec2ae6b2552 | a = ["avinash","umesh","Atique"]
b = ["arun","vinesh","sahir"]
zipped = list(zip(a,b))
print(zipped) |
990,455 | 6bf88cd4778bf5e330e6a18a4242234cb7ea3411 | # encoding: utf-8
import event
import time
from myLogger import logger
class RestEvent(event.Event):
def __init__(self, eventJS, eventJSSearch, eventServer):
self.eventJS = eventJS
self.eventJSSearch = eventJSSearch
self.eventServer = eventServer
self.tourLocations = eventJS.get("to... |
990,456 | ef5ca93cbe5cef31dd55727651930c2cc04e3c30 | import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision.models
from torchvision import datasets, transforms
import seaborn as sns
from tqdm import tqdm
from dataloader import RetinopathyDataset
from torch.utils.... |
990,457 | a0a46f21416a5f5e20b59486216f4f358411252c | #!/usr/bin/env python
# pylint: disable=E1101
# E1101: Allow imports from currentThread
"""
_ExecuteMaster_
Overseer object that traverses a task and invokes the type based executor
for each step
"""
from builtins import object
import logging
import os
import threading
import traceback
import WMCore.WMSpec.Steps.S... |
990,458 | f8b2e84d3fd20a6cd6d778548338c77f26437dc8 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
ConversationHandler)
import logging
from firebase import firebase
firebase = firebase.Fireba... |
990,459 | 29401251ce102f56fd4e95fba4540d70b120907b | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import io
import featurize
input_simple = u"""mereven merev/ADJ
A a/ART
részletezni részletez/VERB
hullámzik hullámzik/VERB
terítse terít/VERB
pillanat pillanat/NOUN
mozgásban mozgás/NOUN
mi mi/NOUN
mindenre minden/NOUN"""
input_with_cases = u"""mereve... |
990,460 | 3b6d6b65f664f6743d294802d709a9c45e42f4c5 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 2 14:15:29 2019
new-2-gram
2. 使用新数据源完成语言模型的训练
按照我们上文中定义的prob_2函数,我们更换一个文本数据源,获得新的Language Model:
下载文本数据集(你可以在以下数据集中任选一个,也可以两个都使用)
可选数据集1,保险行业问询对话集:
https://github.com/Computing-Intelligence/insuranceqa-corpus-zh/raw/release/corpus/pool/train.txt.gz
可选数据集2:豆瓣评论... |
990,461 | 93eded113d737d03cbcbcb517a77c14049e17793 | from enum import Enum
from src.items.aged_brie import AgedBrieItem
from src.items.backstage_passes import BackstagePassesItem
from src.items.conjured import ConjuredItem
from src.items.legendary import LegendaryItem
from src.items.normal import NormalItem
class Categories(Enum):
normal = NormalItem
aged_brie ... |
990,462 | b11e02f7f1d3f5d057c467e6e0e8d2e25e52fc01 | # -*- coding: utf-8 -*-
# 匿名函数
def add(x,y):
return x+y
print(add(1,2))
f = lambda x,y: x+y
print(f(1,2))
# lambda 表达式
# lambda parameter_list: expression(不能写代码语句)
# 三元表达式
# x,y。若 x 大于 y 返回 x 否则 y
# x > y ? x : y
# 条件为真时返回的结果 if 判断条件 else 条件为假时的返回结果
x = 2
y = 1
r = x if x > y else y
print(r) |
990,463 | 35951a55d53ff9c849c86e55ed799f6b2fe9c466 | # -*- coding: utf-8 -*-
import logging
_logger = logging.getLogger(__name__)
from odoo import models, fields, api, exceptions, _
class DocumentationBoard(models.Model):
_name = 'documentation.board'
_description = _('Dashboard')
@api.depends('used_model')
def _get_count_item(self):
for r in self:
res = 0
... |
990,464 | b74f1a28fe59b33192283d8b3f3c7a1f65b46649 | from dataclasses import dataclass, field
from .logger_params import LoggerParams
@dataclass()
class PredictParams:
""" Model predictions config ORM class. """
name: str = 'predict'
experiment: str = 'default_experiment'
data_path: str = 'heart.csv'
model_path: str = 'model.pkl'
save_path: str ... |
990,465 | 6029db8b64880b499698dd18ce50d7d580148074 | class RebarLayoutRule(Enum,IComparable,IFormattable,IConvertible):
"""
The rule for how the rebars in rebar set are laid out
enum RebarLayoutRule,values: FixedNumber (1),MaximumSpacing (2),MinimumClearSpacing (4),NumberWithSpacing (3),Single (0)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx... |
990,466 | 50f2ff6ea2aa7239f829ff37d1dcbef90b4b510d | #!/usr/bin/env python
import socket
import sys
HOST = '192.168.200.132'
PORT = 50012
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print 'Failed to create socket,Error code: ' + str(msg[0]) + ', Error message: ' + msg[1]
sys.exit()
print 'Socket Created.'
s.bind((HO... |
990,467 | e47d8e90d3228e9db4de647ca6705930ea421f37 | #!/usr/bin/env python
from geometry_msgs.msg import PoseStamped, TwistStamped, Point, Quaternion
import rospy
import math
import tf
from std_msgs.msg import Float32, Bool, String
from VelocityController import VelocityController
from sensor_msgs.msg import Imu
import numpy as np
import copy
class position_control():
... |
990,468 | 4ba155810d52cbc1c2c86f66c7eb606ad4a0fdc1 | import cv2
##############################################################
# These parameter values are indicative. You should choose your own
# according to properties of the method you want to demonstrate
h = 5
templateWindowSize = 7
searchWindowSize = 30
#########################################################... |
990,469 | 59da7ae8d872ea39abc4ffd93bf6bac4ffe535c1 | import sys
last_text = ""
last_lang = ""
last_sf = 0
for line in sys.stdin:
line = line.strip()
infos = line.split("\t")
if len(infos) != 3:
continue
lang = infos[0]
text = infos[1]
sf = int(infos[2])
if (last_lang != "" and lang != last_lang) or (last_text != "" and text != last_text):
print last_lang + ... |
990,470 | fb3c19d3c7f093ea13859e82161fa0c85cd2cfc9 | from django import forms
from django.forms import ModelForm
from blog_app.models import Post,Comment
class PostForm(ModelForm):
class Meta():
model=Post
fields= ('author','title','text')
widgets ={
'title':forms.TextInput(attrs={'class':'textinputclass'}),
'text':for... |
990,471 | 2dba0bd99af4070651b637ff6f469c820307734c | import webapp2
import cgi
import re
def build_page(username, password, ver_pass, email, error_username, error_password, error_ver_pass, error_email):
header = "<h1>Signup</h1>"
user_label= "<label style='margin:2% 4%; font-#weight: bold; font-size: 14px; '>Username</label>"
user_input= "<input type='text' ... |
990,472 | 1b7952898f4c65a3305ed23cd5c0a61314ca7c1a | import torch.nn as nn
import torch.nn.functional as F
class DNNet(nn.Module):
def __init__(self, in_num, out_num):
super(DNNet, self).__init__()
self.in_num = in_num
self.conv1 = nn.Conv1d(1, 16, 49, stride=1, padding=0, bias=False)
self.pool1 = nn.MaxPool1d(kernel_size=4, strid... |
990,473 | b813794d9d9e56c57ff4e18141e15904a8bcfc77 | import pandas as pd
import sys,os
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from pandas import DataFrame,read_csv
from numpy import random
"""
print("Python version "+sys.version)
print("Pandas version "+pd.__version__)
print("Matplotlib version "+matplotlib.__version__)
"""
#数据创建
names = [... |
990,474 | 9284b2a97491328b4f6feb7bf8df3d5171b0b5b5 | import logging
from os import path
class DynPathFileHandler(logging.FileHandler):
"""A handler class which writes formatted logging records to disk files."""
def __init__(self, filename, dirpath='.', mode='a', encoding=None, delay=False, errors=None): # noqa: WPS211
"""Open the specified file and us... |
990,475 | ada3a32f9d26ad5f2d1eed4c702ea46308dfebb7 |
class QuerySet():
"""
查询结果存放集,按照sql返回的结果集顺序存放,顺序获取
"""
def __init__(self):
self._set = {}
self._set[0]= 0
self._next_key = 0
self._put_key = 1
def next(self):
"""
从QuerySet 里取下一个结果集,如果没有更多结果集返回 None
"""
self._next_key += ... |
990,476 | 8d46e18299710a6989e7ada32bb5eaf12be31bf7 | def search_array(char,array):
i=0;
final=0;
while i<len(array):
if array[i]==char:
final+=1;
i+=1;
return final;
|
990,477 | a6c82a9b751a8c7e83fa67aa30673c38326d427e | #!/usr/bin/env python
"""
Creates an HTTP server with basic auth and websocket communication.
"""
import argparse
import base64
import hashlib
import os
import time
import threading
import webbrowser
import numpy as np
import cv2
import picamera
from picamera.array import PiRGBArray
from PIL import Image
from datetime ... |
990,478 | aa33860d0bb113b7650330b738e866b98b2c769f | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
cur = parent = ListNode(None)
while head:
while cur.next and cur.next.val < ... |
990,479 | 1def283c1ea4b413a46e005bf5e27c1888c4e3f0 | for l in range(1,5):
#print("\U0001f600" * l)
i = 1
smileys = ""
while (i <= l):
smileys += "\U0001f600"
i = i+1
print(smileys)
|
990,480 | 1480a40562dcb772bc020318b3552ef885aeb430 | import argparse
import math
import re
from typing import Dict
from typing import List
from typing import NamedTuple
from typing import Tuple
from support import timing
INT_RE = re.compile(r'-?\d+')
class Vector(NamedTuple):
x: int
y: int
z: int
def add(self, other: 'Vector') -> 'Vector':
re... |
990,481 | 42f8485df7b3d7e9f0dfd2a0a7af82bb5dc6493b | print('''The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows:
start with any positive integer n. Then each term is obtained from the previous term as follows:
if the previous term is even, the next term is one half the previous term.
If the previous term i... |
990,482 | 3be0b75b9ea0304f2adc90194f5a26148a440d10 | #!/usr/bin/python
"""
Python wrapper of the botan crypto library
https://botan.randombit.net
(C) 2015,2017,2018 Jack Lloyd
(C) 2015 Uri Blumenthal (extensions and patches)
Botan is released under the Simplified BSD License (see license.txt)
This module uses the ctypes module and is usable by programs running
under... |
990,483 | cbaa9e351d775d53c603c83ecbc4874f43ecea51 | from setuptools import find_packages, setup
with open("README.md") as fd:
long_description = fd.read()
setup(
name="tamizdat",
version="0.2.1",
description="flibusta.net indexing and email delivery service",
long_description=long_description,
long_description_content_type="text/markdown",
... |
990,484 | c9e556f4b99dcf9eb81a4b68a75dd858fff61d04 | # Author: Raphael Fonseca
# Social Computing and Social Network Analysis Laboratory, Federal University of Rio de Janeiro, Brazil
# Create Date: 2015-07
# Last Update: 2017-07-27
# -*- coding: utf-8 -*-
import oauth2 as oauth
import json
import time
import pymongo
# API Authentication - Fill in credentials
CONSUMER_... |
990,485 | 7abbdaa1911bb74d62e6b688ef6ef05bd6cf482c | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 13 14:53:48 2019
@author: Administrator
"""
s=input("enter a string:")
list=[s[i] for i in range(len(s))]
print(list) |
990,486 | 141c4fd0e48091ef81b8bc1b842a906418fc2ea0 | import time
import argparse as arg
import datetime
import os
import torch
import torch.nn as nn
import torch.nn.utils as utils
import torch.optim as optim
import torchvision.utils as vision_utils
from tensorboardX import SummaryWriter
from problem4.losses import ssim as ssim_criterion
from problem4.losses im... |
990,487 | 3b88f1956e8e6bb7f314389856d67a7b424bf424 | ii = [('KembFFF.py', 3), ('RennJIT.py', 1), ('AubePRP2.py', 1), ('LeakWTI2.py', 1), ('KembFJ1.py', 1), ('WilkJMC3.py', 9), ('LeakWTI3.py', 1), ('PettTHE.py', 2), ('TennAP.py', 1), ('PeckJNG.py', 1), ('KnowJMM.py', 1), ('WilkJMC2.py', 4), ('CarlTFR.py', 11), ('LyttELD.py', 1), ('KiddJAE.py', 2), ('CoolWHM.py', 1), ('Cla... |
990,488 | e50f0232df4f40575e8a982195e26e99f96eb3fc | from __future__ import print_function
import numpy as np
import utils as u
import models as m
# constants
data_dir = 'data/'
train_filename = 'loan_train.csv'
test_filename = 'loan_testx.csv'
def get_ranges():
train_range = u.get_file_ranges(data_dir + train_filename)
test_range = u.get_file_ranges(data_dir + tes... |
990,489 | 65ebec88ef5ad0bfd1da22aa68c0e675122ca916 | from binaryninja import *
class RunInBackground(BackgroundTaskThread):
def __init__(self, msg, func, *args, **kwargs):
BackgroundTaskThread.__init__(self, msg, True)
self.func = func
self.args = args
self.kwargs = kwargs
def run(self):
self.func(self, *... |
990,490 | 0de6d19df61185d86066d94086a1a993a96ab887 | import sys
import pytest
import numpy as np
from typing import List, Union, Literal, Set
from config import CONFIG
sys.path.insert(0, str(CONFIG.src))
from card_simulator import Card_Deck
from Hands_generator import Hands_Generator
@pytest.fixture
def hands_generator():
hands_generator = Hands_Generator()
re... |
990,491 | f638b6db723284109520689ca4fbcb91e697df30 | # coding: utf-8
###############################################################################
# Module Writen to OpenERP, Open Source Management Solution
# Copyright (C) OpenERP Venezuela (<http://www.vauxoo.com>).
# All Rights Reserved
########################################################################... |
990,492 | dbca30303cafe5c4bda912b03e7c3069dc593eaa | import time
import os
import process as pro1
print("Welcome to TURUCALLER".center(50,'*'))
time.sleep(1)
print('\nPress 1 to login.\nPress 2 to SignUp')
ch1=int(input('Enter your choice: '))
if ch1==1:
import login
name=login.login()
time.sleep(5)
os.system('cls')
pro1.process.pro(na... |
990,493 | 7afeac90e0c1496f915902c51676bc215d2a4eff | # FILE-INDEXER/VALUE-GENERATOR, Written by Benjamin Jack Cullen
import os
import sys
import csv
import time
import codecs
import distutils.dir_util
import fileinput
import datetime
# Files & Paths
mainDir = 'Indexes'
encode = u'\u5E73\u621015\u200e,'
config = 'config.conf'
rawPath = (mainDir+'/Raw-Inde... |
990,494 | 565e01d561903b43a58119b178a317af7b76e69e | import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from IPython.html.widgets import interact
from sklearn.linear_model import LogisticRegression
from visualization_helper import plot_proba_function
from sklearn.datasets.samples_generator import make_blobs
def solve_kmeans_exercise(X, n_clusters=10):
... |
990,495 | 69203a26b2e2b13e29423e2ff4fff862e0bcaa7e | from django.contrib.gis import admin
from geonames.models import Geoname, Alternate
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
class CityListFilter(SimpleListFilter):
# Human-readable title which will be displayed in the
# right admin sidebar ju... |
990,496 | 6e554baa852aefa141b40de389acfcfd80795562 | from django.shortcuts import render
from django.views.generic import CreateView,ListView,DetailView,UpdateView,DeleteView
from blogs.models import Posts
from django.contrib.auth.mixins import LoginRequiredMixin,UserPassesTestMixin
# Create your views here.
def index(request):
return render (request,"blogs/index.ht... |
990,497 | 26f7331d235ee7a9b7a69e561789fa679340fee7 | import matplotlib.pyplot as plt
import matplotlib.cm
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
from matplotlib.colors import Normalize
import matplotlib.cm as cm
def draw_map(x,y):
l_lon = -123.3116
r_lon = -122.9923
... |
990,498 | 2502f46e5fa910c72ba490f98231dc29b99fe642 | import tensorflow as tf
import numpy as np
def __init__():
def recurrent_network():
hidden_size = 100
seq_length = 5
learning_rate = 1e-1
with tf.variable_scope("yolo"):
input_hidden = tf.get_variable('l1',[hidden_size, 5])
hidden_hidden = tf.get_variable('l2',[hidden_size,hidden_siz... |
990,499 | 0f15e585f2680a7a83e0f9ee4e952cc89a313255 | import pefile
from sys import argv
if len(argv) < 2:
print "%s module.dll [0xOFFSET]"
exit()
module_name = argv[1]
pe = pefile.PE(module_name)
#bytes = pe.section[index].get_data()
base = int( argv[2], 16 ) if len(argv) > 2 else pe.OPTIONAL_HEADER.ImageBase
for sym in pe.DIRECTORY_ENTRY_EXPORT.symbols:
print "0x%... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.