text stringlengths 38 1.54M |
|---|
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectAI import DistributedObjectAI
class DistributedVPEventAI(DistributedObjectAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedVPEventAI')
def __init__(self, air):
DistributedObjectAI.__init__... |
# myeven(start, stop)
# 此函数用来生成从 start开始到stop结束(不包含)区间内的一系列偶数
# def myeven(start, stop):
# ....
#
# evens = list(myeven(10, 20))
# print(evens) # [10, 12, 14, 16, 18]
# for x in myeven(21, 30):
# print(x) # 22, 24, 26, 28
#
# L = [x**2 for x in myeven(3, 10)]
# print(L) # 16 36 64
def myeve... |
from runners.python import Submission
class JulesSubmission(Submission):
def run(self, s):
list_size = 256
num_list = [x for x in range(list_size)]
pos = 0
skip = 0
# s = '3, 4, 1, 5'
size_list = [int(x) for x in s.split(',')]
for size in size_list:
... |
import os ,cv2
#face_Dir='/home/chenchaocun/Glint360k/output/'
face_Dir='/Users/chenchaocun/Downloads/1122/'
face_path = os.listdir(face_Dir)
f= open('/Users/chenchaocun/Downloads/glint360k.txt', 'w+')
for name in face_path:
for jpg in os.listdir(face_Dir+name):
print(face_Dir+name+'/'+jpg)
line_tx... |
def birthdayCakeCandles(ar):
maxVal = ar[0]
cnt = 0
for i in ar:
if i > maxVal:
maxVal = i
cnt = 1
elif i == maxVal:
cnt += 1
print cnt
a = [3, 2, 1, 3]
birthdayCakeCandles(a)
|
# -*- coding: utf8 -*-
def assert_equal5(given, expected, msg=None):
if given == expected: return
raise AssertionError("%s != %s" % (given, expected))
def assert5(given):
__debug__ and assert_equal5(given, given)
def test5():
for i in range(20):
assert5(i)
|
from google import auth
from typing import Dict
class SecretPayload:
data: bytes
class AccessSecretVersionResponse:
payload: SecretPayload
class SecretManagerServiceClient:
def __init__(
self,
credentials: auth.credentials.Credentials = ...
):...
def access_secret_version(
... |
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from blog.forms import ContactForm
from django.core.urlresolvers import reverse
def index(request):
context={}
if request.method =='POST':
Vis... |
#settings.py
#默认设置
HOST="127.0.0.1"
PORT=5555
ADDR=HOST,PORT
def center(root,width=300,height=150):
#设置窗口居中
screenWidth=root.winfo_screenwidth()
screenHeight=root.winfo_screenheight()
x=(screenWidth-width)/2
y=(screenHeight-height)/2
root.geometry("%dx%d+%d+%d" % (width,height,x,y)) |
from Blocks import *
import torch.nn.init as init
import torch.nn.functional as F
import pdb
import math
#from layers import *
def croppCenter(tensorToCrop,finalShape):
org_shape = tensorToCrop.shape
diff = org_shape[2] - finalShape[2]
croppBorders = int(diff/2)
return tensorToCrop[:,
... |
import numpy as np
import pandas as pd
import os
import cv2
import load_data
import data_util
from keras.models import Sequential
from keras.layers import Conv2D, MaxPool2D, Flatten, Dense, Lambda, Input
import keras as k
from keras.layers.core import Activation
from keras import optimizers
from sklearn.model_selectio... |
'''
1. 程式名稱:test.py
2. 程式內容:Test the Performance of Lane Detection
(1) Grayscale
(2) Use HSV to find the yellow&white mask
(2) Canny Edge Detection
(3) Hough Transform
(4) Group Left and Right Lines
(5) Fit and Draw
可修改的部份以加入了
gamma correction, CLAHE
'''
from Land_Detection.land_detection impo... |
'''
该源程序用于生成测试用例
'''
import string
import random
import sys
from checkLE import check
# 所有大写字母
s = string.ascii_uppercase
def random_mini_exp():
# 随机选择 二元运算符或者一元运算符
if random.randint(0, 1) == 0:
return "~" + random.choice(s)
else:
# 随机二元运算符
return random.choice(s) + ["|", "&"][ra... |
from game import errors
from game.conf import GRAVITY
from pygame.sprite import spritecollide
class AbstractFallingState():
def __init__(self):
raise errors.AbstractClassError()
def fall(self):
self.frame_count += 1
return int(round(1 + self.frame_count * GRAVITY))
|
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.shortcuts import render_to_response
# 表单
def search_form(request):
return render_to_response('search_form.html')
# 接收请求数据 GET 方法
def search(request):
request.encoding='utf-8'
if 'q' in request.GET and request.GET['q']:
... |
from datetime import datetime
from airflow import DAG
from airflow.operators.dagrun_operator import DagRunOrder
from airflow.operators.python_operator import PythonOperator
from airflow.operators.multi_dagrun import TriggerMultiDagRunOperator
def generate_dag_run():
for i in range(100):
yield DagRunOrder(... |
# -*- coding: UTF-8 -*-
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @tantrumdev wrote this file. As long as you retain this notice you
# can do whatever you want wit... |
# Copyright 2017 Abhinav Agarwalla. All Rights Reserved.
# Contact: agarwallaabhinav@gmail.com, abhinavagarwalla@iitkgp.ac.in
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either... |
def prime(x):
if x == 1:
return False
for i in range(2,x//2 + 1):
if x%i == 0:
return False
return True
print " ".join([str(i) for i in filter(prime,range(1,100))])
|
import time, math
import torch
import numpy as np
class TicToc:
"""
TicToc class for time pieces of code.
"""
def __init__(self):
self._TIC_TIME = {}
self._TOC_TIME = {}
def tic(self, tag=None):
"""
Timer start function
:param tag: Label to save time
... |
from VacEnvWrapper import Environment
from VacEnvGym import VacEnvironment
import VacWindowWrapper as Window
from gym.envs.registration import register
register(
id='VacEnv-v0',
entry_point='VacEnv:VacEnvironment',
) |
from config import config
from web.bot.telegram import handle_update
from web.bot.evernote import oauth_callback, oauth_callback_full_access
urls = [
('POST', '/{}'.format(config['telegram']['token']), handle_update),
('GET', '/evernote/oauth', oauth_callback),
('GET', '/evernote/oauth/full_access', oauth... |
from math import pi, pow
radius = float(input("Enter radius of the circle: "))
area_of_circle = pi * pow(radius, 2)
print("Area of the circle is: %f" % area_of_circle)
'''
Output: python3 chapter1_4_circle.py
Enter radius of the circle: 4
Area of the circle is: 50.265482
'''
|
from rest_framework import serializers
from django.contrib.auth.models import User
from items.models import Item, FavoriteItem
class RigesterSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = User
fields = ['username', 'password', 'fir... |
from flask import Flask
app = Flask(__name__)
app.config.from_object('wsgi.settings')
from wsgi import route
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
DrCoding
LSTM baseline model for the MIMIC-III ICD-9 prediction task
"""
import sys
from typing import List
import torch
import torch.nn as nn
import torch.nn.functional as f
import numpy as np
from utils import create_embedding_from_glove
class DischargeLSTM(nn.M... |
from . import views
from django.conf.urls import url
app_name = 'jobs'
urlpatterns = [
# /jobs
url(r'^$', views.JobIndexView.as_view(), name='index'),
# /jobs/<job_pk>
url(r'^(?P<job_id>[0-9]+)/$', views.JobDetailView.as_view(), name='detail'),
# /jobs/create
url(r'^create/$', views.JobCrea... |
from typing import Dict, Any
from src.data.common_types import AbstractRawDataProvider
from src.data.raw_data.raw_data_providers import ExtruderRawDataProvider
from src.estimator.launcher.launchers import ExperimentLauncher
from src.estimator.model.contrastive_model import ContrastiveModel
from src.estimator.model.est... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# /almadata02/lperez/casa_5.1.1/casa-release-5.1.1-5.el7/bin/casa
#######################################################################
# AS 205 Self-Calibration #
###############################################################... |
# Copyright (c) 2015
#
# All rights reserved.
#
# This file is distributed under the Clear BSD license.
# The full text can be found in LICENSE in the root directory.
from boardfarm import lib
from boardfarm.tests import rootfs_boot
class RouterPingWanDev(rootfs_boot.RootFSBootTest):
'''Router can ping device th... |
import unittest
class TestCase(object):
"""
Compatibility layer for unittest.TestCase
"""
try:
assertItemsEqual = unittest.TestCase.assertCountEqual
except AttributeError:
def assertItemsEqual(self, first, second):
"""Method missing in python2.6 and renamed in python3... |
#!/usr/bin/env python
# Copyright 2015-2016 Yelp 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 ... |
"""
This package contains functionality to simplify the display of complex matrices.
"""
import logging
log = logging.getLogger(__name__)
from .grid2extent import grid2extent
from .complex2rgb import complex2rgb
from .hsv import hsv2rgb, rgb2hsv
from .colormap import InterpolatedColorMap
|
def minimum_chars_palindrome(string: str) -> int:
# The string is already a palindrome
if not string or len(string) == 1:
return 0
if string[0] == string[-1]:
return minimum_chars_palindrome(string[1:-1])
return 1 + min(minimum_chars_palindrome(string[1:]), minimum_chars_palindrome(stri... |
from django.contrib import admin
from .models import Question, Answer, UserAnswer
# Register your models here.
# here I am tabulating answers in line for each questions
# Got ideas from tutorials and doc
# https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.TabularInline
class AnswerInlin... |
from scipy import stats
import numpy as np
data1 = np.array([1,2,1,1,2,1])
data2 = np.array([3,5,5,5,4,5])
# ttest
from math import sqrt
from numpy.random import seed
from numpy.random import randn
from numpy import mean
from scipy.stats import sem
from scipy.stats import t
# function for calculating the t-test ... |
from .featuregroup import FeatureGroup
from .layer import Layer
from .layergroup import LayerGroup
from .imageoverlay import imageOverlay
|
print('"""')
print("THIS IS A STRING")
print('"""')
x = "hi"
print(f"{x} Giovanni")
name = 'Elizabeth II'
title = 'Queen of the United Kingdom and the other Commonwealth realms'
reign = 'the longest-lived and longest-reigning British monarch'
x = f'{name}, the {title}, is {reign}.'
print(x)
print("{... |
#testing how to make a binary tree
#create class that represents an individual node in
#a binary tree
#TODO
#1. make binary tree
#2. creat the maxHeuristic and minHeuristic
#3. find a way to pass the state and Heuristic to the binary tree (Dylan currently working on in brain.py)
#4.
import board
import copy
import ma... |
n,k,q = input().strip().split(' ')
n,k,q = [int(n),int(k),int(q)]
a = [int(a_temp) for a_temp in input().strip().split(' ')]
d = a[n-(k%n):n]+a[0:n-(k%n)]
for a0 in range(q):
m = int(input().strip())
print(d[m]) |
# Generated by Django 2.1.4 on 2019-01-19 13:45
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0060_auto_20190118_1651'),
]
operations = [
migrations.AddField(
model_name='transac... |
#!/usr/bin/python
"""
This is the code to accompany the Lesson 2 (SVM) mini-project.
Use a SVM to identify emails from the Enron corpus by their authors:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preproce... |
from django.core.management.base import BaseCommand, CommandError
from robot_hive import server
from sequbot_data.robot_hive.constants import HIVE_PORT
from sequbot_data import models
STATUS = models.SocialAccount.STATUS
class Command(BaseCommand):
help = 'Starts robot hive server'
def log(self, msg):
... |
import os
import json
import datetime
import pandas as pd
import networkx as nx
from libcity.utils import ensure_dir
from logging import getLogger
from libcity.evaluator.abstract_evaluator import AbstractEvaluator
class MapMatchingEvaluator(AbstractEvaluator):
def __init__(self, config):
self.metrics = ... |
# -*- coding: utf-8 -*-
import pygame
import util
import global_store as store
class Display():
def __init__(self):
self.current_display = WelcomDisplay()
def draw(self):
store.screen.blit(self.current_display.background, (0,0))
"""
# - Ajout de tous les elements de l'ecran -
for item in currentDisplay.d... |
from .browser import BrowserHtml, BrowserResponse
from .client import HttpClient
from .http import (
HttpRequest,
HttpRequestBody,
HttpRequestHeaders,
HttpResponse,
HttpResponseBody,
HttpResponseHeaders,
)
from .page_params import PageParams
from .url import RequestUrl, ResponseUrl
|
from statsmodels.tsa.arima_model import ARIMA
from statsmodels.stats.diagnostic import acorr_ljungbox
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.graphics.tsaplots import plot_pacf
from statsmodels.tsa.stattools import adfuller as ADF
filename ... |
def lambda_handler(event, context):
if event['request']['type'] == "LaunchRequest" :
return onLaunch(event['request'], event['session'])
elif event['request']['type'] == "IntentRequest" :
return onIntent(event['request'], event['session'])
elif event['request']['type'] == "SessionEndedR... |
import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle
app = Flask(__name__)
Linear_Regression = pickle.load(open('Linear_Regression.pkl', 'rb'))
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict',methods=['POST'])
def predict()... |
from flask import render_template, Blueprint, make_response, request
main = Blueprint('main', __name__)
@main.route("/")
@main.route("/home")
def home():
resp = make_response(render_template("home.html"))
resp.set_cookie("userID", "12345")
return resp
@main.route("/getCookie")
def getCookie():
userID = request.... |
#!/usr/bin/env python
import os
import sys
from os.path import join, dirname
from dotenv import load_dotenv
if __name__ == "__main__":
try:
# Create .env file path and load it
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
os.environ.setdefault("DJANGO_SETT... |
from unittest import TestCase
from sprint_2.b_stonks import max_income
class MaxIncomeTest(TestCase):
def test_empty(self):
self.assertEqual(0, max_income([]))
def test_single(self):
self.assertEqual(0, max_income([1]))
def test_two(self):
self.assertEqual(1, max_income([0, 1]))... |
from gandalf_app.database.models import Project, UploadedMediaFile, UploadedDataFile, Analysis, ResultDetails, \
ResultSummary, Elaboration
from gandalf_app.api.project.dao import save, get_all, get_project_by_id, saveMediaFile, saveDataFile, deleteProject, \
get_media_by_id, removeMediaFromProject, get_data_by... |
import pygame
from scripts.game_objects.game_object import GameObject
from scripts.utilities import load_image
class HealthBarNPC(GameObject):
def __init__(self, game, npc):
super().__init__(game, load_image('resources/sprites/gui/npc_hp_bar.png'), npc.rect.x, npc.rect.y - 20, game.all_sprites)
se... |
student = ['A','B','C','D','E']
kor_score = [49,79,20,100,80]
math_score = [43,59,85,30,90]
eng_score = [49,79,48,60,100]
mid_term_score = [kor_score, math_score, eng_score]
student_score =[ 0 for _ in range(len(student)) ]
# print(mid_term_score[0])
for i in range(len(mid_term_score)):
for j in range(len(studen... |
from mcpi.minecraft import Minecraft
mc=Minecraft.create()
x,y,z=mc.player.getTilePos()
mc.setSign(x,y,z,63,0,"Welcome","My","World") |
from pyowm import OWM
import datetime
import os
#from weather import Weather
owm = OWM(os.environ['OWM_API_KEY'])
now = datetime.datetime.now()
def get_weather():
# collect Forecasters for each location
owm_obs = [None, None, None]
owm_obs[0] = owm.three_hours_forecast('Leiden,NL')
owm_obs[1] = owm.three_hours_f... |
# -*- coding: utf-8 -*-
__author__ = 'ivany'
def md5(str):
import hashlib
m = hashlib.md5()
m.update(str)
return m.hexdigest()
def filterHtml(html):
import re
dr = re.compile(r'<[^>]+>', re.S)
return dr.sub('', html) |
import math
class MathUtils:
def dist(a: tuple, b:tuple):
return ((a[0]-b[0])**2+(a[1]-b[1])**2)**0.5
def hypoth(s: int):
return math.sqrt((s**2) * 2) |
from tkinter import *
import time
import sys
tk = Tk()
canvas = Canvas(tk,width=1024,heigh=768) #ancho-alto
canvas.pack()
img2 = PhotoImage(file = "F.png") #fondo Ancho1024 Alto 768
#label1 = Label(tk, image=img2)
#label1.grid(row=1,column=1)
#print(img2.size)
img = PhotoImage(file = "M.png") #personaje
ca... |
# -*- coding: utf-8 -*-
import tensorflow as tf
#""四维张量""
t=tf.constant(
[
#"第1个2行2列2深度的三维张量"
[
[[1,12],[6,18]],
[[9,13],[4,11]],
],
#"第2个2行2列2深度的三维张量"
[
[[2,19],[7,17]],
[[3,15],[8,11]]
]
],tf.float32
... |
#!/usr/bin/env python
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License")... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
if n == 0:
return []
def helper(lo, hi):
if ... |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
import scipy
from scipy import signal
matplotlib.use("pgf")
plt.rcParams.update({
"pgf.texsystem": "pdflatex",
"font.family": "serif",
"font.size": 6,
"legend.fontsize": 5,
"ytick.labelsize": 4,
"... |
import os
import pygame
import eng.interface as interface
import eng.foreground_object as foreground_object
import eng.box as box
import eng.globs as globs
import eng.settings as settings
import eng.font as font
import eng.pokemon as pokemon
from . import summary_screen
import eng.data as data
import eng.script_engin... |
def isprime(number):
for p in range(2,number):
x = number % p
if x == 0:
return False,p
|
from winsound import Beep # Import des modules
from time import sleep
latin=['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',' ']
morse=['-----','.----','..---','...--','....-','.....','-....','--...','---..','----.','.-','... |
import numpy as np
import pandas as pd
from nltk import word_tokenize
from sklearn.metrics.pairwise import euclidean_distances
import json
from tools.exceptions import SummarySizeTooSmall, TextTooLong
from tools.tools import sentence_tokenize
class EmbeddingsBasedSummary:
"""
This algorithm is following the ... |
# Generated by Django 2.0.1 on 2018-01-03 03:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('quora', '0003_auto_20180102_2209'),
]
operations = [
migrations.AlterField(
model_name='answer'... |
from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView
from .models import Entry
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.views.generic.edit import ... |
from pytest_postgresql import factories
# We do custom fixture to have fixed port for easier local connection
postgresql_custom_fixture = factories.postgresql_proc(port=5433)
postgres = factories.postgresql(
'postgresql_custom_fixture',
load=['database_schema.sql']
)
|
import pytest
import torch
from torch.autograd import Variable
from pytorch_unet import UNet
def test_invalid_shape():
with pytest.raises(ValueError):
UNet(input_shape=(3, 33), layers=3, num_classes=1)
def test_unet_double_center():
net = UNet(input_shape=(3, 32), layers=3, num_classes=2, double_ce... |
# -*- coding: utf-8 -*-
def takefirst(elem):
return elem[1]#返回在A上的执行时间
def takesecond(elem):
return elem[2]#返回在B上的执行时间
def calc_jobs_cost(jobs_a,jobs_b):
total_cost=0
temp_calc=0
for i in range(len(jobs_a)):
temp_calc+=jobs_a[i][1]
if temp_calc>total_cost:
total_cost=temp_calc
total_cost+=jobs_a[i][2]
... |
"""
Exploring trained generator model
"""
import os, sys
import numpy as np
import matplotlib.pyplot as plt
# flint imports
# src imports
import utils
################################################################################
### Interrogate latent space
######################################################... |
from biokit.io.fastq import FASTQ as FastQ
def set_example1():
f = FastQ()
f.identifier = ''
f.sequence = 'CCCC'
f.quality = '@ABC'
return f
def set_example2():
f = FastQ()
f.identifier = '@slicing'
f.sequence = 'CCCCTTTT'
f.quality = '@ABC;;;;'
return f
def test_offset():
... |
from model_location import ModelLocation
class ControllerLocation():
def create_location(self,
location_name,
location_genre,
location_code):
return ModelLocation(location_name, location_genre, location_code)
|
import argparse
from cyy_naive_pytorch_lib.default_config import DefaultConfig
class ExperimentConfig(DefaultConfig):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.distributed_algorithm = None
self.worker_number = None
self.round = None
def load_args(self, par... |
# Creating the superclass Candidate which has a name and a position
class Candidate:
def __init__(self,position,name):
self.name = name
self.position = position
self.votes1 = 0 # vote as a first choice
self.votes2 = 0 # vote as a second choice
self.votes3 = 0 # vote as a t... |
import re
def strip_non_alphanumeric(input):
pattern = re.compile('[\W_]+')
return pattern.sub('', input)
|
# content: come on !
# author: 十六
# date: 2020/8/5
# - 需求:爬取搜狗指定词条对应的搜索结果页面(简易网页采集器) UA检测
# 这里 需要加上 UA伪装 US:User-Agent(请求网页载体的身份标识)
# 一定要使用 UA伪装
import requests
if __name__ == "__main__":
# 将UA伪装: 将对应的user-agent 封装到一个字典中
headers = {
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X ... |
# -*- coding: utf-8 -*-
# @Time : 2019-07-19 16:43
# @Author : finupgroup
# @FileName: BERT.py
# @Software: PyCharm
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from keras.callbacks import TensorBoard
from keras_bert import load_trained_model_from_checkpoint, Tokenizer, get_custom_objects
imp... |
#Karla Ivonne Serrano Arevalo
#Ejerercicio 1.b
#Diciembre 2016
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-1,5,100)
y=2*x**2-8*x-11
plt.plot(x,y,linewidth=5, color='r')
plt.legend()
plt.title('Laboratorio 3b ejercicio 1b')
plt.xlabel('eje x')
plt.ylabel('eje y')
plt.grid(True)
plt.show()
|
# -*- coding: utf-8 -*-
"""
Servidor de TFG - Proyecto Janet
Versión 1.0
MIT License
Copyright (c) 2019 Mauricio Abbati Loureiro - Jose Luis Moreno Varillas
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to ... |
from setting import log
logging = log()
class InfoBulider:
def __init__(self,postion,city):
self.__postion = postion
self.__city = city
def urlbulider(self):
url = 'https://www.lagou.com/jobs/positionAjax.json?{}&needAd' \
'dtionalResult=false'.format(self.__city)
... |
import os
import sys
if not os.path.exists('res/recommend_2.txt'):
print('Cannot find res/recommend_2.txt')
sys.exit()
t_users = {}
user_file = "res/predict/dev.users"
with open(user_file, "r") as fp:
for line in fp:
viewer_id = line.strip()
t_users[viewer_id] = 1
inferences = {}
with open('res/recomme... |
from LinearRegression import regression as lr
import numpy as np
import tensorflow as tf
x_data = np.random.randn(2000, 3)
w_real = [0.3, 0.5, 0.1]
b_real = -0.2
learningRate = 0.5
# w_real_column, w_real_row = x_data.shape
# print(w_real_column, w_real_row)
regression = lr(x_data,w_real,b_real,learnin... |
import random
import numpy as np
import itertools
class Allocation:
def __init__(self, num_nodes, comm_matrix, mesh_dims, node_weights=None):
self.num_nodes = num_nodes
self.mesh_dims = mesh_dims
self.comm_matrix = comm_matrix
self.possible_locs = self.generate_possible_coords()
... |
import json
import pymorphy2
morph = pymorphy2.MorphAnalyzer()
with open("./1grams-3.txt") as f:
content = f.readlines()
content = [x.strip() for x in content]
normalised_idf = dict()
print("Parsing has started!")
for raw in content:
tf, word = raw.split('\t')
if word == {}:
continue
word_... |
import logging
import logging.handlers
import os
# from logging_utils.telegramhandler import TelegramLoggerHandler
def generate_logger(name='root'):
logger = logging.getLogger(name)
logger.handlers.clear()
logger.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler()
streamHandler.setF... |
class Solution(object):
def addNegabinary(self, arr1, arr2):
"""
:type arr1: List[int]
:type arr2: List[int]
:rtype: List[int]
"""
n = max(len(arr1),len(arr2))
res=[0]*(n+2)
arr1 = arr1[::-1]
arr2 = arr2[::-1]
for i in xrange(n):
... |
# existing markdown inlinePatterns
# https://github.com/Python-Markdown/markdown/blob/2.6/markdown/inlinepatterns.py
from markdown.extensions import Extension
from markdown.inlinepatterns import SimpleTagPattern, Pattern
from markdown.inlinepatterns import SubstituteTagPattern
from markdown.util import etree
from mark... |
from pymongo import ASCENDING, DESCENDING
from models import Vote, GistPoints, UserPoints
from mongokit import Connection
import settings
con = Connection()
con.register([Vote, GistPoints, UserPoints])
db = con[settings.DEFAULT_DATABASE_NAME]
def run():
collection = db.Vote.collection
collection.ensure_index('... |
# -*- coding: utf-8 -*-
__author__ = 'PC-LiNing'
import gensim
from lda import load_data
import numpy as np
from word2vec import model_util
import redis
def degree_diff(word,centers):
distances = []
word_vec = get_vector(word)
if word_vec is None:
return None
for center in centers:
d... |
import re
import clipboard
import xlrd as xl
def extract_information(file_path, start, end, ent="", append_ents=False):
"""
This method takes a text file and extracts a slice of it and returns a list of strings. entities can be appended.
:param file_path: text file (e.g. parsed pdf file)
:param start... |
import urllib
import requests
import os
import json
from article import Article
from facts import Facts
class Query(object):
def __init__(self, query):
self.API_KEY = os.getenv('GOOGLE_API')
self.SEARCH_ENGINE_ID = '015040051912301786117:ukzldfl328w'
self.query = query.replace(' ','+')
... |
import glob
from pyMCDS_cells import pyMCDS_cells
import numpy as np
import matplotlib.pyplot as plt # if you want to plot results
# run this script from your output directory
xml_files = glob.glob('output*.xml')
xml_files.sort()
print(xml_files)
n = len(xml_files)
t = np.zeros(n)
uninfected = np.zeros(n)
infected ... |
import os,sys,re,time,shutil
import random
import numpy as np
from tfnlp.image_summary.model import ism
from tfnlp.image_summary.image_feature_generator import image_feature_generator
from tfnlp.image_summary.summary_feature import summary_dict,counter,word_list,word_dict
from tfnlp.image_summary.train_decode_generato... |
from nmap import *
def run_nmap(ip, ports):
scan_results = "\n"
string_list = []
print("Running nmap...")
nm = nmap.PortScanner()
nm.scan(ip, ports)
nm.command_line()
for host in nm.all_hosts():
string_list.append('----------------------------------------------------')
st... |
from PySide.QtCore import *
from PySide.QtGui import *
class ParamItem(object):
def __init__(self, name, parent, data, meta, model):
self.name = name
self.parentItem = parent
self.items = {}
self.model = model
if type(data) == dict:
for k, v in data.items():
... |
from django import forms
class UrlSwapForm(forms.Form):
origin_url = forms.URLField(label='Adres url', required=True)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.