text stringlengths 8 6.05M |
|---|
# http://code.google.com/p/dexterity/issues/detail?id=234
from Acquisition import aq_inner
from zope.component import getUtility
from zope.intid.interfaces import IIntIds
from zope.security import checkPermission
from zc.relation.interfaces import ICatalog
from plone.multilingualbehavior.interfaces import IDexterityTr... |
number = int(input())
if number > 1:
for i in range (2,number):
if number%i == 0:
print("nope")
break
elif i == number - 1:
print("yep")
|
from .base import FunctionalTest
from selenium.webdriver.common.keys import Keys
class UserRegistrationTest(FunctionalTest):
def test_new_user_can_register_new_account(self):
#otwieramy strone glowna
self.browser.get(self.server_url)
#klikamy przycisk odpowiedzialny za rejestracje na stro... |
import sys, glob
sys.path.append('../gen-py')
from SpellService import SpellService
from SpellService.ttypes import *
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
# parsing arguments
host=sys.argv[1]
port=sys.argv[... |
from flask import Flask, redirect, url_for, request, render_template
import requests
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/search', methods =['POST'])
def search():
search = request.form['search']
if search == "":
return render_template('index.html... |
import gym
import torch.optim as optim
from dqn_learn import OptimizerSpec, dqn_learing
from utils.gym import get_env, get_wrapper_by_name
from utils.schedule import LinearSchedule
from utils.experiments_mgr import start_experiments_generator
from dqn_model_lrelu import DQNLRelu
from dqn_model import DQN
# Program p... |
from unittest import TestCase
from Queue import Queue
class TestQueue(TestCase):
def test_dequeue(self):
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
self.assertEqual(queue.dequeue(), 1)
self.assertEqual(queue.dequeue(), 2)
self.asser... |
S = input()
R = ""
for c in S:
if c in "aeiou":
R += c
print('S' if R == R[::-1] else 'N')
|
#!/usr/bin/env pypy3
from sys import stdin
from collections import deque
lines = [list(map(int, line.strip().split())) for line in stdin]
t = lines[0][0]
ln = 1
for _ in range(t):
n, a = lines[ln][0], lines[ln+1]
ln += 2
d = deque()
for x in a:
if len(d) == 0 or x < d[0]:
d.append... |
T = [(1, 2), (3, 4), (5, 6)]
for (a, b) in T: # tuple assignment
print(a, b)
D = {'a': 1, 'b': 2, 'c': 3} # Dictionary
for key in D:
print(key, '=>', D[key]) # use dictionary keys iterator and index
L = list(D.items()) # make a list from the dictionary items
print(L)
for (key, values) in L: # iterate th... |
print('-' * 30)
print('Sequência de Fibonacci')
print('-' * 30)
termos = int(input('Quantos termos você quer mostrar? '))
print('~' * 30)
inicio = 3
t1 = 0
t2 = 1
print(f'{t1} → {t2}', end=' → ')
fim = termos
while inicio <= fim:
t3 = t1 + t2
print(t3, end=' → ')
t1 = t2
t2 = t3
inicio += 1
print('... |
array = [-2, 1, -3, 4, 6, 3]
new_array = []
for item in array:
if item % 2 != 0:
new_array.append(item)
array = new_array
print(array)
|
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that app bundles are built correctly.
"""
import TestGyp
import TestMac
import os
import plistlib
import subprocess
import sy... |
#!/usr/bin/python
from PIL import Image
import os, sys
def resize(path, originDir, destDir, dimensionX, dimensionY):
dirs = os.listdir( path+originDir )
print(dirs)
for item in dirs:
if os.path.isfile(path+originDir+item):
im = Image.open(path+originDir+item)
f, e = os.path.splitext(path+orig... |
from unittest import TestCase
from agrupa_numeros.agrupa import agrupa
class AgrupaTests(TestCase):
def test_retorna_vazio(self):
retorno = agrupa('')
self.assertEqual('', retorno)
def test_retorno_de_um_unico_numero(self):
retorno = agrupa('10')
self.assertEqual('[10]',... |
import time
import serial
import utils
class Fob(object):
def __init__(self):
self.ser1 = serial.Serial()
self.ser2 = serial.Serial()
self.fs = 100
self.all_data = (0, 0, 0, 0, 0, 0)
# ser1 is master, and ser2 is the only slave
# two birds are both connected to the ... |
import datetime
import os
from typing import Dict, List, Any, Tuple, Union
import requests
from dateutil import parser
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
class BookingUser:
def __init__(self, base_url: str, class_type: str, user_info, logger):
... |
import os
import sys
#Calculate the path based on the location of the WSGI script.
apache_configuration= os.path.dirname(__file__) #e:\PythonWeb\code\voith_sales\Rail\apache_django_wsgi.conf
project = os.path.dirname(apache_configuration) #e:\PythonWeb\code\voith_sales\Rail
workspace = os.path.dirname(project) #e:\... |
import argparse
from docqa.triviaqa.training_data import ExtractMultiParagraphsPerQuestion
from docqa.data_processing.preprocessed_corpus import PreprocessedData
from docqa.scripts.ablate_triviaqa import get_model
from docqa.text_preprocessor import WithIndicators
from docqa.data_processing.document_splitter import M... |
# -*- coding: utf-8 -*-
from utils import get_img_urls, write_pdf
from datetime import datetime
import json
class Immobilier(object):
def __init__(self, item_url, data):
self.item_url = item_url
self.data = data
self.serialized_data = None
self.interest_data = None
self.url_... |
# -*- coding: UTF-8 -*-
import os,re,shutil,json,random,threading,socket,sys,time#,requests
import unreal
class StaticTextureMeshTask:
def __init__(self):
#self.MaterialLoaderData = 'I:\\svnDir\\ue422_epic_1\\Engine\\Plugins\\zhuohua\\CGGameWork\\Content\\MaterialLoaderData.xml'
self.MaterialLoader... |
# Copyright (C) 2011-2013 Claudio Guarnieri.
# Copyright (C) 2014-2018 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
import datetime
import hashlib
import logging
import os
import pkgutil
import socket
import struct
import ... |
#encoding=UTF8
'''
从redis读取要主动监控的数据,反序列化
按配置文件读取相应的数据
通过redis发布监控的数据
'''
import global_setting
import plugin_conf
import threading
import json
import time,sys
from conf import redis_connecter as redis
hostname='wan'
channel='main_queue'
def get_config_fromredis(host):
host_configure='HostConfiguration::%s' % host#... |
p=print
a=A=b=''
i=26
while i:l=chr(123-i);L=chr(91-i);a+=l;A+=L;b+=L+l;i-=1
c='-'*23
p(A+a);p(b);p(c)
while b:p('| %-20s|'%' '.join(b[:10]));b=b[10:]
p(c)
d='apple','grape','lemon','olive'
for e in a:
if e in'aglo':b+='%s begins with %%s, '%d[i]%e;e=e+': ',d[i];i+=1
p(list(e))
p(b[:-2]) |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from twython import Twython
import requests
from cStringIO import StringIO
from django.core.files import File
# will be used to build tweet absolute url
TWEET_URL_TEMPLATE = "https://twitter.com/{user_name}/status/{tweet_id}/"
def get_cred... |
import cv2
import numpy as np
import pandas as pd
from tqdm import tqdm
def normalize(df, width, height):
"""Normalize the images in the given DataFrame.
Args:
df = [DataFrame] images as a Pandas DataFrame
width = [int] width of the raw images in pixels
height = [int] height of t... |
# Property tax
# Calculation of assessment value and property tax
# Anatoli Penev
# 26.11.2017
# Main fucntion
def main():
# Ask for the property's actual value.
property_value = float(input("Enter the property's actual value: "))
prop(property_value)
# Property value calculation
def prop(pr... |
#!/usr/bin/python3
import requests, base64, argparse, json
class Crypt(object):
def __init__(self, addr, keypair=None):
self.baseurl = addr
if keypair is None:
self.key = requests.get(self.baseurl+"/register").json()
else:
self.key = keypair
def encrypt(self, raw, key=None):
if key is None:
key = s... |
property_key_map = {
"BIRTH_DATE": "birth_date",
"PATIENT_STATUS": "is_deceased",
"DEATH_DATE": "death_date",
"PRIMARY_ONC": "care_provider",
"PAT_ID": "client_id",
"PAT_LAST_NAME": "last_name",
"PAT_FIRST_NAME": "first_name",
"PAT_MIDDLE_NAME": "middle_name",
"PAT_TITLE": "prefix",
... |
from webargs import ValidationError
def limit_length(lower=None, upper=None):
def validate(field):
length = len(field)
return (lower <= length if lower else True) and \
(upper >= length if upper else True)
return validate
def limit_value(lower=None, upper=None):
def valid... |
from folium import Map, Marker, Icon, PolyLine
def get_mex_map():
m = Map(
location=[23.0676883,-104.7929726],
zoom_start=5
)
return m
def set_locations_mex(locationsDict,htmlFileName):
mexMap = get_mex_map()
for key in locationsDict.keys():
if list(locationsDict.keys())[0]... |
from typing import Dict
from .abstract import AbstractInterface
import json
class ProblemsInterface(AbstractInterface):
create_fields = ['title', 'description', 'max_cpu_time', 'max_real_time', 'max_memory', 'author', 'testcases']
retrieve_fields = ['id', 'title', 'description', 'max_cpu_time', 'max_real_time'... |
import requests
import webbrowser
headers = {'User-Agent':'Mozilla/5.0'}
payload = {'txtPlan': '454'}
session = requests.Session()
webbrowser.open( session.post('http://www.esar.alberta.ca/esarmain.aspx',headers=headers,data=payload) )
|
'''
Created on Jul 16, 2013
@author: emma
'''
import unittest #imports unit test/ability to run as pyunit test
from UnitTesting.page_objects.webdriver_wrapper import webdriver_wrapper
from UnitTesting.page_objects.homepage import homepage
class new_releases_fiction(unittest.TestCase):
def new_releases_... |
from src.Algorithms.Nodes.abstract_node import AbstractNode
class DijkstraNode(AbstractNode):
def __init__(self, x, y, parent,distance):
super().__init__(x, y, parent)
self.__distance = distance
def get_distance(self):
return self.__distance
def __lt__(self, other):
retur... |
import glob
import sys
import pyaudio
import wave
import os
import numpy as np
import tensorflow as tf
import librosa
from socket import *
from header import *
if len(sys.argv) < 3:
print("Compile error : python record.py [minutes] [meters]")
exit(1)
FORMAT = pyaudio.paInt16
NODE = sys.argv[2]
seconds = int(s... |
import getpass
import os
import sys
class Who:
"""
Este Metodo detecta quien eres en el sesion actual,
Si detecta el user ROOT se detiene.
"""
user = getpass.getuser()
localhost = os.popen('hostname', 'r')
localhost = localhost.read()
sistema_operativo = os.name
def identificar(... |
import eel
import pyowm
owm = pyowm.OWM('your token')
@eel.expose
def get_weather(place):
mgr = owm.weather_manager()
observation = mgr.weather_at_place(place)
w = observation.weather
temp = w.temperature('celsius')['temp']
# print("В городе " + place + " сейчас " + str(temp) + " градусов.")
... |
#~!/usr/bin/env python3
"""save the best alignment along with the sequence's corresponding score. """
__appname__ = 'align_seqs'
__author__ = 'Zongyi Hu (zh2720@ic.ac.uk)'
__version__ = '0.0.1'
import sys
"""Two example sequences to match"""
# seq2 = "ATCGCCGGATTACGGG"
# seq1 = "CAATTCGGAT"
# Assign the longer seq... |
"""
1 ler os casos de teste Q (entrada)
2 laço de Q até i = 0 (para cada caso de teste)
3 armazenar em uma lista os total de primos gemeos no interval (X-Y) (processamento)
4 exibir a lista em um novo laço (saida)
"""
def eh_primo(x,y):
primos = []
for i in range(x,y+1):
aux = 0
for y in range(... |
from typing import Dict
class AvgCollecter():
def __init__(self, keys=None):
self.total = {k:0 for k in keys} if keys else {}
self.count = {k:0 for k in keys} if keys else {}
self.val = None
def __call__(self, result:Dict[str, float], reset=False):
for k, v in result.items():... |
import numpy as np
class Layout:
"""
Layout(width, height, *anchorWidth, *anchorHeight, *fill)
Parameters
width int: layout width
height int: layout height
achrowWidth int: layout width position from the parent
optional, default: 0
anchorHeight int: layout height position from t... |
import numpy as np
import sys
import math
import time
def merge(lista,p,q,r):
L, R,i,j = [],[],0,0
for a in range(p,q+1): L.append(lista[a])
for a in range(q+1,r+1): R.append(lista[a])
L.append(math.inf)
R.append(math.inf)
for k in range(p,r+1):
if (L[i] < R[j]):
lista... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
img1 = cv2.imread("Img1.png", cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread("Img2.png", cv2.IMREAD_GRAYSCALE)
sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
# Here kp will be a l... |
import sys
# In that way we can give parameters for Python file from the terminal
first_name = sys.argv[0]
last_name = sys.argv[1]
print(f'Hi, I\'m {first_name} {last_name}') |
from django.contrib import admin
from sponsorapp.models import Sponsor
admin.site.register(Sponsor) |
from antlr4 import *
from parser.parity_gameLexer import parity_gameLexer
from parser.parity_gameParser import parity_gameParser
from parser.parity_gameListener import parity_gameListener
from pathlib import Path
from typing import List, Set, Dict
from copy import deepcopy
import re
class ParsedNode:
def __init__... |
import filters
def main():
# Ask what image the user wants to edit
filename = input("Enter filename: ")
#Load the image from the specified file
img = filters.load_img(filename)
#Apply Filters
newimg = filters.obamicon(img)
#Save the final image
filters.save_img(img, "rec... |
import typing
import mysql.connector
from classes import Student, Room
class Model:
def __init__(self, **kwargs):
self.create_db_and_tables(kwargs.get('init_script_path_sh') or './inits/init_script.sh')
self.connection = mysql.connector.connect(
user = ... |
import inspect
import re
from functools import partial
from typing import Any, Callable, Dict, List, Mapping, Optional, get_type_hints
from falcon import HTTP_400, HTTP_415, HTTPError
from falcon import Response as FalconResponse
from falcon.routing.compiled import _FIELD_PATTERN as FALCON_FIELD_PATTERN
from .._pydan... |
#What you will learn
"""
Lists
Searching in Lists
Exception Handling
Slices
Ranges
For Loop
While Loop
#Lists
A list is a data type that holds an ordered collection of items.
The items can be of varrious data types
You can even have lists of lists!
list_name = [item_1, item_2, item_N]
list_name = []
list_name[index... |
from django.contrib.auth.admin import GroupAdmin, UserAdmin
from django.contrib.auth.models import Group, User
from django.contrib.sites.models import Site
from django.contrib import admin
from django import forms
# Register your models here.
# from frontend.models import Article
from django_ace import AceWidget
fro... |
# Copyright 2010-2012 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
__all__ = ['getmaskingstatus']
import sys
import portage
from portage import eapi_is_supported, _eapi_is_deprecated
from portage.localization import _
from portage.package.ebuild.config import config
from porta... |
# client.py --
# Runs in thread and communicates with the Glass Server.
import threading
import socket
import config
import time
import struct
import logging
import GlassProtocol
from variable import variables
class client_c(object):
#Overall client class
def __init__(self):
#Read Conf... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Users\盛田昭夫\Desktop\IonTrap-WIPM-master\GUI_Material\QC2_0.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Main... |
#!/usr/bin/python
# Copyright (c) Istituto Nazionale di Fisica Nucleare (INFN). 2006-2010.
#
# 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... |
#!/usr/bin/env python
'''
This is the main file that the meta-server calls when you want you
run just one robot at the time
'''
import roslib; roslib.load_manifest('br_swarm_rover')
import rospy
from sensor_msgs.msg import CompressedImage
from sensor_msgs.msg import Image
from std_msgs.msg import String
import br_cam... |
# coding:utf-8
st = "Hello World"
# 字符串包含判断操作符: in、not in
print("He" in st)
print("She" not in st)
# 读取字符串的某一部分
print(st[:6])
# string模块提供的方法:
# 从下标0开始,查找在字符串里第一个出现的子串,返回结果:0 ,查找不到返回-1
print(st.find('Hello') > 0)
# 首字母大写
print("字符串:{0},首字母大写:{1}".format(st, st.capitalize()))
# 转小写
print("字符串:{0},转小写:{1}".format(st, ... |
from collections import defaultdict
from cloudshell.shell.core.driver_context import AutoLoadAttribute, AutoLoadDetails, AutoLoadResource, ResourceCommandContext
class LegacyUtils(object):
def __init__(self):
self._datamodel_clss_dict = self.__generate_datamodel_classes_dict()
def migrate_autoload_d... |
'''
Created on Jul 3, 2011
@author: kjell
'''
from random import random
from random import choice
import unittest
example_alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def get_example_alphabet():
return example_alphabet
def generate_examples_... |
from .. import logger, parse_all_sections_symbols
from ..utils import wrap_script_entry_point
from optparse import OptionParser
import sys
from latex_symbol_manager.programs.collect.find_commands import find_all_commands
__all__ = ['lsm_extract_main']
usage = """
%prog -m main.tex -o compact.tex sources.tex ..... |
# coding: utf-8
# Standard Python libraries
from pathlib import Path
from typing import Optional
# iprPy imports
from . import settings
from .tools import screen_input
def load_run_directory(name: Optional[str] = None):
"""
Loads a pre-defined run_directory from the settings file.
Parameters
---... |
# -*- coding: utf-8 -*-
# @Time : 2020-05-22 09:27
# @Author : speeding_motor
from tensorflow import keras
import tensorflow as tf
from config import GRID_SIZE, BATCH_SIZE, ANCHOR_SIZE, ANCHORS, LAMBDA_COORD, LAMBDA_NOOBJ, LAMBDA_OBJ \
, THRESHOLD_IOU
from util.iou import IOU
class YoloLoss(keras.losses.Loss... |
from backbone import *
import re
'''
To check if the cpu and memory usages of the nodes are in optimal ranges
'''
nodes = get_nodes_by_type('namenode')
nodes_data = get_nodes_by_type('datanode')
all_nodes = nodes + nodes_data
percentage = {}
for node in nodes :
for line in node.shellCmd('free').split('\n'):
... |
# Generated by Django 3.1.5 on 2021-01-27 12:42
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Members',
fields=[
('id', models.AutoField(... |
def number(lines):
return ['{}: {}'.format(i, a) for i, a in enumerate(lines, 1)]
|
!ls
import pandas as pd
df=pd.read_csv("ov.tsv", sep="\t")
#df["normfactor"]=
len(df.columns)
for a in list(df["ID"]):
print(a)
df["normfac"]=df.sum(axis=1)
df["normfac"]=df["normfac"]/1000000
df["normfac"]
df[list(df)[:-1]]
df[df["ID"]=="120812A_mkdup_exonCov.tsv"][list(df)[:-1]].divide(10)
df[list(df)[:10]]... |
# python版本3.4
import hashlib
import urllib.request
import urllib
import json
import base64
import message
def md5str(str): # md5加密字符串
m = hashlib.md5(str.encode(encoding="utf-8"))
return m.hexdigest()
def md5(byte): # md5加密byte
return hashlib.md5(byte).hexdigest()
class DamatuApi():
ID = messag... |
'''
Author: MK_Devil
Date: 2022-01-13 11:13:09
LastEditTime: 2022-01-14 11:51:42
LastEditors: MK_Devil
'''
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import
file_mat = open('material.txt', 'r+')
while True:
get_str = input('输入名称,是否,四种数据,使用空格分隔,输入exit结束\n')
if get_str == 'exit':
break
g... |
import math
import sys
import os
#import scipy
#from astLib import astWCS
from kapteyn import wcs
import pyfits
class FoundStar:
pass
if (len(sys.argv) < 3 or len(sys.argv) > 4) :
print "Usage: convert_hstphot_list list.txt ref_raw_data_image.fits [ref_drizzled_SCI_image.fits]"
sys.exit(1)
#run distort... |
#!/usr/bin/python
import sys
import pickle
sys.path.append("../tools/")
import pandas as pd
import matplotlib.pyplot
import pprint
pp = pprint.PrettyPrinter(indent=4)
from feature_format import featureFormat, targetFeatureSplit
from tester import dump_classifier_and_data
from sklearn import tree,metrics,cross... |
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
stack = []
ans = ListNode(0)
node = ans
while head:
stack.append(head.val)
head = h... |
from django.urls import re_path
from election_snooper import views
urlpatterns = [
re_path(
r"^$", views.SnoopedElectionView.as_view(), name="snooped_election_view"
),
re_path(
r"^moderation_queue/$",
views.ModerationQueueView.as_view(),
name="election_moderation_queue",
... |
# Generated by Django 2.2.6 on 2019-12-30 08:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('work', '0074_auto_20191230_0808'),
]
operations = [
migrations.AlterField(
model_name='dprqty',
name='dtr_100',
... |
"""Core settings."""
import collections
from django import forms
from django.conf import settings
from django.contrib.auth import password_validation
from django.utils.translation import gettext as _, gettext_lazy
from modoboa.core.password_hashers import get_dovecot_schemes
from modoboa.core.password_hashers.base i... |
import easygui
from tkinter import Tk
from tkinter.filedialog import askopenfilename
from PyPDF2 import PdfFileWriter, PdfFileReader
import PyPDF2
import re
from tkinter import messagebox
from tkinter import Text
import os
import calendar;
import time
from config import configs
import base64
from datetime import dateti... |
# Upgrading Dart's SDK for HTML (blink IDLs).
#
# Typically this is done using the Dart WebCore branch (as it has to be
# staged to get most things working).
#
# Enlist in third_party/WebCore:
# > cd src/dart/third_party
# > rm -rf WebCore (NOTE: Normally detached head using gclient sync)
# > git clon... |
from collections.abc import Callable, Iterator, Mapping
from typing import Generic, TypeVar
from _typeshed import Incomplete, Self
_T = TypeVar("_T")
_U = TypeVar("_U")
_V = TypeVar("_V")
class AtlasView(Mapping[_T, dict[_U, _V]], Generic[_T, _U, _V]):
def __init__(self, d: Mapping[_T, dict[_U, _V]]) -> None: ..... |
import sdl2.ext
from tetris.configuration.Configuration import *
from tetris.configuration.Colors import *
class MenuState(object):
def __init__(self):
self.selected_index = None
self.buttons = []
def add_button(self, button):
self.buttons.append(button)
if self.selected_index... |
# handle import here
import sys
sys.path.append('../../')
'''
SmsInput
'''
from Clean_Dataset.Utils.csv_util import csv_util
import pandas as pd
import numpy as np
def percentage(data):
'''data is a DataFrame'''
array = np.array(data)
call_count = 0
for row in array:
for value in row[3:]:
... |
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com>
# Copyright (c) 2020 Florent Kermarrec <florent@enjoy-digital.fr>
#
# Code based on ``usb3_pipe``.
# SPDX-License-Identifier: BSD-3-Clause
""" Scrambling and descrambling for USB3. """
import unittest
import operator... |
'''
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "... |
# -*- coding: utf-8 -*-
from typing import List
class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
differences, result = [], 0
for a_cost, b_cost in costs:
differences.append(a_cost - b_cost)
result += a_cost
differences.sort(reverse=True)
... |
import unittest
import numpy.testing as testing
import numpy as np
import hpgeom as hpg
import healsparse
class CoverageMapTestCase(unittest.TestCase):
def test_coverage_map_float(self):
"""
Test coverage_map functionality for floats
"""
nside_coverage = 16
nside_map = 512... |
"""Device Records Classes."""
from fmcapi.api_objects.apiclasstemplate import APIClassTemplate
from fmcapi.api_objects.policy_services.accesspolicies import AccessPolicies
from fmcapi.api_objects.status_services import TaskStatuses
import time
import logging
import warnings
class DeviceRecords(APIClassTemplate):
... |
"""
Compute LSH hash codes based on the provided functor on all or specific
descriptors from the configured index given a file-list of UUIDs.
When using an input file-list of UUIDs, we require that the UUIDs of
indexed descriptors be strings, or equality comparable to the UUIDs' string
representation.
We update a key... |
import numpy as np
import scipy.constants
import scipy.special
def getCoulombLogarithm(T, n):
"""
Calculates the Coulomb logarithm according to the formula given in
Wesson's book "Tokamaks".
:param float T: Plasma temperature (eV).
:param float n: Plasma density (m^-3).
"""
return 14.9 - ... |
l1 = int(input())
c1 = int(input())
l2 = int(input())
c2 = int(input())
a1 = (l1 * c1)
a2 = (l2 * c2)
print(a1 if a1 >= a2 else a2)
|
###MODULES###
import numpy as np
import pandas as pd
import os, sys
import time as t
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.ticker import MaxNLocator
import pathlib
from matplotlib.colors import Normalize
from scipy import interpola... |
#coding:utf-8
import os
from urllib import quote
from flask import flash, url_for, redirect, render_template, request,\
current_app, session, make_response
from flask.ext.login import login_user,logout_user, login_required,\
current_user
from . import auth
from .auth_form import LoginForm, RegisterForm, Reset... |
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from utils import REQ... |
import web
urls = ('/(.*)', 'index'
)
videojsApp = web.application(urls, locals())
render = web.template.render('templates/videojs')
class index:
## create
def POST(self,key):
return 'Not implement yet!'
## delete
def DELETE(self,key):
return 'Not implement yet!'
## read
... |
# Generated by Django 3.1.7 on 2021-04-01 12:03
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('customers', '0001_initial'),
('cars', '0001_initial'),
]
... |
import json
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.middleware.csrf import get_token
from src.bin.lib import empty
class BaseResponse(object):
STATUS_REMARK_OK = ... |
# This file provides a very simple "no sql database using python dictionaries"
# If you don't know SQL then you might consider something like this for this course
# We're not using a class here as we're roughly expecting this to be a singleton
# If you need to multithread this, a cheap and easy way is to stick it on i... |
import numpy as np
import tensorflow as tf
from pynput.keyboard import Key, Controller
import operator
import cv2
import sys, os
import time
import pyautogui
keyboard = Controller()
# Loading the model
jsonFile = open("model.json", "r")
modelJson = jsonFile.read()
jsonFile.close()
loadedModel =tf.keras.models.model_f... |
#!/usr/bin/python
class Solution(object):
def canConstruct(self, ransomNote, magazine):
magaArray = []
for cha in magazine:
magaArray.append(cha)
for cha in ransomNote:
if cha not in magaArray:
return False
else:
magaArray.remove(cha)
return True
solu = Solution()
print(solu.canConstruct("... |
# -*- coding: utf-8 -*-
"""Tests for API signal handlers."""
import mock
import unittest
from webplatformcompat.models import Browser, Maturity
from webplatformcompat.signals import post_save_update_cache
from .base import TestCase
class TestDeleteSignal(TestCase):
def setUp(self):
patcher = mock.patch(
... |
class Solution:
"""
@param num, a list of integer
@return an integer
"""
def longestConsecutive(self, num):
dataSet = set(num)
#for ie in num:
# dataSet.add(ie)
print("dataset is ",dataSet)
res = 0
for ie in set(dataSet):
print... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 9 18:49:30 2018
@author: Haneen
"""
import kivy
from kivy.app import App
from kivy.uix.button import Label
from kivy.uix.widget import Widget
class CustomWidget(Widget):
pass
class CustomWidgetApp(App):
def build(self):
retu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.