text stringlengths 8 6.05M |
|---|
from django.shortcuts import get_object_or_404, render
from django.views.generic import View
from django.http import HttpResponse
from django.utils.html import escape
from django.core.urlresolvers import reverse
from django.views.generic import TemplateView
from crispy_forms.layout import Submit
from crispy_forms.helpe... |
# -*- coding: utf-8 -*-
# Copyright 2018. All Rights Reserved.
#
# 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 appl... |
import json
from pyspark import SparkContext, SparkConf
# from pyspark.sql import SparkSession
# from pyspark.sql import functions as f
import sys
import time
import multiprocessing
start_time = time.time()
# Run Configurations
input_path1 = sys.argv[1]
input_path2 = sys.argv[2]
output_path1 = sys.argv[3]
output_path... |
from webservice.ticketing.jira.jira import *
from webservice.ticketing.jira.issue import * |
"""
This solution was created by Dan, in collaboration with Connor, Taylor,
Eunkyu, Chris, Aurora, and Brandon. Though not as efficient as
Brandon's algorithm, I wanted to show other ways to approach this Ulam
spiral problem and some other Python tricks in practice. I didn't time
any of this so while some of the algor... |
# Дана последовательность целых чисел a[0..n-1] и натуральное число k, такое что для любых i, j: если j >= i + k, то a[i] <= a[j]. Требуется отсортировать последовательность. Последовательность может быть очень длинной. Время работы O(n * log(k)). Доп. память O(k).
# Использовать слияние.
# Sample Input:
# 20
# 3 4 ... |
#! /usr/bin/env python
import os
import tornado.ioloop
import tornado.options
from tornado.options import define, options
import tornado.web
from src.api.controller.BaseStaticFileHandler import BaseStaticFileHandler
from src.api.controller.ServerListController import ServerListController
from src.api.controller.InfoC... |
#!/usr/bin/python
import numpy as np
import pylab as py
import os,sys
from COMMON import mpc, light, grav, msun, yr, nanosec, week, hub0, h0, omm, omv
import COMMON as CM
import mpmath
from scipy import integrate
#from time import time
#################################################
#INPUT PARAMETERS:
inc=0. #Inclin... |
from rest_framework import serializers
from api.models import Company, CompanyStuff
from authentication.serializers import UserSerializer
class CompanySerializer(serializers.ModelSerializer):
class Meta:
model = Company
fields = ('id', 'name')
class CompanyStuffSerializer(serializers.ModelSerial... |
from nio import MatrixRoom
from dors import command_hook, Jenny, HookMessage
import requests
@command_hook(['bible'])
async def bible(bot: Jenny, room: MatrixRoom, event: HookMessage):
verse = event.args[0] + '%20' + event.args[1]
# TODO: USE ASYNC!
i = requests.get('https://labs.bible.org/api/?passage='... |
import numpy as np
def maximization(X,gamma, chi):
# Update model parameters: pi, A, B
K = np.shape(gamma[0])[0]
N = len(gamma)
T = np.shape(gamma[0])[1]
D = np.shape(X[0][0])[0]
# -------------- pi update ---------------
pi = np.zeros((1, K))
for n in range(N):
pi = pi + gamm... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# from django.shortcuts import get_object_or_404, render
# from django.http import HttpResponseRedirect
# from django.urls import reverse
# from django.views import generic
# from django.utils import timezone
# class IndexView(generic.ListView):
# te... |
import sys
REC = {}
def happy(n,path=[]):
if n in REC:
return REC[n]
elif n%10 == 1:
REC[n] = 1
return 1
elif n in path:
REC[n] = 0
return 0
else:
REC[n] = happy(sum(i*i for i in map(int,str(n))),path+[n])
return REC[n]
with open(sys.argv[1],'r'... |
from django.test import TestCase, RequestFactory
from list_app.models import Entry, List
from django.utils.html import escape
from list_app.forms import EntryForm, ListForm, EMPTY_ENTRY_ERROR, EMPTY_LIST_ERROR
from django.contrib.auth.models import User
from django.http import HttpRequest
from list_app.views import new... |
import random
while True:
user_action = input("Enter a choice (rock, paper, scissors): ")
possible_actions = ["rock", "paper", "scissors"]
computer_action = random.choice(possible_actions)
print(f"\nYou chose {user_action}, computer chose {computer_action}.\n")
if user_action == computer_action:
... |
## https://github.com/DigitalCraftsStudents/Instructor-Notes-Clint/blob/master/Programming-102/8-function-return-value.md
# def add_numbers(a,b):
# result = a + b
# return result
# final = add_numbers(1,3) / add_numbers(4,6)
# print(final)
## implicit returns - in python the implicit return is always "None",... |
from tkinter import *
import random as rnd
length = 0
password = []
usr_password = ''
ne = ''
def get_enter():
global length
length = int(pass_len.get())
def func():
win.destroy()
def generator():
global length, password, usr_password, a, label2
random_pass = ["'", 'a', 'b',... |
from panda3d.core import *
import numpy as np
from Geometry import normalizer
def TupleSum(args): # used in
'''
concatenates tuples inside lists
'''
assert type(args) == list # just in case u were still wondering
S=()
for x in args:
S+=x
return S
class RectangleSurface:
def __... |
# This program solves the farmer, grain, goose, fox problem
'''
Character Code Reference
F = Farmer
G = Grain
E = Goose
X = Fox
'''
# Define position of characters in state list
char_pos = {
'F': 0,
'G': 1,
'E': 2,
'X': 3
}
# returns the result of an action on a given state
def get_result(state, action):
n... |
from common.run_method import RunMethod
import allure
@allure.step("极运营/班主任/知识库/知识分类/新增")
def documentDirectory_post(params=None, body=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的环境
:return... |
"""
spine @ rig
a simple spline ik setup
"""
import maya.cmds as mc
from .. base import module
from .. base import control
def build(
spineJoints,
rootJoint,
spineCurve,
bodyLocator,
chestLocator,
pelvisLocator,
prefix = 'spine',
rigScale =1.0,
ba... |
from cudatext import *
"""
in the Editor of created dialog: links are unclickable
"""
class Command:
def run(self):
h, editor = self.init_form()
# both dont work
#dlg_proc(h, DLG_SHOW_NONMODAL)
dlg_proc(h, DLG_SHOW_MODAL)
def init_form(self):
... |
#测试网络,输出loss图像
from keras.models import Sequential
from keras.models import load_model
import numpy as np
import matplotlib.pyplot as plt
model_name = "ResNet50"
X = np.load('drive/app/X_data.npy')
Y = np.load('drive/app/Y_data.npy')
X = X / 25
x_test = X[5000:]
y_test = Y[5000:]
model=Sequential()
model=load_model... |
from django.shortcuts import render, get_object_or_404
from django.views import generic
from django.template import RequestContext
from .models import Petition
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
# Create your views here.
class PetitionView(generic.ListView):
t... |
def compute_sum(n, total):
"""
Compute the total sum range 0 to n
"""
# print(n)
# base case, if you reach n is 0 then you want to return it
print(total[0])
if n == 0:
return 0
total[0] = total[0] + compute_sum(n-1, total)
# else the previous value + (n - 1)
# retur... |
import os
import torch
import torch.nn as nn
from torchvision import datasets, models, transforms
def convrelu(in_channels, out_channels, kernel, padding):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel, padding=padding),
nn.ReLU(inplace=True),
)
def normal_init(m, mean, st... |
"""
If you run this program from the cmd you can search for a keyword in the last crawler result.
You can run this from the cmd with:
$ searcher.py search keyword
The search result is printed in a cmd compatible version and saved to "./search_results/result.json".
TODO:
- make use of some cool regex!
"""
import... |
from django.db import models
import parser
from django.contrib.auth.models import User
class Comic(models.Model):
"""A webcomic (e.g.: "xkcd", "Questionable Content").
Each webcomic has a strategy for retrieving its data:
- Next Button Harvesting: The system will search for a "Next" link on the ... |
this is my new command
|
# Generated by Django 3.0.4 on 2020-03-12 19:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0004_auto_20200312_1829'),
]
operations = [
migrations.AlterField(
model_name='wplyw',
name='created_at',
... |
def cross_product(x, y):
ans = 0
for i in range(min(len(x), len(y))):
ans += x[i]*y[i]
return float(ans)
def norma(x):
ans = 0
for i in x:
ans += i*i
return ans ** (0.5)
def scalar_product(x, y):
return float(norma(x)*norma(y))
def get_user_vector(user):
ans = [... |
# KVM-based Discoverable Cloudlet (KD-Cloudlet)
# Copyright (c) 2015 Carnegie Mellon University.
# All Rights Reserved.
#
# THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANT... |
count = 0
while (count<3):
count = count + 1
print("Hello Tanawin") |
# I pledge my honor that I have abided by the Stevens Honor System
# I understand that I may access the course textbook and course lecture notes but I am not to access any other resource.
# I also pledge that I worked alone on this exam.
def python_operations():
i = int(input("Please enter '1' for mathematical fu... |
#Practice questions Week 4
# Print to canvas
###################################################
# Student should add code where relevant to the following.
import simplegui
# Draw handler
def draw(canvas):
canvas.draw_text("It works!",[120, 112], 48, "Red")
# Create frame and assign callbacks to event han... |
# Test of fcsreader.py
# (cc) 2017 Ali Rassolie
# Formagna
# An illustration of how access the arguments.
# Den här kommer att spara det the user har entered, vilket är värt att förstå.
# Alltså, när användaren skriver exempelvis python 1.py -a hello world (för att -a
# accepterar två arguemnts) kommer man att spara s... |
from model.assistance.assistanceDao import AssistanceDAO
from model.assistance.justifications.justifications import Justification
from model.assistance.justifications.status import Status
from model.assistance.justifications.status import StatusDAO
from model.assistance.justifications.justifications import SingleDateJ... |
import h5py
import numpy as np
import sys
try:
sys.path.append('/afs/ipp/aug/ads-diags/common/python/lib')
from sf2equ_20200525 import EQU
import mapeq_20200507 as meq
AVAILABLE = True
except:
AVAILABLE = False
def isAvailable():
"""
Returns ``True`` if this module can be used to fetch ... |
#!thesis/api
from flask import make_response, jsonify
from core.databaseMongo import nodesDB as db, mainDB
from validator import validateNodeRequest as validate, cleanUpNode as clean
from pymongo.errors import OperationFailure
"""
def computeAvailability(resp, nodeId):
alist = [n["_id"] for n in actionsDB.getAction... |
import bs4
import re
def Capture_Hashtags(text):
#task 1: Clean up HTML (mainly new lines)
soup = bs4.BeautifulSoup(text, 'lxml')
text = soup.get_text()
text = text.replace('\n',' ')
text = text.replace('\r','.')
#task 4: remove links
text = re.sub('https?://[A-Za-z0-9./~]+','', ... |
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('test_skryaga.main.views',
url(r'^requests/$', 'request_list', name='request_list'),
url(r'^requests_change/$', 'ajax_request_priority',
name='request_priority_edit'),
)
|
# -*- coding: utf-8 -*-
"""
Evaluation script for DOA estimation
"""
# interfacing with matlab on my machine required unsetting this env variable
import os
os.unsetenv('MKL_NUM_THREADS')
import argparse
import torch
from model import CRNN, ConvNet, LSTM_FIRST, LSTM_FULL, LSTM_LAST
from doa_math import DoaClasses,to_... |
def noonerize(numbers):
if not isinstance(numbers[0], int) or not isinstance(numbers[1], int):
return 'invalid array'
a, b = numbers
return abs(int(str(b)[0] + str(a)[1:]) - int(str(a)[0] + str(b)[1:]))
'''
Spoonerize... with numbers... numberize?... numboonerize?... noonerize? ...anyway!
You wi... |
"""
Print start, end, elapsed times
"""
import atexit
from time import time, strftime, localtime
from datetime import timedelta
def sec2str(elapsed=None):
""" Pring duration in seconds to HH:MM:SS, current time will be returned if elapsed is None
"""
if elapsed is None:
return strftime("%Y-%m-%d %H... |
import json
import os.path
from .path import relative
CONFIG_FILENAME = 'config.json'
def _get_config_fp():
if os.path.exists(relative(CONFIG_FILENAME)):
return open(relative(CONFIG_FILENAME))
with open(relative(CONFIG_FILENAME), 'w') as f:
f.write('{}')
return _get_config_fp()
... |
from django.urls import path
from .views import homePageView, messageView, registerView, userPage
urlpatterns = [
path('', homePageView, name='home'),
path('users/<str:username>/messages', messageView, name='messages'),
path('register/', registerView, name='register'),
path('users/<str:username>', user... |
import datetime
from django.db import models
from django.db.models import Q
from django.db.models.aggregates import Count
from django.contrib.postgres.search import TrigramSimilarity
class LibroManager(models.Manager):
# manager para el modelo Autor
def listar_libros(self, kword):
resultado = self.fil... |
#!/usr/bin/env python2.7
from distutils.core import setup
import py2exe
setup(console=['ADSToOrigin.py'])
|
String = ("T1.B=>T2.B AND T2.B!=T3.B OR T4.B=T5.B AND T1.B=+4").split(" ")
joinCondition=""
for i in String:
if (i.__contains__("=") and i.count(".")==2) and (not i.__contains__("!")) and (not i.__contains__("<")) and (not i.__contains__(">")):
joinCondition=i
break
|
from torch import gt
from backpack.core.derivatives.elementwise import ElementwiseDerivatives
class LeakyReLUDerivatives(ElementwiseDerivatives):
def hessian_is_zero(self):
"""`LeakyReLU''(x) = 0`."""
return True
def df(self, module, g_inp, g_out):
"""First LeakyReLU derivative:
... |
import yfinance as yf
import streamlit as st
import pandas as pd
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
from datetime import date
import matplotlib as plt
from termcolor import colored
st.write("""
# Beat the market with Hades
This app tries to predict the future price of any... |
from flask import Flask, render_template, jsonify, request
app = Flask(__name__)
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient # pymongo를 임포트 하기(패키지 인스톨 먼저 해야겠죠?)
client = MongoClient('localhost', 27017) # mongoDB는 27017 포트로 돌아갑니다.
db = client.dbsparta #... |
import networkx as nx
f = open("input", "r")
orbits = [x.strip('\n').split(')') for x in f.readlines()]
def part1():
G = nx.DiGraph()
for o in orbits:
G.add_node(o[0])
G.add_node(o[1])
G.add_edge(o[1], o[0])
total = 0
for n in G.nodes:
if n != 'COM':
# Th... |
#-*- coding: utf-8 -*-
from django.contrib import admin
from models import Cidade, Endereco, Pais, Uf
class CidadeAdmin(admin.ModelAdmin):
list_display = ('nome', 'uf',)
search_fields = ('nome', 'uf', )
class EnderecoAdmin(admin.ModelAdmin):
list_display = ('logradouro', 'complemento', 'bairro', 'cidad... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 4 21:46:48 2021
@author: chanchanchan
"""
import streamlit as st
import pandas as pd
from matplotlib import pyplot as plt
import plotly.express as px
import plotly.graph_objects as go
import DissertationPlotwithDataMain as main
import FastFouriorTransfor... |
import os
from vibepy.load_logger import load_logger
from vibepy.read_config import read_config
import vibepy.class_postgres as class_postgres
from run_single_batch import process_batch
from traineval.output_to_postgres import truncate_all_sm_tables
def main():
load_logger(log_config_folder=os.path.dirname(__fi... |
Test = int(input())
for _ in range(Test):
n, k = map(int, input().split())
array = []
num = 1
while len(array) < k:
if num % n != 0:
array.append(num)
num += 1
print(array[-1])
|
from typing import List
from pydantic import BaseModel
class ArticlesBase(BaseModel):
title: str
key_words: List[str] = []
class ArticlesCreate(ArticlesBase):
tags: List[str] = []
class Articles(ArticlesBase):
id: int
tags: List[str] = []
is_hot: bool = False
user_id: int
class C... |
# Pattern Generator
import argparse, itertools
def generatePattern(letters, length):
nchar = 1
i = 26 ** nchar
while i < length:
nchar += 1
i = 26 ** nchar
pattern = itertools.product(letters, repeat=nchar)
pattern_str = ""
i = 0
for p in pattern:
for n in range(nchar):
pattern_str +... |
def evenator(s):
return ' '.join([x if len(x)%2==0 else x+x[-1] for x in s.translate(None,'.,?!_').split()])
'''
Mr. E Ven only likes even length words. Please create a translator so that he
doesn't have to hear those pesky odd length words. For some reason he also
hates punctuation, he likes his sentences to fl... |
"""
Vehicles - TO BE TESTED
Automated Vehicles
"""
from evennia import utils, settings, CmdSet
from typeclasses.objects import Object
COMMAND_DEFAULT_CLASS = utils.class_from_module(settings.COMMAND_DEFAULT_CLASS)
# ------------------------------------------------------------------------------
# Vehicle Commands ... |
from marshmallow import Schema, fields, post_dump
class SchemaWithoutNoneFields(Schema):
"""Prevent serialized fields that have None value"""
SKIP_VALUES = set([None])
@post_dump
def remove_skip_values(self, data):
return {
key: value for key, value in data.items()
if value not in se... |
# features.py
# -----------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
... |
#!/usr/bin/python
from __future__ import division
import sys
import os
import math
import numpy as np
sequence_names = sys.argv[1]
names = []
with open(sequence_names,'r') as f:
lines = f.readlines()
for name in lines:
names.append(name.strip('\n'))
f.close()
threshold = 1
for name in names:
fil... |
a=[3,6,1,0]
m=max(a)
b=a.copy()
b.pop(a.index(m))
c=0
for i in b:
if m>=2*i:
c+=1
if c==len(b):
print(a.index(m))
else:
print(-1)
|
from django.urls import path
from . import views
app_name = "serah_terima"
urlpatterns = [
# path("", views.index, name="index"),
# path("cari", views.cari, name="cari"),
# path("tambah", views.tambah, name="tambah"),
# path("tampil/<int:id>", views.tampil, name="tampil"),
# path("ubah/<int:id>", ... |
"""OctreeLoader class.
Uses ChunkLoader to load data into OctreeChunks in the octree.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, List, Set
from napari.layers.image.experimental._chunk_set import ChunkSet
from napari.layers.image.experimental.octree import Octree
if TYPE_... |
#!/usr/bin/env python
import sys
from os import path
from setuptools import setup, find_packages
sys.path.append(path.join(path.dirname(__file__), 'src'))
from graph_db import __version__ as version
setup(
name='not4oundGraph DB',
version=version,
description='Simple Distributed Graph Database',
lon... |
#!/bin/python
from socket import *
PORT = 24600
s = socket(AF_INET, SOCK_DGRAM)
s.bind(('', PORT))
while(True):
t, addr = s.recvfrom(200)
print "[%s] %s" % (addr[0], t.strip())
|
n = 5
matrix = [[0 for i in range(n)] for j in range(n+1)]
arr = [5,4,3,2,1]
stor = [1,2,3,4,5]
for i in range(n+1):
for j in range(n):
matrix[0][j] = arr[j]
for i in range(1,n+1,+1):
for j in range(n):
if matrix[i][j] == arr[j]:
matrix[i][j] = stor[j]+1
... |
import requests
import unittest
from common.logger import Log
from lxml import etree
class Test(unittest.TestCase):
'''sdk'''
log=Log()
def login(self):
url1 = 'https://cas.zuoyebang.cc/login?service=http://qa-adx2.suanshubang.com/adx-admin/auth-callback'
url2 = 'https://cas.zuoyebang.cc/lo... |
import numpy as np
import h5py
from scipy import stats, mgrid, c_, reshape
from dateutil import parser
from prime_utils import runningAvg, prediction_filename
def getKDE(spl,nskip=0,nthin=1,npts=100,bwfac=1.0):
r"""
Compute 1D and 2D marginal PDFs via Kernel Density Estimate
Parameters
----------... |
class Solution:
def checkValidString(self, s: str) -> bool:
lower=0
upper=0
for ch in s:
if ch=='(':
lower+=1
upper+=1
elif ch ==')':
lower-=1
upper-=1
if lower< 0:
low... |
h = open('Day12/numbers.txt', 'r')
# Reading from the file
content = h.readlines()
for x in range(len(content)):
if content[x].endswith('\n'):
content[x] = content[x][:-1]
def turn(command, direction):
degree = direction
if command[0] == 'R':
degreeR = (degree - int(command[1:])) % 36... |
#Setup
import praw, re, csv, random
#Validate Reddit Access
reddit = praw.Reddit(client_id='Dn_ef002ikq0dw',
client_secret='B_8gGLkYtz6aDmZ4tkP5Dj3BFIo',
password='zzzzzz',
user_agent='pix3lbot_scrape by /u/pix3lbot',
username='pix3lbo... |
# -*- coding: utf-8 -*-
class Solution:
def threeSum(self, nums):
nums.sort()
result = set()
for k, _ in enumerate(nums):
i, j = 0, len(nums) - 1
while i < k and j > k:
if nums[i] + nums[j] + nums[k] == 0:
result.add((nums[i], n... |
def match(usefulness, months):
return "Match!" if sum(usefulness) >= 100*(1-0.15)**months else "No match!"
'''
It is 2050 and romance has long gone, relationships exist solely for practicality.
MatchMyHusband is a website that matches busy working women with perfect house husbands.
You have been employed by Matc... |
from numpy.core.umath import sign
from numpy.ma import exp
import numpy
from pylab import *
from scipy import linalg
from PIL import Image
class Camera(object):
""" Class for representing pin-hole cameras. """
def __init__(self, P):
""" Initialize P = K[R|t] camera model. """
self.P = P
... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 4 11:19:37 2021
@author: anusk
"""
import cv2
import numpy as np
import scipy.interpolate as spi
from matplotlib import pyplot as plt
def EBMA(targetFrame, anchorFrame, blocksize):
accuracy = 1
p =16
frameH, frameW = anchorFrame.shape
print(anchorF... |
'''
# -*- coding: utf-8 -*-
Copyright of DasPy:
Author - Xujun Han (Forschungszentrum Juelich, Germany)
x.han@fz-juelich.de, xujunhan@gmail.com
DasPy was funded by:
1. Forschungszentrum Juelich, Agrosphere (IBG 3), Juelich, Germany
2. Cold and Arid Regions Environmental and Engineering Research Institute, Chinese Aca... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 04 15:53:04 2017
11/01/2017
add_oc - changed xtalk dependence from 2*sqrt(i) i
12/01/2017
removed round() in add_oc
improved hparm() to allow bins, range[0] and binwidth to define
thresh set to 0 - threshing only necessary for prior processed area d... |
# -*- coding: utf-8 -
from .api import ClientAPI
from .api import TodoAppApiException
from .api import Token
__all__ = ["ClientAPI", "TodoAppApiException", "Token"]
|
### stacked RNN ###
import tensorflow as tf
import numpy as np
from tensorflow.contrib import rnn
tf.set_random_seed(777)
tf.reset_default_graph() ## reset
sentence = ("if you want to build a ship, don't drum up people together to "
"collect wood and don't assign them tasks and work, but rather "
... |
from os import EX_OSFILE
import sqlite3
db_name = "table_edu.db"
def sql(query, values=(), return_data=False):
""" return_data=False.. insert or update
return_data=True select data... list[2]: 0-> keys 1-> values """
if return_data == True:
data = None
with sqlite3.connect(db_n... |
import numpy as np
class Fmeasure:
def __init__(self, relnum, beta = 1.0):
self.relnum = relnum
self.beta = beta
def gain(self, node):
# original f
original_f = self._f(node.instances)
# prepare
data_dict = {}
for d in node.instances:
data_di... |
fruit="banana"
letter=fruit[1]
print(letter)
x=3
w=fruit[x-1]
print(w)
|
from datetime import datetime
from collections import namedtuple
from django.shortcuts import render
from django.views.generic import TemplateView
from django.shortcuts import redirect
from django.db.models import Q
from .models import Room, Booking, Checkin
class AdminView(TemplateView):
template_name = 'admin... |
"""boloIndya URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-bas... |
from .serializer import resident, securityGuard
def jwt_response_payload_handler(token, user=None, request=None):
return {
'token': token,
'user': resident.UserSerializer(user).data,
}
def sjwt_response_payload_handler(token, user=None, request=None):
return {
'token': token,
... |
# -*- coding: utf-8 -*-
#폴더 내 각각의 .json파일에 대괄호로 묶기.
import os
import glob
print("이름입력하시오!:"+'\n')
names = input()
path = '/Users/junha_lee/Documents/Junha/School/Projects/SentimentName/sentiment/tmp_twitter/'+names
extension = 'json'
os.chdir(path)
result = [i for i in glob.glob('*.{}'.format(extension))]
for file ... |
cars = {
'Ford' : 'Mustang',
'Nissan' : 'Sunny',
'Toyota' : 'Corolla',
'Bugatti' : 'Veyron'
}
def add_car(make: str, model: str):
cars[make] = model
while True:
choice = input(
"""
Here are some cars.
To display the cars, select 1.
To add a car, select 2.
To quit, select ... |
"""
SceneManager is a collection of classes and functions written in Python for use with Pygame.
SceneManager is pronounced "pig helpers".
Developed by Irv Kalb - Irv at furrypants.com
Full documentation at: https://SceneManager.readthedocs.io/en/latest/
SceneManager contains the following classes:
- Timer - ... |
import boto3
import os
import random, string
from dotenv import load_dotenv
load_dotenv(".env")
dynamodb = boto3.resource("dynamodb",
aws_access_key_id= os.getenv("ACCESS_KEY_ID"),
aws_secret_access_key= os.getenv("ACCESS_SECRET_KEY"),
region_name= os.getenv("REGION")
#aws_session_token= ... |
# Copyright (c) 2017-2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from typing import Any, Collection, NewType, Sequence, Union, overload
from .basic import to_str
__all__ = ["Party", "to_party", "to_parties... |
class Base_Model(object):
default_float = None
default_int = None
def __init__(self):
return
def to_percent_with_diff(self, initial_value: float, difference: float) -> float:
change = initial_value + difference
return round(((change - initial_value) / initial_value) * 100, 2)
... |
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
url = "http://pythonscraping.com/pages/page3.html"
html = urlopen(url)
obj = BeautifulSoup(html, "lxml")
def main():
images = obj.findAll("img", {"src": re.compile("\.\.\/img\/gifts/img.*\.jpg")})
print(images)
for image in images... |
__author__ = 'QC1'
from main.page.android.andr_pe_index import *
class ActivityLogout():
def do_logout(self, driver):
index_page = PageIndex(driver)
print("Logging out. . .")
index_page.tap_logout()
|
# Copyright (C) 2012-2013 Claudio Guarnieri.
# Copyright (C) 2014-2018 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
import random
import re
import logging
import threading
from lib.common.abstracts import Auxiliary
from l... |
import sys
import os
import subprocess
sys.path.insert(0, 'scripts')
import experiments as exp
import fam
def run_concasteroid(dataset, subst_model, is_dna, cores, additional_args = []):
command = []
command.append(exp.python())
command.append(os.path.join(exp.scripts_root, "asteroid/launch_concasteroid.py"))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.