text stringlengths 38 1.54M |
|---|
person = {'first_name': 'marek', 'last_name': 'czekalski', 'age': 23, 'city': 'kielce',}
print(person)
name = person['first_name'].title()
print(name)
possesion = person.get('possesion', 'no possesion declared')
print(possesion.title())
person['possesion'] = 'student'
possesion = person.get('possesion', 'no possesio... |
"""Access to VoxelBrain.
https://nip.humanbrainproject.eu/documentation/user-manual.html#voxel-brain
"""
import abc
import json
import os
import urllib
import numpy as np
import requests
from voxcell import RegionMap, VoxelData, math_utils
from voxcell.exceptions import VoxcellError
def _download_file(url, filepa... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('votes', '0002_liste_nombre_votes'),
]
operations = [
migrations.AlterField(
model_name='liste',
name... |
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from navbar.models import Lang, Contact, Navbar_lang, Social_media, Toetaja
from .models import Treenerid_lang, Treener
# Create your views here.
def treenerid(request):
if 'lang' not in request.session:
request.session['l... |
#>>> s1 = 'vivid'
#>>> s2 = 'dvivi'
#>>> s3 = 'vivid'
#>>> def is_anagram(s1, s2):
#... if s1.lower() == s2.lower():
#... return False
#... return sorted(s1.lower()) == sorted(s2.lower())
s1 = input("Enter the first string:")
s2 = input("Enter the second string:")
def anagramCheck(s1,s2):
if s1.... |
import os
import random
import time
#live_file_tmp = open("live_log","r")
def read():
file = open("accesslog","r")
global live_file
live_file = open("live_log","a")
cnt = random_val()
#Timer.start()
#time.time()
while (True):
data = file.readline()
if cnt == 0:
time.sleep(2)
cnt = random_val()
else :... |
"""
This module contains the eth2 HTTP validator API connecting a validator client to a beacon node.
"""
from abc import ABC
from dataclasses import asdict, dataclass, field
from enum import Enum, unique
import logging
from typing import Collection, Iterable, Optional, Set
from eth_typing import BLSPubkey, BLSSignatur... |
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
table = {}
max_count = 0
number_of_max = 0
for task in tasks:
if task not in table:
table[task] = 0
table[task] += 1
if table[task] == max_count:
... |
"""Given: A DNA string s of length at most 1000 nt.
Return: Four integers (separated by spaces) counting the respective
number of times that the symbols 'A', 'C', 'G', and 'T' occur in s.
Sample:AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC
Output: 20 12 17 21 """
acount = 0
ccount = 0
tcou... |
def calc(a, op, b):
if op == "+":
return a + b
else:
return a - b
s = input()
A, B, C, D = [int(c) for c in s]
ops = ["+", "-"]
ans = ""
for op1 in ops:
for op2 in ops:
for op3 in ops:
if calc(calc(calc(A, op1, B), op2, C), op3, D) == 7:
ans = str(A) + op1 + str(B) + op2 + str(C) + op3 + str(D) + "=7"
... |
from django.urls import include, path
from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView
from rest_framework.routers import DefaultRouter
from . import views
app_name = "api"
api_router = DefaultRouter(trailing_slash=False)
api_router.register(r"journal", views.Journal... |
from typing import List
from Tree.PrintBST import PrintBST
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# Time complexity : O(n),n 是二叉搜索树的节点数。每一个节点恰好被遍历一次。
... |
from collections import OrderedDict
import re
from fsm import fsm
from persistence import DiceType, DiceFace, DiceThrowType, DiceThrowAdjustmentType, DiceThrow, Player, Dice, \
DiceThrowResult, DiceThrowAdjustment
class LogFileParser:
def __init__(self, session):
self.session = session
self... |
from django.urls import path
from carts import views
app_name = 'carts'
urlpatterns = [
path('', views.cart, name='cart'),
path('checkout', views.checkout, name='checkout'),
path('item_remove_cart/<int:pk>/', views.item_remove_cart, name='item_remove_cart'),
path('item_quantity_minus/<int:pk>/', views.... |
#!/usr/bin/python3
x=[]
x.append(0x25)
x.append(0x2b)
x.append(0x20)
x.append(0x26)
x.append(0x3a)
x.append(0x28)
x.append(0x25)
x.append(0x1e)
x.append(0x28)
x.append(0x1e)
x.append(0x32)
x.append(0x34)
x.append(0x21)
x.append(0x2c)
x.append(0x28)
x.append(0x33)
x.append(0x1e)
x.append(0x33)
x.append(0x27)
x.append(0x... |
# dp를 사용하지 않음
# import sys
# n = int(sys.stdin.readline())
# temp = 1 #1에서 더해나가는 방식
# count = 0
# if n ==1:
# print(0)
# else:
# while True:
# if temp*3 < n:
# temp = temp*3
# elif temp*2 <n:
# temp = temp*2
# temp += 1
# count += 1
# if... |
"""
OpenBikes API library
--------------------------------
"""
from obpy.obpy import *
__project__ = 'obpy'
__author__ = 'Axel Bellec'
__copyright__ = 'OpenBikes'
__licence__ = 'MIT'
__version__ = '1.0.0'
|
#-------------------------------------------------------------------------------
# Name: blue2cosd.py
# Purpose:
#
"""
To update SDEP2 with zipped FGDB's stored on an FTP site.
NOTES: For the purposes of this script a 'Dataset' can be any type of data
(Feature Class, Table, etc.). A Feature Dataset (FDS) is th... |
from flask import Flask,render_template,request
from datetime import datetime
import random
import requests
from bs4 import BeautifulSoup
app=Flask(__name__)
#print(datetime.today())
@app.route("/")
def hello():
return render_template("index.html")
@app.route("/hello/<string:name>")
def hellojs(name):
r... |
import time
import json
from nba_api.stats.static import teams
from nba_api.stats.endpoints import leaguegamefinder
from data_gathering.get_plays import plays_to_json
def get_processed_game_ids():
with open('out/all_plays.json') as f:
game_ids = [json.loads(row)['game_id'] for row in f.readlines()]
... |
"""
Runs the job_hunter program
"""
import pandas as pd
import pull_indeed as pull_indeed
import waze
from tqdm import tqdm
def job_hunter():
CITY = str(input("Search which City, State?: "))
CITY = CITY.replace(" ", "+")
JOB_TITLE = str(input("what job title?: "))
JOB_TITLE = JOB_TITLE.replace(" ", "... |
class Solution:
def ways(self, pizza: List[str], k: int) -> int:
MOD = 10**9+7
amt = 0
@lru_cache(None)
def cuts(c, x1, x2, y1, y2):
amt = 0
if c+1 == k:
for i in range(y1, y2):
if 'A' in pizza[i][x1:x2]:
... |
from django.utils import timezone
from cmd_controller.models import CommandController
class CommandContextManager:
def __init__(self, script_name, is_reenterent=False):
self.script_name = script_name
self.is_reenterent = is_reenterent
def __enter__(self):
self.command_controller_qs =... |
import io
import logging
from time import time
from urllib.parse import quote
import pyqrcode
from flask import Blueprint, current_app, redirect, url_for, g, request, Response, flash, send_file
from flask_babel import lazy_gettext as _
from flask_mongoengine.wtf import model_form
from mongoengine import NotUniqueError... |
from tkinter import *
import os
class Demo1:
def __init__(self, master):
self.master = master
self.master.option_add('*font', ('Ariel', 12, 'bold'))
self.master.title("Chatbox - Menu")
self.master.geometry("320x320")
fm = Frame(self.master)
w = Label(self.master, tex... |
# Generated by Django 2.2.4 on 2019-10-25 01:25
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('persona', '0001_initial'),
('venta', '0006_auto_20191024_1612'),
]
operations = [
migrations.AlterF... |
__version__ = "0.1.2"
from .data import *
from .nn import *
from .bocos import *
from .pde import PDE
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse,HttpResponseRedirect
import random
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate,login,logout
from django.contrib.aut... |
#!/usr/bin/env python
import sys
import os
import fnmatch
dirs = ['initialFit','finalFit','mhFit','simFit']
procs = ['ggh','vbf','wzh','tth']
ncats = 9
def organise():
for dir in dirs:
for proc in procs:
for cat in range(ncats):
os.system('mkdir -p plots/%s/%s_cat%d'%(dir,proc,cat))
os.sy... |
from __future__ import absolute_import, unicode_literals
from dash.orgs.models import Org
from django.contrib.auth.models import User
from django.db import models
from django.db.models import Count
from django.utils.translation import ugettext_lazy as _
from tracpro.contacts.tasks import sync_org_contacts
class Abst... |
print('i can only go to two countries now. QAQ')
conutries = ['A','B','C',]
conutries[2] = 'D'
conutries.insert(0,'E')
conutries.insert(2,'F')
conutries.append('G')
print(conutries)
print(conutries.pop(0) + ' Sorry, i am not going yet')
print(conutries.pop(1) + ' Sorry, i am not going yet')
print(conutries.pop(2) + ' S... |
# Title : Find sub array of specified sum
# Author : Kiran raj R.
# Date : 01:11:2020
def find_sub_array(list_in, sum_list):
list_start = 0
list_end = 0
current_sum = list_in[0]
length = len(list_in)
if length < 1:
print(f"List has length of zero")
while list_end < length:
... |
#!/usr/bin/env/ python
n,k = map(int, input().split())
interview = list()
interview = [list( map( int , input().split() ) ) for i in range(n)]
interview.sort(key = lambda x: x[1])
local = int(k*1.5)
line = interview[n - local][1]
sum1 = 0
i = n - 1
while interview[i][1] >= line:
sum1 += 1
i -= 1
print(l... |
"""The game's constants"""
#Paramètre de la fenêtre
NUMBER_OF_SPRITE = 15
SPRITE_SIZE = 30
SIDE = NUMBER_OF_SPRITE * SPRITE_SIZE
WINDOW_TITLE = "Get out MacGyver!!"
#Ensemble des images
IMAGE_MAC = "images/mg.png"
IMAGE_GUARD = "images/guard.png"
IMAGE_FLOOR = "images/floor.png"
IMAGE_WALL = "images/wall.png"
IMAGE_N... |
MAY_12_MATCHES = """
1899 Hoffenheim - Borussia Dortmund
Hertha BSC - RB Leipzig
VfL Wolfsburg - 1. FC Köln
1. FSV Mainz 05 - Werder Bremen
Hamburger SV - Bor. Mönchengladbach
FC Schalke 04 - Eintracht Frankfurt
SC Freiburg - FC Augsburg
Bayer Leverkusen - Hannover 96
Bayern München - VfB Stuttgart
SpVgg Unterhaching ... |
#!/usr/bin/env python
# coding: utf-8
# ### Hello , this is my first kernel.
# ### I will be exploring the housing sale prices in King County, USA between the time period May 2014 - May 2015.
# #### Firstly, I will go through a thorough data exploration to identify most important features and to explore the intercor... |
import csv
if __name__=="__main__":
fday=open("info_day.csv","r")
fnight=open("info_night.csv","r")
combined=open("info_combined.csv","w", newline='')
rday=list(csv.reader(fday))
rnight=list(csv.reader(fnight))
writer=csv.writer(combined)
writer.writerow(['Day',"Temperature(Day)","Temperature(Night)","... |
import random
# This function simulates a single roll of a die.
def rollOneDie():
m = 0
for i in range(1, 100001):
if random.randint(1,6) == 4:
m += 1
print("Total four is ", m, " out of", i)
print("Probability of four is ", m/i)
print("error", ((m/i)-1/6)/(1/6))
p... |
b=4
a=10
print(id(a))
def pola():
a=15
c=4
print("in function",a,b)
def lola():
global b
print("in 2nd function",b)
lola()
pola()
print("outside function",a)
def loka():
x=globals()['a']
print(id(x))
print(x)
globals()['a']=1
print(a)
loka()
print(a) |
import numpy as np
def actf(x):
return 1/(1+np.exp(-x))
def actf_deriv(x):
return x*(1-x)
X = np.array([[0,0,1],[0,1,1],[1,0,1],[1,1,1]])
print(X.shape)
y = np.array([[0],[1],[1],[0]])
#y = np.array([[0],[0],[0],[1]])
np.random.seed(5)
inputs =3 # 입력층 노드는 바이어스를 위해 1개 추가
hiddens =6 # 은닉층도 바이어스를 위해 1개 추가
out... |
def calc():
result = 0
while True:
expression = (yield result)
split = expression.split()
lvalue = int(split[0])
rvalue = int(split[2])
if split[1] == '+':
result = lvalue + rvalue
elif split[1] == '-':
result = lvalue - rvalue
elif... |
"""Compare two HDF5 files.
If the function does not output anything all datasets are present in both files,
and all the content of the datasets is equal.
Each output line corresponds to a mismatch between the files.
:usage:
G5compare [options] <source> <other>
:arguments:
<source>
HDF5-f... |
__author__ = 'Perevalov'
import json
from pprint import pprint
def converting(fl):
# converting weird ASTRA output format to float
if fl is None or fl == "":
return
elif fl.isalnum() and not fl.isdigit():
return
elif len(fl) >= 2 and (fl[-2] == "-" or fl[-2] == "+") and len(fl) != ... |
from time import sleep
from machine import UART
from utils.pinout import set_pinout
from gc import mem_free
from components.rfid import PN532_UART
print("--- RAM free ---> " + str(mem_free()))
pinout = set_pinout()
uart = UART(2, 115200)
#UART1:
#uart.init(baudrate=115200, tx=pinout.TXD1, rx=pinout.RXD1, ... |
# coding = utf-8
"""
Author:micheryu
Date:2020/3/23
Motto: 能用脑,就别动手~
"""
import os
import time
import pytest
from common import Shell
from config import Config
from log import logconf
from report import SendReport
def run(time_str):
conf = Config.Config()
log = logconf.logconf()
log.info('初始化配置文件,path... |
from django.db import models
from django.conf import settings
from django.contrib.auth.models import AbstractUser
USER_TYPES = [('cogmaker', 'Cog Maker'), ('coguser', 'Cog User')]
class User(AbstractUser):
usertype = models.CharField(choices=USER_TYPES, max_length=8)
def __str__(self):
return self.u... |
import json
import sys
import lief
from elftools.common.py3compat import bytes2str
from elftools.elf.elffile import ELFFile
from elftools.elf.sections import NullSection, StringTableSection, SymbolTableSection
from elftools.elf.segments import InterpSegment
from func import compute_entropy
from func import get_sectio... |
from assist_model import *
from assist_view import *
import os
import sys
class ConsoleController:
def __init__(self, command_birthday, command_create, command_delete, command_help, command_edit, command_exit,
command_search, command_show, view):
self.command_birthday = command_b... |
__author__ = 'Vanc Levstik'
import unittest
from pyflare import PyflareHosting
from mock_responses import mock_response_hosting
class PyflareTest(unittest.TestCase):
def setUp(self):
self.pyflare = PyflareHosting('your_api_key')
@mock_response_hosting
def test_host_key_regen(self):
respo... |
"""Base testcases for integrations unit tests."""
from __future__ import annotations
from typing import List
from django.conf import settings
from django.core.cache import cache
from djblets.integrations.manager import shutdown_integration_managers
from djblets.testing.testcases import TestCase, TestModelsLoaderMix... |
from Core.Metadata.Columns.ColumnMetadata import ColumnMetadata
from Core.Metadata.Columns.ColumnType import ColumnType
from GoogleTuring.Infrastructure.Domain.GoogleAttributeFieldsMetadata import GoogleAttributeFieldsMetadata
class GoogleAttributeMetadataColumnsPool:
# Structure fields and parameters
# Obje... |
#!/usr/bin/python3
"""
listen.py
This is the clearpixel listener that is used to determine when an email has been opened by the recipient.
Listener id: 5
Activity id: 1 only.
"""
import os
import cgi
import time
import database
# the data we want is encoded in the following format:
# <16 bytes of junk>AAACC<more... |
"""Unit test module for PSyGrid class."""
# import unittest
# import os
# import shutil
# import zipfile
# from posydon.utils.common_functions import PATH_TO_POSYDON
# from posydon.grids.psygrid import PSyGrid
#
#
# class TestPSyGrid(unittest.TestCase):
# """Class for unit-testing the PSyGrid object."""
#
# @... |
import copy
import datetime
import hashlib
import json
import re
from threading import Lock
import semver
class ResourceKeyExistsError(Exception):
pass
class ConstructResourceError(Exception):
def __init__(self, msg):
super().__init__("error constructing openshift resource: " + str(msg))
# Regex... |
from dqn import DQNTrainer
from utils.grid_search import RandomGridSearch
from joblib import Parallel, delayed
import multiprocessing
import gc
#from guppy import hpy
#from memory_profiler import profile
#@profile
def parallelize(game, params):
print(params)
#game = "/home/eilab/Raj/tw-drl/Games/obj_20_qlen_5_... |
import numpy as np
from tqdm import tqdm
import glob
import os
import cv2
from joblib import Parallel, delayed
import multiprocessing
import fonctions
from datetime import datetime
import fonctions_yal
from sklearn import preprocessing
def calculate(type,n, path_faces): #calculer les histogrammes lbp du dossier n qui t... |
import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as ss
from nems_lbhb.baphy_experiment import BAPHYExperiment
parmfile = '/auto/data/daq/Cordyceps/training2020/Cordyceps_2020_05_25_BVT_1.m'
options = {'pupil': True, 'rasterfs': 100}
manager = BAPHYExperiment(parmfile=parmfile)
rec = manager.ge... |
from datadog import initialize, api
options = {
'api_key': '9775a026f1ca7d1c6c5af9d94d9595a4',
'app_key': '87ce4a24b5553d2e482ea8a8500e71b8ad4554ff'
}
initialize(**options)
newcomment = api.Comment.create(message='Should we use COBOL or Fortran?')
api.Comment.delete(newcomment['comment']['id']) |
from bs4 import BeautifulSoup
import datetime
import helpers
import hockey_scraper as hs
import sys
sys.path.append("..")
from machine_info import *
def fix_name(player):
"""
Get rid of (A) or (C) when a player has it attached to their name
Also fix to "correct" name -> The full list is in helpers.p... |
def swap_cases(s):
ans = []
for i in s:
if i.isupper() == True: #checking if the letter is in upper case, if true then it we convert it to lowercase
ans.append(i.lower())
else:
ans.append(i.upper())
s1 = ''.join(ans) # joining the elements of ans list to form a stri... |
from __future__ import absolute_import
from rlib import jit
from rlib.min_heap_queue import heappush, heappop, HeapEntry
from som.compiler.bc.bytecode_generator import (
emit1,
emit3,
emit_push_constant,
emit_return_local,
emit_return_non_local,
emit_send,
emit_super_send,
emit_push_glo... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.static_menu, name='menu'),
path('dynamic_menu', views.all_dishes, name='dmenu'),
path('<str:dish_id>/', views.detail, name='menu_detail'),
] |
values = input("Please enter the numbers by period : ")
list = values.split('.')
tuple = tuple(list)
print ("List of values are :" , list)
print ("tuple of values are :" , tuple)
color_list = ["Red","Green","White" ,"Black"]
print( "%s %s"%(color_list[0],color_list[-1])) |
#! /usr/bin/env python
'''
Calculate UTR from gff containing ONLY mRNA and CDS
for Apollo gff files: coordinates are ordered
'''
# last update: 7/11/2017
import re
import sys
GFF = sys.argv[1] # single gene gff
with open(GFF) as fin:
for line in fin:
line = line.rstrip()
line = line.split()
... |
from matplotlib.pyplot import *
from mlxtend.plotting import plot_confusion_matrix
from tensorflow.keras import backend
from sklearn.metrics import confusion_matrix
import scipy as sp
import numpy as np
import pandas as pd
import skimage.transform
import PIL
import scipy.ndimage as spi
import matplotlib.pyplot as plt
f... |
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2011,2012,2013,2014,2015,2016 Contributor
#
# 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... |
from sklearn.datasets import make_classification
X, y = make_classification(
n_samples=5000,
n_features=2,
n_informative=2,
n_redundant=0,
n_repeated=0,
n_classes=3,
n_clusters_per_class=1,
weights=[0.01, 0.05, 0.94],
class_sep=0.8,
random_state=0,
)
from imblearn.over_sampling... |
class SilentGenerator():
def __init__(self, rate):
self._RATE = rate
def get_silent(self, seconds):
"""Возвращает массив нулей длинной соответствующей тишине
в seconds секунд при частоте RATE
"""
return [0 for i in range(int(seconds*self._RATE))]
|
#Time: O(n)
#Space: O(n)
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
#brute force:
#iterate and do the calcuation from any index
#lead to O(n^2)
#method 1, preprocess, and divide by every index value
#Time: O(n)
#method... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 15 18:21:21 2017
@author: Eghosa
"""
import numpy as np
import pandas as pd
import sklearn as skl
from sklearn.datasets import make_spd_matrix as make_cov
import matplotlib.pyplot as plt
import scipy as sp
import os
import plotly.offline as py
import plotl... |
import json
import time
import base64
from flask import Blueprint, request, jsonify
from common import url_constant, param_constant, constant
from werkzeug.exceptions import BadRequest, InternalServerError
from utils import log_service, utils, postgres_util, s3_util
from services.audio_collection_services import AudioC... |
from typing import Tuple, List, Callable
# Types needed for various functions
Lambda = float
Delta = float
Precision = float
Recall = float
Frame = List[List[List[int]]] # n x m x 3 dims
Video = List[Frame] # t length video
VideoDataset = List[Tuple[str, List[Tuple[str, bool]]]]
FrameDataset = List[Tuple[Video, Lis... |
import os
import glob
import shutil
import pandas as pd
import importlib
import logging
import pytest
import tests.test_utils as test_utils
import drep
from drep import argumentParser
from drep.controller import Controller
from drep.WorkDirectory import WorkDirectory
@pytest.fixture()
def self():
self = test_uti... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 23 18:37:56 2014
@author: hang
"""
import sys
for i,j in enumerate(sys.argv):
print(i),
print(j)
|
import numpy as np
import os
import cv2
import random
import pickle
import tensorflow
from tensorflow.keras import utils
DATADIR = "/Users/ankithudupa/Documents/Personal Projects/Python/MNIST CNN/trainingSet"
CATEGORIES = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
IMG_SIZE = 28
training_data = []
def create... |
#compute grade problem
#this program is written using the ideas in bypass_ifelse.py
def score_1(score):
#this function is written using the ideas in bypass_ifelse.py
print "Score out of range, Enter a score between 0.0 to 1.0 only"*((score<0.0)+(score>1.0))
#that is the equivalent of:
#if (score<0.0) or (score >1.0... |
import logging
import os
from argparse import ArgumentParser
import sentry_sdk
from sentry_sdk.integrations.logging import LoggingIntegration
from sqlalchemy import create_engine
from feed_proxy import handlers
from feed_proxy.conf import settings
from feed_proxy.fetchers import fetch_sources
from feed_proxy.parsers ... |
from datetime import date
import copy
import json
import csv
from django.test import LiveServerTestCase
from rest_framework import serializers
from rest_framework.test import APITestCase
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdrive... |
import unittest
from solution import Solution
class TestStringMethods(unittest.TestCase):
def test(self):
sol = Solution()
self.assertEqual(sol.updateMatrix([[0,0,0], [0,1,0], [0,0,0]]),
[ [0,0,0], [0,1,0], [0,0,0 ]])
def test2(self):
sol = Solution()
self.assertE... |
from pycocotools import mask as maskUtils
import json
import cv2
import os
import numpy as np
ff = open("output.pkl.json")
data = json.load(ff)
print(len(data))
#print(data[0].keys())
valid_dir = "data/valid/JPEGImages/421/"
valid_annotations= "data/annotations/instances_val_sub.json"
save_dir = "data/save/"
def app... |
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class CurrenciesConfig(AppConfig):
name = "nucoro_currency.currencies"
verbose_name = _("Currencies")
def ready(self):
try:
import nucoro_currency.currencies.signals # noqa F401
except Im... |
# -*- coding: utf-8 -*-
from json import dumps
from django.core.urlresolvers import reverse
from django.conf import settings
from django.forms.formsets import formset_factory
from django.http import Http404
from django.shortcuts import (render_to_response, get_object_or_404,
redirect, Http... |
import labrad
import numpy as np
from matplotlib import pyplot
import lmfit
def expo_model(params, x):
amplitude = params['amplitude'].value
time_offset = params['time_offset'].value
amplitude_offset = params['amplitude_offset'].value
decay_time = params['decay_time'].value
model = amplitude*np.ex... |
# 6.0001 Spring 2020
# Problem Set 3
# Written by: sylvant, muneezap, charz, anabell, nhung, wang19k, asinelni, shahul, jcsands
# Problem Set 3
# Name: Gyalpo Dongo
# Collaborators: Paterne Byiringiro
# Time Spent: 4:00
# Late Days Used: (only if you are using any)
import string
# - - - - - - - - - -
# ... |
import tkinter
import tkinter
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
from tkinter import Menu
from PIL import ImageTk,Image
import cv2
import PIL.Image, PIL.ImageTk
import pygame
import pygame.camera
import keras
import numpy as np
import matplotlib
mat... |
import tkinter as tk
from tkinter import messagebox
app = tk.Tk()
app.title('Calculator')
entry = tk.Entry(app)
entry.pack()
def calc():
#print("clicked")
inp = entry.get()
print(f"'{inp}'")
try:
out = eval(inp)
except Exception as err:
messagebox.showwarning(title = "Error", mess... |
# Generated by Django 3.2 on 2021-04-17 11:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("backend", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="todoitem",
name="finished",
f... |
## 138. Copy List with Random Pointer
#
# A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
#
# Return a deep copy of the list.
##
# Definition for singly-linked list with a random pointer.
class RandomListNode(object):
def __init__... |
import hashlib
import json
from urllib.parse import urlparse
import scrapy
from kingfisher_scrapy.base_spider import ZipSpider
class Malta(ZipSpider):
name = 'malta'
def start_requests(self):
yield scrapy.Request(
'http://demowww.etenders.gov.mt/ocds/services/recordpackage/getrecordpack... |
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
from sklearn.linear_model import LinearRegression
import numpy
import pickle
class TechnicalRiskModel:
def __init__(self):
pass
... |
"""
Django settings for dotaparty project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build path... |
# Scene class components:
## ._manager
## .finished
## .pause()
## .resume()
## .end()
## .handle_input(events, pressed_keys)
## .update(dt)
## .draw(surface)
# Transition class components (in addition to Scene):
## .from_scene
## .to_scene
class scene_manager(object):
def __init__(self):
# Stack of scen... |
def constructSquare(s): # долгое решение
if len(s) == 0: return -1
ans, val =- 1, 10
used, nums = {}, {}
for ch in s:
if ch not in used:
val -= 1
if val <0: return ans
used[ch] = s.count(ch)
sq = int("9"*len(s))
min = int("1"+"0"*(len(s)-1))**0.5
... |
from lib.gopherpysat import Gophersat
from typing import Dict, Tuple, List, Union
import itertools
import random
import time
import sys
from wumpus_cli.lib.wumpus_client import WumpusWorldRemote
gophersat_exec = "./lib/gophersat-1.1.6"
## On genere le voca avec toujours 4 chiffres pour extraire plus facilement les co... |
x = [1, 2, 3, [4, 5, 6], 4, 5, [7, 8, [9, 10]]]
# the input being sent to the function has lists inside lists
def sum_of_all_nums_recursive(nums_and_num_lists: list) -> int:
# param is a list - which returns an int
# specifying this is optional
to... |
# -*- coding:utf-8 -*-
#
# 开发人员 : sunshenggang
# 开始时间 : 19-6-20 下午9:18
# 开发工具 : PyCharm Community Edition
from flask import render_template
from . import home
@home.app_errorhandler(404)
def page_not_found(e):
return render_template('/home/error/404.html'), 404
@home.app_errorhandler(500)
def internal_server_err... |
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
data = pd.read_csv('Iris.csv')
df_norm = data[['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm']].apply(lambda x: (x - x.min()) / (x.max() - x.min()))
X_5= df_norm.head(5)
X_5 = np.array(X_5, dt... |
from dbfread import dbf
table = dbf.DBF("data/Kommun_RT90_region.dbf")
def pull_names(row):
return f"{row['KnNamn']} kommun"
queries = list(map(pull_names, table))
|
numeros = []
num = int(input("Informe um número e, caso deseje sair, informe o valor -1: "))
numeros.append(num)
while(num != -1):
num = int(input("Informe um número e, caso deseje sair, informe o valor -1: "))
numeros.append(num)
def calculaMedia(numeros):
soma = 0
tamNumeros = len(numeros)... |
#!/usr/bin/env python
from __future__ import print_function
import sys
import os
import time
PY3 = sys.version_info[0] == 3
dirpath = os.getcwd()
if PY3:
xrange = range
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from geometry_msgs.msg import Twist
from geometry_msgs.msg import... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.