text stringlengths 8 6.05M |
|---|
"""
l=0
for word in open('Book2.txt').read().split():
longg = ''
if len(word)>len(longg):
longg = word
# for w in open('book2.txt').read().split():
# if
print(longg)
"""
def Words():
file1 = open('Book1.txt', 'r')
file2 =open('Book2.txt','r')
file3 = open('Book3.txt', 'r')
l... |
class TreeNode:
def __init__(self, x=0):
self.val = x
self.left = None
self.right = None
def depth(root):
if root == None:
return 0
else:
return max(depth(root.left), depth(root.right))+1
def isBalanced(root):
if root == None:
return True
n1=dep... |
#!/usr/bin/env python3
import sys
def fizzbuzz(length):
output = []
for iterator in range(0, length):
value = iterator
if iterator % 3 == 0 and iterator % 5 == 0:
value = 'FizzBuzz'
elif iterator % 3 == 0:
value = 'Fizz'
elif iterator % 5 == 0:
... |
# Copyright 2014 Symantec.
#
# 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 writing, s... |
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 读入数据/标签 生成x_train y_train
df = pd.read_csv("../datas/dot.csv")
x_data = np.array(df[['x1', 'x2']])
y_data = np.array(df['y_c'])
x_train = np.vstack(x_data).reshape(-1, 2)
y_train = np.vstack(y_data).reshape(-1, 1)
Y_c =... |
import math
inputFile = open("/Users/samuelcordano/Documents/adventOfCode/Day7_HandyHaversacks/inputFile.txt","r")
Lines = inputFile.readlines()
class bag:
def __init__(self,name,childBags,parentBags) -> None:
self.name = name
self.childBags= childBags
self.parentBags = parentBags
... |
test_case = int(input())
for _ in range(test_case):
a, b, c = [list(input()) for i in range(3)]
# print(a, b, c)
for i in range(len(a)):
if a[i] == c[i]:
b[i], c[i] = c[i], b[i]
elif b[i] == c[i]:
a[i], c[i] = c[i], a[i]
else:
a[i], c[i] = c[i], ... |
import os
import sys
import fam
def extract(datadir, subst_model, index):
for family in fam.get_families_list(datadir):
f = fam.get_raxml_multiple_trees(datadir, subst_model, family)
tree = open(f).readlines()[index]
output = fam.build_gene_tree_path(datadir, subst_model, family, "raxml-ng-" + str(index)... |
import gym
import math
import random
import numpy as np
import tensorflow as tf
import matplotlib.pylab as plt
MAX_EPSILON = 1
MIN_EPSILON = 0.01
LAMBDA = 0.0001
GAMMA = 0.99
BATCH_SIZE = 50
class Model:
def __init__(self, num_states, num_actions, batch_size):
'''
Model definition is the number of states of... |
from flask import Flask,jsonify
import datetime as dt
# Python SQL toolkit and Object Relational Mapper
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from sqlalchemy.pool import StaticPool
engine = create_engine("sqlite:... |
#测试类方法
class student:
company ='saic'
@classmethod
def clsmethod(cl):
print(cl.company)
student.clsmethod() |
import smtplib
from smtplib import SMTPException, SMTPAuthenticationError,\
SMTPSenderRefused, SMTPRecipientsRefused
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
from .models import User
from timesheet import session... |
# coding: utf-8
"""
Задачи для само проверки
"""
# 1
"""
Сформировать возрастающий список из четных чисел от 2 до 10 включительно.
"""
int_list = []
int_list2 = []
n = 10
for i, val in enumerate(range(n+1)):
if i // 2:
int_list.append(val)
int_list = [x for i, x in enumerate(range(2, n+1)) if i... |
t = int(input())
for c in range(t):
input()
print('Y') |
# coding: utf-8
"""
Copyright 2015 SmartBear Software
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 applica... |
import pytest
@pytest.fixture
def client():
from app import app
app.config['TESTING'] = True
return app.test_client() |
# Imports
from django.shortcuts import render
from django.views import generic
# Importing Models
from .models import Post, BlogAuthor, Configuration, PostComment
# Imports for Authentication Views
from django.shortcuts import render, redirect
from .forms import NewUserForm, UserLoginForm
from django.contrib.auth impor... |
from rest_framework import serializers
from .models import FindClosingBracket
class FindClosingBracketSerializer(serializers.ModelSerializer):
class Meta:
model = FindClosingBracket
fields = '__all__'
|
# adapted from mtbatchgen by Zahoor
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from modisco.visualization import viz_sequence
from collections import OrderedDict
import modisco.visualization
import deepdish
import h5py
import numpy as np
import modisco
import argparse
import os
def fetch_... |
import curses
win = curses.initscr()
win.border(0)
win.addstr(0, 1, "Here be the title")
win.refresh()
win.getch()
curses.endwin()
|
class Node:
def __init__(self, key="", count=0):
self.prev = None
self.next = None
self.keys = {key}
self.count = count
def insert(self, node: 'Node') -> 'Node': # 在 self 后插入 node
node.prev = self
node.next = self.next
node.prev.next = node
node.... |
def frange(x, y, jump=1.0):
'''
Range for floats.
Parameters:
x: range starting value, will be included.
y: range ending value, will be excluded
jump: the step value. Only positive steps are supported.
Return:
a generator that yields floats
Usage:
>>> list(... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pdb
import seaborn as sns
if __name__ == '__main__':
sns.set(style="ticks")
hatches = ['----', '/', 'xxx', '///', '---']
colors = ['#FFA500', '#FF0000', '... |
#!/usr/bin/env python
"""Test suite for aospy.io module."""
import sys
import unittest
import aospy.utils.io as io
class AospyIOTestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
class TestIO(AospyIOTestCase):
def test_dmget(self):
io.dmget(['/home/Spen... |
from datetime import datetime
import orm
from .database import database, metadata
class BaseModel(orm.Model):
__abstract__ = True
id = orm.Integer(primary_key=True)
created_at = orm.DateTime(allow_null=True, default=datetime.now())
updated_at = orm.DateTime(allow_null=True)
deleted_at = orm.Dat... |
n = int(input())
h = int(input())
s = float(input())
print('NUMBER = {}\nSALARY = U$ {:.2f}'.format(n, (h * s))) |
# This file is part of beets.
# Copyright 2016, Stig Inge Lea Bjornsen.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use... |
import maya.cmds as cmds
import random
class randoValuez():
def __init__(self):
self.MaxAndMinWin = "Randomizer"
self.RandomValues()
def RandomValues(self):
self.delete()
self.MaxAndMinWin = cmds.window('MaxAndMinWin')
self.colLayout = cmds.columnLayout()... |
#!/usr/bin/python
#from pylab import plot,show,norm
#from pylab import plot,show,norm
#import numpy
import sys
from csv import reader, writer
from decimal import *
#from Carbon.Aliases import true
def load_csv(filename):
samples = list()
with open(filename, 'r') as fd:
csv_reader = reader(fd)
... |
#!/usr/bin/env python
# coding=utf-8
def request(func):
def wrapper():
print("hello, %s" % func.__name__)
func()
print("goodby, %s" % func.__name__)
return wrapper
@request
@request
def hello():
print("hi hulk")
hello() |
from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import Place , Type
def index(request):
image = Place.objects... |
import pygame as pg
from os import path
from settings import *
from sprites import *
from tilemap import *
from pytmx import TiledObjectGroup
from platform import system
from sys import exit
from pygame.locals import *
class Game:
def __init__(self):
pg.init()
flags = FULLSCREEN | DOUB... |
from gevent import monkey; monkey.patch_all()
from gevent.pywsgi import WSGIServer
import web
web.config.debug = False
import gevent
import yaml
import sys
from ezbake.configuration.EzConfiguration import EzConfiguration
from ezbake.configuration.helpers import ZookeeperConfiguration, SystemConfiguration
from ezbake.c... |
import pytest
import os
import numpy as np
from .. import utils
from .. import templates
from .. import filters
from .. import photoz
from .. import filters
from . import test_filters
from . import test_templates
ez = None
# Single redshift for testing
z_spec = 1.0
# Additional catalog objects with random noise
N... |
'''
This module defines :class:`ChannelIndex`, a container for multiple
data channels.
:class:`ChannelIndex` derives from :class:`Container`,
from :module:`neo.core.container`.
'''
import numpy as np
import quantities as pq
from neo.core.container import Container
class ChannelIndex(Container):
'''
A conta... |
from django.shortcuts import render,redirect
from .models import NewUser
from django.contrib import messages
from django.views.generic.base import View
from django.views.generic.base import TemplateView
#renders index page
class indexPage(TemplateView):
template_name = 'index.html'
#view for user registration
cl... |
from helper.my_type import MyType
class Manufacture:
def __init__(self):
self._name = None
def set_name(self, name: str) -> None:
MyType.check("manufacturer name", name, str)
self._name = name
def get_name(self) -> str:
return self._name
|
#!/usr/bin/python
import time
input()
print('started')
start=time.time()
end=start
lap=1
try:
while True:
input()
laptime=round(time.time()-end,2)
tottime=round(time.time()-start,2)
print('Lap %s: %s %s'%(lap,tottime,laptime))
lap+=1
last=time.time()
except KeyboardInterrupt:
print('\nDone')
|
from entity import Entity
# effects act like normal entities, but do not experience collision detection
class Effect(Entity):
def __init__(self,x,y,w,h,dx,dy):
Entity.__init__(self,x,y,w,h,0,0)
self.dx = dx
self.dy = dy
self.debug_color = (0,100,0)
self.feels_gravity = Fal... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Make sure environment files can be suppressed.
"""
import TestGyp
import os
import sys
if sys.platform == 'win32':
test = TestGyp.T... |
import csv
def readCsv():
with open('test.csv', 'r') as f: # 使用上下文打开csv文件
reader = csv.reader(f) # 创建csv阅读器对象
# next(reader)
# 方式一:通过将读取的数据用列表生成式返回
# db = [item for item in reader] # 列表生成式,将读取到的数据放在列表中
# print(type(db))
# 方式二:循环读取文件数据
for item in reader:
... |
import player_info
def count():
for i in range(10):
print(i)
count() |
def capitalize(s,ind):
return "".join([i.upper() if c in ind else i for c, i in enumerate(s)])
'''
Given a string and an array of integers representing indices,
capitalize all letters at the given indices.
For example:
capitalize("abcdef",[1,2,5]) = "aBCdeF"
capitalize("abcdef",[1,2,5,100]) = "aBCdeF". T... |
#!/usr/bin/env python3
# coding: utf-8
import math
#双向
class BiWardNgram():
def __init__(self,word_dic_path,trans_dic_path):
self.word_dict = {} #词语频次词典
self.trans_dict = {} #每个词后接词的出现个数
self.word_counts = 0 #语料库中词总数
self.word_types = 0 #语料库中词种数
wordict_path = word_dic_pat... |
listas = [1, 2, 3, 4, 5, 6, -5]
print(listas)
print(listas[1])
del listas[1]
print(listas)
#Agregar valores en nuestra lista
listas.append('string')
print(listas) |
#!/usr/bin/python3
def no_c(my_string):
new_str = ""
for i in range(0, len(my_string)):
ascii_num = ord(my_string[i])
if ascii_num != 67 and ascii_num != 99:
new_str += my_string[i]
return new_str
|
#!/usr/bin/env python
# encoding: utf-8
# @author: Zhipeng Ye
# @contact: Zhipeng.ye19@xjtlu.edu.cn
# @file: calculate_ngram3.py
# @time: 2020-01-14 01:27
# @desc:
import codecs
import math
import os
import re
import sys
import traceback
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())
class LanguageMod... |
import pandas as pd
import numpy as np
my_list = list('abcd')
my_array = np.arange(4)
my_serie = pd.Series(dict(zip(my_list, my_array)))
print(my_serie.to_frame().reset_index()) |
import configparser
import os
import tkinter
from enum import Enum
from tkinter.filedialog import askopenfilename
class CalculationType(Enum):
MEDALS = "meals"
SHARDS = "shards"
def isMedalCalc(self):
return self.value == self.MEDALS.value
def isShardCalc(self):
return self.value == ... |
from django.shortcuts import render
import numpy as np
import pandas as pd
from django.views.generic import ListView, View
from django.views import View
m_df = pd.read_csv('ipl_analysis/matches.csv')
d_df = pd.read_csv('ipl_analysis/deliveries.csv')
class Index(View):
template_name = "index.html"
def get(s... |
# ============LICENSE_START=======================================================
# Copyright (c) 2017-2021 AT&T Intellectual Property. All rights reserved.
# ================================================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not... |
class WaitlistNames:
logi = "logi"
dps = "dps"
sniper = "sniper"
xup_queue = "queue"
other = "other"
DEFAULT_PREFIX = "default"
|
import re
def find_episode_titles(series):
raise NotImplementedError()
def best_movie_from_year(year, minimum_count = 10000):
raise NotImplementedError()
def episode_count():
raise NotImplementedError()
def series_average_ratings():
raise NotImplementedError()
|
# -*- coding: utf-8 -*-
"""Application configuration."""
import os
class Config(object):
"""Base configuration."""
SECRET_KEY = os.environ.get('FLASKAPP_SECRET')
APP_DIR = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir))
ASSETS_DEBUG = Fa... |
"""add type check utils"""
def type_check(obj: object, type_name: str) -> bool:
"""
circulation dependency problems can be resolved by TYPE_CHECKING,
but this can not resolve NO type linting problems. eg:
if isinstance(msg, Contact):
pass
in this problem, program don't import Conta... |
# https://www.hackerrank.com/challenges/py-collections-deque
'''collections.deque()
A deque is a double-ended queue.
It can be used to add or remove elements from both ends.
Deques support thread safe, memory efficient appends and pops
from either side of the deque with approximately
the same performance in either d... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from textwrap import dedent
import pytest
from pants.backend.kotlin.dependency_inference import kotlin_parser, symbol_mapper
from pants.backend.kotlin.dependency_inference.rules import (
... |
a = input("정수 입력(a) :")
b = input("정수 입력(b) :")
if (a % 2 == 0) and (b % 2 == 0) :
print("두 수 모두 짝수입니다.")
if (a % 2 == 0) or (b % 2 == 0) :
print("두 수 중 하나 이상이 짝수입니다.") |
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('value-benchmarks-2019-01.csv')
x1, y1 = [], []
x2, y2 = [], []
for n, r in df.iterrows():
name = '%s-%s-%s' % (r['func'], r['depth'], r['sparsity'])
if r['sparsity'] == 1:
x1.append(name)
y1.append(r['ns'])
else:
... |
l, r = int(input()), int(input()) / 100
count = 1
result = 0
while True:
l = int(l*r)
if l <= 5:
break
result += (2**count)*l
count += 1
print(result)
|
# -*- coding: utf-8 -*-
# netos/urls.py
from django.conf.urls import url
from django.contrib import admin
from django.urls import path
from . import views # import of application views
app_name = 'netos' # application namespace
urlpatterns = [
url(r'^$', views.index, name='index'),
u... |
rlen,r=map(int,input().split())
if rlen<r:
rlen,r=r,rlen
l=[]
for m in range(r):
temp=list(map(int,input().split()))
temp.sort()
l.append(temp)
for i in range(rlen):
t=[]
for j in range(r):
t.append(l[j][i])
t.sort()
for j in range(r):
l[j][i]=t[j]
for i ... |
print("布尔表达式")
print(True,False)
# result: True,False
print(True == 1)
# result: True
print(True + 2)
# result: 3
print(True + False*3)
# result: 1
print(3 > 2)
# result :True
print((1 < 3)*10)
# reuslt: 10
print('-'*70)
print("条件分支")
# 例1 判断天气
weather = 'sunny'
if weather =='sunny':
print("shopping")
elif weath... |
from django.apps import AppConfig
class LoggingDbConfig(AppConfig):
name = 'logging_db'
|
from django.http import HttpResponse
from django.shortcuts import render
import operator
def home(request):
return render(request,'index.html')
def count(request):
fullname = request.GET['fullname']
worldlist = fullname.split();
worddictionary = {}
for word in worldlist:
if word in worddictionary:
#in... |
#!/usr/bin/python
# -*- coding: latin-1
###############################################################################
###############################################################################
## Title: brain_inspect.py #
## Author: Jose Etxebe... |
class Solution:
def putMarbles(self, weights: List[int], k: int) -> int:
# [9,8,9,1]
minpq, maxpq = [], []
for i in range(len(weights)-1):
heapq.heappush(maxpq, -(weights[i]+weights[i+1]))
heapq.heappush(minpq, (weights[i]+weights[i+1]))
while len(maxpq) ... |
import re
from ..lib import keyword_utils
def recover_full_name(ori_sentence, func):
if func not in ori_sentence:
return ""
index = ori_sentence.index(func)
end_index = index + len(func) - 1
while index >= 0 and ori_sentence[index] != " ":
index -= 1
return ori_sentence[index+1:end_... |
bingo = [
[0, 1, 1, 1, 1],
[0, 1, 0, 1, 0],
[0, 1, 1, 1, 0],
[1, 1, 1, 1, 1],
[1, 1, 0, 1, 0],
]
hantei = 0
for m in range(5):
for n in range(5):
if bingo[m][m] == bingo[n][m]:
hantei += 1
if hantei == 5:
print(str(m))
hantei = 0
|
import numpy as np
from rpy2.robjects import numpy2ri
numpy2ri.activate()
from rpy2.robjects.packages import importr
stats = importr('stats')
# x : np.ndarray
# window : int
# -> (np.ndarray, np.ndarray, np.ndarray)
def stl_r(x, window):
ts = stats.ts(x, frequency=window)
dec = np.array(stats.stl(ts, s_window=windo... |
# while practice
# 打印100以内的偶数之和
# help(range)
# 方法一
i = 0
sum = 0
while i <= 100:
sum += i
i += 2
print("sum = %d" % sum)
# 方法二
i = 0
sum = 0
while i <= 100:
if i%2 == 0:
sum += i
i += 1
print("sum = %d" % sum)
# 方法三
i = 0
sum = 0
while i <= 100:
if i%2 == 1:
i += 1
else:
... |
# -*- coding: utf-8 -*-
#text_manip.py
import re
import urllib2
# import unicodedata
from bs4 import BeautifulSoup
# import nltk
# from xgoogle.search import GoogleSearch, SearchError
import os
import random
def HTML_attribute_content_replace(text, attr, current, replace_with):
return text.replace('%s="%s'%(attr,cur... |
"""
关于八皇后问题的一些解法,包括回溯法之类的方法。
八皇后问题其实是一种十分经典的问题,简单来说在8×8的国际象棋棋盘里边,如何摆放8个皇后,用到递归或者动态规划法之类的,是值得研究的问题。
详细介绍可以看看这一篇文章,介绍的十分详细。
https://www.cnblogs.com/franknihao/p/9416145.html
"""
# 方法一,暴力迭代法。
def checkPos(positionArray):
for i in range(len(positionArray)):
for j in range(len(positionArray)):
if i != j:
... |
"""PreFilter Policies Class."""
from fmcapi.api_objects.apiclasstemplate import APIClassTemplate
import logging
import warnings
class PreFilterPolicies(APIClassTemplate):
"""The PreFilterPolicies Object in the FMC."""
VALID_JSON_DATA = ["id", "name", "type", "description", "defaultAction"]
VALID_FOR_KWA... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from . import WPRPCCommand
class Command(WPRPCCommand):
help = 'Get list of blogs on a wordpress installation.'
def handle(self, url=None, **optz):
server, user, password = self.parse_rpc_endpoint(url, **optz)
self.print_data(server.wp.getUsersB... |
import random
import networkx as nx
import copy
from paras import TIME_THRE, SIMU_THRE
import time
from Timers import Timer
from paras import A1, A2, A3, A4
from paras import C
import numpy as np
from math import log
class mcts(object):
# 如果考虑linking,有args,为entity_mention, mention_entity
def __init__(... |
from lib.Database import Database
async def main(args):
if len(args) == 0: print("What you want to do? [reset]")
else:
if args[0] == "reset": await database_reset()
async def database_reset():
db = Database()
await db.reset() |
from Notes.forms import SearchBarForm
def SearchBarContext(request):
"""
Produces a context variable for the searchbar that's available across
all pages.
:param request:
:return:
"""
return {'searchbar':SearchBarForm()}
def SetCurrentCourses(request):
"""
Produces a context variab... |
from django.db import models
# Create your models here.
class Lecturer(models.Model):
name = models.CharField(max_length=128)
capacity = models.PositiveSmallIntegerField(default=0)
def __str__(self):
return self.name
class Project(models.Model):
name = models.CharField(max_length=128)
de... |
import os
import io
import sys
import errno
import signal
import socket
import logging
PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(
os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(
os.path.join(SCRIPT_DIR, PACKAGE_PARENT, PACKAGE_PARENT)))
fro... |
from django.test import TestCase
import pytest
# Create your tests here.
from datetime import datetime, timedelta
from django.contrib.auth.models import User, Group
from snippets.models import Snippet, CoursePage, CourseList
from django.utils import timezone
class SnippetModelTest(TestCase):
@classmethod
... |
from _typeshed import Incomplete
def gn_graph(
n,
kernel: Incomplete | None = None,
create_using: Incomplete | None = None,
seed: Incomplete | None = None,
): ...
def gnr_graph(
n, p, create_using: Incomplete | None = None, seed: Incomplete | None = None
): ...
def gnc_graph(
n, create_using: I... |
class CornishPlot:
pass |
#-------------------------------------------------------------------------------
# Name: ANSYS Wrapper Generator GUI
# Owner: Mechanical Solutions Inc.
#
# Author: Kyle Lavoie, Mechanical Solutions Inc.
#
# Created: 5/14/2013
# Copyright: (c) Mechanical Solutions Inc.
#--------------------------... |
import turtle
myxloc = 0
myyloc = 0
scr=turtle.Screen()
locations = [[0,0],[0,1],[0,2],[0,3]]
scr.listen()
while True:
def moveleft():
myxloc = myxloc -1
print(myxloc,myyloc)
def moveright():
myxloc = myxloc + 1
print(myxloc, myyloc)
scr.onkey(moveleft,'a')
scr.onkey(moveleft,'d')
|
import os
from shutil import copyfile, rmtree
from abc import ABC, abstractmethod
from ronto import verbose, dryrun, run_cmd
from ronto.model import get_model, get_value, get_value_with_default
def get_init_build_dir():
BUILD_DIR = "build" # default from poky
return get_value_with_default(["build", "build_d... |
from modules import utility
import shopping.shopping_cart
# import shopping.more_shopping.shopping_cart
from shopping.more_shopping.shopping_cart import buy
import random
import sys
my_list = [1, 2, 3, 4, 5]
print(utility)
print(shopping.shopping_cart.buy('apple'))
print(buy('banana'))
# prints a random number betwee... |
# -*- encoding:utf-8 -*-
# __author__=='Gan'
# Given a binary tree, find the length of the longest path where each node in the path has the same value.
# This path may or may not pass through the root.
# Note: The length of path between two nodes is represented by the number of edges between them.
# Example 1:
# Input... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# Example : open/read/close a file with gfal 2.0
#
import sys
import os
import gfal2
max_size=10000000 # maximum size to read
## main func
if __name__ == '__main__':
# comment for usage
if(len(sys.argv) < 2):
print "\nUsage\t %s [gfal_url] \n"%(sys.argv[0])
print " ... |
x=4
print(type(x))
x="edo okati"
print(type(x)) |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
from scipy.stats import norm
# 0 | . | 0.5 1 0
# 1 | . . | 0.25 0.5 1 2
# 2 |. . . .| 0.125 0.25 3 4 5 6
# 3 7
def show(fig):
if False:
fig.show()
else:
fig.suptitle... |
#!/usr/bin/python
from tkinter import Tk, Canvas, Frame, BOTH
import random
import numpy as np
from time import sleep
import matplotlib.pyplot as plt
import pickle
import sys, getopt
#Allowed moves in the board
moves = ['UP','LEFT','RIGHT','DOWN']
oposite_moves = {'UP': 'DOWN', 'DOWN': 'UP', 'LEFT': 'RIGHT','RIGHT':... |
#!/usr/bin/env python
# encoding: utf-8
# @Time : 2019/5/7 15:29
# @Author : lxx
# @File : yuyiCorrector.py
# @Software: PyCharm
import kenlm
import jieba
all_train=[]
for line in open("data/data.train",encoding="utf-8"):
line=line.strip()
line=line.split("\t")
sentens=line[2:]
if len(sentens) ... |
import botostubs
import boto3
import json
boto_session = boto3.Session(profile_name='personal')
photo = 'assets/group_selfie.jpg'
rekognition: botostubs.Rekognition = boto_session.client('rekognition',region_name='ap-south-1')
with open(photo, 'rb') as image:
response = rekognition.recognize_celebrities(
... |
import json
def read_json_file(file_to_read) -> object:
# Opening JSON file
json_file = open(file_to_read, "r")
# returns JSON object as dictionary
json_data = json.load(json_file)
# print(json_data[0]["pid"])
# Closing file
json_file.close()
return json_data
|
import requests
import json
def monero():
get_ = requests.get("https://api.cryptonator.com/api/ticker/xmr-usd", headers={"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"})
jsonData = json.loads(get_.text)
return float(j... |
import os
import torch
from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, TensorDataset)
from Utils.data_class import InputExample, InputFeatures
def read_examples(filename):
with open(filename, 'r') as f:
lines = [data.strip().split('\t') for data in f.readlines()]
exam... |
from fastapi_scaffolding.core import messages
def test_auth_using_prediction_api_no_apikey_header(test_client) -> None:
response = test_client.post('/api/model/predict')
assert response.status_code == 400
assert response.json() == {"detail": messages.NO_API_KEY}
def test_auth_using_prediction_api_wrong_... |
score = int(input("0点から100点までの得点を入力してください:"))
if score >= 0 and score < 60:
print("不合格です")
elif score >= 60 and score <= 100:
print("合格です")
if score >= 80:
print("素晴らしい成績ですね")
else:
print("範囲外の得点です")
"""
実験結果1(2)
入力 score : メッセージ
-1,101 : 範囲外の得点です
0,1,59 : 不合格です
60,61,79 : 合格です
80,81... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.