text
stringlengths
8
6.05M
#!/usr/bin/env python # Code for converting wind sensor data to world frame import rospy from geographic_msgs.msg import Vector3 from geographic_msgs.msg import GeoPose class Converter: def __init__(self): self.wind_sub = rospy.Subscriber('/crw_wind_pub', Vector3, self.wind_callback) self.pose_sub = rospy.Su...
import sys sys.path.insert(0, '') from complex_labeller import Complexity_labeller model_path = '../cwi_seq.model' temp_path = '../temp_file.txt' model = Complexity_labeller(model_path, temp_path) import readability_v_ks nlp = readability_v_ks.spacy.load("en_ner_bc5cdr_md") nlp.add_pipe('readability') from nltk.co...
from django.contrib import admin class NullableTimestampFilter(admin.SimpleListFilter): """ Base class for Admin list filters which define whether a datetime field has a value or is null """ # Title displayed on the list filter URL title = "" # Model field name: parameter_name = "" ...
import random def pickN(N): amount = random.randint(0,N) nums = range(0,N+1) numb = [] for idx, n in enumerate(nums): n = random.randint(0,N) if n not in numb: numb.append(n) if idx > amount: break print sorted(numb) if __name__ == "__mai...
# -*- coding: utf-8 -*- ########################################################################### ## Python code generated with wxFormBuilder (version Feb 26 2014) ## http://www.wxformbuilder.org/ ## ## PLEASE DO "NOT" EDIT THIS FILE! ########################################################################### impo...
import socket def Main(): s = socket.socket() host = "127.0.0.1" port = 8000 s.bind((host, port)) s.listen(1) stream, address = s.accept() print "Connection from the address: " + str(address) while True: data = stream.recv(1024) if not data: break ...
from django.http import HttpResponse from django.shortcuts import render import operator def home(request): #ls=["Rakib Hossain Rifat", 24, 'AUST'] return render(request,'home.html') def Count(request): #getting the text from text input via url input_text=request.GET['input_text'] #print(input_tex...
#!/usr/bin/env python # standard library import os # external from scipy.constants import golden import matplotlib.pyplot as plt # local import utils paths = utils.config_paths() params = {'backend': 'ps', 'axes.labelsize': 8, 'axes.titlesize': 8, 'font.size': 10, 'legend.f...
import random import sys print("""DataBase 12月考査 v1.1.1 """) J = ["その自動車修理工場は1時間の労働につき50ドル請求する。", "彼は事務員の仕事に就いた。", "私たちの最初の仕事は情報を集めることだ。", "私の職業は建築家だ。", "あなたの名前、住所、職業を述べてください。", "新郎新婦は馬車でやって来た。", "あなたの私物を航空貨物で送ってあげましょう。", "その飛行機は燃料を満載していた。", "その運転手は運転中に眠り込んだに違いない。", "昨夜、雨が激しく降った。", "私は君の言うことがほとんど聞こえなかった。", "ちょうどそのとき...
# Coroutine -> 단일 스레드, async하게 동작 (제어권, race condition 처리) # Combining Coroutines with Threads and Process -> non blocking 제공해주기 위해서 import asyncio import timeit import threading from urllib.request import urlopen # block from concurrent.futures import ThreadPoolExecutor # 실행 시작 시간 start = timeit.default_timer() ur...
#!/usr/bin/env python """Restore Pure Storage Volumes Using python""" # usage: ./restorePureVolumes.py -c mycluster -u myusername -a mypure -v myserver_lun1 -v myserver_lun2 -p restore- -s -0410 # import pyhesity wrapper module from pyhesity import * from datetime import datetime # command line arguments import argp...
import base64 import io import docx from flask import request from templatemanager.app import app from templatemanager.utils.handle_api import handle_response META_SUCCESS = {'status': 200, 'msg': '模板生成成功!'} META_ERROR_NOT_EXIST = {'status': 404, 'msg': '生成失败,该模板不存在!'} # @app.route('/template/download', methods=['...
import os import tensorflow as tf import cnn_vgg16 tf.logging.set_verbosity(tf.logging.INFO) DATA_DIRECTORY = os.path.join('DATA', 'Img_compressed') ANNOTATION_FILE = os.path.join('DATA', 'Anno', 'list_attr_img.txt') SIZE = 224 SAMPLE_ATTRIBUTE_IMG_FILE_TRAIN = "sample_attribute_img_train.txt" SAMPLE_ATTRIBUTE_IMG_...
# Generated by Django 3.0.7 on 2020-07-02 02:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Risk_project_ufps', '0004_auto_20200701_2137'), ] operations = [ migrations.AlterField( model_name='gerentes', name=...
from behave import When, Step @When("I enter email and correct password") def step_impl(context): context.authentication_page.fill_login_form("current_password") @When("I enter email and incorrect password") def step_impl(context): context.authentication_page.fill_login_form("incorrect_password") @Step("I...
from flask import jsonify, request from . import api from .exception import ServerException from ..models.campaign import Campaign from ..schemas.campaign import campaign_schema, campaigns_schema @api.route('/campaigns', methods=['GET']) def get_campaigns(): try: campaigns = Campaign.objects data...
from concurrent.futures import ProcessPoolExecutor import json import random import requests from bs4 import BeautifulSoup from django.conf.urls import url from django.contrib import admin from django.contrib.admin.templatetags.admin_static import static from django.http import HttpResponseRedirect from django.contrib....
import unittest import asyncio class AsyncioHelloWordTest(unittest.TestCase): def setUp(self): self.loop = asyncio.new_event_loop() asyncio.set_event_loop(None) def tearDown(self): self.loop.close() def test_dumb(self): async def func(): self.assertEqual(42, 4...
# Program to sort alphabetically the words form a string # Take input from the user my_str = input("Enter a string: ") # breakdown the string into a list of words words = [word.lower() for word in my_str.split()] # sort the list words.sort() # display the sorted words print("The sorted words are:") for word in wor...
# tests are considered passing so long as no error escapes the function # def test_1(): # print("Hello test 1 ") # # def test_2(): # print("Hello test 2") # x = 90/0 # # def test_3(): # print("Hello test 3") # assert False # the ONLY thing the assert key woud does is check that some value is True #...
from django.core.urlresolvers import reverse from django.db.models import Q from django.views.generic.base import RedirectView from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.contrib.me...
from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.index), url(r'^process$', views.process), url(r'^display$', views.display), url(r'^refresh$', views.refresh) ]
#!/usr/bin/python import os import subprocess search_str = os.getenv("COG_ARGV_0") opt_all = os.getenv("COG_OPT_ALL") opt_stats = os.getenv("COG_OPT_STATS") opt_numbers = os.getenv("COG_OPT_NUMBERS") # Add options if they are set netstat_cmd = ["/usr/sbin/netstat"] if opt_all == "true": netstat_cmd.append("-a") ...
import sys, subprocess, os base = sys.argv[1] major, minor, feature, build = [int(x) for x in sys.argv[2:6]] sha = subprocess.getoutput("git -C ../.. rev-parse --verify HEAD") dirty = bool(subprocess.getoutput("git -C ../.. status --porcelain")) filename = "%s_%02x.%02x.%02x.XX-%s%s.bin" %(base, major, minor, featu...
from rates import Rates from utils import get_last_work_day from telegram.ext import Updater, CommandHandler, MessageHandler, Filters import requests from pandas.tseries.offsets import BDay import pandas as pd import matplotlib.pyplot as plt import logging import os import sys from datetime import date, datetime, tim...
import lcm import time import threading from exlcm import extmsg_t, detectmsg_t print("") print("###############################################") print(" This is the real controller of a robot. ") print(" Its purpose is to log information about ") print(" received messages and break when either ") p...
import machine, oled_ssd1306, menu_framework, network # MENUS (menu requires nested list of options and call_function bool in matching index # ----------------------------------------------------------------------------- main_menu = [ ['system', 'mqtt', 'LED', 'stats', 'unused', 'unused2', 'credits'], ...
import random list_of_technology = ["AAPL", "ACIW", "ACN", "ADBE", "ADI", "ADP", "ADSK", "AKAM", "AMD", "AMAT", "ANET", "ANSS", "ARW", "ATVI", "AVGO", "AVT", "AZPN", "BA", "BB", "BLL", "BLKB", "BR", "CDK", "CDNS", "CERN", "CHKP", "CIEN", "COMM", "COUP", ...
# Copyright (c) 2011, James Hanlon, All rights reserved # This software is freely distributable under a derivative of the # University of Illinois/NCSA Open Source License posted in # LICENSE.txt and at <http://github.xcore.com/> import sys import copy import collections from itertools import product import ast from ...
import cv2 import os import sys import numpy import matplotlib.pyplot as plt import src.traditional_method.image_enhance as image_enhance from skimage.morphology import skeletonize, thin import numpy as np import pickle address_lst = os.listdir("../../data/orb_pkl/") name_set = set(address_lst) def removedot(invert...
from textx.metamodel import metamodel_from_file from textx.export import metamodel_export, model_export from textx.exceptions import TextXSyntaxError from pythonmodels import MLayoutGraph, MLayoutSubgraphs, MExpression, MTerm, MFactor import os import sys class Interpreter(): def __init__(self,): metamode...
"""letter_str = input("What letter are you asking about? ") vowels_str = "aeiou".upper() if letter_str.upper() in vowels_str.upper(): print("Your letter {}, and it is a vowel, position {}.".format(letter_str.upper(), vowels_str.find(letter_str) + 1)) else: print("Your letter {}, and it is a consonant, and at po...
from datetime import datetime from django.contrib.postgres.indexes import BrinIndex from django.db import models, transaction from django.db.models import (Case, CharField, Count, DateTimeField, ExpressionWrapper, F, FloatField, Func, Max, Min, Prefetch, Q, S...
# -*- coding: utf-8 -*- import scrapy class BooksSpider(scrapy.Spider): name = 'books' allowed_domains = ['lib.xust.edu.cn'] start_urls = ['http://61.150.69.38:8080/browse/cls_browsing.php'] def parse(self, response): r=response.xpath('//strong/text()').extract_first() # v=r.decode('G...
# -*- coding: utf-8 -*- import urllib2 from SPARQLWrapper import SPARQLWrapper, JSON import sys import nltk from nltk.corpus import stopwords import os import treetaggerwrapper import MySQLdb import unicodedata from urllib import quote_plus def PreparaFiltroTexto(recurso): tittletyope = "" for s in recurso.split():...
#!/usr/bin/env python3 from ev3dev2.motor import LargeMotor, OUTPUT_B, OUTPUT_C, SpeedPercent import socket import time, os HOST = '172.30.1.4' # Raspberry pi server IP PORT = 12345 client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client_socket.connect((HOST, PORT)) os.system('setfont Lat15-TerminusBo...
#!/usr/bin/python def Test1(tree): def sub_parse(sub_tree): name= sub_tree[0] if sub_tree[1]=='x': return [name, sub_parse(sub_tree[2][-1])] else: return name print 'last names=', sub_parse(tree) def Parser(tree_struct, op): name= tree_struct[0] kind= tree_struct[1] op(name,kind) i...
import torch import torch.nn as nn # Creating the architecture of the Neural Network class Network(nn.Module): def __init__(self, input_size, output_size, gpu): super(Network, self).__init__() self.input_size = input_size self.output_size = output_size self.gpu = gpu self....
# Write a function that takes in a number between 1 and 100 and then tries to guess it in as few tries as possible. # Based on whether a guess is larger or smaller than the input number, the code would come up with a new guess # until it gets it right. from collections import deque import numpy as np def guess_num(n...
from urllib.request import urlopen from bs4 import BeautifulSoup import json url = "http://www.weather.com.cn/weather/101010100.shtml" response = urlopen(url) bs = BeautifulSoup(response, "html.parser") # 按照顺序依次找出五列数据: 日期date, 描述 desc, 温度temp 风向direction level 风力 date_list = bs.select("li > h1") ...
import pygame from project.constants import ECRAN # each type of game object gets an init and an # update function. the update function is called # once per frame, and it is when each object should # change it's current position and state. the Spacecraft # object actually gets a "move" function instead of # update, si...
import argparse import os import tensorflow as tf from data_loader import Data from model import Model from datetime import datetime parser = argparse.ArgumentParser(description='Compresion and Classification for HSI') parser.add_argument('--result', dest='result', default='result')# path result, will contain a sub f...
from io import StringIO import os import sys def _writeSinglePotential(pot, minr, maxr, gridPoints, out): """Create a lammps tabulated potential for the given potentials.Potential object. The potential name within the LAMMPs file is of the form pot.speciesA-potspeciesB @param pot potentials.Potential instan...
"""Author Arianna Delgado Created on May 28, 2020 """ """Loop""" """Ask the user to enter a number Display all the numbers up to that number Skip the multiples of 10 (used continuous) Stop is the number is greater that 100 (break)""" #Declares variables and receives input and casts the input to an integer. num1 = i...
from loss import * from CV_params import * import pandas as pd import time from joblib import dump # read data real_cyc = pd.read_csv(r'D:\thesis\data\real.csv', index_col='starttime') observe_cyc = pd.read_csv(r'D:\thesis\data\observed.csv', index_col='starttime') array_real_cyc = np.array(real_cyc) array...
""" Newsletter subscription management. """ import morepath from morepath.request import Response from onegov.core.security import Public from onegov.newsletter import NewsletterCollection, Subscription from onegov.org import _, OrgApp # use an english name for this view, so robots know what we use it for @OrgApp.v...
import socketserver import json import configparser from conf import setting import os SUCCESS_CODE = { '500':'验证通过', '501':'验证失败', '802' : '文件不存在,可以上传', '801' : '文件已经存在', '800' : '文件b不完整,是否继续' } class ServerHandle(socketserver.BaseRequestHandler): def handle(self): while True: ...
from sqlalchemy import Column, ForeignKey, Integer, String, Date, Numeric from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) ...
""" Temporary South module while we move directory structure. """ import sys, os sys.path.insert(0, os.path.dirname(__file__)) raise DeprecationWarning("South has now moved to the south/ subdirectory. You will need to reconfigure your svn:external or library paths in your application. See http://south.aeracode.org/wiki...
#defines-------------------------------------------- WINDOW_WIDTH = 500 WINDOW_HEIGHT = 500 BUTTON_SPACE = 200 BUTTON_WIDTH = 5 BUTTON_HEIGHT = 5 TILE_X = 4 TILE_Y = 4 #--------------------------------------------------- CANVAS_BACKGROUND_COLOR = "lightblue" BUTTON_BACKGROUND_COLOR = "black" BUTTON_FOREGROUND_COLOR = "...
#! usr/bin/python3 # -*- coding: utf-8 -*- # # Flicket - copyright Paul Bourne: evereux@gmail.com from flask import abort, redirect, url_for, flash, render_template, g from flask_babel import gettext from flask_login import login_required from application import app, db from application.flicket.forms.flicket_forms im...
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2021-2023 Kari Kujansuu # # 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 Foundation; either version 2 of the License, or # (at your optio...
from tkinter import Tk, mainloop, PhotoImage, Label, Entry, Button, Frame, font from tkinter.font import Font try: import Tkinter as tk except: import tkinter as tk from PIL import ImageTk , Image import pandas as pd import numpy as np dataset = pd.read_csv("riskdataset.csv") x = dataset.ilo...
class Node: def __init__(self, val): self.val = val self.left = None self.right = None self.parent = None def is_left_child(self): if self.parent and self.parent.left == self: return True else: return False def has_right_child(self): ...
from flask_login import LoginManager class ApplicationCore(object): def __init__(self, app): self.initialize_login(app) def initialize_login(self, app): self.login_manager = LoginManager() self.login_manager.init_app(app) self.login_manager.login_view = 'login'
from onegov.activity import OccasionNeed from onegov.feriennet import _ from onegov.form import Form from psycopg2.extras import NumericRange from wtforms.fields import BooleanField from wtforms.fields import IntegerField from wtforms.fields import StringField from wtforms.fields import TextAreaField from wtforms.valid...
import flask from subprocess import Popen import drawer import json import sys import circle app = flask.Flask(__name__) app.config["DEBUG"] = True @app.route('/', methods=['GET']) def home(): data=json.dumps(drawer.generateCircles(),default=circle.circle2dict) env={} env["DRAWER_INPUT"]=data Popen([...
import argparse import requests import csv # Description of the code shown in help welcome = '''Command line interface to interact with webserver for basic operations.\n Pass val1, val2 and op, or csv file name to open. ''' parser = argparse.ArgumentParser(description=welcome) # Function to perform the http request ...
from django.db import models from users.models import CustomUser class BoxMessage(models.Model): emitter = models.ForeignKey( CustomUser, on_delete=models.CASCADE, null=True) text = models.CharField(max_length=100) last_message = models.ForeignKey( 'chat.BoxMessage', on_delete=models.CASCA...
# Repel Program # Create functionality that will have sprites move away from the mouse. # GLOBAL VARIABLES # Get your color scheme from https://coolors.co/ player_color = "#A4B0F5" npc_color = "#F58F29" bg_color = "#4464AD" def setup(): size(400, 400) def draw(): background(bg_color) ...
def repr_single(s): return "'" + repr('"' + s)[2:] def repr_double(s): single = repr_single(s) return '"' + single[1:-1].replace('"', '\\"').replace('\\\'', '\'') + '"' def test_single(): assert r"'foobar'" == repr_single('foobar') assert r"'\'foobar'" == repr_single('\'foobar') assert "'\\'f...
from django.urls import path from . import views urlpatterns = [ path('bills/agreement', views.FlatBillsCreationAPIView.as_view()), path('bills/history', views.BillsHistoryCreationAPIView.as_view()), path('flat/bills/agreement/<int:flat>', views.BillsByFlatAPIView.as_view()), path('flat/bills/...
#Programa: act13.py #Propósito: Realizar un programa que lea una cadena por teclado y convierta las mayúsculas a minúsculas y viceversa. #Autor: Jose Manuel Serrano Palomo. #Fecha: 30/10/2019 # # Análisis: # Pedimos una cadena al usuario # Para cada caracter hacemos una variable independiente # Si es minuscula lo conve...
import uvicorn from fastapi import FastAPI, APIRouter from starlette.staticfiles import StaticFiles from aop.file_path_cd import file_path_detect from utils.router_utils import get_router import sys import os curPath = os.path.abspath(os.path.dirname(__file__)) rootPath = os.path.split(curPath)[0] sys.path.append(r...
import urllib from BeautifulSoup import * count = int(raw_input("Enter count:")) position = int(raw_input("Enter position:")) url = raw_input("Enter initial url:") name = list() #count = 4 #position = 3 #url = 'http://python-data.dr-chuck.net/known_by_Setana.html' i = 0 while i < int(count): try: html_text = urll...
import unittest from conans.test.utils.tools import TestClient from conans.paths import CONANFILE from conans.test.utils.conanfile import TestConanFile class VersionRangesConflictTest(unittest.TestCase): def setUp(self): self.client = TestClient() def add(name, version, requires=None): ...
import h5py import unittest from click.testing import CliRunner from singl.testing.helpers import create_test_csv_from_ids from singl.testing.helpers import create_test_images from singl.scripts.compress_dataset import compress_dataset class TestCompressDataset(unittest.TestCase): def setUp(self): self....
def is_number_palindrome(n): s = str(n) x = int(s[::-1]) return x == n pal_list = [] for x in range(999,99, -1): for y in range(999, 99, -1): if is_number_palindrome(x * y): pal_list.append(x*y) print max(pal_list)
# Generated by Django 3.0.8 on 2020-07-17 14:00 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('profiles', '0008_auto_20200717_2200'), ('message', '0001_initial'), ] operations = [ migrations.Alt...
import re from checkov.common.models.enums import CheckResult, CheckCategories from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck class ResourceGroupPrefix(BaseResourceCheck): def __init__(self): super().__init__( name="Ensure resource group is prefixed by the...
# ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
#!/usr/bin/env python s = 45 * 18 * 10**17 a = int(raw_input()) s %= a print (a - s), 10**18 + (a-s) - 1
import os import subprocess as sp import time from argparse import ArgumentParser from concurrent.futures import ProcessPoolExecutor, as_completed from shutil import copyfile import pkg.dimension import pkg.human_readable import pkg.list THREADS = 4 def get_args(): parser = ArgumentParser("Batch upscale") p...
print('importing...') import pyaudio from time import time, sleep import numpy as np from scipy import stats from threading import Lock from collections import namedtuple from interactive import listen try: from yin import yin from streamProfiler import StreamProfiler except ImportError as e: module_name = ...
N, L = map( int, input().split()) A = list( map( int, input().split())) ans = "Impossible" for i in range(N-1): if A[i] + A[i+1] >= L: ans = "Possible" t = i break if ans == "Impossible": print(ans) else: print(ans) for i in range(t): print(i+1) for i in range(N-2,t,-...
from django.contrib.auth import get_user_model from django.views.decorators.csrf import csrf_exempt from rest_framework.response import Response from rest_framework.views import APIView User = get_user_model() # from customer.models import Customer # # from customer.api.serializers import CustomerSerializer, UserSerial...
from django.db import models import uuid from django.urls import reverse, reverse_lazy from django import template from django.core.files.storage import FileSystemStorage # Create your models here. fs = FileSystemStorage(location='/media/items') class Category(models.Model): # Field objects = models.Manag...
#import sys #input = sys.stdin.readline from collections import deque def bfs(N, E, s): INF = 10**10 V = [INF]*N d = deque([s]) V[s] = 0 while d: v = d.popleft() now = V[v] for w in E[v]: if V[w] < INF: continue V[w] = now+1 ...
# Generated by Django 3.1.5 on 2021-03-29 04:53 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('main', '0032_auto_20210328_0711'), ] operations = [ migrations.AlterField( model_name='profile'...
import re from urllib.request import urlopen from bs4 import BeautifulSoup url="http://nanabt.com/index.php?c=thread&fid=28&page=" #创建url for a in range(1,10): aa=a+1 aa=str(aa) url1=url+aa fp=urlopen(url1) s=fp.read() soup=BeautifulSoup(s) polist=soup.prettify() print(polist)
import os import pyfits import numpy as np import matplotlib matplotlib.use('agg') import numpy as np import numpy.linalg as la import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from pylab import * import matplotlib.colors import matplotlib.cm import matplotlib.pyplot as plt import math import h5p...
Q = 10**9 + 7 ''' #これは深すぎるらしい def factorial(n): if n == 0: return 1 else: return (n * factorial(n-1))%Q ''' N, M = map( int, input().split()) N, M = min(N, M), max(N, M) if N == M or N+1 == M: NN = 1 MM = 1 for i in range(1,N+1): NN = (NN*i)%Q if N == M: ans = (2*...
# Generated by Django 2.2.6 on 2019-10-27 21:47 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('techei', '0036_auto_20191027_2131'), ] operations = [ migrations.CreateMod...
class Maybe(): """This is a Monad that helps deal with values that aren't there""" def __init__(self, value = None): """ Pass in value to be wrapped in a maybe""" self.value = value def is_there(self): return self.value is None def bind(self, fn): """fmap: ap...
import numpy as np import time import torch from torch.autograd import Variable from utils import variable from Generative_Models.Generative_Model import GenerativeModel class GAN(GenerativeModel): def train_on_task(self, train_loader, ind_task, epoch, additional_loss): self.size_epoch = 1000 ...
# Generated by Django 3.0.7 on 2020-10-13 07:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cl_app', '0006_auto_20201012_1048'), ] operations = [ migrations.AlterField( model_name='itemsitelist', name='site_i...
################################################################################ # PG-46: write code to reverse a c-style string from typing import * def reverse_str(s: List[str]): # first find the length len = 0 for c in s: if c == '\0': break len += 1 if len == 0: ...
import unittest from conans.test.utils.tools import TestClient import platform from conans.util.files import load import os file_content = ''' from conans import ConanFile, CMake class ConanFileToolsTest(ConanFile): name = "test" version = "1.9" settings = "os", "compiler", "arch", "build_type" expor...
#!/usr/bin/env python import math import random import hashlib import socket def fastModularExponentiation(base, exponent, prime): answer = base sizeofexp = int(math.floor(math.log(exponent, 2)) + 1) for i in range(sizeofexp-2, -1, -1): answer = (answer * answer) % prime if (exponent >> i) % 2 == 1: answer...
from fractions import Fraction def getPI(JPI): ## Extract parity if '+' in JPI: return '+' elif '-' in JPI: return '-' else: return '' def getJ(JPI): ## Extract spin w/o parity return Fraction(JPI.replace('+','').replace('-','')) def getJrange(lowval,hi...
# Generated by Django 2.2.19 on 2021-03-23 13:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0003_auto_20210319_1226'), ] operations = [ migrations.RenameField( model_name='user', old_name='state', ...
""" 문제 0보다 크거나 같고, 99보다 작거나 같은 정수가 주어질 때 다음과 같은 연산을 할 수 있다. 먼저 주어진 수가 10보다 작다면 앞에 0을 붙여 두 자리 수로 만들고, 각 자리의 숫자를 더한다. 그 다음, 주어진 수의 가장 오른쪽 자리 수와 앞에서 구한 합의 가장 오른쪽 자리 수를 이어 붙이면 새로운 수를 만들 수 있다. 다음 예를 보자. 26부터 시작한다. 2+6 = 8이다. 새로운 수는 68이다. 6+8 = 14이다. 새로운 수는 84이다. 8+4 = 12이다. 새로운 수는 42이다. 4+2 = 6이다. 새로운 수는 26이다. 위의 예는 4번만에 원...
class Solution: def computeArea(self, a, b, c, d, e, f, g, h): """ :type A: int :type B: int :type C: int :type D: int :type E: int :type F: int :type G: int :type H: int :rtype: int """ # I'm so crazy because I try to l...
import sys import unittest from rdflib import Namespace from funowl import EquivalentObjectProperties, Axiom from funowl.terminals.TypingHelper import isinstance_ EX = Namespace("https://example.org/ex#") class AxiomInstanceTestCase(unittest.TestCase): def test_axiom_instance(self): """ Test axiom ins...
from util import * from scipy.spatial.distance import pdist def toDistance(R): """ This function takes a numpy array containing positions and returns it as distances. Parameters: -R: numpy array containing positions for every atom in every sample Dimensions: (n_samples,n_a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import math # 求一元二次方程的解 def quadratic(a, b, c): delta = b ** 2 - 4 * a * c if delta < 0: print('该方程无实数解') else: x1 = (-b + math.sqrt(delta)) / (2 * a) x2 = (-b - math.sqrt(delta)) / (2 * a) return x1, x2 # 测试 print('quadrati...
import logging import config import KeyBords from aiogram import Bot, Dispatcher, executor, types from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup import States from aiogram.utils import deep_li...
import logging import random from functools import reduce class Operator: pass class Selection(Operator): def __init__(self, pop, select, scale, window): self.pop = pop self.window = window if select == 'wheel': self.evaluate() self.select = self.wheel ...
sumofsquare=0 for i in range(1,101): sumofsquare+=i*i print (sumofsquare) total=0 for i in range(1,101): total+=i squareofsum=total*total print(total) print(squareofsum) print (squareofsum-sumofsquare)
import os import warnings # Ignore future warnings they're annoying. warnings.simplefilter(action="ignore", category=FutureWarning) # Ensure NumPy only uses 1 thread for matrix multiplication, # because NumPy is stupid and tries to use heaps of threads, # which is quite wasteful and makes our models run way more slo...