text stringlengths 38 1.54M |
|---|
from __future__ import unicode_literals
from django.db import models
# Create your models here.
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
from pygme... |
from .filters import filters_rotated, filters_learnable
__all__ = ['filters_rotated', 'filters_learnable']
|
## png_to_copper_list.py
import png
import math
import colorsys
import codecs
filename_in = 'ilkke_font'
filename_out = '../../source/fonts'
def quantize_color_as_OCS(_color):
_new_color = [0,0,0]
_new_color[0] = 2 * int(_color[0] / 2)
_new_color[1] = 2 * int(_color[1] / 2)
_new_color[2] = 2 * int(... |
"""
TCP ๆๅก็ซฏ
"""
import socket
# ๅๅปบๆๅก็ซฏ้ไฟกๅฏน่ฑก
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# p้
็ฝฎIP็ซฏๅฃ
SERRVERADDR = ("192.168.15.3", 6666)
server.bind(SERRVERADDR)
# ๅผๅฏ็ๅฌ
server.listen()
print("ๆๅก็ซฏๅฏๅจ")
# ่ทๅๅฎขๆท็ซฏsocket
client,clientaddr = server.accept()
print("ๅฎขๆท็ซฏ",clientaddr,"่ฟๆฅไธไบ")
# ๆฅๅๅฎขๆท็ซฏๅ้็ๆฐๆฎ
BUFFERSIZE = 102... |
# 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 writing, software
# d... |
from sklearn.cluster import KMeans
from secure_kmeans import *
from timeit import Timer
import cProfile
def graph_performance(sk, naive, secure, range_start, range_end, step):
"""
Utility function to plot time as function of how many data points
are to be clustered
"""
x = [i for i in range(range_... |
print "iets"
x = 2
if x == 2:
print("dit is mijn eerste programma")
print("kijk opa jan ik kan al programmeren")
print "Hoofdstuk: %d" % x
print("en ik doe het met erwin")
print("ik vind het heel heel heel erg leuk om te doen")
print('gaaf he')
tekst = "dit heeft erwin gedaan"
if x == 2:
tekst = "ik kan het... |
# -*- coding: utf-8 -*-
r"""
๋จ์ด ์๋ฒ ๋ฉ: ์ดํ์ ์๋ฏธ๋ฅผ ์ธ์ฝ๋ฉํ๊ธฐ
===========================================
**๋ฒ์ญ**: `์์ฑ์ฐ <http://github.com/sylim2357>`_
๋จ์ด ์๋ฒ ๋ฉ(word embedding)์ด๋ ๋ง๋ญ์น(ํน์ ์ฝํผ์ค, corpus) ๋ด ๊ฐ ๋จ์ด์ ์ผ๋์ผ๋ก ๋์ํ๋ ๋ฐ์ง๋ ์ค์ ๋ฒกํฐ(dense vector)์ ์งํฉ, ํน์ ์ด ๋ฒกํฐ๋ฅผ
๊ตฌํ๋ ํ์๋ฅผ ๊ฐ๋ฆฌํต๋๋ค. ์ฃผ๋ก ๋จ์ด๋ฅผ ํผ์ฒ(feature)๋ก ์ฌ์ฉํ๋ ์์ฐ์ด ์ฒ๋ฆฌ ๋ถ์ผ์์๋ ๋จ์ด๋ฅผ ์ปดํจํฐ ์นํ์ ์ธ
ํํ๋ก ๋ฐ๊พธ์ด ์ฃผ๋ ์... |
#!/usr/local/bin/python2.7
"""
replace low-frequency words in training file with '_RARE_'
and generate new training file - 'parse_train_rare.dat'
then execute
python count_cfg_freq.py parse_train_rare.dat > cfg_rare.counts
to generate new count file
"""
import sys, os
import numpy as np
import json
import types
impor... |
# euler 37
def is_prime(n):
if n <= 1:
return False
elif n <= 3:
return True
elif (n % 2 == 0 or n % 3 == 0):
return False
i = 5
while i * i <= n:
if (n % i == 0 or n % (i + 2) == 0):
return False
i += 6
return True
sumx = 0
for x in ... |
import logging
from .stream import Stream
logger = logging.getLogger(__name__)
class TagManager():
def __init__(self, docker_api, docker_client, version_manager, cache, quiet):
'''
Constructor
@param docker_api: Customer docker API
@type docker_api: DockerApi
@param docke... |
# ้ๆฑ๏ผ0-10ๅถๆฐๆฐๆฎ็ๅ่กจ
# 1. ็ฎๅๅ่กจๆจๅฏผๅผ rangeๆญฅ้ฟ
list1 = [i for i in range(0, 10, 2)]
print(list1)
# 2. forๅพช็ฏๅ if ๅๅปบๆ่งๅพ็ๅ่กจ
list2 = []
for i in range(10):
if i % 2 == 0:
list2.append(i)
print(list2)
# 3. ๆforๅพช็ฏ้
ๅif็ไปฃ็ ๆนๅ ๅธฆif็ๅ่กจๆจๅฏผๅผ
list3 = [i for i in range(10) if i % 2 == 0]
print(list3)
|
# python ไฝฟ็จๅญๅ
ธไปฃๆฟswitch
switcherDict = {
0 : 'Sunday',
1 : 'Monday',
2 : 'Tuesday'
}
day_name = switcherDict[0]
print(day_name)
day_name1 = switcherDict.get(5, 'Unkown')
print(day_name1)
# ๅ่กจๆจๅฏผๅผ
a = [1,2,3,4,5,6,7,8,9]
b = [i**2 for i in a]
print(b)
student = {
'่็': 18,
'็ไบ': 19,
'็ไธ': 20
... |
#coding:utf-8
import smtplib # ๅ้้ฎไปถ
from email.mime.multipart import MIMEMultipart # ๅธฆ้ไปถ
from email.mime.text import MIMEText # ๆๅปบ้ฎไปถ
def sendemail_func(smtp_server, send_user, password, receive_user_list, subject, excel_path, run_num, pass_num, failed_num, pass_rate, failed_rate):
if smtp_server:
... |
list=[1,2,3,4,5,6,7,8,9,10,11]
print("Original List")
print(list)
new_list = [x*2 for x in list]
print(new_list)
new_even_list = [x for x in list if x%2==0 ]
print(new_even_list)
#inner loop
list_same=[10,100]
combine_add = [x+y for x in list for y in list_same]
print(combine_add)
|
def generate_config(context):
properties = context.properties
resource_name = 'mig-' + context.env['name']
project = context.env['project']
zone = properties['zone']
template_id = properties['templateId']
instance_template = 'projects/' + project + '/global/instanceTemplates/' + template_id
... |
from wikiinfo import *
from ...fields import FieldType
class RussianVerbStressField(FieldType):
def __init__(self, db, sdictPath):
self.info = WikiInfo(db, sdictPath)
def pull(self, word):
return self.info.getStress(word)
|
import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
import torch, random
from sklearn.manifold import TSNE
from mpl_toolkits import mplot3d
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import plot_precision_r... |
n = -1
while n < 0:
n = int(input('Digite um nรบmero a saber seu fatorial: '))
if n < 0:
print('Valores negativos nรฃo sรฃo permitidos. Tente novamente.')
else:
if n == 0:
print('O fatorial de {} รฉ igual a 1'.format(n))
else:
fatorial = n
pr... |
import json
def isJson():
with open('books.json') as json_data:
try:
data_dict = json.load(json_data)
data_str = json.dumps(data_dict)
data_dict_02 = json.loads(data_str)
json_data.close()
return data_dict_02
except ValueError as e:
... |
import csv
import random
def load_quotes():
"""Loads all quotes from the CSV."""
quotes = []
with open('quotes.csv', newline='') as quotes_file:
csv_reader = csv.reader(quotes_file)
for row in csv_reader:
if len(row) != 0:
quotes.append({'quote': row[0], 'author... |
import datetime
from unittest.mock import Mock, MagicMock, patch, call
import pytest
from testframework.checkers import bigquery_checker
from testframework.checkers.bigquery_checker import BigqueryChecker
from testframework.checkers.checker_message import CheckerMessage
from testframework.util.assertion import undeco... |
import numpy as np
import random
data_path = './data/web-Google.txt'
with open(data_path, 'r') as f:
data = f.read().replace("\n", ",").split(",")
del data[:5]
# add random k (0,1)
for i in range(len(data)):
# random_k = random.randint(0, 1)
# data[i] += '\t'+str(random_k)
data[i] += '\t1'
#split... |
from collections import defaultdict
from logging import getLogger, NOTSET, basicConfig
from pkg_resources import resource_filename
from logging.config import fileConfig
import numpy as np
import scipy.stats
from statsmodels.sandbox.stats.multicomp import multipletests
# import matplotlib.pyplot as plt
import pandas as... |
import requests
import json
# url = "https://www.earthtory.com/ko/city/seoul_310/hotel#1";
json_url = "https://www.earthtory.com/api/spot/get_spot_list"
data = {
'pl_ci': '310',
'member_srl': '0',
'pl_category': '1',
'cur_page': '1',
'min_price': '92381',
'max_price': '1068800',
'star_rat... |
companies_id = {}
while True:
command = input()
if command == "End":
break
company, employee_id = command.split(" -> ")
if company not in companies_id:
companies_id[company] = []
if employee_id not in companies_id[company]:
companies_id[company].append(employee_id)... |
import pytorch_lightning as pl
from torchvision import transforms
from torchvision.datasets import CIFAR10
from torch.utils.data import DataLoader, random_split
"""
Sample DataModule for CIFAR10 Dataset.
"""
class CIFAR10Data(pl.LightningDataModule):
def __init__(self, data_dir='../../data', batch_size=128,
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 13 17:50:57 2020
@author: samarth
"""
import pandas as pd
from matplotlib import pyplot as plt
import os
from datetime import datetime as dt
from datetime import timedelta
import matplotlib.dates as mdates
import numpy as np
projection_length = 6... |
from chatterbot import ChatBot
from chatterbot.adapters import Adapter
from tests.base_case import ChatBotTestCase
class AdapterValidationTests(ChatBotTestCase):
def test_invalid_storage_adapter(self):
kwargs = self.get_kwargs()
kwargs['storage_adapter'] = 'chatterbot.logic.LogicAdapter'
... |
# Write a Python program that prints "Equal" if three numbers a, b, and c are equal.
# If at least one number if different, the program should print "Not Equal".
x = int(input("Enter First Number :"))
y = int(input("Enter Second Number :"))
z = int(input("Enter Third Number :"))
if (x == y == z):
print("Equ... |
import logging
from queue import Queue
from threading import Thread
_logger = logging.getLogger(__name__)
class BackgroundWriter(Thread):
class WriteAfterDone(Exception):
'''Indicates when an action is taken after requested to stop.'''
def __init__(self, writer, done_callback=None):
'''Wraps... |
import unittest
from changepoint_detector import linear_model as gm
import numpy as np
from scipy.stats import t
class TestLinearModel(unittest.TestCase):
def test_factory(self):
model_generator = gm.DefaultLinearModelFactory
# requires time by datapoints data to be a numpy array
self.assertRaises(Value... |
import collections as co, operator
from string import ascii_lowercase
def count_polymer(data,ign=''):
stack = []
for c in data:
if c != ign.lower() and c != ign.upper():
stack.append(c)
if len(stack) > 1:
x,y = stack[-1], stack[-2]
while len(stack)... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 6 21:26:36 2017
@author: amado
"""
import h5py
import sys
import scipy.misc
import numpy as np
sys.path.append('../../')
from paths import getDropboxPath
data_path = getDropboxPath()+'data/ADEChallengeData2016/'
def createH5(params):
output_file = params['name']+'... |
# Ported to C# li_attribute_runme.cs
import li_attribute
aa = li_attribute.A(1, 2, 3)
if aa.a != 1:
raise RuntimeError
aa.a = 3
if aa.a != 3:
print aa.a
raise RuntimeError
if aa.b != 2:
print aa.b
raise RuntimeError
aa.b = 5
if aa.b != 5:
raise RuntimeError
if aa.d != aa.b:
raise Runtim... |
import json
import lambda_db
json_data = open('input.json')
event = json.load(json_data)
context = "context"
lambda_db.lambda_handler(event, context)
|
import requests
from bs4 import BeautifulSoup
HEADERS = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v... |
class Solution:
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
ln = len(nums)
i = 0
def abs(x):
if x < 0:
return -x
return x
while i < ln:
v = abs(nums[i]) -... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 27 01:02:34 2019
@author: yazi
"""
def launch(data):
length=200
u=[1]
v=[i for i in range(2,length+1)]
A={}
A[1]=0
key_v= dict.fromkeys(range(2,length+1),1000000)
dijikstra(u,v,A,key_v,data)
return A
def... |
import os
def make_img_list(img_dir):
"""ๆๅฎใใฉใซใๅ
ใซๅญๅจใใใในใฆใฎ็ปๅpathใๅใฃใฆใใ"""
ext = ".png"
img_path_list = []
for curDir, dirs, files in os.walk(img_dir):
for file in files:
if file.endswith(ext):
img_path = os.path.join(curDir, file)
img_path_list.append... |
import pickle
import time
import urllib.request
import json
company_list = ['p0000745jr8u', 'p0003884x7lt', 'p0043611aoji', 'p0039557fvbf',
'p0090051h2oq', 'p0006679vz2s', 'p00425z4gu', 'p0009976ed7k',
'p0005859huep', 'p0089280mxzg', 'p0079383unbs', 'p00521862bvn',
'p000... |
# Import libraries
import pandas as pd
import sklearn
import numpy as np
import random
from matplotlib import pyplot as plt
from matplotlib.figure import Figure
import my_func
import time
from eye_identifier import EyeCenterIdentifier, GridSearch
from image_preprocess import imanorm, histeq, imaderiv
from sklearn.ense... |
import sys
sys.stdin=open("input.txt")
def dfs(i):
for j in node[i]:
if not visited[j]:
visited[j]=1
dfs(j)
for t in range(int(input())):
n,m=map(int,input().split())
node=[[] for _ in range(n+1)]
cnt=0
visited=[0]*(n+1)
for i in range(m):
a,b=map(i... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
t = int(raw_input())
for a0 in xrange(t):
n = int(raw_input().strip())
if n == 1:
print '3'
else:
x = 1 + (4 * n * n)
x = x ** (.5)
x = int((x - 1) / 2)
y = 1
i = x
# print '========... |
import torch
from clusterers import base_clusterer
class Clusterer(base_clusterer.BaseClusterer):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.k = 1
print('Setting k to 1 regardless of config.')
def get_labels(self, x, y):
return torch.randint(low=0, high=1, s... |
import pytest
from typing import List
@pytest.mark.parametrize(argnames="phrase, norm_phrase",
argvalues=[("TestPhrase", "testphrase"),
("Test_phrase", "testphrase"),
("test_phrase", "testphrase")])
def test_normalized_st... |
import aiomysql
import asyncio
async def select(loop, sql, pool):
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
r = await cur.fetchone()
print(r)
async def insert(loop, sql, pool):
async with pool.acquire() as conn:
... |
from django.http import HttpResponse
from django.shortcuts import render_to_response
def homepage(request):
return render_to_response('trqlive/homepage.html')
def homepage_static(request):
return render_to_response('trqlive/homepage_static.html')
# vi:ts=4:sw=4:expandtab
|
'''
Function:
Implementation of PSANet
Author:
Zhenchao Jin
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
try:
from mmcv.ops import PSAMask
except:
PSAMask = None
from ..base import BaseSegmentor
from ...backbones import BuildActivation, BuildNormalization
'''PSANet'''
class P... |
import gzip
import pickle
import matplotlib.cm as cm
import matplotlib.pyplot as plt
with gzip.open('mnist.pkl.gz', 'rb') as f:
train_set, valid_set, test_set = pickle.load(f)
train_x, train_y = train_set
print len(train_x[0])
# for l in range(len(train_x)):
for l in range(... |
from typing import List
class Solution:
def numSubseq(self, nums: List[int], target: int) -> int:
nums.sort()
counter = 0
i = 0
j = len(nums) - 1
while i <= j:
if nums[i] + nums[j] > target:
j -= 1
else:
counter += 2 *... |
from zeep import xsd
from .mappings import query_type_mapping
def query_filter(vm, field, value, query_type):
query_function = query_type_mapping[query_type]
if field['type'] is 'String':
query_filter = vm.query_factory[query_function](Field=field['name'], Value=xsd.AnyObject(xsd.String(), value))
... |
from sys import stdin
import itertools
A = input().split()
B = stdin.read().splitlines()
K = int(A[0])
M = int(A[1])
def pwr(list):
return [x**2 for x in list]
ls = {}
for i in range(K):
ls[i] = list(map(int, B[i].split()))
del(ls[i][0])
ls[i] = pwr(ls[i])
dictlist = []
for index in ls:
dictlist... |
#-*- coding: utf-8 -*-
""" Console module container """
from __future__ import print_function
import sys
import time
from builtins import input
import colorama
import rl
from voiceplay import __title__
from voiceplay.utils.helpers import SingleQueueDispatcher
from voiceplay.utils.command import Command
class Cons... |
"""
CEASIOMpy: Conceptual Aircraft Design Software
Developed for CFS ENGINEERING, 1015 Lausanne, Switzerland
The script contains all the geometrical value required for the
weight unconventional analysis.
| Works with Python 2.7
| Author : Stefano Piccini
| Date of creation: 2018-11-26
| Last modifiction: 2019-02-20
... |
import powerbalance as p
# ะะผะฟะพัั ะฝะฐัะตะณะพ ะถะต ะผะพะดัะปั
# ะะพะฝััะฐะฝัั ะธั
ะฟัะฐะฒะธะป
buyCost = 5
buyCostFast = 10
sellCost = 2
sellCostFast = 1
#ะััะธัะปะตะฝะธะต ััะพะธะผะพััะธ ะพะดะฝะพะณะพ ะธัั
ะพะดะฐ ัะฝะตัะณะพะฑะฐะปะฐะฝัะฐ
def makeCost(value,adjust):
result = 0
if adjust > 0:
result -= adjust * buyCost
else:
result += adjust * ... |
#! /usr/bin/env python
import bluetooth
import time
import os
import json
import threading
from threading import Thread
from DatabaseManager import DatabaseManager
from JSONParser import JSONParser
from DetectorsFileParser import DetectorsFileParser
class BluetoothReceiver():
detectors = []
# Method receive... |
# Time: O(n)
# Space: O(1)
# Given a singly linked list, return a random node's value from the linked list.
# Each node must have the same probability of being chosen.
#
# Follow up:
# What if the linked list is extremely large and its length is unknown to you?
# Could you solve this efficiently without using extra s... |
import math
import hashlib
import gym
from enum import IntEnum
import numpy as np
from gym import error, spaces, utils
from gym.utils import seeding
from .rendering import *
from copy import deepcopy
# Size in pixels of a tile in the full-scale human view
TILE_PIXELS = 32
# Map of color names to RGB values
COLORS = {... |
from pyspark.conf import SparkConf
import argparse
import os
import numpy
import sys
import tensorflow as tf
import threading
import time
from datetime import datetime
from tensorflow.python.ops import variable_scope as vs
# from tensorflowonspark import TFCluster
# import pyspark.sql as sql_n #spark.sql
# from... |
# -*- coding:utf-8 -*-
import time
from testcase import *
#ๆทปๅ ็ฉไธๅ
ฌๅธ
login('15707256976', '1234567')
time.sleep(5)
browser.find_element_by_xpath('//div/div/nav/ul/li[1]/ul/li[2]/a').click()
browser.find_element_by_xpath('//div[3]/div[2]/div/div[3]/div/div[2]/div[2]/button').click()
#ๅ
ฌๅธๅ็งฐ
browser.find_element_by_xpath('... |
from django.core.management.base import BaseCommand
from django.db import transaction
from geofr.services.populate import populate_overseas
class Command(BaseCommand):
"""Populate overseas related perimeters."""
@transaction.atomic
def handle(self, *args, **options):
result = populate_overseas()... |
import os
os.system('touch /tmp/demo.txt')
infile = open(filename, 'r') # default
infile = open(filename, 'rb') # binary read [ byte stream ]
infile = open(filename, 'r+') # both input and output
with open('/tmp/demo.txt') as f:
f.read()
f.read(N)
f.readline()
f.readlines() # => [line string... |
# -*- coding: utf-8 -*-
# __author__ = 'eacaen'
import csv
# with open('villains.csv','rt') as fin:
# cin = csv.DictReader(fin,fieldnames=['first','last']) #ๆๅฎๅ็ๅๅญ
#
# vas = [row for row in cin]
#
# print vas
vall = [
{'last': 'a', 'first': 'doc'},
{'last': 'asdd', 'first': 'sss'},
{'last': 'b', 'f... |
from .models import Magazine, Alumni_Article
from django.shortcuts import render, redirect, get_object_or_404
def alumni_portal(request):
articles = Alumni_Article.objects.published()
return render(request, 'alumni_portal.html', {'articles': articles})
def alumni_magazine(request):
magazines = Magazine.... |
class Solution:
def canBeIncreasing(self, nums: list[int]) -> bool:
for i in range(len(nums)):
t = nums[:i] + nums[i+1:]
if all(t[i] < t[i+1] for i in range(len(t)-1)):
return True
return False |
from utils import AverageMeter, ProgressMeter
import torch
# Determine 20 nearest neighbors with SimClR instance discrimination task
def SimCLR_train(dataloader, model, epoch, criterion, optimizer):
# Record progress
losses = AverageMeter('Loss', ':.4e')
progress = ProgressMeter(len(dataloader), [losses], ... |
from jwt import encode, decode
from app import SECRET_KEY
def generate_token(payload):#{ 'id':, 'names':, rol: '' }
token = encode(payload, SECRET_KEY, algorithm='HS256')
return token.decode('utf-8')
def decode_token(token):
return decode(token, SECRET_KEY, algorithms='HS256') |
#!/usr/bin/env python
#-*-coding:utf-8-*-
class person():
def __init__(self,name,age):
self.name=name
self.age=age
print 'person %s has been constructed.'%(self.name)
def tell(self):
print 'I\' %s \nmy age is %d'%(self.name,self.age),
class teacher(person):
def __init__(self,name,age,salary):
person.__ini... |
import pygame
class Player(pygame.sprite.Sprite):
# Constructor function
def __init__(self, x, y,lenX,lenY):
super().__init__()
# altura, largura
self.image = pygame.Surface([lenX, lenY],pygame.SRCALPHA,32)
self.image.convert_alpha()
# Make our top-left corner the pa... |
from wx.lib.pubsub import pub
from game_display import *
from options_dialogs import *
class MainView(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.SetTitle("pyNES")
# Display for emulator
self.display = Display(parent=self)
... |
# ๅฏผๅ
ฅ่ๅพ
from flask import Blueprint
# ๅๅปบ่ๅพ
api = Blueprint('api',__name__)
# ๆไฝฟ็จ่ๅพๅฏน่ฑก็ๆไปถ๏ผๅฏผๅ
ฅๅฐๅๅปบ่ๅพๅฏน่ฑก็ไธ้ข
from . import passport,users,house
# ๅฎไน่ฏทๆฑ้ฉๅญ๏ผๅฎ็ฐๅๅฐ่ฟๅๅๅบๆๅฎๅๅบ็็ฑปๅ๏ผjsonๆ ผๅผ
@api.after_request
def after_request(response):
# ๅฆๆๅๅบ็ๅคดไฟกๆฏๆฏtext/html
if response.headers.get('Content-Type').startswith('text'):
respo... |
#!/usr/bin/env python3
import sys
class Generate:
def __init__(self):
message = sys.argv[1].lower()
count = 0
new_message = []
for char in message:
add = char.upper() if (count % 2) != 0 else char
new_message.append(add)
count+=1
... |
#!/usr/bin/env python
# ----------------------------------------------------------------------
#
# Python script to create spatial database with rate-state friction parameters.
#
# Brad T. Aagaard, U.S. Geological Survey
#
# ----------------------------------------------------------------------
#
# PREREQUISITES: numpy... |
list=['siva','reddy','kumar','meghana']
x=" ".join(list)
z=[]
for i in x[::-1].split():
z.append(i)
|
from typing import Union, Dict, Any, List
from struct import pack
from collections import OrderedDict
from functools import wraps
from starparse import config
import logging
logger = logging.getLogger(__name__)
SBT = Union[str, int, float, list, dict, OrderedDict]
class PackingError(Exception):
"""Packing erro... |
import asyncio
from pyppeteer import launch
from time import sleep
async def close_dialog(dialog):
print("dialog popup")
await dialog.dismiss()
async def main():
browser = await launch()
page = await browser.newPage()
await page.goto('http://gw.roigames.co.kr/')
await page.scre... |
# -*- coding: utf-8 -*-
"""
this is a tool file .It has load_file,save_file,logistic,softmax function
"""
import pickle
import numpy as np
def read_file(path):
with open(path, 'rb') as f:
file = f.read().decode('utf-8')
return file
def writer_file(path, obj):
with open(path, 'wb') as f:
... |
#!/usr/bin/env python3
import argparse
import csv
import sys
import os
import xopen
import fcntl
F_SETPIPE_SZ = 1031 if not hasattr(fcntl, "F_SETPIPE_SZ") else fcntl.F_SETPIPE_SZ
F_GETPIPE_SZ = 1032 if not hasattr(fcntl, "F_GETPIPE_SZ") else fcntl.F_GETPIPE_SZ
def isFloat(val):
if val is None:
return Fal... |
from tests.modules.FlaskModule.API.user.BaseUserAPITest import BaseUserAPITest
class UserQueryStatsTest(BaseUserAPITest):
test_endpoint = '/api/user/stats'
def setUp(self):
super().setUp()
def tearDown(self):
super().tearDown()
def test_no_auth(self):
with self._flask_app.ap... |
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions, status, generics
from quizzz.communitie... |
from flask import render_template, redirect, url_for, flash, request
from werkzeug.urls import url_parse
from flask_login import login_user, logout_user, current_user
from flask_babel import _
from app import db
from app.auth import bp
from app.auth.forms import LoginForm, RegistrationForm, \
ResetPasswordRequestFo... |
from abc import abstractmethod
from datetime import datetime
from decimal import Decimal as D
from decimal import InvalidOperation
from typing import Any, Optional, TypeVar
from exchange.exceptions import DateTimeParseException
from exchange.operation_type import OperationType as OT
from flask_restplus.fields import R... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
a=input("Cien. liet., ludzu, ievadi skaitli: ")
a = int (a)
print("Liet., Tu esi ievadijis skaitli: %d"%(a))
aa = a * a
print("Liet., Tu Esi Ievadijis skaitli: %d"%(a))
aa = a*a
|
################################################################################
### Init
################################################################################
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s... |
#!/usr/bin/python
#
# git log --pretty="%H %P" | this program
# See option descriptions at bottom
#
# This little program cranks through a series of patches, trying to determine
# which trees each flowed through on its way to the mainline. It does a
# 'git describe' on each, so don't expect it to be fast for large num... |
from random import random
from . import Agent
from util.collections import CircularList
from util.listops import sublists, listhash
from util.interpolation import linear_latch
class ActionChainAgent(Agent):
"""docstring for RandomAgent"""
def __init__(self, chain_length):
super(ActionChainAgent, sel... |
"""
Authors: Cristhian Castillo and Kevin Zarama
Icesi University, 2019
This script represent a client in the model Client-Server for a Socket Chatroom
"""
import socket
import sys
import errno
from random import randrange
"""
HEADER INFO
"""
HEADER_LENGTH = 10
"""
HOST INFO
"""
HOST = "127.0.0.1"
PORT = 8080
nickn... |
class node:
def __init__(self,x):
self.value=x
self.next=None
class linkedList:
def __init__(self,n=None):
self.head=n
def insert(self,n):
if self.head==None:
self.head=n
return
node=self.head
if node==None:
node=n
... |
import numpy as np
from numpy import linalg as LA
from scipy.spatial.distance import cdist
# rejection sampling algorithm comes from LSE lecture notes
# alternatively see WOLFRAM: http://mathworld.wolfram.com/CirclePointPicking.html
# # http://mathworld.wolfram.com/HyperspherePointPicking.html
def unit_circumference_... |
# coding=utf-8
# Copyright 2019 The Tensor2Tensor Authors.
#
# 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... |
'''
Created on Mar 13, 2016
Codejam template
@author: Ozge
'''
from itertools import product
filepath = ''
fileprefix = 'C-small-attempt1' #Change
filepathname = filepath + fileprefix
infilename = filepathname + '.in'
outfilename = filepathname + '.out'
lines = open(infilename, 'rU').read().split("\n")
outfile = ope... |
inp1=eval(input("Enter the first number:"))
inp2=eval(input("Enter the second number:"))
print("The arithametic operation are as follows:")
print(inp1,"+",inp2,"=",inp1+inp2)
print(inp1,"-",inp2,"=",inp1-inp2)
print(inp1,"*",inp2,"=",inp1*inp2)
print(inp1,"/",inp2,"=",inp1/inp2)
print(inp1,"//",inp2,"=",inp1//in... |
"""
The MIT License (MIT)
Copyright (c) 2016 Intel Corporation
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, c... |
from mock import Mock, MagicMock, patch, call, mock_open
# To run unittests on python 2.6 please use unittest2 library
try:
import unittest2 as unittest
except ImportError:
import unittest
import re, jenkinsapi
from jenkinsapi.artifact import Artifact
from jenkinsapi.build import Build
from jenkinsapi.custom_e... |
import glob
import time
import os
from primitives.track import Track
from primitives.grid import Grid
from cv_toolkit.cams import FisheyeCamera
from cv_toolkit.transform.camera import UndistortionTransform
from cv_toolkit.transform.common import PixelCoordinateTransform
from ..filtering.measurements import Measureme... |
# -*- encoding: utf-8 -*-
import logging
import arrow
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
logger = logging.getLogger('common')
FORMAT_CHOICES = (('csv', 'csv'),)
PARTY_TYPE_CHOICES = (('id', 'id... |
from flask import Flask, Response, send_from_directory, render_template
app = Flask('app', static_url_path='')
@app.route('/style.css')
def stylecss():
print("hi")
return send_from_directory('.', path='style.css')
@app.route('/style2.css')
def style2css():
print("hi")
return send_from_directory('.', path='style2... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 1 13:50:59 2019
@author: Luke
"""
import pystan
import pandas as pd
import matplotlib as plt
import scipy
df = pd.read_csv('synthetic_data.csv')
player_names = df.Player.unique()
unpooled_model = """data {
int<lower=0> nholes;
vector[nholes] player... |
# Generated by Django 2.2.10 on 2021-11-11 12:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('poles_app', '0002_auto_20211111_1243'),
]
operations = [
migrations.RemoveField(
model_name='answer',
name='value',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.