text stringlengths 38 1.54M |
|---|
import torch
n = 1000
mini = -10
maxi = 10
random_points = (mini - maxi) * torch.rand(n, 2) + maxi
PI = torch.tensor(3.14159265359)
points = []
results = []
for point in random_points:
x1 = point[0]
x2 = point[1]
# f_(x1, x2) = sin(x1 + x2/pi)
r = torch.sin(torch.addcdiv(x1, x2, PI))
points.appe... |
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import newimagedlg
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.dirty = False
self.filename = None
self.messageLabel = QLab... |
#1
print("My name is Anmol kalra")
#2
str1 = "Anmol"
str2 = "kalra"
print(str1+str2)
#3
x = int(input("enter value for x "))
y = int(input("enter value for y "))
z = int(input("enter value for z "))
print("x=",x," y =",y," z=",z)
#4
print("let's get started")
#5
s = "Acadview"
course = "Python"
fees = 5000
str1 = "... |
"""
Copyright 2019 Goldman Sachs.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software di... |
from django.urls import path, re_path
from . import views
app_name = 'beers'
urlpatterns = [
path('', views.brewery, name='brewery'),
re_path(r'(?P<brewery_id>[0-9]+)/favorite/$', views.favorite, name='favorite'),
re_path(r'(?P<brewery_id>[0-9]+)/$', views.brewery_details, name='brewery_details'),
] |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-11-07 14:57
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0011_auto_20161107_1428'),
]
operations = [
migrations.AddField(
... |
# python 3.7
# https://stepik.org/lesson/3364/step/11?unit=947
a = int(input())
s = 0
while a != 0:
s += a
a = int(input())
print(s)
|
from django.test import TestCase
from edc.core.bhp_content_type_map.classes import ContentTypeMapHelper
from edc.lab.lab_profile.classes import site_lab_profiles
from edc.lab.lab_profile.exceptions import AlreadyRegistered as AlreadyRegisteredLabProfile
from edc.subject.appointment_helper.models import BaseAppointment... |
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import HttpResponse
from app01 import models
import os
def upload(request):
if request.method == 'GET':
return render(request,'upload.html')
elif request.method == 'POST':
ob... |
from db import db, ma
import hashlib
class CoworkerModel(db.Model):
__tablename__ = 'Coworker'
coworker_id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(45), nullable=False)
last_name = db.Column(db.String(45), nullable=False)
email = db.Column(db.String(45), unique=Tr... |
# if any breach occurs, use breach window (first to last value > 0)
# if no breach occurs, use +/- N-days
from hec.hecmath import TimeSeriesMath
from hec.hecmath import DSS
from hec.heclib.util import HecTime
# script entry point for TimeWindow modification.
# arguments:
# runTimeWindow - the runtime window after all... |
from django.db import models
class destination(models.Model):
name = models.CharField(max_length=100)
img = models.ImageField(upload_to='pics')
des = models.TextField()
price = models.IntegerField()
offer = models.BooleanField(default = False)
class info(models.Model):
Name = models.CharField... |
from Stats_Functions import std_dev, within_percentage
# Housefly wing lengths in millimeters
wing_lengths = [36, 37, 38, 38, 39, 39, 40, 40, 40, 40, 41, 41, 41, 41, 41, 41, 42, 42, 42, 42, 42, 42,
42, 43, 43, 43, 43, 43, 43, 43, 43, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 45, 45, 45,
... |
from IPython.display import Image
import matplotlib.pyplot as plt
import numpy as np
# Marker Styles: http://matplotlib.org/api/markers_api.html
def plot(data, x_row=0, x_label="Thresholds", x_tick_step=3, y_rows=[1], y_labels=["data"], y_markers=["o"],y_colors=["c"], cluster_plot_file="out.png", figure_size=(20,10) )... |
#! /usr/bin/env python
import sys
sys.path.append("../util")
import matplotlib.pyplot as plt
from netCDF4 import Dataset
import numpy as np
import os
import errno
# Local imports
from UtilityFcts import *
def Main():
LegendFSize=18
AxisFSize=22
TitleFSize=27
YLim=[0,6e12]
YTickLabelSize=20
XLi... |
from django.contrib import admin
from votes.models import Game, Vote
class GameAdmin(admin.ModelAdmin):
pass
admin.site.register(Game, GameAdmin)
class VoteAdmin(admin.ModelAdmin):
pass
admin.site.register(Vote, VoteAdmin)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/19 14:37
# @Author : LiuZhi
# @Site :
# @File : Extends.py
# @Software: PyCharm
class Animal(object):
def run(self):
print('Animal is running ...')
class Dog(Animal):
#pass
def run(self):
print('Dog is running...')
... |
# Generated by Django 2.0.6 on 2018-12-19 00:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userlogin', '0007_auto_20181218_0002'),
]
operations = [
migrations.CreateModel(
name='User_results',
fields=[
... |
'''
Created on 16-Jun-2018
@author: srinivasan
'''
import itertools
import string
class SearchCriteriaException(Exception):
pass
class SearchCriteria:
@staticmethod
def rangeAtoZ():
return [i for i in string.ascii_uppercase]
@staticmethod
def rangeAAtoZZ():
return [str... |
print ("this program is made by Rishu Raj")
a = int (input("enter the length of 1st side of triangle : "))
b = int (input("enter the length of 2nd side of triangle : "))
c = int (input("enter the length of 3rd side of triangle : "))
if a==b==c :
print ("this triangle is equilateral")
if a==b or a==c or b=... |
for t in range(int(input())):
n = int(input())
H = [int(e) for e in input().split()]
if n%2 == 0:
print("no")
else:
if H[0] != 1:
print("no")
else:
flag = 0
for i in range(n//2):
if H[i] != H[n-i-1]:
flag = 1... |
from werkzeug.security import generate_password_hash, check_password_hash
# from flask_login import UserMixin
from application import db, login_manager
from flask_login import UserMixin
class User(db.Model, UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Colu... |
# from keras.activations import *
import random
import numpy as np
from keras.losses import mean_squared_error as MSE
from keras.losses import mean_absolute_error as MAE
from keras.losses import mean_absolute_percentage_error as MAPE
import tensorflow as tf
from typing import List
from math import e
from math import t... |
import fractions
KEYSPACE = 256
def checkKeys(a, b):
if (fractions.gcd(a,KEYSPACE) != 1):
return False
else:
return True
def encrypt(data, keyA, keyB):
cipher = []
for element in data:
newPixel = []
for color in element:
newPixel.append((keyA * color + keyB... |
from tkinter import *
import win32com.client as wincl
speak = wincl.Dispatch("SAPI.spVoice")
def hi(): # speaking bits
ts = ent.get()
speak.Speak(ts)
root = Tk() # GUI bits
root.title("tktts")
but = Button(root, text="Speak!", command=hi)
lab = Label(root, text="What should i say?")
ent = En... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
import time
import datetime
# print "%s%s" % (time.strftime("%Y%m%d%H%M%S", time.localtime()),".log")
# print time.time()
# print time.localtime(time.time())
# print time.asctime( time.localtime(time.time()) )
# print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# ... |
# Modules used are hashlib: for hashing and deque: for Queue. I did not want to write a new queue when the wheel was already invented
import hashlib
from collections import deque
# I am choosing the sha256 algorithm here as a global configurable. The intention is it can be changed at any time
hash_algorithm = hashlib... |
#!/usr/bin/python
"""
Preprocess datasets and generate npz files to be used for training testing.
It is recommended to first read datasets/preprocess/README.md
"""
import argparse
import config as cfg
from datasets.preprocess import coco_extract
parser = argparse.ArgumentParser()
parser.add_argument('--train_files', ... |
#!/usr/bin/env python
import os
f = open('input/{}.txt'.format(os.path.splitext(os.path.basename(__file__))[0]),'r')
content = f.read()
f.close()
tf = 0
tb = None
i = 1
for c in content:
if(c == '('):
tf += 1
if(c == ')'):
tf -= 1
if(tf == -1 and not tb):
tb = i
i += 1
print("Floor {}".format(tf))
prin... |
# 13. Даний корінь A1 непорожнього дерева. Подвоїти значення кожної вершини дерева.
class Node(object):
def __init__(self,left = None,right = None,data = None):
self.left = left
self.right = right
self.data = data
def treewidth(tree = None):
if tree == None:
return 0
if tr... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import gym
import matplotlib.pyplot as plt
import copy
import collections
import random
from torch.distributions import Categorical
# it is actually Dueling DDQN
# hyper-parameters
LR = 0.01
GAMMA = 0.9
op = np.finfo... |
import json
import os
import sys
from typing import Optional
import click
from pelican_stat.collector import PelicanArticleDataCollector
from pelican_stat.plotter import PelicanDataPlotter
@click.group()
def main() -> None:
pass
@main.command()
@click.argument(
"pelican_conf_path", required=True, default=... |
import os
from api import app, db
from datetime import datetime
from api.models import Todo
from ariadne import (
load_schema_from_path,
make_executable_schema,
graphql_sync,
snake_case_fallback_resolvers,
ObjectType,
)
from ariadne.constants import PLAYGROUND_HTML
from flask import request, jsoni... |
from django.shortcuts import render
from django.shortcuts import redirect
# Create your views here.
def index(req):
return render(req, 'index.html')
def not_a_rickroll(req):
return redirect('https://www.youtube.com/watch?v=dQw4w9WgXcQ') |
#7.07. 3 masala. 2 ta meva qo'shish
meva = {"olma", "banan", "apelsin", "nok"}
meva.update(["shaftoli", "gilos"])
print(meva)
|
''' Creates clusters, txtfiles and wordclouds from xkcd tweeter/user descrptions '''
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import Normalizer
from sklearn.cluster import KMeans
import pandas as pd
import numpy as np
import ... |
# Allows the user to view the constructed HWP bacxground images. Shows all four
# HWP rotations associated with a single IPPA angle
#
import os
import sys
import glob
import numpy as np
from astropy.io import ascii
from astropy.table import Table as Table
from astropy.table import Column as Column
from astropy.convolu... |
from django.db import models
# Create your models here.
class ProjectConfig(models.Model):
accept_project = models.BooleanField(default=False, blank=True)
def __str__(self):
return 'Check if accepting project'
|
import pandas as pd
import datetime as dt
import numpy as np
from scipy.stats import norm
Call={'Strike':[20.00,23.00,25.00,28.00,30.00,33.00,35.00,38.00,40.00,42.00,45.00,47.00,50.00,52.00,55.00,57.50,60.00,
62.5,65.00,67.50,70.00,75.00,80.00,85.00,90.00],
'Call price':[37.8,34.65,32.55,29.60,26.95,24.26,23... |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, TextAreaField, SelectField
from wtforms.validators import InputRequired, DataRequired
from flask_wtf.file import FileField, FileRequired, FileAllowed
class PropertyForm(FlaskForm):
title = StringField('Property Title', val... |
from os import listdir
from os.path import exists, isdir, join, splitext
import numpy as np
from nnmnkwii.datasets import FileDataSource
available_speakers = ["fujitou", "tsuchiya", "uemura", "hiroshiba"]
available_emotions = ["angry", "happy", "normal"]
def _get_dir(speaker, emotion):
return "{}_{}".format(spe... |
#!/usr/bin/env python3.6
import data
import argparse
import os
import fi_tools
import sys
import itertools
import config
try:
homedir = os.environ['HOME']
except:
print('Env variable HOME is missing')
sys.exit(1)
def check(appdir, resdir, tool, config, wait, apps, action, instrument, nthreads, inputsize,... |
from manimlib.imports import *
class Reconstruction(VectorScene):
CONFIG = {
"vector1" : [1, 2],
"vector2" : [3, -1],
"vector1_color" : MAROON_C,
"vector2_color" : BLUE,
"vector1_label" : "v",
"vector2_label" : "w",
"sum_color" : PINK,
"scalar_pairs" ... |
"""Usage:
bcm.py <model> [--verbose]
Options:
-h --help This file is used to operate the power system model.
--version (c) Sayonsom Chanda, 2017. Canvass 0.0.1
MIT License. Attribution required.
Software provided AS IS. No WARRANTIES.
--verbose This prints out a ve... |
import json
from yelp_beans.data_providers.data_provider import DataProvider
def test_parse(employees):
result = DataProvider()._parse(json.loads(employees))
assert len(result) == 1
assert result[0]["first_name"] == "Darwin"
assert result[0]["last_name"] == "Stoppelman"
assert result[0]["email"] ... |
#!/usr/bin/python3
"""return TODO list progress"""
import requests
import sys
if __name__ == "__main__":
users = requests.get("https://jsonplaceholder.typicode.com/users/" +
sys.argv[1])
user = users.json().get("name")
all_tasks = requests.get(
"https://jsonplaceholder.typ... |
# Napisz funkcję, która wygeneruje macierz wielowymiarową postaci:
# [[2 4 6]
# [4 2 4]
# [6 4 2]]
# Przy założeniach:
# funkcja przyjmuje parametr n, który określa wymiary macierzy jako n*n i umieszcza
# wielokrotność liczby 2 na kolejnych jej przekątnych rozchodzących się od głównej
# przekątnej.
imp... |
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class QuizUser(AbstractUser):
score = models.IntegerField(null=True, default=0)
|
import numpy as np
import os, re, sys
from sklearn import metrics
from multiprocessing.dummy import Pool as ThreadPool
from sklearn.externals import joblib
from utils.myAUC import *
from utils.MISVM import *
from utils.testSVM import *
prop = os.getcwd().split('/')[-2]
nthreads = 10
seed0 = 1000001 + 100
np.random.... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
def callback(data):
rospy.loginfo(rospy.get_caller_id() + "I heard %s" , data.data)
def listener1():
rospy.init_node('listener1', anonymous=True)
rospy.Subscriber("chatter",String,callback)
rospy.spin()
if __name__=='__main__':
listener1()
|
from collections import defaultdict
class graph:
def __init__(self):
self.graph=defaultdict(list)
def addedge(self,u,v):
self.graph[u].append(v)
def Bfs(self,s):
vis=[]
bfs=[]
Q=[]
Q.append(s)
while Q:
a=Q.pop(0)
vis.append(a)
... |
dic = {
'boy': '소년',
'school': '학교',
'book': '책'
}
dic['boy'] = '남자아이' # 기존 boy를 덮어써버림
dic['girl'] = '소녀'
del dic['book']
print(dic)
print(dic.keys())
print(dic.values())
print(dic.items())
for key, value in dic.items():
print(key, value)
dic2 = {
'student': '학생', 'teacher': '선생님', 'book': '서... |
# pizzastore.py
import abc
class PizzaStore(abc.ABC):
def order_pizza(self, type: str):
pizza = self.create_pizza(type)
pizza.prepare()
pizza.bake()
pizza.cut()
pizza.box()
return pizza
@abc.abstractmethod
def create_pizza(self, type: str):
pass
... |
def f(n):
i=1
z = set("0123456789")
s = set()
prev = -1
while True:
next = n*i
if next == prev: break
t = set(str(next))
s = s.union(t)
if s == z:
return next
i+=1
prev = next
return "INSOMNIA"
import sys
sys.s... |
import os
import re
import sys
import argparse
import pytest
from six import StringIO
from llnl.util.filesystem import working_dir
from llnl.util.tty.colify import colify
from pymod.util.tty import redirect_stdout2 as redirect_stdout
import pymod.paths
import pymod.modulepath
description = "run pymod's unit tests"
s... |
from datetime import datetime
from flask import Blueprint, request
from app.forecast import retrieve_forecast
from dateutil.parser import isoparse
api = Blueprint("api", __name__)
@api.route("/forecast/")
def get_forecast():
time = isoparse(request.args.get("dt"))
try:
resp = retrieve_forecast(
... |
# This isn't correct, but at least it will give me a benchmark of where I am.
# Link to code challenge instructions
import statistics
import numpy as np
class Stats():
# creating an empty list
our_list = [] # setting our list as the attribute?
def __init__(self, mean, median, mode, variance, std_dev, ... |
from __future__ import division
import numpy as np
import scipy as sp
from numpy.random import random
class SVD_C:
def __init__(self,X,k=20):
'''
k is the length of vector
'''
self.X=np.array(X)
self.k=k
self.ave=np.mean(self.X[:,2])
print "the input data size is ",self.X.shape
self.bi={}
self.bu=... |
from vigorish.status.util import (
get_date_status,
get_date_status_from_bbref_game_id,
get_game_status,
)
from vigorish.util.dt_format_strings import DATE_ONLY_2
from vigorish.util.result import Result
def update_bbref_games_for_date_list(scraped_data, db_session, scraped_bbref_dates, apply_patch_list=Tr... |
import re
def output(text):
##------
## This formats output for provided text based on tags
## and is used in the Methods.py
##
## Example: print(display.output("<Red>My Text<Reset>\n"))
## "Red" defines the color and <Reset> changes the text
## color back. '\n' generates a carriage return
##-... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 7 09:04:08 2021
@author: eduardo.alcala
"""
"""
import os
import xml.etree.ElementTree as ET
def printChildInfo( child, lvl ):
auxtag = child.tag[ child.tag.find("}") + 1 : ]
print( "{}{}".format( lvl, auxtag ) )
for key, values in child.attri... |
def note():
note = input("Write Your Notes Here..... ")
with open("note.txt", "a") as file:
file.write(f"/n {note}")
note() |
import torch
import torch.nn as nn
from typing import List
class VFE_Layer(nn.Module):
def __init__(self, in_channels: int, out_channels: int):
"""
A VFE layer class
:param c_in: int, channel dimension of input
:param c_out: int, the dimension of output after VFE, must be even
... |
from py_linq import Enumerable
import pytest
_simple = [1, 2, 3]
_complex = [{"value": 1}, {"value": 2}, {"value": 3}]
_locations = [
("Scotland", "Edinburgh", "Branch1", 20000),
("Scotland", "Glasgow", "Branch1", 12500),
("Scotland", "Glasgow", "Branch2", 12000),
("Wales", "Cardiff", "Branch1", 2970... |
import re
import json
from collections import MutableMapping
from smooch.error import SmoochError
snake_case = re.compile('(?<!^)_([a-z0-9])')
class SmoochResource(MutableMapping):
def __init__(self, api=None, *args, **kwargs):
self._api = api
all_args = kwargs
if len(args) > 0 and typ... |
"""
Tools used by the `explore_ligpy_results.ipynb` notebook that help with
analysis and plotting.
"""
import os
import cPickle as pickle
import numpy as np
from constants import MW
def load_results(path):
"""
Load the results from the ODE solver, along with the program parameters
used to generate those... |
"""-----------------
Opgave 3
Anel Busuladzic
-----------------"""
A = 7+5
B = 16-4
C = 6*2
D = 24//2
E = int(24/2)
print(A)
print(B)
print(C)
print(D)
print(E)
produkt2 = 2**4
print(produkt2) |
import json
import pickle
import threading
import time
# file_x = 'E:/DataSet/data/features_noise.dat'
# file_y = 'E:/DataSet/data/label_class_0.dat'
#
# X = numpy.genfromtxt(file_x, delimiter=' ')
# y = numpy.genfromtxt(file_y, delimiter=' ')
# Y = numpy.array([i for i in range(X.shape[1])])
# print(X.shap... |
#!/usr/bin/env python
# coding: utf-8
# # Punto 6. Taller ecuaciones en diferencias
# # Los números de Lucas están relacionado con los números de Fibonacci, y están definidos por la siguiente secuencia 𝐿𝑛+2=𝐿𝑛+1+𝐿𝑛, 𝐿0=2, 𝐿1=1. Escriba un programa que imprima la siguiente información. El 18-th número de Lucas,... |
# -*- coding: utf-8 -*-
# Original Code : https://github.com/alrojo/CB513/blob/master/data.py
import os
import numpy as np
import subprocess
from utils import load_gz, save_text, save_picke
TRAIN_PATH = '../pssp-data/cullpdb+profile_6133_filtered.npy.gz'
TEST_PATH = '../pssp-data/cb513+profile_split1.npy.gz'
TRAIN_... |
import collections
file = (open('input.txt').read()).split()
frequency = collections.Counter(file)
f = open("output.txt","a")
for i in sorted(frequency):
f.write(i + ' : ' + str(frequency[i]) + '\n') |
# file name : __init__.py
from flask import Flask, request, redirect, url_for
from flask import render_template
import apiCall
# 가나다라마바사
app = Flask(__name__, static_folder='static', static_url_path='/static')
@app.route("/")
def hello():
return render_template("home.html")
@app.route("/home")
def home():
ret... |
import json
import os
import requests
'''
回顾:注释,输入和输出,标识符,保留字,字符串,数字,// ,/ %
切片
今日:
'''
# str1='hello'
# print(str1.upper()) #将字符串大写
# print(str1.capitalize()) #将首字母大写
# print(str1.lower()) #将字符串小写
''''''
'''假设一个字符串的长度为单数,将最中间的那个字符大写
比如:hello heLlo 5//2 =2
welcome welCome 7//2 =3
... |
#WAP to perform stack opertions on list
#!/usr/bin/python
def push(list1,add):
return(list1.append(add))
def pop(list1):
list1.pop()
return list1
def peep(list1):
return list1[-1]
def isFull(list1):
return len(list1)==10
def isEmpty(list1):
return list1==[]
def main():
list1=eval(input("Enter List:"))
... |
# Author: Iuri Diniz (UFOP)
# Date: 03/2021
import igraph as ig
import sys
# input: g, alpha
# output: g
# pij = (1 - (wij/si))**(ki - 1), where:
# w --> weight
# s --> strength
# k --> degree
def backbone(g,alpha):
p={}
adj = g.get_adjacency()
n_nodes = g.vcount()
s = g.strength(weights=g.es... |
import os
import re
import sys
import cmd
import bdb
import dis
import code
import glob
import pprint
import signal
import inspect
import traceback
import linecache
class Restart(Exception):
pass
__all__ = ['run', 'pm', 'Pdb', 'runeval', 'runctx', 'runcall', 'set_trace', 'post_mortem', 'help']
def find_funct... |
#! /usr/bin/python
__title__="Homework 9"
__author__="Thomas Benge"
__date__="04/26/13"
# Program that allows users to share information over a network
import sys
import re
import socket
import threading
import Queue
from NetIO import getNetLine, putNetLine
pat = re.compile(
'^\s*[Ss][Ww][Aa][Pp]\s+(\S+)\s+... |
import urllib
import urllib2
import re
import httplib
from basecall import BaseCall
class CssminifierCall(BaseCall):
def exec_request(self):
data = urllib.urlencode({
'input': self.original })
ua = 'Sublime Text - cssminifier'
req = urllib2.Request("http://cssminifier.com... |
from zmq_utils import send_array_fast, recv_array_fast
import zmq
addr = "tcp://127.0.0.1:10000"
context = zmq.Context()
socket = context.socket(zmq.REP) # pylint: disable=no-member
socket.bind(addr)
print(f"Listening to: {addr}")
while True:
data = recv_array_fast(socket, copy=False)
send_array_fast(socke... |
import os
import sys
import re
import getopt
def connectToWLST():
try:
connect(userConfigFile='/opt/Jenkins/wltserver/config.secure',userKeyFile='/opt/Jenkins/wltserver/key.secure',url='t3://freappd15.oracle.eagle.org:7001')
print 'Successfully connected to the WLST\n'
... |
class Car(object):
def __init__(self, name):
self.__washCar()
self.name = name
def __washCar(self):
print 'Washing the Car'
def fix(self):
print 'Fixing Car...'
def drive(self):
pass
def breaking(self):
pass
""" Inh... |
phrase = input("What is your phrase ")
word= (len(phrase))
count = 0
while count < word:
print("boop ", end="")
count=count + 1
|
def process_item(x):
copy = x
if copy + 1 == 2:
return copy + 1
found = 0
while found == 0:
copy += 1
for i in range(2, copy//2 + 2):
if copy % i == 0:
found = 0
break
else:
found = 1
return ... |
import sys
import random
import os
import datetime
import json
def load_files():
"""
Loading files from the same directory of the script. There are 3 txt files and their names are self explanatory.
It also closes the files after loading so you can edit the files.
"""
directory = os.getcwd()
# ... |
import pygame
import os
pygame.init()
game_screen = pygame.display.set_mode(size=(480, 600))
# 1、加载背景图
background = pygame.image.load("./images/background.png")
# 2、blit绘制背景图
game_screen.blit(background, (0, 0))
# 3、update更新屏幕
hero = pygame.image.load("./images/me1.png")
game_screen.blit(hero, (200, 400))
pygame.disp... |
'''
作者:张斌
时间:2019.3.24
版本功能:简单线性回归的实现,为了使得建立的模型使得方差最小 从而获得回归线y=b1x+b0
'''
#简单线性回归:只有一个自变量 y=k*x+b 预测使 (y-y*)^2 最小
import numpy as np
def fitSLR(x,y):
'''
:param x: 自变量
:param y: 因变量
:return: 模型参数
'''
n=len(x)
dinominator = 0
numerator=0
for i in range(0,n):
nume... |
"""
All core commands implemented in RAPyDo
"""
from importlib.util import module_from_spec, spec_from_file_location
from pathlib import Path
from types import ModuleType
from typing import Dict, Optional
from controller import PROJECT_DIR
BACKUP_MODULES: Dict[str, ModuleType] = {}
RESTORE_MODULES: Dict[str, ModuleT... |
#update test cat's owner
#whom we will send messages
from azure.storage import TableService
import config
table_service = TableService(account_name=config.ACC_NAME,
account_key=config.ACC_KEY)
#newMaster = {'masterID' : '188622142'}
#table_service.update_entity('bandcredentials', 'band','t... |
from __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import smtplib
from email.mime.text import MIMEText
from time import gmtime, strftime, localtime, sleep
import random
# If modifying these scopes, delete the file to... |
import csv as csv
import itertools
import statistics
from statistics import mean
import numpy as np
import matplotlib as matplt
import matplotlib.pyplot as plt
#opens the CSV file, turns it into a list of lists with tabs as the delimiter not commas
lol = list(csv.reader(open('S&P500_Returns_1926-2020.csv', 'rt'), de... |
# -*- coding: utf-8 -*-
import regex as re
import pickle as pickle
import bisect, csv, codecs, bleach, json, operator, os, subprocess
import time as pytime
from collections import OrderedDict
from copy import deepcopy
import numpy as np
from sefaria.model import *
from sources.functions import post_link
from sefaria.s... |
import requests
from bs4 import BeautifulSoup
import pandas as pd
tags = ['covid19', 'coronavirus', 'pandemic', 'covid-19-crisis', 'quarantine']
years = ['2020']
months = ['03', '04']
days = []
for i in range(1, 32):
if len(str(i)) > 1:
days.append(str(i))
else:
days.append(str(0) +... |
from flask import Flask
from flask import jsonify
from flask import request
from flask_cors import CORS
from flask_pymongo import PyMongo
from werkzeug.security import generate_password_hash
from werkzeug.security import check_password_hash
from string import punctuation
from Backend.Algorithm import generateTags
from... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 5 13:08:01 2015
@author: franciscojavierarceo
"""
import os
import pandas as pd
from gensim import corpora, models, similarities
from collections import defaultdict
os.chdir("/Users/franciscojavierarceo/")
df1 = pd.read_csv("NYTimesdata.csv")
df1.head()
frequency = def... |
from PIL import Image
#func for create each bar
def plotBar(image, width, color, heigth=60):
return image.new("RGB", (width, heigth), color)
#main function
def dna_to_barcode(path):
with open(path) as file:
dna_sequence = file.read()
#separating each nitrogenous bases
dna = [char for char in ... |
from datetime import datetime, timedelta
from nonebot.log import logger
from tinydb import TinyDB
import time
from .bilireq import BiliReq
from .config import Config
from .dynamic import Dynamic
from .utils import safe_send, scheduler, get_path
last_time = {}
dynamic_history = TinyDB(get_path('history.json'), encodi... |
# coding: utf-8
"""Views related to administering postage."""
from __future__ import unicode_literals
import StringIO
import flask_login as login
# from flask.ext import login
import flask
from eisitirio import app
from eisitirio.database import db
from eisitirio.database import models
from eisitirio.helpers import... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... |
import numpy as np
import csv
from matplotlib import pyplot as plt
lines = []
np_lines = []
with open("results_moons.csv", "r") as file:
reader = csv.reader(file, delimiter=";")
for l, row in enumerate(reader) :
if l != 0:
# lines.append(row)
lines.append(
[int(ro... |
#Author: Adrien Michaud
import sys
sys.path.append("../Config/")
import GlobalsVars as v
import arff
import os
import subprocess
import time
import numpy as np
import sys
import scipy as sp
import timeit
import cPickle
from scipy import signal
from sklearn import linear_model
#Used to create the tab countaining all da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.