text stringlengths 38 1.54M |
|---|
# -*- coding: utf-8 -*-
from base64 import b64decode
import os
import imghdr
from datetime import datetime
from uuid import uuid4
from PIL import Image
from resizeimage import resizeimage
import io
from flask import request, jsonify
from flask.views import MethodView
from flask_jwt_extended import jwt_required
from c... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
from flask import Flask, render_template, request, jsonify
from lib import *
app = Flask(__name__)
app.debug = True
@app.route("/")
def hello():
return render_template('index.html')
@app.route('/permanize', methods=['POST', 'OPTIONS'])
def my_service():
request.get_json(force=True)
print request.json
text = ... |
from typing import List
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
length1, lastL1 = self.getLinkedListLen(l1)
length2... |
##########################################################################
#
# Copyright (c) 2007, Image Engine Design Inc. All rights reserved.
# Copyright (c) 2011, John Haddon. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that ... |
import numpy as np
from sklearn.mixture import GaussianMixture
# Generate Synthetic data
mu1=300
sig1=100
mu2=1100
sig2=100
mu3=2000
sig3=200
x = list(np.random.normal(mu1,sig1,500))+ list(np.random.normal(mu2,sig2,500))+list(np.random.normal(mu3,sig3,500))
# Fit GMM
model = GaussianMixture(n_components=3, max_iter... |
# Declaring different data structures
tails=["T1","T2","T3","T4","T5","T6"]
gates=["AUS1","DAL1","DAL2","HOU1","HOU2","HOU3"]
airports=["AUS","DAL","HOU"]
flight_times={"AUSDAL":50,"DALAUS":50,"AUSHOU":45,"HOUAUS":45,
"DALHOU":65,"HOUDAL":65}
ground_time={"AUS":25,"DAL":30,"HOU":35}
schedule_flight... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: ivan
"""
"""
Dataset Creation
"""
#Loading Libraries
import time
import warnings
import concurrent
import pandas as pd
from functools import reduce
from pyhorse.Feature_Creation import Feature_Storage
from pyhorse.Database_Management import Extraction_Databa... |
# -*- coding: utf-8 -*-
import picamera
import picamera.array
import cv2
import pygame
import sys
pygame.init()
size=(320,240)
screen = pygame.display.set_mode(size)
def pygame_imshow(array):
b,g,r = cv2.split(array)
rgb = cv2.merge([r,g,b])
surface1 = pygame.surfarray.make_surface(rgb)
surface... |
"""
This module contains classes used to describe cluster configuration
"""
import os.path
import os
import inspect
import json
import contextlib
import tarfile
import hashlib
import tempfile
import base64
import io
import yaml
import pkg_resources
import docker
import docker.errors
from .. import utils
class Bas... |
class Node(object):
def __init__(self, value=None):
self.value = value
self.left = None
self.right = None
def get_value(self):
return self.value
def set_value(self, value):
self.value = value
def get_left_child(self):
return self.left # PJ: We are c... |
#!/usr/bin/python
rows = input("Enter no. of rows:")
for i in range(rows,0,-1):
for i in range(i):
print "*",
print ""
|
"""
Takes an unsolved Sudoku puzzle and returns it solved.
"""
import re
from collections import Counter
NUM_SEARCHES = 0
# Define some helpful global variables
def cross(A, B):
"""
Cross product of elements in A and elements in B.
"""
return [a + b for a in A for b in B]
rows = 'ABCDEFGHI'
cols = ... |
import sys, logging
logging.basicConfig(stream = sys.stderr)
from flask import render_template, request, jsonify, make_response
from app import app
from datetime import datetime, timedelta
import pymysql as mdb
import json
import re, os
import pandas as pd
import numpy as np
from time import mktime
import pickle
# ut... |
from ethernet_servo.control import units
from ethernet_servo.api import api, BaseResource
from . import models
ns = api.namespace('devices', description='Configured servo controllers')
@ns.route('/<string:name>/goto')
@ns.param('name', 'The servo controller name as configured')
class DeviceGotoRaw(BaseResource):
... |
from django.conf import settings
from django.contrib.auth.models import User
from django.test import override_settings
from model_mommy import mommy
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from .utils import (assign_user_to_role, create_d... |
# vim: ai ts=4 sts=4 et sw=4
from mwana.apps.userverification.models import DeactivatedUser
from mwana.apps.userverification.models import UserVerification
from django.contrib import admin
from django.db.models import Max
from rapidsms.contrib.messagelog.models import Message
class UserVerificationAdmin(admin.Model... |
# Generated by Django 3.1.7 on 2021-06-04 17:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('page', '0006_auto_20210604_2027'),
]
operations = [
migrations.AddField(
model_name='whatjob',
name='title',
... |
from model.contact import Contact
from random import randrange
def test_modify_some_contact(app, db, check_ui):
if len(db.get_contact_list()) == 0:
app.contact.create(Contact(firstname='test'))
old_contacts = db.get_contact_list()
index = randrange(len(old_contacts))
contact = Contact(firstnam... |
import math
import sys
fin = sys.stdin
num_cases = int(fin.readline().strip())
def solve(B,M):
if M > 2 ** (B-2):
return None
slides = []
for _ in range(B):
slides.append([0] * B)
for i in range(B-1):
for j in range(i+1, B-1):
slides[i][j] = 1
for j in range... |
from __future__ import annotations
from os import getcwd, path
from traceback import extract_tb, print_exception
from flask import Response, jsonify, current_app
from werkzeug.exceptions import HTTPException
from jsonclasses.excs import (ObjectNotFoundException,
ValidationException,
... |
# Copyright 2016-2022. Couchbase, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
from django.db import models
from django.contrib.auth import get_user_model
from patients.models import Patients
class Doctors(models.Model):
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='doctors_user')
specialised = models.CharField(max_length=15, default='PATIENT')
... |
from ROAR.planning_module.local_planner.smooth_waypoint_following_local_planner import SmoothWaypointFollowingLocalPlanner
from functools import reduce
from ROAR.utilities_module.utilities import two_points_to_yaw_pitch
from ROAR.perception_module.lane_detector import LaneDetector
from ROAR.planning_module.local_plann... |
import flask
from simplejson import dumps
from .. import auth
@auth.bp.route("/register",methods=("GET","POST"))
def register():
# front-end
if flask.request.method=="GET":
if auth.check_client_session():
return flask.redirect("/")
return flask.render_template(
"auth.h... |
import pandas as pd
import anndata as ad
from scipy.sparse import csr_matrix
from anndata import AnnData
def read_snv_genotyping(filename: str) -> AnnData:
""" Read SNV genotyping into an AnnData
Parameters
----------
filename : str
SNV genotyping filename
Returns
-------
AnnDat... |
import streamlit as st
from multiapp import MultiApp
import home
from classification import ClassificationMain
from clustering import ClusteringMain
# import your app modules here
app = MultiApp()
st.set_page_config(layout="wide")
# Add all your application here
app.add_app("Home", home.app)
app.add_app("Predict Lo... |
import sqlite3
conn = sqlite3.connect('database.db')
print("Database opened successfully")
conn.execute('CREATE TABLE allItems (name TEXT, addr TEXT, city TEXT, descrp TEXT, Type TEXT, aid TEXT)')
print ("Table created Successfully")
conn.execute('CREATE TABLE food (fileid INTEGER PRIMARY KEY AUTOINCREMENT,name TEX... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 16 09:15:49 2017
@author: Administrator
"""
from pyquery import PyQuery as pq
import pandas as pd
main_doc=pq('http://data.eastmoney.com/cjsj/yzgptjnew.html')
table_doc=main_doc('tr[class=""]')
text_list=[]
for each in table_doc:
text=pq(each).text().split(... |
from functions import *
def test_func():
assert func(3) == 4
def test_multiplication():
assert multiplication(4, 8) == 32
def test_price_calculation():
assert price_calculation(19) == 100
assert price_calculation(20) == 120
assert price_calculation(40) == 150
assert price_calculation(65) == 2... |
import os
import astropy.units as u
import click
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
pd.set_option('display.max_columns', 500)
from colorama import Fore
from tqdm import tqdm
from cta_plots import load_signal_events, load_background_events
from cta_plots.binning import make_defaul... |
# Copyright 2020 The Weakly-Supervised Control Authors.
#
# 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 la... |
max = 1000000
n = [1] * max
c = 2
t = 0
array=[]
while c<max:
array.append(c)
i = c
while i < max:
n[i] = 0
i += c
while c<max and n[c]==0:
c += 1
#print array
if 4 in array:
print 'hi'
else:
print 'no'
"""a=[1,2,3,4]
del a[2]
print a"""
|
"""
The ledger_data method retrieves contents of
the specified ledger. You can iterate through
several calls to retrieve the entire contents
of a single ledger version.
`See ledger data <https://xrpl.org/ledger_data.html>`_
"""
from dataclasses import dataclass, field
from typing import Any, Optional, Union
from xrpl.... |
import numpy as np
from .module import Module
class MaxPool2d(Module):
def __init__(self, kernel_size, stride=(1, 1), padding=(0, 0)):
super(MaxPool2d, self).__init__()
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
def forward(self, inputs):
... |
from collections import defaultdict, Counter
def load_foods(input_filename):
foods = []
with open(input_filename) as f:
for line in f:
line = line.rstrip("\n")
ingredients_and_allergens = line.split()
ingredients = set()
allergens = set()
pa... |
from django.db import models
class State(models.Model):
name = models.TextField(max_length=255)
abbr = models.TextField(max_length=255)
class Meta:
db_table = 'states'
def __unicode__(self):
return self.name
|
#Henry Murillo
#11/30/2020
from Project2_Flask import app
if __name__ == '__main__':
app.run(debug=True) |
import torch
from torch.optim.lr_scheduler import CosineAnnealingLR
from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer
class nnUNetTrainerCosAnneal(nnUNetTrainer):
def configure_optimizers(self):
optimizer = torch.optim.SGD(self.network.parameters(), self.initial_lr, weight_decay=sel... |
'''
author : teja
date : 10/8/2018
'''
def calculate_handlen(hand):
"""
Returns the length (number of letters) in the current hand
"""
sum_v = 0
for i_1 in hand:
sum_v = sum_v + hand[i_1]
return sum_v
def main():
'''
main
'''
n_1 = input()
adict = {}
for i_1 in r... |
"""
基于Keras的LSTM多变量时间序列预测https://blog.csdn.net/qq_28031525/article/details/79046718
数据文件https://archive.ics.uci.edu/ml/machine-learning-databases/00381/PRSA_data_2010.1.1-2014.12.31.csv
目标:利用前N_in个时刻的pollution信息,预测下N_out个时刻的pollution
笔记:
1.将时序数据转化为有监督数据的方法,这里采用随机分离的方式获取train和test
2.回归问题,loss='mae', optimizer='adam',评估采... |
import networkx as nx
from file_operations import load_pickle, save_pickle
from settings import GRAPH_GML_FILENAME, LANGUAGE_MAP_FILENAME, GRAPH_LANGUAGE_GML_FILENAME
class LanguageGraphCreator:
def __init__(self, data_dir: str, language: str):
self.data_dir = data_dir
self.graph = nx.read_gml(s... |
import setup_path
import airsim
import sys
import time
print("""This script is designed to fly on the streets of the Neighborhood environment
and assumes the unreal position of the drone is [160, -1500, 120].""")
client = airsim.MultirotorClient()
client.confirmConnection()
client.enableApiControl(True)
print("armi... |
from datetime import datetime, timezone, timedelta
def now():
hours_diference = timedelta(hours=-3)
time_zone = timezone(hours_diference)
return datetime.now().astimezone(time_zone).strftime("%d/%m/%Y - %H:%M:%S")
|
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import pymysql
from scrapy.exceptions import D... |
class Prediction:
def __init__(self, mapper=None, rareWords=None):
self.rareWords = rareWords
self.mapper = mapper
def predictOne(self, data, confidence=False):
# WordSwapperWithMapper
data = set(
filter(
lambda val: val is not None,
... |
from django.conf.urls import url
from trndy_cleaners.accounts.views import (
ClientDetailView ,
EmployeeDetailView ,
ClientListView ,
EmployeeListView
)
app_name = "accounts"
urlpatterns = [
url(r'^clients/$', ClientListView.as_view()),
url(r'^clients/(?P<user_id>[\d]+)$', ClientDetailView.... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class ModGRU(nn.Module):
def __init__(self, input_dim, h_dim):
super(ModGRU, self).__init__()
self.cell = nn.GRUCell(input_dim, h_dim)
self.comb = nn.Linear(input_dim*2, input_dim)
self.com2 = nn.Linear(input_dim+h... |
"""
The MIT License (MIT)
Copyright (c) 2015-2021 Rapptz
Copyright (c) 2021-2021 Pycord Development
Copyright (c) 2021-present Texus
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restri... |
def is_well_formed1(nstr):
left_chars = []
for ch in nstr:
if ch == "(":
left_chars.append(")")
if ch == "{":
left_chars.append("}")
if ch == "[":
left_chars.append("]")
if ch == ")":
if not left_chars or ch != left_chars.pop():
... |
# A Viginere Cipher takes an input of text
# and a key that is used to encrypt it
# using the Vigenere table.
# Refer to the image
import argparse
import os
parser = argparse.ArgumentParser(
description = "Encrypt/Decrypt using Vigenere Cipher",
usage = os.path.basename(__file__) + " -e <text> -k <key>",
... |
import asyncio
import datetime
import unittest
class Test(unittest.TestCase):
def test_command_echo(self):
counter = 0
list_input = ['echo Hello, Python!', 'echo Hello, World', 'echo very very very very long line']
list_exp = ['Hello, Python!', 'Hello, World', 'very very very very... |
# Generated by Django 2.0.7 on 2018-08-27 18:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='location',
name='foursquare_id',
... |
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board or not board[0]:
return
d = self.build_dict(board)
def build_set(self, board):
s = set()
fo... |
import glob # sciezki do plikow
import pandas as pd # wyswietlenie na stronie
import datetime as dt #pandas
import os #odpalanie
import last_zero
files_path = "in/*.txt" # sciezka do plikow in
files_path2 = "out/*.txt" # sciezka plikow out
files_in = glob.glob(files_path)
files_out = glob.glob(files_path2)
in_st... |
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, SUPERUSER_ID, _
from odoo.exceptions import UserError, ValidationError
class PurchaseOrder(models.Model):
_inherit = "purchase.order"
encumb_id = fields.Many2one('encumb.order', string='Encumberance Order', copy=False,dom... |
from django.test.client import RequestFactory
from nose import tools
from .cases import ContestTestCase
class TestContestUrls(ContestTestCase):
def setUp(self):
super(TestContestUrls, self).setUp()
self.rf = RequestFactory()
self.url = self.contest.get_absolute_url()
self.contest... |
import json
def get_file_data(file_name):
file = open(file_name)
data = json.load(file)
file.close()
return data
colors_data = get_file_data("colors.json")
families_data = get_file_data("families.json")
genders_data = get_file_data("genders.json")
life_forms_data = get_file_data("lifeForms.json")
ph... |
import random
def quicksort(list):
if len(list)<2:
return list
else:
rad = random.randint(0,len(list)-1)
pivot = list[rad]
smaller = [i for i in list[1:] if i<pivot]
bigger = [i for i in list[1:] if i>=pivot]
return quicksort(smaller) + [pivot] + quicksort(bigger... |
class NumberingSchema(Element,IDisposable):
""" A class to support assigning numbers to elements of a particular kind for the purpose of tagging and scheduling them. """
def AppendSequence(self,fromPartition,toPartition):
"""
AppendSequence(self: NumberingSchema,fromPartition: str,toPartition: str)
Appe... |
import importlib
if importlib.util.find_spec("web"):
print("import flask_sqlalchemy for models")
from web import db
Base = db.Model
orm = db
else:
print("import sqlalchemy for models")
import sqlalchemy as db
import sqlalchemy.orm as orm
from sqlalchemy.ext.declarative import declarati... |
import os
def get_temp():
# f = open("/dev/DHT11_Device", "rb")
# temp = f.readlines()
# f.close
# print(temp)
#f = os.open("/dev/DHT11_Device", os.O_RDONLY)
#text = os.read(f)
#print(text)
#os.close(f)
# with open("/dev/DHT11_Device", "rb") as f:
# print repr(f.read(10))
#print("Hello")
return os.popen("... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
from lesson3.db.dbhelper import DBHelper
class Lesson3Pipeline(object):
def process_item(self, item, spider... |
from django.contrib import admin
from .models import Category,Image
admin.site.register(Category)
admin.site.register(Image)
# Register your models here.
|
#! /usr/bin/env python
import os
import sys
sys.path.append(os.path.join(os.environ['REPO_DIR'], 'utilities'))
from utilities2015 import *
stack = sys.argv[1]
first_bs_sec, last_bs_sec = section_range_lookup[stack]
dm = DataManager(stack=stack, labeling_dir='/home/yuncong/csd395/CSHL_data_labelings_losslessAlignCrop... |
import os
# import nose
# from nose.tools import *
import logging
import shutil
LD = logging.Logger('root')
LD.setLevel(logging.INFO)
LD.addHandler(logging.StreamHandler())
class TestPlawLen(object):
@classmethod
def setup_class(cls):
num = 0
with open("data/plaws.csv", 'rb') as source:
... |
import numpy as np
# Zadanie 1 - rozklad LU macierzy
def gauss(a, level=0):
if level < a.shape[0] - 1:
for i in range(level + 1, a.shape[0]):
a[i][level] /= a[level][level]
for j in range(level + 1, a.shape[0]):
a[i][j] = a[i][j] - a[level][j] * a[i][level]
... |
if __name__ == '__main__':
with open('input.txt', 'r') as f:
with open('output.txt', 'w') as o:
lines_list = f.read().splitlines()[1:]
for idx, pancakes in enumerate(lines_list):
num_flips = 0
index = 0
curr_pancake = pancakes[0]
for pancake in pancakes:
if pancake != curr_pancake... |
#!/usr/bin/env python2.5
#
# Copyright 2011 the Melange authors.
#
# 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 applic... |
# NERD TRUE OR FALSE TEST
def nerd():
print("O usuário é nerd? [S/N]")
nerd = input()
if nerd == 's' or nerd == "sim":
print("O usuário É nerd, portanto, \nNão faltaras!!")
elif nerd == 'n' or nerd == "nao":
print("O usuário NAO É nerd, dessa forma, \nFaltarás!")
else:
pr... |
# condition to send email if 'True' email will be sent
SEND_EMAIL = True
# email smtp (smpt of yahoo, gmail, msn, outlook etc.,)
SMPT = "smtp.gmail.com:587"
# email subject
SUBJECT = "MyProject Automation Execution Status"
# credentials
FROM = "XXXXX@gmail.com"
PASSWORD = "XXXXX"
# receivers
TO = "XXXXX@gmail.com"... |
import pickle
import traceback
import glob
import os
import numpy as np
import modules.common_params.common_headless as c
import modules.memory_classes.memory_headless as m
import modules.queues.queue_headless as q
import modules.organisms.organism_headless as o
from conf.config import Config, default_ancestors
import ... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.main, name='main'),
path('index/', views.Index.as_view()),
path('about_company/', views.about_company, name='about_company'),
path('allspec/', views.AllSpec.as_view()),
path('contacts/', views.contacts, name='contacts')... |
import torch
import torch.nn as nn
from torecsys.utils.decorator import jit_experimental, no_jit_experimental_by_namedtensor
from typing import Tuple
class PositionBiasAwareLearningFrameworkLayer(nn.Module):
def __init__(self,
input_size : int,
max_num_position : int):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class KoubeiAdvertCommissionAdvertPurchaseModel(object):
def __init__(self):
self._channel_id = None
self._out_unique_id = None
self._security_code = None
... |
from model import Model;
# 2014.06.19 01:18:18 EDT
class SuperGraph:
numNodes = 0
numEdges = 0
edges = []
def __init__(self, numStructs):
self.numNodes = numStructs
self.numEdges = 0
self.edges = []
def hasEdge(self, i, j):
return max(i, j) - 1 in self.edges[(mi... |
list3 = [1, 2, 3, 2, 4, 10]
x = 0
for i in list3:
if x >= i:
pass
else:
if x <= i:
x = i
list3.append(i)
elif x == i:
list3.append(i)
print(x)
|
import matplotlib.pyplot as plt
import numpy as np
from .config_helper import CYCLES_LOG
def plot():
fig, axs = plt.subplots(2, figsize=(10, 10))
axs[0].set_title("Loss")
axs[1].set_title("Accuracy")
offset = 0
for i, cycle_log in enumerate(CYCLES_LOG):
losses, accuracies = cycle_log
... |
import re
import os
def main():
os.chdir('/photoanalysistool0/sliding_window_approach')
filename = "extracted_info.txt"
file_ptr = open(filename, "r")
write_temp_ptr = open("ref_temp.txt","w")
write_ptr = open("ref.txt","w")
line_count = 0
line_list = []
regex = re.compile('[@_!#$%^&*()<>?/\|}{~:©«¥\`~:;... |
#coding:utf-8
import web
import subprocess
import re
render = web.template.render('templates/')
urls = (
'','hello',
'/del','hello',
)
app = web.application(urls,globals())
look = subprocess.Popen("cat /proc/mdstat|grep '^md'|awk '{print $1}'",shell=True,stdout=subprocess.PIPE)
info = look.stdout.re... |
string_value = 'hogehoge'
int_value = 123
int_list = [1, 2, 3, 'str']
dict_sample = {'foo':1, 'bar':2}
if type(string_value) == str:
print("string_value is str")
if type(int_value) == int:
print("int_value is int")
if type(int_list) == list:
print("int_list is list")
if type(int_list[0]) == int:
pri... |
import Setup
#Save dictionary to json file.
def UCLAClean():
"""Cleans the scraped data from the UCLAScraper. returns the results in a dictionary containing the "columns"
'name','description' and 'preqName' and the "rows" with the course number labels. The function returns the
dictionary and saves a c... |
from time import time
n_max = 1000000
integers = list(range(n_max))
integers[1]=0
i = 2
while i*i <= n_max :
if integers[i]!=0 :
for j in range(2,(n_max-1)//i+1) :
integers[j*i] = 0
i+=1
primes = [u for u in integers if u!=0]
t = time()
def Rmod(k,n) :
m = 0
m10 = 1
for i in range(k) :
m+=m10
m10*=1... |
# Copyright 2014
# The Cloudscaling Group, Inc.
#
# 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... |
from Grafica import Grafica
import random
def GNP(n,p):
G = Grafica(n)
for u in range(n):
for v in range(u+1, n):
r = random.random()
if r < p:
G.conectar(u,v)
return G
def generar_parejas(n):
parejas = []
for u in range(n):
for v in range(u+... |
import matplotlib.pyplot as plt
import numpy as np
freq = 2e6
t_symbol = 1e-6
n_symbols = 2
sampling_rate = 1e8
n_samples = sampling_rate * t_symbol * n_symbols
dt = 1/sampling_rate
t = np.linspace(0, dt * (n_samples - 1), n_samples)
y = np.sin(2 * np.pi * freq * t )
plt.plot(t, y)
plt.show()
|
from Domain.Repository import IRoiSeriesRepository
from Domain.Model import ZRoiSeries
from Infrastructure.Repository import connection_to_db
from typing import List
class ImpSqliteRoiSeriesRepository(IRoiSeriesRepository):
def get_all_roi_series(self) -> List[ZRoiSeries]:
pass
def get_roi_series_fr... |
order_list = ['Wings', 'Cookies', 'Spring Rolls', 'Salmon', 'Steak', 'Meat Tornado',
'A Literal Garden', 'Ice Cream', 'Cake', 'Pie', 'Coffee', 'Tea', 'Unicorn Tears']
print("""
**************************************
** Welcome to the Snakes Cafe! **
** Please see our menu below. **
**
** To qu... |
# Generated by Django 3.0.4 on 2020-06-06 17:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gestionAsociados', '0018_auto_20200606_1245'),
]
operations = [
migrations.AlterField(
model_name='educacion',
name=... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: file
Description :
Author : ybw
date: 2020/11/16
-------------------------------------------------
Change Activity:
2020/11/16:
-------------------------------------------------
... |
import newt,csv,unicodedata,os
import networkx as nx
import newtx as nwx
api=newt.getTwitterAPI()
users=['lfeatherstone','jamesgraymp','davidevennett','mike_fabricant']
projpath='test'
sampleSize=997
def checkDir(dirpath):
if not os.path.exists(dirpath):
os.makedirs(dirpath)
def outputter(fn,twd):
f=open(fn,... |
import os
import random
import tensorflow as tf
from datasets.tf_datasets import create_ucf101_data_feed_for_k_sample_per_action_iterative_dataset, \
create_data_feed_for_train, create_diva_data_feed_for_k_sample_per_action_iterative_dataset_unique_class_each_batch
from models import ModelAgnosticMetaLearning, C3... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver=webdriver.Firefox()
driver.get("http://youtube.com")
search=input("What to search in youtube: ")
try:
ytbSearch=driver.find_element_by_id("masthead-search-term")
ytbSearch.send_keys(str(search))
vidSearch=driver.fi... |
#A9_Q1
class Animal:
def animal_attribute(self):
print("IT has 4 legs")
class Tiger(Animal):
def properties(self):
print("IT has a tail")
y=Tiger()
y.properties()
y.animal_attribute()
#A9_Q2
#OUTPUT-A,B
#A9_Q3
class Cop:
def __init__(self, name, age, workexp, desg):
self.name = ... |
import random
import matplotlib.pyplot as plt
import numpy as np
import copy
gt = np.array([1/6, 2/6, 3/6, 4/6, 5/6], dtype = np.float)
def get_sequence():
states = []
rewards = []
currentState = 2
while currentState != -1 and currentState != 5:
states.append(currentState)
currentState... |
import numpy as np
import cv2 as cv
import glob
if __name__ == "__main__":
image_file_names = glob.glob("/home/vignesh/Documents/COS700/Code/models/research/deeplab/datasets/potsdam/exp/train_on_trainval_set_mobilenetv2/vis/segmentation_results/*prediction.png")
image_count = 0
image_file_names.sort()
... |
# -*- coding:utf-8 -*-
import pymysql.cursors
from config import settings
from base.base_log import BaseLogger
logger = BaseLogger(__name__).get_logger()
def execute(sql, params=None, db=settings.TEST_DEFAULT_DB, is_fetchone=True):
# Connect to the database
connection = pymysql.connect(host=settings.TEST_MYS... |
"""
This type stub file was generated by pyright.
"""
from sqlite3 import dbapi2 as Database
from typing import Any, Callable
from django.db.backends.base.base import BaseDatabaseWrapper
def decoder(conv_func: Callable) -> Callable:
...
class DatabaseWrapper(BaseDatabaseWrapper):
...
FORMAT_QMARK_REGEX: An... |
from distutils.core import setup
setup(
name='TasksToPipeline',
version='',
packages=['oauth2', 'cssutils', 'cssutils.css', 'cssutils.tests', 'cssutils.tests.test_encutils',
'cssutils.scripts', 'cssutils.stylesheets', 'httplib2', 'requests', 'requests.packages',
'requests.packag... |
n = raw_input()
nL = len(n)
cnt = 0
while len(n) != 1:
s = 0
for i in n:
s += int(i)
n = str(s)
cnt += 1
print cnt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.