text stringlengths 38 1.54M |
|---|
from utils.utils import create_dataset, Trainer
from layer.layer import Embedding, FeaturesEmbedding, EmbeddingsInteraction, MultiLayerPerceptron
import torch
import torch.nn as nn
import torch.optim as optim
from DIN import BaseModel
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
pr... |
from __future__ import division
from math import sin, cos, acos, asin, degrees, pi
import serial
from time import sleep
import numpy as np
from scipy.interpolate import splprep, splev, splrep
class Skycam:
''' Represents entire 3-node and camera system. Contains methods to calculate
and initialize paths, c... |
import math as m
f_values_1 = [0, 0.062057145, 1.0558914326, 5.3775128776, 17.0202629818, 41.5748215863, 86.2292060414, 159.7687706061, 272.5762067482, 436.6315430847, 665.5121453814, 974.3927165529, 1380.0452966628, 1900.8392629238, 2556.7413296971, 3369.3155484932, 4361.7233079714]
f_values_2 = [0, 1.0558914326, 1... |
#!/usr/bin/python3
"""calculates the fewest number of
operations needed for the end result"""
def minOperations(n):
counter = 0
if n <= 1:
return counter
for i in range(2, n + 1):
while n % i == 0:
++counter
j = int(n / i)
return minOperations(j) + i
|
"""
Generic plot functions based on matplotlib
"""
from __future__ import absolute_import, division, print_function, unicode_literals
try:
## Python 2
basestring
except:
## Python 3
basestring = str
import numpy as np
import pylab
import matplotlib
from matplotlib.font_manager import FontProperties... |
# -*- coding:utf-8 -*-
# author: hpf
# create time: 2020/11/11 17:19
# file: 92_反转链表II.py
# IDE: PyCharm
# 题目描述:
# 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
#
# 说明:
# 1 ≤ m ≤ n ≤ 链表长度。
#
# 示例:
#
# 输入: 1->2->3->4->5->NULL, m = 2, n = 4
# 输出: 1->4->3->2->5->NULL
# 解法一: 递归
# Definition for singly-linked list.
class ListNode:
def... |
"""
Plot barycentric
"""
import numpy as np
from mpl_toolkits.mplot3d import Axes3D, art3d
from scipy.spatial import ConvexHull
from itertools import combinations
import seaborn as sns
import matplotlib.pyplot as plt
from dreye.utilities.barycentric import (
barycentric_to_cartesian,
barycentric_dim_reduction... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
# Register your models here.
from .models import Customer, Merchant, MerchantType, TransactionType, Currency, AccountCategory, Account
from .models import AccountSnapshot, Transaction
class AccountSnapshotAdmin(admin.Mo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
from setuptools.extension import Extension
# Force `setup_requires` Cython to be installed before proceeding
from setuptools.dist import Distribution
except ImportError:
print("Couldn't import setu... |
from codecs import open
from os import path
# Always prefer setuptools over distutils
from setuptools import find_packages, setup
here = path.abspath(path.dirname(__file__))
about = {}
with open(path.join(here, "bk_monitor_report", "__version__.py"), "r", encoding="utf-8") as f:
exec(f.read(), about)
long_descri... |
"""
Compute subpixel bias in localization data.
Subpixel bias in localization coordinates may arise depending on the
localization algorithm [1]_.
References
----------
.. [1] Gould, T. J., Verkhusha, V. V. & Hess, S. T.,
Imaging biological structures with fluorescence photoactivation
localization microscopy. Na... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time
#smtp import
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encode... |
# coding: utf-8
# ### Add upstream, downstream and basin PFAF_ID to database
#
# * Purpose of script: create a table with pfaf_id and upstream_pfaf_id, downstream_pfaf_id and basin_pfaf_id
# * Author: Rutger Hofste
# * Kernel used: python35
# * Date created: 20171123
#
#
# The script requires a file called .passwo... |
#encoding=utf-8
""" ``views`` module.
"""
## wheezy
from wheezy.http import HTTPResponse
from wheezy.http import HTTPRequest
from wheezy.web.handlers import BaseHandler
## project
#from config import cached
#from database import db_session
#from models import Greeting
#from repository import Repository
#from valid... |
from django.http import HttpRequest, HttpResponse
from zerver.decorator import webhook_view
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
from zerver.lib.validator import WildValue, check_string, to_wild_value
from zerver.lib.webhooks.common import check_send_we... |
from os import getlogin
########################## GLOBAL CONST #######################################
USR_NAME = getlogin()
PYAGN_PATH = "/home/{}/Documents/PyAgain/manager".format(USR_NAME)
PR_LIST_PATH = PYAGN_PATH + ".pr_list"
LOOP = True
PROMPT = "[PyAgain] "
USR = ("<{}>".format(USR_NAME))
YES = ["yes", "Y... |
# -*- coding: utf-8 -*-
"""Main module."""
# import configparser
# import os
# cp = configparser.ConfigParser()
# txtpath = os.path.dirname(os.path.abspath(__file__))+'/config.txt'
# try:
# with open(txtpath) as f:
# cp.read_file(f)
# token = cp.get('Config','password')
# prin... |
import pandas as pd
import numpy as np
def generate_features():
movie_industry = pd.read_csv("../data/movie_industry.csv", encoding = "ISO-8859-1" )
movie_industry = movie_industry[movie_industry.year >= 2007]
directors2007 = np.unique(movie_industry.director.values)
actors2007 = np.unique(movie_indust... |
#Print Generators Performance
import random
import time
#import memory_profiler
names=['Mark','Steve','Charles','Ramesh','Tom']
majors=['Computer Science','Math','Biology','Chemistry','Art','Electrical']
def person_list(num):
result = []
for i in range(num):
person = {
'id': i,
... |
import tensorflow as tf
import numpy as np
from tfModels.layers import residual, conv_lstm
from tfModels.tensor2tensor.common_layers import layer_norm
from .processor import Processor
class CONV_Processor(Processor):
def __init__(self, is_train, args, name='conv_processor'):
self.num_cell_units = args.mo... |
import pandas as pd
import shutil
import os
data = pd.read_json('dfdc_train_part_49/metadata.json')
data = data.T
data['file'] = data.index
files = os.listdir('dfdc_train_part_49/audio')
for i in range(len(files)):
for x in range(len(data.file)):
if files[i].split('.')[0]==data.file[x].split(... |
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from classes.views import (classroom_update,classroom_delete,
classroom_create,classroom_detail,classroom_list)
from API.views import (ListView,DetailView,UpdateView,DeleteView,Crea... |
from ftw.upgrade import UpgradeStep
class AddOGDSSyncConfiguration(UpgradeStep):
"""Add OGDS sync configuration.
"""
def __call__(self):
self.install_upgrade_profile()
|
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def loadData(filename):
df = pd.read_table(filename, '\t', header=None)
return np.array(df.loc[:,0:1]), np.array(df.loc[:,2])
def showData(X, y, w=None, b=None):
plt.scatter(x=X[:,0], y=X[:,1], c=y)
i... |
from django.urls import path
import spendings.room_api.views as views
urlpatterns = [
path("<int:room_id>/state/", views.room_state),
path("<int:room_id>/spendings/", views.room_spendings),
path("<int:room_id>/depts/", views.room_depts),
path("<int:room_id>/settlements/", views.room_settlements),
... |
'''
@Author: your name
@Date: 2020-02-29 09:53:57
@LastEditTime: 2020-02-29 11:17:41
@LastEditors: Please set LastEditors
@Description: In User Settings Edit
@FilePath: /pyenv/numpy/np7.py
'''
import numpy as np
# 71. 对于给定的 5x5 二维数组,在其内部随机放置 p 个值为 1 的数:
p = 3
Z = np.zeros((5, 5))
np.put(Z, np.random.choice(range(5*5)... |
import itertools
import time
def coordinates(length, width):
return itertools.product(range(length), range(width))
def neighbours(xy, graph_len):
x, y = xy[0], xy[1]
neighbour_list = []
if x != 0:
neighbour_list.append((x-1, y))
if x != graph_len-1:
neighbour_list.append((x+1, y))
... |
from django.contrib import admin
from .models import productSold
# Register your models here.
admin.site.register(productSold) |
from queue import Queue as PythonQueue
class Queue:
def __init__(self, max_size) -> None:
self.max_size: int = max_size
self.data = [None] * max_size
self.head: int = -1
self.tail: int = -1
def is_empty(self) -> bool:
return self.head == -1
def is_full(self) -> bo... |
import logging
CONSIDER_NEIGHBORING_NODES_AS_CONTEXT = 6 # defines the number of links the surrounding to consider as neighbouring nodes
class Decider:
'''The Decider class takes the several metrics into account and
identifies a meaning for each link that is most likely to be the correct one in the
... |
# coding=utf-8
import os
import sys
import django
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # 把manage.py所在目录添加到系统目录
os.environ['DJANGO_SETTINGS_MODULE'] = 'AJoke.settings' # 设置setting文件
django.setup()
from records.models import CSInfo, InterfaceLogs
from ENVS import DICT_TOKEN_PA... |
import math
def isPrime(n):
for i in range(2,int(math.sqrt(n))+1):
if n%i==0:
print('i= ',i)
return 0
num=int(input('Enter a integer number (2~32767): '))
result=isPrime(num)
if result==0:
print('{} is not prime' .format(num))
else:
print('{} is prime' .format(num... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 5 14:58:52 2017
@author: lracuna
"""
from vision.camera import Camera
from vision.rt_matrix import *
import numpy as np
from matplotlib import pyplot as plt
#%%
# load points
points = np.loadtxt('house.p3d').T
points = np.vstack((points,np.ones(points.shape[1])))
#%%... |
def get_countries_data():
return {
'Albania': {
'eventName': 'Festivali i Këngës',
'watchLink': 'https://www.rtsh.al/rtsh-live/RTSH1-HD.html',
'stages': ['Night...', 'Final'],
"altEventNames": ["FiK"]
},
'Andorra': {
'eventName': '-... |
# -*- coding: utf-8 -*-
import scrapy
import hashlib
class ParliamentSpider(scrapy.Spider):
name = 'parliament'
source_title = 'House of Commons'
source_link = 'https://www.parliament.uk/site-information/foi/foi-and-eir/commons-foi-disclosures/'
allowed_domains = ['www.parliament.uk']
start_urls =... |
import torch
from deeprobust.graph.targeted_attack import BaseAttack
from torch.nn.parameter import Parameter
from copy import deepcopy
from deeprobust.graph import utils
import torch.nn.functional as F
import numpy as np
from copy import deepcopy
import scipy.sparse as sp
class RND(BaseAttack):
"""As is described... |
import random
import string
def generate_random_string(chars=None, length=4):
"""
Used by various services to create easy to remember
room codes.
:param chars: List of string, Characters to use if provided, otherwise just upper and lower case
:param length: Integer, The length the generated string... |
import sys
import re
from porterStemmer import PorterStemmer
from collections import defaultdict
import copy
porter=PorterStemmer()
class QueryIndex:
def __init__(self):
self.index={}
self.titleIndex={}
#term frequencies
self.tf={}
#inverse document frequencies
sel... |
from flask import Blueprint, jsonify
from app.models.ability import Ability
from app import db
blueprint = Blueprint('ability_api', __name__, url_prefix='/api/ability')
@blueprint.route('/')
def list():
abilities = db.session.query(Ability).all()
return jsonify(columns=['name', 'description'], data=[[ability... |
import argparse
from besttags import Manager
def main():
parser = argparse.ArgumentParser(
description="Get the best hashtags for your post")
parser.add_argument('tags', nargs='+',
help="The tags you are interested in")
parser.add_argument('--fix', nargs='+',
... |
def solution(S, K):
# write your code in Python 3.6
newString = ''
count = 0
for i in range(0, len(S)):
if (count == K):
newString += '-'
count = 0
# i = i + 1
if (S[i] != '-'):
newString += S[i]
count = count + 1
newString2... |
import json
import random
config_file = 'article_app/content_api.json'
stock_file = 'article_app/quotes_api.json'
# Create Controller additions here
def process_config_file(config = config_file):
import os
print(os.getcwd())
with open(config) as json_file:
data = json.load(json_file)
return d... |
import os
from globus_sdk.exc import GlobusSDKUsageError
def _on_windows():
"""
Per python docs, this is a safe, reliable way of checking the platform.
sys.platform offers more detail -- more than we want, in this case.
"""
return os.name == "nt"
class LocalGlobusConnectPersonal(object):
r"... |
import inspect
from models.tf_scikit_template import BaseTfScikitClassifier
from models.classifier.oselm import OSELM
class SciKitOSELM(BaseTfScikitClassifier):
def __init__(self,
input_dim=None,
output_dim=None,
hidden_num=None,
batch_size=None, ... |
#!/usr/bin/python
from Edge import Edge
from GreedyEdgeSelection import GreedyEdgeSelection
from GreedyTreeGrowing import GreedyTreeGrowing
def loadGraphFrom(filename):
f = open(filename, 'r')
V = int(f.readline())
#print V
ELines = f.readlines()
E = []
for el in ELines:
e = Edge(el)
... |
# Copyright (c) Ralph Meijer.
# See LICENSE for details.
"""
XMPP Component Service.
This provides an XMPP server that accepts External Components connections
and accepts and initiates server-to-server connections for the specified
domain(s).
"""
from twisted.application import service, strports
from twisted.python ... |
# -*- coding: utf-8 -*-
from django.test import TestCase, Client
from django.utils import timezone
from .models import Bitcoin
class TestPages(TestCase):
def setUp(self):
for i in range(3, 600, 5):
Bitcoin.objects.create(
price=i,
time=timezone.now() - timezone... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from opyscad import *
import config, bed, vertex, screw
height = bed.bar2bed_h
length = 100.0
bed_mount_dy = 43.0
bed_mount_dx = bed.l - bed.hole_dx
screw = screw.m3
hole_l = 6.0
bed_hole_dx = 10.0
bar_hole_dx = 10.0
nut_depth = 2.75
def create():
bar_mount_dx = vertex.... |
import pycom
import socket
import ssl
import sys
import time
from network import LTE
BLACK = 0x000000
WHITE = 0xFFFFFF
RED = 0xFF0000
GREEN = 0x00FF00
BLUE = 0x0000FF
YELLOW = 0xFFFF00
# send AT command to modem and return response as list
def at(cmd):
print("modem command: {}".format(cmd))
r = lte.send_at_cm... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 1 10:51:11 2018
@author: junseon
"""
import functools
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers.normalization import BatchNormalization
from keras import back... |
import logging
import json
from flask import render_template
from flask_wtf import Form
from wtforms import fields
from wtforms.validators import Required
import pandas as pd
from . import app, estimator, target_names
from violent_fe import feature_engineer
logger = logging.getLogger('app')
class PredictForm(For... |
from reservation.reservation_handler import _ReservationHandler
from reservation.reservation_result import ReservationResult
class ReservationHandlerUseList(_ReservationHandler):
def allows_reservation(self, other_reservation_handler):
return ReservationResult.TRUE
|
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def sortList(self, head):
pass
def merge(self, l, r):
if l is None:
return r
if r is None:
return l
result = None
if l.val < r.val:
... |
# Generated by Django 2.0.1 on 2018-01-17 02:03
import django.contrib.gis.db.models.fields
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Letters',
fields... |
__author__ = 'Josh'
import os
import urllib
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
vowels = ['a', 'e', 'i', 'o', 'u']
consonants = [x for x in alphabet if x not in vowels]
def join_with_spaces(lst):
#joins togethe... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def create_list(arr):
if len(arr) == 0:
return None
head = None
tail = None
for x in arr:
new_node = ListNode(x)
if not head:
head = new_node
tail = new_node
... |
import pandas as pd
reader = pd.read_csv('C:/bank/data_set/analyze/social.csv')
reader2 = reader.set_index('month', drop=False)
# print(reader2.index.unique().values[2])
# print(reader2.loc['mar', 'cons.conf.idx'].value_counts())
# print(reader2['month'].value_counts())
def printtttt(df):
idx_q = df.in... |
# Dependencies
from splinter import Browser
from bs4 import BeautifulSoup as bs
import pymongo
import pandas as pd
import time
import os
# trying Splinter
def init_browser():
# chromedriver = os.getenv(str(os.environ.get('CHROMEDRIVER_PATH')), "chromedriver.exe")
# executable_path = {"executable_path": chromed... |
# Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
"""
Utilities module (internal)
This module contains a number of tools that help with the interface for this
plugin. This contains things such as the multicase decorator, the matcher
class for querying and filtering lists of things, support for aliasing
functions, and a number of functional programming primitives (com... |
from matplotlib.pyplot import *
x, y1, y2, y3 = [], [], [], []
for i in range(11):
x.append(i)
y1.append(i)
y2.append(i ** 2)
y3.append(i ** 3)
plot(x, y1,"r--", label="x")
plot(x, y2,"go", label="y^2")
plot(x, y3,"bs", label="y^3")
axis([0, 10, 0, 100])
title("my diagram dajumm")
xlabel("x")
ylabel("y... |
from configs import sac_default as default_lib
def get_config():
config = default_lib.get_config()
config.tau = 1.0
config.target_update_period = 50
return config
|
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
key points:
1.善用 for k,v in dTlb.items():
2. sorted(“cba”) 回傳['a','b','c']
class Solution(object):
def groupAnagrams(self, strs... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.views.generic import View
from django.shortcuts import render_to_response
from fuzzyapp.database import fuzzyQuery, convert_fuzzy
from fuzzyapp.models import Materia
from fuzzyapp.forms import FiltroMateriasForm, AgruparMateriasForm
class L... |
# TODO(colin): fix these lint errors (http://pep8.readthedocs.io/en/release-1.7.x/intro.html#error-codes)
# pep8-disable:E128
"""Backend of API Explorer
Serves as a proxy between client side code and API server
"""
import cgi
import json
import logging
import sys
import flask
import oauth
import werkzeug.debug
impo... |
from django.urls import path
from .views import HomePagesView, AboutPageView
urlpatterns = [
path('about/', AboutPageView.as_view(), name='about'),
path('', HomePagesView.as_view(), name='home'),
] |
import numpy as np
import matplotlib.pyplot as plt
from code_base.classifiers.cnn import *
from code_base.data_utils import get_CIFAR2_data
from code_base.layers import *
from code_base.solver import Solver
data = get_CIFAR2_data()
for k, v in data.items():
print('%s: ' % k, v.shape)
model = ThreeLayerConvNet(num_c... |
from django.test import TestCase
from bookmarks.models import Bookmark, Folder
from django.urls import reverse
class BookmarkListViewTest(TestCase):
@classmethod
def setUpTestData(cls):
folder1 = Folder.objects.create(name="Folder11")
folder2 = Folder.objects.create(name="Folder2")
al... |
from rest_framework.permissions import BasePermission
from .models import Article
class IsAuthenticatedAndOwner(BasePermission):
def has_permission(self, request, view):
if request.user.is_authenticated:
print('---->', 'request.user.is_authenticated', request.user.is_authenticated)
... |
"""
Methods for manipulating winched profiler data.
Tuomas Karna 2013-01-17
"""
import numpy as np
from scipy.interpolate import interp1d
from crane.data import dataContainer
from crane.data import timeArray
def generateSat01ProfilerModData(obsWProfilerDC, modProfileDC):
# merge time ranges
tmin = max(obsWP... |
import pandas as pd
from utils_data import create_calibrated_df
from utils_mturk import get_list_id_within_doc, prepare_df_for_evaluation, perform_evaluation
# data preparation
df_results_mturk = pd.read_csv('data/pairwise_race_cs.csv')
# Single models
for random_seed in [0, 3, 42]:
df_predictions = create_calib... |
import os
from libavg.utils import getMediaDir, createImagePreviewNode
from . import schubser
__all__ = [ 'apps', ]
def createPreviewNode(maxSize):
filename = os.path.join(getMediaDir(__file__), 'preview.png')
return createImagePreviewNode(maxSize, absHref = filename)
apps = (
{'class': schubser.Schu... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import unicode_literals
from abc import (
ABCMeta,
abstractmethod,
)
import os
import sys
fro... |
from __future__ import division
import numpy as np
import copy
from cwc.evaluation.metrics import average_cross_entropy
from sklearn.svm import SVC
from sklearn.preprocessing import label_binarize
from scipy.optimize import minimize
from ovo_classifier import OvoClassifier
from confident_classifier import Confident... |
import cv2 as cv
import numpy as np
img=cv.imread('i.png')
cv.imshow('Picture',img)
## Converting to GrayScale
#gray= cv.cvtColor(img,cv.COLOR_BGR2GRAY)
#cv.imshow('Grayscale',gray)
## blur
#blur=cv.blur(img,(5,5),borderType=cv.BORDER_DEFAULT)
#cv.imshow('Blur',blur)
## Edge Cascade
#canny=cv.C... |
from nitrogen_db_client import NitrogenDbClient
from odd import Odd
from pro_match import ProMatch
def embed_all():
cursor = ProMatch.get_all_matches()
print cursor.count()
for m in cursor:
print "here"
match = ProMatch.from_dict(m)
odds_cursor = Odd.get_odds_for_match(match.id)
for o in odds_cursor:
ma... |
from flask import Flask, render_template,request
import streamlit as st
def praxis():
st.title("Learning Streamlit")
name = st.text_input("student_name","Type here")
num = st.text_input("roll_no","Type here")
result = ""
if st.button("Show Result"):
st.success(f"The Student name is {name} w... |
from PyQt5 import QtCore, QtGui, QtWidgets
import pandas as pd
import datetime
from talib import SMA,STDDEV
import numpy as np
class MABolClass():
def BuyAndHold(self, ui, KBar):
self.ui = ui
# 初始資金
InitCapital=1000000
OrderPrice = None
OrderQty = 0
CoverPrice = N... |
from math import sqrt
def inputvars():
f = open('input.txt')
num = int(f.readline())
numlist = f.readline().split()
return int(numlist[0]), int(numlist[1])
def outputvars(num, output):
f = open('output.txt', 'w')
f.write('Case #1:\n')
for x in range(num):
f.write(str(output[x]) + '\n')
f.close()
... |
print ('Calculando a área do círculo.')
print()
pi = 3.14
raio = float(input('Para começar o calculo da área do circulo, informe o raio em cm: '))
print(f'Já sabemos que PI é uma constante e vale {pi}.')
A = pi * (raio * raio)
print()
print(f'A área do circulo com raio = {raio}² multiplicado por PI ({pi}) é igual a {A}... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Commands.
"""
from ergo.core import Command, COMMANDS
from aochat.aoml import *
### CALLBACKS ##################################################################
def help_callback(chat, player, args):
if args and args[0] in COMMANDS:
command = COMMANDS[ar... |
import matplotlib
import matplotlib.pyplot as plt
import json
import os
matplotlib.rcParams['font.family'] = "Times New Roman"
matplotlib.rcParams['font.size'] = 10
nbins=8
# fig_dir = os.getcwd()
fig_dir = "/Users/crankshaw/ModelServingPaper/osdi_2016/figs"
f = open('../results/cache_error.json','r')
res = json.loa... |
def find(N, K):
data = [0]
i = 1
while i < N:
size = len(data)
for j in range(size):
c = data[j]
if c == 0:
data.append(1)
else:
data.append(0)
i += 1
return data[K - 1]
if __name__ == '__main__':
print(fin... |
#!/usr/bin/env python3
import logging
import math
from math_helpers import pgcde
from prime import _getPrime
from multiprocessing import Process, Pipe, cpu_count, Queue
import base64
class RSA(object):
"""RSA main class"""
def __init__(self, size=4096):
# prime number
self.p, self.q = 2, 3... |
# Calculates the number of fruits that can be collected
def fruit_baskets(fruits):
totals_array = []
for i in range(0, len(fruits) - 1):
j = i
fruit = fruits[i]
one = fruits[i]
two = fruits[i+1]
total = 0
while fruit == one or fruit == two:
total += 1... |
"""
Class for manipulating with page https://sgpano.com/create-new-virtual-tour/
"""
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from Lib.common.NonAppSpecific import send_text, check_if_elem_exist
from... |
import os
import sys
import subprocess
if (len(sys.argv) < 2):
print("Usage: python3 walk_stack.py <.dmp file>")
exit(1)
dmp = sys.argv[1]
syms = [f for f in os.listdir(os.getcwd()) if f.endswith(".sym")]
minidump_stackwalk = os.path.dirname(os.path.realpath(__file__)) + "/minidump_stackwalk"
for sym in syms... |
print("Hey how is it going?")
statement = input()
while statement != "stop copying me":
print(statement)
statement = input()
print("UGH FINE YOU WIN")
|
#!/usr/bin/env python
# coding=utf-8
import sys
#find result
import sys
count = 0.0
current_key = -1
Pt_sum = 0
event_files = set()
for line in sys.stdin:
key,value = line.split('\t')
key = int(key)
if key != current_key:
if current_key != -1:
print("{0},{1},{2}".format(current_k... |
from django.shortcuts import redirect, render, get_object_or_404
from todoapp.models import Category, TodoList
from .forms import CreateTask
def index(request):
todos = TodoList.objects.all()
return render(request, "todoapp/todo.html", {'todos': todos})
def create_task(request):
query_results = Category... |
"""
MWHair - Mediawiki wrapper
Description - This is a mediawiki client written by Hairr <hairrazerrr@gmail.com>
It was orignally created to be used at http://runescape.wikia.com/
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as publish... |
from atcoder.dsu import DSU
N = int(input())
sx, sy, tx, ty = (int(x) for x in input().split())
cs = []
for _ in range(N):
x, y, r = (int(x) for x in input().split())
cs.append((x,y,r))
dsu = DSU(N)
for i in range(N):
for j in range(i+1,N):
x1, y1, r1 = cs[i]
x2, y2, r2 = cs[j]
ds = (x1-x2)**2 + (y1... |
import argparse
import csv
import os
import math
from scipy import stats
# PROJECTS = ['Closure', 'Lang', 'Chart', 'Math', 'Mockito', 'Time']
PROJECTS = ['Math']
# PROJECT_BUGS = [
# [str(x) for x in range(1, 134)],
# [str(x) for x in range(1, 66)],
# [str(x) for x in range(1, 27)],
# [str(x) for x i... |
import pymysql
def connect():
#conn = pymysql.connect("opencab1.miniserver.com","3306","ok_gopi","Optometry123","ok_mcd")
conn = pymysql.connect(host='opencab1.miniserver.com', user='ok_gopi', passwd='Optometry123', db='ok_mcd', charset='utf8', port=3306)
cur = conn.cursor()
try:
cur.execute("C... |
from scenario import *
import matplotlib
from matplotlib import animation
pl = plane(np.array([0,0,0,0]), normal=np.array([1,0,0,0]))
import time
rout = routine(f=goof, tInit=0,tFinal=10000, y0=qp0, ordinaryStepLen=1e-1,method="StV",timeline=True, savePlaneCuts=True, nopythonExe=True, timelineJumps=30)
startT = tim... |
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
import gym
import tflearn
from collections import deque
from policy_gradient.ddpg import Actor, Critic, OrnsteinUhlenbeckActionNoise
from policy_gradient.memory import SequentialMemory
tf.app.flags.DEFINE_string('checkpoint', '', 'load... |
import pandas as pd
from django.db import DatabaseError, transaction
from items import models as activoM
from proveedores.models import Proveedor
from operaciones.models import MANTENIMIENTO_CHOICES, Operacion
from django.contrib.auth.models import User
def choiceHelper(x,choices,default):
# y choices
for... |
from typing import List, Iterable, Callable, Dict, Tuple, Set
from matplotlib import pyplot as plt
from sklearn.metrics import precision_recall_curve, auc
from contradiction.medical_claims.cont_classification.path_helper import load_raw_predictions
from contradiction.medical_claims.token_tagging.acc_eval.path_helper ... |
from typing import Tuple
import enum
class Side(enum.Enum):
def __new__(cls, tl, tr, axis) -> Side: ...
UP = ()
DOWN = ()
NORTH = ()
SOUTH = ()
EAST = ()
WEST = ()
@property
def tl(self) -> int: ...
@property
def br(self) -> int: ...
@property
def ids(self) -> ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 24 19:20:29 2017
@author: thodoris
"""
import pandas
import numpy
import os
import copy
import core
from sklearn.model_selection import ParameterGrid
from sklearn.model_selection import train_test_split
from sklearn.model_selection import StratifiedKFold
from sklearn i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.