text stringlengths 8 6.05M |
|---|
# http://www.bmfbovespa.com.br/pt_br/servicos/market-data/historico/mercado-a-vista/cotacoes-historicas/
import pandas
import datetime, shelve
import collections
import bovespa
import numpy as np
from sklearn.externals import joblib
from sklearn.preprocessing import Normalizer
def ReadData(filePath):
## This fu... |
__author__ = 'Alexey'
from graph_tools.graph_builder import build_random_graph
from graph_tools.graph_drawer import draw_graph
n = input("Enter vertices number: ")
p = input("Enter probability: ")
if type(n) != int or type(p) != float:
print "Your input is invalid, sorry :C Try again?"
exit(1)
vertices, adja... |
from sklearn.datasets import load_boston
dataset = load_boston()
dir(dataset)
print(dataset['DESCR'])
dataset['data'].shape
import seaborn as sns
import pandas as pd
dataframe = pd.DataFrame(dataset['data'])
dataframe.columns = dataset['feature_names']
dataframe
import matplotlib.pyplot as plt
dataframe.corr(... |
# paper tables -- Mark
import pandas as pd
cb_1979_2007_avg = pd.DataFrame({'table2':{'freezeup_start': '10-16',
'freezeup_end': '11-12',
'breakup_start': '05-28',
'breakup_end': '08-01',}})
cb_1979_2013_clim = pd.DataFrame({'table3':{'freezeup_start': '10-09',
'freezeup_end': '12-01',
'... |
# using SendGrid's Python Library
# https://github.com/sendgrid/sendgrid-python
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
from flask import Flask
app = Flask(__name__)
app.secret_key = "super secret key"
from gcp_utils import get_secret
# Imports the Google Cloud client l... |
#! /usr/bin/env python3
# coding=utf-8
import hashlib
from lxml import etree
try:
from .resume_base import BaseExtract
except:
from resume_base import BaseExtract
import time
import re
from core.base import Base
from config import SITE_SOURCE_MAP
import json
from copy import deepcopy
def first(tree_res):
... |
from django import template
register = template.Library()
@register.filter('break')
def break_(loop):
raise StopLoopException(loop, False)
|
# encoding: utf-8
class Table(object):
def config_db(self,pkg):
tbl=pkg.table('persona', pkey='id', name_long='Persona', name_plural='Persone',caption_field='nominativo')
self.sysFields(tbl)
tbl.column('cognome', size=':30', name_long='Cognome',validate_case='c')
tbl.column('nome', ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-08-15 13:52
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('messaging', '0006_auto_20160814_2145'),... |
# [23/3] Exception handling in Python
def divide(a,b):
try:
return a/b
except ZeroDivisionError: # always specify type of error exception
return ("You are dividing by zero")
except TypeError:
return ("Wrong data type")
print(divide(2,0))
print("End of the program")
|
from onegov.form.models import FormDefinition
from onegov.reservation import Resource
from onegov.directory import Directory
from onegov.org.models.file import ImageSet
from onegov.org.models.page import News, Topic
from sqlalchemy.orm import defer
class SiteCollection:
def __init__(self, session):
self.... |
# Modified work:
# -----------------------------------------------------------------------------
# Copyright (c) 2015 Preferred Infrastructure, Inc.
# Copyright (c) 2015 Preferred Networks, Inc.
# -----------------------------------------------------------------------------
# Original work of _roi_pooling_slice, forwa... |
#-*-coding:utf-8-*-
# Author:Lu Wei
class Foo:
def show(self):
print(123)
pass
Foo.show('a')
|
import os
from ftp_data import *
import time
print('\n\ngetting requiremenys.txt\n\n')
filename = 'requirements.txt'
localfile = open(filename, 'wb')
ftp.retrbinary('RETR ' + filename, localfile.write, 1024)
time.sleep(2)
print('\n\nrunning requirements.txt\n\n')
os.system('pip install -r requirements.txt... |
import pytorch_lightning as pl
from datasets import load_dataset
from torch.utils.data import DataLoader
from transformers import AutoTokenizer
def convert_to_features(example_batch, indices, tokenizer, text_fields, padding, truncation, max_length):
# Either encode single sentence or sentence pairs
if len(te... |
import streamlit as st
import requests
import smtplib
from bs4 import BeautifulSoup
import time
def alerter(receiveremail_id,al_price,url):
headers={
'authority': 'www.amazon.in',
'cache-control': 'max-age=0',
'rtt': '200',
'downlink': '3.6',
'ect': '4g',
'sec-ch-ua': '^\\^',
'sec-ch-ua-... |
import torch
a = torch.rand((2,2,2))
print(a)
print(a.size())
unsqe = a.unsqueeze(2)
print(unsqe, unsqe.size()) |
import requests
import argparse
class Valut:
def __init__(self, country):
self.country = country
def get(self):
url = "https://www.cbr-xml-daily.ru/daily_json.js"
data = requests.get(url).json()
valut_data = data["Valute"][self.country]
valut = {
"Country"... |
#!/usr/bin/env python
import sys
import os
import fnmatch
from tvtk.api import tvtk
from numpy.random import randint, rand, permutation
import numpy as np
import time
from optparse import OptionParser
num_objects_in_scene = 8
model_center_square = 1.5
camera_height = 1.5
camera_height_delta = 0.5
camera_rotation_d... |
import threading
import time
from speech_recognition import Microphone, RequestError, WaitTimeoutError, UnknownValueError
import logger
from utils import getResource
class Recorder:
def __init__(self, recognizer, queue):
self.recognizer = recognizer
self.microphone = Microphone()
self.i... |
from decimal import Decimal
from django.conf import settings
from .models import Region
from datetime import datetime
from dateutil.parser import parse as parsedate
class erange(object):
def __contains__(self, dt):
if self.From is not None and dt < self.From:
return False
if self.To ... |
import numpy as np
pi=3.14159265358979323
n=10000
seed=1
const=48271
denom=2.0**31.0-1.0
incir=0.0
for i in range(1-1, n+1, 1):
for j in range(1-1, n+1, 1):
seed=(const*seed)%denom
ran_f=seed/denom
coords1=ran_f
coords2=ran_f
slength=np.sqrt(coords1*coords1+coords2*coord... |
import os
import pwd
import stat
import yaml
from aj.api import *
class BaseConfig(object):
"""
A base class for config implementations. Your implementation must be able to save
arbitrary mixture of ``dict``, ``list``, and scalar values.
.. py:attribute:: data
currenly loaded config content... |
import random
from TargetDB import TargetDB
class Target:
global MAX_IP
MAX_IP = 255
global USABLE_PORTS
USABLE_PORTS = 34434
remotelyConnected = False
deployedExploit = None
global generateIP, generatePortStatus, generatePortsAndServices, initiateDatabase, initiateAliveStatus, selectRandomServices, listOfSe... |
import sublime
import sublime_plugin
#view.run_command('py_help_me')
#ctrl+shift+o pacages/user/Default.sublime-keymap
SCOPE, ICON = "markup.deleted", "dot"
regions = {}
class CodeMarkerClearAllCommand(sublime_plugin.TextCommand):
def run(self, edit):
for key in list(regions):
reg = self.view... |
HILL = 0
TREE = 1
WATER = 2
ROAD = 3
PASTURE = 4
COL_DISPLAY = 7
ROW_DISPLAY = 7
|
import re
regexp = 'a'
s = 'igorosha@gmail.com'
find = re.findall(regexp, s)
print(find)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# python3
from pwn import *
context(log_level = 'debug', arch = 'i386', os = 'linux') # 能显示调试信息
shellcode = asm(shellcraft.sh())
#io = process('./level1')
io = remote('pwn2.jarvisoj.com', 9877)
text = io.recvline()[14: -2] # b"What's this:0xfff06990?\n" 14:-2是 fff06990
#p... |
import rospy
from std_msgs.msg import String
rospy.init_node('no_1')
responde = 'Soma 35132'
def recebe_resposta(resposta):
global responde
responde = resposta.data
def timerCallBack(event):
print(responde)
msg = String()
msg.data = '35132'
pub.publish(msg)
pub = rospy.Publisher('/topic1'... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 8 14:32:27 2018
@author: Kankana Sinha
"""
import pandas as pd
#Task4
#Open the Others.csv file and read it to a Panda's dataframe
filename = 'Others.csv'
df = pd.read_csv(filename , sep = ',')
#Generate all info to create summary table in data quality... |
#!/usr/bin/env python3
import os
from subprocess import getoutput
import unittest
prg = "./hello.py"
class CheckNumbers(unittest.TestCase):
def test_output(self):
out = getoutput(f"python3 {prg}")
self.assertEqual(out, "hello world")
if __name__ == "__main__":
unittest.main()
|
g = (0,255,0)
r = (255,0,0)
x = (0,0,0)
lock_image = [
x,x,x,r,r,x,x,x,
x,x,r,x,x,r,x,x,
x,x,r,x,x,r,x,x,
x,x,r,x,x,r,x,x,
x,r,r,r,r,r,r,x,
x,r,r,r,r,r,r,x,
x,r,r,r,r,r,r,x,
x,r,r,r,r,r,r,x
]
unlock_image = [
x,x,x,g,g,x,x,x,
x,x,g,x,x,g,x,x,
x,x,g,x,x,g,x,x,
x,x,g,x,x,x,x,x,
x,g,g,g,g,g,g,x,
x,g,g,g,g,g,g,x,
x,g,g,g... |
# Created by Inseong on 2018-02-05
from django.urls import path
from . import views
app_name = 'message'
urlpatterns = [
path('messages/', views.message_list, name='messages'),
path('<int:pk>/', views.message_detail, name='message_detail'),
path('delete/<int:pk>', views.delete_message, name='message_delet... |
import dash
import dash_core_components
import plotly.express as px
import pandas as pd
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Output, Input
# Data Exploration with Pandas
df = pd.read_csv("vgsales.csv")
# print(df[200:205])
# print(df.iloc... |
def intro_part_of_the_day(part):
"""Asks for the temperature of the corresponding part of the day"""
correct = False
while correct == False:
try:
part_of_the_day = input(part + ": ")
except TypeError:
pass
else:
if part_of_the_day <= 50 and part_of... |
import random
import operator
NB_MIN = 1
NB_MAX = 50
NB_QUESTION = 4
operators = {
'+': operator.__add__,
'-': operator.__sub__,
'*': operator.__mul__,
'/': operator.__truediv__,
'%': operator.__mod__,
}
def ask_question():
a = random.randint(NB_MIN,NB_MAX)
b = random.randint(NB_MIN,NB_MA... |
#!/usr/bin/env python
# Funtion:
# Filename:
# 开发简单的FTP:
# 1. 用户登陆 #可以完成
# 2. 上传/下载文件
# 3. 不同用户家目录不同
# 4. 查看当前目录下文件
# 5. 充分使用面向对象知识
import socket,os
class Ftp_server(object):
def __init__(self, ip, port):
self.ip = ip
self.port = port
def run_server(self):
server = socket.soc... |
"""empty message
Revision ID: fffeae1bb48c
Revises: 55585c569f52
Create Date: 2018-03-02 16:58:59.159175
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'fffeae1bb48c'
down_revision = '55585c569f52'
branch_labels = None
depends_on = None
def upgrade():
# ... |
# File_name: stop_rds.py
# Purpose: Stop rds instances that are running
# Problems:
# 1. Amazon will autostart rds when stopped for 7 days => auto start stop after 6 days! ( 5.8 days to be sure )
# Author: Søren Wandrup-Bendixen
# Email: soren.wandrup-Bendixen@cybercom.com
# Created: 2019-07-01
# Called from lambda_fu... |
import logging
import argparse
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from ScapyPacketGenerator import *
MTU = 1500
def main(argv):
#initiate class
self = ScapyPacketGenerator()
#declare default values
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--interfa... |
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_prime(x):
return sigmoid(x) * (1 - sigmoid(x))
def j_quadratic(y_pred, y):
return 0.5 * np.mean((y_pred - y) ** 2)
def j_quadratic_derivative(y, y_pred):
return (y_pred - y) / len(y)
class Neuron:
def __init__(self... |
# Simple Linear Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv("Salary_Data.csv")
X = dataset.iloc[:, 0:1]
y = dataset.iloc[:, -1]
# Splitting the dataset into training and test data
# Making test size 1/3rd of... |
#-*- coding:utf8 -*-
from django.contrib import admin
from django.db import models
from django.forms import TextInput, Textarea
from django.http import HttpResponseRedirect
from .models import SaleProduct,SaleSupplier,SaleCategory
from shopback.trades.filters import DateFieldListFilter
class SaleSupplierAdmin(admin.Mo... |
# user inputs
def split_check():
while True:
try:
people = float(input("How many people are splitting the check? "))
if people > 1:
break
else:
raise ValueError
except ValueError:
print('Try that again. Please enter a va... |
from transformers import T5Tokenizer, T5ForConditionalGeneration
from .base_single_doc_model import SingleDocSummModel
class T5Model(SingleDocSummModel):
# static variables
model_name = "T5"
is_extractive = False
is_neural = True
def __init__(self, device="cpu"):
super(T5Model, self).__i... |
#!/usr/bin/env python3
import numpy as np
from scipy.linalg import norm, solve
from itertools import count
from scipy import sparse
def make_system(M):
"""
form the (2^M) x (2^M) system described in (1) with entries
A_{ij} = 3 if j = i
-1 if j = i+1
-1 if j = i-1
... |
from __future__ import unicode_literals
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
import random, re
import spacy
nlp = spacy.load('en')
#--------------------------------------------------------------------------------------------------------------#
def Name_Entity(... |
from PIL import Image
def generic_printer(match_arm_prefix, match_arm_suffix, if_present, if_not_present, end, imports, typeName, fileName):
printstr = imports + '\nuse crate::alphabet::Alphabet;\npub struct ' + typeName + ''' {
}
impl Alphabet for ''' + typeName + ''' {
fn new() -> Self { Self{} }
fn is_... |
#!usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:yaoli
@file: hello.py
@time: 2018/03/16
"""
def application(environ, start_response):
start_response('200 OK',[('Content-Type', 'text/html')])
#http状态码 200 -服务器成功返回网页,OK 一切正常
#404 -请求的网页不存在
#503 -服务不可用 还有一些其他的状态码
body = '<h1>hello, %s!... |
import cv2
import numpy as np
import os
import pandas as pd
file_name = 'bbox.txt'
datafile = open(file_name,"w+")
names = os.listdir()
main_bounding_list=[]
img = cv2.imread('week_15_page_3.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.bilateralFilter(gray, 11, 17, 17)
cv2.imwrite('output4.jpg',gray)
'... |
#!/usr/bin/env python
import numpy as np
import scipy.io as spio
import matplotlib.pyplot as plt
import os.path as ospath
from bbt_svm import get_classifier_filename, get_scaler_filename, disp_acc_metrics
from sklearn.externals import joblib
from bbt_filename import get_feature_filename
from bbt_character import eval_... |
import unittest
class Solution:
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
least_left = len(nums) - 1
for i in reversed(range(len(nums)-1)):
if i + nums[i] >= least_left:
least_left = i
return least_left =... |
import sys
import os
import json
import glob
import tqdm
import traceback
from argparse import ArgumentParser
from typing import Tuple, List, Dict, Any
import torch
from torch.utils.data import DataLoader
from transformers import (BertTokenizer,
BertConfig,
RobertaTo... |
import csv
import matplotlib.pyplot as plt
import math
import pandas as pd
def read_t_1():
fix = []
for i in range(1,10):
f = i/10
with open('data t '+str(f)+' and r0.csv', 'r') as csvnew:
read = csv.reader(csvnew)
for line in read:
fix.append(list(map(f... |
from flask_migrate import Migrate
from os import environ
from sys import exit
from config import config_dict
from app import create_app, db
get_config_mode = environ.get("CROP_CONFIG_MODE", "Production")
try:
config_mode = config_dict[get_config_mode.capitalize()]
except KeyError:
exit("Error: Invalid CROP_C... |
from __future__ import print_function
import os
import sys
import numpy
import tensorflow as tf
from auto_reg_input import *
import matplotlib.pyplot as plt
tf.app.flags.DEFINE_integer('training_iteration', 100,
'number of training iterations.')
tf.app.flags.DEFINE_integer('model_version',... |
a =0
def b():
a+=2
|
from django.shortcuts import render, redirect
from .forms import GeneForm, GeneFormList, DiseaseByGeneForm
from .models import Gene
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from variant_register.models import Variant
from disease_register.models import Disease, ... |
from typing import List, Union
class SummModel:
"""
Base model class for SummerTime
"""
# static variables
model_name = "None"
is_extractive = False
is_neural = False
is_query_based = False
is_dialogue_based = False
is_multi_document = False
is_multilingual = False
de... |
# -*- coding: utf-8 -*-
import scrapy
from ..items import NewsLinkItem
class UtusanNewsLinkSpider(scrapy.Spider):
name = 'utusan_news_link'
allowed_domains = ['www.utusan.com.my']
start_urls = ['http://www.utusan.com.my/berita/terkini',
'http://www.utusan.com.my/berita/jenayah'
... |
from operator import itemgetter
from collections import Counter
from collections import deque
import queue as Q
import math
import copy as c
def solution():
# Write your code here
NM = list(map(int, input().rstrip().split()))
n = NM[0]
m = NM[1]
players = []
for _ in range(n):
player = ... |
import sys
if __name__ == "__main__":
'''
Given: A positive integer n (3≤n≤10000).
Return: The number of internal nodes of any unrooted binary tree having n leaves.
'''
n = int(sys.stdin.readline().rstrip())
# An unrooted tree with n leaves and m internal nodes should have n + 3m total degrees... |
from google.cloud import bigquery, storage
import traceback
import logging
def create_table(project, dataset_id, table_id):
schema = [
bigquery.SchemaField("event_name", "STRING", mode="NULLABLE"),
bigquery.SchemaField("user_id", "STRING", mode="NULLABLE"),
bigquery.Schema... |
'''
项目:电子词典
模块:socket pymysql
'''
import socket,pymysql
import os,sys
from multiprocessing import Process
#处理注册函数
def doRegister(client,db,username,password):
#判断user表中是否有此用户
cursor = db.cursor()
sel = 'select password from user where username=%s'
#根据要注册的用户名判断查询结果是否为空
cursor.execute(sel,[username]... |
def solution(arr, length):
if not isinstance(arr, list):
return
original_length = 0
num_of_blank = 0
i = 0
while arr[i] != "\0":
if arr[i] == " ":
num_of_blank += 1
original_length += 1
i += 1
new_length = original_length + num_of_blank * 2
if new... |
'''
Contains the modules used for the Morpher API-fuzzing utility
G{packagetree}
Morpher is a API fuzzing tool for Windows Dynamically Linked Libraries (DLLs).
Morpher's methods are based around two major ideas:
1. Mutational fuzzing - Many fuzzers either
generate valid data for the API calls, which ... |
import numpy as np
def sus(fitness: np.ndarray, n: int, start: float) -> list:
"""Selects exactly `n` indices of `fitness` using Stochastic universal sampling alpgorithm.
Args:
fitness: one-dimensional array, fitness values of the population, sorted in descending order
n: number of individual... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python
# @Time : 2:48 下午
# @Author : lidong@test.com
# @Site :
# @File : model_type.py
from commons.exceptions import EmptyException
MODEL_CLASS_DICT = {}
class ModelMeta(type):
def __init__(cls, name: str, bases: tuple, attrs: dict):
"""
:para... |
import time, copy,random
from django.conf import settings
from rest_framework.views import Response
from rest_framework.permissions import AllowAny
from decimal import Decimal
from datetime import datetime
from django.db.models import F
from tools import viewset, dianwoda
from weixin.pay import WeixinPay
from weixin.... |
from django.test import TestCase
from lists.models import CV, JOB, EDUCATION, INTERESTS, AWARDS
class HomePageTest(TestCase):
def test_uses_home_template(self):
response = self.client.get('/')
self.assertTemplateUsed(response, 'home.html')
# REMOVED TEST AS I'M CHANGING THE ARCHITECTURE OF THE ... |
import ROOT
import root_numpy as rnp
from rootpy.io import root_open
import AtlasStyle as Atlas
from math import sqrt, log
import numpy as np
from array import array
from copy import deepcopy
mBB_Binning_long = array('d',range(50, 300, 10))
def Make1DPlots(samples, histname, var, weight, cuts, binning):
for s in... |
import getplayers, getmatchids, getchampiondata, gettraitdata, getitemdata, getcompdata, getotherdata, getpopularitydata
import sqlite3
from datetime import datetime
if __name__ == '__main__':
a = datetime.now()
getplayers.get_all_challengers()
getplayers.get_all_grandmasters()
getmatchids.get_all_matc... |
def get_gene_map_intron():
import msgpack
import blosc
root = '/hps/nobackup/stegle/users/horta/dataset/intron/quant_splicing/transcript-qtls'
with open(root + '/gene_map_intron_filter2.msg', 'rb') as f:
return dict(msgpack.unpackb(f.read()))
|
# -*- coding: utf-8 -*-
from runjs import *
from runjs.backends.jsonable import Jsonable
js_lib_code = '''
function hello_value(v) {
return v + 5;
}
function hello_list(l) {
var sum = 0;
for (i = 0; i < l.length; i++) {
sum += l[i];
}
return sum;
}
function hello_dict(d) {
return Obje... |
from collections import OrderedDict
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.settings import api_settings
from drf_hal_json import LINKS_FIELD_NAME, EMBEDDED_FIELD_NAME
class HalPageNumberPagination(PageNumberPagination):
page_si... |
import django.conf.urls
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import RedirectView
from django.contrib import admin
admin.autodiscover()
urlpatterns = django.conf.urls.patterns('',
# Examples:
# url(r'^$', 'gtgapp.views.home', name='home'),
# u... |
class FlashCards:
def __init__(self, questions_dict):
self.questions = questions_dict.keys()
self.answers = questions_dict.values() |
#!/usr/bin/env python
""" The typical Lotka-Volterra Model, simulated using scipy to perform numerical integration for solving ordinary differential equations (ODEs) """
import scipy as sc # import scipy, call it sc
import scipy.integrate as integrate
import pylab as p # Contains matplotlib for plotting
# import mat... |
# 투포인터, 배열 스플라이싱 사용
# 투포인터 문제 찾아 연습하고 유형에 익숙해지기
# 최대한 그 요소 주변에서 찾아야 한다고 생각했는데..
n = int(input())
arr = list(map(int, input().split()))
arr.sort()
answer = 0
for i in range(n):
temp = arr[:i]+arr[i+1:]
left, right = 0, n-2
while left < right:
compare = temp[left]+temp[right]
if arr[i] == co... |
import requests
from RYProj import __version__
def main():
print(__version__)
if __name__ == "__main__":
main()
|
def function2(x): #define la funcion function2 que acepta un termino
return 2*x # devuelve el valor de 2*x de la funcion
a = function2(3) #llama la funcion entregandole el parametro 3 y se lo adjudica a la variable a
print(a) #Printea la variable a
b = function2(4) #llama la funcion entregandole el parametr... |
#!/usr/bin/env python
import sys
import requests
import json
# parse the solr status
"""
this does sadly not work on older versions of requests:
with requests.get(status_url) as get_data:
solr_status = get_data.json()
"""
status_url = 'http://localhost:8983/solr/admin/cores?action=STATUS&wt=json'
# fetch status
... |
class client:
def __init__(self,clientID,name):
self._clientID=clientID
self._name=name
def __str__(self):
return "\nClient name:"+self._name+"\nClient ID: "+str(self._clientID)+"\n"
def getClientName(self):
return self._name
def getID(self):
return... |
### NOT USED, for reference
import os
import glob
from random import randint
from uuid import uuid4
from config import images_loc
#filenames = list(glob.glob(os.path.join(images_loc,'*.*')))
filenames = list(range(100))
class Board:
n_rows = 5
n_cols = 5
n_entries = 25
n_red = 8
n_blue = 8
... |
# Generated by Django 3.1.1 on 2020-09-20 19:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('recipes', '0002_auto_20200920_1905'),
]
operations = [
migrations.RenameModel(
old_name='myRecipes',
new_name='Recipe',
... |
import phoenixdb
import phoenixdb.cursor
import pandas as pd
from sqlalchemy import create_engine
# TODO:
def return_connection_string(database_name, database_user, database_password, database_host, database_port):
try:
connection_string = 'mysql+mysqlconnector://' + database_user + ':' + \
d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import html5lib
from packaging_repositories.entries import _parse_base_url
@pytest.mark.parametrize(
("html", "url", "expected"),
[
(b"<html></html>", "https://example.com/", "https://example.com/"),
(
b"<html><head>"
... |
# -*- coding: utf-8 -*-
from odoo import models, fields, api, _
class Session(models.Model):
_name = 'open_academy.session'
_description = 'This is the session model for the Open Academy module.'
name = fields.Char(string='Session Title', required=True)
date_start = fields.Date(string='Start... |
import os
def encrypt(file_name):
key = 150
input_f = open('copies/' + file_name)
ch = input_f.read()
result = ""
for c in ch:
result += chr((ord(c) + key) % 256)
key = (key - 1) % 256
input_f.close()
output_f = open('encrypted/' + file_name, "w")
output_f.write(result)
output_f.close()
for afile in os.... |
import networkx as nx
from single_agent_planner import move, is_constrained, get_path
def construct_mdd(my_map, agent, start, goal, h_values, cost, constraints):
'''
This method build a single agent mdd
'''
mdd = nx.DiGraph()
h_value = h_values[start_loc]
explore = []
# build contraint table for agent
... |
from __future__ import division
from matplotlib import pyplot as plt
def get_errors(arr):
print len(arr)
for i in xrange(1, 10):
arr[i - 1] = i * 5 / arr[i - 1]
if __name__ == "__main__":
x = [i*5 for i in xrange(1, 10)]
print len(x)
Y_1 = [5.151, 9.11, 12.60, 17.200, 6.811, 16.64, 16.07... |
import matplotlib
matplotlib.use('Agg')
import scipy.io as sio
import matplotlib.pyplot as plt
import pylab
import numpy as np
import sys
import csv
from matplotlib.colors import ListedColormap
from sklearn import svm, neighbors, datasets, linear_model
from sklearn.metrics import accuracy_score
from sklearn.model_sel... |
# 39. Combination Sum
'''
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (includ... |
#coding:utf-8
# api-doc export to markdown
import json
def print_parameters(nodes,indent=1):
text =''
for node in nodes:
text+='\t'*indent + u'\t%10s:\t%10s\t[%s]\t --:%s\n'%( node.get('name'),
'('+node.get('type')+')',
node.get('default','unset'... |
from flask import Flask
from flask import request
from flask import Markup
from flask import render_template as st
from mikoto.libs.text import render
app = Flask(__name__, static_url_path="/static")
@app.route("/", methods=['POST', 'GET'])
def index():
if request.method == 'POST':
md_content = request.form['md_con... |
class Solution:
def numTeams(self, rating: List[int]) -> int:
#loop through the items
#assume the item to be min
#check if there is bigger item
#if count is 2 add the combination to a list
#if the item exisit in the list continue searching
count = 0
for i,item... |
from django.urls import path, include
# from app import views
from rest_framework_simplejwt.views import TokenRefreshView
from authentication.views import PersonView, PersonAuthViewSet
login = PersonAuthViewSet.as_view({
'post': 'login',
})
register = PersonAuthViewSet.as_view({
'post': 'register'
})
redirect ... |
import rg
import time
import math
# Data structures
#
# game
# turn - int 0-100
# robots
# [coords] : {
# 'player_id' : id,
# 'hp' : hp,
# 'location' : [coords]
# }
'''
Gnats
Fly around attacking target once then fleeing to another target
'''
... |
# encoding: utf-8
from __future__ import unicode_literals
import pytest
from datetime import datetime, timedelta
from bson import ObjectId as oid
from bson.tz_util import utc
from marrow.mongo import Document
from marrow.mongo.field import String, Binary, ObjectId, Boolean, Date, TTL, Regex, JavaScript, Timestamp
fr... |
import tkinter as tk
import random, webbrowser, os
from datetime import datetime
from fpdf import FPDF
from time import sleep
class Question:
def __init__(self, type, prompt, choices, correct):
self.prompt = prompt.strip("\n")
self.type = type.strip("\n")
self.choices = choices
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.