text stringlengths 8 6.05M |
|---|
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame({
'n_min': [1,1,1,1,1,2,2,2,2,3,3,3,4,4,5],
'n_max': [1,2,3,4,5,2,3,4,5,3,4,5,4,5,5],
'F-m': [0.8373,0.5696,0.45,0.413,0.3945,0.6359,0.5978,0.578,0.5715,0.6849,0.6922,0.6929,0.6958,0.6917,0.5631]})
result = df.pivot(index=... |
from distutils.core import setup
setup(
name='regraph',
version='1.0',
description='Make graphs from standard input based on regular expression.',
author='Guilherme Starvaggi Franca',
author_email='guifranca@gmail.com',
scripts=['regraph'],
)
|
import socket
import json
import pickle
from io import BytesIO
class PSQClient:
def __init__(self, port):
self.port = port
def _send(self, connection, some_bytes):
message_size = str(len(some_bytes)).encode()
size_length = len(message_size)
connection.sendall(bytes([size_lengt... |
from django import forms
from django.forms import ModelForm
from classes.models import Restaurant, Food
# from crispy_forms.helper import FormHelper
# from django.validator import validate_slug
class AddRestaurantForm(ModelForm):
class Meta:
model = Restaurant
fields = ['restaurant_name','picture_... |
from flask import Flask, redirect, url_for
app = Flask(__name__)
#statis route
@app.route("/welcome")
def hellow():
return "Hello world!"
#dynamic route
@app.route("/<name>")
def printname(name):
return f"hello {name}!"
#redirect to another page if opened a page that is not for the user(say)
@app.route("/adm... |
#!/usr/bin/env python
'''
Let d(n) be defined as the sum of proper divisors of n
(numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a != b, then a and b
are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11... |
# Generated by Django 4.0.5 on 2022-08-20 11:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0018_time'),
]
operations = [
migrations.AddField(
model_name='livedata',
name='toGameT1',
f... |
"""
Save auto repair notes.
Created on 25.05.2017
@author: Ruslan Dolovanyuk
"""
import sqlite3
from drawer import Drawer
def setup(conn, cursor):
"""Create table in database."""
script = '''CREATE TABLE window (
id INTEGER PRIMARY KEY NOT NULL,
px INTEGER NOT NULL,
... |
from django.conf.urls import url
from django.urls import path
from . import views
app_name = "login_app"
urlpatterns = [
path('', views.home, name="home"),
path('signup/', views.signUp, name="signup"),
path('signin/', views.signIn, name="signin"),
path('signout/', views.signOut, name='signout'),
pa... |
#-*- coding=utf-8 -*-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_pagedown import PageDown
#from celery import Celery, platforms
import logging
import datetime
from datetime import timed... |
from .main import process_sql
# This function gets all of the payment records from the database
# and is used to handle searching and sorting so that only the records the user wants to see are fetched.
def get_payments(type_search, datetime_sorts, search_field, search_term):
parameters = ()
search = ''
# ... |
import requests
import json
import file_result.result
def getFileScanId(url,apikey,a,b):
# /file/scan
# /文件/扫描
# 上传并扫描文件
# 限制为32MB
params = {'apikey': apikey}
files = {'file': (a, open(b, 'rb'))}
response = requests.post(url, files=files, params=params)
my_scan_id = str(response.json()[... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 22 13:55:11 2019
@author: Joule
"""
from Aksjon import Aksjon
class EnkeltSpill:
"""Singelt spill"""
def __init__(self, spiller1, spiller2):
self.spiller1 = spiller1
self.spiller2 = spiller2
self.vinner = None
sel... |
import unittest
from pycolorizer import (
Color,
NoStyleFoundError,
InvalidStyleNameError,
RecursionInThemeError
)
class ColorTest(unittest.TestCase):
def setUp(self):
self.color = Color()
def test_given_string_should_apply_style(self):
self.assertEqual(
"\033[31mf... |
'''
This script will pass input values to a Boom Crane module to receive the
dynamic response of such a crane to the given parameters. It will
then plot the relevant results.
Created by: Daniel Newman
Date: 09-28-2016
'''
import warnings
warnings.simplefilter("ignore", UserWarning)
import sys
sys.path.append('/User... |
#!/usr/bin/env python3
# SPDX-License-Identifier: CC0-1.0
import sys
import urllib.request
import urllib.parse
import cgi
from collections import namedtuple
from typing import Optional, Tuple
COUNT_DNC = 44053
COUNT_PODESTA = 59028
COUNT_CLINTON = 33727
#USER_AGENT = 'Mozilla/5.0'
USER_AGENT = 'Mozilla/5.0 (Windows ... |
import json
import socket
import sys
import threading
import time
from flask import Flask
from flask_restful import Api, Resource, reqparse, abort
app = Flask(__name__)
api = Api(app)
"""REQUEST PARSING SECTION"""
"""Creates request parser for JSON data sent through requests"""
user_get_args = reqparse.RequestParser(... |
MAX_RESULTS = 10 # Max emails retrieved in a single list request
SCOPES = ["https://mail.google.com/"] # Full scope for read/write/modify/delete
AUTH_TOKEN = "token.json" # Oauth token that is generated after the first authentication flow
RETRIEVE_LABELS = ['INBOX', 'UNREAD'] # Labels fetched
CREDENTIALS_FILE =... |
from flask import Flask
app = Flask(__name__)
@app.route('/user/<username>')
def show_user_profile(username):
return "User {}".format(username)
@app.route('/post/<int:post_id>')
def show_post(post_id):
return "Post {}".format(post_id)
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
|
from management.models import appointment
from django.shortcuts import render,redirect
from django.contrib import messages
from django.contrib.auth.models import User,auth
from django.contrib.auth import authenticate,login,logout
from .forms import CreateUserForm
from django.contrib import messages
# Create your views ... |
import sys
from subprocess import Popen, PIPE
def insert_clickhouse(csv_file):
insert_clickhouse_cmd = 'cat ' + csv_file +' | clickhouse-client -h132.227.123.200 --query="INSERT INTO heartbeat.versioned_probes FORMAT CSV"'
insert_clickhouse_process = Popen(insert_clickhouse_cmd,
... |
class MapSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.cache = {}
def insert(self, key, val):
"""
:type key: str
:type val: int
:rtype: void
"""
self.cache[key] = val
def sum... |
"""
"""
import phantom.rules as phantom
import json
from datetime import datetime, timedelta
##############################
# Start - Global Code Block
def say(msg):
phantom.debug(msg)
phantom.comment(comment=msg)
def flatten_strlist(input_list):
def _recurse(input_list):
new_list = []
... |
from typing import Optional, Union
import numpy as np
from ._abstract import AbstractLinearProgram
from ._constraint import LinearConstraint
from ._equation import LinearEquation
from ._utilities import pad_right
class ObjectiveFunction:
def __init__(self, equation: LinearEquation, objective: str):
self... |
lista = [ ]
numero = int(input("Digite seu número: "))
contador = 0
while contador < numero:
if contador % 2 != 0:
lista.append(contador)
contador += 1
print("Os número ímpares são: ", lista)
|
#!/usr/bin/env python
'''
Program : lha2isa.py
Version : 1.0
Author : b.k.gjelsten@fys.uio.no
Description :
TO FIX
x Need to deal with the decays of antiparticles
o Note also the hack for the top mass ... maybe look up the value
o There are some negative widths ... (from slha file?)
o Finally do the EWSB paramet... |
import media
import fresh_tomatoes
import errno
import csv
def fetch_data_file():
file_path = "data/movie_data.csv"
print("Attempting to open file: "+file_path)
try:
file = open(file_path,"r") #open file for 'r' reading
except IOError as e:
if e.errno == errno.ENOENT:
retur... |
f = float(input("Enter degrees f°:"))
c = (f - 32) *9 /5
print("this is your degrees in c°", round( c, 2)) |
import enum
import Entry
class CategoryId(enum.Enum):
id_1 = 1,
id_2 = 2,
id_3 = 3,
id_4 = 4,
id_5 = 5,
id_6 = 6,
id_7 = 7,
id_8 = 8,
id_9 = 9,
id_10 = 10,
id_11 = 11,
id_12 = 12,
id_13 = 13,
id_14 = 14,
def build_category_description():
categories = {}
... |
from extensions import DatabaseConnection as db_conn
from .models import Event
class EventManager(db_conn):
def __init__(self):
pass
def deserialize(self, row):
return Event(*row)
def create(self, event):
query = f"""
INSERT
INTO Event (
C... |
##########################
#Strings deuxième partie #
#Auteur: Marlene Marchena#
##########################
message = "Bonjour tout le monde"
print(message)
text1 = "Bonjour"
text2 = 'tout le monde'
print(text1 + " " + text2)
#on peut faire des operation avec strings
print(text1 * 3)
print(len(message))
# print(mes... |
def tankvol(h, d, vt):
|
#!/usr/bin/python
class GrabzItWaterMark:
def __init__(self, identifier, xPosition, yPosition, format):
self.Identifier = identifier
self.XPosition = xPosition
self.YPosition = yPosition
self.Format = format |
# This file is only intended for development purposes
from kubeflow.kubeflow.ci import base_runner
base_runner.main(component_name="twa_tests",
workflow_name="twa-tests")
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-07-31 20:19
from __future__ import unicode_literals
from django.db import migrations
import image_cropping.fields
class Migration(migrations.Migration):
dependencies = [
('training', '0010_course_detail_bg'),
]
operations = [
... |
def name(a,*d):
if a==1 and d=="a" and g=="pass":
return g
else:
return a
def call(**args):
for i in args:
print(i)
a=call(name='aloukik',passd='a',pas='s')
if a==1:
print("accepted")
else:
print(a) |
"""
Utility functions for working with FASTA files. Includes various functions for
reading and writing FASTA files.
Written by Kevin Wu in Ortiz Lab, May 2015
"""
import genomeUtil as g
def writeFASTA(filename, header, sequence, trimHeaders = True, append = True):
# Allows us to deal with both file inputs and s... |
import time, datetime
class MyTimer ():
def __init__(self):
self.startTime = time.time()
def getNow(self, format):
return datetime.datetime.today().strftime(format)
def getTime(self):
return time.time() - self.startTime
|
class Question:
def __init__(self):
# print ("Constrctor created\n")
self.container1 = []
self.container2 = []
self.names = set()
def addContainer(self, container):
if len(self.container1) == 0:
self.container1.append(container)
elif len(self.contai... |
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from rest_framework import status
from rest_framework.parsers ... |
import os
# set a cron job to run the program
# open the music file
os.system("open /Users/rahul/Desktop/to_u.mp3")
# exit program
exit() |
# ___________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and
# Engineering Solutions of Sandia, LLC... |
#coding: utf-8
import numpy as np
import sys
from matplotlib.pyplot import plot
from matplotlib.pyplot import show
#exp() linespace()
N = int (sys.argv[1])
#N = 10
weights = np.exp(np.linspace(-1,0.,N))
weights /= weights.sum()
print "Weights :", weights
c = np.loadtxt('data.csv',delimiter =',',usecols=(6,),unpack ... |
#recebendo o input
texto = str(input("Digite um texto ou palavra: "))
#modificando o texto
primeira_letra = texto[0]
ultima_letra = texto[-1]
tamanho_texto = len(texto)
texto_invertido = texto[::-1]
texto_maiusculo = texto.upper()
texto_minusculo = texto.lower()
#apresentando os resultados
print("\n\nA primeira e últ... |
import pandas as pd
import torch
from PIL import Image
import os
from maskrcnn_benchmark.structures.bounding_box import BoxList
class giro(object):
def __init__(self,ann_file,root,transforms=None): #the size value controls how big the pictures we want to be
self.root= root # directory for pictures
... |
# encoding: utf-8
import hashlib
from datetime import datetime
from werkzeug import generate_password_hash, check_password_hash, cached_property
from flask import Blueprint, url_for, redirect, g, \
flash, request, current_app, render_template, send_from_directory, views, session
from flask.ext.login import login... |
N = int(input())
number = []
number=list(map(int, input().split()))[:N]
print(max(number)) |
from notesentry import NotesEntry
class NotesView:
'''
Wrapper for lotus.domino.View class
'''
def __init__(self,view):
self.view=view
self.known_entries = []
def _entrycollection_to_list(self,collection):
new_list=[]
entry = collection.getFirstEntry()
whil... |
import os
import configargparse
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
def create_config():
p = configargparse.getArgumentParser(default_config_files=[os.path.join(BASE_DIR, 'conf_local.ini'),
os.path.join(BAS... |
#!/usr/bin/env python
# ==================================================================================== #
#
# Copyright (c) 2017 Raffaele Bua (buele)
#
# 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... |
# Generated by Django 3.0.5 on 2020-05-05 08:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0003_character_armor_class'),
]
operations = [
migrations.RemoveField(
model_name='character',
name='weap... |
import numpy as np
import matplotlib.pyplot as plt
from skimage.util.shape import view_as_windows
import time
plt.rcParams.update(plt.rcParamsDefault)
plt.style.use('seaborn-deep')
def disp(loci, locj):
'''
Takes the coordinates of locations i and j and returns the euclidean distance between them
'''
s = locj -... |
# Generated by Django 3.2.5 on 2021-07-22 02:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('project', '0005_task_note'),
]
operations = [
migrations.AlterField(
model_name='task',
name='note',
fie... |
from auto_layer import auto_layer_core
import maya.cmds as cmds
class Core(object):
def create_depth_cone(self):
"""
Creates a visual Aid for large scale sets on DTX
Returns:None
"""
self.set_render_layer()
if cmds.objExists('DTX_Depth_Cone'):
cmds.dele... |
import nltk
from nltk import FreqDist
from nltk.corpus import PlaintextCorpusReader
import re
from nltk.collocations import *
from nltk import word_tokenize, pos_tag
from nltk.corpus import wordnet
from nltk.stem import WordNetLemmatizer
def alpha_filter(w):
# pattern to match a word of non-alphabetical character... |
# https://www.hackerrank.com/challenges/diagonal-difference/problem
def diagonalDifference(arr):
# Write your code here
# frist diagonal
n = len(arr)
m = len(arr[0])
diag1 = 0
diag2 = 0
for i in range(n):
diag1 = diag1 + arr[i][i]
for i in range(n):
m = m-1
diag2... |
from rfc3987 import parse
import socket
import re
import urllib2
class Validations:
def __init__(self, db, domain_config):
self.db = db
socket.setdefaulttimeout(30)
self.local_domain = domain_config.get('name', None)
def check_valid_domain(self, domain):
pattern = re.compile(
... |
__version__ = "2.3.0"
import abc
from enum import Enum
from typing import (
Dict,
Iterator,
List,
Tuple,
Union,
Any,
Optional,
Callable,
overload,
TypeVar,
Type,
)
import PyQt5.QtCore
import PyQt5.QtGui
import PyQt5.QtWidgets
MoVariant = Union[None, bool, int, str, List[Any... |
from .base_methods import BaseWebDriver
from .locators import LoginPageLocators, MainPageLocators
from .environment import ProdEnv
class LoginPage(BaseWebDriver):
def go_to_login_page(self):
self.find_and_click_button(*LoginPageLocators.LOGIN_PAGE)
def should_be_login_page(self):
# Check if ... |
from database_helper import Database
class StatsHelper():
def __init__(self):
self.database = Database()
print("Stats Helping initialising!")
#Used for content table
def select_all_employee(self):
result = self.database.fetch_all("SELECT * FROM employeedata")
return resul... |
from django.db import models
from datetime import datetime
from product import Product
class Service(Product):
class Meta:
db_table = 'services'
app_label = 'inventory'
|
from orun.views.dashboard import Dashboard
from orun.contrib import admin
@admin.register('test.dashboard')
class TestDashboard(Dashboard):
def get(self, request):
return '<dashboard>teste</dashboard>'
|
# from django.test import TestCase, Client
# from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework import status
class TestIndexView(APITestCase):
def test_index_view_status_code(self):
response = self.client.get('')
self.assertEqual(response.status_code... |
## Problem 16
def digitsum(n):
l=str(n)
somme=0
for i in range(len(l)):
somme+=int(l[i])
return somme
# print(digitsum(2**1000))
## Probelm 22
alphabet=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
def str_to_n... |
from crontab import CronTab
my_cron = CronTab(user='user')
my_cron.remove_all(comment='checkstatus')
my_cron.write()
|
def load_config(config_data):
if 'swift' not in config_data:
raise Exception("swift section is mandatory in the configuration")
required_parameters = ('auth_url', 'user_id', 'project_id', 'password', 'region')
if set(required_parameters) <= set(config_data['swift']):
pass
else:
... |
#!/usr/bin/env python
"""
From http://stefaanlippens.net/svnignorescript
"""
import optparse
import os
import subprocess
def svn_propget(svnprop, path):
"""Fetch a svn property of a file or directory."""
subproc = subprocess.Popen(
["svn", "propget", svnprop, path],
stdout=subprocess.PIPE
... |
# -*- coding: utf-8 -*-
import nysol._nysolshell_core as n_core
from nysol.mcmd.nysollib.core import NysolMOD_CORE
from nysol.mcmd.nysollib import nysolutil as nutil
class Nysol_Mnormalize(NysolMOD_CORE):
_kwd ,_inkwd,_outkwd = n_core.getparalist("mnormalize",3)
def __init__(self,*args, **kw_args) :
super(Nysol... |
import os
#如果该块中只有一条语句,则可以在同一行中指定它
if os.name == 'posix':
print('You are cool')
def say_hello():
return 'hello'
print(say_hello())
#清单理解
class Employee:
def __str__(self):
return self.name + str(self.salary)
def __init__(self,name,salary):
self.name = name
self.salary = sala... |
# generator.py
#
# This file is used to generate unique imagery from a trained vae mode
# It is required to run vae.py before this program can be used
#
# Dependancies
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from keras import backend as K
import sys... |
import pandas as pd
import numpy as np
from autumn.core.project import (
Project,
ParameterSet,
load_timeseries,
build_rel_path,
use_tuned_proposal_sds,
)
from autumn.calibration import Calibration
from autumn.calibration.priors import UniformPrior, TruncNormalPrior
from autumn.calibration.targets ... |
#!/usr/bin/python
# a is list, b is list
# l is list of combined with a before b
# then turn l to make b before a
l = []
a1 = 1
a2 = 6
b1 = 3 # a1 < b1 < a2
b2 = 10 # b2 > a2
aLen = a2 - a1
bLen = b2 - b1
lLen = aLen + bLen
for i in range(a1,a2):
l.append(i)
for i in range(b1,b2):
l.append(i)
def show(l=l,... |
from scipy.sparse import csr_matrix
from scipy.sparse import vstack
import networkx as nx
import cPickle
import numpy as np
import sys
import tensorflow as tf
import scipy.io as sio
class data(object):
def __init__(self, args):
self.dataset = args.dataset
self.all_x = self.read_attributes(args.att... |
from django.contrib import admin
from app01 import models
# Register your models here.
# shi123456
admin.site.register(models.Direction)
admin.site.register(models.Classification)
admin.site.register(models.Level)
admin.site.register(models.Video)
admin.site.register(models.Img) |
# -*- coding: utf-8 -*-
import re
import scrapy
from ..items import NewsLink
from scrapy_redis.spiders import RedisSpider
class VietnamNewsPulsSpider(RedisSpider):
name = 'vietnam_news_puls'
allowed_domains = ['www.vietnamplus.vn']
start_urls = [
# 'https://www.vietnamplus.vn/chude/bien-dong/205.v... |
from upm import pyupm_i2clcd as lcd
from upm import pyupm_led as Led
from upm import pyupm_temperature as T
from upm import pyupm_light as light_as_hum
from upm import pyupm_tsl2561 as upmTsl2561
import serial
import requests
import time
light_status=0
ir_end = time.time()
ir_finished = True
myLcd = lcd.Jhd1313m1(0, ... |
import hashlib
import datetime
class Block:
def __init__(self, previous_hash, data):
self.previous_hash = previous_hash
self.data = data
self.timestamp = datetime.datetime.now()
self.hash = self.compute_hash()
def compute_hash(self):
temp = hashlib.sha256()
temp.update(str(self.previous... |
'''
Faca um programa em Python que recebe tres
numeros e calcule sua media.
'''
# Recebe os numeros do teclado:
n1 = input ("Informe o primeiro numero: ")
n2 = input ("Informe o segundo numero: ")
n3 = input ("Informe o terceiro numero: ")
# Converte para numerico:
n1 = float (n1)
n2 = float (n2)
n3 = fl... |
import csv, argparse, sys
from collections import defaultdict
# Parse command-line arguments
parser = argparse.ArgumentParser(description="Counts the number of valid/invalid samples in a Tobii data file")
# The Tobii developer's guide suggests that samples
# with a validity code of 2 or higher should be
# considered ... |
import numpy as np
import os
import sys
import io
import random
import time
import tqdm
import hnswlib
import re
DIM=128
MAX_ITER = 30
CLUSTER_NUM = 150000
SIFT_FEATURES = 44039833
def count_sift_features(inputpath):
print('Read sift Features')
start_time = time.time()
non_decimal = re.compile(r'[^\d]+')... |
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT License.
"""
import os
import subprocess
import unittest
from mechanical_markdown import MechanicalMarkdown, MarkdownAnnotationError
from unittest.mock import patch, MagicMock, call
DEFAULT_TIMEOUT = 300
class MechanicalMarkdownTests(unittest.TestCas... |
from cutout import cleanup
cleanup()
|
# Generated by Django 2.2 on 2019-04-24 07:58
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('onlclass', '0034_auto_20190421_0925'),
]
operations = [
migrations.AddField(
mode... |
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
import django
django.setup()
from datetime import datetime
from polls.models import Question, Temperature
#from django.utils import timezone
import pyowm
import geopy
from geopy.geocoders import Nominatim
cities = ['New York','San Francisco','Boston','... |
#!/usr/bin/env python
# Fakelag.py - Auto Fakelag excempt for authenticated clients.
# Licensed under GPL3, Free Software etc etc
import weechat
import re
NAME = "Fakelag.py"
AUTHOR = "Ferus - irc.datnode.net #hacking"
VERSION = "1.0"
LICENSE = "GPL3"
DISC = "Auto Fakelag exempt script for clients who authenticate t... |
from unittest import TestCase
from tutnese import encode_duplicates, encode, decode
class TestTutnese(TestCase):
# Tests for encode_duplicates()
def test_encode_duplicates_empty_string(self):
self.assertEqual(encode_duplicates(""), "")
def test_encode_duplicates_pdf_string(self):
pdf_str... |
from data_structures.array import find_max
""" COUNT SORT
Time Complexity: O(n + maxval) - (can be maxval - minval)
Space Complexity: O(n + k) - len(out) and len(cum)
Notes:
1. Efficient when k < n.
2. Uses partial hashing to count occurence in O(1).
To determine:
1. Parallel... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: yuanzi
import turtle
import time
def main():
#设置一个画面
windows = turtle.Screen()
#设置背景
windows.bgcolor('pink')
#生成一个黄色乌龟
bran = turtle.Turtle()
bran.shape('turtle')
bran.color('red')
#开始你的表演
turtle.home()
turtle.dot()
for i in range(1,10):
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
s=raw_input()
l=0
ans1=''
ans2=''
for i in s:
if i.islower():
l+=1
ans1+=i.lower()
ans2+=i.upper()
if l*2>=len(s):
print ans1
else:
print ans2
|
"""
Python Wechaty - https://github.com/wechaty/python-wechaty
Authors: Huan LI (李卓桓) <https://github.com/huan>
Jingjing WU (吴京京) <https://github.com/wj-Mcat>
2020-now @ Copyright Wechaty
Licensed under the Apache License, Version 2.0 (the 'License');
you may not use this file except in compliance wit... |
mem = open('input.txt', 'r').read().rstrip().split(',')
def mint(nr):
if(type(nr) is str):
return int(nr)
else:
return nr
# len of mem: 678
addr = 0
while(True):
instruction = mem[addr]
opcode = instruction[-2:] if len(instruction) >= 2 else '0' + instruction
modes = [0, 0, 0]
i = 2
for m in reversed(in... |
from django.template.loader import render_to_string
from django.core.mail import send_mail
from django.conf import settings
def send_subscribe_mail(email, **kwargs):
subject= 'AMD Telecom'
html = render_to_string('subscribe.html')
send_mail(
subject=subject,
message='',
from_email=s... |
"""
Verify a SciToken from command-line inputs.
"""
import argparse
import scitokens
from scitokens.utils.errors import InvalidTokenFormat
from scitokens.utils.errors import MissingIssuerException
from scitokens.utils.errors import MissingKeyException
from scitokens.utils.errors import NonHTTPSIssuer
from scitokens.ut... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import chi2
class DataGenerator:
@staticmethod
def next(p1, p2):
click1 = 1 if (np.random.random() < p1) else 0
click2 = 1 if (np.random.random() < p2) else 0
return click1, click2
@staticmethod
def get_p_value(T):
determinant = T[0,0] *... |
number = eval(input('Enter a number: '))
if number >= 1 and number <= 20:
print(f'{number} is between 1 and 20')
else:
print(f'The number is not between 1 and 20') |
import json
import attr
import numpy as np
from scipy.ndimage import convolve
# from simulation.coordinates import Voxel
# from simulation.grid import RectangularGrid
from simulation.module import Module, ModuleState
from simulation.modules.geometry import GeometryState, TissueTypes
from simulation.molecule import Mo... |
from translationstring import TranslationStringFactory
_ = TranslationStringFactory('onegov.town')
|
from django.db import models
from user.models import User
from project_management.models import Project
# Drawings
class Plans(models.Model):
title = models.CharField(max_length=255)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
def __str__(self):
return self.title
class PlanO... |
import math
import pygame
class Player:
def __init__(self, x = 0, y=0, dx=0, dy=0, hp=0):
self.x = x
self.y = y
self.dx = dx
self.dy = dy
self.size = 30
self.hp = hp
self.playership = pygame.image.load('images/ship.png').convert_alpha()
... |
def greet(name):
print("This is out")
def say_hello():
print("My name is %s" % name)
return say_hello
ret = greet("Lechrond")
ret()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.