index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
989,500 | 83f0aafcff15202524b487ec34d57bea3a0e5de3 | from functools import reduce
my_list = [1,2,4]
print( list( map( lambda item: item*2, my_list ) ) )
print( reduce( lambda acc, item: acc + item, my_list ) ) |
989,501 | 769b34dd740aeb7926cf94c22fca0e1f219b1b60 | import textract
text = textract.process(r"q.doc")
text = text.decode()
print(text)
with open('111.txt','w',encoding='utf-8') as f:
f.write(str(text))
|
989,502 | d28285caa2a70558bde6e904f7eb803d19801ca0 | from django.contrib import admin
# Register your models here.
from .models import App_file
admin.site.register(App_file) |
989,503 | 105e271edfceb543360d596b98a69eaafbc78e19 | n = 118382
sorted_num = sorted(str(n), reverse=True)
print(sorted_num)
new_num = list(map(int, sorted_num))
print(int("".join(sorted_num)))
# join은 list를 다시 합쳐주는 함수
|
989,504 | 4e7dc3018a47c081f378bea5f915f7ef9caee644 | ##################################################
# Finding a Shared Spliced Motif
#
# http://rosalind.info/problems/LCSQ/
#
# Given: Two DNA strings s and t (each having length
# at most 1 kbp) in FASTA format.
#
# Return: A longest common subsequence of s and
# t. (If more than one solution exists, you may
# re... |
989,505 | 58cd0f9cec9261cf6b387c07b123f4c3be7341cf | # Source: https://pymotw.com/2/socket/udp.html
import socket, sys, time
host = sys.argv[1]
textport = sys.argv[2]
n = sys.argv[3]
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
port = int(textport)
server_address = (host, port)
d= socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
p = 1007
sa = ('localhost', p)... |
989,506 | 16154401ba585baaa1bd91226ab9b5a0f3c7d53e | import python_sns.config as config
import python_sns.core as core
from cyrm_python_tools_framework.framework import post_parse_log, run_id
import logging
# Constructs the logger
post_parse_log(config.TOOLNAME, "", run_id(), run_id())
LOGGER = logging.getLogger(config.TOOLNAME)
def main():
"""
Main entry poi... |
989,507 | 56c30403e8db2c53d61bd992fbfe4a9a216a9cc7 | import sys, zipfile, os, shutil, json, traceback, logging
sys.path.append("../")
from lib.utils import download_and_extract_zip, parse_configurations
from lib.db_handler import db_handler
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
BASE_URL = "https://nvd.nist.gov/feeds/json/cve/1.1/nvdcve-1.1-"
EXTENSION... |
989,508 | a5a2719dc6157cabd34cf49912add11f86066c4d | #Range
#Range這個型別可用來創建並儲存特定範圍內的整數,故得名Range。
#必須特別注意的是,一旦Range被創建了,裡面的內容是不可修改的
#在Python中,我們有幾個方法可以創造Range。
#Range(stop)
#stop:停止點
#Range(start, stop)
#start:起始點
#stop:停止點
#Range(start, stop, step)
#start:起始點
#stop:停止點
#step:間隔
r1 = range(10)
r2 = range(5, 50, 5)
print(type(r1))
print(r1)
print(r2)
""" 若沒有給起始值,將預設為0... |
989,509 | 6f3ecda1d6c69334283403f3c293893739f852cb | import numpy as np
from scipy.stats import multivariate_normal
from sklearn.cluster import KMeans
import time
def em_mog(X, k, max_iter=20):
"""
Learn a Mixture of Gaussians model using the EM-algorithm.
Args:
X: The data used for training [n, num_features]
k: The number of gaussians to b... |
989,510 | 5c1551247674ff35e211d288233e0438cfbeba16 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""ThreadLocal解决了全局变量需要加锁,局部变量传递麻烦的问题,下例演示了它的用法"""
import threading
local=threading.local()
def func(name):
print 'current thread:%s'%threading.currentThread().name
local.name=name
print '%s in %s' %(local.name,threading.currentThread().name)
t1=threading.Thre... |
989,511 | 149bb7e5fce98be6aa57110d76e753472b120c83 | from flask import Flask
import folium
import folium.plugins as plugins
import numpy as np
import pandas as pd
import requests
import geopandas
import branca
from datetime import datetime, timedelta
from folium.plugins import FloatImage
from folium.plugins import Draw
from folium.plugins import MiniMap
from folium.featu... |
989,512 | 0dd34e0e745813cce7829cda541539c182658ff0 | from django import forms
from .models import Encuesta
class EncuestaForm(forms.ModelForm):
CHOICES=[('1',' '),
('2',' '),
('3',' '),
('4',' '),
('5',' ')]
like = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'class' : 'custom'}),choices=CHO... |
989,513 | 2403f08b83156ac7265b0497a09fd2d28f1d3ce8 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import thread
import threading
import RPi.GPIO as GPIO
from classes.ShiftRegister595 import ShiftRegister595
'''A standard pattern like so:
10000000
11000000
01000000
01100000
and so on.
'''
_pattern = [0x80, 0xC0, 0x40, 0x60, 0x20, 0x30, 0x10, 0x18, 0x08, 0x... |
989,514 | 01eaae1e4071dd2c03e8948948b6cb8d8ca30fce | """Rss feed
Revision ID: 96693ddf7038
Revises: 6ba25e05a1c7
Create Date: 2020-06-08 14:59:42.606219
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '96693ddf7038'
down_revision = '6ba25e05a1c7'
branch_labels = None
depends_on = None
def upgrade():
# ### c... |
989,515 | 9ad355c2f6a2ce7d3b9411029c01db43a8a2c2d1 | # Name: Zaki Ahmed, Bryan Rodriguez, John Tran
# Date: 22 Feb 2021
# Class: CS 362
# Assignment: Group Project: Part 1
from task import conv_num, conv_endian
import unittest
import task
import random
import datetime
class TestCase(unittest.TestCase):
def test1(self):
self.assertTrue(True)
def test1... |
989,516 | 0aab06d5442fcc85a0182c71150d6a2a3262c14e | import numpy as np
def get_data(name):
data = np.genfromtxt('data/' + str(name) + '.csv',delimiter=',')
X = data[:,:-1]
y = data[:, -1]
return X, y |
989,517 | 44b1a38ed0d67dde28cb391e273d7e2c3800713c | class C(object):
def __init__(self, v):
self.__value = v
def show(self):
print(self.__value)
c1 = C(10)
#print(c1.__value)
c1.show()
#외부에서 접근 가능한 변수를 파이썬은 property, 루비는 attirbute라고 함
#Python에선 원래 getset없이 인스턴스 변수값에 직접 접근이 가능하지만,
#init에서 __value로 설정 해두면 직접 접근이 안되게 만들 수 있음(인스턴스 변수 안의 함수 사용도 안되게 됨... |
989,518 | 624994f372911ed86095b96da71164ed0a9ef8e5 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0007_auto_20150803_1532'),
]
operations = [
migrations.AddField(
model_name='organization',
n... |
989,519 | 8426aa746d50c2fafae9f967be2fbc639c3728e9 | def main():
print("hello there")
def goodby():
print("'later")
|
989,520 | 2a90cd22c186ab5c1d64f98608b61bd084197b03 |
import ROOT
#Open the rootfile and get the workspace from the exercise_0
fInput = ROOT.TFile("Workspace_mumufit.root")
ws = fInput.Get("ws")
ws.Print()
#You can set constant parameters that are known
#If you leave them floating, the fit procedure will determine their uncertainty
ws.var("meanJpsi").setConstant(1)
#S... |
989,521 | 71292c35b5ff4bebbe9bf51004841cf852fb3b84 | import pytest
import glob
import os
import sys
import pathlib
PATH_HERE = os.path.abspath(os.path.dirname(__file__))
PATH_PROJECT = os.path.abspath(PATH_HERE+"/../")
PATH_DATA = os.path.abspath(PATH_PROJECT+"/data/abfs/")
PATH_HEADERS = os.path.abspath(PATH_PROJECT+"/data/headers/")
try:
# this ensures pyABF is im... |
989,522 | c0e4f40e7c2d0da2a872f685dfbd81ce8d25cae1 | import numpy as np
from numba import njit
from PIL import Image, ImageDraw, ImageFont
@njit(cache=True)
def jit_cast(img, type_max=65535, dtype=np.uint16):
# casting to set dtype
return (type_max * img).astype(dtype)
def get_user_kp(preset, blue, red, magenta, green, cyan, yellow):
# check if a preset i... |
989,523 | 444463239a934de597f38d42c549c61f5d819bc8 | import os
import unittest
from fbs.parser import load
from lang.kt.generate import generate_kt
from lang.py.generate import generate_py
from lang.rust.generate import generate_rust
from lang.swift.generate import generate_swift
from pathlib import Path
class CodeGeneratorTests(unittest.TestCase):
TEST_CASE = "te... |
989,524 | af227ea45a874b851fc6d56805557e826d35e0a9 | """Docutils transforms used by Sphinx when reading documents."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, cast
from docutils import nodes
from sphinx import addnodes
from sphinx.transforms import SphinxTransform
if TYPE_CHECKING:
from docutils.nodes import Node
from sphinx... |
989,525 | baa50853bea0a3cb2b8e359bda26e35a88cb6da9 | """empty message
Revision ID: 1d0442758bfb
Revises: 2f8cb1401dd0
Create Date: 2015-08-16 21:59:56.248774
"""
# revision identifiers, used by Alembic.
revision = '1d0442758bfb'
down_revision = '2f8cb1401dd0'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... |
989,526 | a6ae7d7164d9b869554a68b10a6cd02a37e5f0a6 | from Arvore_Final import Arvore
arvore = Arvore()
arvore.inserir(50)
arvore.inserir(30)
arvore.inserir(20)
arvore.mostrar()
arvore.balanceamento(30) # Passando o no problemático
arvore.mostrar()
|
989,527 | cf673db93851e2ddf06e7525b8a3238399bc0d59 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Create: 12-2018 - Carmelo Mordini <carmelo> <carmelo.mordini@unitn.it>
"""Module docstring
"""
import matplotlib.pyplot as plt
import sys
import numpy as np
from uncertainties import unumpy as unp
from scipy.integrate import cumtrapz, quad
from scipy.interpolate impor... |
989,528 | 5450792ab3d4947d806895ab96a50987d6293900 | from django.db import models
from django.contrib.auth.models import User
#minhas classes e funções
from ifrs.validator import validate_CPF
#############################################################################
##################### SERVIDOR ##############################################
######################... |
989,529 | 5ef5e14ca0f0fe6a04dcfa14c93c2956ea1fb2b5 | print("Loading save file...")
file = open("store.txt", "r")
counter = int(file.read())
file.close()
print("Press Control-C to quit.")
while True:
try:
print("Checking "+str(counter)+"... ", end="")
number = counter
while number != 1:
if number % 2 == 0:
number /=... |
989,530 | 096cb1c1e29c1ec8ea8451dad319d66e60b487fb | with open('3-input.txt') as f:
lines = [line.rstrip() for line in f]
skip = []
count = 2
for l in lines:
if count % 2 == 0:
skip.append(l)
count += 1
print(len(skip))
# tree = 0
# index = 0
# for l in lines:
# if l[index] == "#":
# tree += 1
# print(index)
# index = (index + 3) % int(len(l))
# p... |
989,531 | e4247a4da31e22e71521f1ada2b0d28a0fdb571f | VERSION = (1, 1, 1)
from .backends import EmailBackend
from .models import PRIORITY
from .utils import send_mail
|
989,532 | 687961844014c7a972d3d37912358f226d1abb50 | from turtle import*
import math
import time
def drawSquare(turtle, x, y, length = 100):
turtle.up()
turtle.goto(x,y)
turtle.setheading(270)
turtle.down()
for count in range(4):
turtle.forward(length)
turtle.right(90)
ttl = Turtle()
ttl.pencolor('red')
drawSquare(ttl,0,0)
ttl.penc... |
989,533 | 75e02a65c2f709a0bb6cb8e8fc58aa7a2f14880a | # -*- coding: utf-8 -*-
#
# builds a house xml used for the homepage of current multi definitions
#
import DataUnPacker
from ServerUtils import sanitize
import sys, os, time, codecs
from pprint import pprint
def buildHouseXML(root_path, xml):
cfg = os.path.join(root_path,'pkg','std','housing','itemdesc.cfg')
if... |
989,534 | 81277a09a5fbbec9b011666f40749ece4aaf077c | import torch
from torch import Tensor
from torch.nn import Module, functional
from torch.nn.modules.utils import _ntuple
class PeriodicPadNd(Module):
def forward(self, x: Tensor) -> Tensor:
return functional.pad(x, self.padding, 'circular')
def extra_repr(self) -> str:
return '{}'.format(self... |
989,535 | d4954ee8b72a47c9f73e8212b345ac4bf501f809 | from com.abc.lib.college.student_ops import get_details, get_grade
name = input('Enter name : ')
roll = int(input('Enter roll : '))
marks = float(input('Enter marks : '))
gender = input('Enter gender : ')
print(get_details(name=name, roll=roll, marks=marks, gender=gender))
print(get_grade(marks=marks)) |
989,536 | 8f730ba3546f9da3107c0b2a8fba06db834b09f2 |
'''
* File Name : date_time_practice.py
* Language : Python
* Creation Date : 05-01-2021
* Last Modified : Wed Jan 6 10:29:09 2021
* Created By : David Hanson
'''
import datetime
print(datetime.time(3, 43, 2))
|
989,537 | 235bbb1a52305c3a1d26bc23aaf947e2b51a1266 | import mysql.connector
from mysql.connector import Error
#hi
def lambda_handler(event, context):
""" Connect to MySQL database """
try:
db = mysql.connector.connect(host=os.environ['HOST'],user='USERNAME',passwd='PASSWORD', port='PORT', database='kart')
if db.is_connected():
... |
989,538 | 6a879f13aa11abf4698a65668dd8391714635559 | import xlsx_parce
import data_types
from typing import List, Tuple
import sys
import os
# number of symbols that must be equal in pns
root = 8
tail = 4
def compare_pns(components: List[data_types.Component]):
"""
compares all rows and gets similar pns
:param components:
:return:
"""
equal: ... |
989,539 | 7e17b46eee68d8a8406fd035d9b7d0820e14f3ab | print('\033[32m Olá! Seja bem vindo a aula de 66 \033[m')
# Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuario digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles.
s = t = 0
while True:
... |
989,540 | d42a5957800148056a623d52e667f46957e4ade7 | from django.core.management.base import BaseCommand, CommandError
import zipfile
import re
import csv
from django.utils.six import PY3
from italian_utils.models import Comune
class Command(BaseCommand):
args = '<file_zip>'
help = "Importa l'elenco dei comuni proveniente dal sito istat"
def handle(self, *... |
989,541 | 6d17806b5d1cea6a57f423bfc4d06d28a666d7ec | #!/usr/bin/env python2.7
import os
from scipy import integrate
from scipy.interpolate import griddata
from astropy.io import fits
from astropy.table import Table
from astropy.time import Time
import astropy.coordinates as coo
import astropy.units as u
import numpy as np, healpy as hp
import matplotlib.pyplot as plt
... |
989,542 | 76c2ba80354736e9be915bb18125d61d93fdc99a | """
Author: Lizhou Cai
Course: CSCI 4270
File: hw7_part2.py
Purpose: Do optical flow on pairs of images
to detect motion of the camera and objects
"""
import cv2
import numpy as np
import numpy.linalg as LA
import os
import sys
def is_inlier(p1, p2, foe, tau):
"""
check if a line through two point... |
989,543 | d2d5883006de26ccd538f5d28b33543abc80f534 | from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from .country import Country
from .measure import Measure
|
989,544 | 43a3931b7ff9df06acfdd7344a51ac9a2959cf2f | #http://www.careercup.com/page?pid=facebook-interview-questions
def longestRepeated(string):
seen = set()
substrings = []
answer = ''
for i in range(len(string)):
substring = string[i]
seen = set(string[i])
for j in range(i+1, len(string)):
if string[j] in seen:
if len(substring) > len(answer):
... |
989,545 | 5fcdf61d89f6a52ad0bcee48c9e12fbe3fa43c3d | from PIL import Image
from numpy import asarray, argmax, array
LABELS = ('circle', 'line', 'arch')
def get_one_hot(label):
result = [0] * len(LABELS)
result[LABELS.index(label)] = 1
return result
def get_label(one_hot):
return LABELS[argmax(one_hot)[0]]
def __to2d__(img):
result = img.convert... |
989,546 | 209c85bc0979f10270bd7e53867baf9cea52aa00 | """
= EN =
A famous casino is suddenly faced with a sharp decline of their revenues.
They decide to offer Texas hold'em also online. Can you help them by writing
an algorithm that can rank poker hands?
Task
Create a poker hand that has a method to compare itself to another poker hand:
compare_with(self, other_hand)
A... |
989,547 | d9d925abe0c18e60a7b244e50a60cba52504c77b | import time
from random import randrange
from threading import *
class Client(Thread):
def __init__(self):
Thread.__init__(self)
self.running = True
def run(self):
while self.running:
with open("sf.txt", "w+") as f:
for line in f.read():
... |
989,548 | 0163b59ed074f3f8e7b416f003fd3642f53bc66e | # coding=utf-8
'''Escribe un programa que escriba en pantalla los 30 primeros números naturales (del 1 al 30),
así como su media aritmética.'''
for numero in range(1,31):
print (numero) |
989,549 | c807c491ab0a931ec925ac090343d0ef7f9933cc | import os
import shutil
import sys
import tempfile
if sys.version_info.major == 3 and sys.version_info.minor >= 3:
impl = 'py_33'
else:
impl = 'py_old'
__path__.append(os.path.join(os.path.dirname(__file__), impl))
from py_curl.downloader import Downloader
from py_curl.machinery import PostRemoteFinder
fro... |
989,550 | 77f484aa811d5c5f54faa8e80524fba903b856d6 | from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.metrics import roc_auc_score
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from gwo import gwo
from performance impo... |
989,551 | 5c9617ad749a2bf15229fbcf72c5c81c2e8188fb | # -*- coding: utf-8 -*-
"""
Created on Sun May 16 09:31:53 2021
@author: Muhammad Ayman Ezzat
Youmna Magdy Abdullah
"""
from utils import get_molecular_weight, linear_spectrum, subset_spectrum, reversed_map
def theoritical_spectrum(peptide_sequence):
"""Returns the theoritical spectru... |
989,552 | 78df0fbf913b44aaca888020475dd08cb2ad4c85 | import os
COMPUTER_NAME = os.environ['COMPUTERNAME']
print("Computer: ", COMPUTER_NAME)
TARGET_VOXEL_MM = 1.00
MEAN_PIXEL_VALUE_NODULE = 41
LUNA_SUBSET_START_INDEX = 0
SEGMENTER_IMG_SIZE = 320
NDSB3_RAW_SRC_DIR = "C:/data/kaggle/dsb17/original/dsb17/stage1/"
LUNA16_RAW_SRC_DIR = "E:/data/kaggle/dsb17/origin... |
989,553 | f2bcc18042ea2747dfe8f1a3e8c236c218ece250 | from django.conf import settings
from django.db import models
from django.forms import ModelForm
from django.db.models.signals import post_delete
from django.dispatch import receiver
from back_end.settings import USE_S3, MEDIA_ROOT
import shutil
class Event(models.Model):
created_at = models.DateTimeField(auto_now... |
989,554 | b41926c0012001dab7346c718f16f8e62713be3e | import tensorflow as tf
import cv2
import numpy as np
import glob
im_list = glob.glob("/home/aiserver/muke/dataset/landmark-data/image/*")
tfrecord_file_train = "data/train.tfrecord"
tfrecord_file_test = "data/test.tfrecord"
im_size = 128
def write_data(begin, end, tfrecord_file):
writer = tf.python_io.TFRecord... |
989,555 | 00aee5ba24ad7229e19577f8569526cb0adde7a2 | """
Return list of messages given a datetime (empty is now) : [ (title, message), ]
Load, unload and reload messages give their name
"""
import yaml
import glob
import os.path
from datetime import datetime
from collections import OrderedDict
from messageApp.messages import Messages
class MessageApp():
def __init__(se... |
989,556 | f766ae0bec3977c893b7f9412d3f1abfafa107f5 | import sys
import cv2 as cv
import numpy as np
import os
#np.seterr(over='ignore')
# проблемы с переполнением (были)
def is_pupil_center(a,b):
global c1, c2, c3, c4
if ((c1 + a > c1 * 2 + 12) or (c1 + a < c1 * 2 - 12)):
if ((c3 + a > c3 * 2 + 10) or (c3 + a < c3 * 2 - 10)):
ret... |
989,557 | 9ee101d6961ecb6751c49e5534917ef463d7c3fa | #pdf_merger.py
#from PyPDF2 import PdfFileReader, PdfFileWriter
import os
import glob
import sys
from PyPDF2 import PdfFileWriter, PdfFileReader
from pdf2image import convert_from_path, convert_from_bytes
def pdf_splitter(path):
fname = os.path.splitext(os.path.basename(path))[0]
pdf = PdfFileRea... |
989,558 | 58511c39b5eda458c0c21a2bc556228d8ecbd9f0 | # Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
989,559 | 71b4a904f91cf354113df79f66c1c6333fb44f49 | import db_util
def get_price(RFID):
q = "SELECT price FROM items WHERE rfid = RFID;"
c = db_util.db_open()
price = db_util.db_query(c, q)
return price
def get_name(RFID):
q = "SELECT name FROM items WHERE rfid = RFID;"
c = db_util.db_open()
name = db_util.db_query(c, q)
return name
de... |
989,560 | c1b7b7db487935cbe2c26cdec203b922f16f9d93 | from heapq import heappush, heappop
def main():
N, M = map(int, input().split())
# 日数別に仕事を管理
works = [[] for _ in range(M)]
for i in range(N):
A, B = map(int, input().split())
if A > M:
continue
deadline = M - A
# heapqは最小値を返す仕組みしかないので、最大値... |
989,561 | 02e79d5359538fd9d0b6e152af885e835568c999 | from django.http import HttpResponse
from django.shortcuts import render
from APP2.models import Student
import random
# Create your views here.
def lala(request):
return render(request, 'lala.html')
# 增加数据
def add_student(request):
student = Student()
student.s_name = 'Lily%d' % random.randrange(100)
... |
989,562 | a451ed2d6ba0a5aeaf12e2791ed1c5863e4689d6 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
989,563 | fecacacee30d381affaf672dc7eb37cb7bb2a92d | import math
from PIL import Image
import asyncio
from io import BytesIO
import os
import mercantile
import fiona
from shapely import speedups
if speedups.available:
speedups.enable()
from shapely import geometry as shp
import ujson
from .tbutils import ObjDict, TileNotFound
def num2box(z, x, y, srid='4326'):
... |
989,564 | a939bdbb3eb84ebdcde269c96c2befd003ed73ac | st1=list(input())
i=0
while(i<len(st1)):
temp=st1[i]
st1[i]=st1[i+1]
st1[i+1]=temp
i+=2
print("".join(st1))
|
989,565 | 04f7fea9821aa04e033278142f80cee92abdf076 | import functools, os, requests
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
from werkzeug.security import check_password_hash, generate_password_hash
from flask import (
flash, g, render_template, request, session, url_for, jsonify, redirect, json
)
from fl... |
989,566 | 094ad59e84cfede97045699e13de6e9cac16839f | # 2839번 (브론즈1)
# 수학, 다이나믹 프로그래밍, 그리디 알고리즘, 브루트포스 알고리즘
def bags(kg):
b5 = kg//5
if kg - (b5 * 5) == 0:
return b5
for i in range(b5, -1, -1):
left = kg - (i * 5)
if left % 3 == 0:
return i + left // 3
return -1
n = int(input())
print(bags(n)) |
989,567 | d1f5d340a2ff887d2fa6732293f8965d2056e52f | from flask import Flask
import rocksdb
app = Flask(__name__)
db = rocksdb.DB("test.db", rocksdb.Options(create_if_missing=True))
from app import views |
989,568 | 79d731729650ac91be9eacda3aac0601ba20dae8 | import numpy as np
import matplotlib.pylab as plt
import math
import rls
#-----------------------------------------------------------
# Example: sinus signal
#-----------------------------------------------------------
samples = 300
time = np.linspace(0.1, 5, samples)
true_signal = [math.sin(x) for x in time]
noise =... |
989,569 | 48f96cfb21640094e2da6ed5fdb8827af2ba735f | import json
from flask import Flask
from flask_restful import reqparse, abort, Api, Resource
import app
from app.room import RoomList, Room
from app import models
#https://flask-restful.readthedocs.io/en/latest/quickstart.html#endpoints
app.api.add_resource(RoomList, '/room')
app.api.add_resource(Room, '/ro... |
989,570 | fc04b33da491137ba86f664463243028f3164fb7 | import peewee
from datetime import datetime, date
from .core import JSONField
host = 'data.ultragis.com'
db_fetch = peewee.MySQLDatabase(host=host, database='fetch', user='root', password='Bayesian@2018', charset='utf8')
class BaseModel(peewee.Model):
class Meta:
database = db_fetch
# 信息采集表
class Gath... |
989,571 | dd6bfa1b22676e947b79f561e87c61ccb16e17cf | array = [int(x) for x in input().split()]
while array != [0,0,0]:
array.sort()
if array[2]**2 == array[0]**2 + array[1]**2:
print("right")
else:
print("wrong")
array = [int(x) for x in input().split()]
|
989,572 | 593d74eb46b8a882dba7ccd47878f3ef4380d184 | #!/usr/bin/env python
# This code is based on the sample at https://pypi.python.org/pypi/inotify
#
from __future__ import print_function, unicode_literals
import logging
import inotify.adapters
import sys
def usage():
print("""python watcher.py watchpath
watchpath is a folder to watch
Writes log messages to stdou... |
989,573 | e7724b70881646cfa18298020a801b0921e429d4 | __copyright__ = "Copyright (C) 2020 University of Illinois Board of Trustees"
__license__ = """
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 th... |
989,574 | b6e7c739dfd7ef2540ba0a14dd436c3a3e480323 | """ Resource Module """
import os
import json
import logging
from urllib.parse import urlparse
#pylint: disable=E0401
from astarte.exception import ResourceError
from astarte.utility import TMP_REFERENCE_DIR
L = logging.getLogger(__name__)
class Parser:
""" Resource Parser Module.
"""
... |
989,575 | 65ad93f02fe6964b3e8156af5648728f6b527c86 | #!/usr/bin/env python3
#
# Copyright 2021 Graviti. Licensed under MIT License.
#
"""User, Commit, Tag, Branch and Draft classes.
:class:`User` defines the basic concept of a user with an action.
:class:`Commit` defines the structure of a commit.
:class:`Tag` defines the structure of a commit tag.
:class:`Branch` d... |
989,576 | 6b9c92a288da24d8c102601756ec01bd1de4c195 | ## Sid Meier's Civilization 4
## Copyright Firaxis Games 2005
from CvPythonExtensions import *
import CvUtil
import random
from math import sqrt
import sys
import RFCUtils #Rhye
utils = RFCUtils.RFCUtils()
import Consts as con
import StoredData #Rhye
import cPickle as pickle
gc = CyGlobalContext() #Rhye
"""
NOTES AB... |
989,577 | 4c63dbff475821ce119c56f4d8188a4fd389dd57 | import time
import signal
import logging
import re
from datetime import datetime
from twisted.words.protocols import irc
from twisted.internet import protocol, reactor
from cardinal.plugins import PluginManager, EventManager
from cardinal.exceptions import (
CommandNotFoundError,
ConfigNotFoundError,
Inte... |
989,578 | f99060e4765b4c16be77ce94ee95c56f384a1594 | t= int(input())
for _ in range(t):
a, b = map(int, input().split())
s = a + b
S = str(s)
c = 0
matches = {'0':6,'1':2,'2':5,'3':5,'4':4,'5':5,'6':6,'7':3,'8':7,'9':6}
for d in S:
if d in matches.keys():
c += matches[d]
print(c)
|
989,579 | 200cdd1ac8abcd619da2de5a6c52c0ce7755c16d | """
多分支语句:
多分支:
if 表达式1:
表达式1成立执行的代码
elif 表达式2:
表达式2成立执行的代码
elif 表达式3:
表达式3成立执行的代码
else:
三个条件都不满足执行的代码
A[90,100]
B[80,90)
C[70,80)
D[60,69]
E < 60
跟电脑猜石头剪子布,打印输赢
1.计算机随机生成:0.石头 1.剪刀 2.布
ra... |
989,580 | 40d73e206fa2738c381b2ce3ad9be1c14c92ef38 | import os
import csv
fname1 = 'granite.rho_u.txt'
fname2 = 'granite.table.txt'
fnames = [fname1, fname2]
def returnReader(fname, delimiter):
with open(fname, 'r') as infile:
reader = csv.reader(infile, delimiter=delimiter)
return list(reader)
def removeOutput(oname):
if oname in os.listdir(os... |
989,581 | da68cc323c07bdbcd960de28dc743073cb157cc2 | import struct
packed = struct.pack('>i4sh', 7, b'spam', 8)
print(packed)
|
989,582 | 786bcc26874e9b14994f7f92323915459adc17ab | from openpyxl import load_workbook
wb = load_workbook('btc.xlsx', data_only = True)
ws = wb.active
values = []
for row in range(2, 460):
for column in "B":
cell_name = "{}{}".format(column, row)
values.append(ws[cell_name].value)
for string in values:
strings = str(string)
print strings... |
989,583 | 5d391c70c1988abac130cbd2eab0f064fae0261e | from django.urls import path,include
from .views import *
from django.conf.urls.static import static
from django.conf import settings
# routers=DefaultRouter()
# routers.register('listings/',Listing_view)
urlpatterns = [
path('listings/<int:pk>/',Listing_detail.as_view()),
# path('listings/<int:pk>/',Listing... |
989,584 | 63d0ca83d5d8a3a700413070e35a09e3997f70c4 | import os
import sys
from colorama import Fore
class Helper(object):
@staticmethod
def get_fg_colorcode_by_identifier(identifier):
if identifier == 'black':
return Fore.BLACK
elif identifier == 'cyan':
return Fore.CYAN
elif identifier == 'magenta':
re... |
989,585 | 91a0058709fa8ed988e762790f87bf8ad1130f2e | """
EXERCÍCIO 075: Análise de Dados em uma Tupla
Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre:
A) Quantas vezes apareceu o valor 9.
B) Em que posição foi digitado o primeiro valor 3.
C) Quais foram os números pares.
"""
def main():
pass
if __name__... |
989,586 | 9cf7c52ea5675d259eb60f7af771b2603d4b6410 | # -*- coding: utf-8 -*-
"""
Copyright(c) 2018 Gabriel Ramos Rodrigues Oliveira
"""
class No:
def __init__(self,item=None,proximo=None):
self.item = item
self.proximo = proximo
def __repr__(self):
return "No({})".format(self.item.__repr__())
def __str__(self):
r... |
989,587 | 9d9bcb66111b95b39086e4954e9d7227b54b2c76 | """
Tag: bit, string
Given a start IP address ip and a number of ips we need to cover n, return
a representation of the range as a list (of smallest possible length) of CIDR blocks.
A CIDR block is a string consisting of an IP, followed by a slash, and then
the prefix length. For example: "123.4... |
989,588 | 58cbd9c5b54d5e45c5ebd6ea591be3c0a1d96ada | from .memes import *
def setup(bot):
bot.add_cog(Memes(bot))
|
989,589 | 9e8767a3f020c80ea221884d8c3f34ed53c517a9 | #!/usr/bin/python
import re
import paramiko
def look():
FILE = '/opt/jboss-as-7.1.1.Final/standalone/configuration/standalone.xml'
r = re.compile('jndi.*pool')
for line in open(FILE):
if r.search(line):
print line.split()[1:3]
look()
|
989,590 | a5c59de9684795e3832835784e2ac2e8dc2bdd19 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 7 08:14:22 2017
@author: SHAHZAD
This file will select top 100 feature from benign and malware pmi value
"""
if __name__ == "__main__":
text_file = open("full_sorted_pmi_benign_out.txt", "r")
b_feature1 = text_file.readlines()
text_file.close()
text_file... |
989,591 | adf8485865964cf5c44fe24b60d2b9e23c14a44f | # Solitamos y almacenamos los números
print("Introduce un numero")
n1=int(input())
print("Escribe otro numero")
n2=int(input())
# Suma de los numeros
suma = n1+n2
## Imprimimos el resultado
## Importante: Hay que convertir el suma a String
print("La suma de ambos números es: "+str(suma))
|
989,592 | e7968a23bff3fc27e9a496fd66cdcc0e40193d64 | """
Section 2
Parallelism with MultiProcessing > multiprocessing(5) : Queue, Pipe
keyword : queue, pipe, Communication between processes
"""
from multiprocessing import Process, Pipe, current_process
from multiprocessing.process import parent_process
import time
import os
# 프로세스 통신 구현 : Pipe
# 부모-자식 프로세스간 1:1 연결
# 실행... |
989,593 | 8a08e791e832d2a687d1bdaae10a46fd0ab048d6 | # ============ Base imports ======================
from io import StringIO
from functools import partial
# ====== External package imports ================
import numpy as np
import psycopg2 as psy
# ====== Internal package imports ================
# ============== Logging ========================
import logging
from ... |
989,594 | 8ec0bb424b433beceb15295b62a3b62dae44b77b | from setuptools import setup
setup(
name='pyuptodate',
version='0.1.0',
author='Tarek Amr',
author_email='',
url='https://github.com/gr33ndata/pyuptodate',
packages=['pyuptodate'],
scripts=['pyuptodate/pyuptodate.py'],
license='LICENSE.txt',
description='Check all installed Python modules and update the... |
989,595 | dcea1e6c482057ba4fa5b0eedec45f91c7fbe570 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2017 DataONE
#
# Licensed under the Apache... |
989,596 | 3f6c3eae50dfea8e9f1298e0cf8121e898653eb8 | from django.test import TestCase
from main_app.models import Park
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
CREATE_PARK_URL = reverse('park:create')
def create_park(**params):
return Park.create_park(**params)
class PublicParkAPITests(TestCase... |
989,597 | 68df0fbd2be1fec5f7c20fcb5cb9c555629976f1 | from bisect import bisect_left,bisect_right
import string
dic = {c:[] for c in string.ascii_lowercase}
n = int(input())
s = list(input())
q = int(input())
for i,c in enumerate(s,start=1):
dic[c].append(i)
for i in range(q):
p,l,r = map(str,input().split())
if p =='1':
j = int(l)
if r == s[j-1]:
... |
989,598 | f8991a4cc5f673d31c9fc890d67610a0b992f404 | '''
Created on Apr 17, 2013
@package: ally core http
@copyright: 2012 Sourcefabric o.p.s.
@license: http://www.gnu.org/licenses/gpl-3.0.txt
@author: Gabriel Nistor
Provides HTTP specifications for indexes.
'''
from ally.core.impl.processor.render.json import createJSONBlockForIndexed, \
createJSONBlockForConten... |
989,599 | d5feac8cdf178e268812596bd00f438b3121bac8 | # -*- coding: UTF-8 -*-
# Copyright 2016 Red Hat, Inc.
# Part of clufter project
# Licensed under GPLv2+ (a copy included | http://gnu.org/licenses/gpl-2.0.txt)
"""stringiter-combine filter"""
__author__ = "Jan Pokorný <jpokorny @at@ Red Hat .dot. com>"
from itertools import chain
from ..filter import Filter
def st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.