text stringlengths 8 6.05M |
|---|
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_text
from django.utils.http import u... |
# Generated by Django 3.1.2 on 2020-10-31 13:49
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('testingSystem', '0002_auto_20201031_1136'),
]
operations = [
migrations.CreateModel(
name='Chec... |
# Importing repositries
import csv
import random
# DEBUG
#task_number = random.randint(0, 10) #Giving me random lines
# Importing routine file
raw_morning_data = open('morn_data.csv') #importing the data raw
read_morning_data = csv.reader(raw_morning_data) #reading the data raw
row = list(read_morning_data) #creating... |
# Write a Python program to convert a pair of values into a sorted unique array
def sortValues(values):
print(sorted(values))
values = [3,4,2,3,5,6,4,3]
sortValues(values) |
# -*- 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 Crawler.Edinburgh.Edinburgh import settings
class EdinburghPipeline(object):
'''
#链接数据库
def ... |
import pandas as pd
path = input("type your path:")
name = input("type your file name:")
rst = name + 'negf.fasta'
aim= path+ '/' + name + "neg.csv"
resu=path+ '/' + rst
df1 = pd.read_csv(aim)
with open(resu,'a') as file_handle:
n2=0
for row in df1.itertuples():
aimid = row[2]
... |
# Copyright 2017 Google 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 in writin... |
#####################################
# Imports
#####################################
# Python native imports
from PyQt5 import QtCore, QtGui, QtWidgets
import time
import logging
import socket
import rospy
# Custom Imports
#####################################
# Global Variables
####################################... |
# Copyright (c) 2020. Yul HR Kang. hk2699 at caa dot columbia dot edu.
import numpy as np
from matplotlib import pyplot as plt
from pprint import pprint
import time
import numpy_groupies as npg
from collections import OrderedDict as odict
from typing import Union, Iterable, Sequence, Callable, Tuple, Any
import torc... |
#jci5kb Justin Ingram
#mgb5db Megan Bishop
from random import shuffle
from negotiator_base import BaseNegotiator
class CareBearBot(BaseNegotiator):
iteration_limit = 500
def __init__(self):
super().__init__()
# History of offers
self.our_offer_history = []
self.enemy_offer_his... |
import random
def get_rand_list(b,e,N):
r_list=random.sample(range(b,e),N)
return (r_list)
def get_overloap(L1,L2):
L3=[]
for num in L1:
if num in L2:
L3.append(num)
return (L3)
def main():
list1=get_rand_list(0,10,5)
list2=get_rand_list(0,10,5)
print(list1)
p... |
from utils.io import *
def export_inferred_stance():
predicted_stance_path = ""
input_stance_path = "" |
"""
Given a binary tree, return the sum of values of its deepest leaves.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def deepestLeavesSum(self, root) -> int:
if not ro... |
# -*- coding: utf-8 -*-
import unittest
import sys
sys.path.append('../../python')
from testecono.TestUser import TestUserPersist
from testecono.TestUser import TestUserDelete
from testecono.TestUser import TestUserFindById
from testecono.TestUser import TestUserFindAll
from testecono.TestJustification import *
... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import threading
from pathlib import Path
from typing import Callable
from pants.bsp.spec.lifecycle import InitializeBuildParams
from pants.bsp.spec.not... |
my_name = 'Damiano'
your_name = input('Enter your name: ')
print(f'Hello {your_name}!')
age = input('Enter your age: ') # Enter 3
print(f'You have lived for {age * 12} months.') # Prints You have lived for 333333333333 months.
age = input('Enter your age: ') # Enter 3
age_num = int(age)
print(f'You have lived for... |
"""
This file contains your PayPal test account credentials. If you are just
getting started, you'll want to copy api_details_blank.py to api_details.py,
and substitute the placeholders below with your PayPal test account details.
"""
from paypal import PayPalConfig
# Enter your test account's API details here. You'l... |
from FK import *
import serial
import math
import time
PI = math.pi
RADIUS = 80
def usage():
print "Usage : input 9 pose parameters."
ser = serial.Serial(
port='/dev/cu.usbmodem1421',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
ser.isOp... |
import tensorflow as tf
sess = tf.Session()
hello = tf.constant('Hello, TensorFlow!')
print sess.run(hello)
a = tf.constant(10)
b = tf.constant(32)
print sess.run(a + b)
a = tf.placeholder("float")
b = tf.placeholder("float")
y = tf.mul(a, b)
print sess.run(y, feed_dict={a: 3, b: 3})
|
#Transfer weights from model trained with normal LSTM unit to unrolled LSTM units
import sys
sys.path.append('utils/')
from init import *
import pdb
sys.path.insert(0, pycaffe_path)
sys.path.insert(0, 'utils/python_layers/')
import caffe
caffe.set_mode_gpu()
caffe.set_device(0)
import argparse
import numpy as np
def ... |
from django.db import models
from django.forms import ModelForm
class Results(models.Model):
petal_length = models.FloatField()
petal_width = models.FloatField()
sepal_length = models.FloatField()
sepal_width = models.FloatField()
prediction = models.CharField(max_length=100)
'''
class PredictForm(ModelForm):
cl... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author: Andy Garcia
# Date: 1/28/2017
import sys, os
from PyQt5.QtWidgets import (QWidget, QGridLayout,
QPushButton, QApplication, QCheckBox, QSlider)
from PyQt5 import (QtGui,QtCore)
import serial
#sys.path.append(os.path.dirname(__file__) + "../XboxController/")... |
import os.path
import regions_classifier as rc
from svm_tools import get_dataset_prediction_rank
def usage_regions_classifier():
alphabet = "ACGT"
radius = 10
count = 10
dataset = rc.Dataset(os.path.abspath(r"..\..\data\germline\human\VJL_combinations.fasta"),
os.path.abspath... |
from bing_image_downloader import downloader
downloader.download('apple fruit', limit=3, output_dir='dataset/train')
# downloader.download('fresh guava', limit=350, output_dir='dataset/test') |
print('5 задание')
str = input('Введите сторку: ')
list = str.split(' ')
amount = len(list)
print('Количество слов в строке: ', amount)
#python task5.py |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/9/27 11:38
# @Author : Jason
# @Site :
# @File : decision_tree.py
# @Software: PyCharm
import pandas as pd
from sklearn.tree import DecisionTreeClassifier as DTC
from sklearn.tree import export_graphviz
from sklearn.externals.six import String... |
import unittest
import depfinder.finder as finder
class FinderTest(unittest.TestCase):
def test_find_deps(self):
deps = finder.find_deps('depfinder')
ground_truth = ['coverage', 'chardet', 'idna', 'urllib3',
'requests', 'docopt', 'coveralls']
result = [True for p... |
#!/usr/bin/env python
# coding: utf-8
# Copyright 2017 Google 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 a... |
#encoding:utf-8
import pymysql
import requests
# 打开数据库连接
db = pymysql.connect("rm-2ze6g25687k3mjso64o.mysql.rds.aliyuncs.com",
"shaozi2016", "XLyNF4I0TQA9YXZf", "db_test")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
query_sql='select content from sz_message ... |
import csv
import sys
from urllib import request, error
import shutil
import json
import os
import ssl
def import_species_list(species):
SPECIES_LIST = {}
fields = ["num","name"]
with open(species) as csvfile:
f = csv.DictReader(csvfile, fields)
for row in f:
SPECIES_LIST[int(r... |
# Generated by Django 3.0.4 on 2020-04-19 12:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('apps', '0008_auto_20200419_1502'),
]
operations = [
migrations.AlterField(
model_name='question',
name='answer',
... |
"""Package level common values"""
import os
DEBUG = False
BASE_URL = 'http://localhost:5000/api/' if DEBUG else 'http://auacm.com/api/'
try:
session = open(
os.path.join(os.path.expanduser('~'), '.auacm_session.txt'),
'r').readline().strip()
except IOError:
session = ''
# pylint: disable=anom... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 22 00:22:04 2019
@author: HP
"""
T=int(input())
while(T):
n,m=[int(x) for x in input().split()]
A=[]
for i in range(n):
B=[int(x) for x in input().split()]
A.append(B)
DP=[[0 for i in range(m)] for j in range(n)]
for i in ra... |
#-*- coding: utf-8 -*-
import pandas as pd
import matplotlib.pyplot as plt
catering_sale = '../data/catering_sale.xls'
data = pd.read_excel(catering_sale, index_col=u'日期')
plt.rcParams['font.sans-serif'] = ['SimHei'] #正常显示中文
plt.rcParams['axes.unicode_minus'] = False #正常显示正负号
plt.figure()
# box_line = plt.boxplot(r... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 5 00:53:28 2020
@author: lifecell
"""
print(7+8)
7+8 |
from django.conf import settings
from django.http import HttpResponse
from django.utils import timezone
from django.views import View
from osmcal import views
from pytz import timezone as tzp
from timezonefinder import TimezoneFinder
from . import serializers
from .decorators import ALLOWED_HEADERS, cors_any, language... |
#!/usr/bin/env python3
'''
python_package_template setup config
'''
import os
from setuptools import setup
here = os.path.dirname(__file__)
about = {}
with open(os.path.join(here, 'python_package_template', '__about__.py')) as fobj:
exec(fobj.read(), about)
setup(
name='python_package_template',
version=... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import getopt
import json
import logging
from analyse_immo.factory import Factory
from analyse_immo.database import Database
from analyse_immo.rendement import Rendement
from analyse_immo.rapports.rapport import generate_rapport
__NAME = 'Analyse ... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
train = pd.read_csv("kospi200test_r.csv")
end_prices = train['종가']
#normalize window
x_len = 40
y_len = 10
sequence_length = x_len + y_len
result = []
for index in range(len(end_prices) - sequence_length + 1):
idk = []
idk[:] = end_pr... |
import json
from celery import shared_task
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Count
from responses.models import NewsOrgType, Response, Tool, ToolTask
from responses.utils.aws import defaults, get_bucket
@shared_task(acks_late=True)
def add_survey_response(respons... |
#!/usr/bin/env python
# encoding: utf-8
from datetime import datetime
TIMESTAMP = datetime.today().strftime('%Y%m%d-%H%M%S') |
import abc
from typing import List
from app.domainmodel.user import User
from app.domainmodel.movie import Movie
from app.domainmodel.actor import Actor
from app.domainmodel.genre import Genre
from app.domainmodel.review import Review
from app.domainmodel.director import Director
repository_instance = None
class Re... |
import math
import random
import time
import matplotlib.pyplot as plt
from pyrep import PyRep
from pyrep.objects.shape import Shape
class RRT:
'''
Define a node class that represents a node in our RRT
'''
class Node:
def __init__(self, x, y, theta):
self.x = x
self.y = y
self.theta = ... |
class Book:
title = ""
author = ""
code = 0
def init(self, title, author, code):
self.title = title
self.author = author
self.code = code
def print(self):
print(self.title)
print(self.author)
print(self.code)
|
from django.db import models
from django.db.models.fields import TextField
from .base_modles import Timestamp
from .card_models import CardInfo
class CardComment(Timestamp):
for_card = models.ForeignKey(CardInfo,on_delete=models.CASCADE)
name = models.CharField(max_length=515,null=True,blank=True)
body = m... |
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#################################################################################
# #
# plot_data.py: plot all science run interruption related data #
# ... |
#!/usr/bin/python3
## Get image data
## to the "imu_data" topic
import rospy
from sensor_msgs.msg import Image
from geometry_msgs.msg import Pose
# Dependencies for estimation
import numpy as np
from scipy.signal import find_peaks, butter, filtfilt
class PosEstimator():
def __init__(self):
self.top... |
import sys
import random
import time
import config
import py3buddy
import globals
colorlist = {"NOCOLOUR": py3buddy.NOCOLOUR,
"RED": py3buddy.RED,
"BLUE": py3buddy.BLUE,
"GREEN": py3buddy.GREEN,
"CYAN": py3buddy.CYAN,
"YELLOW": py3buddy.YELLOW,
... |
# -*- coding:utf-8 -*-
# inheritance
class FirstClass(object):
pass
if __name__ == '__main__':
f = FirstClass()
|
from ._title import Title
from plotly.graph_objs.parcoords.line.colorbar import title
from ._tickformatstop import Tickformatstop
from ._tickfont import Tickfont
|
"""Exceptions, error handlers, and high level validators."""
class TinyFlowException(Exception):
"""Base exception for ``tinyflow``."""
class NotAnOperation(TinyFlowException):
"""Raise when an object should be an instance of
``tinyflow.ops.Operation()`` but isn't.
"""
class NotACoroOperation(No... |
# Generated by Django 2.2.4 on 2019-10-06 08:03
from django.db import migrations, models
import django.db.models.deletion
import smart_selects.db_fields
class Migration(migrations.Migration):
dependencies = [
('announcements', '0002_auto_20191005_1658'),
]
operations = [
migrations.Alte... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 28 11:18:32 2019
@author: se14
"""
# train the FP reduction network for fold k (user inputted variable)
import os
import sys
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
import matplotlib.pyplot as plt
import time... |
a = 1
print(a)
a = 3
print(a)
print(a)
# 檔名: indent_demo.py
# 作者: Kaiching Chang
# 時間: July, 2014
|
__author__ = 'Justin'
import googlemaps
from googlemaps import convert
from datetime import datetime
from datetime import timedelta
gmaps = googlemaps.Client(key='AIzaSyAVf9cLmfR52ST0VZcFsf-L-HynMTCzZEM')
# Geocoding an address
# geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')
# print(g... |
#!/usr/bin/env python
class arraylist:
def __init__(self):
self.maxlength = 10000
self.elements = [None]*self.maxlength
self.last = 0
def first(self):
return 0
def end(self):
return self.last
def retrieve(self,p):
if p > self.last or p < 0... |
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applications import inception_v3
def preprocess_image(image_path):
# Util function to open, resize and format pictures
# into appropriate arrays.
img = keras.preprocessing.image.load_img(image_path)
img = ker... |
#python create_cmpd_image.py /home/chrism/metab_id/data/frag/metlin/C00642_neg_40mv.frag /home/chrism/metab_id/misc/unique_mass_lst_C00642_children_only.txt 1 0
from numpy import *
import sys
from matplotlib import pyplot as plt
CPD_MASSES = sys.argv[1]
MASS_LIST = sys.argv[2]
use_metlin = float(sys.argv[3])
mass_or_i... |
import sys
import requests
import html5lib
from bs4 import BeautifulSoup
from tqdm import tqdm
import time
reload(sys)
sys.setdefaultencoding('utf-8')
def text_save(filename, data):
file = open(filename, 'w')
for i in range(len(data)):
s = str(data[i]).replace('[', '').replace(']', '')
s = s.r... |
import ast
import time
from datetime import datetime,timedelta,date
from decimal import Decimal, ROUND_HALF_UP
from django.http import JsonResponse
from django.shortcuts import render
from django.contrib.auth.models import User
from rest_framework.views import APIView
from rest_framework import generics
from rest_fram... |
from django.shortcuts import render
from inventory.models import Item #use to query databse
from django.http import Http404 #to return 404 page when needed
# Create your views here.
def index(request):
items = Item.objects.exclude(amount=0)
return render(request, 'inventory/index.html', {'items': items,})
#creates ... |
import json
import requests
from requests.packages.urllib3.filepost import encode_multipart_formdata
class Media(object):
#def __init__(self):
#register_openers()
def uplaod(accessToken, filePath, mediaType):
openFile = open(filePath, "rb")
param = {'media': openFile.read()}
postData, c... |
# Compatibility layer between Python 2 and Python 3
from __future__ import print_function
import sqlite3
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from scipy import stats
from sklearn import metrics
from sklearn.metrics import classification_report
from sklearn... |
# -*- coding: utf-8 -*-
import pymysql
from .items import SinaNewsItem
import traceback
import logging
from Sina_News.middlewares import UrlFilterAndAdd, URLRedisFilter
import os
from twisted.enterprise import adbapi
logger = logging.getLogger(__name__)
checkFile = "isRunning.txt"
class SinaNewsPipeline(object):
... |
class Solution:
# @param A : list of list of integers
# @param B : integer
# @return an integer
def searchMatrix(self, A, B):
rows = len(A)
cols = len(A[0])
start = 0
end = rows * cols - 1
while start <= end:
mid = (start + end) / 2
num = A... |
#student I.D: 15315901
"""A class for Gaussian integers
A Gaussing integer is a complex number of the form a+bi where a and b are integers"""
"""write the code for the class Gaussian which models Gaussian integers. Your code should have:
1. A constructor so that we can create objects of the class Gaussian as follows... |
from datetime import datetime
from pydantic import BaseModel, EmailStr
class UserBase(BaseModel):
username: str
avatar: str = None
# email: EmailStr
class UserCreate(UserBase):
nickname: str
password: str
class UserActivated(UserBase):
id: int
is_active: bool
email: EmailStr
cla... |
import re
import sys
import xbmcaddon
from resources.lib import scraper, xbmc_handler
### get addon info
__addon__ = xbmcaddon.Addon()
__addonid__ = __addon__.getAddonInfo('id')
__addonidint__ = int(sys.argv[1])
def main(params):
# See if page number is set, or set it to 1
try:
page... |
import tensorflow as tf
import tensorflow.keras as keras
model = keras.applications.vgg16.VGG16(include_top=False, weights="imagenet", input_shape=(224, 224, 3))
for layer in model.layers:
layer.trainable = False
x = model.output
x = keras.layers.Flatten()(x)
x = keras.layers.Dense(30, activation="relu")(x)
x = ... |
from mod_base import*
class Part(Command):
"""Part list of channels."""
def run(self, win, user, data, caller=None):
args = Args(data)
if not args: args = [win.GetName()]
self.bot.PartChannels(args)
module = {
"class": Part,
"type": MOD_COMMAND,
"level": 2,
"zone":IRC_Z... |
import pymysql
import csv
import codecs
config = {'user': 'root',
'password':'',
'port': 3306,
'host': '127.0.0.1',
'db': 'book',
'charset': 'utf8'}
def get_conn():
conn = pymysql.connect(user=config['user'],
password=config['... |
# Generated by Django 2.2.13 on 2020-07-10 06:03
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('shop', '0035_auto_20200710_1132'),
]
operations = [
migrations.DeleteModel(
name='ContactForm',
),
migrations.DeleteMod... |
# math2: maximum minimum and factor
# zio800
from math import *
# maximum and minimum
def maxmin(lst):
nummax = lst[0]
nummin = lst[0]
for item in lst:
if item < nummin:
nummin = item
if item > nummax:
nummax = item
print('max = ', nummax, ', min... |
from django.db import models
class myform(models.Model):
data=models.CharField(max_length=20000)
title=models.CharField(max_length=100)
slabel=models.CharField(max_length=100)
class values(models.Model):
lform=models.ForeignKey(myform)
fieldId=models.CharField(max_length=10)
label=models.CharField(max... |
import datetime
from typing import List
import dateutil.tz
from flask import Blueprint, render_template, request, redirect, url_for, abort, flash
from . import db, model
from .model import Survey
import flask_login
import json
bp = Blueprint("main", __name__)
@bp.route("/")
@flask_login.login_required
def index... |
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
import statsmodels.formula.api as smf
from linearmodels import RandomEffects
from statsmodels.regression.rolling import RollingOLS
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
f... |
import requests
url = "http://google.com"
headers = {"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64)\
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.68"}
res = requests.get(url, headers = headers)
res.raise_for_status()
print(len(res.text))
with open("myGoogle.htm... |
import random
import physics as phy
from math import pow, sqrt
import graphics
class Moon:
def __init__(self, h, s):
self.height = h
self.size = s
self.angle = random.randint(0,399)
self.position = 0, 0
self.last_move = None
self.update_pos()
self.tower = Non... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-09-07 13:51
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('garmin', '0006_auto_20170907_0934'),
]
operatio... |
from vtk_rw import read_vtk, write_vtk
import numpy as np
compartment = 'upper'
hemis = ['lh', 'rh']
vtk_file = '/scr/ilz3/myelinconnect/new_groupavg/profiles/%s/%s/%s_lowres_new_avgsurf_groupdata.vtk'
avg_npy_file = '/scr/ilz3/myelinconnect/new_groupavg/profiles/%s/%s_group_avg_profiles_%s.npy'
#avg_vtk_file = '/sc... |
from django.http import HttpResponse
import os
import sys
import dotenv
from linebot import LineBotApi, WebhookParser
from linebot.models import TextSendMessage
dotenv.load_dotenv()
channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None)
if channel_access_token == None:
print('Specify LINE_CHANNEL_A... |
# -*- coding: utf-8 -*-
import csv
import scrapy
import os
class AppradiofmSpider(scrapy.Spider):
name = 'appradiofm'
allowed_domains = ['appradiofm.com']
start_urls = ['http://appradiofm.com/by-country/']
def parse(self, response):
datas = response.xpath('.//*[@class="col s12 m6 l4 margin-al... |
class DataAugmentation(object):
""" Data Augmentation.
Base class for applying common real-time data augmentation.
This class is meant to be used as an argument of `input_data`. When training
a model, the defined augmentation methods will be applied at training
time only. Note that DataPreprocess... |
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import numpy as np
from math import *
theta = 0
alpha = 0
def init():
glClearColor(0.051, 0.051, 0.051, 0)
glClear(GL_COLOR_BUFFER_BIT)
glMatrixMode(GL_PROJECTION)
gluPerspective(90, 1, 1, 3050)
gluLookAt(50... |
import numpy as np
import sys
import os
import graphlab
from preprocess import *
from kmeans import *
from visualization import *
# load wikipedia data
wiki = graphlab.SFrame('../../data/people_wiki.gl/')
# preprocess TF IDF structure
wiki['tf_idf'] = graphlab.text_analytics.tf_idf(wiki['text'])
# transform into a ... |
import time, pytest
import sys,os
sys.path.insert(1,os.path.abspath(os.path.join(os.path.dirname( __file__ ),'..','..','lib')))
from clsCommon import Common
import clsTestService
from localSettings import *
import localSettings
from utilityTestFunc import *
import enums
class Test:
#=========================... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 02 13:19:51 2013
@author: mark
"""
# General imports
import math
import numpy as np
from datetime import datetime
from datetime import timedelta
import pandas as pd
def td_to_mins(x):
"""
Converts a timedelta object to minutes
"""
return x.days * 24.0 * ... |
#!/usr/bin/python
#
# Copyright 2014 Google.
#
# 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 ... |
#!/usr/bin/env python
# encoding: utf-8
'''
Find MST for facilities problem.
'''
import glob
import json
import itertools
from operator import attrgetter
import os
import random
import sys
import math
import networkx as nx
import numpy
import random as Random
#Returns an array of the shortest path between any two p... |
#
# n1 = 255
# n2 = 1000
#
# print(hex(n1), hex(n2))
import math
print(math.sqrt(100))
def quadratic(a, b, c):
if b ** 2 - 4 * a * c >= 0:
slt1 = -b + math.sqrt(b ** 2 - 4 * a * c)
slt1 = slt1/(2*a)
slt2 = -b - math.sqrt(b ** 2 - 4 * a * c)
slt2 = slt2 / (2 * a)
... |
print("1st loop:")
for name in "John", "Sam", "Luis":
print("Hello " + name + "\n")
print("\n2nd loop with defined range:")
for i in range(10, 30):
print(i)
print("\n3rd loop with only given a sequence")
for i in range(10):
print(i)
print("\n4th loop")
total = 0
for i in 5,6,11,13:
print(i)
to... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as pub... |
from flask.blueprints import Blueprint
import logging
from flask_login import login_required
from flask.templating import render_template
from waitlist.permissions import perm_manager
from waitlist.storage.database import CCVote, Account
from waitlist.base import db
from sqlalchemy.sql.functions import func
bp = Blue... |
person = {
"name":"win.d",
"Play" : "pubg PC",
}
print(person)
person["status"] = "live streaming"
print(person)
person = {
"name" : "frank lampard",
"description" : "legendary Icon",
}
print(person)
person["age"] = "41"
del person["age"]
print(person)
person["status"] = "coaching chealse... |
from pathlib import Path
def read_fasta(fasta_file):
sequences = []
with Path(fasta_file).open('r') as ff:
sequence = []
for line in ff:
if line.startswith('>'):
if sequence:
sequences.append(''.join(sequence))
sequence = []... |
import os
import argparse
import csv
from sys import exit
from datetime import datetime, date
my_path = "C:/Programming/Alpha/CSV/"
"""
parser = argparse.ArgumentParser(description='First Test using Command Line Args')
parser.add_argument('-i','--input', help='Input file name',required=True)
parser.add_argument('-o',... |
from girder.models.setting import Setting
from girder.plugins.imagespace.settings import ImageSpaceSetting
class CmuSetting(ImageSpaceSetting):
requiredSettings = ('IMAGE_SPACE_CMU_PREFIX',
'IMAGE_SPACE_CMU_BACKGROUND_SEARCH',
'IMAGE_SPACE_CMU_FULL_IMAGE_SEARCH')
... |
def decorator_function(any_function):
def wrapper_function():
print('this is awesome function')
any_function()
return wrapper_function()
@decorator_function
def func1():
print('esta es la funcion uno')
func1()
|
from pandas.core.common import flatten
from collections import defaultdict
input = open('data/16.txt').read().split('\n\n')
all_rules = [list(map(int, i.split(' ')[-4:])) for i in input[0].replace('or ', '').replace('-', ' ').split('\n')]
rule_names = [i.split(' ')[0] for i in
input[0].replace('departure... |
from .set_convolution import SetConvLayer
from data import load_dataset
import torch
import torch.nn as nn
from sklearn.cluster import KMeans
import numpy as np
# binary classifier
class SetConvNetwork(torch.nn.Module):
def __init__(self, cfg, anchor):
super(SetConvNetwork, self).__init__()
sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.