text stringlengths 38 1.54M |
|---|
# Copyright (c) Dec 22, 2014 CareerMonk Publications and others.
# E-Mail : info@careermonk.com
# Creation Date : 2014-01-10 06:15:46
# Last modification : 2008-10-31
# by : Narasimha Karumanchi
# Book Title : Data Structures And Algorithms Made In Java
# Warranty : This... |
import unittest
from core.common import download
import os
from datetime import datetime
TEST_FILE_PATH = 'core/test/common/test_file.html'
TEST_URL = 'https://www.google.ie/'
class DownloadTest(unittest.TestCase):
@classmethod
def clean(cls):
if os.path.isfile(TEST_FILE_PATH):
... |
# 핸드폰 번호 가리기
# 문제 설명
# 프로그래머스 모바일은 개인정보 보호를 위해 고지서를 보낼 때 고객들의 전화번호의 일부를 가립니다.
# 전화번호가 문자열 phone_number로 주어졌을 때, 전화번호의 뒷 4자리를 제외한 나머지 숫자를 전부 *으로 가린 문자열을 리턴하는 함수, solution을 완성해주세요.
# 제한 조건
# s는 길이 4 이상, 20이하인 문자열입니다.
def solution(phone_number):
phone_number = list(phone_number)
for i in range(len(phone_number)... |
import math
print("enter the first complex number")
x=complex(float((input("Enter the real part"))),float((input("enter the imaginary part"))))
print("enter the second complex number")
y=complex(float((input("Enter the real part"))),float((input("enter the imaginary part"))))
print(complex(x+y))
print(complex(x-y... |
SPLAT_FORM_URL = "http://www.cv.nrao.edu/php/splat/c_export.php"
HIT_LIMIT = 2000
SPLATALOGUE_TIMEOUT = 30
"""
NB this script has a export limit of 2000 hits.
Change HIT_LIMIT to accomodate your needs.
"""
__all__ = ['search']
import numpy as np
try:
from astropy.table import Table
use_astropy = True
except... |
# Code der Aufgabe 1 hier
class Vector3:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def len(self):
return (self.x**2 + self.y**2 + self.z**2)**0.5
# folgenden Code nur ausführen, wenn diese Modul direkt ausgeführt wird
# (nicht beim Importieren)
if __... |
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponseRedirect
from django.shortcuts import redirect, reverse, render, get_objec... |
from datetime import datetime, timezone
from time import sleep, monotonic
from urllib.parse import quote_plus
from uuid import uuid4
import requests
from config import sheet_api_url
from utils.myworkers import MyWorkers
book_worker = MyWorkers(1)
# Получение JSON из гугл таблицы
def get_data_from_sheet(params, met... |
# read.py
# loading a file with open()
import numpy as np
resultados = open("resultados.txt", "r")
lines = 0
n = int(input("Número de processos: "))
r = int(input("Número de repeticoes: "))
# initialize array with counter for all processes
# in the end, every index of this array = r
process_counter = np.zeros(n)
p... |
def is_Even_or_Odd(number):
if number % 2 == 0:
print("This number is even :", number)
else:
print("The number entered is odd: ", number)
num = int(input("Enter the number: "))
x = num
is_Even_or_Odd(x)
|
import es920lr
import time
import sys
import serial
import MySQLdb
if __name__ == "__main__":
db = MySQLdb.connect(host="localhost", user="OWNER", passwd="12345", db="prototype_lab")
cur = db.cursor()
ser = serial.Serial("/dev/ttyUSB0", 115200)
lr = es920lr.ES920LR(ser)
lr.set_id("0001", "1111",... |
import argparse
def argument():
parser = argparse.ArgumentParser(description = 'Executes extraction of HC metrics vs SAT')
parser.add_argument( '--inputdir', '-i',
type = str,
required = True,
help = 'Where the m... |
import pandas as pd
import numpy as np
import jieba
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import special_dict
from collections import Counter
from chinesetrans.langconv import *
from PIL import Image
import re
import matplotlib
FILE_PATH = '自由时报正文分詞... |
from rest_framework.request import Request
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from ..models import AndelaUserProfile
def jwt_authentication_middleware(get_response):
def middleware(request):
try:
user_jwt = JSONWebTokenAuthentication().authenticate(Reque... |
#!/usr/bin/python3
"""Script to return user info based on given ID number"""
import requests
import sys
if __name__ == "__main__":
url = 'http://jsonplaceholder.typicode.com/users/'
r_todo = requests.get(url + '{}/todos'.format(sys.argv[1])).json()
r_user = requests.get(url + '{}'.format(sys.argv[1])).jso... |
import FWCore.ParameterSet.Config as cms
process = cms.Process('DQM')
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1000) )
process.verbosity = cms.untracked.PSet( input = cms.untracked.int32(-1) )
# minimum of logs
process.MessageLogger = cms.Service("MessageLogger",
statistics = cms.untrac... |
# Shamelessly ripped and modified from
# https://github.com/SublimeText/TrailingSpaces
import sublime, sublime_plugin
DEFAULT_MAX_FILE_SIZE = 1048576
DEFAULT_COLOR_SCOPE_NAME = "invalid"
DEFAULT_IS_ENABLED = True
# Set whether the plugin is on or off.
# Reuseing TrailingSpaces' config.
ts_settings = sublime.load_set... |
# Database config
database_host='127.0.0.1'
database_name='sports'
database_user='root'
database_password=''
# Some private secret for hashing
secret='1482ec1b2364f64e7d162a2b5b16f477' |
#question:
#Answer of the output should be:
# {'Randy':['Input.txt','Output.txt'], 'Stan':['Code.py']}
# class FileOwners:
# @staticmethod
# def group_by_owners(files):
# return None
# files = {
# 'Input.txt': 'Randy',
#... |
#!/usr/bin/python
# import high-level functions
import os
import sys
from pprint import pprint
class read:
def __init__(self, core, filename):
self.supportedseperators = ['";"', '\';\'',
'","', '\',\'',
'"|"', '\'|\'',
... |
# users GET /users(.:format) users#index
# POST /users(.:format) users#create
# new_user GET /users/new(.:format) users#new
# edit_user GET /users/:id/edit(.:format) users#edit
# user GET /users/:id(.:format) ... |
from enum import Enum
class SearchSessionStatus(Enum):
IN_PROGRESS = "IN_PROGRESS"
COMPLETE = "COMPLETE"
|
from math import*
r = float(input("Raio:"))
alt = float(input("Altura:"))
op = input("Opcao:")
volume = (4*pi*(r**3))/3
volcalota = (pi*(alt**2)*(3*r-alt))/3
combustive = volume - volcalota
if(op == "1"):
print(round(volcalota, 4))
if(op=="2"):
print(round(combustive, 4)) |
"""
Problemas propuestos
Cargar una cadena de caracteres por teclado. Mostrar la cadena del final al principio
utilizando subíndices negativos.
Confeccionar un programa con las siguientes funciones:
1) Cargar una lista con 5 palabras.
2) Intercambiar la primer palabra con la última.
3) Imprimir la lista
"""
def carg... |
from flask import Flask, jsonify, request
import numpy as np
import datetime
import sendgrid
import os
from sendgrid.helpers.mail import *
app = Flask(__name__)
global_M = {} # Master dictionary of patients
@app.route("/api/new_patient", methods=["POST"])
def new_patient():
""" initialize patient and accept fu... |
#!/usr/bin/env python
from __future__ import print_function
from future.standard_library import install_aliases
install_aliases()
# noinspection PyCompatibility
from urllib.parse import urlencode
# noinspection PyCompatibility
from urllib.request import urlopen
import json
import os
from flask import Flask
from f... |
def monthle_payment(principal, annual_interest_rate, duration):
r = annual_interest_rate / 1200
n = duration * 12
if r != 0 :
y = (principal * (r*((1+r)**n)))/(((1+r)**n)-1)
else :
y = principal / n
return y
|
'''
Data access wrappers for WSD datasets in Raganato et al
WSD Evaluation Framework project
'''
from lib import wsd_parser
class WSDDataset:
def __init__(self, config, name):
self.config = config
self.name = name
(
self.labels,
self.unique_sense_IDs
) = ws... |
from django.db import models
# Create your models here.
class Exam(models.Model):
name = models.TextField()
instruction = models.TextField()
duration = models.IntegerField()
class Question(models.Model):
examId = models.ForeignKey(Exam, on_delete=models.CASCADE)
question = models.TextField()
... |
import collections
import copy
import errno
import fcntl
import fnmatch
import glob
import inspect
import multiprocessing
import os
import os.path
import pprint
import re
import scapy.all as scapy
import signal
import socket
import subprocess
import sys
import tempfile
import time
import traceback
import commands as b... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial=tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W):
return tf... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
"""Tests for various encoding issues throughout the library"""
import unittest
import cybox.bindings as bindings
from cybox.common import Contributor, String, MeasureSource
from cybox.core ... |
import discord
import asyncio
from random import randint
import time
#save token to text file
token = open('token.txt', 'r').read()
#start discord client
client = discord.Client()
#when connected
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#when message is se... |
from Integrateur.PhysiqueGenerale import PhysiqueGenerale
from Math.Point import Point
from Math.Vecteur import Vecteur
class ILeapFrog(PhysiqueGenerale):
def __init__(self, objs, dt):
super().__init__(objs)
self.dt = dt
self.first = True
def prochainePosition(self, obj, dt):
... |
from __future__ import print_function
import sys
import argparse
from datetime import timedelta
from subprocess import Popen
from time import time, sleep
def red(text):
RED = '\033[91m'
END = '\033[0m'
return RED + text + END
def log(*args):
print(*args, file=sys.stderr)
sys.stderr.flush()
cla... |
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from config import config
db_path = config["database"]["path"]
db_engine_str = "sqlite:///" + db_path
engine = create_engine(db_engine_str, convert_unicode=Tru... |
import sys
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
mail_server = 'smtp.gmail.com:587' # Mail Server
mail_account = '' # name of mail account
mail_password = '' # password
addr_sender = '' # sender email
addr_receiver = '' # receiver email... |
import math
def power(x,n):
res = 1
x = x%1000000007
while(n>0):
if(n&1):
res = (res*x)%1000000007
n //=2
x = (x*x)%1000000007
return res
def inverse(n):
return power(n,1000000007-2)
def fermet(n,r):
if r==0:
return 1
fact = [... |
from zope.interface import Interface
class IChat(Interface):
def initialize(self, username=None):
""" Check if the user is registered, and register if not
"""
def get_uncleared_messages(self, audience='*', mark_cleared=False):
""" Retrieve the uncleared messages from the chat server
... |
# Generated by Django 2.0 on 2018-11-23 04:55
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('hood', '0006_auto_20181122_2043'),
]
operations = [
migrations.RemoveField(
model_name='neighborhood',
name='admin',
)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
See http://stackoverflow.com/a/20824134/2401932
'''
import csv
from operator import itemgetter
import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt
import scipy.optimize as optimize
import sys
sys.path.append('.')
from experiments.data impor... |
import requests
from email.mime.text import MIMEText
from datetime import date
import smtplib, sys
from datetime import datetime
import time
import subprocess
dtime = datetime.now().strftime("%d-%m-%Y")
#Set frequency with seconds to check vaccine availablity
frequency = 60
# set PINCODE below with 6 digit numeric va... |
def reverseList(li):
length = len(li)
for i in range (length//2):
li[i],li[length-1-i] = li[length-1-i], li[i]
li = [2,4,5,12,53,57]
reverseList(li)
print(li)
def reverseList2(li):
length = len(li)
for i in range(length//2):
li[i],li[-i-1] = li[-i-1],li[i]
li = [32,13,53,25,76,21]
rev... |
import multiprocessing
import time
class ReadWriteLock(object):
""" A lock that allows multiple readers and one writer.
Members:
print_lock - lock to print debug information
lock - lock to make ReadWriteLock operations atomic
readGo - Condition Variable that Readers wait on
writeGo - Conditio... |
"""A module that provides plotters for Vicon markers that have been tracked via biplane fluoroscopy to ascertain the
spatiotemporal syncing accuracy between the Vicon and biplane fluoroscopy systems ."""
import numpy as np
from typing import Sequence, List
import matplotlib.figure
import matplotlib.pyplot as plt
from ... |
from Individual import Individual
from Population import Population
from TextProcessing import TextProcessing
import string
import random
import numpy as np
class GeneticAlgorithm:
def __init__(self, population_size, number_of_generations, mutation_rate, cross_chance, encoded_text):
self.population_size =... |
from fastapi import FastAPI
cinema = FastAPI()
movie_genre = {
'horrors': {
'1': 'Я - легенда! (8.5)',
'2': 'Чужой (8.3)',
'3': 'Мумия (8.3)'
},
'drama': {
'1': 'Зеленая миля (9.1)',
'2': 'FORD против FERRAR... |
# -*- coding: utf-8 -*-
"""
绘制3d图形
"""
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
def plot_3d(np_3d):
# np 为3维张量
shape = np_3d.shape
for i in range(shape[0]):
# 定义figure
fig = plt.figure()
# 创建3d图形的两种方式
# 将figure变为3d
... |
# 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... |
# /usr/bin/env python
# Download the twilio-python library from http://twilio.com/docs/libraries
import os
from twilio.rest import Client
# Find these values at https://twilio.com/user/account
account_sid = "ACe4e43683af664305fcc2094c6f181eea"
auth_token = "cfc35a637ea16d3ed060c412cd34a7c6"
client = Client(account_sid... |
import shelve
from django.db.models import F
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from person.models import Person
import rtyaml
class Command(BaseCommand):
help = 'Reports if any legislator twitter bios change.'
storage_fn = 'data/misc/twitter_bios.s... |
from django.contrib import admin
from core.models import User, Type, Address, Phone
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
pass
@admin.register(Type)
class TypeAdmin(admin.ModelAdmin):
pass
@admin.register(Address)
class AddressAdmin(admin.ModelAdmin):
pass
@admin.register(Phone)
... |
from AccessControl import Unauthorized
from AccessControl.Permissions import delete_objects
from plone.app.content.browser.contents import ContentsBaseAction
from plone.app.content.interfaces import IStructureAction
from plone.base import PloneMessageFactory as _
from Products.CMFCore.utils import getToolByName
from Pr... |
from pytest import raises
from pathlib import Path
from scraper.item_scraper.item_scraper import parse
from scraper.item_scraper.validators import (
ValidationError,
validate_css_selector,
validate_file_path,
validate_task,
)
CACHE_DIR = Path(__file__).parent / 'data' / 'cache_dir'
def test_css_sel... |
"""Functions for reading and writing measured light curve data to
SALT2-format files"""
import os
import math
from collections import OrderedDict
import numpy as np
__all__ = ["read", "write", "readdir", "writedir"]
# Reading Metadata
# ----------------
# Names are converted to lowercase, then the following lookup ... |
import pygame as pg
from .. import tools, prepare
from ..components.labels import Label
from ..components.course_hole import HOLE_INFO, CourseHole
from ..components.ball import Ball
from ..components.scorecard import Scorecard
class ViewScorecard(tools._State):
def __init__(self):
super(ViewS... |
# Hopper Disassembler script to insert x86/x64 instructions to return
# an integer from the current procedure. Should handle both 64-bit and
# 32-bit values. Automatically inserts function prologue if its epilogue
# remains unchanged - to avoid inserting the prologue, run this at the
# very beginning of the function so... |
from ..Core.commands import Commands
from ..Core.registers import Registers
from ..Runtime.base import Base
from ..Runtime.atoi import Atoi
from .write import Write
class Read(Base):
is_loaded = False
def __init__(self, compiler):
Base.__init__(self, compiler)
if Read.is_loaded:
... |
# coding:utf-8
# __author__ = 'BianXuesheng'
# __data__ = '2016/07/12_13:48 '
from django.conf.urls import url,include
from django.contrib import admin
from webuser.views import index,register,weblogin,weblogout
urlpatterns = [
url(r'^$', index),
url(r'^register/$', register),
url(r'^login/$', weblogin),... |
import cv2
import time
'图像插值'
img = cv2.imread("../images/1.jpg")
rows, cols, channels = img.shape
print(rows, cols, channels) # [w, h, c]
time_start = time.time() # 开始时间
'图片缩放:resize()'
resize1 = cv2.resize(img, dsize=(cols * 2, rows * 2)) # 按尺寸进行缩放
resize2 = cv2.resize(img, dsize=(0, 0), fx=2, fy=2) # 按比例进行缩放
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 11 10:28:37 2019
Modified on 16/07/2020
@author: luisf
"""
import requests
from bs4 import BeautifulSoup as bs
import time
import pandas as pd
class scrape_anime_bruh:
def __init__(self, url_pattern, pages_to_scrape=1, sleep_interval=-1, content_parser=None):
... |
__all__ = ['click']
# from
# http://martyalchin.com/2008/jan/10/simple-plugin-framework/
from .start import ActionProvider , PluginMount
def list():
return ActionProvider.plugins
import os
from os.path import dirname
basedir = dirname(__file__)
l = os.listdir(basedir)
for i in l:
if i.endswith('.... |
from trainers.logger import BaseLogger
from trainers.base import BaseTrainer
from trainers.nae import NAETrainer, NAELogger
def get_trainer(cfg):
# get trainer by specified `trainer` field
# if not speficied, get trainer by model type
trainer_type = cfg.get('trainer', None)
arch = cfg['model']['arch'... |
import random
import sys
class Animal:
__name = ""
def __init__(self, name):
self.__name = name
def setName(self, name):
self.__name = name
def getName(self):
return self.__name
cat = Animal("Jack")
cat.setName("Tommy")
print(cat.getName())
class dog(Animal):
__owner ... |
# coding: utf-8
import sys
from setuptools import setup, find_packages
NAME = "etl app"
VERSION = "1.0.0"
# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setuptools
REQUIRES = [
"connexion"
]
setup(
name=NAME,
version=VE... |
"""This module contains the halo abundance calculations.
"""
import numpy as np
from pyccl.halos.hmfunc import MassFuncTinker08
import scipy.integrate as intg
import scipy.interpolate as interp
from scipy.special import erfc
import scipy.stats as stats
from lensing_haloes.cosmo.cosmo import cosmology, dVdz
from pdb i... |
# Copyright 2017-2023 Posit Software, PBC
#
# 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 agreed to in ... |
import tensorflow as tf
import random
from DeepQNet.readData import *
class Env:
def __init__(self, normalized: np.ndarray, time_series: tuple, actions: np.ndarray,
input_size: int=50, transaction_cost = 0.0005):
self.name = "env1"
self.normalized = normalized
self.price_d... |
num=int(input("Enter a number:"))
if(num%3)==0:
print("Enter a number is even")
else:
print("Enter a number is odd") |
from etcetera import api
import argparse
import logging
def main():
parser = argparse.ArgumentParser(prog='etc', description='etcetera: managing cloud-hosted datasets')
parser.add_argument('-v', '--verbose', action='store_true', help='Print debug info')
subparsers = parser.add_subparsers(dest='cmd', hel... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 18 13:38:16 2021
@author: 1999a
"""
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras import datasets, layers, models, utils
from dataload import loadPreprocess
from sklearn import metrics
from sklearn.preprocessing import... |
import csv
import sys
import time
import datetime
###
# SEARCH FOR THE INTERACTORS, CREATES THE INTERACTOME AND THE LIST OF INTERACTORS
# by Paolo Tieri, CNR, paolo.tieri@cnr.it, 2017-2021
# ported from Python 2 to Python 3 on May 2021
###
### print instructions
print('\n'+"#####################################... |
import collections
# def _read_file():
# for row in open("input"):
# yield row
def only_unique(words):
# A Set, with counter for duplicated words.
counts = collections.Counter(words)
# A list of tuples with most common words (I only ask for the most common one).
# The tuple is like a dict, ... |
#!/usr/bin/python3
import asyncio
import logging
import sys
from sqlalchemy.exc import ProgrammingError
import similar_songs
import song_creator
import tiered_song_creator
from database.Session import get_session
sys.path.append("/opt/")
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def _mai... |
import sys
sys.path.append('../../python')
import inject
inject.configure()
import uuid
import json
import datetime
import logging
from model.registry import Registry
from model.connection.connection import Connection
from model.assistance.utils import Utils
from model.assistance.assistance import AssistanceModel
fro... |
def print_board(board):
for i in board:
print(i)
def check_diagonal(row, col, N, board):
'''
Helper function to is_safe
'''
row_2 = row
col_2 = col
while row != 0 and col != 0:
row -= 1
col -= 1
if board[row][col] == 1:
return False
while co... |
f = open('unidade', 'r')
f.seek(121509 + 24300 + 3)
n = int(input('Qual bloco?'))
block = -1
conteudo = ''
while (block != n):
conteudo = f.readline()
block+=1
print('conteudo da linha:')
print(conteudo) |
"""Reverse_Tool URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-... |
'''
一种双核CPU的两个核能够同时的处理任务,现在有n个已知数据量的任务需要交给CPU处理,假设已知CPU的每个核1秒可以处理1kb,
每个核同时只能处理一项任务。n个任务可以按照任意顺序放入CPU进行处理,现在需要设计一个方案让CPU处理完这批任务所需的时间最少,
求这个最小的时间。
输入包括两行:
第一行为整数n(1 ≤ n ≤ 50)
第二行为n个整数length[i](1024 ≤ length[i] ≤ 4194304),表示每个任务的长度为length[i]kb,每个数均为1024的倍数。
输出一个整数,表示最少需要处理的时间。
问题实质是动态规划问题,把数组分成两部分,使得两部分的和相差最小。就... |
# /usr/bin
# Kirk Boyer : 2016 Google Code Jam
# Counting Sheep Problem : Qualifying Round
import sheepSolvers
import sys
import os.path
if __name__ == "__main__":
# pick solver based on input
input_name = sys.argv[2]
solver_name = sys.argv[1]
solver = getattr(sheepSolvers, solver_name)
prefix =... |
import re, csv, json, os, requests
from lxml import etree
from pprint import pprint
from dateutil import parser
from rdflib import URIRef, Literal, Namespace, Graph
from rdflib.namespace import RDF, OWL, SKOS, DCTERMS, XSD, RDFS, FOAF
from config import EXIST, GRAPHDB
ELI = Namespace("http://data.europa.eu/eli/ontolog... |
# -*- coding: utf-8 -*-
__author__ = "Lee.le"
from Views.tools import *
from django.shortcuts import render, HttpResponse
import json
def progress(request):
"""
显示测试用例内容
:param request:
:return:
"""
if request.method == 'POST':
pass
config = configparser.ConfigParse... |
__author__ = 'Mansoori'
from subprocess import call
from prism_trim import prism_trim
import ConfigParser
confige_file = './config.cfg'
class prism_trim_parser():
prism_trim;
prism_path = '.\data\prism output';
pathway_prob = [];
all_gene_pathway_prob = {}
def __init__(self):
self.... |
"""
Имя проекта: practicum_1
Номер версии: 1.0
Имя файла: 24.py
Автор: 2020 © Ю.А. Мазкова, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 10/12/2020
Дата последней модификации: 10/12/2020
Связанные файлы/пакеты: numpy, random
Описание: Решение за... |
# Copyright 2017-2023 Posit Software, PBC
#
# 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 agreed to in ... |
import sys
#import argpase
import numpy as np
def friendsneeded(shynessfrequency):
npshy = np.array( [int(c) for c in shynessfrequency] )
npshycum = npshy.cumsum()
pplstanding = npshycum[0]
additional = 0
for i in range(len(npshy))[1:]:
pplstanding = npshycum[i-1]+additional
if i... |
from pyDatalog import pyDatalog
pyDatalog.create_terms('X,Y')
pyDatalog.create_terms('trash') # type of item
pyDatalog.create_terms('plasticContainer,paperContainer,organicContainer,glassContainer,mixedContainer') # types of containers
pyDatalog.create_terms('plastic,glass,paper,cardboard,organic') # material
pyDatalog... |
from lost_and_found_app import models
from django.forms import ModelForm
class PostCreateForm(ModelForm):
class Meta:
model = models.Post
fields = ("title", "description", "author_name", "author_phone")
class PostEditForm(ModelForm):
class Meta:
model = models.Post
fields = (... |
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# ScanCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/scancode-toolkit for support or download.
# See https://aboutcode.org for more in... |
class Solution:
def minMoves(self, target: int, maxDoubles: int) -> int:
res = 0
while target != 1:
if target % 2 == 1 and maxDoubles != 0:
target -= 1
elif maxDoubles > 0:
target = target / 2
maxDoubles -= 1
... |
# ////////////////////////////////////////////////////////////////////////////
# ----------------------------------------------------------------------------
#
# Amnesia - Layer 1 binary analysis system.
# Copyright (c) 2013 Tristan Strathearn (r3oath@gmail.com)
# Website: www.r3oath.com
#
# ---------------------------... |
#python3
'''
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out their common interest with the least list index sum.
If there is a choice tie between answers, output all of them with no order requireme... |
def adapt_to_ex(model):
self.conv_sections = conv_sections
self.glob_av_pool = torch.nn.AdaptiveAvgPool2d(output_size=1)
self.linear_sections = linear_sections
self.head = head
self.input_shape = input_shape
self.n_classes = head.out_elements
self.data_augment = DataAugmentation(n_class... |
# Copyright 2015 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 agre... |
import collections
import logging
import threading
import time
_REPORT_INTERVAL_S = 1.0
_INDENT = ' '
_MIN_REMAINDER = 0.01
class Profiled(object):
# Shared state; _lock must be held while using these values.
_stacks_by_threadid = collections.defaultdict(lambda: list())
_last_report_time = time.time()
_rep... |
# 1065 - pares entre 5 números
n = 5
qtd_pares = 0
qtd_positivos = 0
qtd_negativos = 0
while (n > 0):
v = int(input())
if (v % 2 == 0):
qtd_pares += 1
if (v > 0):
qtd_positivos += 1
if (v < 0):
qtd_negativos += 1
n -= 1
print("{} valor(es) par(es)".format(qtd_pares))
print... |
import itertools
import operator
import matplotlib
matplotlib.rcParams['interactive'] == True
matplotlib.interactive(True)
from matplotlib import pyplot as plt
from skimage import color
from skimage import io
import numpy as np
import re
import csv
import os
import aire
image1 = io.imread("images\\resultats\\region_s... |
'''
Created on Jun 3, 2016
@author: Daniel
'''
import unittest
from poker.Deck import Hand, Card
from poker.WinPatterns import HighCard, Pair, TwoPair, ThreeOfAKind, Straight, Flush, FullHouse, FourOfAKind, StraightFlush, RoyalFlush
class TestHighCard(unittest.TestCase):
def test_low_high_card(self):... |
# Generated by Django 2.2.6 on 2019-10-19 10:08
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('twix', '0002_auto_20191019_1457'),
]
operations = [
migrations.AddField(
model_name='task',
... |
class InsufficientIngredientsException(Exception):
"""Raised when ingrediets are not sufficient"""
pass
class IngredientsOverflowException(Exception):
"""Raised when ingredients overflow"""
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.