text stringlengths 8 6.05M |
|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Animal:
def __init__(self, nombre, patas):
self.nombre = nombre
self.patas = patas
def saluda(self):
print "El animal llamado" + self.nombre + "saluda"
class Perro(Animal):
def ladra(self):
print "Guau"
def saluda(self):
print "El perro da la patita"
... |
def xor_string(s1,s2):
mul = int(len(s1) / len(s2) + 1)
s2 *= mul
s2 = s2[:len(s1)]
return ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(s1,s2)) |
import sympy
from sympy.assumptions.assume import AppliedPredicate, global_assumptions
from typing import Dict, List, Union
a, b, c = sympy.symbols('a b c')
d_a, d_b, d_c = sympy.symbols('Δa Δb Δc')
class Expression:
args: List[sympy.Symbol]
expr: sympy.Expr
def __init__(self, args: List[sympy.Symbol], ... |
# Python Coroutines and Tasks.
# Coroutines declared with async/await syntax is the preferred way of writing asyncio applications.
#
# To actually run a coroutine, asyncio provides three main mechanisms:
#
# > The asyncio.run() function to run the top-level entry point “main()” function.
# > Awaiting on a corout... |
# -*- coding: utf-8 -*-
__author__ = 'lish'
import sys,time
import MySQLdb,os
import sys
reload(sys)
sys.setdefaultencoding('gbk')
base_path='/opt/www/ec_con'
class updateTmpTable(object):
def cleartmptable(self):
#清空临时表tmp_con_goods和tmp_con_guide
tr_tmp_goodsinfos_sql='TRUNCATE TABLE public_db... |
{
'includes': ['../../test.gypi'],
'targets': [{
'target_name': 'testlib',
'type': 'static_library',
'sources': ['testlib.cc'],
}],
}
|
"""
Scanner and Tokens for Small
"""
__author__ = "Campbell Mercer-Butcher"
import re
import sys
from token import Token
class Scanner:
'''Matches tokens through out provided file'''
def __init__(self, input_file):
'''Reads the whole input_file'''
# source code
self.input_string = in... |
from lxml import html
from stop_words import stop_words
import requests
import re
import io
urls = [
"https://en.m.wikipedia.org/wiki/List_of_S%26P_500_companies",
"https://en.m.wikipedia.org/wiki/Dow_Jones_Industrial_Average",
"https://en.m.wikipedia.org/wiki/Nikkei_225",
"https://en.m.wikipedia.org/w... |
from __future__ import print_function
import gzip;
import os, sys;
import numpy as np;
from math import sqrt
import MDAnalysis as mdanal;
from MDAnalysis.analysis import contacts;
# TODO: Add count_traj_files to utils
import glob
def count_traj_files(path, extension):
if not os.path.exists(path):
raise Ex... |
#!/usr/bin/python
import sys
HASH = 10000
def solve(filename):
fin = open(filename, "r")
fout = open(filename[:-2] + "out", "w")
case_count = int(fin.readline())
for i in xrange(case_count):
result = process_case(parse_case(fin))
output = 'Case #%d: %s' % (i+1, result)
print(o... |
from django.forms import ModelForm
from wall.models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ['message']
def save(self, author):
post = super().save(commit=False)
post.author = author
post.save()
return post
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-05 14:25
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("elections", "0049_move_status")]
operations = [
migrations.RemoveField(model_name="election", na... |
import random
from rasmus.bio import phylo
import Spidir
from Spidir import Search
from Spidir.Debug import *
# events
EVENT_GENE = 0
EVENT_SPEC = 1
EVENT_DUP = 2
# fractional branches
FRAC_NONE = 0
FRAC_DIFF = 1
FRAC_PARENT = 2
FRAC_NODE = 3
#==================================================================... |
import asyncmongo
import tornado.ioloop
from tornado import gen
import time
def s():
db.test.find()
@gen.engine
def test_query(i):
'''A generator function of asyncmongo query operation.'''
#response, error = yield gen.Task(db.test.find, {})
yield gen.Task(tornado.ioloop.IOLoop.instance().add_timeout, tim... |
#! /usr/bin/env python
import rospy
import roslib
from geometry_msgs.msg import PointStamped
def main():
#Main fucntion. Put everything here
pub = rospy.Publisher("/camera/object_candidates",PointStamped,queue_size=10)
rospy.init_node("talker")
rate = rospy.Rate(10)
while not rospy.is_shutdown():... |
# -*- coding: utf-8 -*-
import os
import threading
import main2
import thread
class ImgBarEnv:
'''网址保存在文件中'''
def __init__(self):
self.path = './log/'
if not os.path.exists(self.path):
os.mkdir(self.path)
def resumeDownload(self):
firstUrl = self.getThreadHistory(1)... |
import sys
import glob
import numpy as np
from astropy.io import fits
from astropy.wcs import WCS
try:
PREFIX = sys.argv[1]
except:
sys.exit(f"Usage: {sys.argv[0]} PREFIX")
zfile = PREFIX + ".npz"
with np.load(zfile) as data:
cube = data['rho'].T
x = data['x']
y = data['y']
z = data['z']
xx ... |
number_page = float(input())
pages = float(input())
number_days = float(input())
read_book = number_page / pages
time_days = read_book / number_days
print(time_days)
|
# coding=utf-8
from myspider.items import ImagesItem
from scrapy.http import Request
import scrapy
import re
class JandanPicSpider(scrapy.Spider):
name = 'jandan_pic'
allowed_domains = ['i.jandan.net']
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.... |
import paramiko
import getpass
import sys
import time
from datetime import datetime
user = 'user'
password = '12345678'
f = open('Gashkova41a.txt', 'w')
for i in range(1,254,1):
ip = '172.22.76.' + str(i)
print("Connecting to {}".format(ip))
client = paramiko.SSHClient()
client.set_mis... |
# Copyright (c) 2020. Yul HR Kang. hk2699 at caa dot columbia dot edu.
import matplotlib as mpl
import numpy as np
import torch
from matplotlib import pyplot as plt
from collections import OrderedDict as odict
import torch
from torch import optim
from torch.nn import functional as F
from torch.utils.tensorboard impo... |
ISR.enable(1)
enable(1)
|
from cctpy import *
from ccpty_cuda import *
import time
import numpy as np
import math
ga32 = GPU_ACCELERATOR()
momentum_dispersions = [-0.05, -0.025, 0.0, 0.025, 0.05]
particle_number_per_plane_per_dp = 12
particle_number_per_gantry = len(momentum_dispersions) * particle_number_per_plane_per_dp * 2
default_gantry... |
import pytest
from common.contants import basepage_dir, test_login_dir
import yaml
from page.base.basepage import _get_working
from page.base.main import Main
def get_env():
'''
获取环境变量:uat、dev、mo正式站
'''
with open(basepage_dir, encoding="utf-8") as f:
datas = yaml.safe_load(f)
# 获取bas... |
# coding = utf-8
# -*- coding:utf-8 -*-
import json
import os
import threading
import time
from urllib.parse import urlencode
import chardet
# from fake_useragent import UserAgent
import redis
import requests
from pyquery import PyQuery as pq
from soupsieve.util import string
from Cookie_pool.account_saver import Red... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 16 22:01:21 2018
@author: Marcus
"""
import numpy as np
class filter_synthesis:
"""Synthesise a filter."""
def __init__(self,
cutoff_frequency,
order,
filter_type="maximally_flat"):
"""Initialise... |
t = 2
def split_child(x, index, y):
z = BNode()
x.children.insert(index + 1, z)
x.keys.insert(index, y.keys[t - 1])
z.keys = y.keys[t:]
y.keys = y.keys[:t - 1]
if not y.is_leaf():
z.children = y.children[t:]
y.children = y.children[:t]
class BNode(object):
def __init_... |
#=================================================================================================================================================
#=================================================================================================================================================
# JAMMSoft Joint Orient To... |
import asyncio
import time
from typing import List
class SomethingThatWaits:
def __init__(self, timeout_in_sec: int = 3) -> None:
self.timeout_in_sec = timeout_in_sec
self.check_interval_in_sec = 1
self.last_heard = time.monotonic()
async def start(self) -> None:
while True:... |
import numpy as np
import torch
from torch import optim
import argparse
import csv
from hyperspn.dataset_utils import load_dataset
from hyperspn.model_utils import load_model
from hyperspn.inference_utils import log_density_fn, compute_parzen, timestep_config
DEVICE = "cuda:0" if torch.cuda.is_available() else "cpu"
... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#setup computational graph
x_data = np.load('linreg_x.npy')
y_data = np.load('linreg_y.npy')
x = tf.placeholder(tf.float32, shape=x_data.shape,name='X')
y= tf.placeholder(tf.float32, shape=y_data.shape,name='Y')
print(y_data.shape)
w = tf.... |
"""Huggingface datasets FLEET challenge dataset script."""
import logging
import json
import numpy as np
from hydra.utils import instantiate
from fewshot.utils import get_hash
import datasets
from fewshot.challenges import registry
from fewshot.utils import ExampleId
logger = logging.getLogger('datasets.challenge')
_... |
#========================================
# author: Changlong.Zang
# mail: zclongpop123@163.com
# time: Thu Sep 14 17:17:15 2017
#========================================
import maya.cmds as mc
import pymel.core as pm
import curve
#--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+... |
from rangegenerator.rangegenerator import *
from reverser.reverser import *
from evener.evener import *
from odder.odder import * |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright 2018(c). All rights reserved.
#
# This is free software; you can do what the LICENCE file allows you to.
# Author: Ing. Oraldo Jacinto Simon
class CountLine(object):
'''Count the LOCs ... |
# @Time :2019/8/3 17:40
# @Author :jinbiao |
# Game written by HUSNOO M. Sultan on April 14th 2021
# Hangman game. Computer will display a word with characters
# blanked out. User has to geuss characters to complete the word.
import random
def find_max_chances(word):
singular_chars = {}
for char in word:
if char in singular_chars:
singular_chars[char] +... |
import logging
from .Renderer import Renderer
from ..PageTree.PageTree import *
class MediaWikiRenderer(Renderer):
def __init__(self, configs, reporter):
super().__init__(configs, reporter)
self.configs = configs
self.doc_title = configs['doc_title']
#saving the hooks
self.... |
# coding=utf8
"""
_env.py
Desc: Be used import diffent directory`s package
Maintainer: wangfm
CreateDate: 2016-11-07 17:05:50
"""
__all__ = []
import os
import sys
libs_path = ["\..\\..\\",
"\..\\",
"\..",
"\..\\..\\..\\"]
Home_Path_TMP = os.environ.get('PY... |
"""
class MySecondClass:
def __init__(self):
self.blah = "blarg"
class MyClass:
def __init__(self):
self.first = 2
self.second = 5
self.thingy = MySecondClass()
def myfunc(self):
print(self.first)
print(self.second)
c = MyClass()
print(c.thingy.blah)
c.thingy.blah = ";alksdjgaslkfg"
print(c.thingy.blah)
c1 = MyClas... |
# -*- coding: utf-8 -*-
class Solution:
def minCostClimbingStairs(self, cost):
previous, current = cost[0], cost[1]
for i in range(2, len(cost)):
previous, current = current, cost[i] + min(previous, current)
return min(previous, current)
if __name__ == "__main__":
solutio... |
from django.contrib import admin
from .models import Auction
admin.site.register(Auction)
|
import socket
from threading import Thread
import time
class UDPBroadcastReciever(Thread):
def __init__(self,PORT):
try:
self.PORT = PORT
self.sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #UDP
self.sock.setblocking(0) #Non blocking socket
self.sock.... |
from django.shortcuts import render
def index(request):
return render( request, "disappearing_ninja/index.html" )
def ninjas(request):
return render( request, "disappearing_ninja/ninjas.html" )
def ninja_select(request, ninja_color):
context = { 'img_src': "disappearing_ninja/img/notapril.jpg" }
if n... |
import random
import re
import requests
from decimal import Decimal
from lxml import html
from re import sub
from urllib import pathname2url
URL = '''http://www.zillow.com'''
SEARCH_FOR_SALE_PATH = '''homes/for_sale'''
GET_PROPERTY_BY_ZPID_PATH = '''homes'''
GET_SIMILAR_HOMES_FOR_SALE_PATH = '''homedetails'''
IMAGE_... |
# coding:utf-8
from CommonAPI import fomate_bytes, fomate_str
from BasicConfig import DeviceConfig, RegionConfig
import typing
import struct
from RegionInfo import RegionInfoType
class DeviceInfoType:
"""
设备信息封装类
"""
def __init__(self):
self.dev_id = DeviceConfig.dev_id
self.dev_m... |
from __future__ import absolute_import, division, print_function
import abc
import copy
import os
import kvt.registry
import torch
import torch.nn as nn
from kvt.models.layers import AdaptiveConcatPool2d, Flatten, GeM, Identity, SEBlock
from kvt.registry import BACKBONES, MODELS
from kvt.utils import build_from_confi... |
def setup_environment(env):
SDK = r"F:/SDKs"
SFML = SDK + r"/SFML-2.1"
LUA = SDK + r"/lua-5.2.2"
LUABRIDGE = SDK + r"/LuaBridge/Source"
MINIZIP = SDK + r"/minizip"
env.Append(CPPPATH=[SFML+"/include", LUA+"/include", LUABRIDGE, MINIZIP])
env.Append(LIBPATH=[SFML+"/lib", LUA+"/lib", MINIZIP])
|
from itinerary_main import *
from functools import reduce
import numpy as np
from sklearn.decomposition import PCA
def getCategories(attractions):
cats = []
for attraction in attractions:
attraction_cats = set()
groups = attraction["groups"]
for group in groups:
attraction_cats.add(group['name'])
categor... |
print('===== EXERCICIO 005 =====')
print('Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e antecessor')
n = int(input('Digite um número: '))
print('O sucessor do número {} é {} e o antecessor é {}'.format(n, (n+1), (n-1)))
|
#! /usr/local/bin/python
# Import sys for access to argv, import glob for wildcard
# file path matching
import sys,glob
# For each sent path (regardless of no)
for path in sys.argv[1:]:
# For all files matching the pattern *.txt
for filepath in glob.glob(path+"*.txt"):
# Get a filehandle with read
file = ... |
#!/usr/bin/env /proj/sot/ska/bin/python
#####################################################################################################
# #
# create_five_min_avg.py: create 5 min averaged data for give... |
import tensorflow as tf
from tensorflow.python import debug as tf_debug
import os
import sys
import time
import logging
import re
from PIL import Image
sys.path.append(os.getcwd())
from data import data_utils
from config.global_config import CFG
import models.crnn_model as crnn_model
logging.basicConfig(
level=log... |
from django.db import models
from django.template.defaultfilters import slugify
from django.urls import reverse
class Countries(models.Model):
name = models.CharField(max_length=15, blank=True, null=True)
alphacode2 = models.CharField(max_length=2, blank=True, null=True)
capital = models.CharField(max_len... |
from cms.apps.pages.models import Page
from django.db import models
class FooterLinkAbstract(models.Model):
page = models.ForeignKey(
Page,
blank=True,
null=True
)
link = models.CharField(
max_length=1024,
blank=True,
null=True
)
link_text = model... |
# Напишите программу, которая принимает на вход список целых чисел и выводит на экран значения, которые повторяются в нём более одного раза.
# Для решения задачи может пригодиться метод sort списка.
# Формат ввода:
# Одна строка с целыми числами, разделёнными пробелом.
# Формат вывода:
# Строка, содержащая числа, ра... |
from django.db import models
from apps.items.models import WeaponTemplate, ShipTemplate
import random
class EnemyValues(models.Model):
""" balance enemy numbers """
random_money = models.FloatField()
random_xp = models.FloatField()
rookie_money = models.IntegerField()
rookie_xp = models.Int... |
from sklearn.neighbors import NearestNeighbors
import numpy as np
from stl import mesh
import pycaster
import os,fnmatch,csv
import vtk
from vtk.util.numpy_support import vtk_to_numpy
pv3d_file_path = 'Masked.pv3d'
#pv3d_folder_path = './PV3D Files/'
stl_file_path = 'PhantomMaskforAugust27thData.stl'
function_switch_l... |
import requests
from datetime import datetime
class VideoInfo:
# Where the CLI is accessing the DB, chose to access my local machine
def __init__(self, url="http://localhost:5000"):
self.url = url
self.selected_video = None
# Video store employee adding new video into inventory
... |
import boto3
import pathlib
import os
from flask import Flask
from app.main.util.tacotron.model import Synthesizer
from app.main.util.vocoder.vocoder import load_model
from .config import config_by_name, Config
os.environ["CUDA_VISIBLE_DEVICES"] = ""
synthesizer = Synthesizer(
pathlib.Path('./a... |
# 前缀 后缀 dp
class Solution:
def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]:
n = len(security)
if n == 0 or n < 2 * time + 1:
return []
if time == 0:
return [i for i in range(n)]
pre, post = [0] * n, [0] * n
for i in ra... |
from mod_base import*
class ModuleLevel(Command):
"""Change the permission level of a module.
Usage: modlevel mod level
"""
def run(self, win, user, data, caller=None):
args = Args(data)
if len(args) < 2:
win.Send("specify module and level to set")
return False
... |
"""Given a structured argumentation framework as input, your task here is to print out the number of attacks
(not defeats) generated."""
from argsolverdd.common.misc import parse_cmd_args
from argsolverdd.structured.parser import read_file
from argsolverdd.structured.argument import Arguments
pa = parse_cmd_args()
r... |
import requests as req
from enum import IntEnum
from html.parser import HTMLParser
import abc
import sys
from requests.auth import HTTPBasicAuth
import json
import os
import execjs
# 爬取erp页面
path = 'save.html'
url = 'http://source.com'
# url = 'http://www.baidu.com'
auth = {'username': '',
'password': ''}
c... |
import pandapower as pp
import numpy as np
import pandas as pd
import pandapower.networks
import numpy.random
class GenerateDataMLPF(object):
""" Use load data to create a set of power flow measurements required by the MLPF algorithms.
This class uses the package Pandapower to run power flow calculations. Gi... |
# Pythonda tuple xam xuddi int, str, yoki lst kabi ma'lumot turi xisoblanadi
# listga juda o'xshab ketadi lekin farqi bor tuple da () kabi qavsdan foydalanamiz va
# tuple ni listga o'xshatib o'zgartirib bo'lmaydi faqat uni indexning qilishimiz ya'ni
# qaysidir tartib raqam ostidagi elementini chaqirib olishimiz mumkin... |
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
class HELLO(nn.Module):
def __init__(self):
super(HELLO, self).__init__()
self.init_info = "Hello World!"
print(self.init_info)
def forward(self):
pass
return
|
from morphing_agents.mujoco.dog.env import MorphingDogEnv
from morphing_agents.mujoco.dog.designs import DEFAULT_DESIGN
from morphing_agents.mujoco.dog.elements import LEG_UPPER_BOUND
from morphing_agents.mujoco.dog.elements import LEG_LOWER_BOUND
from morphing_agents.mujoco.dog.elements import LEG
import numpy as np... |
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
RUNNING = True
green, red, blue = (27, 22, 17)
GPIO.setup(red, GPIO.OUT)
GPIO.setup(green, GPIO.OUT)
GPIO.setup(blue, GPIO.OUT)
Freq = 100
INT = 0.2
RED = GPIO.PWM(red, Freq)
GREEN = GPIO.PWM(green, Freq)
BLUE = GPIO.PWM(blue, Freq)
try:
while RUNNING:
... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
import pickle
import pandas as pd
import streamlit as st
from PIL import Image
pickle_in = open("CreditCardClassifier (1).pkl","rb")
classifier=pickle.load(pickle_in)
def predict_credit_card_defaul... |
from PyQt5 import QtWidgets, QtCore, QtGui
from bsp.leveleditor.DocObject import DocObject
class HistoryPanel(QtWidgets.QDockWidget, DocObject):
GlobalPtr = None
@staticmethod
def getGlobalPtr():
self = HistoryPanel
if not self.GlobalPtr:
self.GlobalPtr = HistoryPanel()
... |
import unittest
from six.moves import cPickle
import smqtk.representation.classification_element.memory
class TestMemoryClassificationElement (unittest.TestCase):
def test_serialization(self):
e = smqtk.representation.classification_element.memory\
.MemoryClassificationElement('test', 0)
... |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# __author__ = caicaizhang
def gen(stop):
start = 0
print('generator starts...')
while start < stop:
print('before is:{}'.format(start))
yield start
print('after is:{}'.format(start))
start += 1
print('generator stops')
#列表推... |
from aristotle_mdr.apps import AristotleExtensionBaseConfig
class AristotleDHISConfig(AristotleExtensionBaseConfig):
name = 'aristotle_dhis'
verbose_name = "Aristotle DHIS2 downloader"
description = """Provides downloads for a number of different content types in
the <a href='http://www.ddialliance.org'>DH... |
class globalNames:
#folder = "/Users/isidro/code/king/hayday/com.supercell.hayday-v1.26.113-1450-Android-4.0.3/assets/data/"
folder = "/Users/isidro.gilabert/workspace/hayday/src/data/"
#folder = "../data/"
crafted_products = "CraftedProducts"
fishing = "Fishing"
trees = "Trees"
fruits = "... |
from arago.actors import Router
class BroadcastRouter (Router):
"""Routes received messages to all children"""
def _forward(self, task):
for target in self._children:
target._enqueue(task)
|
## Santosh Khadka
# www.LINK_HERE.com
'''
283. Move Zeroes - Easy
Given an integer array nums, move all 0's to the end of it while
maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,... |
import datetime
from sqlalchemy import Column, DateTime, Integer
from bitcoin_acks.database.base import Base
class Toots(Base):
__tablename__ = 'toots'
id = Column(Integer, primary_key=True)
timestamp = Column(DateTime, nullable=False,
default=datetime.datetime.utcnow, )
pull... |
from logging import Logger
import os
import re
import traceback
from typing import List
from fig_package.format.hpgl2.hpgl2_elm_classes import cHpgl2Status
from ..basic_reader import BasicReader
from .exceptions import BadHpgl2FormatError
from ..format.hpgl2 import cHpgl2ElmCommand, cHpgl2IN, cHpgl2PG, cHpgl2RO, \
... |
"""
Map object
"""
import pyglet
from pyglet.gl import *
import random
import mapgen
class Map(object):
"""
Grid-based map.
"""
def __init__(self, width, height, game_data, tilesize = 32):
"""
width, height: dimension in tiles
background: background image to use
... |
import torch.nn as nn
import torch.nn.functional as F
from misc import torchutils
from net import resnet50
import torch
class CAM(nn.Module):
def __init__(self):
super().__init__()
self.k = 1e-3
self.resnet50 = resnet50.resnet50(pretrained=True, strides=(2, 2, 2, 1))
self.stage1 =... |
#!/usr/bin/python3
import discord
from discord.ext import commands
#import pylistenbrainz
# get our token from config.py
from config import token
import database
import lbz
bot = commands.Bot(command_prefix='&')
@bot.command()
async def ping(ctx):
await ctx.channel.send("pong!")
@bot.command()
async def lbzsetup(... |
# -*- coding: utf-8 *-*
from bookcity import boyPage as boy
from bookcity import girlPage as girl
from bookcity import publicPage as publich
from bookcity import searchPage as search
from bookcity import welfarePage as welfare
from find import rankingList as ranking
# boy.HeavyThisWeek(121)
# boy.MillionsUsersHotr... |
import tensorflow as tf
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# https://keras.io/models/model/
from tensorflow.keras.layers import Dense
from tensorflow.keras import Sequential
from tensorflow.keras.optimizers import Adam
matplotlib.rcParams['font.family'] = 'Malgun Gothic'
matplotlib.... |
from urllib.parse import urlencode
from requests.exceptions import ConnectionError
import requests
import pymongo
from pyquery import PyQuery as pq
from config import *
import re
base_url = 'https://weixin.sogou.com/weixin?'
header = {
'Cookie': 'sw_uuid=8222458958; sg_uuid=6309065996; dt_ssuid=2372241637; pex=C864... |
import os
from os.path import isfile, join
class Project:
def __init__(self, project_name, path):
self.project_name = project_name
self.path = path # '../../../data/{}/'.format( self.project_name )
def getInputPath(self):
return self.path
def mkdir(self, path):
... |
# Create your views here.
from django.shortcuts import render_to_response
from django.core.paginator import Paginator, EmptyPage
from blog.models import Post, Category
from django.contrib.syndication.views import Feed
def getCategory(request, slug, page=1):
# Get specified category
posts = Post.objects.filter(... |
import os
import urllib
from sgmllib import SGMLParser
import subprocess as sp
import platform
import shutil
POOL = 'http://repository.spotify.com/pool/non-free/s/spotify/'
BASE = ''
SPOTIFY_SHARE = os.path.expanduser('~/.cache/spotify-install/')
DEB_CACHE = os.path.expanduser('~/.cache/spotify-deb-cache/')
SYSTEM = ... |
import math
def IsSignificant(p1, p2, n, alpha):
'''
This function takes in the arguments p1,p2,n,alpha
where:
p1 and p2 are the accuracies of the models
n is the number of samples
and alpha is the significance level
It outputs a boolean 1 (if significant) and 0 (if not significant)
as well the Z statisti... |
import sys
import json
import json.decoder
import urllib.request
import urllib.error
import html.parser
from .stdout import Stdout
class Asciicast:
def __init__(self, stdout, width, height, duration, command=None, title=None, term=None, shell=None):
self.stdout = stdout
self.width = width
... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import mean_absolute_error as mae
from sklearn.linear_model import LinearRegression
from datetime import datetime
sp500 = pd.read_csv('sphist.csv')
#columns = [Date,Open,High,Low,Close,Volume,Adj Close]
... |
'''
# COMPOSITION
# return a new function which composes f and g
def compose(f, g):
return lambda x: f(g(x))
# LAMBDA - anonymous functions
add = compose(lambda a: a + 1, lambda a: a + 1)
x = add(12)
print (x)
z = lambda x,y: x*y
print(z(10, 5))
def make_incrementor (n): return lambda x: x + n
f = make_inc... |
from settings import *
#MOB CLASS
class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
#ADD ROBOT IMAGES
self.robotRight = [
pygame.image.load(os.path.join(img_folder, "robotLeft0.png")).convert(),
... |
from django.urls import path, include
from .views import (CreateProductView,
AdList,
ViewProductDetail,
ProductLikeToggle,
ProductLikeAPIToggle,
ProductSaveToggle,
ProductSaveAPIToggle,
... |
import unittest
from SpotifyScraper.scraper import Scraper
from SpotifyScraper.request import Request
class TestSpotifyScraper(unittest.TestCase):
if __name__ == "__main__":
temp = Scraper(session=Request().request()).get_playlist_url_info(
url='https://open.spotify.com/playlist/4aT59fj7Kajej... |
"""
///////////////////////////////////////////////////////
│
│ Filename: automate_3_plot_close_distal.py
│ Description:
│ To print close scores (and distal scores)
│ so that you can copy paste them into analyze.py
│ in order to make a scatter plot with labels
│ ==================================================
│ Au... |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from braindecode.mywyrm.plot import ax_scalp
from braindecode.paper import map_i_class_pair, resorted_class_names
from copy import deepcopy
from braindecode.datasets.sensor_positions import CHANNEL_10_20_APPROX
from bra... |
#!/usr/bin/env python3
# Advent of code Year 2019 Day 13 solution
# Author = seven
# Date = December 2019
import enum
import re
import sys
from os import path
sys.path.insert(0, path.dirname(path.dirname(path.abspath(__file__))))
from shared import vm
with open((__file__.rstrip("code.py") + "input.txt"), 'r') as inp... |
import unittest
import sys
import os
from generators.BinaryTreeGenerator import BinaryTreeGenerator
from test.generatorstest.AbstractBaseGeneratorTest import AbstractBaseGeneratorTest
import logging
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
class BinaryTreeGeneratorTest(AbstractB... |
# Counts down to 0 positive intergers
def countdown(n):
if n <= 0:
print('Blastoff!')
else:
print(n)
countdown(n-1)
# Counts up to 0 negative intergers
def countup(n):
if n >= 0:
print('Blastoff!')
else:
print(n)
countup(n+1)
# Take input... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.