text stringlengths 8 6.05M |
|---|
import xml.etree.ElementTree as etree
class Corpus:
def __init__(self):
self._sentences = []
def load_corpus(self, path_to_file):
tree = etree.parse(path_to_file)
root = tree.getroot()
for sentence in root.iter('sentence'):
for source in sentence.iter('source'):
... |
from django.db import models
from .Musica import Musica
class Categoria(models.Model):
slug = models.SlugField(primary_key=True, max_length=100)
nome = models.CharField(max_length=255)
descricao = models.CharField(max_length=500)
categoria_mae = models.ForeignKey("self", blank=True, null=True)
ordem = models.Posi... |
from random import randint
from prac_08.unreliable_car import UnreliableCar
def main():
new_car = UnreliableCar('Truck', 100, 80)
print(new_car)
random_distance = randint(0, 100)
new_car.drive(random_distance)
print(new_car)
main() |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 29 15:14:17 2019
@author: KelvinOX25
"""
import pyvisa
import time
import logging
import numpy as np
import struct
from qcodes import VisaInstrument, validators as vals
class Tektronix_AWG3252(VisaInstrument):
def __init__(self, name, address, **kw):
... |
from django.contrib import admin
from .models import Podcast
# Register your models here.
class PodcastAdmin(admin.ModelAdmin):
list_display = ('title', 'description', 'image', 'audio', 'completed')
admin.site.register(Podcast, PodcastAdmin)
|
import os
import gtk
import time
import gobject
import threading
import traceback
import envi.bits as e_bits
import envi.config as e_config
import vwidget
import vwidget.main as vw_main
import vwidget.views as vw_views
import vwidget.layout as vw_layout
import vwidget.memview as vw_memview
import vwidget.windows as ... |
'''
Created on Aug 4, 2010
@author: avepoint
'''
from google.appengine.ext import db
from google.appengine.api import users
class MTGCard(db.Model):
name = db.StringProperty(required=True)
edition = db.StringProperty()
color = db.StringProperty()
type = db.StringProperty()
rarity ... |
# 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, software
# d... |
"""
DCC XML Generator Functions
H3A
"""
import os
import dcc
import dccxml
def GenH3A_AEWBParams(handle, h3a_aewb_params, cls_id):
return
def GenH3A_AEWBXML(directory, filebase, params, h3a_aewb_params):
if (os.path.exists(directory) == False):
print ('Creating direct... |
# 第 0013 题: 用 Python 写一个爬图片的程序,爬 这个链接里的日本妹子图片 :-)
import os
import time
from bs4 import BeautifulSoup
import urllib.request
import urllib
def download_pic(url_pic,local_pic):
urllib.request.urlretrieve(url_pic, local_pic)
pass
url = 'https://www.enterdesk.com/zhuomianbizhi/secaibizhi/'
headers = {'User-agen... |
import unittest
from katas.kyu_6.greatest_position_distance import greatest_distance
class GreatestDistanceTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(greatest_distance([0, 2, 1, 2, 4, 1]), 3)
def test_equals_2(self):
self.assertEqual(greatest_distance([9, 7, 1, 2, 3... |
from flask import Flask, abort, flash, make_response, redirect, request, render_template, session, url_for
from functools import wraps
import json
import jwt
import logging
import os
import requests
import settings
import xml.etree.ElementTree as ET
# define our webapp
app = Flask(__name__)
#configuration from settin... |
from ._title import Title
from plotly.graph_objs.histogram2d.colorbar import title
from ._tickformatstop import Tickformatstop
from ._tickfont import Tickfont
|
def get_password_level(pw):
level = 0
letters = 0
numbers = 0
specials = 0
if len(pw) < 8 or " " in pw:
return(level)
for char in pw:
if char.isalpha():
letters += 1
elif char.isnumeric():
numbers += 1
else:
specials += 1
if... |
# -*- coding: utf-8 -*-
'''测试函数的定义和调用'''
#有返回值得函数
def func01():
print('hello world!')
return '世界,你好!'
#没有返回值得函数
def func02():
print('good luck!')
#直接调用
func01()
func02()
print('------分割线-------')
#直接调用并使用返回值
print(func01())
print(func02())
#多次调用
print('------分割线-------')
for _ in range(2):
print(fun... |
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
row = amount + 1
column = len(coins) + 1
K = [[-1 for x in range(row)] for y in range(column)]
for i in range(row):
K[0][i] = 0
for i in range(column):
K[i][0] = 1
for i in... |
def program():
fr = open("manout.txt","w")
with open("manin.txt", "r") as f:
data = f.readlines()
for line in data:
words = line.split()
Ishr = int(words[0])
Clem = int(words[1])
IshrMan = int(words[2])
ClemMan = int(words[3]... |
from string import ascii_uppercase as az, maketrans
class CaesarCipher(object):
def __init__(self, shift):
self.shifted = az[shift:] + az[:shift]
self.decode_trans = maketrans(self.shifted, az)
self.encode_trans = maketrans(az, self.shifted)
def decode(self, s):
return s.upper... |
import multiprocessing
import psutil
MEMORY_PER_JOB = 1024 * 1024 * 1024
def _calculate_jobs():
jobs_cpu = multiprocessing.cpu_count()
avail_mem = psutil.virtual_memory().available
jobs_mem = int(avail_mem / MEMORY_PER_JOB)
return min(jobs_cpu, jobs_mem)
def run(param):
if 'make_jobs' in param[... |
#!/usr/bin/python
# -*- coding: utf8 -*-
# auth : bluehdh0926@gmail.com, suck0818@gmail.com
# setting management json
import json, os, platform
class syncn(object):
def __init__(self, path='', debug=False):
try:
self.debug = debug
self.path = os.getcwd()+"\\setting.json"
... |
def is_pandigital(n):
s = str(n)
for it in (iter(reversed(s)), iter(s)):
mem = []
for i in range(9):
try:
digit = next(it)
except StopIteration:
return False
else:
if digit == '0' or digit in mem:
... |
count=0
def is_palindrome(word):
"""
Reversing the string
:param input: word
:return: reversed word
"""
w=""
count = -1
for i in word:
w+=word[count]
count+=-1
if w==word:
print("TRUE")
else:
print("FALSE")
is_palindrome("abba")
is_palindrome("ab... |
#Advent of Code 2020 - Day8
import copy
def get_input(file):
with open(file, 'r') as f:
return f.read().split('\n')
all_conditions = get_input('day8_input.txt')
all_conditions_test = get_input('day8_test.txt')
def day8(input_val):
accumulator = 0
unique_vals = []
counter = 0
loop = False
... |
import cmd
import connection
class pyccConsole(cmd.Cmd):
debug=True
prompt = '> '
def __init__(self, backendConnection, logicThread, todoQueue, notifyEvent, *args, **kargs):
cmd.Cmd.__init__(self,*args,**kargs)
self.backendConnection = backendConnection
self.logicThread = logicThread
self.todoQueue = tod... |
#Algorithme d'optimisation
import math as m
import time
import cvrp.const as const
import cvrp.utile as utile
import cvrp.learning as learn
import cvrp.route as route
import cvrp.linKernighan as LK
import cvrp.ejectionChain as EC
import cvrp.crossExchange as CE
import cvrp.ClarkeWright as CW
def gravity_center(route... |
# libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('MELBOURNE_HOUSE_PRICES_LESS.csv')
sample_mean = []
for iteration in range(100):
df_subsample = df.sample(1000)
mean = df_subsample['Price'].mean()
sample_mean.append(mean)
plt.hist(sample_mean, bins=10, density=... |
# -*- coding: utf-8 -*-
import scrapy
import os
import csv
class MyradiosSpider(scrapy.Spider):
name = 'myradios'
allowed_domains = ['my-radios.com']
start_urls = ['http://my-radios.com/']
def parse(self, response):
datas = response.xpath('.//*[@class="list-inline intro-social-buttons"]/li').... |
import unittest
from katas.kyu_7.alphabetize_by_nth_char import sort_it
class SortItTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(sort_it('bid, zag', 2), 'zag, bid')
def test_equals_2(self):
self.assertEqual(sort_it('bill, bell, ball, bull', 2),
... |
# Exercício 10.1 - Livro
class Televisao:
def __init__(self):
self.ligada = False
self.canal = 0
self.tamanho = 0
self.marca = ''
t1 = Televisao()
t1.tamanho = 32
t1.marca = 'AOC'
print(f'TV {t1.marca} de {t1.tamanho} polegadas')
t2 = Televisao()
t2.tamanho = 42
t2.marca = 'Samsnug... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# File: osc4py3/demos/speedudpcommon.py
# <pep8 compliant>
"""Common data for testing UDP transmission speed.
"""
MESSAGES_COUNT = 1000
IP = "127.0.0.1"
PORT = 6503
|
from flask import Flask, render_template
app = Flask('HelloApp')
@app.route('/')
def helloWorld():
return render_template(
'layout.html',
title='HELLOOOOOO WORLLLLLLD',
hello='Hello World!!!!!'
)
if __name__ == '__main__':
app.run(debug=True)
|
from decodeNYTpage import decodeWebPage
def writeToFile(content):
with open('NYT_webpages.txt','w') as open_file:
open_file.write(content)
if __name__=="__main__":
writeToFile(decodeWebPage())
|
#Area of rectange
l=int(input("Enter length"))
b=int(input("Enter breadth"))
area=l*b
print("area is",area) |
import datetime
from collections import OrderedDict
from django.db.models import Count, Q
from django.db.models.functions import TruncDate
from django.utils import timezone
from django.utils.translation import gettext as _
from colossus.apps.subscribers.constants import ActivityTypes
from colossus.apps.subscribers.mo... |
from distutils.core import setup
setup(name='uff',
version='0.6.3',
description='uff',
author='Nvidia',
packages=['uff'],
)
|
import requests
from bs4 import BeautifulSoup
import pandas as pd
from TickersList import tickers
import re
# Column names that are needed in the pandas dataframe
column_names = ['Ticker','Company Name','BusinessType','Date','Open','High','Low','Beta',
'VWAP','Market Cap All Classes', 'Dividend',
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement
from revolver import command, file, package
from revolver import contextmanager as ctx
def install():
package.install('stunnel')
with ctx.sudo():
file.sed('/etc/default/stunnel4', 'ENABLED=0', 'ENABLED=1')
de... |
numero_a_adivinar = 20
numero_del_usuario = int(input("ingresa un numero del 1 al 30"))
if numero_a_adivinar == numero_del_usuario:
print("mut bien")
else:
intento_dos = int(input("ingresa un numero del 1 al 30 2"))
print("mal, intentalo devuelta")
if numero_a_adivinar == numero_del_usuario:
print("mu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def next_weekday(d, weekday):
# Returns the next weekday for a datetime
days_ahead = weekday - d.weekday()
if days_ahead <= 0: # Target day already happened this week
days_ahead += 7
return d + datetime.timedelta(days_ahead)
def newyear(d... |
import requests
import bs4
from bs4 import BeautifulSoup
import re
import pandas as pd
from time import sleep, time
from warnings import warn
import numpy as np
#From year 2000 to 2017
#Scraping the first four pages of each year
pages = [str(i) for i in range(1,5)]
years_url = [str(i) for i in range(2000, 2018... |
import json
from ..constantes import *
from util import *
def create_chart(conf, entries):
"""
Update Chart configuration and Datas
"""
serie_index = 0
for serie in conf['series']:
data = []
for entry in entries:
if entry is not None:
dat... |
#display.py
#***********************************************
#GlassClient RJGlass
#display.py -- Used to initalize the display and windows for pyglet
#
#***********************************************
import os
import logging
import pyglet
from pyglet.gl import *
from xml.etree.ElementTree import ElementTree
import ... |
#!/usr/bin/env python
try:
import urllib.request
from urllib.parse import urlparse
import bs4 as bs
import sys, subprocess, os, zipfile
except ModuleNotFoundError as e:
print("[*] Error: ", e)
sys.exit()
def search_subs():
# entering 'movie name' into url
url = "http://... |
import random
print('Welcome to the number guessing game')
number_to_guess= random.randint(1,10)
number_of_tries=1
guess=int(input('Please guess the number'))
while number_of_tries<=1:
print("chance",number_of_tries,"\n")
if number_to_guess==guess:
print('Well done, you win!')
pri... |
from panda3d.core import GeomVertexFormat, GeomVertexWriter, Vec4
from .Geometry import Geometry
from .PolygonView import PolygonView
class Polygon(Geometry):
def __init__(self):
Geometry.__init__(self, "polygon", GeomVertexFormat.getV3c4())
self.vertices = []
self.color = Vec4(1, 1, 1, 1... |
# 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, software
# d... |
from django.urls import path
from .views import *
app_name = 'iot'
urlpatterns = [
path('create', create_iot, name='iot_create'),
path('validate-serial-no', validate_serial_no, name='validate_serial_no'),
path('validate-plate-no', validate_plate_no, name='validate_plate_no'),
path('iot-list',iot_list,n... |
from flask import *
app = Flask(__name__)
app.secret_key = 'my precious'
@app.route('/')
def home():
return render_template('home.html')
@app.route('/boiler_installation')
@app.route('/boiler_servicing')
@app.route('/plumbing')
@app.route('/bathroom_installation')
@app.route('/other_services')
def services():
... |
import time
from mock import patch
from nose.tools import assert_equals, assert_true, assert_not_in, assert_in, assert_not_equals
from ckanpackager.lib.statistics import CkanPackagerStatistics, statistics, extract_domain, \
anonymize_email, anonymize_kwargs
class TestStatistics(object):
def setUp(self):
... |
"""Tree traversal problems
- DFS: Depth-firt search
- BFS: Breadth-first search
"""
if __name__ == '__main':
# Recursion will first find the last iteration, and then execute all bottom
# to the top.
#
# This is know as Depth-firt search (DFS), this method allocate all memory and
# then remove afte... |
VALID = frozenset('abcdefABCDEF')
def fisHex(s):
return reduce(lambda b, c: b ^ c, (int(a, 16) for a in s if a in VALID), 0)
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def buildList(root):
a=[]
if root == None:
a.append("bozo")
return a
elif root.left == None and root.right == None:
a.append(root.val)
... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.kotlin.goals import debug_goals
def rules():
return debug_goals.rules()
|
from django import forms
from .models import Msg
class MsgForm(forms.ModelForm):
class Meta:
model = Msg
fields = ('name', 'title', 'text',)
|
# -*- coding: utf-8 -*-
class Solution:
def transpose(self, A):
return [[A[j][i] for j in range(len(A))] for i in range(len(A[0]))]
if __name__ == "__main__":
solution = Solution()
assert [[1, 4, 7], [2, 5, 8], [3, 6, 9],] == solution.transpose(
[
[1, 2, 3],
[4, ... |
# File: proj3.py
# Author: Maura Choudhary
# Date: 12/4/18
# Section: 20
# E-mail: maurac1@umbc.edu
# Description: This program allows a user to play or solve a sudoku puzzle
# Constants for the board
MIN_NUM = 1
MAX_NUM = 9
EMPTY = 0
SEPARATOR = ","
BOX1 = [1, 2, 3]
BOX2 = [4, 5, 6]
BOX3 = [7, 8, 9]
# Constants for ... |
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from abc import ABCMeta, abstractmethod
from dataclasses import dataclass
from pathlib import Path
from textwrap import dedent
from typing import Any, I... |
from sys import argv
import random
script = argv
max_q = int(input("max_q available-->"))
file=open("quess.txt", 'a')
def entry():
global ques_no
print("""Enter the option of operation which you want to do
1.face questions 2.assign answers""")
a = int(input("..."))
if a == 1:... |
# pylint: disable=g-bad-file-header
# Copyright 2015 The TensorFlow Authors. 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/LICENS... |
from gi.repository import GObject
import xml
from Coordinates import Coordinates
class Action(GObject.Object):
#__metaclass__ = abc.ABCMeta
__gsignals__ = {
"abstract_signal" : (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, ( GObject.TYPE_OBJECT,))
}
def __init__(self):
GObject.Object.__init__(self)
self.pr... |
from django.shortcuts import render, redirect, HttpResponseRedirect, reverse
from subreddit.models import Subreddit
from subreddit.forms import SubredditCreationForm
from reddituser.models import RedditUser
from post.models import Post
from subreddit.helper import random_subreddits, subreddit_search
import random
if S... |
import pandas as pd
import numpy as np
import datetime
import math
from datetime import timedelta, date
exclude_days = [date(2020, 3, 1), date(2020,3,8), date(2020,3,15), date(2020,3,22), date(2020,3,25), date(2020,3,29), date(2020,3,30), date(2020,3,31)]
deliveries_df = pd.read_csv("delivery_orders_march.csv")
... |
import socket
import os
server_Host = 'localhost'
server_Port = 7343
client = socket.socket()
client.connect((server_Host,server_Port))
data_empty = ''
data_empty = data_empty.encode()
while True:
print("------------------------")
f = open("D:\own.txt",'ab+')
f_l = open("D:\limit.txt",'wb+')
data = ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 12 01:25:40 2018
@author: ck807
"""
import os, glob
import cv2
import numpy as np
from keras.preprocessing.image import img_to_array
##################################################################################################################... |
import numpy as np
import math
T = 1.0
dens = 0.9
sigma=1
epsilon=1
print "hello world!"
def fill_init_pos(n, positions):
m = int((n/4)**(1.0/3)+0.01) #amount of unit cells per direction
print "m: ",m
a=(4.0/n)^(1./3)
#do things
positions[0]=[0.0,0.0,0.0]
positions[1]=[0.5,0.5,0.0]
positions[2]=[0.5,0... |
#!/usr/bin/env python
import roslib
roslib.load_manifest('baxter_rr_bridge')
import rospy
import baxter_interface
from std_msgs.msg import Empty
import sys, argparse
import struct
import time
import RobotRaconteur as RR
import thread
import threading
import numpy
from geometry_msgs.msg import (
PoseStamped,
P... |
# 计算测试数据
import numpy as np
import src.utils as utils
import gc
if __name__ == '__main__':
malls = utils.get_malls()
conn = utils.get_db_conn()
cur = conn.cursor()
i = 1
for mall_id in malls:
print(utils.get_time(), ' ','start handle mall ', mall_id)
# xgb获取模型
# model = ... |
#!/usr/bin/python3.6
from collections import Counter
set_of_string = "aaaasddddrrrww+++wwcccxxx+++"
my_counter = Counter(set_of_string)
print(my_counter)
# print(my_counter.items())
# print(my_counter.keys())
# print(my_counter.values())
# print(my_counter.most_common(2))
# print(my_counter.most_common(2)[0][0])
p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: trainer.py
# Author: Qian Ge <geqian1001@gmail.com>
import os
import scipy.misc
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib.patches as patches
class Trainer(object):
def __init__(self, model, trai... |
'''
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
Example 1:
Input:
s: "cbaebabacd" p: "abc"
Output:
[0, 6]
E... |
"""empty message
Revision ID: d82dd1e7ad3c
Revises: 9bb2d69fbd7f
Create Date: 2018-10-26 10:44:16.979729
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd82dd1e7ad3c'
down_revision = '9bb2d69fbd7f'
branch_labels = None
depends_on = None
def upgrade():
# ... |
import pytest # noqa: F401 (imported but unused)
import numpy as np
from osmo_camera import tiff as module
from osmo_camera.constants import DNR_TO_TIFF_FACTOR
@pytest.mark.parametrize(
"name, test_rgb_image",
[
(
"Within [0, 1) DNR",
# fmt: off
np.array(
... |
print("Bonjour")
print("Ludovic")
print("fama")
print("Bazdar")
print("BOUGUERRA")
print("fama")
print("modif Lova")
print("aziz")
|
import facebook
class FacebookMessenger:
def __init__(self):
self.graph = facebook.GraphAPI(
"__REMOVED__")
def post_message(self, msg):
try:
self.graph.put_object("__REMOVED__", "feed", message=msg)
print "Facebook success"
except Excep... |
'''
Why 0.1*10 == 1
The exact value of decimal 0.1 can't be represented in 64-bit binary floating-point, so it gets rounded to the nearest representable value, which is 0.1000000000000000055511151231257827021181583404541015625.
However, while the exact value of 0.100000000000000005551115123125782702118158... |
import os
#=========1=========2=========3=========4=========5=========6=========7=
''' PARAMETER: a single string
RETURNS: the string with all / replaced with @ '''
def str_encode(string):
return string.replace("/","@")
''' PARAMETER: a single string
RETURNS: the string with all @ replaced with / '''
def... |
# 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 use ... |
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> a=(1,2,3,4,"nikhil")
>>> a[2]=5
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
a[2]=5
TypeError: 'tuple' object... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-10-06 09:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app1', '0001_initial'),
]
operations = [
migrations.AddField(
mod... |
#!/usr/bin/env python3
import sys
import json
from util.aoc import file_to_day
from util.input import load_data
def main(test=False):
numbers = [
json.loads(line) for line in load_data(file_to_day(__file__), test)
]
p1_res = numbers[0]
for num in numbers[1:]:
p1_res = add(p1_res, nu... |
#!\usr\bin\env python
import os
import sys
import subprocess as sp
dimensions = \
{"merged":63, \
"colorNormalHist":45, \
"colorHSV":3, \
"colorRGB":3, \
"colorH":5, \
"colorS":5, \
"colorV":5, \
"colorHist":30, \
"normal":3, \
"normalX":5, \
"normalY":5, \
"normalZ":5, \
"normalHist":15, \
"fpfh":33, \
"colorHSVNorm... |
#!/bin/env python3
# Level-specific solvers
from . import player
class Level_1_2:
def __init__(self, the_map):
# Get da map
self._map = the_map
# Get da pacman
self._pacman = player.Pacman(the_map.get_items(9), 0)
# Get da ghost
ghost_list = the_map.get_items(2)
... |
#BEGIN_HEADER
import simplejson
import sys
import os
import ast
import glob
import json
import logging
import time
import subprocess
import threading, traceback
from collections import OrderedDict
from pprint import pprint
import script_util
import script_util2
from biokbase.workspace.client import Workspace
from biok... |
from Tested_Method.MethodToTest import working_function_2
from unittest.mock import patch,call
TESTED_MODULE = 'Tested_Method.MethodToTest'
# mocking just the public function
@patch(f'{TESTED_MODULE}.get_element_1', return_value = 10)
@patch(f'{TESTED_MODULE}.get_element_2',return_value= 5)
@patch(f'{TESTED_MODULE}.se... |
class Solution:
def maxSubArray(self, nums):
max_c = max_g = nums[0]
for i in range(1,len(nums)):
max_c = max(nums[i], max_c + nums[i])
if max_c > max_g:
max_g = max_c
return max_g
if __name__ == '__main__':
# nums = [-2, 1, -3, 4, -1, 2, 1, -5... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
# @File:main.py
# @Author: Michael.liu
# @Date:2020/6/30 13:18
# @Desc: this code is ....
from .helper import *
from .decisiontree_model import *
from .gbdt_lr_model import *
import time
import argparse
from .config_xgb import *
from .xgboost_model import *
head_path = './f... |
from setuptools import setup
__author__ = 'Kurt Rose'
__version__ = '0.1dev'
__contact__ = 'kurt@kurtrose.com'
__url__ = 'https://github.com/kurtbrose/relativity'
__license__ = 'MIT'
setup(name='relativity',
version=__version__,
description="Relational object sets.",
long_description=__doc__,
... |
from ctypes import *
from enum import Enum
FT_LIST_NUMBER_ONLY = 0x80000000
FT_LIST_BY_INDEX = 0x40000000
FT_LIST_ALL = 0x20000000
class FT_DEVICE(Enum):
FT_DEVICE_BM = 0
FT_DEVICE_AM = 1
FT_DEVICE_100AX = 2
FT_DEVICE_UNKNOWN = 3
FT_DEVICE_2232C = 4
FT_DEVICE_232R = 5
FT_DE... |
import os
import json
import sys
from infraboxcli.log import logger
def init(_):
p = os.getcwd()
logger.info("Initializing %s" % p)
infrabox_json = os.path.join(p, 'infrabox.json')
if os.path.exists(infrabox_json):
logger.error("%s already exists" % infrabox_json)
sys.exit(1)
doc... |
import time
from math import sqrt, tan, sin, cos, pi, ceil, floor, acos, atan, asin, degrees, radians, log, atan2, acos, asin
from random import *
import numpy
from pymclevel import alphaMaterials, MCSchematic, MCLevel, BoundingBox
from mcplatform import *
import Queue
import utilityFunctions
from helper import *
from... |
from concurrent.futures import ProcessPoolExecutor , wait
import time
executor = ProcessPoolExecutor(max_workers=100)
def task(msg):
print(f"{msg} start!")
time.sleep(1)
print(f"{msg} end!")
return f"{msg} done!"
def print_result(future):
result = future.result()
print(result)
def main():
... |
num_char = len(input("What is your name?\n"))
# print("Your Name has " + num_char + " Characters.") This Line gives Type Error because num_char is of integer Data Type.
print(type(num_char)) #This Line prints The type of num_char i.e. <class 'int'>
# type conversion
new_num_char = str(num_char)
# Now This line work... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 5 14:09:52 2019
@author: PC
"""
import pickle
import xlrd
import os
#打开模型,利用pickle模块
def open_model(path):
with open(path,"rb")as f:
s=f.read()
model=pickle.loads(s)
return model
#加载数据
def load_data(file):
wb=xlrd.open_workbook(file)
... |
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
https://www.cnblogs.com/zhuifengjingling/p/5277555.html
"""
row = [[] for _ in range(9)]
col = [[] for _ in range(9)]
area = [[] for _ in range(9)]
f... |
import argparse
from core.render_markdown import output_md
from core.render_html import output_html
from core.export_ddl import output_ddl_sql
if __name__ == '__main__':
parser = argparse.ArgumentParser(
prog="输出数据库信息到markdown/html/pdf",
usage="""
python main.py -t [type]
""... |
#!/usr/bin/env python
import sys
base_addr = int(sys.argv[1], 16)
f = open(sys.argv[2], 'r') # gadgets
for line in f.readlines():
target_str, gadget = line.split(':')
target_addr = int(target_str, 16)
# check alignment
if target_addr % 8 != 0:
continue
offset = (target_addr - base_addr) / 8
print '... |
#Leo Li
#Sep. 23
#This is guessing game in which the player has to guess the number that the system automatically generates. The player has 7 chances, and the system would make different suggestions according to how far is the user input away from the correct answer. When the game is finished, player can choose to play... |
def lineup_students(string):
return sorted(string.split(), key=lambda x:(len(x), x), reverse=True)
'''
Suzuki needs help lining up his students!
Today Suzuki will be interviewing his students to ensure they are progressing
in their training. He decided to schedule the interviews based on the length
of the stude... |
from __future__ import print_function, unicode_literals
from datetime import timedelta
from django.db import models
from django.db.models import Max, Sum, Count
from django.db.models.query import QuerySet
from django.utils import timezone
from generic_aggregation import generic_annotate
from hitcount.models import Hi... |
"""Point 클래스는 2차원 평면의 점 (또는 2차원 벡터)을 나타내는 클래스이다.
* 필요한 멤버는 점의 x-좌표와 y-좌표이다."""
class Point:
def __init__(self, x=0, y=0):
self.x = x # x-좌표를 위한 멤버 self.x
self.y = y # y-좌표를 위한 멤버 self.y
def __str__(self):
return f"({self.x},{self.y})" # 문자열 출력
#생성함수(magic method 중 하나)__init__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.