text stringlengths 8 6.05M |
|---|
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import KFold
from sklearn.model_selection import train_test_split
cancer = load_breast_cancer()
x_train, x_test, y_train, y_test = train_test_split(cancer.data, cancer.target, stratify = cancer.... |
class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
x1, y1 = points[0][0], points[0][1]
x2, y2 = points[1][0], points[1][1]
x3, y3 = points[2][0], points[2][1]
if (x1 == x2 and y1 == y2) or (x1 == x3 and y1 == y3) or (x2 == x3 and y2 == y3):
return Fa... |
'''
Created on Jul 20, 2012
@author: petrbouchal
'''
from BusinessPlans import *
#===============================================================================
# #===============================================================================
# # ADVANCED ANALYTICS 3: TIME SERIES
# #===============================... |
def backtracking(W, wt, val, n):
return 0 |
# Vehicles Pattern1(from W to S)
for i, veh in enumerate(self.vehicles_W_S):
# Check if there are vehicles ahead. If true, stop
if (veh.getPosition().x + veh.getSpeed().x, veh.getPosition().y + veh.getSpeed().y) in self.collision_check_W:
self.calculate_vehnum(i, veh.getP... |
#!/home/walker/anaconda3/bin/python3
#coding=utf-8
######################################################
# > File Name: train.py
# > Author: Yanming Ji
# > Mail: 1225401399@qq.com
# > Created Time: 2019ๅนด09ๆ06ๆฅ ๆๆไบ 14ๆถ56ๅ55็ง
# > Description: ่ฎญ็ปๆจกๅ
################################################... |
import unittest
from katas.kyu_6.weird_string_case import to_weird_case
class WeirdStringCaseTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(to_weird_case('This'), 'ThIs')
def test_equals_2(self):
self.assertEqual(to_weird_case('is'), 'Is')
def test_equals_3(self):
... |
"""cleanup
Revision ID: 9ca5901af374
Revises: a477f34dbaa4
Create Date: 2020-01-28 20:44:00.184324
"""
from alembic import op
import sqlalchemy as sa
import app.model_types
# revision identifiers, used by Alembic.
revision = '9ca5901af374'
down_revision = 'a477f34dbaa4'
branch_labels = None
depends_on = None
def ... |
NAMES = set()
TRANSFORMATIONS = set()
A = "transformations.txt"
B = "code_and_first_name_only.txt"
t = open(A, 'w')
n = open(B, 'w')
class Inside(): pass
class Outside(): pass
def switch(x):
if isinstance(x,Inside):
return Outside()
elif isinstance(x, Outside):
return Inside()
else:
exit("error")
f = ope... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
import os
AUTHOR = "Christopher D'Cunha"
SITENAME = "D'Cunha Matata"
SITEURL = ""
THEME = os.path.abspath("modules/theme")
DISPLAY_PAGES_ON_MENU = False
DEFAULT_PAGINATION = 10
TIMEZONE = "Europe/London"
DEFAULT_LANG = 'en'
FEED... |
import numpy as np
import matplotlib.pyplot as plt
import sys
import os
from mpl_toolkits.mplot3d import Axes3D
modes = [0, 1, 4]
figdir = "media/"
fig_filetype = "pdf"
if not sys.argv[1]:
print("Usage: python plot_eigenmode.py <path_to_data_dir>")
datadir = sys.argv[1]
figdir = os.path.join(datadir, figdir)
pri... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 27 06:31:12 2020
@author: Siddhi
"""
from random import seed
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
#Split dataset into training and testing set
def train_test_split(dataframe,split=0.70):
train_size = int(split * len(data... |
#!/usr/bin/python
import numpy as np
#Input parameters:
ofile='../data/LISA/LISA' #Output file for the data.
#-----------------------------------------------------------------
ifile1='../data/LISA/lisa.out' #I think it comes from: http://www.srl.caltech.edu/~shane/sensitivity/MakeCurve.html
ul1=np.array(np.loadtxt(i... |
from rest_framework import serializers
from app.models import Image
class ImageSerializer(serializers.ModelSerializer):
image = serializers.SerializerMethodField('serialize_image')
class Meta:
model = Image
fields = ('id', 'name', 'desc', 'image', 'created_at', 'updated_at')
def seriali... |
import numpy as np
def __discrete_unif_pdf(x, start, n_numbers):
# TODO ensure that only ints are passed here.
# TODO this should return 0 for any non integer number.
if x >= start and x <= start +n_numbers:
return 1/n_numbers
else:
return 0
_discrete_unif_pdf = np.vectorize(__discrete... |
from tensorflow.keras.layers import BatchNormalization, Conv2D, Activation, MaxPooling2D, ZeroPadding2D
from model.modules import conv_block, identity_block
def resnet_graph(input_image, architecture, stage5=False, train_bn=True):
"""Build a ResNet graph.
architecture: Can be resnet50 or resnet101
... |
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.externals import joblib
import gc
file_name_str = 'dt_mod_{}_{}_{}_{}.pkl'
gc.enable()
# df_train = pd.read_csv('Kaggle_Datasets/Facebook/train.csv')
# df_test = pd.read_csv('https://... |
from django.shortcuts import render
from django.http import HttpResponse, Http404, HttpResponseRedirect
from .models import Lecture, Question, Tag
from django.urls import reverse
from django.db import DatabaseError
from django.contrib import messages
from . import profanity
import re
# PEP8 OK
# 1 View for index pag... |
import json
path=r"C:\Users\ๅ่ฑ\Desktop\ๆฐๆฎ้ฉฑๅจ่ฏปๅjson.json"
m=open(path,"r")
a=m.read()
lis=json.loads("a")
|
from matplotlib import pyplot as plt
def plot(history, from_epoch = 0):
try:
acc = history.history['acc'][from_epoch:]
val_acc = history.history['val_acc'][from_epoch:]
# summarize history for accuracy
plt.plot(acc)
plt.plot(val_acc)
plt.title('model accura... |
""" Script to read the root files from positron simulation and saved their hittime distributions to txt file.
These hittime distributions can then be analyzed further with pulse_shape_analysis_v1.py as reference to the prompt
signal of IBD-like NC events (to compare hittime distributions of positrons and NC ev... |
inputs = [1.2,5.1,2.1]
weights = [3.1,2.1,8.7]
bias =3
output = inputs[0]*weights[0] + inputs[1]*weights[1] + inputs[2]*weights[2] +bias
print(output)
|
# -*- coding: utf-8 -*-
import itertools
class Solution:
def combine(self, n, k):
return [list(el) for el in itertools.combinations(range(1, n + 1), k)]
if __name__ == "__main__":
solution = Solution()
assert [
[1, 2],
[1, 3],
[1, 4],
[2, 3],
[2, 4],
... |
class Dispatcher(object):
def __init__(self, handlers=[]):
self.handlers = handlers
def handle_request(self, request):
for handle in self.handlers:
request = handle(request)
return request
def function_1(in_string):
print(in_string)
return "".join([x for x in in_st... |
from dataclasses import *
@dataclass
class TelephonBook:
name: str
mail: str
tel: str
remark: str
member: str
def load(new):
address = []
with open(r"C:\Users\admin\OneDrive\ใในใฏใใใ\python1\08\20k1026-07-address.txt", encoding="UTF8") as file:
for line in file:
info = li... |
from treadmill.infra.setup import base_provision
from treadmill.infra import configuration, constants, exceptions, connection
from treadmill.api import ipa
class LDAP(base_provision.BaseProvision):
def setup(
self,
image,
count,
key,
cidr_block,
... |
from django.db import models
from accounts.models import User
# Create your models here.
class Order(models.Model):
username = models.CharField(max_length=200,blank=True,null=True)
order_id = models.CharField(max_length=200,blank=True,null=True)
address = models.CharField(max_length=200,blank=True,n... |
# This file is part of beets.
# Copyright 2016, Blemjhoo Tezoulbr <baobab@heresiarch.info>.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitati... |
import logging
from django.urls import reverse
from django.contrib import admin
from django.db.models import Model
from django.db.models import CASCADE
from django.db.models import PROTECT
from django.db.models import Sum, Max
from django.db.models import CharField
from django.db.models import TextField
from django.db.... |
"""
mod_cmds.py
Created: March 13, 2019 by Mimi Sun
Purpose: cog with mod commands
"""
import discord
from discord.ext import commands
import typing
class Mod_cmds(commands.Cog):
def __init__(self, bot):
self.client = bot
#mass ban members
@commands.command(aliases=[])
@commands.has_... |
import os
from app import create_app, db
from app.models import User, Card, Notification, Task, Tag, Tagging
app = create_app()
@app.shell_context_processor
def make_shell_context():
request_ctx = app.test_request_context()
request_ctx.push()
return {
"db": db,
"User": User,
"Car... |
from PyTsetlinMachineCUDA.tm import RegressionTsetlinMachine
from PyTsetlinMachineCUDA.tools import Booleanizer
#from pyTsetlinMachineParallel.tm import RegressionTsetlinMachine
#from pyTsetlinMachineParallel.tools import Binarizer
import numpy as np
from time import time
from sklearn.model_selection import train_test... |
#Write a void function to draw a star, where the length of each side is 100 units. (Hint: You should turn the turtle
#by 144 degrees at each point.)
import turtle
paper = turtle.Screen()
leonardo = turtle.Turtle()
def draw_star(n):
"""
Draw star
:param n: length of side
:return:
"""
for i in... |
"""
Stack Class
Inherits from SLLIST (Single Linked List)
Supports operations: Push, Pop, Top, Length, Is_Empty
"""
from data_structure_and_algorithms import SingleLinkedList
class Stack:
def __init__(self):
"""
"""
self._linked_list = SingleLinkedList()
self._length = 0
def i... |
from __future__ import unicode_literals
# install django-multiselectfield
from multiselectfield import MultiSelectField
from django.db import models
# Status du drone. En recopiant les l'attribut system_status de l'objet vehicule cree
STATUS_drone = ((1, 'UNINIT'),
(2, 'BOOT'),
(3, 'CALIBRATING'... |
from enum import Enum
class Vulnerability:
def __init__(self, kind=None, description=None, transactions=None):
self.type = kind
self.description = description
self.transactions = transactions
self.tested = False
self.confirmed = False
def __str__(self):
return ... |
lb = int(input("enter lower boud: "))
ub = int(input("enter upper bound: "))
for n in range(lb,ub+1):
if n % 9 == 0 and n% 5!= 0:
print(n) |
class mysolution:
def copybook(self, data,k):
length = len(data)
for i in range(0, k):
return
way = mysolution()
data=(2,5,4,3)
k = 2
res = way.copybook(data,k)
#result(2,5) (4,3)
|
print("LETTER T HAS BEEN SUCCESSFULLY EXECUTED") |
from django.urls import path
from .views import stock_count_by_date, stock_count_by_person, stock_count_in_channel, channel_count_by_stock, person_count_by_stock
urlpatterns = [
path("count/date", stock_count_by_date, name="CountStockFromDate"),
path("count/sender", stock_count_by_person, name="CountStockByPer... |
class triangulo:
def __init__(self):
self.LadoA = None
self.LadoB = None
self.LadoC = None
def perim(self):
perim = self.LadoA + self.LadoB + self.LadoC
return perim
def getMaiorLado(self):
return self.__MaiorLado
def getArea(self):
return self.per... |
import os
import sys
# import imgaug # https://github.com/aleju/imgaug (pip3 install imgaug)
import time
# Import Mask RCNN
ROOT_DIR = os.path.abspath("../../")
sys.path.append(ROOT_DIR) # To find local version of the library
# Root directory of the project
from samples.coco.coco import CocoConfig, CocoDataset
from... |
from flask_wtf import FlaskForm
from wtforms import TextAreaField, SubmitField
from wtforms.validators import DataRequired, Length
class MessageForm(FlaskForm):
message = TextAreaField('Message', validators=[DataRequired(), Length(min=0, max=140)])
submit = SubmitField('Send')
|
# coding: utf-8
from flask_wtf import FlaskForm
from flask import session
from wtforms import StringField, PasswordField, SubmitField, SelectField, SelectMultipleField, TextAreaField
from wtforms.validators import DataRequired, ValidationError
from app.modles import User
record_type = [(0, 'A'), (1, 'NS'), (2, 'CNAME'... |
from ._layout import LayoutValidator
from ._data import DataValidator
|
import os
def get_query(query_file: str):
path = os.path.dirname(os.path.abspath(__file__))
graphql_file = os.path.join(path, query_file)
with open(graphql_file, 'r') as query_file:
query = query_file.read()
return query
comments_graphql_query = get_query('comments.graphql')
pull_request... |
# This is a helper module that contains conveniences to access the MS COCO
# dataset. You can modify at will. In fact, you will almost certainly have
# to, or implement otherwise.
# Limit GPU usage
from os import environ
print("Limiting gpu usage")
environ['CUDA_VISIBLE_DEVICES'] = '2'
import sys
# This is evil, fo... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
from cmath import phase
z=complex(input())
print(abs(z))
print(phase(z)) |
# Authentication with the old founder dating backend, to be used for transitioning.
# Validate the password with the old PHP method. If it passes, convert the user to
# a "new" account by changing the password to the django method.
#
# This always returns None, so the django method will be called next.
from django.co... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
df = pd.DataFrame({
'x': [1, 5, 7, 6.5, 9.5, 13.75, 17.15, 14, 12, 16],
'y':[3, 2, 4, 1.5, 6.25, 8.5, 11.25, 10.6, 8, 19.5]})
np.random.seed(20... |
def bmi():
# What is your height and weight?
# My height is 5 feet 11 inches
# I weigh about 180 pounds.
#Weight in lbs/ height in inches squared (703)
|
import tensorflow as tf
import numpy as np
import matplotlib
matplotlib.use('Agg')
from multiprocessing import Pool
from queue import Queue
from sklearn.model_selection import ParameterGrid
from sklearn import datasets
from sklearn.model_selection import train_test_split
from pandas import read_csv
from sklearn.prepro... |
from flask import Flask, request, make_response, render_template
from flask_restful import Resource, Api
import scraper
app = Flask(__name__)
api = Api(app)
class Home(Resource):
def get(self):
headers = {'Content-Type': 'text/html'}
return make_response(render_template('index.html', test = "TEST"... |
import re
import urllib.request
import pprint
pattern='title="(.+?)"'
data=urllib.request.urlopen('https://book.douban.com/publishers/').read().decode('utf-8')
res=re.compile(pattern).findall(str(data))
f=open('ๅบ็็คพไฟกๆฏ.txt','w')
for i in res:
try:
f.write(i+'\n')
print('%sๅๅ
ฅๆๅ ' % str(i))
except U... |
from safedelete.managers import SafeDeleteManager
class UnemploymentManager(SafeDeleteManager):
pass |
##encoding=utf-8
"""
Import Command
--------------
from archives.urlencoder import urlencoder
"""
import random
class UrlEncoder():
base_url = "http://www.archives.com/member/"
available_activity_id = [
"32d47e7f-1b40-44af-b6a1-93501b7c2a59",
]
def __init__(self):
self.birth_r... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class MovieTimeItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
# ๅฝฑ้ขๅ็งฐ
cinema_name = scrapy.Field... |
import math
import random
from game import Game
# Check how much of each win condition
# I occupy, and pick the one
# that looks the best
class OccupyBot:
def getMove(self, board, whichPlayerAmI):
winBoard = self.createWinBoard(board, whichPlayerAmI)
enemiesWinBoard = self.createWinBoard(board,... |
from .modelfactory import *
from .optim import *
from .trainer import *
from .evaluator import *
|
from django.contrib.auth.hashers import make_password
from django.contrib.auth.password_validation import validate_password
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
"""Serializes a user profile object"""
def create(... |
def mean(L):
S = 0
for x in L:
S += x
return S / len(L)
|
def myfunc(*args):
print(sum(args)*0.05)
myfunc(50,50) |
from __future__ import annotations
import sys
import click
from ai.backend.client.session import Session
from ai.backend.client.output.fields import agent_fields
from ..types import CLIContext
from . import admin
@admin.group()
def agent():
"""
Agent administration commands.
"""
@agent.command()
@cli... |
from tkinter import *
from tkinter.filedialog import askopenfilename
# from tkinter import ttk
from PIL import Image, ImageTk#import Image, ImageTk
calibUnitChoices = {
'um': 1e6,
'mm': 1e3,
'cm': 1e2,
'm': 1,
'km': 1e-3,
'in': 39.3701,
'ft': 3.28084,
'mi': 0.000621371,
}
def cali... |
from PIL import Image
import sys
print sys.argv
def check(palette, copy):
palette = sorted(Image.open(palette).convert('RGB').getdata())
copy = sorted(Image.open(copy).convert('RGB').getdata())
print 'Success' if copy == palette else 'Failed'
check('Goth.png', 'test.png') |
from fractions import Fraction
def reduce(fraction):
""" Shadows built-in name 'reduce' (forced by Codewars) """
f = Fraction(*fraction)
return [f.numerator, f.denominator]
|
# Copyright (C) 2020 THL A29 Limited, a Tencent company.
# All rights reserved.
# Licensed under the BSD 3-Clause License (the "License"); you may
# not use this file except in compliance with the License. You may
# obtain a copy of the License at
# https://opensource.org/licenses/BSD-3-Clause
# Unless required by appl... |
from .base import BaseEventTestCase
from graphql_relay import to_global_id
from django.db import transaction
from api.models import Interest
class InterestTestCase(BaseEventTestCase):
"""
Test interest queries
"""
def test_user_can_join_and_unjoin_category(self):
# Test for joining a categor... |
'''
Date:201211
Functionally about collect, clean and wrangling methods data.
'''
import pandas as pd
#DATAFRAME 1 - 6 BEST MARATHONS MAJORS
def checkingdata():
majors = pd.read_csv("/Users/ariadnapuigventos/Documents/CURSOS/BRIDGE/DS_Ejercicios_Python/BootCamp_TheBridge/Proyecto_Navidad_Ariadna/documentation/wor... |
import random
import numpy as np
import time, datetime
from collections import deque
import gym
import pylab
import sys
import pickle
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from tensorflow.python.framework import ops
ops.reset_default_graph()
import tensorflow as tf
from typing import List
env = gym.make('... |
#!/usr/bin/env python
import uproot
fname = '/Users/ploskon/data/HFtree_trains/13-06-2019/488_20190613-0256/unmerged/child_1/0001/AnalysisResults.root'
print('[i] reading from', fname)
file = uproot.open(fname)
print(file.keys)
all_ttrees = dict(file.allitems(filterclass=lambda cls: issubclass(cls, uproot.tree.TTreeM... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import logging
from dataclasses import dataclass
from pants.backend.kotlin.lint.ktlint.skip_field import SkipKtlintField
from pants.backend.kotlin.lint.ktlint.subsystem import KtlintSubsys... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 30 09:23:42 2013
@author: bejar
"""
import scipy.io
import numpy as np
from scipy import corrcoef
from sklearn.cluster import spectral_clustering,affinity_propagation
import matplotlib.pyplot as plt
from pylab import *
from sklearn.metrics import silhouette_score
from sk... |
# test adding comments to source
import marshaltools
# pick a test source
name = "ZTF19aabfyxn"
# load your program
prog = marshaltools.ProgramList("AMPEL Test", load_sources=True, load_candidates=False)
# try to post a message twice (should fail the second time)
prog.comment(name, "AMPEL test comment: to be posted ... |
import turtle
paper = turtle.Screen()
leo = turtle.Turtle()
paper.bgcolor("lightgreen")
leo.shape("arrow")
leo.color("pink")
leo.pensize(3)
def draw_star(n):
"""
Draw star
:param n: length of side
:return:
"""
for i in range (5):
leo.right(144)
leo.forward(n)
def draw_5_stars... |
import pytest
from enumerate_data import enumerate_names_countries
expected_lines = ['1. Julian Australia',
'2. Bob Spain',
'3. PyBites Global',
'4. Dante Argentina',
'5. Martin USA',
'6. Rodolfo ... |
#User function Template for python3
# Function to check if string
# starts and ends with 'gfg'
def gfg(a):
b = a.lower()
if((b.startswith('gfg') or b.startswith('GFG')) and b.endswith('gfg') or b.endswith('GFG')): # use b.startswith() and b.endswith()
print ("Yes")
else:
print ("No") |
import os
from win32com.client import Dispatch
def conectar_com():
CATIA = Dispatch('CATIA.Application')
CATIA.Visible = True
return CATIA
def crear_documento(nombre,objeto_com):
parte = objeto_com.Documents.Add('Part')
product1 = parte.GetItem("Part1")
product1.PartNumber = nombre
retur... |
# -*-coding=utf-8-*-
# @Time : 2020/1/1 0:08
# @File : trend.py
# ็ป่ฎกๅๅธ่ถๅฟ
import datetime
import numpy as np
import pymongo
import pandas as pd
from settings import send_aliyun,llogger
from config import QQ_MAIL
logger = llogger('log/trend_.log')
db = pymongo.MongoClient('192.168.10.48',17001)
doc= db['db_parker']['j... |
import pygame
from pygame import *
import sys
import random
import time
# window setup
win = pygame.Surface
WIDTH = 700
HEIGHT = 700
gameDisplay = pygame.display.set_mode((WIDTH,HEIGHT))
# song setup
pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load('... |
from datetime import datetime, timedelta
import json
from celery.decorators import task
from celery.utils.log import get_task_logger
from .fitbit_push import call_push_api
logger = get_task_logger(__name__)
@task(name="fitbit.store_health_data")
def store_fitbit_data(data):
'''
Celery task to store fitbit healt... |
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
longest = 0
currentSubStr = ''
for letter in s:
while(currentSubStr.find(letter) is not -1):
currentSubStr = currentSubStr[1:]
curre... |
import math
value = []
i = 1
while True:
z = int(input())
if z == -1: break
value.append(z)
for x in range(1,len(value)+1):
li = []
i = 1
li.append(value[x-1] / 2)
while True:
li.append(li[i-1] - ((li[i-1]**3 - value[x-1]) / (3 * li[i-1]**2)))
if math.fab(li[i]**3 - value[x-1]) < 0.00001*value[x-1... |
function [y,stop] = fcn(u1,u2)
persistent pathcount;
persistent pathlength;
persistent path; %error in code, initially used path but this is already a matlab function
persistent pathPre;
if isempty(pathcount)
pathcount=1;
pathPre=u2;
[pathlength,~]=size(pathPre);
path=[pathPre; pathPre(p... |
#!/usr/bin/python
import time
import json
DATA_FILE = "SenseHat.json"
CACHE_ALIVE = 5 # seconds
PRESSURE_OFFSET = 24.5 # = 206 m altitude
class SenseHat2(object):
def __init__(self):
self.data = None
self.humidity = None
self.tempH = None
self.pressure = None
self.tempP = None
self.m... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
class getsizeERRO(Exception):
pass
def get_file_size(file_name):
s = os.path.getsize(file_name)
if s == 0:
raise getsizeERRO('File Size value 0')
else :
return s
def save(file_name,data):
f = open(file_name, 'w')
... |
from tabulate import tabulate
from typing import List
class Table:
def __init__(self, header: List[str] = []):
self.header: List[str] = header
self.rows: List[List[str]] = []
self.style: str = "psql"
def set_header(self, header: List[str]):
self.header = header
def add_r... |
import torch
import hydra
import sys
from train import train, evaluate
from dataset import VQADataset
from models.base_model import VQAModel
from torch.utils.data import DataLoader
from utils import main_utils, train_utils
from utils.train_logger import TrainLogger
from omegaconf import DictConfig, OmegaConf
from tools... |
import finitefield
import truthtable
import primpoly
def DFT(array, dpoly):
""" Given an array of polynomials, maps it to its discrete fourier transform using as its nth root of unity the root of the primitive polynomial dpoly !!note that order of root must equal size of array!!
"""
f = []
uroo... |
from .login_attempt_record import LoginAttemptRecord
from .login_record import LogRecord
|
from flask import Flask, render_template, g, request
import re
import praw
import sqlite3
import os
app = Flask(__name__)
DATABASE = os.getcwd() + '\database.db'
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
return db
... |
# -*- coding: utf-8 -*-
__author__ = 'lish'
import io,MySQLdb
#import ImageDraw
from PIL import Image,ImageDraw
try:
# Python2
from urllib2 import urlopen
except ImportError:
# Python3
from urllib.request import urlopen
import requests
import hashlib
import base64
import sys,os,time,uuid
reload(sys)
sys.setdefa... |
from sqlalchemy.orm import sessionmaker
import creTable
Session_class = sessionmaker(bind=creTable.engine)
session = Session_class()
# b1 = creTable.Book(name = 'Python With Alex',pub_date='2014-05-02')
b2 = creTable.Book(name = 'C++ ็ฝ็ป็ผ็จ',pub_date='2014-05-02')
# b3 = creTable.Book(name = 'PHP With Alex',pub_date='... |
import time
from multiprocessing import Queue, Process
from bot import Bot
from helpers import load_configs
def start_bot(config, messages, id):
bot = Bot(config, messages, bot_id=id)
bot.resume()
while True:
bot.loop()
time.sleep(2)
def get_queue_and_start():
queue = ... |
"""AppConfig for stats."""
import collections
from django.apps import AppConfig
from django.utils.translation import gettext, gettext_lazy as _
GLOBAL_PARAMETERS_STRUCT = collections.OrderedDict([
("general", {
"label": _("General"),
"params": collections.OrderedDict([
("logfile", {
... |
# ๅ
ๆๅบ ๅ ๅๆบฏๅ ๅชๆไธไธ
class Solution:
res = []
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
n = len(candidates)
res = []
def backtrack(i, tmp_sum, tmp):
# if tmp_sum > target or i == n:
# retur... |
# -*- coding: utf-8 -*-
import requests
from architect.manager.client import BaseClient
from celery.utils.log import get_logger
logger = get_logger(__name__)
DEFAULT_RESOURCES = [
'spinnaker_account',
'spinnaker_application',
# 'spinnaker_artifact',
'spinnaker_pipeline_config',
'spinnaker_pipeli... |
import os
import pathlib
from tempfile import NamedTemporaryFile
import gzip
import re
import json
from itertools import groupby
from collections import Counter
from fabric.api import sudo, get
from fabric.contrib.files import exists
from fabtools import require
from appconfig.tasks import *
init()
def sql(app, sql... |
from ex1 import *
def choose_element_list(list_in_which_to_choose:list)->all:
nombre_de_la_liste_tirer = random.randint(0,len(list_in_which_to_choose))
nombre_retourner = list_in_which_to_choose[nombre_de_la_liste_tirer]
return nombre_retourner
liste_alea = gen_list_random_int()
print("LISTE DE BASE :",list... |
from flask import Blueprint
from flask import request
from flask import render_template
from flask_login import login_required
from .controller import Log
bp = Blueprint('loginfo', __name__)
@bp.route('/loginfo/search')
@login_required
def loginfo_search():
data = Log.find_by_condition()
return render_templa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.