text stringlengths 8 6.05M |
|---|
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
# Create your views here.
def about(request):
return render(request, 'about/about.html')
def idea(request):
return render(request, 'about/idea.html')
def introduction(request):
return render(request, 'about/intr... |
from . import *
class RequestList(Base):
__tablename__= 'requestlist'
__table_args__ = {'mysql_engine':'MyISAM'}
id = Column('ID', Integer, primary_key=True)
song_id = Column('songID', Integer, ForeignKey('song.id'), index=True)
t_stamp = Column(DateTime, index=True)
host = Column(String(255))
... |
#!/usr/bin/env python3
import argparse
import bs4
import github
import json
import re
import requests
import sys
import ssdeep
import sre_constants
import os
import os.path
import urllib.parse
import time
import base64
SIMILARITY_THRESHOLD = 65
ACCESS_TOKEN_BASE64 = 'Z2hwX0tCOGl1SEVrMng5THFzZTIxalA2Y1BkTlg2OGhNbTRCQT... |
#Programa: act19.py
#Propósito: Escribe un programa que pida un número entero entre uno y doce e imprima el número de días que tiene el mes correspondiente.
#Autor: Jose Manuel Serrano Palomo.
#Fecha: 17/10/2019
#
#Variables a usar:
# dias array para los dias de los meses
# mes será el mes del año
#
#Algoritmo:
# LEER ... |
"""trymake URL Configuration
Author: Sidhin S Thomas (sidhin@trymake.com)
Copyright (c) 2017 Sibibia Technologies Pvt Ltd
All Rights Reserved
Unauthorized copying of this file, via any medium is strictly prohibited
Proprietary and confidential
"""
from django.conf.urls import url, include, static
from django.contr... |
from rest_framework import serializers, fields
from accounts.api.serializers import AuthorSerializer
from GlobalModels.models import (
Location,
Skills,
Field_of_work,
Tools,
Frame,
Frame_comment
)
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
... |
import tushare as ts
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
df = ts.get_hist_data('600848')
def makeChange(v):
if( v > 0):
return 1
elif( v < 0):
return -1
else:
return 0
changeVl = df.... |
from flask_security.signals import user_registered, user_confirmed
from flask.ext.login import user_logged_out
from ..admin import add_admin_view
from ..signals import user_changed_profile
from . import views, sso, admin
from .config import DiscourseConfig
def init_app(app):
config = DiscourseConfig.from_app(app)... |
""" The manage subscription views. """
import morepath
from onegov.election_day import _
from onegov.election_day import ElectionDayApp
from onegov.election_day.collections import DataSourceCollection
from onegov.election_day.collections import DataSourceItemCollection
from onegov.election_day.forms import DataSource... |
import sys
from PyQt4 import QtGui, uic
app = QtGui.QApplication(sys.argv)
widget = uic.loadUi('at.ui')
widget.show()
sys.exit(app.exec_())
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-04-14 09:47
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('SRS', '0004_student'),
]
operations = [
migrations.CreateModel(
... |
# 生成器都是迭代器,迭代器不一定都是生成器
# 可迭代对象:list,tuple,dict,string
from collections import Iterable,Iterator,Generator
l=[1,2,3]
d = iter(l) # <list_iterator object at 0x10be38908>
print(d)
# 什么是迭代器:
# 满足两个条件:有iter方法,有next方法
'''
凡是可作用于for循环的对象都是Iterable(可迭代对象)类型
凡是可作用域next()函数的对象都是Iterator(迭代器)类型它表示一个惰性计算的序列
'''
print(next(d))
p... |
from typing import Any, Dict
class EventEnricher:
def enrich(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""
I provide additional data for an event
The data is enriched in-place, but also returned for convenience
Args:
data: calendar data in ou... |
from openpyxl import Workbook
count = input('全シート数 : ')
# Workbookオブジェクト生成
wb = Workbook()
# WorkSheetオブジェクト取得
ws = wb.active
# デフォルトで作成されるシート名を変更
ws.title = '概要_1'
for i in range(2, int(count) + 1):
# シートを作成する
# シート名はtitle引数で指定する
# f-stringsを使用
wb.create_sheet(title=f'概要_{i}')
wb.save('シート数指定.xlsx'... |
#!-*- coding:utf8-*-
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph() # 建立一个空的无向图G
G.add_node(1) # 添加一个节点1
G.add_edge(2, 3) # 添加一条边2-3(隐含着添加了两个节点2、3)
G.add_edge(3, 2) # 对于无向图,边3-2与边2-3被认为是一条边
print("nodes:", G.nodes()) # 输出全部的节点: [1, 2, 3]
print("edges:", G.edges()) # 输出全部的边:[(2, 3)]
print(... |
from onegov.form.fields import MultiCheckboxField as MultiCheckboxFieldBase
from onegov.form.widgets import MultiCheckboxWidget as MultiCheckboxWidgetBase
from onegov.gazette import _
class MultiCheckboxWidget(MultiCheckboxWidgetBase):
def __call__(self, field, **kwargs):
kwargs['data-expand-title'] = fi... |
from .base import FuncTest
class LayoutStylingTest(FuncTest):
def test_layout_and_styling(self):
# Edith goes to the home page.
self.browser.get(self.server_url)
self.browser.set_window_size(1024, 768)
# She notices the input box is nicely centered.
input_box = self.get_i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 5 13:48:56 2021
@author: janeyalex
"""
import pandas as pd
import collections
f = open("ulysses.txt",'r')
l1=[]
l2=[]
for line in f:
lineword=line.split(':')
#if not lineword[0].isdigit():
l1.append(lineword[0])
l2.append(int(line... |
Temp = eval(input("How warm is it out today?"))
if Temp > 104:
print("Wow, its very hot out")
elif Temp > 86:
print("Wow, its hot out")
elif Temp > 68:
print("Huh, its pretty warm out today")
elif Temp > 50:
print("O... |
from sklearn.feature_extraction.text import TfidfTransformer, TfidfVectorizer
from sklearn.svm import LinearSVC, SVC
from sklearn.metrics import f1_score,classification_report, confusion_matrix
import pandas as pd
from pprint import pprint
from collections import Counter
df=pd.read_csv('texts.csv')
df2=pd.read_csv('/U... |
import string
import random
from random import randint
while True:
s=string.printable
n=input("\nenter anything")
x=random.choice([10,11,12,13,14,15])
print(s[randint(0,10)],end="")
print(s[randint(11,37)],end="")
print(s[randint(63,89)],end="")
#print(s[randint(90,99)],end="")
for i in... |
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
import re
def validate_telephone(telephone):
if not re.match(r'\+7\(\d{3}\)-\d{3}-\d{2}-\d{2}$', telephone):
raise ValidationError(
_(f'Telephone number should be +7(XXX)-XXX-XX-XX')
... |
#!/usr/bin/env pypy3
# -*- coding: UTF-8 -*-
import heapq
n,k=[int(i) for i in input().split()]
l=[int(i) for i in input().split()]
cnt=[i for i in l if i<0]
m=0
for a,i in enumerate(l):
if i<0 and m==0:
m=1
elif i<0 and l[a-1]>=0:
m+=1
d={}
q=[]
chk=-1
for i in l:
if i<0:
if chk>0:... |
from django.views.generic import DetailView
from eventex.subscriptions.forms import SubscriptionForm
from eventex.subscriptions.models import Subscription
from .mixins import EmailCreateView
new = EmailCreateView.as_view(
model=Subscription, form_class=SubscriptionForm,
email_subject='Confirmação de inscriçã... |
class way:
(up, down, north, south, east, west) = range(6)
all = [up, down, north, south, east, west]
vert = [up, down]
horiz = [north, south, east, west]
ns = [north, south]
ew = [east, west]
@staticmethod
def opposite(d):
return [1, 0, 3, 2, 5, 4][d]
#[down, up, south, north, west, east][d]
... |
# coding: utf-8
import json
import re
import warnings
from operator import itemgetter, attrgetter
from functools import reduce, partial
from itertools import repeat, starmap
from pathlib import Path
from sys import stderr, stdout
from typing import Any, Pattern, Iterable, Union, Mapping, Tuple
from jsonschema import D... |
import numpy as np
import random
from graphviz import Digraph
import itertools
class AST:
def __init__(self, depth):
#木の深さ
self.depth = depth
#最大要素数(深さ"depth"での完全二分木の要素数)
self.max_size = 2**self.depth-1
#ASTの配列
self.ast = np.array([None for i in range(self.max_size)]... |
Trees
Trees are an essential data structure for storing hierarchical data with a directed flow.
root node is at the very top and this is also a parent.
child or children nodes
When a node has no children, we refer to it as a leaf node.
Binary Search Tree
A binary tree is a type of tree where each parent can have n... |
#!/usr/bin/env python
import argparse
import os
import shutil
import xml.etree.ElementTree as etree
def parse_xml_without_schema(file_path):
it = etree.iterparse(file_path)
for _, el in it:
if '}' in el.tag:
el.tag = el.tag.split('}', 1)[1]
return it.root
def extract_date(xml):
... |
import gnupg
from pprint import pprint
gpg = gnupg.GPG(gnupghome='/home/testgpguser/gpghome')
key_data = open('mykeyfile.asc').read()
import_result = gpg.import_keys(key_data)
pprint(import_result.results)
|
from Login.BasePage import *
class LoginPage(Page):
url = '/'
username_loc = (By.ID, 'accountName') # 账号
password_loc = (By.ID, 'pwd') # 密码
submit_loc = (By.CLASS_NAME, 'login_in') # 登录按钮
newcontract_loc = (By.LINK_TEXT, '新建合同')
def type_username(self, username... |
#class MessageSerializer(serializers.ModelSerializer):
# #owner = serializers.ReadOnlyField(source='owner.username')
#
# class Meta:
# model = Message
# fields = ('id', 'ride', 'sender', 'receiver', 'body') |
# -*- coding: utf-8 -*-
from distutils import version
__version__ = '2.1.0'
version_info = version.StrictVersion(__version__).version
default_app_config = 'debreach.apps.DebreachConfig'
|
DROP TYPE IF EXISTS ret_func_ext_has_spouse_candidates CASCADE;
CREATE TYPE ret_func_ext_has_spouse_candidates AS (person1_id text, person2_id text, sentence_id text, description text, is_true boolean, relation_id text);
CREATE OR REPLACE FUNCTION func_ext_has_spouse_candidates(
sentence_id text, p1_id text, p1_tex... |
from django.db import models
from datetime import datetime
from product import Product
class Shipping(Product):
class Meta:
db_table = 'shipping_methods'
app_label = 'inventory' |
import logging
from collections import Iterable
from functools import lru_cache
from typing import Tuple, Dict, List
from odoo import fields
from odoo.fields import resolve_mro
_logger = logging.getLogger(__name__)
class Choice:
id: int
ref: str
name: str
def __init__(self, id_: int, ref: str, name... |
class LocalConfig(object):
DEBUG = True
DEVELOPMENT = True
SECRET_KEY = 'do-i-really-need-this'
SQLALCHEMY_DATABASE_URI='sqlite:////home/mahrezbh/Project/Flask_project/database.db'
class ProductionConfig(LocalConfig):
DEVELOPMENT = False
DEBUG = False
SQLALCHEMY_DATABASE_URI = 'postgresql:/... |
"""
#------------------------------------------------------------------------------
# Properly scaled experimental values for a PoleZero Shaper
#
# This script contains generalized phase and amplitude shifting values for an undamped second order system
#
# Created: 6/20/17 - Daniel Newman -- dmn3669@louisiana.edu
#
# ... |
from argparse import Namespace, ArgumentParser
from typing import Optional
class ConsoleCommand:
def configure(self, argument_parser: ArgumentParser):
pass
def get_command(self) -> str:
raise Exception("Command name must be defined: {}".format(self.__class__))
def get_description(self) -... |
def describe(myVar):
print(myVar, "is of type", type(myVar))
def display_ref(myVar):
print(myVar, "ref is: " + str(id(myVar)))
def display_ev(desc, term):
print(desc + ": " + str(term))
import inspect
def nameof(var):
callers_local_vars = inspect.currentframe().f_back.f_locals.items()
return [var... |
import os
import numpy as np
from sklearn import preprocessing
import csv
import time
import random
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
time_start = time.time()
def mkdir(path):
isExist = os.path.exists(path)
if isExist:
print("the path exist")
... |
import pygame, sys
class menuBlock:
menuBlock1 = pygame.Rect
size = 1
x = 0
y = 0
w = 0
h = 0
displayText = ""
marginPercent = 50
COLOUR = (0,0,0,255)
menuBlockFont = pygame.font.Font
menuBlockText = pygame.font.Font.render
menuBlockTextRectangle = pygame.Rect
def ... |
n=int(input('Enter the elements.no :-'))
wl2=list(map(int,input('Enter seperate elements by space:-').split()))
odd=[]
even=[]
for i in wl2:
if i%2==0:
even.append(i)
else:
odd.append(i)
finaly=sorted(odd)[::-1]
even=sorted(even)
for i in even:
finaly.append(i)
print(finaly)
|
import multiprocessing
import math
import time
import run_random_new, run_loop
if __name__ == "__main__":
width = 100 # meter
height = 100 # meter
density = float(0.0125)
num_base = 1
pos_base = "0,0"
set_energy = 1 # set energy = 1 Joule
pkt_control = 200 # bit
... |
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.generics import get_object_or_404
from rest_framework import filters
from .models import School, Student
from .serializers import SchoolSerializer, StudentSerializer, StudentDetailSerializer, StudentNestedSerial... |
"""
methods for manipulating vectors on the simplex.
Includes methods to generate multinomial logistic params on S^D+1 from
real valued vectors in R^D (and back)
"""
import autograd.numpy as np
import autograd.numpy.random as npr
def logit(p):
"""takes rows of R^D+1 vectors on the simplex and outputs R^D l... |
'''
Created on Nov 10, 2015
@author: Jonathan
'''
def emailsLargest(courses):
sizes = {}
for course in sorted(courses):
name = course.split(":")[0]
if name not in sizes:
sizes[name] = 0
else:
sizes[name] += 1
largest = max(sorted(sizes), key = sizes.get)
... |
from setuptools import setup
setup(name='piano',
version='0.1',
url='https://github.com/SonyCSLParis/piano',
author=['Gaëtan Hadjeres'],
author_email=['gaetan.hadjeres@sony.com'],
license='MIT',
packages=['BFT'],
zip_safe=False)
|
from django.contrib.auth.models import User
from django.db import models
#
# Models
class Userprofile(models.Model):
user = models.ForeignKey(User, related_name='userprofile', on_delete=models.CASCADE)
active_team_id = models.IntegerField(default=0) |
#!/usr/bin/env python
"""
Classification of cells into cell types/states.
"""
import re
from typing import List
from dataclasses import dataclass, field
from anndata import AnnData # type: ignore[import]
import scanpy as sc # type: ignore[import]
from imc.graphics import get_grid_dims, rasterize_scanpy
from imc.u... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 25 09:55:31 2020
@author: melaniee
Plots RA and Dec of all original images from one night to explore variations
"""
from astropy.io import fits
import os
import glob
import matplotlib.pyplot as plt
import numpy as np
from astropy.coordinates import... |
# print(2 + 1)
# print(23 % 2)
# print(2 ** 3)
# print(2 + 10 * 10 + 3)
# print((2 + 10) * (10 + 3)) |
class Solution:
def isHappy(self, x):
def function(number):
squares = 0
while number:
squares += (number % 10) ** 2
number = number // 10
return squares
y = x
while True:
x = function(x)
if x == 1: ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
def is_valid_email(addr):
if re.match(r'^.+@(gmail|microsoft).com$', addr):
return True
return False
assert is_valid_email('someone@gmail.com')
assert is_valid_email('bill.gates@microsoft.com')
assert not is_valid_email('bob#example.com')
asser... |
#!/usr/bin/env python
# -*- coding: UTF8 -*-
#******************************************************************************\
#* $Source$
#* $Id$
#*
#* Copyright (C) 2006 - 2011, Jérôme Kieffer <kieffer@terre-adelie.org>
#* Licence GPL v3+
#*
#* This program is free software; you can redistribute it and/or modify
#* ... |
#!/usr/bin/env python
"""
Code to load an expert policy and generate roll-out data for behavioral cloning.
Example usage:
python3 run_expert.py experts/Humanoid-v1.pkl Humanoid-v1 --render \
--num_rollouts 20
Author of this script and included expert policies: Jonathan Ho (hoj@openai.com)
"""
import ... |
for a in range(19,0,-2):
print(a) |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 18 08:03:06 2012
@author: leonard
"""
import matplotlib
def cmap_xmap(function,cmap):
""" Applies function, on the indices of colormap cmap. Beware, function
should map the [0, 1] segment to itself, or you are in for surprises.
See also cmap_xmap.
... |
INF = float('inf')
def minPathCost(graph,V):
minCost = graph.copy() #[ [0 for x in range(V)] for x in range(V) ]
for k in range(V):
for i in range(V):
for j in range(V):
minCost[i][j] = min( minCost[i][j], minCost[i][k]+minCost[k][j] )
for l in range(V):
for m in range(V):
if( minCost[l][m] == I... |
import pygame as pg, time, math, sys
from pygame.locals import *
from random import randint
class Coin:
def __init__(self, screen):
self.x = 660
self.y = randint(0,19)*20
self.sprite = pg.image.load("images/coin.png")
self.sprite = pg.transform.scale(self.sprite,(20,20))
se... |
# -*- coding: utf-8 -*-
# Author:benjamin
# Date:
from django.contrib.auth.decorators import login_required
class LoginRequiredMixin(object):
@classmethod
def as_view(cls, **initkwargs):
#调用父类的as_view()
view = super(LoginRequiredMixin,cls).as_view(**initkwargs)
return login_required(vie... |
# Copyright The OpenTelemetry 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 law or agreed to in ... |
import numpy as np
import pandas as pd
def visualize_policy(policy, actions):
list_actions = list(actions.keys())
argmaxed_policy = np.argmax(policy, axis=-1)
visual_policy = np.vectorize(list_actions.__getitem__)(argmaxed_policy)
return pd.DataFrame(data=visual_policy)
def create_grid(l... |
from autumn.infrastructure.remote.buildkite.buildkite import CommandStep, InputStep, Pipeline
from .calibrate import (
commit_field,
chains_field,
runtime_field,
trigger_field,
)
from .full import burn_in_field, sample_size_field
fields = [
chains_field,
commit_field,
runtime_field,
bu... |
import os
import sys
import numpy as np
import cv2
import re
import json
import string
from StringIO import StringIO
import random
import time
from datetime import datetime
def chroma_key(src, dest):
if not os.path.exists(src):
raise IOError('Error: %s does not exists' % src)
if not os.path.exists(de... |
#-*- coding:utf-8 -*-
from numpy import *
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn import metrics
# 三大步骤:
'''
1、特征的选择:标准:总方差最小
2、回归树的生成:停止划分的标准
3、剪枝:
'''
# 导入数据集
def loadData():
df = pd.read_csv('C:\\Users\\subshine\\Desktop\\train1.csv', sep=',', header=0, index_col... |
from gemlibapp import create_app, db
db.create_all(app=create_app())
|
from intent_handling.signal import Signal
class ClassesWithTopicIntent:
NAME = 'CLASSES_WITH_TOPIC'
def __init__(self, parameters):
self.parameters = parameters
def execute(self, db):
pretty_topic = ' '.join(self.parameters.subject_matter.split('_'))
sql = 'SELECT code ' \
... |
#!/usr/bin/env python
'''
Using names.txt (right click and 'Save Link/Target As...'),
a 46K text file containing over five-thousand first names,
begin by sorting it into alphabetical order. Then working out
the alphabetical value for each name, multiply this value by
its alphabetical position in the list to obtai... |
#!/usr/bin/env python
PACKAGE = 'turtle_thing'
NODE = 'Turtle_Server'
import rospy
# roslib.load_manifest('my_pkg_name')
from actionlib import SimpleActionClient, SimpleActionServer
from geometry_msgs.msg import Twist
from turtle_thing.msg import Turtle_positionAction, Turtle_positionResult
class Turtle_Server :
de... |
primeiroTermo = float(input('Digite o primeiro termo: '))
diferenca = float(input('Diferenca: '))
print(primeiroTermo, end=" >> ")
i = 1
while i < 11:
primeiroTermo += diferenca
print(primeiroTermo, end=" >> ")
i += 1
print("FIM") |
import os
import time
import math
import numpy as np
from keras.callbacks import Callback, ModelCheckpoint, TensorBoard
from keras.layers import Dense, Dropout, Embedding, LSTM, TimeDistributed
from keras.models import load_model, Sequential
from keras.optimizers import Adam
from logger import get_logger
from utils ... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('about/', views.about, name='about'),
path('mugs/', views.mugs_index, name='index'),
path('mugs/<int:mug_id>/', views.mugs_detail, name='detail'),
path('mugs/create/', views.MugCreate.as_view(),... |
from geopy import distance
from Utils.stops import stops, intercept
from Utils.linestring_selector import LinestringSelector
from Utils.routes_analyzer import routes_analyzer
from Utils.metrics_evaluator import metrics_evaluator
from Utils.NetworkManager import send_data
import geopandas as gpd
# Step 0 Parse the Ge... |
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if len(height) <= 2:
return 0
left_cursor = 0
left_highest = height[0]
right_cursor = len(height) - 1
right_highest = height[len(height) - 1... |
import inspect
if "rungame" not in inspect.getmodule(inspect.stack()[0])._filesbymodname["__main__"]:
import rungame
class AI:
def __init__(self):
print(__name__ + " AI Loaded")
self.image = "projetile.png"
def turn(self):
self.robot.projMoveForward()
|
from pydantic import BaseModel, ValidationError
from models.game.player import Player
import typing
__all__ = (
'GameModel', 'CREATE_WARRIOR', 'CREATE_WORKER',
'CREATE_WAR_STEP', 'CREATE_FINISH_STEP',
)
CREATE_WARRIOR = 0 # Событие на создание юнита.
CREATE_WORKER = 1 # Событие на создание юнита.
CREATE_WAR... |
import gunicorn.app.base
from gunicorn.config import Config
import multiprocessing
import sys
def number_of_workers():
return (multiprocessing.cpu_count() * 2) + 1
def get_options_from_cli():
parser = Config().parser()
options = parser.parse_args(sys.argv)
return options
def get_options():
option... |
import os
import cv2
import time
import sys
from picamera.array import PiRGBArray
from picamera import PiCamera
import RPi.GPIO as g
from gtts import gTTS
from ocr import OCR
from pygame import mixer
class Main():
def __init__(self):
self.G_CHANGE_MODE_BUTTON = 23
self.G_FUNCT... |
TOKEN = 'NzI0MjIwMTY1MTAwNjY3MDIw.Xu9Asw.bGq3zD24-N6egYAeH-6MLajfucg'
POST_ID = 724146211917135944 #id post to read reactions from
ROLES = {
'🎮': 724140706612117596,#gamer
'🔫': 724140803487694898,#cs
'🤖': 724140936254193725,#pubg
'🏫': 724140992814383135,#minecraft
'👦': 724141100104679515,#new user
} #rolies... |
#!/usr/bin/env python2
"""variance.py:
A script to analyze the variance of subjects from block to block.
Graphs are outputed in a folder called "analysis".
"""
import os,glob,sys
import matplotlib.pyplot as plt
__author__ = "Omid Rhezaii"
__email__ = "omid@rhezaii.com"
__copyright__ = "Copyright 2015, Michael Silver La... |
import os,sys
sys.path.append('/usr/share/osckar/lib/')
import osckar as o
osckar = o.Osckar()
def connect(host,port):
osckar.connect(host,port)
osckar.registerEvent('VM_START_SUCCEEDED')
osckar.registerEvent('VM_BUILD_SUCCEEDED')
def buildVMC(vm_name, install_mirror):
file = open("/etc/kiosckar/kios... |
def setup():
size(300, 300)
smooth()
strokeWeight(30)
background(0)
def draw():
stroke(200, 20)
line(mouseX - 50, mouseY - 50, 100 + mouseX - 50, 100 + mouseY - 50)
line(100 + mouseX - 50, mouseY - 50, mouseX - 50, 100 + mouseY - 50)
|
from django.shortcuts import render
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth.models import User
from accounts.permissions import Faci... |
# ==================================================================================================
# Copyright 2012 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
from senticnet.senticnet import SenticNet
import nltk
from tqdm import tqdm
import xlrd
import pandas as pd
import random
from textblob import TextBlob
import numpy as np
import IPython
import re
from nltk.corpus import stopwords
import json
import inflection as inf
from wordcloud import WordCloud
from gensim.models im... |
'''
Created on Sep 16, 2016
@author: Dayo
'''
import logging
import arrow
from .models import SMSDeliveryReportTransaction, SMSDeliveryReport, EmailReportTransaction, EmailDeliveryReport,\
EmailReceiverAction
def process_sms_deliveryreport_transaction():
# get all unproces... |
"""
Functions for initializing HMMs for training
"""
import os, random, re
import util
random.seed(0)
def word_to_phone_mlf(model, dict, word_mlf, phone_mlf, mono_list):
"""
Convert the word-level mlf to a phone level mlf with HLEd
"""
if not os.path.isfile(word_mlf):
util.log_write(model.log... |
import os
import datetime
from flask import Flask, session,request,render_template,flash,logging,redirect,url_for
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from flask_sqlalchemy import SQLAlchemy
import csv
from models import *
from c... |
from io import StringIO
from lxml import html as etree
def _get_xml_field(parent):
for node in parent:
if node.tag == 'form' and parent.tag == 'field':
return
elif node.tag == 'field':
yield node
else:
for child in _get_xml_field(node):
y... |
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
import feedparser
def index(request):
"""Taking url request as parameter and feeding into feedparser module to store"""
feed = feedparser.parse(request.GET.get("url", None))
"""return the parsed object to rss parse ... |
import tensorflow as tf
import os
class SegCaps(object):
def __init__(self, sess, config, is_train):
self.sess = sess
self.name = 'SegCaps'
self.mask = config.mask
self.ckpt_dir = config.ckpt_dir
self.is_train = is_train
print (config.batch_size)
num_classes=256 #182
batch_size = 2 #... |
import dnslib
data = "be63010000010000000000000279610272750000010001".decode("hex")
q = dnslib.DNSRecord.parse(data)
r=q.reply(data='127.0.0.1')
r.add_answer(dnslib.RR(rtype=1, rclass=1, ttl=600, rdata='127.0.0.1'))
print r.pack()
|
# files in input/enrichGene folder created by Yan Kou
# each file reports significant peaks from a ChIP-seq experiment
# peaks are reported as distance to nearest gene
import time
import zipfile
import codecs
folder = 'input/'
date = time.strftime('%Y%m%d', time.localtime())
zippedfilename = 'enrichGene.zip... |
rows = int(input("Enter the no of rows: "))
for row in range(1,rows):
for row in range(0,row,1):
print(format(2**row,"4d"), end=" ")
for row in range(-1+row,-1,-1):
print(format(2**row, "4d"), end="")
print("")
|
from time import sleep
print('{:=^30}'.format(' Lojas Silva ').upper())
valor = float(input('Qual o valor total do produto/serviço: R$'))
print('Formas de pagamento'.upper())
print('[1] Dinheiro -> À vista, -10% de desconto')
print('[2] Cartão -> À vista, -5% de desconto')
print('[3] Cartão -> Parcelado 2x')
print('[... |
from PyQt5.QtCore import QDate
date = QDate.currentDate()
d = QDate(2011,11,23)
print("2011 Days In A Month:{0}".format(d.daysInMonth()))
print("2011 Days In A Years:{0}".format(d.daysInYear()))
print()
print("now Days In A Month:{0}".format(date.daysInMonth()))
print("now Days In A Years:{0}".format(date.daysInYear... |
#!/usr/bin/env python
#
# Copyright 2017 - The Android Open Source Project
#
# 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 requir... |
# Generated by Django 2.2.2 on 2019-06-24 08:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('teacher', '0003_auto_20190619_1137'),
]
operations = [
migrations.AlterModelOptions(
name='teacher',
options={'ordering': ('... |
cx = 0
cy = 0
fsize = 0
counter=0
#FunnyRect() описание прямоугольника
class FunnyRect():
global cx, cy, fsize
def setCenter(self, x,y):
self.cx = x
self.cy = y
def setSize(self, size):
self.fsize = size
def render(self):
rect(self.cx, self.cy, self.fsize, self.fsize)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.