text stringlengths 8 6.05M |
|---|
from panda3d.core import Point2, Vec3, Vec4, KeyboardButton, NodePath, LineSegs, MeshDrawer, BitMask32, Shader, Vec2
from panda3d.core import Geom, GeomNode, GeomVertexFormat, GeomLines, GeomVertexWriter, GeomVertexData, InternalName, Point3
from panda3d.core import TextNode
from .BaseTool import BaseTool, ToolUsage
f... |
import threading
import time
number = []
def add_num():
print("thread 1 sendo executada")
for i in range(5):
number.append(i)
time.sleep(1)
print("fim da thread")
def show_num(num):
print("thread 2 sendo executada")
for i in num:
print(i)
time.sleep(1)
print("fim da... |
#B
d,g,ai=map(int,input().split())
print(int(d*g*ai//100))
|
import os
import csv
from io import StringIO
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.contrib.auth.hashers import make_password
#from corecode.models import StudentClass
from .models import CustomUser, StaffBulkUpload, Staffs
@receiver(post_save, sen... |
"""
Setup file for mimic
"""
from __future__ import print_function
from setuptools import setup, find_packages
try:
from py2app.build_app import py2app
py2app_available = True
except ImportError:
py2app_available = False
_NAME = "mimic"
_VERSION = "2.0.0"
def setup_options(name, version):
"""
... |
import cv2
import math
import numpy as np
def calculateDistance(firstPoint, centroid):
return math.sqrt((centroid[0] - firstPoint[0, 0])**2 + (centroid[1] - firstPoint[0, 1])**2)
def findMaximumR(points, centroid):
maxDistance = 0
distanceList = []
for point in points:
distance = calculateDis... |
import paho.mqtt.client as mqtt
class MessageHandler:
def __init__(self, qos=0):
self.topics = dict() # <topic, callback>
self.qos = qos
self.client = mqtt.Client()
self.client.on_connect = self.__on_connect__
self.client.on_message = self.__on_message__
def __on_conn... |
from pytube import YouTube
link = 'https://www.youtube.com/watch?v=Id8YjwJDQwg&t=839s'
#To save the video to your location
save_location = 'E:\\'
try:
YouTube(link).streams.first().download(save_location)
print('Video saved')
except:
print('Connection Error')
#To save the video where the python is install... |
import logging
# setup logger
FORMAT = '%(asctime)-15s %(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger('piiipod')
|
import requests
import os
from bs4 import BeautifulSoup as bs
baseURL = "https://www.ibiblio.org/ram/"
page= requests.get(baseURL+"bcst_all.htm")
soup= bs(page.text,'html.parser')
songs = soup.find_all('table')[4].select('li a')
folderName = 'Bhajans'
if(not os.path.exists(folderName)):
os.mkdir(folderName)
os.c... |
import time
import json
import csv
import os
import requests
from bs4 import BeautifulSoup
from jinja2 import Template
import headers
# these represent different job functions
FUNCTION_FACETS = [17, 18, 14, 2, 4, 20, 5, 13, 12, 26] #FA
SENIORITY_FACETS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #SE
LOCATION_FACETS = [ #G
'... |
# contains the entities declaration and definition of medicine information
from protorpc import messages
from google.appengine.ext import ndb
from google.appengine.ext.ndb import msgprop#alpha feature dangerous
#contains the real entities that we are going to model in for medicine api purpose
class Dossage(messages.Me... |
# Dependencies
import requests
# Google developer API key
gkey = "AIzaSyA_Clyz3478YAUnsESNHE5dyktvvMoa-vw"
# Target city
target_city = "Boise, Idaho"
# Build the endpoint URL
target_url = "https://maps.googleapis.com/maps/api/geocode/json" \
"?address=%s&key=%s" % (target_city, gkey)
# Print the assembled URL
p... |
import os
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn')
STANDARD_COLORS = [
"Chartreuse",
"Aqua",
"Aquamarine",
"BlueViolet",
"BurlyWood",
"CadetBlue",
"Chocolate",
"Coral",
"CornflowerBlue",
"Cornsilk",
"Crimson",
"Cyan",
"DarkCyan",
... |
from archana import flask_demo
from archana.flask_demo import jsonify
from sqlalchemy import create_engine
app = flask_demo.Flask(__name__)
app.config["DEBUG"] = True
vehicle_types = [
{'id': 1,
'type': 'aircraft'},
{'id': 2,
'type': 'spacecraft'},
{'id': 3,
'type': 'watercraft'}
]
def con... |
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.stdout = sys.stderr
sys.path.insert(0,"/var/www/allure/")
from allure import app as application
application.secret_key = 'Add your secret key' |
#Nothing needs to go here, Python just needs this file here so it can understand directory structure
|
# stdlib
from typing import List, Dict, Any, Tuple
import bson
# 3rd party
from pprint import pprint
# local
from . import usercollection, activitycollection
from . import START_OF_WEEK
from .util import datetime_to_secs
from .algo import train_from_interactions
def flatfeed(userid: bson.objectid.ObjectId) -> List[... |
# -*- coding: utf-8 -*-
'''
Se conecta al router wamp y hace correr el Wamp del Digesto
'''
if __name__ == '__main__':
import sys, logging, inject
sys.path.insert(0,'../python')
logging.basicConfig(level=logging.DEBUG)
from autobahn.asyncio.wamp import ApplicationRunner
from model.config impo... |
import unittest
from jousting.round.kick import Kick
from jousting.round.controller import Controller
from jousting.player.knight import Knight
class KickTest(unittest.TestCase):
def setUp(self):
p1 = Knight("P1")
p2 = Knight("P2")
self.controller = Controller(p1, p2)
self.kick = ... |
#!/usr/bin/env python3
def make_ext(modname, pyxfilename):
from distutils.extension import Extension
return Extension(
name = modname,
sources=[pyxfilename],
extra_compile_args=["-O3","-march=native"]
)
|
a2=int(input())
if(a2>0):
print("Positive")
elif(a2<0):
print("Negative")
else:
print("Zero")
|
# -*- coding: utf-8 -*-
from model.validator import Validator
from control.control_analise import ControlAnalise
class ControlValidator(object):
def __init__(self):
self.validator = Validator()
self.control_analise = ControlAnalise()
sel... |
import torch
import torch.nn
import torchvision.models
import torchvision.models.resnet
from chess_recognizer.common import BOARD_DIMENSIONS
class Resnet(torch.nn.Module):
def __init__(self, pretrained: bool = True):
super().__init__()
self.resnet = torchvision.models.resnet18(pretrained=pretrain... |
from django.contrib import admin
from .models import Portfolio, Service, Carousel_figure, Client_words, Structure
# Register your models here.
admin.site.register(Portfolio)
admin.site.register(Service)
admin.site.register(Client_words)
admin.site.register(Structure)
admin.site.register(Carousel_figure) |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 13:51:00 2015
@author: fbeyer
"""
#to activate virtuals environment
#cd ..
#source venvPLS/bin/activate
#!/usr/bin/env python2
import itertools
from multiprocessing import Pool, freeze_support, Array, Process, Queue
from functools import partial
import numpy as np
from... |
# _*_ coding: utf-8 _*_
__author__ = 'FWJ'
__date__ = 2017 / 9 / 12
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
import pymysql
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:Qaz123456789@localhost:3306/net_news?charset=utf8'
db = SQLAlchemy(app)... |
class Person():
def __init__(self,name,surname):
self.name = name
self.surname = surname
@property
def fullname(self):
return f'{self.name} {self.surname}'
@fullname.setter
def fullname(self,tamad):
name, surname = tamad.split(' ')
self.name = name
s... |
from sdcli.config._config import Config
from sdcli.config.config_obs import ConfigOBS |
# -*- coding: utf-8 -*-
import os
import requests
import tarfile
import shutil
from tqdm import tqdm
def download(src, url):
file_size = int(requests.head(url).headers['Content-Length'])
header = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrom... |
import xlrd
import pymysql
#读取EXCEL中内容到数据库中
wb = xlrd.open_workbook('./dates.xls')
sh = wb.sheet_by_index(0)
dfun=[]
nrows = sh.nrows #行数
ncols = sh.ncols #列数
fo=[]
fo.append(sh.row_values(0))
for i in range(1,nrows):
dfun.append(sh.row_values(i))
conn=pymysql.connect(host='localhost',user='root... |
import json
from datetime import datetime
class Kestra:
def __init__(self):
pass
@staticmethod
def _send(map):
print("::" + json.dumps(map) + "::")
@staticmethod
def _metrics(name, type, value, tags=None):
Kestra._send({
"metrics": [
{
... |
import pandas as pd
df = pd.read_csv('../data/corona_virus_data.csv')
df = df.groupby(['Country', 'Date']).apply(lambda x: x.sort_values('Date'))
df.to_csv('corona_virus_condensed.csv') |
numbers = [int(line.strip()) for line in open('day1_input.txt')]
for i in numbers:
for j in numbers:
for k in numbers:
if i + j + k == 2020:
print(f"{i} * {j} * {k} = {i*j*k}") |
from django.db import models
from safedelete.config import SOFT_DELETE
from safedelete.models import SafeDeleteModel, SOFT_DELETE_CASCADE
from clients.models import Client
from users.models import User
from .managers import RevenueExpenditureManager
import datetime
class RevenueExpenditure(SafeDeleteModel):
_saf... |
#!/usr/bin/python
import sys
import os
sys.path.append(os.getcwd())
import argparse
import termcolor as T
import re
from collections import defaultdict
import matplotlib as mp
import matplotlib.pyplot as plt
import glob
import numpy
import math
import plot_defaults
import sys
import itertools
from helper import *
fro... |
# MSSERG | 4.11.2016
# Variable = Word
# English; Russian;
e_habits="habits"; r_habits="привычки";
e_bit="bit"; r_bit="немного";
e_back_to_front="back to front"; r_back_to_front="начиная с последней страницы";
e_iustance="iustance"; r_iustance="экземпляр";
e_annoying="annoying"; r_annoying="ра... |
# -*- encoding:utf-8 -*-
# __author__=='Gan'
# Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive),
# prove that at least one duplicate number must exist. Assume that there is only one duplicate number,
# find the duplicate one.
# Note:
# You must not modify the array (assu... |
# -*- coding:utf-8 -*-
# author: will
from aip import AipNlp
from flask import request, jsonify
from app import mongo_store
from app.models import Article
from config.lib_config import LibConfig
from utils.log_service import Logging
from . import api_article
@api_article.route('/article_tag', methods=['POST'])
def ... |
from django.shortcuts import render
def index(request):
print ("Index" * 10)
return render(request,'r_portfolio/index.html')
def projects(request):
return render(request,'r_portfolio/projects.html')
def about(request):
return render(request,'r_portfolio/about.html')
def testimonials(request):
re... |
from settings import *
from sprites import *
class Pong:
def __init__(self):
pg.init()
self.screen = pg.display.set_mode ((WIDTH, HEIGHT))
self.clock = pg.time.Clock()
self.running = True
def new(self):
self.ball1 = ball(self)
self.player2 = paddle2()
... |
import contextlib
from django.test import TestCase
from django.utils import timezone
from elections.models import (
DEFAULT_STATUS,
Election,
ModerationHistory,
ModerationStatuses,
)
from elections.tests.factories import ElectionFactory
from elections.utils import ElectionBuilder
from freezegun import ... |
import setuptools
from glob import glob
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="nbsimplegrader",
version="1.3.4",
author="Adam Blake",
author_email="adamblake@g.ucla.edu",
description="Author, distribute, and grade Jupyter noteb... |
from django.db import models
from General.models import Location
from General.models import User
from General.models import Deliveryman
from General.models import Delivery
# Create your models here.
STATUS_RENT_CHOICES = [
('на', 'На рассмотрении'),
('за', 'Оформлено'),
('оп', 'Оплачено'),
('во', 'Во... |
from __future__ import print_function
import torch
import numpy as np
import inspect
import re
import os
import collections
import random
from PIL import Image
from pdb import set_trace as st
from torch.autograd import Variable
def normalize(n, minN=-1, maxN=1):
"""
Normalize between -1 and 1
"""
if... |
import base64
url = 'cHM6'
str_url = base64.b64decode(url).decode("utf-8")
print((str_url))
print(type(str_url))
url = "https://www.jianshu.com/p/9b4ab709cffb"
bytes_url = url.encode("utf-8")
print(bytes_url)
str_url = base64.b64encode(bytes_url) # 被编码的参数必须是二进制数据
print(str_url)
|
from sys import stdin
N = int(stdin.readline().strip())
# Odd = Alice; Even = Bob
while N > 2:
N += -2
if N == 2:
print("Bob")
else:
print("Alice") |
from rest_framework import serializers
from .models import Company, Contact, Project, Task
class CompanySerializer(serializers.ModelSerializer):
class Meta:
model = Company
fields = (
'id', 'name', 'email', 'phone', 'url', 'description', 'contacts', 'projects'
)
class Conta... |
#!/usr/bin/python3
# Filename: list_this.py
import pyperclip
def list_no_quotes(mylist):
# this could be one-lined but is broken up for improved readability
mylist = str(mylist.split('\n')).strip('[').strip(']').replace(r'\r', r",").replace(r"'", "").rstrip(', ')
pyperclip.copy(mylist)
def list_quotes(m... |
from django.views.generic import *
from django.urls import reverse_lazy
from django.contrib.auth.mixins import AccessMixin, LoginRequiredMixin
from django.contrib.auth.models import User, Group
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.db.models import Q, Subquery, OuterRef
from... |
"""
This code is adapted from Deep Learning tutorial introducing multilayer perceptron
using Theano.
Added Dropout from https://github.com/mdenil/dropout/blob/master/mlp.py
"""
__docformat__ = 'restructedtext en'
import os
import sys
import timeit
import numpy
import theano
import theano.tensor as T
from logisti... |
from selenium import webdriver
from time import sleep
# import xlrd
import random
import os
import time
import sys
sys.path.append("..")
# import email_imap as imap
# import json
import re
# from urllib import request, parse
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.action_chains i... |
while True:
try:
r = input()
q = int(input())
p = [int(x) - 1 for x in input().split()]
for c in range(q):
print(r[p[c]], end='')
print()
except EOFError:
break |
import unittest
from hypothesis import given
from hypothesis import strategies as st
from validators import ValidationError, Required
from fields import Field, FormField, ListField, DictField, ChoiceField
class TestField(unittest.TestCase):
def test_simple(self):
field = Field()
for val in (None... |
class IntegerDemo:
def set_value(self, v):
self.value = v
def add(self, p):
self.value += p
def subtract(self, p):
self.value -= p
def multiply(self, p):
self.value *= p
i = IntegerDemo()
i.set_value(int(input("v: ")))
i.add(int(input("+: ")))
i.subtract(int(input("-: ")))... |
#
# Copyright © 2021 Uncharted Software Inc.
#
# 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 l... |
import pandas as pd
data = [
{"Line Number": 11, "Report Hour": 6, "Kits Completed": 34},
{"Line Number": 11, "Report Hour": 7, "Kits Completed": 55},
{"Line Number": 12, "Report Hour": 6, "Kits Completed": 67},
{"Line Number": 12, "Report Hour": 7, "Kits Completed": 56},
{"Line Number": 14, "Repor... |
import os
bashCommand = "sudo arp-scan --interface=enp0s25 --localnet | grep 192.168.2.* > output.txt"
os.system(bashCommand)
f = open('output.txt', 'r')
print f.read()
print f
|
# encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import
from __... |
import click
from .mail import sendmail
from .utils import create_new_sheet, show_sheet,\
list_sheets, delete, check_in, check_out,\
generate_attachment_txt, generate_attachment_excel
@click.group()
def cli():
pass
@cli.command()
@click.argument('id', type=int, required=False)
def show(id):
... |
from mod_base import*
class Evl(Command):
"""Evaluate a python expression."""
def run(self,win,user,data,caller=None):
try:
result = str(eval(data))
win.Send(result)
return True
except Exception,e:
win.Send("fail:"+str(e))
return False
mo... |
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com>
# SPDX-License-Identifier: BSD-3-Clause
"""
This module contains definitions of memory units that work well for USB applications.
"""
import unittest
from amaranth import Elaboratable, Module, Signal, Memory
from a... |
# -*- coding: utf-8 -*-
class Solution:
def maximum69Number(self, num: int) -> int:
digits = list(str(num))
for i, digit in enumerate(digits):
if digit == "6":
digits[i] = "9"
break
return int("".join(digits))
if __name__ == "__main__":
so... |
#!/usr/bin/python
import BaseHTTPServer
import re
import urllib
import sys
import traceback
import os
def ParseArgs(uri):
if not uri:
return {}
kvpairs = uri.split('&')
result = {}
for kvpair in kvpairs:
k, v = kvpair.split('=')
result[k] = urllib.unquote(v)
return result
class RequestDispatche... |
from django.conf.urls import url
from django.urls import path, include
from django.views.generic import TemplateView
from post_app.views import *
from post_app import views
urlpatterns = [
path('', PostListViewAPI.as_view(), name='list'),
path('create/', PostCreateAPIView.as_view(), name='create'),
url(r... |
#!/usr/bin/env python3
# Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
"""Shared front-end analyzer specific presubmit script.
See http://dev.chromium.org... |
import random
from termcolor import colored
import argparse
import re
import mana
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument("-l", "--library", help='The library path', required=True)
parser.add_argument("-d", "--debug", action='store_true', help='Enable Debug mode')
par... |
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Audience
from advertising.serializers import AudienceSerializer
AUDIENCE_URL = reverse("advertising:audi... |
from django.conf.urls import patterns, include, url
from bees import urls as bees_urls
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'bee_farm.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^bees/', include(bees_urls, namespace='bees')),
)
|
from django.db.models.query import QuerySet
from django.shortcuts import render
from question.models import Question
from rest_framework import generics
from .serializers import QuestionSerializer
# Create your views here.
class QuestionsList(generics.ListAPIView):
queryset=Question.objects.all()
serializer... |
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#############################################################################
# #
# create_ede_plots.py: create ede plots #
# ... |
from django.contrib import admin
from .models import Video, Device, RemoteHistory, Lock, Record, Door, AddDevice
# Register your models here.
admin.site.register(Door)
admin.site.register(Video)
admin.site.register(Device)
admin.site.register(RemoteHistory)
admin.site.register(Lock)
admin.site.register(Record)
admin.s... |
from flask import Blueprint
from flask import jsonify
from shutil import copyfile, move
from google.cloud import storage
from google.cloud import bigquery
import dataflow_pipeline.unificadas.unificadas_segmentos_beam as unificadas_segmentos_beam
import dataflow_pipeline.unificadas.unificadas_campanas_beam as unificadas... |
# coding: utf-8
# In[4]:
# Naive Bayes using NLP
# USe following code if it wont work in first place with UTF-8 code error
# import sys
# reload(sys)
# sys.setdefaultencoding('utf-8')
import os
os.chdir("C:\\Users\\manishk.bajpai\\Desktop\\")
import csv
smsdata = open('SMSSpamCollection.txt','r')
csv_reader = ... |
#coding:gb2312
#´æ´¢Êý¾Ý
import json
numbers = [2,3,5,6,7,8,4,9]
filename = 'numbers.json'
with open(filename,'w') as f:
json.dump(numbers,f)
|
def closestsubarraysum(arr, x):
closest = arr[0] + arr[1]
for i in range(0, len(arr)):
for j in range(1, len(arr)):
if (arr[i] + arr[j]) < x and (arr[i] + arr[j] > closest):
closest = arr[i] + arr[j]
return closest
print(closestsubarraysum([10,22,28,29,30,40],54))
... |
# coding=UTF-8
import time
import signal
from functools import wraps
from os.path import join, getsize
import os
log_dir = './logs/'
def initiDir(dir):
# Detect whether the directory is existing, if not then create
if os.path.exists(dir) == False:
os.makedirs(dir)
def getCurrentPath():
import os
... |
from . import db
class UserProfile(db.Model):
first_name = db.Column(db.String(80))
last_name = db.Column(db.String(80))
gender = db.Column(db.String(1))
email = db.Column(db.String(255), unique=True)
location = db.Column(db.String(80))
biography = db.Column(db.Text)
image = db.Column(db.... |
# Find the number of n-digit natural numbers A such that no three consecutive
# digits of A have a sum greater than 9.
# Let f(n, B) = the number of n-digit natural numbers A (leading zeros allowed)
# with B is the number formed by the first two digits of A such that
# no three consecutive digits of A have a sum great... |
import matplotlib.pyplot as plt
#import matplotlib.patches as mpatches
import numpy as np
import datetime
import os
from collections import OrderedDict
import LearnerProfile
def Graph(data, number, name='graph', title=''):
MAX_RANGE = 10
MIN_RANGE = -5
# displaces chunks for the histogram based on width of individ... |
# coding: utf-8
import datetime
import random
import string
class VotePool(object):
_pool = {}
@classmethod
def _gen_unique_id(cls):
id = ''.join([random.choice(string.digits) for i in range(4)])
if id in cls._pool:
return cls._gen_unique_id()
return id
@classmet... |
#!python
#
# tofpgen: Do the easy things to convert the output of F* (or guiguts)
# into fpgen input. Try not to do anything that will be wrong.
# Output is simply stuck into a file called out
# -- character set to UTF-8
# -- em-dashes
# -- curly quotes
# -- /##/ -> <quote>...</quote>
# -- [#] -> <fn id='#'... |
# Python Substrate Interface Library
#
# Copyright 2018-2023 Stichting Polkascan (Polkascan Foundation).
#
# 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/LIC... |
"""
Data visualization functions to simplify plots in Seaborn.
"""
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def _get_steps(df, ax, width):
"""Properly spaces values in x-axis."""
steps = ( ( df[ax].max() - df[ax].min() ) / width / 10 )
steps = max(int(round(steps)), 1)
... |
#!/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... |
from openpyxl import load_workbook
def copyData(sourceFilePath,destinationFilePath):
wb = load_workbook(sourceFilePath)
sheet = wb.sheetnames
dataSheet = ''.join(sheet)
sheet = wb[dataSheet]
# get max row count
max_row = sheet.max_row
#get max column count
max_column = sheet.max_column
... |
# Submission by Smit Rao
# Email: raosmit2@gmail.com
VAR = 'x'
def differentiate(expr: str) -> str:
'''Differentiate simple expression expr and return the result as a string.
An expression is simple if its derivation only requires use of the
power/exponent rule.
Keep negative powers ... |
# Copyright (c) 2017-2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# fmt: off
# isort: skip_file
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
imp... |
# libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
from scipy.special import factorial
df = pd.read_csv('Absenteeism_at_work.csv', delimiter=';')
plt.plot(df['Age'], df['Absenteeism time in hours'], 'bo')
plt.xlabel('Age')
plt.ylabel('Absenteeism time in hours')
plt.title('... |
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
def inverse(root):
if not root:
return root
l = inverse(root.left)
r = inverse(root.right)
root.left, root.right = r, l
return root
def same(t1, t2):
... |
import time
import random
class Trade:
#Simple class to represent a trade
def __init__(self, timestamp, quantity, indicator, price):
self.timestamp = timestamp
self.quantity = quantity
self.indicator = indicator
self.price = price
class Stock:
#Simple class to represent a Stock superclass
#From test data... |
from rest_framework import permissions
class UpdateProfile(permissions.BasePermission):
def has_object_permission(self, request, view, object):
if request.method in permissions.SAFE_METHODS :
return True
else:
return object.id == request.user.id
class UpdateStatus(permissi... |
# Copyright 2018 Cable Television Laboratories, Inc.
#
# 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... |
# Generated by Django 2.1.3 on 2018-11-06 08:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='locations',
name='location',
... |
# -*- coding:utf-8 -*-
# Created by LuoJie at 11/22/19
from gensim.models.word2vec import LineSentence, Word2Vec
import numpy as np
import codecs
# 引入日志配置
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
def load_word2vec_file(save_wv_model_path):
# 保存词向量... |
from datetime import datetime, timedelta
from pytz import timezone
import pytz
def est_time():
eastern = timezone('US/Eastern')
# fmt = '%Y-%m-%d %H:%M:%S %Z%z'
fmt = '%Y-%m-%d'
loc_dt = eastern.localize(datetime.now())
return str(loc_dt.strftime(fmt)) |
import pickle
import torch
import numpy as np
import torch.nn as nn
import pytorch_lightning as pl
import torch.nn.functional as F
from .rnn_nn import *
from .base_classifier import *
class RNN_Classifier(Base_Classifier):
def __init__(self,classes=10, input_size=28 , hidden_size=128, activation="relu" ):
... |
from django.test import TestCase
from django.contrib.auth import get_user_model
import datetime
from treatment_sheets.models import TxSheet, TxItem
from common.models import Prescription
User = get_user_model()
class TxSheetTest(TestCase):
def setUp(self):
self.owner = User.objects.create(username='Mar... |
# -*- coding: utf-8 -*-
from collections import deque
class Solution:
def numIslands(self, grid):
if not grid:
return 0
result = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == "1":
result += 1
... |
class_names_10 = ['Right Hand', 'Left Hand', 'Rest', 'Feet',
'Face', 'Navigation', 'Music', 'Rotation', 'Subtraction', 'Words']
class_names_5 = ['Right Hand', 'Rest', 'Feet', 'Rotation', 'Words']
marker_10_class = {'01 - Right Hand': [1], '02 - Left Hand': [2], '03 - Rest': [3],
'04 - Feet': [4], '05 - Fac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.