text stringlengths 38 1.54M |
|---|
from . import ErrorState
class ScanError(Exception):
def __init__(self, line: int, message: str):
self.line = line
self.message = message
def report(self):
print(f'[line {self.line}] Error: {self.message}')
ErrorState.hadError = True
|
#################################################################################
# FOQUS Copyright (c) 2012 - 2023, by the software owners: Oak Ridge Institute
# for Science and Education (ORISE), TRIAD National Security, LLC., Lawrence
# Livermore National Security, LLC., The Regents of the University of
# California... |
import leafly.search_for_words as sfw
import leafly.nlp_funcs as nl
import leafly.explore_individ_reviews as eir
import pandas as pd
import numpy as np
from scipy import spatial
from fancyimpute import BiScaler, KNN, NuclearNormMinimization, SoftImpute
from sklearn.preprocessing import StandardScaler
import os
import p... |
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tick
import h5py
import colorsys
import argparse
import glob
import sys
from hic import flow
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.patches import Circle
aspect = 1/1.618
resolution = ... |
import cv2
clicked = False
def onMouse(event, x, y, flags, param):
global clicked
if event == cv2.EVENT_LBUTTONUP:
clicked = True
cameraCapture = cv2.VideoCapture(0)
cv2.namedWindow('Live')
cv2.setMouseCallback('Live', onMouse)
print('Showing camera feed. Click window or press any key to stop.')
suc... |
from helpers.post_helper import post_helper
from helpers.user_helper import user_helper
from helpers.user_connection_helper import user_connection_helper
from dal.user_provider import user_provider
from mysql_dal.mysql_user_provider import mysql_user_provider
class profile_helper(object):
def __init__(self, user_... |
from django.urls import path,include
import dl
urlpatterns = [
path('', include('dl.urls')),
]
|
import errors
from api.validator import TokenId, Choose
from model.account.role import Role
class TokenRole(TokenId):
def __init__(self, role):
self.role = role
super().__init__()
def __call__(self, value):
token = super().__call__(value)
if not Role.validate(token.role, self.... |
from adapter.repository.models.usermodel import UserModel
from domain.user import User
class UserRepo:
def __init__(self):
self.users = self.create_users()
def create_users(self):
user_list = []
for n in range(3):
u = UserModel(n, "name" + str(n), n)
user_list... |
import csv
import sys, os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from plot_invisibles import colors
import time
import glob
import re
import json
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument("--channel",ty... |
print('''Crie um Software de gerenciamento bancário. Esse software deverá ser capaz de criar clientes e contas.
Cada cliente possiu nome, cpf, idade.
Cada conta possui um cliente, saldo, limite, sacar, depositar e consultar saldo.''')
from Exercicios.Ex_Aula09_cliente import Cliente
from Exercicios.Ex_Aula09_conta imp... |
def rotate_matrix(matrix):
n = len(matrix)
if n == 0:
return []
print matrix
for i in range(0, (n/2)):
first = i
last = n - 1 - i
for j in range(first, last):
offset = j - first
# save top
top = matrix[first][j]
# right -> top
matrix[first][j] = matrix[j][last]
# bottom -> right
... |
import sys as S
def f(case_number, n):
seen = set()
s = str(n)
for i in range(10**(len(s)+1)):
for d in str(n*(i + 1)):
seen.add(d)
if len(seen) == 10:
break
if len(seen) == 10:
print 'Case #' + str(case_number) + ': ' + str(n * (i + 1))
else:
print 'Case #' + str(case_number) ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 05 19:29:12 2016
@author: Kevin
"""
from directionsAPI import DirAPI
from ElevationAPI import ElevationAPI
from decode import decode
from geopy.distance import vincenty
from math import floor, atan2
from subprocess import call
def getDSVFile(lat1, lng1, lat2, lng2, avdH... |
# -*- coding: utf-8 -*-
n = int(raw_input())
if n % 4 == 0:
print('{} {}'.format(n / 2 - 2, n / 2 + 2))
elif n % 2 == 0:
print('{} {}'.format(n / 2 - 3, n / 2 + 3))
else:
middle = n / 2
first = middle - middle % 3
if first % 2 == 0:
first += 3
second = n - first
print('{} {}'.format... |
from django.urls import path
from rest_framework import routers
from .views import (
QuestionViewSet,
AnswerViewSet,
TagListView,
CategoryListView,
OpenQuestionListView,
SolvedQuestionListView
)
router = routers.DefaultRouter(trailing_slash=False)
router.register('questions', QuestionViewSet, ba... |
def survey1():
answer={}
question=["What is your first name? ","What is your last name? ", "How old are you? ", "What is your birthday? Format in MM/DD/YY ","How much time do you spend on your phone? Type the following options: A little, average, or often."]
data= ["name", "last name", "age", "birthd... |
import ytglobal
import ytSet
import ytGet
print "---Use ytSet() to set global---"
ytSet.SetBrowser()
print "#1 Isolate Method, set browser to: " + ytglobal.runEnv.BROWSER
ytSet.SetPlatform()
print "#2 Class Method, set browser to: " + ytglobal.runEnv.PLATFORM
print "Directly get Browser: " + ytglobal.runEnv.BROWSER... |
# Copyright 2016 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 ... |
from django.shortcuts import redirect
from django.http import HttpResponseRedirect
from django.views.generic.edit import CreateView, DeleteView, UpdateView
from django.views.generic import ListView
from django.urls import reverse_lazy
from django.contrib import messages
import datetime as dt
from .budget_business impo... |
import sys
from Foundation import NSObject, NSLog
from netrepr import NetRepr, RemoteObjectPool, RemoteObjectReference
__all__ = ["ConsoleReactor"]
class ConsoleReactor(NSObject):
def init(self):
self = super().init()
self.pool = None
self.netReprCenter = None
self.connection = N... |
from django.shortcuts import render, redirect, Http404
from django.contrib import messages
from django.contrib.auth import authenticate
from django.contrib.auth import login as _login
from django.contrib.auth import logout as _logout
from django.conf import settings
from appointment.forms.authentication import LoginFo... |
from django.shortcuts import render
from trades.models import Trades
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.db.models import Max
from user.models import Profile
@login_required
def get_data(request):
trades = Trades.objects.filter(user_id=request... |
celebAction = input('Enter a verb...')
Celebrity = input('Please enter the name of a celebrity...')
Gender = input('is that a he, she or they?')
Animal = input('Please enter a type of animal...')
Verb = input('What is the animal doing...')
numberofAnimals = input('How many of them are there?')
print ("%s " "%s " "are" ... |
# formhandler/tpl.py
# Lillian Lemmer <lillian.lynn.lemmer@gmail.com>
#
# This module is part of FormHandler and is released under the
# MIT license: http://opensource.org/licenses/MIT
"""tpl: super simple templater.
"""
import os
TEMPLATE_ROOT = 'tpl'
def template(content, head_filename=None, fo... |
# Generated by Django 2.2.1 on 2019-05-08 03:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mm', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='song',
name='hotComment',
field=... |
# -*- coding: utf-8 -*-
# Scrapy settings for Doubanspider project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/... |
#!/usr/bin/python
import sys
def compute(prey, otherHunter, dist):
temp0 = max( otherHunter[0] , otherHunter[0] )
temp1 = otherHunter[0] - otherHunter[0]
temp1 = min( prey[1] , dist )
if temp0 > prey[0] :
temp0 = otherHunter[1] - temp0
else:
if otherHunter[1] != 0:
temp0 = dist % otherHunter[1]
else:
... |
from flask import render_template, flash, redirect, session, url_for, request, abort
from flask.ext.login import login_user, logout_user, current_user, login_required
from smh import app, db, lm, blogic
from smh.forms import LoginForm, NameForm
from smh.models.models import User, Post
from datetime import datetime... |
import re
from collections import defaultdict
import argparse
import os
from numpy.random import shuffle
def read_examples(f):
example_lines = []
for line in f.readlines():
if line.strip() == '':
if example_lines:
yield Example.from_lines(example_lines)
examp... |
import numpy as np
def trimboth(a, proportiontocut, axis=0):
"""
Slices off a proportion of items from both ends of an array.
Slices off the passed proportion of items from both ends of the passed
array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and**
rightmost 10% of scores). The ... |
from ProblemConfigurations.Hallway import generate_hallway_problem, generate_hallway_reeb_graph
import matplotlib.pyplot as plt
from Drawing import draw_problem_configuration
from DRRRT import augment_reeb_graph
environment, robot, start, goal = generate_hallway_problem()
reeb_graph = generate_hallway_reeb_graph()
dr... |
"""TDGam Component, sub-class of TDGamContainer."""
import re
import json
import logging
from pprint import pformat
from .plugins import TouchDesigner
from .container import TDGamContainer
class TDGamComponent(TDGamContainer):
"""Class to interface with the selection of ops by the user.
These ops need to be... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 11 08:29:29 2021
Autores:
SANTIAGO GAONA CARVAJAL
LUIS DIAZ DIAZ
"""
from timeit import default_timer
def fib(n): #Funcion Fibonacci Iterativo
terminos = [0,1]
i = 2
while i <= n:
terminos.append(terminos[i-1]+terminos[i-2]) #Fibonacci
... |
#!/usr/bin/env python3
import math
import random
import sys
# enumerate(A[1:],1) the second 1 means the index start from 1
# because of the slice, the first item in A is excluded, you need the start=1
# so the index is the same as the index of A.
def buy_and_sell_stock_twice(prices):
max_total_profit, min_price_so... |
import os
import zipfile
import random
import json
import paddle
import sys
import numpy as np
from PIL import Image
from PIL import ImageEnhance
import paddle.fluid as fluid
from multiprocessing import cpu_count
import matplotlib.pyplot as plt
from model import VGGNet
from data_processor import *
d... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 18 09:11:33 2017
@author: beoka
"""
import numpy as np
import App
import Vector
import Body
from PIL import Image
import struct
Q = Vector.Quaternion.fromArray
from pybullet import getQuaternionFromEuler as eToQ
class Level(object):
""" Houses all the code necessary... |
import client
import os
import logging
import numpy as np
import pickle
import random
import sys
import shutil
import torch
import utils.dists as dists # pylint: disable=no-name-in-module
from utils.fl_model import load_weights, extract_weights # pylint: disable=no-name-in-module
from datetime import datetime
import ... |
import numpy as np
import math
import random
##initialization
ts_rew = 0
ad_feat = []
d = 10 #dimension
delta = input("Delta : ") #preferably 0.05
delta = float(delta)
B = [np.identity(d)] #B deals with contexts, 10 is dimension of context
mu_hat = [np.zeros(d)] #parameter which we want to estimate
f = [np.zeros(d)]
... |
#!/usr/bin/env python
# coding: utf-8
# # Assignment 1
# ## Python Basic Programs
# ### 1. Print Hello world! :
# In[ ]:
print("Hello world!")
# ### 2. Declare the following variables: Int, Float, Boolean, String & print its value.
#
# In[ ]:
a = 10
print(a, "is of type", type(a))
b = 5.0
print(b, "is a ty... |
import os
import shutil
import re
def remove_dir(rm_dir):
dir_under = os.listdir(rm_dir)
for each in dir_under:
filepath = os.path.join(rm_dir, each)
if os.path.isfile(filepath):
try:
os.remove(filepath)
except:
print("remove %s error." % ... |
import sys
import json
from deriva.core import ErmrestCatalog, AttrDict, get_credential, DEFAULT_CREDENTIAL_FILE, tag, urlquote, DerivaServer, get_credential, BaseCLI
from deriva.core.ermrest_model import builtin_types, Schema, Table, Column, Key, ForeignKey, DomainType, ArrayType
import utils
import traceback
tables ... |
import shutil
import subprocess
from pathlib import Path
import pytest
from cookiecutter.main import cookiecutter
from common import EXTRA, PARAMS, OUTPUT_DIR
@pytest.fixture(autouse=True)
def post_build():
if Path(OUTPUT_DIR).is_dir():
shutil.rmtree(OUTPUT_DIR)
yield
try:
container_bui... |
#coding:utf-8
__author__ = 'findme'
import warnings
warnings.filterwarnings("ignore")
import jieba #分词包
import numpy #numpy计算包
import codecs #codecs提供的open方法来指定打开的文件的语言编码,它会在读取的时候自动转换为内部unicode
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['figure.figsize'] = (10.... |
"""
This module contains the main LatexBot class.
"""
import aiohttp
import asyncio
import atexit
import datetime
import json
import logging
import marshmallow
import os
import pyryver
import random
import re
import signal
import time
import typing # pylint: disable=unused-import
from dataclasses import dataclass
from... |
#reference: https://gist.github.com/govert/1b373696c9a27ff4c72a
#Some helpers for converting GPS readings from the WGS84 geodetic system to a local North-East-Up cartesian axis.
#The implementation here is according to the paper:
#"Conversion of Geodetic coordinates to the Local Tangent Plane" Version 2.01.
#"The bas... |
import webbrowser
import time
print time.ctime()
count = 0
while count < 3:
webbrowser.open('https://goo.gl/9u9E97')
time.sleep(10)
count += 1
|
usernames = input().split(", ")
allowed_chars = set("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-")
valid_usernames = []
for username in usernames:
validation = set(username)
if 3 <= len(username) <= 16 and validation.issubset(allowed_chars):
valid_usernames.append(username)
... |
import os
import glob
import sys
def readFile(currentFile, limitstr):
count = 0
limit = int(limitstr)
countLines = 0
prevLine = ""
funcName = ""
fp = open(currentFile, 'r')
lines = fp.readlines()
print("in file ", currentFile, "\n")
for line in lines:
if ("{" in line):
... |
class Solution:
def constructDistancedSequence(self, n: int) -> List[int]:
rslt = [0]*(2*n-1)
mark = [0]*(n+1)
def bk(i, cnt):
if cnt == 0:
return True
if i >= 2*n-1:
return False
if rslt[i]:
return bk(i+1, c... |
# 766. Toeplitz Matrix
# https://leetcode.com/problems/toeplitz-matrix/description/
class Solution:
def isToeplitzMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
for i in range... |
#!/usr/bin/env python2.5
"""
#######################################################################
#
# Copyright (c) Stoke, Inc.
# All Rights Reserved.
#
# This code is confidential and proprietary to Stoke, Inc. and may only
# be used under a license from Stoke.
#
##########################################... |
from django.forms import ModelForm
from .models import Projects, Profile, Review
from django.contrib.auth.forms import UserCreationForm
from django.contrib .auth.models import User
from django import forms
from pyuploadcare.dj.forms import ImageField
class SignUpForm(UserCreationForm):
email = forms.EmailField(max... |
from django.contrib import admin
#from leaflet.admin import LeafletGeoAdmin
# Register your models here.
#admin.site.register(GeoSite, LeafletGeoAdmin)
|
from InProfileComboBox import *
class BedComboBox(InProfileComboBox):
def __init__(self, parent, managementDialogClass, finderClass):
DataSelectionComboBox.__init__(self,
parent,
BedManagementDialog,
... |
# Generated by Django 3.2.3 on 2021-05-25 15:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
... |
#!/usr/bin/python # This is server.py file
import socket
import sys
if 1 :
for arg in sys.argv:
print(arg)
# create an INET, STREAMing socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (socket.gethostname(), 12345)
print ('[TCP Server] starting up on %s port %... |
"""
paper,scissors,rock,lizard,spock
paper X -1 1 -1 1
scissors 1 X -1 1 -1
rock -1 1 X 1 -1
lizard 1 -1 -1 X 1
spock -1 1 1 -1 X
"""
import random
res = [ [ {"r": 0, "t": "draws"}, {"r": -1, "t": "is c... |
from django.db import models
from listArch.models import Company
class Collection(models.Model):
name = models.CharField(max_length=250, null=True, blank=True, verbose_name='Koleksiyon Adı')
company = models.ForeignKey(Company, blank=True, null=True, on_delete=models.CASCADE)
creationDate = models.DateTi... |
import numpy as np
import java
def utils_gen_windows(data_length, window_size, step_width):
"Generate indices for window-slizes with given length & step width."
start = 0
while start < data_length:
yield start, start + window_size
start += step_width
def reshape(raw_data, window_size, step... |
# Partial simulation of gravity
# I have predifined a path (an ellipse) but the velocity (and even acceeleration) at each instant of time
# is decided by the distance between the star and respective planet (only gravitational force)
# This is PART 2 in my attempt to make a full simulation
# WORKING !!
import tur... |
# Title : List comprehension examples
# Author : Kiran raj R.
# Date : 27:10:2020
# Transpose of a matrix
list1 = [[1, 2], [3, 4], [5, 6], [7, 8]]
out = [[row[i] for row in list1] for i in range(2)]
print(out)
# Square of elements
square = [i*i for i in range(1, 11)]
print(square)
# Print vowels
name = "kiran ... |
def encode(json, schema):
payload = schema.Main()
payload.type = json['type']
payload.coordinates = json['coordinates']
return payload
def decode(payload):
return payload.__dict__
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tarutil.py
#
# Copyright 2012 Alma Observatory <hyperion@Neptune>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of... |
import os
import glob
import shutil
import argparse
import configparser
from collections import Counter
import numpy as np
from imblearn.over_sampling import SMOTE
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
def join_split(folder, test_size... |
import pygame
from time import sleep
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# This sets the WIDTH and HEIGHT of each grid location
WIDTH = 74
HEIGHT = 74
# This sets the margin between each cell
MARGIN = 5
#test
# Create a 2 dimensional a... |
from django.db import models
from .message_handlers import Handler
from .texts import get_text
class Tournoment(models.Model):
name = models.CharField(max_length=32)
cost = models.PositiveIntegerField(default=0)
background = models.PositiveIntegerField(default=0)
# rewards here
level_min = models... |
#**************************************************************************#
# This file is part of pymsc which is released under MIT License. See file #
# LICENSE or go to https://github.com/jam1garner/pymsc/blob/master/LICENSE #
# for full license details. #
#***********... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import queue
import logging
from pyflickr.core import oauth
from pyflickr.core.mapper import FileAppender
from pyflickr.core.request import Accessor
from pyflickr.core.manager import DateManager, Validator
VENDOR = "flickr"
CLASS = "photos"
METHOD = "search"
if __name__ ... |
# -*- coding: utf-8 -*-
'''
otsu.fun - SSWA Resources Docs String
@version: 0.1
@author: PurePeace
@time: 2020-01-07
@describe: docs string for api resources!!!
'''
demo = \
'''
演示接口
传参:{ foo }
---
- Nothing here
```
null
```
'''
# run? not.
if __name__ == '__main__':
print('only docs... |
# Copyright (c) OpenMMLab. All rights reserved.
from torch._subclasses.fake_tensor import _is_tensor_constructor
from torch.utils._python_dispatch import TorchDispatchMode
class MetaTensorContext(TorchDispatchMode):
def __torch_dispatch__(self, func, types, args=(), kwargs=None):
if _is_tensor_constructo... |
import turtle
def talloval(turtle, r): # Verticle Oval
turtle.left(45)
for loop in range(2): # Draws 2 halves of ellipse
turtle.circle(r,90) # Long curved part
turtle.circle(r/2,90) # Short curved part
def flatoval(turtle, r): # Horizontal Oval
turtle.r... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 1 12:55:28 2018
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from datetime import datetime
from collections import Counter
#import time
#from datetime import date,timedelta
#import requests
sns.set(color_codes='Dark')
... |
#!/usr/bin/env python3
import re, sys
# organized as (pattern, replacement, is_recursive?)
substitutions = (
(r'\b([a-zA-Z)])(\d+,?)+\b', r'\1'), # remove most citation numbers
(r'([a-zA-Z)]+)(\d+,?)+\b', r'\1'), # (part of above)
(r'\[[0-9, -]+\]', r''), # remove [citations]
(r'www\.', r''), # www is... |
import math
import numpy as np
import torch
import torch.nn.functional as F
from utils import StaticEmbeddingExtractor
class Ranker:
def __init__(self, path_to_predictions, embedding_path, data_loader, all_labels, max_rank, y_label):
"""
This class stores the functionality to rank a prediction wi... |
# Generated by Django 3.0.7 on 2020-07-24 00:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0034_auto_20200722_0509'),
]
operations = [
migrations.AlterField(
model_name='order',
name='payment_method'... |
#!/usr/bin/python3
def soma(x, y):
return x + y
print(soma('daniel' , 'prata'))
#__________________________________________________________
def boas_vindas(nome):
return 'Seja bem vindo {}'.format(nome.title())
print(boas_vindas('daniel'))
#_________________________________________________________
def l... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#dateTime:2019/3/5 0005 下午 15:25
#file:copyfile.py
#design: nchu xlm
#浅copy只会copy最顶层的数据,对于不可变的数据类型,只会copy它的引用
# 深拷贝它会递归拷贝,如果是不可变数据类型他只会引用不会拷贝,如果是可变数据类型,它会递归拷贝
# 1. copy.copy 浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象。
# 2. copy.deepcopy 深拷贝 拷贝对象及其子对象
import requests
url="https://www.baidu.co... |
#!/usr/bin/python3
'''
Assuming a sorted list, search for a value in the list by repeatedly
bisecting it.
'''
def search_list(in_list, in_val):
list_len = len(in_list)
head = 0
tail = list_len - 1
while head <= tail:
idx = int((head + tail) / 2)
if in_list[idx] == in_val:
r... |
Product of Current and Next Elements
Given an array of integers of size N as input, the program must print the product of current element and next element if the current element is greater than the next element. Else the program must print the current element without any modification.
Boundary Condition(s):
1 <= N <= ... |
#!/usr/bin/python3
def common_elements(set_1, set_2):
if isinstance(set_1, set) and isinstance(set_2, set):
new_set = {e for e in set_1 if e in set_2}
return new_set
return set()
|
from fingerprint import add_song
import argparse
parser = argparse.ArgumentParser(description='Add a song or directory of songs to the reference database')
parser.add_argument('path', help='path/to/song/or/directory')
args = parser.parse_args()
add_song(args.path)
|
import Arena
#from connect4.Connect4Game import Connect4Game, display
#from connect4.Connect4Players import *
from tictactoe.TicTacToeGame import TicTacToeGame, display
from tictactoe.TicTacToePlayers import *
#from gobang.GobangGame import GobangGame, display
#from gobang.GobangPlayers import *
import numpy as np
from... |
# -*- coding: utf-8 -*-
import logging
from django.test.client import Client
from mock import patch
from networkapi.api_network.tasks import create_networkv6
from networkapi.api_network.tasks import deploy_networkv6
from networkapi.ip.models import NetworkIPv6
from networkapi.test.test_case import NetworkApiTestCase
... |
import subprocess
import sys
import numpy as np
import scipy.stats as stats
from scipy.signal import detrend
from joblib import Parallel, delayed
#import nitime.algorithms as tsa
from multitaper_spectrogram import *
from bandpower import *
# this is python version of sample entropy which is very slow but runs on differ... |
import pandas as pd
import matplotlib.pyplot as plt
from stats.frames import games, info, events
plays = games.query("type == 'play' & event != 'NP'")
plays.columns = ['type', 'inning', 'team', 'player', 'count', 'pitches', 'event', 'game_id', 'year']
pa = plays.loc[plays['player'].shift() != plays['player'],['year',... |
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
import time
if __name__ == "__main__":
train_num = 20000
test_num = 30000
data = pd.read_csv('train.csv')
train_data = data.values[0:train_num, 1:]
train_label = data.values[0:train_num, 0]
... |
class Critter(object):
"""Virtual pet"""
def __init__(self,name,hunger=0,boredom=0):
self.name=name
self.hunger=hunger
self.boredom=boredom
def __pass_time(self):
self.hunger+=1
self.boredom+=1
@property
def mood(self):
unhappiness=self.hunger+self.bor... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2018/8/27 11:51
# @Author : zhangxingchen
# @Site : zxcser@163.com
# @File : test_rever.py
# @Software: PyCharm
def reverse(string):
return string[::-1]
def test_reverse():
string = "good"
assert reverse(string) == "doog"
another_string = ... |
"""Some waveguides make unnecessary crossings."""
import gdsfactory as gf
from gdsfactory.samples.big_device import big_device
if __name__ == "__main__":
c = big_device()
c = gf.routing.add_fiber_single(component=c)
c.show(show_ports=True)
|
import os
import datetime
import argparse
DEFAULT_ADDR = "127.0.1.1"
DEFAULT_PORT = "8338"
CMD_RL = "export CUDA_LAUNCH_BLOCKING=1 && \
export PYTHONPATH={}:$PYTHONPATH && \
python -u -m torch.distributed.launch \
--nproc_per_node={} \
--master_addr {} \
--master_port {} \
-... |
import numpy
from pyIEM import iemdb
i = iemdb.iemdb()
coop = i['coop']
maymin = []
aprgdd = []
rs = coop.query("SELECT year, min(low) from alldata WHERE month = 5 and stationid = 'ia0200' GROUP by year ORDER by year ASC").dictresult()
for i in range(len(rs)):
maymin.append( rs[i]['min'] )
rs = coop.query("SELECT ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'F:\BE32001\pythonProject\alarm.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QDialog,... |
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
from IPython import get_ipython
# %% [markdown]
# # Prepare Titanic Model for Web / API
#
# Final result on Heroku:
# https://titanic-model-app.herokuapp.com/
#
# Sources:
# 1. https://www.kaggle.com/c/titanic/data
#
# 2. htt... |
# Generated by Django 2.0.1 on 2018-01-21 14:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('test_app', '0012_add_decimal'),
]
operations = [
migrations.AddField(
model_name='secondobject',
name='elapsed',
... |
from setuptools import setup, find_packages
PACKAGE = "fastapi-sqlalchemy"
VERSION = "0.9.0"
setup(
name=PACKAGE,
version=VERSION,
author="Matthew Laue",
author_email="matt@zuar.com",
url="https://github.com/zuarbase/fastapi-sqlalchemy",
packages=find_packages(exclude=["tests"]),
include_p... |
from django.db import models
from tinymce.models import HTMLField
# Create your models here.
class HomeSlider(models.Model):
Name = models.CharField(max_length=120)
Image =models.ImageField(upload_to='slider/')
class Meta:
ordering = ('Name',)
def __str__(self):
return self.Name
class HomeSlider2(models.... |
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import requests
print("Initializing driver...")
browser = webdriver.Firefox() # executable_path='geckodriver.exe')
browser.get('http://o2tvseries.com/Madam-Secretary-8/Season-04/index.html')
elements = browser.find_... |
class Person:
def __init__(self, name, address):
self.name = name
self.address = address
def getName(self):
return self.name
def getAddress(self):
return self.address
def setAddress(self, address):
self.address = address
def __str__(self):
... |
# -*- coding: utf-8 -*-
"""
@Time : 2020/5/22 16:28
@Author : QDY
@FileName: 123. 买卖股票的最佳时机 III_动态规划_hard.py
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入: [3,3,5,0,0,3,1,4]
输出: 6
解释: 在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.