text stringlengths 8 6.05M |
|---|
from django.shortcuts import render, HttpResponse
from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter
from rest_auth.registration.views import SocialLoginView
from django.contrib.auth.decorators import login_required
from ratelimit.decorators import ratelimit
# Create your views here.
clas... |
# Please Add Your HTTP Access Token (api_key) on line below
api_key="YOUR_API_KEY"
base_url="https://bank-apis.justinclicks.com/API/V1/IFSC/"
# Country code ( case sensitive ) in,us,au,ru,fr,gb
# Cateogires business,entertainment,general,health,science,sports,technology
import requests
from telegram import *
fr... |
import json
from datetime import datetime
from queue import Queue
import xlsxwriter
from pip._vendor.distlib.compat import raw_input
import requests
import threading
import time
import random
print("##########################")
print("##########################")
print("Script: Giuseppe Compare\n")
print("sito web: ht... |
def main():
sales_data = {}
f = open("sales_report.csv")
for line in f:
line = line.rstrip()
entries = line.split(",")
salesperson = entries[0]
melons = int(entries[2])
if salesperson in sales_data:
sales_data[salesperson] += 1
else:
... |
"""
"""
from spp_datapre import *
from sklearn import metrics
import datetime
from spp_finger_model import *
# torch.cuda.set_device(1)
# torch.cuda.set_device(1)
def train(trainArgs, models_path, model_name):
"""
args:
model : {object} model
lr : {floa... |
### this is a code naming keerti and manoj
print("keerthi")
print("manoj")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Simple Bot to reply to Telegram messages.
This program is dedicated to the public domain under the CC0 license.
This Bot uses the Updater class to handle the bot.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and register... |
import sys
from rosalind_utility import parse_fasta
def olap_graph(strings, k):
''' Create Overlap Graph
:param strings: DNA strings
:param k: suffix length
:return: adjacency list of Ok
'''
adj_list = []
for name, string in strings.items():
for name2, string2 in strings.items():
... |
#!/usr/bin/env python3
from lib.parser import parse
from lib.symbol_ID import toID
from lib.data_retrieval import retrieve
from lib.data_analysis import summarize
from lib.prettify import formatAndPrint
def main():
geneSymbols, toJSON = parse()
geneIDs = toID(geneSymbols)
symbolMap = {symbol: gID for sym... |
import requests
from re import match
from datetime import timedelta, datetime
from os.path import isfile, getsize
from json import loads
from collections import OrderedDict
def handleAPIResponse(statuscode: int) -> bool:
if statuscode == 204:
raise RateLimitError(statuscode)
elif statuscode == 400:
... |
# Importing required libraries, obviously
import streamlit as st
import cv2
from PIL import Image
import numpy as np
import os
st.set_option('deprecation.showfileUploaderEncoding', False)
# Loading pre-trained parameters for the cascade classifier
try:
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + ... |
'''
@title Test Suite: GameEngine Class
@author Carlos Barcelos
@date TODO
'''
import sys #
sys.path.append("..") # Adds higher directory to python modules path.
import json # Handle JSON files
import unittest # assert(actual, expected)
from src.Achievements import Achievements # Import the Achievements class
from s... |
# coding: utf-8
"""
Explore the sales data
"""
from os.path import join, exists
from collections import defaultdict
from pprint import pprint
import numpy as np
import pandas as pd
from datetime import timedelta
from utils import (save_json, load_json, ORDERS_NAME, ORDERS_LOCAL_PATH, DATA_DIR,
convert_categori... |
class Solution(object):
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 2:
return 0
maxnum, another = nums[0], nums[1]
index = 0
if maxnum < another:
maxnum, another = another, ma... |
'''
Created on 15 Apr 2016
@author: peterb
'''
from tornado import gen
from tornado.ioloop import IOLoop
from motor.motor_tornado import MotorClient
from spddo.mongo.control.context import Context
from spddo.mongo.control.login import login
from tornado.web import HTTPError
Context.mongo_client = MotorClient('mongod... |
from functools import wraps
from time import time, sleep
import threading
from multiprocessing import Process
def cal_time(func):
@wraps(func)
def wrapper():
start_time = time()
func()
end_time = time()
print("This func cost %fs" % (end_time - start_time))
return wrapper
... |
from django import forms
from django.contrib.auth.models import User
from .models import profile
class user_form (forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta :
model = User
fields = ('password','username' ,'email')
class profile_form (forms.ModelForm):
... |
#!/usr/bin/python3
"""Provides a function to insert text in a file after specific lines"""
def append_after(filename="", search_string="", new_string=""):
"""Insert text in a file after lines containing a specific string"""
with open(filename, 'r+') as iostream:
lines = [
line + new_string... |
import sys
sys.path.append("../")
import torch
import torch.nn as nn
import uuid as uid
import numpy as np
import torch.optim as optim
import torch.nn.functional as F
from utils.template import TemplateModel
from tensorboardX import SummaryWriter
from tqdm import tqdm
from TrainingBackBone.gen_data import get_loader
fr... |
national_ids = [1223, 3543, 5647, 6593, 1235, 9087]
dob = [str(_id)[:2] for _id in national_ids]
print(dob)
blood_types = ("A+", "A-", "B+", "B-", "O+", "O-", "AB+", "AB-")
print(blood_types)
evens = [4, 6, 8, 12]
print([num * 10 for num in evens])
names = ["nagah shaban", "john", "mohammed", "ali"]
to_upper = ... |
inputFile = open("output.txt","r")
sortedFile = open("sortedData.txt", "w")
lines = inputFile.readlines()
lines.sort()
for line in lines:
data = line.strip().split('\t')
if len(data) != 2:
continue
else:
sortedFile.write(line)
inputFile.close()
sortedFile.close()
|
from django.test import TestCase, Client
from django.urls import reverse
from django.http import Http404
from django.shortcuts import get_object_or_404
from products.models import ProductBrand, Product, ProductType
class TestProductsViews(TestCase):
def setUp(self):
self.client = Client()
self... |
import asyncio
from datetime import datetime
from importlib import reload
import os
from pytz import utc, timezone
import sqlite3
import sys
import yaml
import aionotify
from pydle import MinimalClient
import handler
def adapt_ts(dt):
return int(dt.timestamp())
def convert_ts(i):
dt = datetime.fromtimestamp... |
import re
import random
WORDS = ["DEGREES"]
def handle(text, mic, profile):
random_number = random.random()
random_degree = 24 + random_number
random_rounded_degree = round(random_degree,2)
mic.say("This room has a Temperature of %s degrees" % random_rounded_degree)
def isValid(text):
return bo... |
# RF로 모델링 하시오!!!
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split, KFold, cross_val_score, GridSearchCV, RandomizedSearchCV
from sklearn.decomposition import PCA
from sklearn.metrics import r2_score
from sklearn.ensemble... |
from rest_framework import viewsets
from api.banners.serializers import SiteBannerSerializer
from api.base import ShareViewSet
from api.pagination import CursorPagination
from share.models import SiteBanner
class SiteBannerViewSet(ShareViewSet, viewsets.ReadOnlyModelViewSet):
"""View showing all active site-wid... |
import random
from datetime import datetime
from tqdm import tqdm
from termcolor import colored
import timeit
import matplotlib.pyplot as plt
import numpy as np
def perform_walk(d_in, d_out, in_count, out_count) -> str:
## https://www.geeksforgeeks.org/hierholzers-algorithm-directed-graph/
## https://math.stac... |
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class BasePage:
def __init__(self, driver):
self.driver = driver
def do_click(self, by_locator):
WebDriver... |
class Activity:
NAME = None
"""str: Activity name
"""
def get_name(self):
"""Gets the activity name
Returns:
str: Name of the activity
"""
return self.NAME
class Run(Activity):
NAME = 'run'
class Walk(Activity):
NAME = 'walk'
|
def values(entry1,entry2):
entry1value = entry1
entry2value = entry2
print(entry1value)
print(entry2value)
from tkinter import *
import datetime
import modify
#from gtts import gTTS
#from playsound import playsound
allow = False
def main(entry1):
root = Tk()
date1 = entry1.get... |
#=========================================================================#
# Extracting features from images using a pretrained VQ-vAE model #
# Save the extracted features as FITS file for later use #
#=========================================================================#
import time
imp... |
# We have a table with employees and their salaries, however,
# some of the records are old and contain outdated salary information.
# Find the current salary of each employee assuming that salaries increase each year.
# Output their id, first name, last name, department ID, and current salary.
# Order your list by... |
from repo.RentalRepository import *
from repo.RepositoryException import *
import pickle
class PickleRentalRepository(RentalRepository):
def __init__(self,file="/home/bogdan/Documents/lab57/src/pickle_rentals.txt"):
super().__init__()
self.__file=file
self.__loadData()
de... |
import torch
import math
import numpy as np
def comp_ang(pred_n, gt_n):
"""
:param pred_n: (N, 3)
:param gt_n: (N, 3)
:return: a scalar, average angle between predicted normals and gt normals
"""
# for un-orient normal vector, it's fine if it's flipped, cos(theta) = -1 means correct... |
def removingLeadingZeros(num):
str_num = str(num)
nw_str = str_num
while nw_str[0] == 0:
nw_str = nw_str[1:]
return nw_str
print(removingLeadingZeros(0d 00002334))
def reverse(nm):
nm_str = str(nm)
rev_str = ''
ln = len(nm_str)-1
while ln >= 0:
rev_str += nm_str[ln]
... |
import os
import cv2
import time
def resize_images(images, new_size):
"""Resize a list of input images to a given new_size"""
return [cv2.resize(im, new_size) for im in images]
def read_directory_images(path, extension, n=None):
"""
Read images from a directory based on file extension
:param pat... |
# Strictly-Increasing-or-Decreasing
# -------------------------------------------------------------
def incre_decr(a, b, c):
if(a < b) and (b < c):
return "increasing"
elif(a > b) and (b > c):
return "decreasing"
else:
return "nither"
print(incre_decr(1,2,3))
# i = 0
# def check(array):
# for i in ... |
while True:
try:
#codigo
n = int(input())
cad = [int(x) for x in input().split()]
i = 1
while n > 0:
if not (i in cad):
print(i)
pass
n = n - 1
i = i + 1
except EOFError:
b... |
from simple_dispatch import subscriber, dispatch, dispatch_after, dispatch_before
from unittest import TestCase
class TestCases(TestCase):
def test_subscription(self):
"""
There are a few test functions defined. One that subscribes to event A. One that subscribes to event B, and
a third t... |
# --------
# Note
# --------
# kg <=> lbs inverter
# import math
# weight = float(input("type Your Weight: "))
#
# if math.isnan(weight):
# print('Not a vilate weight.(weight should be number)')
#
# else:
# unit = input("is it (L)lbs or (K)Kg: ").upper()
# if unit == 'L':
# print(f'{weight} lbs')
... |
import math
def print_matrix( matrix ):
s = "["
for i in range(len(matrix)):
s += "["
for j in range(len(matrix[i])):
s += str(matrix[i][j]) + " "
s = s[:-1]
s += "]\n"
print s[:-1] + "]"
def ident( matrix ):
matrix[:] = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, ... |
import numpy as np
import pandas as pd
%matplotlib inline
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.layers import Input, Embedding, LSTM, Activation, Dense, Conv1D, ... |
from prettyPrint import prettyPrint
from nltkCountWords import nltkCountWords
def commonWords(file1, file2):
dict1 = nltkCountWords(file1)
dict2 = nltkCountWords(file2)
dictionary = {}
for key in dict1:
if dict2.has_key(key):
dictionary[key] = min(dict1[key], dict2[key])
prettyPrint(dictionary)
return dict... |
import FWCore.ParameterSet.Config as cms
from Configuration.StandardSequences.FrontierConditions_GlobalTag_cff import *
GlobalTag.globaltag = "80X_dataRun2_HLT_v12"
|
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insert_back(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
... |
"""Utility functions for user management."""
from bcrypt import hashpw, gensalt
from flask import current_app as app
from app.extensions import db
from app.models.db import User
from app.utils.base import Return
def change_pw(email: str, pw: str) -> Return:
"""Change the user's password.
Args:
emai... |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 30 12:40:08 2018
@author: shams
"""
# importing libraries
import pandas as pd
import numpy as np
import numpy as np
import pandas as pd
from keras.preprocessing import sequence
from keras.models import load_model
from keras.layers import Dense, Input, LSTM
from keras.mo... |
from modules.evaluation import EvaluationFramework
from modules.metrics import metrics
from pyod.models.iforest import IForest
from pyod.models.lof import LOF
from pyod.models.knn import KNN
from pyod.models.pca import PCA
from pyod.models.ocsvm import OCSVM
from pyod.utils.utility import standardizer
import pandas a... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 6 17:01:21 2019
@author: nanokoper
"""
import math
import numpy as npimport
import matplotlib.pyplot as plt
from scipy import stats
from datetime import datetime
import numpy as np
def fibo(k = 70, m = 100):
count=0
a = 0 # x(n-1)
b = 1... |
#Returns the total nuber of a particular type of cell in a grid
def SumCellType(iGrid, TypeOfCell):
return sum(sum(iGrid == TypeOfCell))
# returns the position of the cell in the iRows*iCols matrix
def PointCoordinates(r, c, iRows, rankNum):
i = rankNum * iRows + r - 1
return (i, c)
#Dist... |
# Copyright 2011-2012 James McCauley
#
# 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 ... |
import cv2 as cv
def nothing(x):
pass
cv.namedWindow('Binary')
cv.createTrackbar('threshold', 'Binary', 0, 255, nothing)
cv.setTrackbarPos('threshold', 'Binary', 127)
img_color = cv.imread('../sample/ball.png', cv.IMREAD_COLOR)
img_gray = cv.cvtColor(img_color, cv.COLOR_BGR2GRAY)
while(True):
thre = cv.get... |
from app import db
class Customer(db.Model):
__tablename__ = 'customers'
id = db.Column(db.Integer, primary_key=True)
created = db.Column(db.DateTime)
# Seller Information
roller = db.Column(db.String(32))
closer = db.Column(db.String(32))
leadbase = db.Column(db.String(32))
service_r... |
for a in range(1,333):
for b in range(a,500):
c=1000-a-b
if a**2 + b**2 == c**2:
print(a,b,c)
print(a*b*c)
|
from rest_framework import serializers
from followers.models import Follower
class FollowerSerializer(serializers.ModelSerializer):
userTo = serializers.CharField(source='user_to.name', read_only=True)
userFrom = serializers.CharField(source='user_from.name', read_only=True)
class Meta:
model = Fol... |
# TODO: reformat this mess to a proper class
from ilovemhc import utils, define, wrappers
from path import Path
import numpy as np
import click
import logging
import subprocess
import prody
def prepare_models(pdb, prm, rtf, **kwargs):
pdb = Path(pdb)
outdir = pdb.dirname()
pdb_hsd = Path(pdb[:-4] + '_h... |
from django.conf.urls import url
from python_stripe_payment import views as application
urlpatterns = [
url(r'^$', application.main, name='index'),
url(r'^charges$', application.charges, name='charges')
]
|
import sys
sentence = input("Enter a sentence: ")
list1 = sentence.split(" ")
newList = []
def pyReverse():
for i in range(1, len(list1) +1):
newList.append(list1[len(list1) -i])
return " ".join(newList)
print(pyReverse())
|
import argparse
from .infer import blind_source_separation
parser = argparse.ArgumentParser("restore sound for each speaker")
parser.add_argument("-i", "--input_file", type=str, help="the mixed audio file")
parser.add_argument("-m", "--model_dir", type=str, help="the directory \
where the trained model is stored")
arg... |
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from .models import Card, Category, Deck
# Create your views here.
def homepage(request):
if request.user.is_authenticated:
return redirect ("li... |
# coding: utf-8
"""
There are two very different strong baselines currently in the kernels for this competition:
- An *LSTM* model, which uses a recurrent neural network to model state across each text, with no
feature engineering
- An *NB-SVM* inspired model, which uses a simple linear approach on top of naive ... |
# Generated by Django 2.2 on 2019-03-13 18:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wikiApp', '0003_auto_20190313_1548'),
]
operations = [
migrations.CreateModel(
name='relativeItemsModel',
fields=[
... |
a=300
b=400
c=400 # we have a starting point
while a**2 + b**2 != c**2: # while the numbers are not a pythagorean triple
if a**2 + b**2 > c**2: # if a and b are too high
a -=1 # subtract 1 from a
b -=1 # and 1 from b
c +=2 # but add 2 to c to keep the numbers' sum at 1000
if a**2 + ... |
import unittest
def find_rotation_point(words_array):
l=len(words_array)
if(l==0):
return
elif(l==1):
return 0
return rotate(words_array,0,l-1)
def rotate(words_array,low,high):
while(low<high):
mid=(low+high)//2
if (words_array[mid]<words_array[mid-1] ... |
#!/usr/bin/env python
"""
Problem 1: Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
# List Compression
sum([i for i in range(1000) if i%3==0 or... |
'''
Given a root of a BST and a key find the next element of the key in BST
'''
import math
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def nextElement(root, key):
nextElem = None
subtree = root
while subtree:
if key < subtree.val... |
from setuptools import setup
setup(name='Odoo',
version='8.0',
description='OpenShift deployment quickstart for Odoo',
author='Quoc Pham',
url='https://github.com/quocpp/odooTest',
)
|
#!/usr/bin/env python
#import libraries
import gtk
import gobject
import os
#import other python scripts
import plots
import schematic
import toolbar
import temporalwindow_dialog
import export_dialog
import propagator
import config
class Application:
def init_window(self):
self.window = gtk.Window... |
if __name__ == "__main__":
counter = 0;
while True:
True == True
False == False
print(counter)
counter += 1
|
#!/usr/bin/python
import matplotlib.pyplot as plt
from IPython import display
from IPython.display import clear_output
import pandas
import numpy as np
n_bins = 8
n_bins_angle = 10
cart_position_bins = pandas.cut([-2.4, 2.4], bins=n_bins, retbins=True)[1][1:-1]
pole_angle_bins = pandas.cut([-2, 2], bins=n_bins_angle,... |
import random
import os.path
import pygame
from pygame.locals import Rect, QUIT, KEYDOWN, K_RIGHT, K_LEFT, \
K_SPACE, K_ESCAPE, FULLSCREEN
from Alien import Alien
from Bomb import Bomb
from Explosion import Explosion
# from GameLevel import GameLevel
from Player import Player
from PlayerLives import PlayerLives
... |
# import unittest
# from db_results import ResultsDatabase
#
#
# class ResultsDatabaseTests(unittest):
#
# def __init__(self): |
'''
This code is intended to serve as a basic example for a pendulum disturbed by a trolley
'''
import warnings
warnings.simplefilter("ignore", UserWarning)
# import all appropriate modules
import numpy as np
from scipy.integrate import odeint
import si
import si_2mode
import Generate_Plots as genplt
import InputShap... |
import requests
import json
def send_data(data):
API_URL = "https://polimi-demo.partners.mia-platform.eu/geolocalization/trip"
data = json.dumps(data)
session = requests.Session()
session.headers.update({'Content-Type' : 'application/json'})
request = session.post(API_URL, data=data)
session... |
# import socket
#
# # 创建socket
# sk = socket.socket()
# address = ('127.0.0.1',8006) # 127.0.0.1 特殊的地址 可以代指本机地址
# sk.connect(address)
#
# data = sk.recv(1024) # 一次最大收1024字节 阻塞
# print(str(data,'utf-8'))
# sk.close()
# 小虎
import socket
sk = socket.socket()
address = ('127.0.0.1',8006)
sk.connect(address)
while Tru... |
#!/usr/bin/python
class priorityQueue:
def __init__(self,M):
self.N = 0
self.MAX = M
self.a = [0]*M
def insert(self,i):
self.N = self.N + 1
if(self.N >= self.MAX):
raise Exception("Would exceed size of array")
self.a[self.N] = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
There's several code patterns for exception handling.
"""
def divide1(a, b):
"""Manually exam to avoid error.
"""
if b == 0:
raise ValueError("Zero division Error!")
return a * 1.0 / b
def divide2(a, b):
"""use ``try... except PossibleEx... |
import os
import shutil
# from datetime import datetime
import tensorflow as tf
import numpy as np
from utils import Dataset
class BinaryNNetMF:
def __init__(self):
"""
Base class for binary link prediction. This variant considers a square link matrix, where rows and columns
correspond to... |
import logging
import re
import pandas as pd
import numpy as np
from lightgbm.callback import _format_eval_result
import torch
from torch.utils.data import Dataset, DataLoader
def update_tracking(model_id, field, value, csv_file='logs/history.csv',
integer=False, digits=None):
try:
d... |
import os
import sys
import pytest
import pytorch_lightning
import torch
from src.nn.binarized_linear import BinarizedLinear
@pytest.fixture(scope="module")
def fix_seed():
pytorch_lightning.seed_everything(777)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
forward_t... |
import unittest
def matching_parens(num):
"""Returns a set of all num pairs of mataching parens."""
out = set()
_build_parens(out, 0, 0, num, '')
return out
def _build_parens(_set, left, right, num, _str):
"""Build parens matching string position after position.
Each position can be '(' ... |
# -*- encoding: utf-8 -*-
from app.home import blueprint
from flask import render_template, redirect, url_for, request
from flask_login import login_required, current_user
from app import login_manager
from jinja2 import TemplateNotFound
from flask import make_response, send_file
import os
import pandas as pd
import n... |
# You are given an array (zero indexed) of N non-negative integers, A0, A1 ,…, AN-1.
# Find the minimum sub array Al, Al+1 ,…, Ar so if we sort(in ascending order) that sub array, then the whole array should get sorted.
# If A is already sorted, output -1.
# Example :
# Input 1:
# A = [1, 3, 2, 4, 5]
# Return: [1,... |
'''lanche = ('Hamburguer', 'Suco', 'Pizza', 'Pudim')
print(lanche[1:3])'''
'''lanche = ('Hamburguer', 'Suco', 'Pizza', 'Pudim')
print(len(lanche))#quantidade de varíáveis com o len'''
'''lanche = ('Hamburguer', 'Suco', 'Pizza', 'Pudim')
for comida in lanche:
print(f'Eu vou comer um {comida}')'''
'''lanch... |
#!/usr/bin/env python
# -*-coding:utf-8 -*-
# Author:Renkai
list1 = [1, 99, 23, 45, 100, 0, 678]
# print(dir(list1))
# list1.append(999)
# list1.insert(0,999)
# print(list1)
list2 = list1.copy()
print(list2)
print(list1.count(100))
print(list1.index(100))
# list1.remove(100)
# print(list1)
# ele = list1.pop()
# p... |
class NPyParser():
def __init__(self, str2parse):
self.RAW = str2parse
self.GRAM = ''
self.TERMS = []
self.NONTS = []
def Tokenize(self):
pass
def GenTokens(self, STR):
pass
class PyTRANla... |
'''
from keras.layers.core import *
# Model is a NN.
model = Sequential()
model.add(Dense(dim = 128)) # Number of input neurons?
# What is the function used on each neuron
model.add(Activation('softmax'))
# Optimization - chose GD for you
'''
# Testing with numpy.
import numpy as np
# Avoid for loops!!! Chan... |
from rest_framework import serializers
from kratos.apps.trigger import models
class TriggerRecordSerializer(serializers.ModelSerializer):
class Meta:
model = models.TriggerRecord
fields = ('id', 'project', 'oper', 'version', 'branch', 'issuekey', 'created_at', 'updated_at')
|
# Generated by Django 3.2.4 on 2021-06-30 02:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('appwed', '0004_auto_20210630_0859'),
]
operations = [
migrations.AddField(
model_name='netxgen',
name='Day',
... |
from django.urls import path
from pic import views
app_name = 'pic'
urlpatterns = [
path('site/logo/<str:name>/', views.site_logo, name='site-logo'),
path(
'template/logo/<str:site_name>/<str:template_name>/',
views.template_logo, name='template-logo'
),
path(
'template/field/<... |
from django.db import models
import os
# Create your models here.
class SeccionNoticia(models.Model):
seccion = models.CharField('Seccion', max_length=20)
descripcion = models.CharField('Descripcion', max_length=75, null=True, blank=True)
menu = models.BooleanField(default=False, verbose_name='Va en el me... |
# Generated by Django 3.1.4 on 2021-01-21 15:18
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='StoreInf... |
from django.db import models
from django.contrib.auth.models import User
from .validators import validar_cedula
# Create your models here.
class Competencia(models.Model):
description = models.CharField(max_length=100)
estado = models.BooleanField(default=True)
def __str__(self):
return self.description
... |
import tensorflow as tf
import numpy as np
from matplotlib import pyplot as plt
import cv2
%matplotlib inline
from tf_explain.core.activations import ExtractActivations
def apply_grey_patch(image, top_left_x, top_left_y, patch_size):
patched_image = np.array(image, copy=True)
patched_image[top_left_y:top_lef... |
# Copyright PA Knowledge Ltd 2021
# For licence terms see LICENCE.md file
import construct
class VerifyControlHeader:
@staticmethod
def validate(frame):
return VerifyControlHeader._check_valid_control_header(frame) and \
VerifyControlHeader._check_EOF(frame) and \
VerifyContro... |
#Using pandas is not cheating right
import pandas as pd
dirt = r'C:\Python\Rosalind\Degree_Array\rosalind_deg.txt'
foo = open(dirt, 'r')
data = foo.readlines()
num_list = []
#Skip first line of data
iter_data = iter(data)
next(iter_data)
#Adds every number to a list
for item in iter_data:
num = item.split()
... |
import hashlib
import logging
import threading
import requests as req_sender
from flask import Flask, request # import main Flask class and request object
from pteromyini.lib.design_pattern.observer import Event
class Server:
def __init__(self):
self.log = logging.getLogger(__name__)
... |
from django.urls import path,re_path
from . import views
from django.conf.urls import url #導入url套件
app_name='myapp'
urlpatterns = [
path('', views.index, name="index"),
path('index/', views.index, name="index"),
re_path('^ajax/ajax_index_Img/$', views.ajax_index_Img, name="ajax_index_Img"),
]
|
"""Advent of Code Day 24 - Electromagnetic Moat"""
def extend(join, unused, strength, length):
"""Try to extend a bridge by adding an unused, matching part to it."""
info.append((strength, length))
for to_try in unused:
if join in to_try:
updated_unused = [part for part in unused if pa... |
#import sys
#input = sys.stdin.readline
Q = 10**9+7
# def getInv(N):#Qはmod
# inv = [0] * (N + 1)
# inv[0] = 1
# inv[1] = 1
# for i in range(2, N + 1):
# inv[i] = (-(Q // i) * inv[Q%i]) % Q
# return inv
def main():
N, K = map( int, input().split())
if K == 1:
print(0)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.