text stringlengths 38 1.54M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 7 20:19:18 2021
@author: Md.Abdullah
"""
from PIL import Image
img=Image.open("J:\Digital-Image-Processing\Images\messi.jpg")
#img.show()
new_img=Image.open("J:\Digital-Image-Processing\Images\messi.jpg").convert("L")
new_img.show() |
# Generated by Django 3.1.1 on 2020-12-09 23:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('login', '0004_shopuser_recipes'),
]
operations = [
migrations.AlterField(
model_name='shopuser',
name='recipes',
... |
import string, cgi, time, json
import threading
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from ConfigParser import *
from servotorComm import runMovement
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
self.send_response... |
from flask import Flask, render_template, request , redirect
import MySQLdb
import pandas as pd
import json
from flask_mysqldb import MySQL
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index22.html")
@app.route('/getAllBlogs')
def getAllBlogs():
conn = My... |
""" There are three types of edits that can be performed on strings:
insert a character, remove a character, or replace a character.
Given two strings, write a function to check if they are one edit
or zero edits away.
pale, ple -> true
pales, pale -> true
pale, bale -> true
pale, bake -> false
create dictionary
chec... |
import sys
import gc
from scipy.sparse import coo_matrix
from scipy.sparse import csr_matrix
from scipy.io import mmwrite
from scipy import sparse
import tables
import time
import numpy as np
import pickle
def store_sparse_mat(M, name, filename='store.h5'):
print(M.__class__)
assert(M.__class__ == sparse.csr.... |
# 邮箱设置
EMAIL_USE_TLS = False #是否使用TLS安全传输协议(用于在两个通信应用程序之间提供保密性和数据完整性。)
EMAIL_USE_SSL = False #是否使用SSL加密,qq企业邮箱要求使用
EMAIL_HOST = 'smtp.163.com' #发送邮件的邮箱 的 SMTP服务器,这里用了163邮箱
EMAIL_PORT = 25 #发件箱的SMTP服务器端口
EMAIL_HOST_USER = 'louisyoung163@163.com' #发送邮件的邮箱地址
EMAIL_HOST_PASSWORD = 'YPTZUTEJJAXTYFWY' #... |
from discord.ext import commands
import discord
import platform
import os
class activeCommand(commands.Cog):
def __init__(self, bot):
self.bot = bot
cur_path = os.path.dirname(__file__)
# Update Command
@commands.command(pass_context=True)
@commands.has_permissions(manage_messages=True)
... |
from __future__ import division
from pprint import pprint
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from gcloud import GenomicsOperation, OperationCostCalculator
from cromwell import Metadata
from collections import defaultdict
import json
import sys
import math
import a... |
from edge import Edge
class Vertex:
def __init__(self, id):
self.id = id
self.edgesTo = []
self.edgesFrom = []
def addEdgeTo(self, edge):
self.edgesTo.append(edge)
def addEdgeFrom(self, edge):
self.edgesFrom.append(edge)
def toString(self):
list = "Id: ... |
def solution(people, limit):
# 가벼운 사람부터 무거운 사람 순으로 sort 진행
people.sort()
# light한 사람과 무거운 사람을 비교하는 방식으로 진행.
# 그러다가 둘이 더해서 100 이하가 되면 light에 1 더해주고 heavy는 1 빼주고, count에 1 더해주는 방식으로 진행
# else 문으로는 heavy만 빼준다.
# 이걸 계속 반복하다가 light가 heavy보다 커지는 경우 break
# 어차피 탈 수 있는 사람은 최대 2명이고 limit 제한이 있기... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self,... |
from selenium import webdriver
from bs4 import BeautifulSoup
import requests
def init_driver():
options = webdriver.ChromeOptions()
options.add_argument('--headless')
# options.add_argument('window-size=1200x600')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
... |
import math
import pickle
from pympler import tracker
import numpy as np
import cv2
from visnav.algo import tools
from visnav.algo.base import AlgorithmBase
from visnav.algo.keypoint import KeypointAlgo
from visnav.algo.tools import PositioningException, Stopwatch
from visnav.iotools import lblloader
from... |
import tensorflow as tf
import sys
import hyperparams as hyp
def read_and_decode(filename_queue):
compress = tf.python_io.TFRecordOptions(
compression_type=tf.python_io.TFRecordCompressionType.GZIP)
reader = tf.TFRecordReader(options=compress)
_, serialized_example = reader.read(filename_queue)
... |
import pandas as pd
import matplotlib.pyplot as plt
def read_vegetable_data(filename):
df = pd.DataFrame()
# Please, introduce your answer here
return df
def generate_plot_1(df):
# Code to generate Plot 1 (show or save to file)
# Please, introduce your answer here
print('Plot 1 not completed yet.') # Remov... |
import tushare as ts
import pandas as pd
from scipy import stats
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
year = 2019
quarter = 3
basics_df = ts.get_stock_basics("2019-09-30")
profit_df = ts.get_profit_data(year, quarter)
growth_df = ts.get_growth_data(year... |
"""
A second, custom AdminSite -- see tests.CustomAdminSiteTests.
"""
from __future__ import absolute_import
from django.conf.urls import patterns
from django.contrib import admin
from django.http import HttpResponse
from . import models, forms, admin as base_admin
class Admin2(admin.AdminSite):
login_form = fo... |
from tools.color_utils import ColorUtils
# 方形大小
class Rect:
width: int
height: int
# 特征 所有点加起来的值
feature: int
# 特征点1 坐标0,0的颜色
feature_1: int
# 特征点2 坐标中心点的颜色
offset_x2: int
offset_y2: int
feature_2: int
# 特征点3 坐标最右下角点的颜色
# 3个特征点都符合的情况下再计算总值
feature_3: int
def... |
# -*- coding: utf-8 -*-
"""
1.3 URLify: Write a method to replace all spaces in a string with '%20: You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string. (Note: If implementing in Java, please use a character array s... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2018 Kyoto University (Hirofumi Inaguma)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Base class for loading dataset for the CTC and attention-based model.
In this class, all data will be loaded at each step.
You can use the multi-GPU ... |
import hoomd
import hoomd.md
import hoomd.dump
import hoomd.group
from hoomd.htf import tfcompute
import tensorflow as tf
from sys import argv as argv
from math import sqrt
if(len(argv) != 3):
print('Usage: basic_ann_ff.py [N_PARTICLES] [training_dir]')
exit(0)
N = int(argv[1])
training_dir = argv[2]
with hoomd... |
import sys
alphabet = ['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']
foundLetters = []
with open('commentFromOcrHtml.txt') as f:
for line in f:
for letter in alphabet:
if letter in line:
... |
import unittest
from apidaze.http import Http, HttpMethodEnum
from urllib3_mock import Responses
import json
responses = Responses('urllib3')
class TestHttp(unittest.TestCase):
@property
def httpInstance(self):
return Http(
api_key='API_KEY',
api_secret='API_SECRET',
... |
import requests
import Cookie
import sys
import random
from bs4 import BeautifulSoup
from urlparse import urljoin
outputFP = './public/graphFile.json'
# Function to write urls from DFS to json file for
# d3
# Args: urls in order from DFS, filePath to save
# Returns: None
def writeToFile(urls, filePath):
with open... |
# Generated by Django 2.2.3 on 2019-07-30 08:15
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Attendee',
fields=[
('first_nam... |
import os
SRC_SUFFIX = ['.c', '.cpp', '.cc', '.cxx']
class Workspace:
def __init__(self, include_paths):
self.include_paths = include_paths
def calculate(self):
paths = []
for path in self.include_paths:
if os.path.isdir(path):
paths.extend(self._walk(pa... |
import pytest
from shop_restapi.models.item import ItemModel
from shop_restapi.models.store import StoreModel
from shop_restapi.models.user import UserModel
@pytest.fixture
def item():
item = ItemModel(name='item_name', price=1.00, store_id=1)
return item
@pytest.fixture
def store():
store = StoreModel(... |
# -*- coding: utf-8 -*-
import os
from .common_utils import ScriptRunner, forceIP
from .exceptions import ParamProcessingError, NetworkError
__all__ = ('ParamProcessingError', 'processHost', 'processSSHKey')
def processHost(param, process_args=None):
"""
Given parameter is a hostname, try to change it to... |
# https://pymotw.com/3/asyncio/control.html
"""
wait() can be used to pause one coroutine until th other background
operations complete - if order of execution doesn't matter.
"""
import asyncio
async def phase(i):
print('in phase {}'.format(i))
await asyncio.sleep(0.1 * i)
print('done with phase {}'.fo... |
'''
Set in python:
Important points to set:
1. Set ko {} is braket se denote karete hain.
2. Set values ka koi order nahi hota hai. Means values ko agar index position ke behalf par feach karna caho to error milega.
3. Set me values hamesa unique honge.
4. Set values hamesa suffle karte rahete hain.
Set ka use colle... |
import requests
import json
from datetime import datetime
from mirrorpy.plugin import Plugin
class WeatherPlugin(Plugin):
baseurl = "http://api.openweathermap.org/data/2.5/{0}?units=metric&APPID=1ba44d08af637d2899097f510bf9f882"
query_url = None
def __init__(self, name="", query=None, city=None, coords=... |
hero_ids = {
1: 'antimage',
2: 'axe',
3: 'bane',
4: 'bloodseeker',
5: 'crystal_maiden',
6: 'drow_ranger',
7: 'earthshaker',
8: 'juggernaut',
9: 'mirana',
10: 'morhpling'
} |
import tensorflow as tf
import numpy as np
from tensorflow.contrib.distributions import Normal
from ..ops import backward_warp, forward_warp
from .image_warp import image_warp
DISOCC_THRESH = 0.8
def length_sq(x):
return tf.reduce_sum(tf.square(x), 3, keepdims=True)
def compute_losses(im1, im2, flow_fw, flow... |
import numpy as np
# Finding unsige cell
# File name: SUDOKU.py
def FindUnsignedLocation(Board, l):
for row in range(0, 9):
for col in range(0, 9):
if (Board[row][col] == 0):
l[0] = row
l[1] = col
return True
return False
# Hàm kiểm tra tính... |
#! /usr/bin/env python
#
def multiperm_enum ( n, k, counts ):
#*****************************************************************************80
#
## MULTIPERM_ENUM enumerates multipermutations.
#
# Discussion:
#
# A multipermutation is a permutation of objects, some of which are
# identical.
#
# While there a... |
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
import pandas as pd
from ansm_utils import get_selectors
import time
import content_agent
url = "https://ansm.sante.fr/S-informer/Informations-de-securite-Lettres-aux-professio... |
# _*_ coding: utf-8 _*_
"""
ctask.py by xianhu
"""
import re
from typing import TypeVar
class Task(object):
"""
class of Task, to define task of fetcher, parser and saver
"""
# class variable, which to define type of parameters
TypeContent = TypeVar("TypeContent", str, tuple, list, dict)
Typ... |
import csv
from DataCollection.User import User
__author__ = 'lizzybradley'
class FixTotalEdits:
user_list = []
def __init__(self, filename):
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
self.user_list.append(User(row))
def fix(self):
for user in self.user_l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# DateTime : 2019-06-03 14:04:35
# Author : dongchuan
# Version : v1.0
# Desc : Http过滤器:过滤掉正常的URL,减少后续机器学习的数据压力
import re
import sys
import urlparse
import simplejson
from urldetect.conf.config import Config
from urldetect.utils.common import Common
from urldetect.u... |
from Gui.Base.widget import Widget
class ButtonPressedController:
def __init__(self, widget: Widget):
self.widget = widget
for i in range(len(self.widget.buttons)):
func = self.__getattribute__("button{}_on_click".format(i))
self.widget.buttons[i].clicked.connect(func)
cl... |
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selene.support._extensions.webdriver_manager import ChromeType
from selene import Config, Browser, support
@pytest.fixture(scope='function')
def driver_per_... |
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from mapbox import Distance
from ..profiles.model import Profile
from ..hitches.model import Hitch
from .model import Drive
f... |
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.app import App
from kivy.uix.image import Image
# import kivy
class AlternateApp(App):
def build(self):
self.layout=BoxLayout()
... |
import csv
from collections import Counter
with open("height_weight.csv",newline="") as f:
reader=csv.reader(f)
file_data=list(reader)
file_data.pop(0)
newData=[]
for i in range(len(file_data)):
num=file_data[i][1]
newData.append(float(num))
data=Counter(newData)
mode_for_data_range={"50-... |
from django.shortcuts import render
from .models import Team
def teamlist(request):
items = Team.objects.all()
return render(request, 'MyApp/teamplayer.html', {'items': items})
|
from django.db import models
class ContentType(models.Model):
name = models.CharField(max_length=128)
#Include model into same app
class Meta:
app_label = 'communications'
def __unicode__(self):
return self.name
class Submissions(models.Model):
name = models.CharField(max_lengt... |
# -*- coding: cp1252 -*-
'''
Created on 30/09/2013
@author: Pedro
'''
def contarelementos(lista):
if lista==[]:
return 0
else:
return 1+contarelementos(lista[1:])
def multiplicarelementos(multi,lista,resp=[]):
if lista==[]:
return resp
else:
return multiplicareleme... |
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
N = INT()
ans = 0
for i in range(1, N+1):
if i % 3 == 0 or i % 5 == 0:
continue
else:
ans += i
print(ans)
|
from flask.ext.wtf import Form, TextField, TextAreaField, SubmitField
# import classes above
#fill in variables
class ContactForm(Form):
name = TextField("name")
email = TextField("email")
message = TextAreaField("message")
submit = SubmitField("submit")
|
import logging
import signal
logger = logging.getLogger(__name__)
class GracefulKiller:
kill_now = False
def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
def exit_gracefully(self, signum, frame):
logger.... |
import telebot
import config
import cityWeather as cw
import wear
bot = telebot.TeleBot(config.TOKEN)
@bot.message_handler(commands=['start','help','reroll'])
def req(mes):
if mes.text == '/help':
bot.send_message(mes.chat.id, 'Для получения информации о погоде в городе, введите его и отправьте мне.')
elif mes.te... |
#################################################################################################################
# ewstools
# Description: Python package for computing, analysing and visualising
# early warning signals (EWS) in time-series data
# Author: Thomas M Bury
# Web: https://www.thomasbury.net/
# Code repo: h... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Option',
fields=[
('id', models.AutoField(verbo... |
#
# This computer program is the confidential information and proprietary trade
# secret of Anuta Networks, Inc. Possessions and use of this program must
# conform strictly to the license agreement between the user and
# Anuta Networks, Inc., and receipt or possession does not convey any rights
# to divulge, reproduce,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
import sys
from vectors import Vector
from colors import Color
import actors
import actions
import language
import logs
test_string = '''
Cast:
bob = Square size 50x50 color red
star = Star color white
'''
#print(table_of_symbols)
#print(r... |
"""
职责链模式:
链条上的每个环节有自己的职责范围,在自己的职责范围内就立即处理,入股超过自己的职业,那么就传给链条的一下环节
"""
from abc import ABC, abstractmethod
class BaseHandler(ABC):
@abstractmethod
def hande(self, money):
pass
class Kuaiji(BaseHandler):
def __init__(self):
self.next_handler = None
def set_next_handler(self, next_hand... |
a=int(input())
sum=0
b=input().split()
for i in range(len(b)):
x=int(b[i])
for j in range(i):
if(int(b[j])<x):
sum=sum+int(b[j])
print(sum) |
# from continent import *
from itertools import combinations
from color import Color
from card import Card, add_card, find_card, remove_card, total_wildcards
from troop import Troop
class Player():
def __init__(self, color, troops, cards=[]):
''' [color] is a Color object. [troops] is int. [cards] is a l... |
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render
from woid.core.models import Organization
from woid.core.forms import OrganizationForm
def home(request):
user = request.user
i... |
#import java.util.ArrayList;
# this class implements the getPossibleActions for each type of piece
import Utils
from Position import Position
from Action import Action
from State import State
class Piece:
# this method must be completed with all the possible pieces
def __init__(self):
self.m_color = -1
self.m... |
# example 4: ToUpper
text = data.getObject()
data.setProperty("input",text)
outputText = text.upper()
data.setProperty("output",outputText)
data.setObject(outputText) |
# Generated by Django 3.2.8 on 2021-10-19 02:33
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('pages', '0003_auto_20211018_2040'),
]
operations = [
migrations.AddField(
model_name='newsletter',
... |
"""
Utility functions for the firex_keeper package.
"""
from collections import namedtuple
import gzip
import json
import os
import stat
from firexapp.submit.uid import Uid
from firexapp.events.event_aggregator import FireXEventAggregator
from firexapp.events.model import FireXTask
FireXTreeTask = namedtuple('Fi... |
#!/usr/bin/python3
#--------------绘制barChart直方图(多色)包括x轴数据+y轴数据 使用append插入单行-----------------
from openpyxl import Workbook
from openpyxl.chart import (
Reference,
Series,
BarChart
)
book = Workbook()
sheet = book.active
# Create some data and add it to the cells of the active sheet.
rows = [
("USA", ... |
from django.urls import path
from . import views
urlpatterns = [
path ('',views.main, name="main"),
path ('contact.html',views.contact, name="contact"),
path ('gallery.html',views.gallery, name="gallery"),
path ('about.html',views.about, name="about"),
] |
from django.db import models
# Create your models here.
class Module(object):
def __init__(self, moduleName, pin, pinStatus, key, error):
self.moduleName = moduleName
self.pin = pin
self.pinStatus=pinStatus
self.key=key
self.error=error
|
import sys
import numpy as np
import math
exec(open("tracts_mod.py").read())
# Read in the parameters
rate = sys.argv[1]
tstart = int(sys.argv[2])
npts = int(sys.argv[3])
maxlen = int(sys.argv[4])
pop = int(sys.argv[5])
Ls = [1]
thefile = open("psivec.txt","r")
psivec = list(np.loadtxt("psivec.txt"))
# Run tracts co... |
# Copyright 2018 SEDA Group at CU Boulder
# Created by:
# Liam Kilcommons
# Space Environment Data Analysis Group (SEDA)
# Colorado Center for Astrodynamics Research (CCAR)
# University of Colorado, Boulder (CU Boulder)
"""
ssj_auroral_boundary
--------------------
Figure of Merit boundary identification for DMSP SSJ5... |
# file mygame/typeclasses/latin_noun.py
from evennia import DefaultObject
# adding the following for colors in names for pluralization
from evennia.utils import ansi
# adding the following for redefinition of 'return_appearance'
from collections import defaultdict
# from evennia.utils.utils import list_to_string
clas... |
# Generated by Django 3.1.1 on 2020-10-01 05:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('uploadingJson', '0005_auto_20201001_1030'),
]
operations = [
migrations.AlterField(
model_name='jsondatas',
name='id... |
import numpy as np
import matplotlib.pyplot as plt
import mltools as ml
iris = np.genfromtxt("data/iris.txt", delimiter=None)
Y = iris[:,-1]
X = iris[:,0:2]
X,Y = ml.shuffleData(X,Y)
Xtr,Xte,Ytr,Yte = ml.splitData(X, Y, 0.75)
def partA(Xtr, Xte, Ytr, Yte):
knn = ml.knn.knnClassify()
# varying values of K
for k in ... |
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from secret import username, passwd
'''
1. Timer
2. Refresh every 5sec
3. Alternative route
4. Notify sms
5. Set selector
'''
# open chrome
driver = webdriver.Chrome()
driver.get("https://or.ump.edu.my/or/")
... |
# Generated by Django 3.1.1 on 2020-11-24 08:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0008_auto_20201124_0139'),
]
operations = [
migrations.CreateModel(
name='teacher',
fields=[
... |
#!/usr/local/bin/python3
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Merge
import matplotlib.pyplot as plt
import pickle
import json
import mfcc_model
import tempotrack_model
import spectral_contrast_peaks_model
... |
#!/bin/env python
# ^_^ encoding: utf-8 ^_^
# @date: 2015/8/27
__author__ = 'icejoywoo'
import numpy as np
# create a 3D numpy array
arr = np.zeros((3, 3, 3))
a = np.array([
[11, 12, 13],
[21, 22, 23],
[31, 32, 33],
])
print a.T
# 多维数据用 , 分割,表示对不同维度的操作
print a[1,:]
print np.nonzero(a[:,0])[0]
print ... |
#!/usr/bin/python
import getopt
import os
import signal
import string
import sys
def file_to_pid(fname):
if (not os.path.exists(fname)):
return -1
f = open(fname, 'r')
pid = int(f.readline())
f.close()
return pid
def pid_to_file(fname, pid):
f = open(fname, 'w')
f.write(str(pid))
... |
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Oct 26 2018)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
###########################################################################
impor... |
"""
.. module:: wheel_control
:platform: Unix
:synopsis: Module for interfacing with the Commanduino core device in the Base Layer
.. moduleauthor:: Graham Keenan <https://github.com/ShinRa26>
"""
import os
import sys
import time
import inspect
HERE = os.path.dirname(os.path.abspath(inspect.getfile(inspect.... |
from src.program import get_secret_number
def test_secret_number_in_range():
secret_number = get_secret_number()
assert 1 <= secret_number <= 100
|
#!/usr/bin/env python
from StringIO import StringIO
from PIL import Image
import cv2
import numpy as np
import math
def list_camera_ids():
return ['0', '1']
class Camera(object):
def __init__(self, camera_id, size, fps):
self.width = size[0]
self.height = size[1]
self.count = 0
self.last_state... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time
import numpy as np
import scipy as sp
import scipy.io as sio
import sys
import os
#import MySQLdb
dict_clean = {}
with open('train.txt','r') as f:
for line in f.readlines():
key_val = line[:-1].split(' ')
dict_clean[key_val[0]] = key_val[1]
def CNNclean(pa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayEbppJfexportChargeinstQueryModel(object):
def __init__(self):
self._biz_type = None
self._extend_field = None
self._page = None
self._page_query = None
... |
#Written by 《ERFAN》
#t.me/ErfanMAfshar
import hashlib,os
def main() :
os.system('clear')
print("---------------------------------")
print("| |")
print("| Hash Generator |")
print("| |")
print("| {00} Generate... |
# -*- coding: utf-8 -*-
"""
Append simulation results into one projection file per turn (i.e. sum up all separate simualations, but keep turns separated).
"""
import numpy as np
import os
#import matplotlib.pyplot as plt
for folder in ('70100644Phantom_labelled_no_bed',
'70114044Phantom_labelled_no_be... |
import players
import string
'''
Squash league management UI
Author: Ed Jones
Date: 18 May 2016
'''
#
# default data file
data_file = "../data/players.txt"
#
# null edit value
edit_none = players.edit_none
#
# if anything has changed the data then prompt
modified = 0;
# always load the players.txt file
players.load_... |
#
# Copyright (c) 2007 Hyperic, 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 w... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-18 13:52
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import smart_selects.db_fields
class Migration(migrations.Migration):
initial = True
de... |
"""
Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""
import re
from cfnlint.rules import CloudFormationLintRule
from cfnlint.rules import RuleMatch
class OutputNameStyle(CloudFormationLintRule):
"""Check if Outputs follow style guide"""
id =... |
import sys
stdin = ["4", "1 2", "3 4", "5 6", "7 8"]
# In Python 3, this question doesn't apply. The plain int type is unbounded.
for line in sys.stdin:
temp = line.split(" ")
if len(temp) < 2:
continue
print(int(temp[0]) + int(temp[1])) |
import requests
from bs4 import BeautifulSoup
import random
response = requests.get('https://cookpad.com/kondate/categories/6')
#print(response)
#print(response.text)
data = BeautifulSoup(response.text, 'html.parser')
recipe_class_data = data.find_all(class_="kondate_title")
recipe_name_list = []
recipe_url_list... |
import math # Подключение математического модуля
try: # Защищенный блок 1
b = float(input("Введите B="))
d = float(input("Введите D="))
x = float(input("Введите X="))
try: # Защищенный блок 2
if x >= 8:
y = (x-2)/(x**2)
else:
y= (b**2)*d+4*(x**2)
prin... |
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import numpy as np
import csv
from afinn import Afinn
import sys
DEBUG = False
infilename = sys.argv[1]
'''
VADER gives every text a score for its sentiment. These thresholds are determined by a grid-search. They are tuned on the Semeval 2017 task ... |
#coding:utf8
'''
'''
import os,sys
import urllib,urllib2
from bs4 import BeautifulSoup
from persistent_qutu import insert,dbconn,find_ele
def down_image(src, imgid):
"把图片保存到磁盘空间"
global img_dir
try:
#src = 'http://i1.taoqutu.com/2014/07/06110832568.jpg'
print '-1-',
... |
import unittest
from hello_source import hello
class MyTestCase(unittest.TestCase):
def test_something(self):
self.assertEqual("Hello, CIS 189!", hello.hello_message())
if __name__ == '__main__':
unittest.main()
|
import random
import operator
geen_pool = "abcçdefgğhıijklmnoöpqrsştuüvwxyzABCÇDEFGĞHIİJKLMNOÖPQRSŞTUVWXYZ 1234567890 ,.-;:_!#%&/()=?@${[]}'"
goal = "Çağıl İlhan Sözer"
global goal_length
goal_length = len(goal)
population = []
mutation = False
first_population = []
global say
say = 0
class Individual : #CREATING C... |
jogo=int(input(" "))
v=3
e=2
d=1
x=-1
cont=0
acum=0
while(jogo!=x):
cont=v+e+d
acum=(cont+jogo)/100
cont=cont+1
print(acum)
|
#Implement functionality of find using find.py?(find.py /root/dirname “txt”)(use sys.argv)
#!/usr/bin/python
import os
import sys
import fnmatch
def find_file(path,my_file):
result = []
for roots,dirnames,filenames in os.walk(path):
for file in filenames:
if file.endswith(my_file):
... |
# coding=utf-8
from Deck import Deck
from Player import PlayerDeck
def war(player1_card, player2_card, player1, player2, loot):
# הוספת הקלפים שהוצאנו כבר אל השלל
loot.add_card(player1_card)
loot.add_card(player2_card)
# הוספת 2 קלפים מכל שחקן אל השלל
for i in range(2):
if not player1.is_... |
#Бонус 4: программа переделывает слово или фразу так,
#чтобы после каждой согласной добавлялось 'aig'
def check_if_cons(s):
consonants = 'qwrtpsdfghjklzxcvbnm'
if s in consonants:
return True
else:
return False
def main():
s = input('Введите слово или фразу латиницей. ')
if s != ''... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.