text stringlengths 38 1.54M |
|---|
# Webhooks for external integrations.
import re
from typing import Dict, List, Optional, Tuple
from django.http import HttpRequest, HttpResponse
from zerver.decorator import authenticated_rest_api_view
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
from zerver.l... |
import os
import sys
import time
os.system("sudo service apache2 stop")
time.sleep(5)
print "apache2 stopped"
os.chdir("/home/pi/node-rtsp-rtmp-server")
os.system("./start_server.sh &")
print "streaming server starting"
time.sleep(40)
print "streaming server started"
os.chdir("/home/pi/picam")
os.system("./picam -... |
variables = {}
variables["app.name"] = "Microbe"
variables["year"] = "2011"
variables["author"] = "Alexandre Deckner <alex@zappotek.com>"
variables["app.class"] = "App"
variables["main.view.class"] = "MainView"
variables["main.window.class"] = "MainWindow"
variables["app.signature"] = "application/x-vnd.Haiku-" + vari... |
import time
import base64
import uuid
from fastapi import APIRouter,Request
from base import get_base_resp
dynamic_data_router = APIRouter(prefix="/dynamic-data", tags=["Dyncmic Data"])
@dynamic_data_router.get("/base64/{value}")
async def get_base64_value(value:str="SFRUUEJJTiBpcyBhd2Vzb21l"):
resp_text = "Inco... |
from django.shortcuts import render
from rest_framework import viewsets,generics,mixins
from django.views.generic import DetailView,ListView
from .serializers import AssetSerializer,ServerSerializer,TreeNodeSerializer,IDCSerializer
from .models import Asset,Server,TreeNode,IDC
from .page import StandardResultsSetPagin... |
# query string -> "http://www.example.com?key1=value1&key2=value2"
# it is this part after question mark
# we can check options for requests on "https://icanhazdadjoke.com/api"
import pyfiglet
from random import choice
import requests
url = "https://icanhazdadjoke.com/search"
def print_f(text_to_print, color="MAGE... |
#100-999之间的水仙花数
for item in range(100,1000):
ge=item%10
shi=item//10%10
bai=item//100
#print(ge,shi,bai)
if ge**3+shi**3+bai**3==item:
print(item,'is a flower.')
|
'''
Module providing the `Synapses` class and related helper classes/functions.
'''
import collections
from collections import defaultdict
import functools
import weakref
import re
import numbers
import numpy as np
from brian2.core.base import weakproxy_with_fallback
from brian2.core.base import device_override
from... |
from localground.apps.site.tests.views.print_tests import *
from localground.apps.site.tests.views.forms import *
from localground.apps.site.tests.views.map_tests import *
from localground.apps.site.tests.views.profile_tests import *
from localground.apps.site.tests.views.sharing_tests import *
from localground.apps.si... |
'''usuario = {
'nombre':'juan perez',
'domicilio':{
'calle':'Calle Falsa 123',
'localidad':'Saenz Peña'
},
'nivel':'basico'
}
print(usuario['domicilio'].get('localidad'))
'''
'''
verduras =['papa','cebolla','rucula','batata','lechuga']
#contador=0
for contador, una_verdura in enumerate(... |
# from networkx.generators import random_clustered
import numpy as np
import logging
import sys
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Rectangle
import networkx as nx
import tqdm
from tqdm import trange
from pyfme.aircrafts import Cessna172
from pyfme.environment.atmosphere import ISA19... |
FACT_MAP = {
0: 1,
1: 1
}
def factorial(n):
if n in FACT_MAP:
return FACT_MAP[n]
return n * factorial(n - 1)
def sumDigits(toSum):
value = 0
while toSum > 0:
value += toSum % 10
toSum = toSum // 10
return value
sumDigits(factorial(100))
|
# this all of the function and variables from tkinter.
from tkinter import *
# this to import the theme from tkinter. theme is like a background color or font.
from tkinter import ttk
# this will create the top parent windows which i can use as a parent windows for others widgets.
# the reference for the pare... |
# Searching algorithms
def linear_search(array, val, len):
answer = 'Not found'
index = 0
while index < len:
if array[index] == val:
answer = index
index += 1
return answer
def better_linear_search(array, val, len):
answer = 'Not found'
index = 0
while index <... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('snippets', '0002_remove_like_whether_like'),
]
operations = [
migrations.RenameModel(
old_name='Like',
... |
import sys
def get_min_tapes():
global N, L, points
cnt, now = 0, -1
for point in points:
if point > now:
now = point + L -1
cnt += 1
return cnt
if __name__ == '__main__':
N, L = map(int, input().split())
points = sorted(list(map(int, sys.stdin.readline().s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 3.3.0 (http://hl7.org/fhir/StructureDefinition/EligibilityRequest) on 2018-05-12.
# 2018, SMART Health IT.
from . import domainresource
class EligibilityRequest(domainresource.DomainResource):
""" Determine insurance validity and scope of co... |
from django.test import TestCase
from django.contrib.auth.models import User
from django.urls import reverse
from .models import *
import unittest
class AddProductTest(TestCase):
"""Tests the "sell" form where a user adds a new product for sale
Model(s): Product, ProductType, User
Template(s): c... |
###PRIVATE PREAMBLE###
import numpy as np
from utils.util_data import integers_to_symbols, add_cartesian_awgn as add_awgn
###PRIVATE PREAMBLE###
def trainer(*,
agents,
bits_per_symbol: int,
batch_size: int,
train_SNR_db: float,
signal_power: float = 1.0,
ba... |
import numpy as np
from skimage import img_as_ubyte
__all__ = [
"percentile_normalize",
"percentile_normalize99",
"normalize",
"minmax_normalize",
"float2ubyte",
]
def percentile_normalize(
img: np.ndarray, lower: float = 0.01, upper: float = 99.99
) -> np.ndarray:
"""Channelwise percenti... |
STANFORD_JAR="/home/dang/Desktop/stanford-corenlp-full-2016-10-31/stanford-corenlp-3.7.0.jar"
STANFORD_MODEL="/home/dang/Desktop/stanford-corenlp-full-2016-10-31/stanford-corenlp-3.7.0-models.jar"
from nltk.parse.stanford import StanfordParser
def sfParser(jar_path=STANFORD_JAR,model_path=STANFORD_MODEL):
return ... |
import seaborn as sns
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
tips = sns.load_dataset("tips")
g = sns.jointplot("total_bill", "tip",
data=tips, kind="hex",
xlim=(0, 60), ylim=(0, 12))
k = sns.jointplot("total_b... |
""" making a code for withdrawal """
savings_account = 100000
current_account = 100000
withdrawal = 0
account_type = int(input("""
enter the account type
1. savings 2. current
>>> """.title()))
if account_type == 1:
prompt = int(input("\nenter amount\n>>> ".title()))
if prompt <= savings_accoun... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def no_op(apps, schema_editor):
# Do nothing on reversal
pass
# The following data was downloaded from the world bank dataset
# http://databank.worldbank.org/data/views/reports/metadataview.aspx
# Latit... |
# Copyright 2021 Alibaba Group Holding Limited. All Rights Reserved.
from ..utils.registry import Registry
MODELS = Registry("MODELS")
BACKBONES = Registry("BACKBONES")
NECKS = Registry("NECKS")
HEADS = Registry("HEADS")
BRICKS = Registry("BRICKS")
STEMS = BRICKS
LOSSES = Registry("LOSSES")
|
import json
import general
def get(memb):
with open(general.settings) as f:
settings = json.load(f)
f.close()
lvl1 = settings["perms"]["lvl1"]
lvl2 = settings["perms"]["lvl2"]
lvl3 = settings["perms"]["lvl3"]
lvl = [0]
for r in memb.roles:
if r.name in lvl3:
... |
import FWCore.ParameterSet.Config as cms
from CalibTracker.SiStripChannelGain.SiStripGainsPCLHarvester_cfi import SiStripGainsPCLHarvester
alcaSiStripGainsAAGHarvester = SiStripGainsPCLHarvester.clone()
alcaSiStripGainsAAGHarvester.calibrationMode = cms.untracked.string('AagBunch')
alcaSiStripGainsAAGHarvester.DQM... |
#!/usr/bin/python3
# Platform module
import platform
print(platform.platform())
print(platform.platform(1))
print(platform.platform(0,1))
|
from sympy import *
from sympy.parsing.latex import parse_latex
import os
import subprocess
# import random
from PyQt5.QtWidgets import QDialog
class vh_bbt_b3(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
def bbt_b3(self):
# bien = self.lne_bien.text()
# lay tho... |
#!/usr/bin/env python3
'''
obecnyURL = driver.get_url
driver.close() -> zamyka karte
driver.quit() -> wychodzi?
opis: bot zakupowy -> do sklepow komputronik i x-kom.
jesli dany produkt jest dostepny,
zostanie zakupiony i zamowiony do salonu.
jesli jest niedostepny skryp ma sie przerwac.
docelow... |
# Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import absolute_import
from telemetry.internal.browser import extension_to_load
class ExtensionDict(object):
"""Dictionary of ExtensionPa... |
from unittest import TestCase, main
from telegraph.utils import content_to_html, html_to_content
from fixtures import CONTENT, HTML
class TestUtils(TestCase):
def test_content_to_html(self):
html = content_to_html(CONTENT)
self.assertEqual(html, HTML)
def test_html_to_content(self):
... |
#!/usr/local/bin/python
import httplib, sys, string, regsub
def massage(stuff):
stuff = regsub.gsub('\(GRAND PRAIRIE\|CALGARY\|EDMONTON\|MEDICINE HAT\) *, *CA', '\\1, AB', stuff)
stuff = regsub.gsub('\(WHISTLER\|VANCOUVER\) *, *CA', '\\1, BC', stuff)
stuff = regsub.gsub('WINNIPEG *, *CA', 'WINNIPEG, M... |
import logging
from moon_manager.api.base_exception import BaseException
logger = logging.getLogger("moon.manager.api." + __name__)
class UnknownName(BaseException):
def __init__(self, message):
# Call the base class constructor with the parameters it needs
super(UnknownName, self).__init__(messa... |
# Dzien 5 CIEZKIE ZAJECIA
# Sowniki
# Slownik tworzy sie otwierajac nawias klamrowy.
# names, surnames i city to klucze i im przypisane sa wartosci.
# # deklaruje slownik:
# contacts = {"names": ["Ala", "Ola", "Jan"], "surnames": ["Kowalski", "Malinowska", "Igrekowski"],
# "cities": ["Warszawa", "Gdansk",... |
a = int(input())
for _ in range(a):
num = list(map(str, input().split()))
sum = 0
for i in range(len(num)):
if i == 0:
sum = float(num[i])
elif num[i] == "@":
sum = sum * 3
elif num[i] == "%":
sum = sum + 5
elif num[i] == "#":
... |
a = []
with open('journey.txt') as f:
for line in f:
line = line.strip('\n')
a.append(line)
def sliceArray(array, n):
a = array[::n]
return a
def calculateTrees(right, down):
array = a
trees = 0
u = 0
if (down > 1):
array = sliceArray(array, down)
for item in a... |
import pygame
import random
import neat
import math
#Initializing the pygame
pygame.init()
#create screen
screen=pygame.display.set_mode((640,960))
score=0
px = 320
py = 944
status="T"
red=(255,0,0)
green=(0,255,0)
WHITE=(255,255,255)
status="T"
step_x=0
step_y=-16
pos=[(320,944)]
snek_len=... |
import cv2
import numpy as np
from color_test import BaseDetector
class PutdownPosition(object):
def __init__(self, level=None, row=None, col=None, bag_d=140, left_edge=90, right_edge=510, top_edge=100,
bottom_edge=400):
self.level, self.row, self.col = level, row, col
self.bag_d = bag_d
self._c... |
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
total = 0
nums.sort()
for i in range(len(nums) // 2):
total += nums[2 * i]
return total
nums = [6, 2, 6, 5, 1, 2]
# Output: 4
sol = Solution(... |
# -*- coding:utf-8 -*-
"""
@project : CCMS
@author:hyongchang
@file:test_accounts.py
@ide: PyCharm
@time: 2020-09-26 18:47
"""
import sys
import os
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
import pytest,allure
from service.api.Business.Business... |
import numpy as np
import matplotlib.pyplot as plt
from src.learning_perceptrons.basic_classifier import LinearClassifier
from src.sigmoid_perceptrons.sigmoid_perceptrons import SigmoidClassifier
def accuracies_plot(train: int = 5000):
"""
Generates a plot showing the accuracy of the classifier's output ove... |
def counting_sheep(n):
result = []
i = 1
if result is None:
result = []
if n == 0:
return "INSOMNIA"
while len(result) < 10:
num_to_check = n * i
for c in str(num_to_check):
if c not in result:
result.append(c)
i += 1
retur... |
import folium
from folium import plugins
import pandas as pd
import requests
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from xml.etree import ElementTree
%matplotlib inline
df=pd.read_csv('pop_data.csv')
m = folium.Map([6.5244,3.3792], zoom_start=1)
one=df.loc[df['Year'] == 2010]
firs... |
from django.urls import path
from . import views
urlpatterns = [
path('auth/', views.auth, name='auth'),
path('token/', views.token, name='token'),
path('', views.handle, name='handle'),
]
|
from __future__ import division
import numpy as np
import os
from scipy import ndimage as ndi
from skimage import feature
from scipy.misc import imread
from scipy.misc import imsave
import shutil
azcomplexity = []
#calculate complexity of letters a-z and store them in a list
for i in range(65,91):
#read image file t... |
from cattr._compat import is_bare, is_py37, is_py38
if is_py37 or is_py38:
from typing import Dict, List
def change_type_param(cl, new_params):
if is_bare(cl):
return cl[new_params]
return cl.copy_with(new_params)
List_origin = List
Dict_origin = Dict
else:
def chan... |
from selenium.webdriver.common.keys import Keys
import time
class TicketDeletePage:
URL = 'http://127.0.0.1:5000/tickets'
def __init__(self, browser):
self.browser = browser
def load(self):
self.browser.get(self.URL)
def delete_ticket(self, tl):
# * operator ex... |
import sqlite3
# get access to a db file
conn = sqlite3.connect('jobDB.db')
# create cursor object to gain access to methods like commit and execute
cur = conn.cursor()
conn.commit()
try:
cur.execute('''DROP TABLE JobsTable''')
conn.commit()
except:
pass
# create a new table
cur.execute(... |
import socket
import pygame
class Dualshock:
def __init__(self,id):
self.loopFlag = True
pygame.joystick.init()
self.keyMap = {'joyX':3,'joyY':4,'start':9}
self.__id = id
#canvas variables
self.clock = pygame.time.Clock()
self.x = 10
self.y = 10
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, jsonify, request
tasks = [
{
"id": 1,
"title": "learn python",
"description": "blablabla",
"done": False
},
{
"id": 2,
"title": "learn flask",
"description": "foofoofoo",
... |
#!/usr/bin/python3
"""Module Student to Disk and Reload"""
class Student:
"""Defines class student"""
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self, attrs=None):
"""Retrieves a dictio... |
#!/usr/bin/python
from pychartdir import *
# Sample data for the Box-Whisker chart. Represents the minimum, 1st quartile, medium, 3rd quartile
# and maximum values of some quantities
Q0Data = [40, 45, 40, 30, 20, 50, 25, 44]
Q1Data = [55, 60, 50, 40, 38, 60, 51, 60]
Q2Data = [62, 70, 60, 50, 48, 70, 62, 70]
Q3Data = [... |
import winsound
from random import randint
from time import sleep
import wx
ganarcambio=0
ganarsincambio=0
perdercambio=0
perdersincambio=0
abierta=0
actual=0
otra=0
premio=0
turno = False
class MiFrame(wx.Frame):
def __init__(self,*args,**kwargs):
global turno
wx.Frame.__init__(self,*args,**kwar... |
# Copyright 2019 NVIDIA Corporation
#
# 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 agreed to in wr... |
#-*- coding:utf8-*-
#制作图表,添加节点和边
import networkx as nx
import matplotlib.pyplot as plt
#/Users/kun/Desktop/
G = nx.DiGraph()
G.add_node(1)
G.add_node(2)
G.add_nodes_from([3,4,5,6])
G.add_cycle([1,2,3,4])
G.add_edge(1,3)
G.add_edges_from([(3,5),(3,6),(6,7)])
nx.draw(G)
#write_pajek(G, path, encoding='UTF-8')
#nx.w... |
def combination(arr, r):
def generate(chosen):
global answer
if len(chosen) == r:
answer += [chosen[:]]
return
start = arr.index(chosen[-1]) + 1 if chosen else 0
for nxt in range(start, len(arr)):
chosen += [arr[nxt]]
generate(chosen)
... |
def intersect(A, B):
n = len(A)
m = len(B)
iA = 0
iB = 0
common = []
while iA < n and iB < m:
if A[iA] < B[iB]:
iA += 1
elif B[iB] < A[iA]:
iB += 1
elif A[iA] == B[iB]:
common.append(A[iA])
iA += 1
iB += 1
... |
'''
Given a string s, return the longest palindromic substring in s.
'''
class Solution:
def longestPalindrome(self, s):
possible = set()
longest = s[0]
for char1 in s:
char = char1
possible.add(char)
s = s[1:]
for char2 in s:
... |
import csv
import os
from worker.abstract_item_generator import BaseItemGenerator
__author__ = 'pradeepv'
class SnomedConceptGenerator(BaseItemGenerator):
def __init__(self):
self.input_file = super().file_to_read('conceptfile')
self.infile = None
@property
def generate(self):
"... |
import torch
from tqdm import tqdm
def land_auto(loc, A, z_points, grid, dv, model, constant=None, batch_size=1024, metric_grid_sum=None,
grid_sampled=None,
init_curve=None, grid_init_curves=None, q_prob=None):
"""
Checks if scale is tensor or scale and calls corresponding LAND fun... |
while True:
n_50 = n_20 = n_10 = n_1 = 0
while True:
try:
value = int(input('Quanto deseja sacar?: R$'))
break
except ValueError:
print('Somente números inteiros, Por Favor!!')
print('Voce Recebeu:')
while value >= 50:
n_50 += 1
val... |
class Student:
__totalCGPA = 0.0
__totalCredits = 0
def __init__(self, id, name, address):
self.__studentId = id
self.__studentName = name
self.__studentAddress = address
def getStudentId(self):
return self.__studentId
def getStudentName(self):
retur... |
import time
import argparse
import os
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.utils as vutils
import torch.autograd... |
# Generated by Django 3.1.2 on 2021-01-04 08:04
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
def kratke_slova(list):
"""
Funkce hleda v seznamu sloa kratsi nez 5 pismen
"""
vysledek = []
for slovo in list:
if len(slovo) < 5:
vysledek.append(slovo)
return vysledek
def slova_k(list):
"""
funkce hleda v seznamu zvirata zacinajici na "k"
"""
vysledek = ... |
import requests, threading, os
from colorama import Fore
os.system(f'title [server leaver]')
os.system(f'mode 80,20')
print(f' {Fore.CYAN}server leaver \n\n')
print(f' {Fore.YELLOW}@9n8 {Fore.LIGHTMAGENTA_EX} \n')
def leave(guild_id, token)... |
"""
Tests for utils
To run all tests in suite from commandline:
python -m unittest tests.utils
Specific test class:
python -m unittest tests.utils.TestTicker
"""
# import pandas as pd
# import numpy as np
from .context import yfinance as yf
from .context import session_gbl
import unittest
# import requests_c... |
# Generated by Django 3.2.2 on 2021-05-29 18:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contact', '0003_about_imageabout_social'),
]
operations = [
migrations.AddField(
model_name='imageabout',
name='alt'... |
# https://github.com/MatrixManAtYrService/MathScripts/blob/master/listTopologies.py
# Consider the discrete topology on X
# X_Discrete = { {} {a} {b} {c} {a,b} {a,c} {b,c} {a,b,c} }
# Let the set Y contain all nontrivial elements of X_discrete
# Y = { {a} {b} {c} {a,b} {a,c} {b,c} }
# Notice that for any subset Z of... |
#'playlistId': 'PLcFcktZ0wnNn0VMRzVqV82s4vKpaTii_W',
# Import the modules
import requests
import pprint
import json
from YouTube_API_Key import get_my_api_key
# Define API KEY
DEVELOPER_KEY = get_my_api_key()
# Define Base URL
BASE_URL = 'https://www.googleapis.com/youtube/v3'
# Define Endpoint
ENDPOINT = 'comment... |
# 람다라는 함수가 있는데 당장 이해하실 필요는 없습니다.
# 함수를 아주 간단하게 표현할때 쓰는데요. 언젠가 필요할 때 쓰시면 됩니다.
# 어려우면 안써도 지장없습니다.
# 먼저 lambda가 아닌 함수를 만들어볼게요.
# 아래와 같이 x를 주면 1을 더해서 돌려주는 함수를 보세요.
def addOne(x) :
return x + 1
# 1을 x로 함수에 전달하니 f(x) = x + 1에서 1 + 1 = 2가 됩니다.
print(addOne(1))
# 그런데 아래처럼 한줄로 간단하게 표현할 수 있어요.
addOneLambda = (lambd... |
# Generated by Django 3.1 on 2021-03-12 19:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('react_chat_app', '0006_post'),
]
operations = [
migrations.AddField(
model_name='co... |
from django.urls import path
from ProyectoUniversidadApp import views
urlpatterns = [
path('index',views.index, name="Index"),
path('credito',views.credito, name="Credito"),
path('financiero',views.financiero, name="Financiero"),
path('operacional',views.operacional, name="Operacional"),
]
|
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render, redirect, get_object_or_404
from django.http import JsonResponse, HttpResponse
from .models import Snippet, Tag, Library, Language
from .forms import SnippetForm
from users.models ... |
from collections import defaultdict
import pandas as pd
import numpy as np
def getMostSignificantLabel(LABELS_FILE_PATH, LABELS_SEPERATOR, LABELS_NAMES):
df = pd.read_csv(LABELS_FILE_PATH, header= None, sep=LABELS_SEPERATOR,
names = LABELS_NAMES)
shapeOfDF = df.shape
numberOfColumns = sh... |
import xarray as xr
import numpy as np
test_gebco=False
test_bedmachine=True
#gebco
if test_gebco:
gebco1 = xr.open_dataset('../grid_gebco_30sec.nc')
gebco2 = xr.open_dataset('../grid_gebco_30sec_original.nc')
assert np.allclose(gebco1.lon.data, gebco2.lon.data)
assert np.allclose(gebco1.lat.data, ge... |
# Generated by Django 2.1.15 on 2020-04-03 20:49
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='NgoTable',
fields=[
('id', models.AutoFiel... |
print("(LabWork 2)Богатько Александр В2 ИПЗ-12")
print("Ведите первое число: ")
A = int(input())
print("Введите второе число: ")
B = int(input())
print("Введите третье число: ")
C = int(input())
if A>=1 and A<=3:
print("Ответ: " + str(A))
if B>=1 and B<=3:
print("Ответ: " + str(B))
if C>=1 and C<=3:
... |
import numpy
n,m = map(int,input().split())
arr = numpy.zeros((n,m),int)
for i in range(n):
arr[i] = numpy.array(input().split(),int)
print(numpy.prod(numpy.sum(arr, axis = 0))) |
import numpy as np
import cv2
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
'''
Cartesian plane starts from top left in open cv
(0,0) denotes top left corner of screen
move down: increase height
move right : increase width
'''
while True:
ret, frame = cap.read()
height = int(cap.get(4))
width = int(cap.get(3))
... |
from insuletchallenge import datasets
from insuletchallenge import models
from sklearn.model_selection import train_test_split
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Model
from tensorflow.keras.models import load_model
from tensorflow.keras.optimizers import Adam
from tensorflow.k... |
from io import BytesIO
import random
from flask import Response
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
@app.route('/plot.png')
def plot_png():
fig = create_figure()
output = BytesIO()
FigureCanvas(fig).print_png(output)
return Re... |
def average(arr):
new_list = set(arr)
total_numbers = len(new_list)
sum_number = sum(new_list)
average_number = sum_number / total_numbers
return average_number
n = int(input())
arr = list(map(int, input().split()))
result = average(arr)
print(result) |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2019-09-15 19:22
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('tv_shows_app', '0001_initial'),
]
operations = [
migrations.RenameModel(
... |
import numpy as np
from scipy.optimize import minimize
def slabr(n,n1,n2,d,freq_range):
r=((n1-n)/(n1+n)+(n-n2)/(n+n2)*np.exp(4*np.pi*1j*n*d/2.9979e8*freq_range))/(1+(n1-n)/(n1+n)*(n-n2)/(n+n2)*np.exp(4*np.pi*1j*n*d/2.9979e8*freq_range))
return r
def slabrr(n,r12,r23,d,freq):
r=((r12+r23*np.exp(4*np.pi*1... |
#Metar Bug
#Patrick Pragman
#Ciego Services
#January 31, 2018
#Flask App to watch for changes in the weather
from flask import Flask, render_template, request, jsonify
from metar import Metar
from get_metar import get_metar
from local_config import Path
app = Flask(__name__)
@app.route('/')
def index():
return r... |
# utf-8
# exercício 103
def ficha(name='<desconhecido>', score=0):
print(f'O jogador {name} fez {score} gol(s) no campeonato.')
# programa principal
n = str(input('Nome do jogador: '))
g = str(input('Número de Gols: '))
if g.isnumeric():
g = int(g)
else:
g = 0
if n.strip() == '':
ficha(score=g)
else... |
import turtle as t
def tp(x,y):
t.pu()
t.goto(x,y)
t.pd()
t.screensize(1920,1080,"black")
t.setup(1920,1080,0,0)
t.pensize(1)
t.speed(10)
t.pencolor("white")
tp(-300,300)
t.color('white','white')
t.begin_fill()
for i in range(4):
t.fd(600)
t.rt(90)
t.end_fill()
tp(-290,290)
t.color... |
import pandas as pd
data_file = r'data.csv'
data_df = pd.read_csv(data_file)
print data_df.shape # (484192, 15)
print data_df.columns
'''columns_names = [u'id', u'pickup_user_id', u'total_amount', u'pickup_user_address_id',
u'created_at.x', u'ki', u'cost_for_two', u'created_at.y',
u'driver_ass... |
import json
import logging
import os
import pathlib
import sys
from collections import OrderedDict
from datetime import datetime
import click
import humanfriendly
import pandas
__version__ = '1.1.5'
logger = logging.getLogger()
@click.group()
@click.option('--debug', is_flag=True)
@click.pass_context
def cli(ctx,... |
from django import template
from django.template import Library
register = template.Library()
@register.filter
def url_replace(request, field, value):
dict_ = request.GET.copy()
dict_[field] = value
return dict_.urlencode() |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2018-05-25 17:05
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('default', '0002_job'),
]
operations = [
migrations.RenameField(
model_nam... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .forms import UploadFileForm
from django.contrib import messages
from .models import Leaderboard
from .fileProcessor import handle_uploaded_file
def viewAll(request):
board=Leaderboard.objects.all()
return render(request, ... |
# Vocabulary
RESERVED_TOKENS = {'PAD': 0, 'UNK': 1}
RESERVED_ENTS = {'PAD': 0, 'UNK': 1}
RESERVED_ENT_TYPES = {'PAD': 0, 'UNK': 1}
RESERVED_RELS = {'PAD': 0, 'UNK': 1}
extra_vocab_tokens = ['alias', 'true', 'false', 'num', 'bool'] + \
['np', 'organization', 'date', 'number', 'misc', 'ordinal', 'duration', 'person... |
"""GLD module."""
import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize, special, stats
class GLD:
r"""Univariate Generalized Lambda Distribution class.
GLD is flexible family of continuous probability distributions with wide variety of shapes.
GLD has 4 parameters a... |
from hw2 import *
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('kodim04.png')
plt.imshow(img)
C = split(img, 16)
A, B, e_rel = compress(C, 50)
print(e_rel)
img2 = join(A @ B, 16, img.shape[1], img.shape[0])
print(relError(img, img2))
plt.figure()
plt.imshow(img2)
plt.show() |
from random import *
def new_game(n):
matrix = []
for i in range(n):
matrix.append([0] * n)
return matrix
def add_two(mat):
a=randint(0,len(mat)-1)
b=randint(0,len(mat)-1)
while(mat[a][b]!=0):
a=randint(0,len(mat)-1)
b=randint(0,len(mat)-1)
mat[a][b]=2
return mat... |
sounds = [{
"soundName": "A Bass",
"md5": "c04ebf21e5e19342fa1535e4efcdb43b.wav",
"sampleCount": 28160,
"rate": 22050,
"format": "",
"tags": [
"music",
"instruments",
"notes"
]
},
{
"soundName": "A E... |
# worker.py - master-slave parallelism support
#
# Copyright 2013 Facebook, Inc.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from i18n import _
import errno, os, signal, sys, threading, util
def countcpus():
'''try to cou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.