text stringlengths 8 6.05M |
|---|
"""
BicycleGAN
----------
Implements the BicycleGAN[1], a combination of the VAEGAN and the LRGAN.
It utilizes both steps of the Variational Autoencoder (Kullback-Leibler Loss) and uses the same
encoder architecture for the latent regression of generated images.
Losses:
- Generator: Binary cross-entropy + L1-late... |
from collections import defaultdict
import pandas as pd
# Local imports
from database import Connection
from database import db_logging as db
from utilities import directories as dr
from utilities import utils
from meeting import DividerMeeting
def add_to_db(mtg, session=None):
"""
Wrapper to add a Meeting ... |
'''
@author : Anish Lakkapragada
@date : 1 - 7 - 2021
This utils module is for all the "other stuff" used in ML. Here we provide a function to plot a confusion matrix,
a one-hot encoder, and a reverse one-hot encoder too.
'''
import numpy as np
import pandas as pd
def confusion_matrix(y_pred, y_test, plot=True):
... |
# Generated by Django 3.0.7 on 2020-10-12 07:54
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cl_table', '0042_auto_20201011_1718'),
]
operations = [
migrations.RemoveField(
model_name='stock',
name='equipmentcost',
... |
from django import forms
from .models import Zak
class ZakForm(forms.ModelForm):
class Meta:
model = Zak
fields = ["task","amount"]
class PayForm(forms.ModelForm):
class Meta:
model = Zak
fields = ["task","amount"] |
#Input
print("Enter your array")
array = list(map(int, input().split()))
n = len(array)
#Sorting
for i in range(0,n):
s = i #Smallest element currently
c = i #Position where next smallest element needs to be inserted
for j in range(s+1, n):
if array[j] < array[s]:
s... |
import fnmatch
import string
class Match:
ACCEPT=1
REJECT=2
UNKNOWN=3
class PathFilter(object):
class Rule(object):
def __init__(self, pattern, match_action):
assert match_action in (Match.ACCEPT, Match.REJECT)
self.pattern = pattern
self.match_action = mat... |
class HardCodedClassifier:
def __init__(self):
""" This is a classifier that isn't all that great, it always returns '1' (for the first kind of flower)
At this point it's just an excuse for a function """
def train(self, data):
return 1
def predict(self, data):
return 1
... |
#!/usr/bin/python
#coding:utf-8
import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
import tensorflow as tf
sess = tf.InteractiveSession()
#构建Graph
#构建输入占位符,标签占位符,x是输入,y_是正确的输出
x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])
#构建单层网络基本参数... |
def isWhiteLine(str):
if(str.split()==[]):
return True
return False
for line in open('Amit.txt'):
if not isWhiteLine(line):
print line
|
from bisect import bisect
N = int(input())
X = list(map(int,input().split()))
NX = sorted(X)
a = NX[int(N/2)]
b = NX[int((N-2)/2)]
for i in range(N):
if bisect(NX,X[i]) <= N/2:
print(a)
else:
print(b)
|
#!/usr/bin/python
#import tf
import rostf
import math
import numpy as np
import numpy.linalg as la
def YZXEulerFromQuaternion(q):
#return rostf.euler_from_quaternion(q, axes='syzx')
return rostf.euler_from_quaternion(q, axes='ryzx')
def QFromAxisAngle(axis,angle):
axis= axis / la.norm(axis)
return rostf.quat... |
from django.conf.urls import url
from .views import UserSettingsListView
urlpatterns = [
url(r'^$',
UserSettingsListView.as_view(),
name='list-all-my-settings')
]
|
# -*- coding: utf-8 -*-
# This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt)
# Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016
import os
import shutil
import tempfile
from unittest import TestCase
from mock import patch
from tsfresh.scripts import ... |
import turtle
import time
'''
t = turtle.Turtle()
#t.hideturtle()
def drawRectangle(t,x,y,w,h,colorP = "black"):
t.fillcolor("blue")
t.begin_fill()
t.pencolor(colorP)
t.up()
t.goto(x,y)
t.down()
t.goto(x+w,y)
t.goto(x+w,y+h)
t.goto(x,y+h)
t.goto(x,y)
t.end_fill()
drawRectangle(t,0,0,40,80)
def drawDot(t,x,y... |
# Generated by Django 2.2.9 on 2020-02-15 02:15
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... |
from django.contrib.auth import get_user_model
from django.db import models
User = get_user_model()
class Customer(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.CharField(max_length=100)
city_born = models.CharField(max_length=5... |
# ----------------------------------------------------------------------------
# Copyright 2014 Nervana Systems Inc.
# 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.o... |
import gym
from gym import error, spaces, utils
from gym.utils import seeding
import glob
import os
import random
import math
import pandas as pd
import numpy as np
class StocksEnv(gym.Env):
metadata = {'render.modes': ['human']}
def __init__(self, datadir):
self.comission = 0.25 / 100.
se... |
from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
from .forms import *
class Index(View):
template_name = 'color.html'
form_class = ColorForm
def get(self, request):
# <view logic>
return render(request, self.template_name, {'form': sel... |
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.svm import LinearSVC
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.multiclass import OneVsRestClassifier
import csv, random
import nltk
from sklearn.metrics impor... |
integer_number = 58746
i = len(str(integer_number))
# print(i)
while i>0:
print(integer_number//(10**(i-1)))
integer_number = integer_number%(10**(i-1))
i -= 1
|
KBH_NEIGHBORHOODS = {
'1': 'Indre By',
'2': 'Østerbro',
'3': 'Nørrebro',
'4': 'Vesterbro/Kgs. Enghave',
'5': 'Valby',
'6': 'Vanløse',
'7': 'Brønshøj-Husum',
'8': 'Bispebjerg',
'9': 'Amager Øst',
'10': 'Amager Vest',
'99': 'Udenfor inddeling'
}
COUNTRY_CODES = {
'0': 'Uop... |
import pandas as pd
def load_generic(path, trailing_space=False, columns=None):
"""
Load a generic Avida-style data file.
:param path: the path to the data file
:param trailing_space: is there a trailing space at the end of each line?
:param columns: the names of the columns
:return: a Pand... |
from blog.serializers import BlogSerializer, UserSerializer, LoginSerializer, RegisterSerializer
from .models import Blog
# from rest_framework.views import APIView
from rest_framework import response
from rest_framework import viewsets
from rest_framework.authentication import SessionAuthentication, BasicAuthenticatio... |
from django.db import models
# Create your models here.
class Areas(models.Model):
name=models.CharField(max_length=50,verbose_name='location')
pid=models.ForeignKey('self',on_delete=models.SET_NULL,related_name='addinfos',null=True)
class Meta:
db_table='areas'
def __str__(self):
re... |
#!python
# Copyright (c) 2000-2021 HVR Software bv
################################################################################
#
# NAME
# hvrskeletonagent.py
#
# SYNOPSIS
# as agent
# python hvrskeletonagent.py mode loc chn
#
# DESCRIPTION
# < description >
#
# OPTIONS
#
# AGE... |
from legislators_pudding import leg
from legislators2 import names
for name in names:
for rep, bio_id in leg:
if all(x in rep for x in name.replace("-"," ").split(" ")):
print(f"{bio_id}")
break
|
# coding: utf-8
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plot
from mpl_toolkits.mplot3d import Axes3D
# --- 線形回帰(単特徴) ---
# ある都市に出店するか否かの判断する為
# 人口(x)から利益(y)を予測する
# データセットはそれぞれ10000で割ったfloat。x/=10000 y/=10000
def plot_data(X, y):
plot.plot(X, y, 'rx', markersize=... |
from django import forms
from . import models
class CreateArticle(forms.ModelForm):
class Meta:
model = models.Article
fields = ['Nombre','Imagen','Leyenda','Precio']
class CreateOrder(forms.ModelForm):
class Meta:
model = models.Order
fields = ['Articulos']
|
# import the api
import api
tokens = api.fullLogin()
print(api.getProfileId(tokens[0]))
def onmessage(message, profileid, _type):
#returns taps
if(_type == "tap"):
print(profileid + " tapped you. returning tap")
socket.tap(profileid, 0)
socket = api.messageSocket(tokens, onmessage)
socket.sta... |
from flask import Flask, request, make_response
from flask_cors import CORS
from urllib import parse
app = Flask(__name__);
CORS(app, resources=r'/*')
@app.route("/", methods=['POST'])
def hello_world():
reqData = str(request.data).strip("b'");
reqData = reqData.split("&");
dic = {};
for x in reqData:
x = parse... |
import os
import csv
def f(x):
return x + 3
z = f(2)
if z == 5:
print("z равно 5")
else:
print("z не равно 5")
# без ввода параметров
def z():
return 59 + 10
print(z())
# Принимает больше одного параметра
def sisi(a, b, c, d):
return a + b + (c * d)
k = 2
v = 5
n = 8
m = 4
print(sisi(... |
from client import Client
from server import Server
IP = '127.0.0.1'
PORT = 1342
def start_server():
server = Server(IP, PORT)
server.start()
def start_client():
client = Client(IP, PORT)
client.start()
def main():
while True:
print('[1] Server')
print('[2] Client')
ch... |
import streamlit as st
import pandas as pd
import re
import numpy as np
import pickle
import os
html_temp = """
<div style="background:#025246 ;padding:10px">
<h2 style="color:white;text-align:center;"> Arac Fiyat Tahmin Uygulaması</h2>
</div>
"""
page11 =st.sidebar.radio("Sayfalar", ("Fırsatlar","Arac ... |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import numpy as np
ext_modules = [
Extension("word2vec.word2vec_c", ["./word2vec/word2vec_c.pyx"]),
Extension("word2vec.model_c", ["./word2vec/model_c.pyx"]),
Extension("word2vec.data.dataset_c", [... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2019-12-09 04:16
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('web', '0014_auto_20191206_0846'),
]
operations = [... |
import sesion2_6 as ml
variable = ml.mi_funcion(9)
print variable
variable2 = ml.tabla_de_mutiplicar(1,2)
print variable2 |
from cipher_yc4021 import cipher_yc4021
import pytest
def cipher(text, shift, encrypt=True):
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
new_text = ''
for c in text:
index = alphabet.find(c)
if index == -1:
new_text += c
else:
new_index =... |
import os
import sys
from django.apps import apps
from django.utils import lru_cache
from django.utils import six
@lru_cache.lru_cache()
def get_app_template_dirs(dirname):
"""
Return an iterable of paths of directories to load app templates from.
dirname is the name of the subdirectory containing templ... |
charname = chr(int(input('Please input a number of chr: ')))
filename = input('Please input the filename: ')
f = open(filename,'r')
num = 0
lines = f.readlines()
for line in lines:
for ch in line:
if ch == charname:
num += 1
else:
pass
print(num) |
import timeit
import pandas as pd
import numpy as np
import multiprocessing
from multiprocessing import Process, Manager, Value, Array, Lock
from ctypes import c_char_p
from itertools import islice
manager = Manager()
linhas = list()
dicionario = manager.dict()#Array(c_char_p, 80)
ocorrencias = manager.dict()#Arr... |
#!/usr/bin/env python3
#******************************************************************************
#
#"Distribution A: Approved for public release; distribution unlimited. OPSEC #4046"
#
#PROJECT: DDR
#
# PACKAGE :
# ORIGINAL AUTHOR :
# MODIFIED DATE :
# MODIFIED BY :
# REVISION :
#
# Copyrigh... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def create_llist(l):
"""
正序创建链表
"""
head = now_node = None
for value in l:
new_node = ListNode(value)
if not now_node:
head = now_node = new_node
else:
... |
from selenium import webdriver
import time
from pprint import pprint
from selenium.webdriver.common.keys import Keys
from collections import Counter
import time
driver = webdriver.Chrome('chromedriver') #exe 생략 가능
driver.get("http://zzzscore.com/color/")
driver.implicitly_wait(300)
btns = driver.find_elements_by_xpa... |
# hello.py
import tensorflow as tf
import multiprocessing as mp
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
core_num = mp.cpu_count()
config = tf.ConfigProto(
inter_op_parallelism_threads=core_num,
intra_op_parallelism_threads=core_num )
sess = tf.Se... |
# run from (main) directory containing
# code, images and text folders
import re, HTMLParser, operator
parser = HTMLParser.HTMLParser()
filename = 'image0_optimistic'
sample_tab = " "
# hocr output conversion
res = [] # distance, code
with open('text/misc/'+filename+'.hocr') as hocr_output:
for line in hocr_outpu... |
#!/usr/bin/env python
from scipy.sparse import coo_matrix, csr_matrix, diags
import numpy as np
import math
from sklearn.utils.extmath import safe_sparse_dot
from base import nnz_csrrow, LTRBase
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def dsigmoid_from_pred(pred):
return pred * (1-pred)
def dsigmoid(x):... |
# Generated by Django 3.0.7 on 2020-11-07 06:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cl_app', '0012_delete_tempuomprice'),
]
operations = [
migrations.CreateModel(
name='VoidReason',
fields=[
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import os
import re
from tensorflow.python.platform import gfile
# Define special symbols
_PAD = b"PAD"
_GO = b"GO"
_EOS = b"EOS"
_UNK = b"UNK"
_START_VOCAB = [_PAD, _GO, _EOS, _UNK]
PAD_ID = 0... |
"""empty message
Revision ID: bf8a1557b052
Revises: 57153c1a89e3
Create Date: 2016-07-29 15:11:10.948199
"""
# revision identifiers, used by Alembic.
revision = 'bf8a1557b052'
down_revision = '57153c1a89e3'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... |
import unittest, os
from keyvaluestorage import KeyValueStorage
class KeyValueStorageCase( unittest.TestCase ):
def setUp(self):
self.filename = 'testKeyValueStorageData2.txt'
if os.path.isfile(self.filename):
os.remove(self.filename)
def testFileIsExist(self):
storage = K... |
import random
import generate_private_public
from elsig_hash import egGen
import RSA
Bob_id = 0
Alice_key = tuple()
Alice_id = 0
bob_n = 0
bob_e = 0
signed_m = ""
def key_id_Generation():
global Alice_id
Alice_id = random.randint(1000001, 10000000)
# to be from other ranges generated in cert (to be uniqu... |
import sys
class BathroomCoder(object):
DIRS = {
'U': (0, -1),
'D': (0, 1),
'R': (1, 0),
'L': (-1, 0),
}
def __init__(self, matrix, x, y):
self.matrix = matrix
self.x = x
self.y = y
def move(self, direction):
instruction = self.DIRS[dir... |
def solution(total_lambs):
return max_henchmen_when_stingy(total_lambs) - max_henchmen_when_generous(total_lambs)
def max_henchmen_when_generous(total_lambs):
curr_cost = 1
henchmen = []
while total_lambs >= curr_cost:
total_lambs -= curr_cost
henchmen.append(curr_cost)
curr_co... |
# Generated by Django 2.0.7 on 2018-07-13 09:25
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Plate',
fields=[
('id', models.AutoField(au... |
import glob
import os
import eyed3
path = "E:/Dom/Music/Music/**"
for file in glob.glob(path, recursive=True):
if file[len(file) - 4:] == ".mp3":
file = file.replace("\\", "/")
audio = eyed3.load(file)
trackno = audio.tag.track_num[0]
title = audio.tag.title
... |
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import json
import argparse
import logging
import fnmatch
import rethinkdb
LOG = logging.getLogger('shotgunCache')
SCRIPT_DIR = os.path.dirname(__file__)
DEFAULT_CONFIG_PATH = '~/shotguncache'
CONFIG_PATH_ENV_KEY = 'SHOTGUN_CACHE_CONFIG... |
#!/usr/bin/python
#coding:utf-8
import os
import yaml
import click
import config
import logging
from tempfile import NamedTemporaryFile
from utils.helper import get_ssh, get_address, output_logs, scp_file
from utils.tools import activate_service, scp_template_file
logger = logging.getLogger(__name__)
@click.argumen... |
print(Hello Ritik)
|
from selenium import webdriver
import assistant_speaks as ass
def find_web(text):
driver = webdriver.Firefox(executable_path="/home/neosoft/Ankit/Voice-Assistant-in-Python-master/geckodriver"
)
driver.implicitly_wait(1)
driver.maximize_window()
if 'youtube' in text.lower... |
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None:
return False
visited = {}
while head.next != None:
try:
temp = visited[head.next]
return True
... |
import torch
from .base_model import BaseModel
from .L_model import LModel
from utils import eval_utils
from . import model_utils
class GCNetModel(LModel):
@staticmethod
def modify_commandline_options(parser, is_train=True):
parser.add_argument('--L_Net1_name', default='L_Net') # specify the name of... |
# Sinusoidal function fitter.
#
# Copyright (C) 2010-2011 Huang Xin
#
# See LICENSE.TXT that came with this file.
from __future__ import division
import numpy as np
from mpfit import mpfit
def onedsinusoid(x,H,A,omega,phi):
"""
Returns a 1-dimensional sinusoid of form
H+A*np.sin(omega*x+phi)
"""
... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
'''
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequen... |
# 给定一个二维数组, 沿对角线遍历这个矩阵. 一开始没有考虑
# 边界条件, 只是把所有可能的遍历一遍, 但是一旦给出一个很
# 长的一维向量就会很浪费时间, 然后优化了一下将 i 和 j
# 的起始值修改, 边界条件检查更加严格
class Solution:
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if matrix == []:
return []
M... |
#! usr/bin/python3
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def lnprint(self):
l = []
while self is not None:
l.append(self.val)
self = self.next
print(l)
|
from Calculation import summation as sum
from Calculation import multiplication
n1 = int(input("Enter the first number: "))
n2 = int(input("Enter the second number: "))
print("Product = ", multiplication(n1, n2))
n1 = int(input("Enter the first number: "))
n2 = int(input("Enter the second number: "))
print("Sum = ", s... |
from djstripe.models import Product, Plan
from rest_framework import serializers
from apps.subscriptions.helpers import get_friendly_currency_amount
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('id', 'name')
class PlanSerializer(serializers.ModelS... |
"""Twente spelling correction list ingestion."""
import os.path
import logging
import re
import pandas as pd
from ..dbutils import add_lexicon_with_links, session_scope
LOGGER = logging.getLogger(__name__)
def parse_line(line):
"""Extract wordform and corrections from line of Twente spelling correction list fil... |
import warnings
import pandas as pd
import lightgbm as lgb
warnings.filterwarnings('ignore')
from xgboost.sklearn import XGBClassifier
from catboost import CatBoostClassifier
from sklearn.linear_model import LogisticRegression
print('Load Data...............')
df = pd.read_csv("x_train_cat.csv")
test =... |
# Copyright (c) 2018 Javier M. Mellid <jmunhoz@igalia.com>
#
# 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 limitation the rights
# to use, copy, modif... |
from decimal import Decimal
class GpsKalman(object):
def __init__(self):
self.variance = Decimal('-1')
self.longitude, self.latitude = None, None
self.time_stamp = None
self.accuracy = None
def set_state(self, coordinate: str, time_stamp: float, accuracy: Decimal):
sel... |
from pathlib import Path
from PIL import Image
from .objects.color import Color
from .objects.country import Country
from .objects.flag_cube import FlagCube
from .objects.stylized_flag import StylizedFlag
IMAGE_MAX_SIZE = 96
NUMBER_OF_PIXELS_BETWEEN_TWO_CUBES = 32
DISTANCE_BETWEEN_TWO_CUBES = 28
class CountryLoade... |
from django.db import models
class adVisit(models.Model):
device_id = models.CharField(unique=True, max_length=128)
type = models.CharField(max_length=255,default='text_home')
count = models.IntegerField(default=0)
last_visit=models.DateTimeField(auto_now=True)
class Meta:
db_table = u"o... |
SCREEN_SIZE = 800
SQ_COLUMNS = 10
SQ_SIZE = int(SCREEN_SIZE / SQ_COLUMNS)
SQ_PADDING = 3
SQ_COLOR_GRAY = (200, 200, 200)
SQ_COLOR_ILLEGAL = SQ_COLOR_GRAY # (255, 75, 95)
GRID_LINE_COLOR = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (10, 15, 242)
GREEN = (5, 120, 10)
YELLOW = (230, 230, 50)
RED = (250, 50, ... |
import os
import gym
import time
import argparse
import joblib
import dexterous_gym
parser = argparse.ArgumentParser()
parser.add_argument('--env', type=str, default="EggHandOver-v0")
parser.add_argument('--delay', type=float, default=0.03, help="time between frames")
args = parser.parse_args()
files = os.listdir(arg... |
from wx import *
import wx
app = wx.App()
window = wx.Frame(None,title = 'Helloworld',size = (300,200))
panel = wx.Panel(window)
label = wx.StaticText(panel,label = 'Helloworld',pos= (100,60))
window.Show(True)
app.MainLoop()
|
from game.console import Console
console = Console()
console.play() |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Handle UI
"""
# TODO: Switch to use pandas
# TODO: Fix UI timezone problem
# TODO: Use responsive size when Bokeh eventually supports it with tabs, or get rid of tabs
import numpy as np
from bokeh.io import output_file, save
from bokeh.layouts import widgetbox
from b... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 28 17:10:29 2019
@author: Ray Hao
"""
import json
from random import shuffle
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier
from sklearn.linear_model import SGDClassifier
from sklearn.metrics imp... |
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from fbInfo import views
urlpatterns = [
url(r'^user_fb/$', views.UserFbListView.as_view()),
url(r'^user_fb/(?P<pk>[0-9]+)/$', views.UserFbDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
|
"""
A convolutional neural network for MNIST that is compatible with
population-based training.
"""
from typing import Any, List, Tuple, Callable
import math
import random
import os
from matplotlib.axes import Axes
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
import tensorflow as tf
from pbt imp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import os.path as op
import shlex
import subprocess
from tempfile import mkdtemp
from multiprocessing import cpu_count
from flask import Flask, render_template, request, redirect, \
send_from_directory, url_for
from flask_appconfig import AppConfig
from fla... |
import pandas as pd
import json
import sys
from casos import casos_positivos, casos_fallecidos
poblacion_arequipa = 1526342
positivos_arequipa = list(casos_positivos[casos_positivos['DEPARTAMENTO'] == "AREQUIPA"].shape)[0]
positivos_hombres_arequipa = list(casos_positivos[(casos_positivos['DEPARTAMENTO'] == "AREQU... |
import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def json_add_view(request, *args, **kwargs):
if request.method == 'POST':
if request.body:
data = json.loads(request.body)
A = data.get('A')
B = data.get... |
import requests
from rfc3987 import match
MAX_MESSAGE_LENGTH = 120
class Bot:
def __init__(self, DB_Id=0):
self.DB_Id = DB_Id
def parseCommand(self, message):
commandArgs = message.split(maxsplit=1)
if len(commandArgs) < 1:
return self.error("NULL")
elif commandAr... |
# 참조: 에라토스테네스의 체
'''
에라토스테네스의 체 : 범위에서 합성수를 지우는 방식으로 소수를 찾는 방법.
1. 1은 제거
2. 지워지지 않은 수 중 제일 작은 2를 소수로 채택하고, 나머지 2의 배수를 모두 지운다.
3. 지워지지 않은 수 중 제일 작은 3을 소수로 채택하고, 나머지 3의 배수를 모두 지운다.
4. 지워지지 않은 수 중 제일 작은 5를 소수로 채택하고, 나머지 5의 배수를 모두 지운다.
5. (반복)
'''
n=1000
a = [False, False] + [True]*(n-1)
primes=[]
#2 ~ n까지 구한... |
import os
import random
STAR = "Star"
CIRCLE = "Circle"
MINIMAX = "MINIMAX"
ALPHABETA = "ALPHABETA"
class OutputInfo:
def __init__(self):
self.__player = None
self.__algorithm = None
self.__depth = None
self.__state = None
self.__score_board = None
self.__output_f... |
# -*- coding: utf-8 -*-
import pytest
import irc3
import irc3d
from irc3.compat import asyncio
@irc3.plugin
class P:
connections_made = []
def __init__(self, bot):
self.bot = bot
def connection_made(self, *args, **kwargs):
self.bot.log.info('P.connection_made')
self.ready.set_re... |
from collections import defaultdict
from datetime import datetime
from onegov.agency.collections import ExtendedAgencyCollection, \
ExtendedPersonCollection
from onegov.core.csv import CSVFile
from onegov.core.orm.abstract.adjacency_list import numeric_priority
from onegov.core.utils import linkify
def with_open... |
# Requires pymongo 3.6.0+
from pymongo import MongoClient
client = MongoClient("mongodb://47.92.211.251:30000/")
database = client["new_carDataset"]
collection = database["ruihu8"]
BATCH_SIZE=100
def getAll():
query = {}
projection = {}
projection["car"] = 1.0
projection["formatOpinionSet"] = 1.0
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 2 21:50:07 2017
@author: Erik
"""
import numpy as np
from skimage.feature import hog
import cv2
import os
import matplotlib.image as mpimg
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
from sklearn.preprocessing impor... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 3 17:02:35 2018
@author: jhodges
"""
import glob
import matplotlib.pyplot as plt
import numpy as np
def getTime(file):
with open(file,'r') as f:
lines = f.readlines()
simTime = -1
for line in lines:
if 'Total Farsite Run Time' in line:
... |
# Solution Derived from Derrick Sherrill's youtube video: https://www.youtube.com/watch?v=kFeXwkgnQ9U&t=45s
def quick_sort(arr):
length = len(arr)
if length <= 1:
return arr
else:
pivot = arr.pop()
greater = []
lower = []
for number in arr:
if number > pivot:
... |
class hash:
def __init__(self):
self.MAX=5
self.arr=[None for i in range(self.MAX)]
def get_hash(self,key):
h=0
for c in key:
h+=ord(c)
return h%self.MAX
def __setitem__(self, key, value):
h=self.get_hash(key)
star=h
while self.... |
#!/usr/bin/python3
#******************************************************************************
#
#"Distribution A: Approved for public release; distribution unlimited. OPSEC #4046"
#
#PROJECT: DDR
#
# PACKAGE :
# ORIGINAL AUTHOR :
# MODIFIED DATE :
# MODIFIED BY :
# REVISION :
#
# Copyright (c... |
#!/usr/bin/env python
# ENCODE DCC spp call peak wrapper
# Author: Jin Lee (leepc12@gmail.com)
import sys
import os
import argparse
from encode_lib_common import (
assert_file_not_empty, human_readable_number, log,
ls_l, mkdir_p, rm_f, run_shell_cmd, strip_ext_ta)
from encode_lib_genomic import (
subsampl... |
# find prime.py
# to find the nth prime number efficiently
import math
def is_prime(k):
if k ==2:
return True
elif k % 2 ==0:
return False
else:
temp = int(math.sqrt(k))+1
for i in range (3, temp, 2):
if k % i == 0:
... |
# Two lists of numbers are given that can contain
# up to 10,000 numbers each. Print all the numbers
# that appear in both the first and second list,
# in ascending order.
a = list(map(int, input().split()))
b = list(map(int, input().split()))
print(*sorted(list(set(a) & set(b))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.