text stringlengths 38 1.54M |
|---|
import json
from random import randint
import doctest
scenarios = [
[0, 0],
[1, 0],
[1, 'n'],
[2, 0],
[2, 'n'],
[3, 0],
[3, 'n']
]
types = [ "General", "Cat1A", "Specialty" ]
specialties = [
{ "board": "Internal Medicine",
"primaries": [
"Internal Medicine"
],
"sub... |
class Solution:
def removeDuplicates(self, S: str) -> str:
i=1
while i < len(S):
if S[i] == S[i-1]:
S = S[:i-1] + S[i+1:]
if i > 1:
i -= 1
else:
i += 1
return S
|
#!/usr/bin/python3
#-*- coding: utf-8 -*-
import sys
import pyp11
from Token import Token
print('Работа с функциями inittoken:')
#Выбираем библиотеку
#Программный токен
lib = '/usr/local/lib64/libls11sw2016.so'
#Для Windows
#lib='C:\Temp\ls11sw2016.dll'
#Облачный токен
#lib = '/usr/local/lib64/libls11cloud.so'
#Аппа... |
def getExamenMesclado(self,cant):
print self.cantPreguntas+1
items=range(1,self.cantPreguntas+1)
self.randomPreg=random.sample(items,self.cantPreguntas)
print self.randomPreg
for i in self.preguntas:
items2=range(1,i.getCantRtas()+1)
vecAux1=random.sample(items2,len(items2))
self.randomRta.append(ve... |
# Generated by Django 2.0.7 on 2018-07-30 05:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pagesapp', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='page',
old_name='order',
new_na... |
#!/usr/bin/env python3
import base64
import json
import re
import subprocess
import requests
imds_server_base_url = "http://169.254.169.254"
instance_api_version = "2021-02-01"
instance_endpoint = imds_server_base_url + \
"/metadata/instance?api-version=" + instance_api_version
attested_api_version = "2021-02-... |
from config_reader import ConfigReader
import database_helper
class SubsetResultFunc:
def __init__(self, source_dbc, destination_dbc, schema):
self.source_db = source_dbc
self.destination_db = destination_dbc
self.schema = schema
def tabulate(self):
#tabulate
row_counts... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from isola_ai import Opponent
class Isola:
def __init__(self):
self.game_board = [ [ ' - ' for y in range(7) ] for x in range(7) ]
self.turn = 0
self.move_counter = 0
self.pieces = [' X ',' O ']
self.coords = [[0,3],[6,3]]
... |
# -*- # -*- coding=UTF-8 -*-
"""Pyblish lite nuke interagation. """
from __future__ import absolute_import, division, print_function, unicode_literals
import codecs
import wulifang
import wulifang.nuke
from wulifang.vendor.pyblish_lite import control, delegate, settings, util, window
from wulifang.vendor.Qt import... |
#
# Create by Hua on 4/5/22.
#
"""
The power of the string is the maximum length of a non-empty substring that contains only one unique character.
Given a string s, return the power of s.
Example 1:
Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.
Exampl... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
return self.PreOrder... |
tsc = 15
ccc = 5
hdc = 100
shc = 3
def totalCost(ts, cc, hd, shc):
total = (ts * tsc)+(cc * ccc)+(hd * hdc)
totalQty = ts + cc + hd
print("Total Cost--->", total)
if total > 100:
discount = total * 0.1
print("Total Shipping Cost:$", total)
else:
print("Shipping to fees will ... |
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import sklearn
import pandas as pd
import os
import sys
import time
import tensorflow as tf
from tensorflow import keras
dataset = tf.data.Dataset.from_tensor_slices(np.arange(10))
print(dataset)
for item in dataset:
print(item)
#1、rep... |
"""
Problem description
- https://leetcode.com/problems/sort-array-by-parity/
Result
- Runtime: 56 ms, faster than 99.82% of Python online submissions for Sort Array By Parity.
- Memory Usage: 11.5 MB, less than 100.00% of Python online submissions for Sort Array By Parity.
"""
class Solution(object):
def sor... |
import time
import argparse
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader, dataloader
from lib.vgg11 import VGG11, VGG11_test
from lib.dataset import VehicleX
from lib.utils import *
def test(opt):
# set torch seed
torch.manual_seed(opt.seed)
# set up test set
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 26 01:21:08 2021
@author: afjav
"""
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
LIMIT = 1500
handle = "benshapiro"
driver = webdriver.Chrome("C:/Users/afjav/OneDrive/Desktop/chromedriver.exe")
driver.get("https://twit... |
# Python
import os
import logging
log = logging.getLogger(__name__)
def verify_file_exists(device, file, size=None, dir_output=None):
"""verify that the given file exist on device with the same name and size
Args:
device (`obj`): Device object
file ('str'): file path on the devic... |
if __name__ == "__main__":
'''__name__ holds the name of the module
the top level script is called __main__
otherwise, if imported, it is not __main__
'''
print("This script is not intended to be executable.")
exit()
server = None
def export_server(inp_server):
'''store a server in the muds... |
# clean the inventory from kubernetes creation
import requests,json,base64,paramiko,pdb,yaml,os
mgr="192.168.0.66"
mgruser="admin"
mgrpasswd="Nicira123$"
cred=base64.b64encode('%s:%s'%(mgruser,mgrpasswd))
header={"Authorization":"Basic %s"%cred,"Content-type":"application/json"}
print "this will delete t1 LR, lsw po... |
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
iris = load_iris()
X = iris.data
y = iris.target
print(type(X))
print(type(y))
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
esti... |
import os
from nidm.experiment.Utils import annotate_data_element
# placeholder
bids_terms = {}
def add_term(bids_terms):
'''
This helper function will prepare data structures for re-using the nidm-experiment
annotate_data_element function
:bids_terms_dict: dictionary of existing BIDS terms. used for... |
from ui import UI
from ui.low.license import License
from ui.high.checklist import Checklist
__author__ = 'John Underwood'
class EditEntity(UI):
"""
TODO: Need to check for address validation
"""
License()
Checklist()
runtime = {
'editEntity': (
'Click',
'//*[@... |
# -*- coding: UTF-8 -*-
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from api import urls
from handlers.lobby_handler import GameLobby
from tornado.options import define, options
from pymongo import MongoClient
define("port", default=5000, help="run on the given port", t... |
def change_positions(players: list):
players[0], players[-1] = players[-1], players[0]
print(players)
if __name__ == "__main__":
change_positions(
players=['Ashleigh Barty', 'Simona Halep', 'Naomi Osaka',
'Karolina Pliskova', 'Elina Svitolina']
)
|
import os
import sys
sys.path.insert(0, os.path.abspath('../..'))
from ..common_test_util import expected_result
from test.hquery.hquery_test_util import query_html_doc
def test_the_sum_of_decimals_is_a_decimal():
assert query_html_doc('', '90+8.6') == expected_result('98.6')
assert query_html_doc('', '-0.2... |
from rest_framework.pagination import PageNumberPagination
class Pagination1000(PageNumberPagination):
page_size = 1000
page_size_query_param = 'page_size'
max_page_size = 1000
class Pagination100(PageNumberPagination):
page_size = 100
page_size_query_param = 'page_size'
max_page_size = 1000... |
"""
Widgets to set TWISS parameters.
"""
# force new style imports
from __future__ import absolute_import
# internal
from madgui.widget.param import ParamTable, Bool, String, Float, Matrix
# exported symbols
__all__ = [
'TwissWidget',
]
class TwissWidget(ParamTable):
"""
Widget to show key-value pairs... |
"""This module contains performance tests of oneclient using sysbench benchmark.
"""
__author__ = "Jakub Kudzia"
__copyright__ = "Copyright (C) 2015 ACK CYFRONET AGH"
__license__ = "This software is released under the MIT license cited in " \
"LICENSE.txt"
import re
from tests.utils.docker_utils import ... |
class Create:
def __init__(self, temp_DB=None, cart=None, Is_it_Free=False):
self.temp_DB = temp_DB
self.cart = []
self.Is_it_Free = Is_it_Free
|
import numpy as np
import cv2
def main():
#img1 = cv2.imread('j.png')
#img2 = cv2.imread('j_noise.png')
#imgBinJotaNormal = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
#imgBinJotaRuido = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
#cv2.imshow("Imagem Normal", img2)
w_size = 3
##########... |
'''
Show system status on a 2x16 LCD display
'''
import os
import status
import math
import serial
from time import sleep
def checkLcd(lcd, throw = True):
if not len(lcd) == 2:
if throw:
raise RuntimeError('Invalid LCD character array')
return False
for l in lcd:
if not len(l) == 1... |
# Test cases for Opportunistic Wireless Encryption (OWE)
# Copyright (c) 2017, Jouni Malinen <j@w1.fi>
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
import hostapd
import hwsim_utils
from utils import HwsimSkip
def test_owe(dev, apdev):
"""Opportunistic Wi... |
#!/bin/python3
import math
import os
import random
import re
import sys
def calculate(arr, i, j):
a = arr[i][j]
b = arr[i][j+1]
c = arr[i][j+2]
d = arr[i+1][j+1]
e = arr[i+2][j]
f = arr[i+2][j+1]
g = arr[i+2][j+2]
return (a+b+c+d+e+f+g)
if __name__ == '__main__':
arr = []
f... |
# Script to generate cropped images based on bounding boxes for OCR.
from PIL import Image
import xml.etree.ElementTree as ET
import argparse
import os
def get_crops(args):
tree = ET.parse(args.xml_file)
root = tree.getroot()
count = 0
if not os.path.exists(args.output_dir):
os.makedirs(args.... |
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import redirect
from django.utils import timezone
from .models import Post, Co... |
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selen... |
# 7kyu - Palindrome chain length
""" Number is a palindrome if it is equal to the number with digits in reversed order.
For example, 5, 44, 171, 4884 are palindromes and 43, 194, 4773 are not palindromes.
Write a method palindrome_chain_length which takes a positive number and returns the number
of special steps ne... |
import psycopg2
import json
import os
import datetime
class YelpDataImporter:
"""Creates a database (if necessary) and fills table from json files.
Contains functions to create (if necessary) a database and tables to store
data from the Yelp JSON files. Provides on-screen feedback to the user.
Attrib... |
# This Python file uses the following encoding: utf-8
# encoding: utf-8
import os
from Lesson import Lesson
from TemParse import TemParse
from ProcessGraph import ProcessGraph
from Feature import FeatureExtractor
from TemMatch import TemMatch
import Japanese
import Utl
def kNN(fn1,fn2,num = 5):
fe = FeatureExtrac... |
import sys
import struct
from collections import namedtuple
from time import sleep
from pathlib import Path
import os
import io
import zlib
import math
from PIL import Image
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
from xml.dom import minidom
from xml.etree import ElementTree
import has... |
import numpy as np
import cv2 as cv
import pdb;pdb.set_trace()
face_cascade = cv.CascadeClassifier('/Users/ludaming/anaconda2/envs/nfsv/lib/python3.6/site-packages/cv2/data/haarcascade_frontalface_default.xml')
eye_cascade = cv.CascadeClassifier('/Users/ludaming/anaconda2/envs/nfsv/lib/python3.6/site-packages/cv2/data/... |
from django.conf.urls import url
from users.views import *
from users import views as myapp_views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# debut web service
url(r'^$', UserList.as_view()),
url(r'^interests/$', InterestList.as_view()),
url... |
import calendar
yyyy= 2021
mm = 1
obj = calendar.Calendar()
# iteratign with itermonthdates
for day in obj.itermonthdates(2021, 1):
print(day)
|
print("Hello World")
print("Goodbye")
Print("Hello again")
Print("Stop saying hello")
# This is a hello world |
try:
raise ValueError(534)
except ValueError as e:
print(repr(e))
# Var bound in except block is automatically deleted
try:
e
except NameError:
print("NameError")
|
S=[]
E=[]
def init(infile):
input = open(infile, 'r')
s_str = input.readline()
S = s_str.split()
e_str = input.readline()
E = e_str.split()
input.close()
return [S,E]
def get_mat(infile, S, E):
R = {}
for s in S:
for e in E:
if s in R:
R[s].updat... |
#!/usr/bin/env python3
import sys
import itertools
with open(sys.argv[1]) as file_input:
for line in file_input:
line_list = line.split(',')
for perm in itertools.permutations(line_list):
print(perm) |
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
import pandas as pd
def normalization(data):
# data is a numpy multidim array
minval=np.amin(data,axis=0) # axis=0 returns an array containing the smallest element for each column
maxval=np.amax(data,axis=0)
... |
# Generated by Django 3.2.5 on 2021-09-13 23:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0021_alter_product_price'),
]
operations = [
migrations.AddField(
model_name='product',
name='shipping',
... |
from pymodbus.client.sync import ModbusTcpClient
import library.utils as utils
from library.base_modbus import BaseModbus
import asyncio
class PlcModbus(BaseModbus):
def __init__(self, logger, variables_dict=None):
super().__init__(variables_dict=variables_dict, logger=logger)
self.ip = u... |
from django.contrib import admin
from .models import Empresa
from .models import Contacto
from .models import Relaciones
admin.site.register(Empresa)
admin.site.register(Contacto)
admin.site.register(Relaciones) |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-07-03 18:20
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('erp', '0004_servicereport'),
]
operations = [
... |
#!/usr/bin/python
import sys
import MySQLdb
import cgi, cgitb
import os
from dbparams import myHost, myUser, myPasswd, myDb
import jinja2
from util import processList
cgitb.enable()
jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
db = MySQLdb.connect(host = myHost, ... |
import RPi.GPIO as GPIO
import time
import os
import controller as controller_methods
import requests
import simplejson as json
import settings
"""Retrieve all controller metadata from the database and save it to a file for later use.
Store controllers being used in the runtime in memory in the controllers dictionary... |
#!/usr/bin/python3
''' same as 0 but export data in the CSV format '''
import json
import requests
from sys import argv as av
if (__name__ == '__main__'):
userDb = requests.get('https://jsonplaceholder.typicode.com/users')
userDb = userDb.json()
json_dict = {}
for user in userDb:
aux_list ... |
'''
This should not be a secrets file. To be renamed as directory_setup
#TODO: Joshua to coordinate the migration of this out of the secrets folder
#TODO: Joshua to ensure that (1) EVERY setting is used
#(2) EVERY setting is populated
----------------------------------
This file sets up the directory paths of all inp... |
from neuron import gui
#In this program, we will be importing data from online files of the form:
#(x1,x2,x3,x4,x5,x6,x7) -> (compartment#,neuralID,xpos,ypos,zpos,diam,parent#)
|
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 14 23:55:14 2020
@author: PC
"""
import pandas as pd
import numpy as np
import time
def meses(mes):
mes_dict = {
1: 0, 2: 31, 3: 59, 4: 90, 5: 120, 6: 151,
7: 181, 8: 212, 9: 243, 10: 273, 11: 304, 12: 334,
}
return mes_dict[mes]
def main(... |
from copy import copy, deepcopy
import pytest
from returns.context import RequiresContext
from returns.primitives.exceptions import ImmutableStateError
def test_requires_context_immutable():
"""Ensures that Context is immutable."""
with pytest.raises(ImmutableStateError):
RequiresContext.from_value(... |
from django.shortcuts import render
# Create your views here.
def index(request):
context = {'value1': 5, 'value2': 10};
return render(request, 'local_weather/index.html', context)
|
import sqlite3
conn = sqlite3.connect("BD.db")
cursor = conn.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS student
(id integer,name text, vuz text, idstudaka integer, kurs integer,
gruppa text, tel text, datarojdeniya text)
""")
|
from nltk import word_tokenize, bigrams
from collections import Counter
from math import floor
import os
import pdb
import io
import pickle
counter = dict()
top_k_val = 300
def get_ngrams(text, n=2):
words = word_tokenize(text)
ngrams = list()
for each in words:
for i in range(len(each)-n):
... |
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
perimetre = 0
height = len(grid)
width = len(grid[0])
for line in range(height):
for column in range(width):
if grid[l... |
__author__ = "Laurence Elliott"
from urllib.request import urlopen as uOpen
from bs4 import BeautifulSoup as soup
import re
import os
# associates the windows clear terminal command with a simpler name
clear = lambda: os.system('cls')
# this script scrapes the list of all steam products (including bundles,... |
import numpy as np
from itertools import chain
from typing import Sequence, Tuple, Dict, List, Set
import parse
import features
def train_test_folds(ids: List, shuffled_index_sequence: Sequence, num_folds: int) -> Sequence[Tuple[set, set]]:
length_test = len(ids) // num_folds
out = []
for i in range(num_... |
from django.shortcuts import render, redirect
from .forms import ProductForm
from django.views.decorators.http import require_http_methods
# Create your views here.
@require_http_methods(['GET', 'POST'])
def get_name(request):
if request.method == 'POST':
form = ProductForm(request.POST)
if form.is... |
#!/usr/bin/env python
# See file LICENSE.txt for licensing information.
"""
Spanakopita markup tool. The markup is loosely based on a combination of
http://txt2tags.sf.net with Python's concept of significant whitespace.
Blank lines and indentation are significant. More indentation than the previous
line will cause... |
from django.shortcuts import get_object_or_404
from .permissions import IsAuthorOrReadOnly
from question.models import Answer, Question
from rest_framework import generics
from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.permissions import IsAuthenticated... |
import tensorflow as tf
import cnn_utils
"""
Our model. Based on DeepMask architecture.
Features:
- 5 forward layers
- 5 skip layers
- 1 recurrent layer
"""
def variables():
"""
Returns a dict of variables for use with .model()
"""
N_CHANNELS = 7
... |
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2022, Oracle and/or its affiliates.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
# Portions Copyright 2001-2007, Computronix (Canada) Ltd., Edmonton, Alberta,
# Canada. All rights reserved... |
list = {}
for i in range(0, 4):
name = input("Enter the name: ")
age = int(input("Enter the age: "))
size = int(input("Enter a shoe size: "))
list[name] = {"Age": age, "Shoe size": size}
ask = input("Enter the name: ")
print(list[ask])
|
import re
komunikat = 'To be, or not to be, that is the question'
cyfry = re.findall('[aeiou]',komunikat)
print('Liczba samogłosek w tekście:',len(cyfry)) |
"""libraryproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Clas... |
# -*- coding: utf-8 -*-
###############################################################################
##
## 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 3 of th... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 7 13:46:34 2017
@author: calorim
"""
import xspec as xs
import numpy as np
import matplotlib.pyplot as mpl
# define own absorption model
# based on IR nH data, using
# Ander & Ebihara abundances
# Wisconsin cross sections
# and averaged over FOV
fn = "data/irnh_Anders... |
# Wrapper class for _libmat MATLAB C API to Read MAT-File Data
import winreg
from ctypes import *
import numpy as np
import platform
import os
import sys
matlabdir = ""
libexts = {"Linux": ".so", "Darwin": ".dylib", "Windows": ".dll"}
libext = libexts[platform.system()]
# to hold ctypes.cdll objects
_libmat = None
... |
__author__ = 'jerry'
class Person:
def __init__(self):
print 'init'
@staticmethod
def sayhello(hello):
if not hello:
hello = 'hello'
print 'i will sya %s' % hello
@classmethod
def introduce(cls, hello):
cls.sayhello(hello)
print 'from hello met... |
from collections import deque
first, last = input().split()
if first == last:
print(0)
print(first)
print(last)
exit()
N = int(input())
s = [input() for _ in range(N)]
s.append(last)
def is_movable(a, b):
d = 0
for i in range(len(a)):
if a[i] == b[i]:
continue
d ... |
# -*- coding: utf-8 -*-
"""
DSAP Workshop
"""
from dsap_w4_graphs import Digraph, Graph, QueueNode, Queue
##########################################
# Graphs and breadth-first search
# Create an undirected graph
graph = Graph()
graph.addEdge('1','2')
graph.addEdge('2','3')
graph.addEdge('1','3... |
class Card:
def __init__(self, rank, suit):
'''Initialize the card's suit and rank.'''
self.rank = rank
self.suit = suit
def __str__(self):
'''Return a string composed of the rank and suit. The rank comes first.
For example, the 3 of Clubs would be 3c.
... |
#!/usr/bin/python3
# spymer v7.7
# Author: vaon4ik
import requests
import random
import datetime
import sys
import time
import argparse
import os
import json
from colorama import Fore, Back, Style
os.system('cls' if os.name=='nt' else 'clear')
def Main():
global info
global proxy
ver = '77'
version = requests.po... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from .client import *
from .pay import *
name = 'wechatpy_ext'
__version__ = '0.1'
|
def readInput():
weight = int(input("please input the weight of the parcel in grammes:"))
class_post = int(input("whether First class or Second class post is required:"))
insuranceWanted = input("do you want insurance, y or n:")
itemWorth = 0
if insuranceWanted == "y":
itemWorth = int(input(... |
import pygame
from Settings import SNAKE_HEAD_IMG
class Head(pygame.sprite.Sprite):
def __init__(self, pos_x=0, pos_y=0):
super(Head, self).__init__()
self.img = pygame.image.load(SNAKE_HEAD_IMG)
self._pos_x = pos_x
self._pos_y = pos_y
def update_x_position(self, pos):
... |
def fruit_color(fruit):
if fruit == 'apple':
return 'red'
elif fruit == 'banana':
return 'yellow'
elif fruit == 'pear':
return 'green'
elif fruit == 'orange' or fruit == 'lemon':
return fruit
else:
return "unknown"
fruit = raw_input ("Input fruit nam... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Progress handlers for APT operations"""
# Copyright (C) 2008-2009 Sebastian Heinlein <glatzor@ubuntu.com>
#
# Licensed under the GNU General Public License Version 2
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU ... |
# Проект: К явлению радуги
import numpy as np
import matplotlib.pyplot as plt
# Начальные параметры R0-радиус, менять нельзя
# Прицельный параметр ro должен от 0 и до 1
R0 = 1
ro = 0.895
# Функция расчитывающая углы
def func(R=R0, ro0=1, n0=1):
alpha = np.arctan(ro0/np.sqrt(R**2 - ro0**2))
k = np.sin(alpha)... |
from typing import List
def match(pattern: List[str], source: List[str]) -> List[str]:
"""Attempt to match pattern to source
% matches a sequence of zero or more words and _ matches any single word
Args:
pattern - a pattern using to % and/or _ to extract words from the source
source - a ... |
import matplotlib.pyplot as plt
eigenvalues = [2.1779, 1.4633, 1.3622,
1.1666, 1.0146, 0.9590,
0.8924, 0.7333, 0.6845,
0.6200, 0.4911, 0.4350]
variances = [x / sum(eigenvalues) for x in eigenvalues]
names = ['Gender', 'Age', 'Time in Hospital',
'Number of Lab Procedures', 'Number of Procedures',
'... |
# encoding=utf-8
import datetime
import sys, getopt
from groupingsentences.second import gs_grouping_sentences_to_xmind
from groupingsentences.first import gs_grouping_sentences_to_xls
def main(argv):
inputfile = ''
outputfile = ''
top_words_count = 8
encoding = 'gb18030'
max_items = 1000
top_... |
# import mymodule
from main_package import some_main_script
from main_package.sub_package import mysubscript
some_main_script.report_main()
mysubscript.sub_report() |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name= 'index'),
path('login/', views.login_view, name='login_view'),
path('register/', views.register, name='register'),
path('adminpage/', views.admin, name='adminpage'),
path('customer/', views.customer, name=... |
"""utilities for creating property classes"""
import collections.abc
from copy import deepcopy
from functools import lru_cache
from magpylib._src.defaults.defaults_values import DEFAULTS
SUPPORTED_PLOTTING_BACKENDS = ("matplotlib", "plotly", "pyvista")
ALLOWED_SYMBOLS = (".", "+", "D", "d", "s", "x", "o")
ALLOWED_... |
from django.shortcuts import render,HttpResponse,redirect
from .models import Questionnaires,Questions,Options
from django.contrib.auth.decorators import login_required
# Create your views here.
import pymysql
def index(request):
return render(request,'user/index.html')
# 创建问卷
@login_required()
def createQuestion... |
import abc
from ..._vendored import six
@six.add_metaclass(abc.ABCMeta)
class _DataType(object):
"""
Base class for data type. Not for external use.
"""
_DATA_TYPE = None
def __eq__(self, other):
if type(self) is not type(other):
return NotImplemented
return self._a... |
# coding: UTF-8
import os
import sys
from google.appengine.ext.webapp import template
import datetime
import email.utils
import hashlib
import time
import urlparse
import urllib
import urllib2
import logging
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# '''
# This node listens to a service call for a joint trajectory planner.
# These will be bridged to the Toyota safe pose changer.
# '''
import rospy
from tmc_manipulation_msgs.srv import SafeJointChange
from sensor_msgs.msg import JointState
class HeadBridge(object)... |
import openpyxl
import os
import pandas as pd
def result_files(path):
return [f for f in os.listdir(path) if f.endswith('.xlsx') and f.startswith('RESULTS_')]
def name_from_pair(fn, par, inst):
prefix = fn.replace('RESULTS_', '').replace('.xlsx', '')
return prefix + str(par) + '_' + str(inst) + '.sm'
... |
from statcast_batter import statcast_batter
from baseball_scraper import playerid_lookup
import pandas as pd
import numpy as np
from datetime import datetime,timedelta
import re
import pickle
def append_next_game_details(df2):
#determine if the player gets a hit the next game
df_huge = pd.DataFrame()
play... |
#average O(nlogn), worst case O(n^2)
def quicksort(array):
if len(array) < 2:
return array
else:
pivot = array[0]
smaller = [i for i in array[1:] if i <= pivot]
higher = [i for i in array[1:] if i > pivot]
return (quicksort(smaller) + [pivot] + quicksort(higher))
pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.