text stringlengths 38 1.54M |
|---|
import sys
import re
import numpy as np
class Crystal (object):
"""
Base class for all 2D crystals.
Every 2D crystal must be described using a 2D Bravais lattice and an atomic basis.
This class ignores the atomic basis and uses only the number of atoms inside the given unit cell.
Each 2D crystal is described ... |
from bs4 import BeautifulSoup
import bleach
import pickle
import sys
def generate_name(id):
return "fnust" + str(id)
def decrypt(val):
try:
if val[:5] == "fnust":
return int(val[5:])
except:
return None
if __name__ == "__main__":
data_path = sys.argv[1]
tmp_path = s... |
def minDistance(word1,word2):
distance = [[a for a in range(len(word1) + 1)] for b in range(len(word2) + 1)]
for i in range(1, len(word2) + 1):
distance[i][0] = distance[i - 1][0] + 1
for i in range(1, len(word2) + 1):
for j in range(1, len(word1) + 1):
if word2[i - 1] == word... |
# _*_coding:utf-8 _*_
import requests
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
# 这是目标url
# url = 'https://www.baidu.com/s?wd=python'
# 最后有没有问号结果都一样
url = 'https://www.baidu.com/s?'
# 请求参数是一个字典 即wd=python
kw = {'wd... |
class MaxHeap:
def __init__(self, heap, n):
self.H = heap
self.n = n
self.basicOperation = 0
def deleteMax(self):
self.H[1] = self.H[self.n]
self.H[self.n] = -1
self.n -= 1
k = 1
v = self.H[k]
heap = False
while heap != True and ... |
##-----------------------------
# Pychrash Course
# Eric Matthes
# Cap. 8 - Funções
# pets.py, p.195
##-----------------------------
# 8.3. Camiseta
def make_shirt(tam, msg):
"""Função para estampar uma camiseta."""
print('\nO tamanho da camiseta é ' + tam.title() + '.')
print('Sua mensagem deve ser: ' + m... |
#!/usr/bin/env python
def from_military_time(military):
suffix = ':00am' if military < 12 else ':00pm'
standard = 12 if military % 12 == 0 else military % 12
return str(standard) + suffix
|
import ika
import engine
class text:
blackbg = ika.Image("gfx\\blackbg.png")
def __init__(self, x, y, text):
self.x = x
self.y = y
self.fh = engine.font.height
self.alive = True
self.text = text
while self.alive == True:
self.Update()
self.Render()
ika.Input.Update()
ika.Video.S... |
from covidsim import Cell, Simulator, State
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def get_c(s):
if s == State.Normal:
return 'b'
elif s==State.Infected:
return 'r'
elif s==State.Recovered:
return 'g'
... |
#If on Windows to avoid fullscreen, use the following two lines of code
from kivy.config import Config
Config.set('graphics', 'fullscreen', '0')
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.core.audio import SoundLoader
from os ... |
from django.urls import path, include
from django.views.decorators.cache import cache_page
from .views import (
IndexView,
donation,
VideosView,
category_video,
VideoCategoryView,
AudiosView,
subscribe,
faq,
live_view,
odds_view,
privacy_policy,
tandc,
contac... |
# Generated by Django 3.1 on 2020-08-25 10:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0005_auto_20200825_1426'),
]
operations = [
migrations.AlterField(
model_name='video',
name='comments',
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-18 08:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Api',
... |
#!/usr/bin/env python3
"""
Little game for the Scroll HAT Mini.
"""
import math
import scrollphathd
import time
from gpiozero import Button
from random import random, shuffle
# ------------------------------------------------------------
print("""Scroll HAT Mini: rockfall.py
Dodge the falling rocks using the X and... |
#
from __future__ import division
import _config
import sys, os, fnmatch, datetime, subprocess
sys.path.append('/home/unix/maxwshen/')
import numpy as np
from collections import defaultdict
from mylib import util, compbio
import pandas as pd
# Default params
inp_dir = _config.OUT_PLACE + 'ill_a_align/'
NA... |
#!/usr/bin/env python3
class LogicGate:
def __init__(self, lbl):
self.label = lbl
self.output = None
def get_label(self):
return self.label
def get_output(self):
self.output = self.perform_gate_logic()
return self.output
class BinaryGate(LogicDate):
def __... |
import cv2
import numpy as np
import insightface
np.random.seed(123) # for reproducibility
def get_groundtruth(dataset):
"{frame_id: [template_id, x, y, w, h]"
frame_map = {}
# with open(dataset, 'r', encoding='utf-8') as csvreader:
with open(dataset, 'r') as csvreader:
all_data = csvreade... |
import pymongo
class Database(object):
URI = "mongodb://127.0.0.1:27017"
DATABASE = None
@staticmethod
def initialize(db_name):
client = pymongo.MongoClient(Database.URI)
Database.DATABASE = client[db_name]
@staticmethod
def insert(collection_name,data):
Database.DATAB... |
'''
峰值元素是指其值大于左右相邻值的元素。
给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。
数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。
你可以假设 nums[-1] = nums[n] = -∞。
示例 1:
输入: nums = [1,2,3,1]
输出: 2
解释: 3 是峰值元素,你的函数应该返回其索引 2。
示例 2:
输入: nums = [1,2,1,3,5,6,4]
输出: 1 或 5
解释: 你的函数可以返回索引 1,其峰值元素为 2;
或者返回索引 5, 其峰值元素为 6。
'''
class Solution:
... |
import numpy as np
import cv2
import imutils
from collections import deque
orange_lower=(5,134,125)
orange_upper=(255,255,255)
pts=deque()
cap=cv2.VideoCapture(0)
while True:
ret,frame=cap.read()
frame=imutils.resize(frame,width=600)
blur=cv2.GaussianBlur(frame,(11,11),0)
hsv=cv2.cvtColor(frame,cv2.... |
#!/usr/bin/env python
# coding: utf-8
import enlighten
import numpy as np
import pandas as pd
import seaborn as sns
import pingouin as pg
import matplotlib.pyplot as plt
from os.path import join, exists
from sklearn.experimental import enable_halving_search_cv
from sklearn.model_selection import HalvingGridSearchCV, ... |
import argparse
import os
import pickle
import sys
from argparse import ArgumentParser
import torch
from torch.nn.parallel import DataParallel, DistributedDataParallel
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import custom_datasets
import models.custom
import models.mobilen... |
__all__ = ()
from re import compile as re_compile, escape as re_escape
from hata.ext.slash import InteractionResponse
from ...bots import SLASH_CLIENT
from .builders import build_components, build_content, process_entries
from .constants import (
CUSTOM_ID_CLOSE, CUSTOM_ID_PAGE_BASE, CUSTOM_ID_PAGE_NEXT_DISABLE... |
from setuptools import setup
setup(
name="client_app",
version="1.0",
description="client",
author="Vladimir Novikov",
author_email="vovasnew@mail.ru",
install_requires=[
"PyQt5==5.15.4",
],
include_package_data=True,
packages=["src"],
)
|
##
# wrapping: A program making it easy to use hyperparameter
# optimization software.
# Copyright (C) 2013 Katharina Eggensperger and Matthias Feurer
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Found... |
import argparse
def argument():
parser = argparse.ArgumentParser(description = '''
Generates monthly averaged files
''',
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument( '--inputdir', '-i',
type = str,
... |
from django.db import models
# Create your models here.
class News(models.Model):
objects = models.Manager()
title = models.TextField('TITLE', max_length=255, unique=True)
content = models.TextField('CONTENT', blank=True)
company = models.CharField('COMPANY', max_length=50,blank=True)
saved_time ... |
#Write a function called most_oscars, which takes in one
#parameter, a dictionary. This dictionary maps names to the
#number of Academy Awards for which they have been nominated.
#This function should return a tuple containing the name and
#number of nominations for the person who has the most
#nominations.
#
#You may ... |
import os
def writeFile(path, writeMethod, line):
with open(path, writeMethod) as f:
f.write(line)
path = r"C:\Users\Lenovo\Desktop\毕业论文\毕业论文数据\空气质量.txt"
keepPath = r"C:\Users\Lenovo\Desktop\python学习(公司)\文件读写\练习"
with open(path,"r") as f:
# 将第一行的标题省略,让描述符跳到第二行
f.readline()
# 循环遍历读取的readlines... |
#global_x, global_y, global_z, px,py,pz,time
#df_all['global_z']>4175.0027)and(df_all['global_z']<4175.003)and(np.sqrt(df_all['global_x']**2+df_all['global_y']**2)<120
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from matplotlib.backends.bac... |
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
"""
1 2 3 4 | num1 x
| 5 6 7 8 num2 y
xmax = 1 xmin = 2
ymax = 7 ymin = 8
... |
# def: numbers- numerical data type that can be used to perform calculations in python
# def: Strings- immutable objects used to output text o the screen in python
# def: list - objects used to hold an ordered pair of data such as integers, decimals and strings. can be changed
# def: tuples- data object used to store a... |
import json
import time
from jinja2 import Template
TEMPLATE = Template(
' async with ctx.transaction("Request {{method}} {{url}}"):\n'
" resp = await ctx.browser.{{method}}(\n"
" '{{url}}',\n"
" headers={{headers}},\n"
" {{json}}"
" )\n"
... |
n1 = int(input("enter no1"))
n2 = int(input("enter no2"))
n3 = int(input("enter no3"))
def greatest(n1,n2,n3):
if n1>n2:
if n1>n3:
return n1
else:return n3
elif n2>n3:
return n2
else:return n3
print(greatest(n1,n2,n3))
|
import requests, json, turtle
iss = turtle.Turtle()
def setup(window):
global iss
window.setup(1000, 500)
window.bgpic('earth.gif')
window.setworldcoordinates(-180, -90, 180, 90)
turtle.register_shape('iss.gif')
iss.shape('iss.gif')
def move_iss(lat, long):
global iss
iss.hideturtle()... |
__description__="Unpickle contact map"
def __pkl_to_map(pkl_input_filename,matrix_output_filename):
import pickle
matrix_out_file=open(matrix_output_filename,'wt')
with open(pkl_input_filename,'rb') as f:
matx = pickle.load(f)
matx_size=len(matx)
for i in range(matx_si... |
import numpy as np
from Tkinter import *
class Paint:
def paint(self, event):
x1, y1 = (event.x - 1), (event.y - 1)
x2, y2 = (event.x + 1), (event.y + 1)
if(x1 > 0 and x2 < self.width and y1 > 0 and y2 < self.height):
self.cv.create_rectangle(x1, y1, x2, y2, fill='black', widt... |
from django.shortcuts import render,get_object_or_404,redirect
from . import models
from . import forms
from django.contrib import messages
from django.utils import timezone
from django.urls import reverse,reverse_lazy
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_requir... |
def get_plans_by_user(username,db_connection):
"""Returns a list of plans for a username
Args:
username (string): logged in username
db_connection (string): sqlite 3 connection
Returns:
list of plan names (strings)
"""
query = "SELECT name FROM Plan WHERE username = :userna... |
# You can add to this file in the editor
import pyotp
import sqlite3
import hashlib
import uuid
from flask import Flask, request
app = Flask(__name__)
db_name = 'test.db'
@app.route('/')
def index():
return 'Welcome to the hands on lab for an evolution of password systems!'
if __name__ == '__main__':
app.r... |
#!/soft/packages/python/2.6/bin/python
import argparse
import json
import os
import shutil
import sys
import time
def main():
parser = argparse.ArgumentParser(description='program for setting a variable in the control api')
parser.add_argument('subsystem', metavar='subsystem',
help="This is... |
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rekrutacja.settings')
app = Celery('rekrutacja',
broker='amqp://localhost',
backend='rpc://',
include=['skaner.tasks'])
|
from django.contrib import admin
from django.forms import CheckboxSelectMultiple
from .models import MainFacility, Service, HotelFacility, RoomFacility,\
Hotel, RoomPrice, HotelImgs, UserComment
import xadmin
from django import forms
class HotelImgInline(object):
model = HotelImgs
extra = 1
class RoomPri... |
# Generated by Django 2.2 on 2019-04-06 23:34
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('food_poll', '0007_auto_20190407_0217'),
]
operations = [
migrations.AlterFie... |
gifdir = "D:/Projects/python/Gifs/"
from PIL.ImageTk import PhotoImage
from tkinter import *
win = Tk()
img = PhotoImage(file=gifdir + "1.gif")
can = Canvas(win)
can.pack(fill=BOTH)
can.create_image(2, 2, image=img, anchor=NW) # координаты x, y
win.mainloop()
|
#!/usr/bin/env python
import os
import csv
import random
import string
import json
# uses os.getcwd() to define the user's working directory
def get_file_path(filename):
dir_path = os.getcwd()
file_path = os.path.join(os.getcwd(), filename)
return file_path
print "What is the name of your csv? Be sure to include... |
# coding: utf-8
# Copyright (C) 2016 UKP lab
#
# Author: Daniil Sorokin (ukp.tu-darmstadt.de/ukp-home/)
#
import nltk
np_grammar = r"""
NP:
{(<NN|NNS>|<NNP|NNPS>)<NNP|NN|NNS|NNPS>+}
{(<NN|NNS>+|<NNP|NNPS>+)<IN|CC>(<PRP\$|DT><NN|NNS>+|<NNP|NNPS>+)}
{<JJ|RB|CD>*<NNP|NN|NNS|NNPS>+}
{<NNP|NN|NNS|NNPS... |
# coding: utf-8
import urllib
import contextlib
import lxml.html
def get_menus():
url = 'http://www.hsd.co.kr/lunch/lunchList.html'
with contextlib.closing(urllib.urlopen(url)) as u:
html = u.read()
return parse_menus(html)
def parse_menus(html):
root = lxml.html.fromstring(html)
for na... |
##########################################################
## ##
## grammar lesson 1: first person becomes second person ##
## ##
##########################################################
######################... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 7 11:44:56 2019
@author: elina
"""
""" Lesson 11 is about printing values, asking for user input and storing input
to do operations with it.
Note: functions were not part of the lesson, but made testing easier."""
# creates a (double) line space
space = "\n"
def prin... |
from django.db import models
class Whitelist(models.Model):
id = models.IntegerField(primary_key=True)
msisdn = models.CharField(max_length=15)
active = models.IntegerField(max_length=1)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(null=True, blank=True)
... |
a=int(input("Enter a number:"))
num_list=[]
for num in range(1,(a)*2):
if (num%2)!=0:
num_list.append(str(num))
print(','.join(num_list))
|
# solution to https://www.hackerrank.com/challenges/maximum-element
n = int(input())
stack = []
size = 0
for i in range(n):
cmd = input().split(" ")
if cmd[0] == '1':
val = int(cmd[1])
if size == 0:
item = [val, val]
else:
m = max(val, stack[size-1][1])
... |
import json
from multiprocessing import Pool
from urllib.parse import quote_plus
import requests
from retrying import retry
from sentry_sdk import capture_exception
from concertowl.apis.events import filter_events, unique_collected_events
from eventowl.settings import SENTRY_DSN
API_URL = 'https://rest.bandsintown.c... |
# 정수 N개로 이루어진 수열 A와 정수 X가 주어진다. 이때, A에서 X보다 작은 수를 모두 출력하는 프로그램을 작성하시오.
N, X = map(int, input().split())
A = list(map(int, input().split()))
for i in range(N): #왜 0, N-1은 안되는 것인가?????????
if A[i] < X:
print(A[i], end=" ") |
from pwn import *
from Exrop import Exrop
binname = "/lib/x86_64-linux-gnu/libc.so.6"
libc = ELF(binname, checksec=False)
open = libc.symbols['open']
read = libc.symbols['read']
write = libc.symbols['write']
bss = libc.bss()
rop = Exrop(binname)
rop.find_gadgets(cache=True)
#print("func-call gadgets 0x41414141(0x20,... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import sklearn as sk
... |
#!/usr/bin/python
import sys
if len(sys.argv) == 1:
print 'input grep expression'
sys.exit(1)
import commands,os
user=os.environ['USER']
grep=sys.argv[1]
list=commands.getstatusoutput("ps -ewf |grep '%s'" % grep)[1].split('\n')
for item in list:
username,pid = item.split()[0:2]
if username == user:
print userna... |
import math
def solution(arr):
answer = 0
i=1
arr.sort()
# lcm = (a*b) / gcd
# gcd = (a*b) / lcm
#print(arr[0]*arr[1]/math.gcd(arr[0],arr[1])) >최소공배수
while(True):
answer=0
answer=arr[-1]*i
for j in arr:
if(answer%j==0):
continue
... |
#!/usr/bin/env python
# coding:utf-8
"""
162. 寻找峰值
难度
中等
峰值元素是指其值大于左右相邻值的元素。
给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。
数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。
你可以假设 nums[-1] = nums[n] = -∞。
示例 1:
输入: nums = [1,2,3,1]
输出: 2
解释: 3 是峰值元素,你的函数应该返回其索引 2。
示例 2:
输入: nums = [1,2,1,3,5,6,4]
输出: 1 或 5
解释: 你的函数可以返回索引 1... |
# The main example from README: fetch multiple properties from the page
from pprint import pprint
from wikipedia_ql import media_wiki
wikipedia = media_wiki.Wikipedia(cache_folder='tmp/cache')
pprint(wikipedia.query(r'''
from "Guardians of the Galaxy (film)" {
page@title as "title";
section[headi... |
import sys
src_directory = '../../../'
sys.path.append(src_directory)
import src.model
import src.solvers
import src.physical_constants
import pylab
import dolfin
dolfin.set_log_active(True)
theta = pylab.deg2rad(-3.0)
L = 100000.
H = 1000.0
a0 = 100
sigma = 10000
class Surface(dolfin.Expression):
def __init__(... |
from django.conf.urls import url
from .views import UserApiCreateView, UserApiUpdateView, UserApiDetailListView
urlpatterns = [
url(r'^$', UserApiDetailListView.as_view(), name='user_list'),
url(r'^create/$', UserApiCreateView.as_view(), name='user_create'),
url(r'^(?P<pk>\d+)/update/$', UserApiUpdateView.... |
#
# @lc app=leetcode id=212 lang=python3
#
# [212] Word Search II
#
# @lc code=start
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
trie = {}
for word in words:
t = trie
for w in word:
t = t.setdefault(w, {})
... |
from net.yolo_top import yolov3
import numpy as np
import tensorflow as tf
from net.config import cfg
from PIL import Image, ImageDraw, ImageFont
from predict.draw_box import draw_boxes
import matplotlib.pyplot as plt
import os
class YOLO_PREDICT:
def __init__(self, gpu = "0"):
o... |
# coding: utf-8
from __future__ import unicode_literals
from yargy import (
rule,
or_
)
from yargy.interpretation import fact
from yargy.predicates import gram
from yargy.pipelines import morph_pipeline
from .name import (
NAME,
SIMPLE_NAME
)
Person = fact(
'Person',
['position', 'name']
)
... |
"""
Authors: Liu, Yuntian
Murphy, Declan
Porebski, Elvis
Tyrakowski, Bartosz
Date: March, 2016
Purpose: Machine Learning Team Project.
Generalised Machine Learning Models:
1. Linear Regression.
2. Ridge Regression.
3. Lasso.
... |
import sys
H, W = map(int, input().split())
a = [[str(c) for c in l.strip()] for l in sys.stdin]
ans = "No"
def check(x, y):
if(x<0 or x >= H or y<0 or y>=W):
return
else:
search(x, y)
def search(x,y):
if(a[x][y] == "#" or a[x][y] == "1"):
return
elif(a[x][y] == "g"):
global ans
ans = "Yes"
a[x][y] = "1... |
password = 'a123456'
x = 3
while x > 0:
x = x - 1
pw = input('Login Password: ')
if pw == password:
print('Login Success')
break
else:
if x > 0:
print('Wrong Password. You have', x , 'chance left')
else:
print('Login Fail')
|
#!/usr/bin/python
# coding: utf8
import geocoder
location = 'Ottawa, Ontario'
ottawa = (45.4215296, -75.6971930)
def test_arcgis():
g = geocoder.arcgis(location)
assert g.ok
osm_count, fields_count = g.debug()[0]
assert osm_count == 0
assert fields_count > 1
def test_arcgis_reverse():
g = g... |
#
# Run workflows according to main etlconf
#
#
# to update bq_run_script to replace more than on pair of project-dataset
#
#
import os
import sys
import getopt
import json
import datetime
# ----------------------------------------------------
# default config values
# To override default config values, copy the k... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("EXOSinglePhoSkim")
process.load("FWCore.MessageService.MessageLogger_cfi")
process.MessageLogger.cerr.FwkReport.reportEvery=cms.untracked.int32(1000);
process.options = cms.untracked.PSet(
wantSummary = cms.untracked.bool(True)
)
process.maxEvents... |
import airflow,os
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.python_operator import PythonOperator
from datetime import timedelta
default_args = {
'owner':'airflow',
'depends_on_past':False,
'start_date':airflow.utils.dates.days_ago(1),
'retr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# coding: utf8
import os
import itertools
import pytest
import time
from allure_commons.types import AttachmentType
from selene.api import *
import selene
import allure
from selene import browser
from selene import config
from selene.browsers import BrowserName
from selene... |
import tensorflow as tf
import numpy as np
import time
K=5
MAX_ITERS = 1000
def clusterize(batch):
start = time.time()
n = len(batch)
dim = len(batch[0])
print batch
points = tf.placeholder(tf.int32, [n,dim])
cluster_assignments = tf.Variable(tf.zeros([n], dtype=tf.int64))
# Use K r... |
from django.urls import path
from User import views
from rest_framework_jwt.views import obtain_jwt_token
app_name = 'user'
urlpatterns = [
path('register/', views.UserRegisterView.as_view()),
path('login/', views.UserLogingView.as_view()),
path('jwt-login/', obtain_jwt_token), # 会返回一个token,如果在s... |
# https://guoruibiao.gitbooks.io/effective-python/content/shi_yong_none_he_wen_dang_shuo_ming_dong_tai_de_zh.html#
import json
def decode(data, default={}):
try:
return json.loads(data)
except ValueError:
return default
def decode2(data, default=None):
"""Load JSON data from string.
... |
# https://programmers.co.kr/learn/courses/30/lessons/60057
# ababcdcdababcdcd
# 압축 단위를 처음부터 정하고 시작하기 때문에 코드가 짧았던 문제. 실제 정답 코드말고 주석 처리된 코드는 step이 정해져 있지 않고
# 해당 문자열 패턴이 압축할 수 있는 패턴이면 압축을 실행함. 예를 들어 xabab의 경우 정답 코드로는 압축이 안 되지만
# 주석처리된 코드로는 x2ab로 압축이 가능하다. 그 외에는 정답으로 제출한 코드와 깃헙에 올라온 정답 코드의 로직이 거의 같다.
# def solution(s):
... |
#print integer number either using %d
myWeight=54.9
print("My lucky number is %f" %myWeight)
#or using "{0:d}".format(luckyNumber)
print("My lucky number is {0:f}".format(myWeight))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 10 13:13:07 2020
@author: marc
"""
from __future__ import print_function
import os
import torch
import torch.multiprocessing as sp
from envs import create_atari_env
from app import ActorCritic
from testing import Testing
from train i... |
import tensorflow as tf
print(tf.__version__)
import tensorflow as tf
import tensorflow_addons as tfa
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
from imutils import paths
import os
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_te... |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
import socket, time
import tf
from geometry_msgs.msg import Point, PoseStamped
from geometry_msgs.msg import Twist
import rospy
from mavros_msgs.msg import *
from mavros_msgs.srv import *
from nav_msgs.msg import *
from tf.transformations import *
from gazebo_... |
"""
Chef is teaching a cooking course. There are N students attending the course, numbered 1 through N.
Before each lesson, Chef has to take attendance, i.e. call out the names of students one by one and mark which students are present. Each student has a first name and a last name. In order to save time, Chef wants t... |
#Import Modules
import discord
from discord.ext import commands
import random
#Cog Setup
class Decks(commands.Cog):
def __init__(self,client):
self.client = client
self.setting_newdeck = ["1 h","2 h","3 h","4 h","5 h","6 h","7 h","8 h","9 h","10 h","11 h","12 h","13 h","1 d","2 d","3... |
'''#Subtask 1
t=int(input())
for I in range(t):
n=int(input())
sum1=0
sum1+=n
for j in range(1,(int(n)//2)+1):
if(n%j==0):
sum1+=j
print(sum1)'''
#Printing all the divisors
#Subtask 2 - Observed patern of pairs
from math import sqrt
t=int(input())
for I in range(t):... |
x = 23
x += 1
print(x)
x -= 4
print(x)
x *= 5
print(x)
x //= 4
print(x)
x /= 5
print(x)
x **= 2
print(x)
x %= 5
print(x)
greeting = "Good "
greeting += "morning"
print(greeting)
greeting *= 5
print(greeting)
print()
number = 5
multiplier = 8
answer = 0
for i in range(mult... |
from rest_framework import viewsets
from django.utils.datastructures import MultiValueDictKeyError
from rest_framework.response import Response
from random import randint
from django.db.models import Q
from django.contrib.auth.models import User, Group
from .serializers import *
from .models import *
# Admin View
cl... |
# Program to display average of given positive numbers
total = 0
count = 0
while True:
num = int(input("Enter a number [0 to stop] :"))
if num == 0:
break # Terminate loop
if num < 0:
continue
total += num
count += 1
print("Average = ", total / count) |
"""empty message
Revision ID: 2eaba3ac57e4
Revises: 76e53bf2dfd4
Create Date: 2018-10-08 15:43:04.972131
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '2eaba3ac57e4'
down_revision = '76e53bf2dfd4'
branch_labels = None
depe... |
# npm install --save bcrypt
# npm install --save jsonwebtoken
# logar, checar, inserir, excluir
# db.posts.remove( {"_id": ObjectId("60df6e64d83fe730142c7090")}) //excluir um item por ID |
import scrapy as sc
#// *[ @ id = "qt0324253"] / div[1] / p / text()
class matrixQuotes(object):
name="qoutes"
start_urls=[
'https://www.imdb.com/title/tt0133093/quotes',
]
def parse(self, response):
for quote in response.css('div.list'):
print(quote) |
user = dict({
'Cutesexyrobutts': {
"Java": 3.6,
"Python": 4.5,
"OpenGL": 2.3,
"JS": 4.3,
"Flutter": 5.0,
},
"Ishikey": {
"Java": 1.6,
"Python": 2.5,
"OpenGL": 4.3,
"JS": 2.3,
"Flutter": 1.0,
},
"MUK": {
"Java": 2... |
print('Bem Vindo ao calculador de médias!')
nome = (input('digite seu nome: '))
nota1 = float(input('digite sua primeira nota: '))
nota2 = float(input('digite sua segunda nota: '))
nota3 = float(input('digite sua terceira nota: '))
nota4 = float(input('digite sua quarta nota: '))
media = (nota1 + nota2 + nota3 + nota... |
import os
import itertools
import numpy as np
import matplotlib.pyplot as plt
SRC_DIR = os.path.dirname(os.path.realpath(__file__))
ROOT_DIR = os.path.abspath(os.path.join(SRC_DIR, os.pardir))
DATA_DIR = os.path.join(ROOT_DIR, "data")
# Make sure the directories exist
for directory in [DATA_DIR]:
if not os.path... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import os.path
import tornado.ioloop
from tornado.web import Application
import motor
from myredis import MyRedis
import uuid
from views import *
from tornado.options import define, options, parse_command_line
define("port", default=8888, help="run on the given port", type=int)
define("mongo_host", default="localhost... |
# -*- 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 ... |
# 指定需要导出的模块
__all__ = ['c7']
# 模块初始化
a = 'This is __init__.py file'
print(a)
import sys
import datetime
import io
|
# -*- coding: future_fstrings -*-
# Copyright 2018 Brandon Shelley. 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
#
#... |
from matplotlib import pyplot as plt
import numpy as np
plt.style.use("fivethirtyeight")
print(plt.style.available)
ages_x = [18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35
]
x_indexes=np.arange(len(ages_x))
width=0.2
print(x_indexes)
py_dev_y = [20046, 17100, 20000, 24744, 30500, 37... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.