text stringlengths 8 6.05M |
|---|
# created by Ryan Spies
# 3/2/2015
# Python 2.7
# Description: parse through a individual data files from IEM website
# (e.g. hourly ASOS) and generate formatted cardfile. Also creates a summary csv file
# with calculated valid data points and percent of total. Used to display in arcmap
# datacard format: http://www.n... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'advanced.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObj... |
def geometric_sequence_elements(a, r, n):
return ', '.join(str(a * r ** i) for i in xrange(n))
|
from enum import Enum
class RaidBoss(Enum):
ASTROLAB = "astrolab"
SAMURAI = "samurai"
MAD_KING = "mad king"
GUNLORD = "gunlord"
FROSTWING = "frostwing"
TWIN_FACE = "twin face"
|
list = [4, 2, 3,3]
def findIndex():
for i in range(len(list)):
if list[i] == 2:
index = i
return index
print(findIndex())
fo = open("avatar_list.txt", "r")
print(fo.read()) |
from pa.plugin import Plugin
class LNetworkPlugin(Plugin):
__pluginname__ = 'LNetwork'
pass
|
'''
sentinela.py
Copyright 2013 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope that i... |
import argparse
import json
import os
import re
import sys
from collections import namedtuple
from utilities import constants
class Arguments:
class __Arguments:
def __init__(self):
parser = argparse.ArgumentParser(
description="Collect OSINT for GitLab groups and, optionally,... |
import roboclaw.py
|
'''
:Boneh-Lynn-Shacham Identity Based Signature
| From: "D. Boneh, B. Lynn, H. Shacham Short Signatures from the Weil Pairing"
| Published in: Journal of Cryptology 2004
| Available from: http://
| Notes: This is the IBE (2-level HIBE) implementation of the HIBE scheme BB_2.
* type: signature (identity-ba... |
import cv2
import numpy as np
# 读入图像并转化为float类型,用于传递给harris函数
filename = './images/test_corner.jpg'
img = cv2.imread(filename)
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray_img = np.float32(gray_img)
# 对图像执行harris
Harris_detector = cv2.cornerHarris(gray_img, 2, 3, 0.04)
# 腐蚀harris结果
dst = cv2.dilate(Harri... |
from lxml import etree
import re
f = open ('result1.xml', 'r')
xml = f.read ()
f.close ()
root = etree.fromstring (xml)
c = 0
#f = open ('data1_validurl.txt', 'r')
#urls = f.readlines ()
#f.close ()
print "<dblp>"
for article in root.xpath ('*'):
if len (article.xpath ('author/text ()')) == 0:
c = c + ... |
from datetime import datetime
from django import forms
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Subscribe(models.Model):
""" stores the email addresses of the people who subscribed to the teaser. """
email = models.EmailField(_(u'Subscribers'), max_length... |
from n3_camera_models_and_augmented_reality import camera
from n4_multiple_view_geometry import sfm
from PIL import Image
from pylab import *
from numpy import *
def example_plot_3d_points():
# plotting 3D points
from mpl_toolkits.mplot3d import axes3d
fig = figure()
ax = fig.gca(projection='3d')
... |
import random as rng
import math
import entities
class Block(object):
def __init__(self, biome=-1):
self.explored = False
self.biome = biome
self.sound = -1
def passable(self):
return not self.collides
def interact(self, player):
return "Boop."
class Null(Block):
def __init__(self, biome=-1):
Bl... |
from .searchstims import Searchstims
from .voc import VOCDetection
|
import time
import sys
import torch
import numpy as np
import copy
import pickle
import gzip
import hashlib
import os.path
from tqdm import tqdm
from backpack import backpack, extend
from backpack.extensions import BatchGrad
from env import WindowEnv, WindowEnvBatch
class SumLoss(torch.nn.Module):
def __init__(s... |
import os
import shutil
from typing import Any, Callable, Optional, Tuple
import numpy as np
from PIL import Image
from .utils import download_and_extract_archive, download_url, verify_str_arg
from .vision import VisionDataset
class SBDataset(VisionDataset):
"""`Semantic Boundaries Dataset <http://home.bharathh... |
word = 'brontosaurus'
d = dict()
for c in word:
if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
print(d)
# user th get method
word1 = 'brontosaurus'
d1 = dict()
for c1 in word1:
d1[c1] = d1.get(c1, 0) + 1
print(d1)
counts = {'chuck': 1, 'annie': 42, 'jan': 100}
print(counts.get('chuck', 0))... |
from PyQt5.QtWidgets import QSizePolicy
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class PlotCanvas(FigureCanvas):
def __init__(self, parent=None, width=8.8, height=10.5, dpi=100, title=' '):
self.fig = Figure(figsize=(width, heig... |
# Generated by Django 3.0.3 on 2020-03-12 20:00
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main_app', '0011_auto_20200312_2056'),
]
operations = [
migrations.RemoveField(
model_name='membre',
name='mail',
),... |
#!/usr/bin/python39
from environment import terrain_gen, error, loop
from environment import __dumb_controller, debug_draw_terrain
import numpy as np
import matplotlib.pyplot as plt
print('Draw road')
terrain = terrain_gen()
plt = debug_draw_terrain(terrain)
plt.xlabel('Example road segment')
plt.legend()
plt.show()
... |
from bsm.loader import load_relative
from bsm.loader import LoadError
from bsm.handler import HandlerNotAvailableError
from bsm.logger import get_logger
_logger = get_logger()
def run(param):
cmd = param['command']
if not cmd:
_logger.error('Command is empty')
raise HandlerNotAvailableError
... |
# Bài 04: Viết hàm
# def get_file_size(file)
# để lấy và trả về dung lượng của file
def get_file_size(file) :
with open(file,'r',encoding='utf-8') as text :
text.read()
print(text.tell())
get_file_size('text/text.txt')
|
def overlap(a, b):
overlap = []
for i in a:
if (not(i in overlap)) and (i in b):
overlap.append(i)
print(overlap)
|
"""
This example demonstrates how to retrieve information for a channel.
"""
from pyyoutube import Client
API_KEY = "Your key" # replace this with your api key.
def get_channel_info():
cli = Client(api_key=API_KEY)
channel_id = "UC_x5XG1OV2P6uZZ5FSM9Ttw"
resp = cli.channels.list(
channel_... |
from google.cloud import translate
from core.env import Environment
class TranslationService:
def __init__(self, env: Environment) -> None:
self._env = env
def translate(self, text: str, target_lang: str):
parent = f"projects/{self._env.google_project_id}"
client = translate.Trans... |
# -*- coding: utf-8 -*-
# All models are imported here in order to be accessed through the root package
from app.models.users import User
from app.models.tokens import UserToken, PasswordToken
from app.models.comments import TournamentComment, PollComment
from app.models.results import Result
from app.models.to... |
import io
import pathlib
from collections import namedtuple
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
from torchdata.datapipes.iter import IterDataPipe, Mapper, Zipper
from torchvision.prototype.datasets.utils import Dataset, GDriveResource, OnlineResource
from torchvision.prototype.datasets... |
if 5>2:
print("5 is greater than 2")
print("5 is greater") |
import os
import json
import time
import sys
search_domain_dev = 'http://search-mparticle-docs-dev-bjdn4zkr3qejlv27yt7ydobuqe.us-east-1.cloudsearch.amazonaws.com'
search_domain_prod = 'http://search-mparticle-docs-prod-6ozkfhxijk6v43sgv6wjl4kapq.us-east-1.cloudsearch.amazonaws.com'
search_domain = search_domain_prod i... |
import logging
from .device_management import application
from .performance_analysis import pa
from .fault_management import fm
from .probe_monitoring import pm
from flask import Flask
from config import pms_app
# from run_pms import pms_app
from logging.config import dictConfig
dictConfig({
'versio... |
"""
Adapted from: https://realpython.com/async-io-python/
"""
import re
import time
from urllib.parse import urljoin
from urllib.request import urlopen
import aiofiles
import aiohttp
from aiohttp import ClientSession
HREF_RE = re.compile(r'href="(.*?)"')
def fetch_html(url):
""" GET request wrapper to fetch pag... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 20 11:12:01 2019
@author: HP
"""
r=[]
s=[]
c=3
def rod_cutting(n,p):
r.append(0)
for i in range(1,n+1):
q=-5
ind=i
for j in range(1,i+1):
if q<(p[j]+r[i-j]):
ind=j
q=p[j]+r[i-j]
... |
# Generated by Django 3.1.7 on 2021-03-26 12:00
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
]
|
#----------------URL and imports-----------------------
import requests #Should be install requests libary
URL = 'http://localhost:8088/services/'
#---------------REQUESTS--------------------------------
def get_users():
response = requests.get(URL+'users/all')
users = response.json()
#print(response.conte... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 14 16:02:12 2018
@author: Binish125
"""
import random
pop_size=400
Num_items=15
Num_items=Num_items-1
tot_capacity=10
sim_run=4
val=[1,4,5,7,10,5,9,4,8,11,5,10,12,4,9]
wt=[1,3,4,5,4,2,3,6,8,4,1,2,6,5,1]
generations=50
def weighted_choice(items):
weight_total=sum(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 3 13:48:09 2018
@author: vincent
"""
import os, sys
info_files = sys.argv[1:3]
info_files = [os.path.expanduser(f) for f in info_files]
info_files = [os.path.abspath(f) for f in info_files]
genome_size = float(sys.argv[3])
coverage = float(sys.a... |
# encoding=utf8
'''
Created on 2016-08-18
@author: jingyang <jingyang@nexa-corp.com>
Usage:
fab staging deploy
fab prod deploy
'''
from fabric.api import local
from fabric.context_managers import lcd, cd
from fabric.operations import put, run
from fabric.state import env
import os
# import wingdbstub
PROJECT... |
"""
2. Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order, and each of their nodes contains a single digit.
Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, ex... |
from __future__ import division
import time
import numpy as np
import pandas
import csv
import itertools
from sklearn.svm import SVR
from sklearn.model_selection import KFold, cross_val_predict
from sklearn.metrics.regression import mean_squared_error, r2_score
import matplotlib.pyplot as plt
"""Read in dataset"""
... |
import requests
from utils.functions import *
from colorama import init, Fore
def main():
init()
userInput = input(
"::. welcome to bitband brute v1.0 .::\n1- brute force attack\n2- dictionary attack\n3- quit\n\nchoose your option: "
)
if userInput == "1":
username = input("username: ... |
import numpy as np
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QFileDialog, QMessageBox
from ui import MainWindow_design
from PlotWindow import PlotWindow
from DREAM import DREAMIO
import AUG
import EqFile
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.f... |
from flask import Flask, redirect, url_for, render_template, request
from time import sleep
import RPi.GPIO as GPIO # import the RPi library and its GPIO function?? PWM to control the servo motor??
app = Flask(__name__)
#Default page(Spray Power Off)
@app.route("/", methods=["GET","POST"])
def home():
TES_pin = ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-02-25 18:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('qa', '0011_ratequestion'),
]
operations = [
migrations.AlterModelOptions(
... |
import os
from build_database import build_database
ruta1=os.path.dirname(os.path.abspath(__file__))+'\\TerrassaBuildings900\\val\\images'
ruta2=os.path.dirname(os.path.abspath(__file__))+'\\TerrassaBuildings900\\train\\images'
savepath1=os.path.dirname(os.path.abspath(__file__))+'\\TerrassaBuildings900\\val'
savepath... |
# ランナーパッケージ
# train, infer, loggingがimportできるようにする
from runner.runner import Runner
from runner.infer import Infer
from utils import *
from dataset import *
from models import * |
#!/usr/bin/python3
''' I/O module '''
def append_write(filename="", text=""):
''' Appends a string at the end of a text file (UTF8) and returns the
number of characters added.
'''
with open(filename, mode='a', encoding='utf-8') as f:
return f.write(text)
|
import json
import os
from collections import UserDict
from .logger import get_logger
logger = get_logger('config')
global_config_paths = {"LOCAL": "local_config.json",
"TESTNET": "testnet_config.json",
"MAINNET": "mainnet_config.json"}
env_defaults = {'LOCAL': './confi... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2
import hashlib
import json
import time
import datetime
import datamodel as dm
from apiconfig import APIConfig
from logger import Logger
class OpenWeatherMap:
def getDateStr(self, delta_days):
#create time string of the following format: "yyyy-mm-d... |
'''
| From: "Digitalized Signatures and Public-Key Functions as Intractable as Factorization".
| Published in: 1979
| Security Assumption: Integer Factorization
* type: public-key encryption
* setting: Integer
:Authors: Christina Garman
:Date: 09/2011
'''
from charm.core.math.integer impo... |
# encoding: utf-8
import os
import io
import sys
from setuptools import setup, find_packages, Command
from shutil import rmtree
NAME = 'reelog'
DESCRIPTION = 'python log best practice.'
URL = ''
EMAIL = 'samrui0129@gmail.com'
AUTHOR = 'Sam Rui'
REQUIRES_PYTHON = '>=2.7.0'
VERSION = '1.6.7'
REQUIRED = [
]
EXTRAS = {... |
import pandas as pd
import os
import numpy as np
from manatee.preprocess import parse_weekly_timestamps
from manatee.shapelet_train import train_shapelets, batch_events_to_rates
import pickle
series_size = 240 * 60
num_bins = 300
min_points = 5
filter_bandwidth = 2
density = True
data = pd.read_pickle('../all_emails_k... |
#questao 2 - condição
saldoInicial = float(input('Insira seu saldo inicial: '))
debitos = float(input('Insira o total de debitos: '))
creditos = float(input('Insira o total de creditos: '))
saldoFinal = saldoInicial + (creditos - debitos)
if saldoFinal > 0:
print("Saldo porsitivo em R$",saldoFinal)
elif saldoFinal... |
from django.db import models
POSITIONS = (
("GK", "Goal Keeper"),
("DF", "Defender"),
("DF", "Defender"),
("MF", "Midfielder"),
("FW", "Forward"),
)
class League(models.Model):
name = models.CharField(max_length = 100)
start_date = models.DateField()
end_date = models.DateField(null = ... |
def cast_params_to_ufloat(params, stdev=0.1):
from uncertainties import ufloat
u = {}
for p, val in params.items():
if isinstance(val, dict):
u[p] = cast_params_to_ufloat(val)
if isinstance(val, float):
u[p] = ufloat(val, val * stdev, tag=p)
else:
... |
"""Noticeable difference model for CIE Lab color space."""
def cieLabJND(markSize):
"""Calculate the interval for two CIE Lab colors to be noticeable different.
Calculate the minimum interval needed along CIE L, a, and b axis for two
colors of a certain size to be noticeably different. Here we use the a m... |
import pytest
from LayerClient import LayerClient
class MockRequestResponse(object):
def __init__(self, ok, json=None, text=None, status_code=200):
self.ok = ok
self._json = json
self.text = text
self.status_code = status_code
def json(self):
if self._json is None:
... |
"""PyTorch Dataset class for visual search stimuli"""
from pathlib import Path
import imageio
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset
class Searchstims(Dataset):
"""dataset of visual search stimuli"""
def __init__(self,
csv_file,
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-01-11 17:41
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("organisations", "0015_organisationdivisionset_mapit_generation_id")
]
def add_curies(apps, s... |
import pytest
import redislite
from pydantic_aioredis.config import RedisConfig
from pydantic_aioredis.model import Model
from pydantic_aioredis.store import Store
@pytest.fixture()
def redis_server(unused_tcp_port):
"""Sets up a fake redis server we can use for tests"""
instance = redislite.Redis(serverconf... |
from flask import render_template, flash, redirect, g, session, request, url_for
from app import app
from .forms import LoginForm, RegisterForm
from flask.ext.login import login_user , logout_user , current_user , login_required
from app import db, models, lm
# u = models.User(nickname='john', password='12345')
# db.s... |
from django.db import models
from django_mysql.models import JSONField
class Movies(models.Model):
popularity = models.FloatField(null=True, blank=True)
director = models.CharField(max_length=256)
genre = JSONField(null=True, blank=True)
imdb_score = models.FloatField(null=True, blank=True)
name = ... |
#!/usr/bin/python2.7
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import math
#plt.rcParams["legend.fontsize"]=13
plt.rcParams["legend.fontsize"]=47
plt.rcParams["font.size"]=45
p = plt.figure(figsize=(24,12),dpi=200)
rc('font',**{'family':'serif','serif':['Times']})
rc('text', usetex... |
#encoding:utf-8
import requests,json
class Controller:
username = 'admin'
password = '123654789'
#Login
def __init__(self):
self.session = requests.Session()
self.session.verify = False
def login(self):
LOGIN_PARAM = {'username': self.username,
'passw... |
import copy
import json
import time
from django.urls import reverse
from rest_framework import status
valid_data = {
"citizens": [
{
"citizen_id": 2,
"town": "Москва",
"street": "Льва Толстого",
"building": "16к7стр5",
"apartment": 7,
... |
import pandas as pd
import os
data = pd.read_csv("elements.csv")
#print(data.iloc[5:6,5:6])
#print(data.index[1])
#a = data.iloc[5:6,5:6]
#float(a)
#print("Melting point", a)
#print(data[["Element", "Symbol"]])
col = data.iloc[:,0:0]
print(col)
s1 = data['Number']
print((data['Number'])[3])
|
'''
169. Majority Element
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Example 1:
Input: nums = [3,2,3]
Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2]
O... |
from models.exceptions import ACCESS_DENIED, BIRTHDAY_NOT_FOUND
from utils.database import SQLite3Instance
class Birthdays:
def __init__(self, user_id):
self.user_id = user_id
self.db = SQLite3Instance()
def get_birthdays(self) -> list:
""" Метод получает все записи ДР
:return... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Address'
db.create_table('competition_address', (
('id', self.gf('django.db.mode... |
#!/bin/python3
import re
import sys
from sys import stdin
colnames = []
reqColumns = sys.argv[1:]
for i in stdin:
record = i.replace("\n", "").split(',')
selectedColumns = []
if record[0] == 'id':
colnames = record
continue
for i in range(0,len(record)):
if colnames[i] in reqCo... |
def matrixReshape(nums, r, c):
if r * c != len(nums) * len(nums[0]):
return nums
rtn_val = []
i = 0
new_num = []
for comp in nums:
for num in comp:
new_num.append(num)
i += 1
if i == c:
i = 0
rtn_val.append(new_num)
new_num = []
return rtn_val
print(matrixReshape([[1,2],[3,4]], 1,... |
"""Tests relating to submitting solutions"""
# pylint: disable=invalid-name, no-name-in-module, import-error
import auacm, unittest
from unittest.mock import patch
from mocks import MockResponse, MockFile, PROBLEMS_RESPONSE
class SubmitTests(unittest.TestCase):
"""Tests relating to submits"""
@patch('builti... |
import matplotlib.pyplot as plt
import numpy as np
# path in computer and clusters
path_comp_moumita = "/media/moumita/Research/Files/University_Colorado/Work/work4/Spells_data_results/results/CNN/imp_results/graph/"
path_comp_brandon = ""
path_cluster = "/projects/mosa2108/spells/"
path = path_comp_moumita
x = np... |
class Solution(object):
def searchInsert(self, nums, target):
"""
https://leetcode.com/problems/search-insert-position/
binary search problem. needed help as i was using wrong mid value in conditions.
"""
if target <= nums[0]:
return 0
if target > nums[-1]... |
# Generated by Django 2.2.7 on 2019-12-26 13:11
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('statics', '0007_reply_re... |
from django.shortcuts import render
from tickets.models import Ticket
from tickets.forms import TicketForm
# Create your views here.
def ticket_search(request):
tickets = Ticket.objects.filter(ticketName__icontains=request.GET['query'])
form = TicketForm(instance=None)
return render(request, "search_result... |
from django.contrib import admin
from .models import Token
class TokenAdmin(admin.ModelAdmin):
readonly_fields = ("token",)
admin.site.register(Token, TokenAdmin)
|
import mnist
import numpy as np
import matplotlib.pyplot as plt
from numpy.lib.stride_tricks import as_strided
import classifiers
from scipy.linalg import svd
import math
PEGASOS = 0
SGDQN = 1
ASGD = 2
data = mnist.read_data_sets("MNIST_data/", one_hot=True)
print data.train.images.shape
print data.train.labels.sha... |
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.util.osutil import OS_ALIASES, _values, normalize_os_name
def test_alias_normalization() -> None:
for normal_os, aliases in OS_ALIASES.items():
for alias in aliase... |
import os
import io
from flask import json, jsonify
from app import app
AUTH_TOKEN = ""
def get_token():
print('get_token')
token_file = 'auth_token.txt'
with open(token_file, 'r') as f:
os.environ["AUTH_TOKEN"] = f.readline()
print(os.environ["AUTH_TOKEN"])
print('')
def upload_file():
... |
from django import forms
from . models import Technologies
class TechnologiesForm(forms.ModelForm):
class Meta:
model = Technologies
fields = ["techno"] |
import math, sys
import os.path
import cmath
from math import sqrt
#################################################################################################################
#################################################################################################################
# data structure to stor... |
from template.db import Database
from template.query import Query
from template.transaction import Transaction
from template.transaction_worker import TransactionWorker
from template.config import init
from random import choice, randint, sample, seed
init()
db = Database()
db.open('./ECS165')
grades_table = db.create... |
print("Enter quantity")
q = int(input())
print("enter Price")
p = int(input())
total = q * p
if total >= 100000:
d = total * 0.1
print("Your guantity is = " + str(q) + " your number per item is = " + str(p) + " your Total is = " + str(total))
|
import json
def create_case(mesh_file="",
lx=4,
source_term="noforce",
initial_condition="uniform",
nsamples=0,
dt=0.001,
T_end=0.0,
uinf=[1.0,0.0,0.0]) :
default = {
"case" : ... |
# linreg.py
#
# Standalone Python/Spark program to perform linear regression.
# Performs linear regression by computing the summation form of the
# closed form expression for the ordinary least squares estimate of beta.
#
# TODO: Write this.
#
# Takes the yx file as input, where on each line y is the first element
#... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import rospy
from std_msgs.msg import String, Empty, UInt8
from silbot3_msgs.srv import SpeechRecognitionStart, SpeechRecognitionStartResponse
import os
import signal
import traceback
import speech_recognition as sr
from speech_recognition import Microphone
class Recognize... |
"""
Copyright MIT and Harvey Mudd College
MIT License
Summer 2020
Defines the interface of the Controller module of the racecar_core library.
"""
import abc
from enum import IntEnum
from typing import Tuple
class Controller(abc.ABC):
"""
Handles input from the controller and exposes constant input state per... |
"""
This module lets you practice using Create MOVEMENT and SENSORS,
in particular the DISTANCE and ANGLE sensors.
Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder,
their colleagues and PUT_YOUR_NAME_HERE. September 2015.
""" # TODO: 1. PUT YOUR NAME IN THE ABOVE LINE.
from new_create_i... |
from src import king_bot, settings
import sys
# these could be read in via arguments, file or login manually - read documentation
gameworld = "com3" # choose uppercase (exact world name) - optional
email = "vlrizkidz93@tuta.io" # optional
password = "melodies" # optional
proxy = "" # optional
# increase the number... |
from django import forms
from apps.forms import FormMixin
from apps.news.models import News,Banner
from apps.course.models import Course
class EditNewsCategoryForm(forms.Form,FormMixin):
pk=forms.IntegerField(error_messages={'required':'必须传入分类的id!'})
name=forms.CharField(max_length=100)
class WriteNewsForm(f... |
import re
text_grid_1 = open('F:\Projects\Active Projects\Project Intern_IITB\Rishabh_FA_Audio\Test\hehe\\08024satishpilena_56580b937e63f5035c0025f5_57fe36059ee20a04985ba1a0_9_00020200000000022002200020002020.TextGrid', 'r')
text_grid_2 = open('F:\Projects\Active Projects\Project Intern_IITB\Rishabh_FA_Audio\Test\hehe... |
def getSubstrings(s):
""" get_substrings == PEP8 (forced mixedCase by CodeWars) """
s = s.lower()
length = len(s)
seen = set()
for a in xrange(length):
for b in xrange(1, length + 1):
end = a + b
if end > length:
break
seen.add(s[a:end])
... |
import json
from django.conf import settings
from modeltranslation import admin
from modeltranslation.utils import build_localized_fieldname
class TranslationAdmin(admin.TranslationAdmin):
change_form_template = 'trans/admin/change_form.html'
def _get_translation_options(self, origin_lang):
opti... |
import sys
import random
def main(num):
"""Prints x random words where x is user supplied
Params: num - sys argv[1]
int -> ()
"""
with open('/usr/share/dict/words') as file:
words = file.readlines()
for x in range(int(num)):
rand = random.randint(0, len(words)-1)
... |
from pytest_contextgen import create_context_in_tuple, \
parametrize_context_tuple, pair_context_with_doubles, get_contexts, get_apis
pytest_plugins = ['pytest_returnvalues']
def pytest_addoption(parser):
parser.addoption("--api", action="store",
help="API: cuda/ocl/supported",
# can't get AP... |
# Generated by Django 2.2.6 on 2019-10-26 13:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Collage',
fields=[
... |
import asyncio
async def publisher(q):
while True:
print('enqueued thing')
q.put_nowait({'a': 'thing'})
await asyncio.sleep(0.5)
async def worker(queue):
while True:
# Get a "work item" out of the queue.
my_dict = await queue.get()
print(f'processed {my_dict}... |
import logging
from .omaha import Omaha
# from .client import Client
# from .indicator import Indicator
# from .company import Company
from .version import __version__
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.INFO)
__all__ = ["__version__", "Client", "D... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.