repo_name stringlengths 13 51 | branch_name stringclasses 4
values | import_graph stringlengths 40 15.7k | directory_tree stringlengths 125 5.52k | file_1_name stringlengths 5 79 | file_1_content stringlengths 27 58.8k | file_2_name stringlengths 6 89 | file_2_content stringlengths 16 33.4k | file_3_name stringlengths 6 79 | file_3_content stringlengths 60 29.4k | file_4_name stringlengths 6 85 | file_4_content stringlengths 48 22.1k | file_5_name stringlengths 6 86 | file_5_content stringlengths 38 27.8k | file_6_name stringlengths 7 103 | file_6_content stringlengths 39 37.3k | file_7_name stringlengths 7 99 ⌀ | file_7_content stringlengths 66 41.3k ⌀ | file_8_name stringlengths 8 98 ⌀ | file_8_content stringlengths 117 51.9k ⌀ | file_9_name stringlengths 8 96 ⌀ | file_9_content stringlengths 75 27.4k ⌀ | file_10_name stringlengths 9 95 ⌀ | file_10_content stringlengths 62 18.5k ⌀ | file_11_name stringlengths 8 93 ⌀ | file_11_content stringlengths 25 14.1k ⌀ | file_12_name stringlengths 7 94 ⌀ | file_12_content stringlengths 118 13.2k ⌀ | file_13_name stringlengths 8 98 ⌀ | file_13_content stringlengths 35 29.6k ⌀ | file_14_name stringlengths 9 88 ⌀ | file_14_content stringlengths 37 16.6k ⌀ | file_15_name stringlengths 10 100 ⌀ | file_15_content stringlengths 90 31.5k ⌀ | file_16_name stringlengths 9 99 ⌀ | file_16_content stringlengths 384 20.1k ⌀ | file_17_name stringlengths 14 90 ⌀ | file_17_content stringlengths 202 14.2k ⌀ | file_18_name stringlengths 9 97 ⌀ | file_18_content stringlengths 107 34.6k ⌀ | file_19_name stringlengths 9 97 ⌀ | file_19_content stringlengths 146 26.4k ⌀ | file_20_name stringlengths 10 100 ⌀ | file_20_content stringlengths 474 21.4k ⌀ | file_21_name stringclasses 19
values | file_21_content stringclasses 19
values | file_22_name stringclasses 16
values | file_22_content stringclasses 16
values | file_23_name stringclasses 14
values | file_23_content stringclasses 14
values | file_24_name stringclasses 10
values | file_24_content stringclasses 10
values | file_25_name stringclasses 9
values | file_25_content stringclasses 9
values | file_26_name stringclasses 9
values | file_26_content stringclasses 9
values | file_27_name stringclasses 7
values | file_27_content stringclasses 7
values | file_28_name stringclasses 7
values | file_28_content stringclasses 7
values | file_29_name stringclasses 7
values | file_29_content stringclasses 7
values | file_30_name stringclasses 6
values | file_30_content stringclasses 6
values | file_31_name stringclasses 6
values | file_31_content stringclasses 6
values | file_32_name stringclasses 6
values | file_32_content stringclasses 6
values | file_33_name stringclasses 6
values | file_33_content stringclasses 6
values | file_34_name stringclasses 5
values | file_34_content stringclasses 5
values | file_35_name stringclasses 5
values | file_35_content stringclasses 5
values | file_36_name stringclasses 4
values | file_36_content stringclasses 4
values | file_37_name stringclasses 4
values | file_37_content stringclasses 4
values | file_38_name stringclasses 4
values | file_38_content stringclasses 4
values | file_39_name stringclasses 4
values | file_39_content stringclasses 4
values | file_40_name stringclasses 4
values | file_40_content stringclasses 4
values | file_41_name stringclasses 4
values | file_41_content stringclasses 4
values | file_42_name stringclasses 4
values | file_42_content stringclasses 4
values | file_43_name stringclasses 4
values | file_43_content stringclasses 4
values | file_44_name stringclasses 4
values | file_44_content stringclasses 4
values | file_45_name stringclasses 4
values | file_45_content stringclasses 4
values | file_46_name stringclasses 4
values | file_46_content stringclasses 4
values | file_47_name stringclasses 4
values | file_47_content stringclasses 4
values | file_48_name stringclasses 4
values | file_48_content stringclasses 4
values | file_49_name stringclasses 4
values | file_49_content stringclasses 4
values | file_50_name stringclasses 3
values | file_50_content stringclasses 3
values | file_51_name stringclasses 3
values | file_51_content stringclasses 3
values | file_52_name stringclasses 3
values | file_52_content stringclasses 3
values | file_53_name stringclasses 3
values | file_53_content stringclasses 3
values | file_54_name stringclasses 3
values | file_54_content stringclasses 3
values | file_55_name stringclasses 3
values | file_55_content stringclasses 3
values | file_56_name stringclasses 3
values | file_56_content stringclasses 3
values | file_57_name stringclasses 3
values | file_57_content stringclasses 3
values | file_58_name stringclasses 1
value | file_58_content stringclasses 1
value | file_59_name stringclasses 1
value | file_59_content stringclasses 1
value | file_60_name stringclasses 1
value | file_60_content stringclasses 1
value | file_61_name stringclasses 1
value | file_61_content stringclasses 1
value | file_62_name stringclasses 1
value | file_62_content stringclasses 1
value | file_63_name stringclasses 1
value | file_63_content stringclasses 1
value | file_64_name stringclasses 1
value | file_64_content stringclasses 1
value | file_65_name stringclasses 1
value | file_65_content stringclasses 1
value | file_66_name stringclasses 1
value | file_66_content stringclasses 1
value | file_67_name stringclasses 1
value | file_67_content stringclasses 1
value | file_68_name stringclasses 1
value | file_68_content stringclasses 1
value | file_69_name stringclasses 1
value | file_69_content stringclasses 1
value | file_70_name stringclasses 1
value | file_70_content stringclasses 1
value | file_71_name stringclasses 1
value | file_71_content stringclasses 1
value | file_72_name stringclasses 1
value | file_72_content stringclasses 1
value | file_73_name stringclasses 1
value | file_73_content stringclasses 1
value | file_74_name stringclasses 1
value | file_74_content stringclasses 1
value | file_75_name stringclasses 1
value | file_75_content stringclasses 1
value | file_76_name stringclasses 1
value | file_76_content stringclasses 1
value | file_77_name stringclasses 1
value | file_77_content stringclasses 1
value | file_78_name stringclasses 1
value | file_78_content stringclasses 1
value | file_79_name stringclasses 1
value | file_79_content stringclasses 1
value | file_80_name stringclasses 1
value | file_80_content stringclasses 1
value | file_81_name stringclasses 1
value | file_81_content stringclasses 1
value | file_82_name stringclasses 1
value | file_82_content stringclasses 1
value | file_83_name stringclasses 1
value | file_83_content stringclasses 1
value | file_84_name stringclasses 1
value | file_84_content stringclasses 1
value | file_85_name stringclasses 1
value | file_85_content stringclasses 1
value | file_86_name stringclasses 1
value | file_86_content stringclasses 1
value | file_87_name stringclasses 1
value | file_87_content stringclasses 1
value | file_88_name stringclasses 1
value | file_88_content stringclasses 1
value | file_89_name stringclasses 1
value | file_89_content stringclasses 1
value | file_90_name stringclasses 1
value | file_90_content stringclasses 1
value | file_91_name stringclasses 1
value | file_91_content stringclasses 1
value | file_92_name stringclasses 1
value | file_92_content stringclasses 1
value | file_93_name stringclasses 1
value | file_93_content stringclasses 1
value | file_94_name stringclasses 1
value | file_94_content stringclasses 1
value | file_95_name stringclasses 1
value | file_95_content stringclasses 1
value | file_96_name stringclasses 1
value | file_96_content stringclasses 1
value | file_97_name stringclasses 1
value | file_97_content stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
shuishen112/pairwise-rnn | refs/heads/master | {"/run.py": ["/data_helper.py", "/config.py"], "/test.py": ["/data_helper.py", "/config.py"], "/models/__init__.py": ["/models/QA_CNN_pairwise.py"]} | └──
├── config.py
├── data_helper.py
├── main.py
├── models
│ ├── QA_CNN_pairwise.py
│ ├── __init__.py
│ └── my
│ └── nn.py
├── run.py
└── test.py | /config.py | class Singleton(object):
__instance=None
def __init__(self):
pass
def getInstance(self):
if Singleton.__instance is None:
# Singleton.__instance=object.__new__(cls,*args,**kwd)
Singleton.__instance=self.get_test_flag()
print("build FLAGS over")
ret... | /data_helper.py | #-*- coding:utf-8 -*-
import os
import numpy as np
import tensorflow as tf
import string
from collections import Counter
import pandas as pd
from tqdm import tqdm
import random
from functools import wraps
import time
import pickle
def log_time_delta(func):
@wraps(func)
def _deco(*args, **kwargs):
star... | /main.py |
import data_helper
import time
import datetime
import os
import tensorflow as tf
import numpy as np
import evaluation
now = int(time.time())
timeArray = time.localtime(now)
timeStamp = time.strftime("%Y%m%d%H%M%S", timeArray)
timeDay = time.strftime("%Y%m%d", timeArray)
print (timeStamp)
def main(args):
ar... | /models/QA_CNN_pairwise.py | #coding:utf-8
import tensorflow as tf
import numpy as np
from tensorflow.contrib import rnn
import models.blocks as blocks
# model_type :apn or qacnn
class QA_CNN_extend(object):
# def __init__(self,max_input_left,max_input_right,batch_size,vocab_size,embedding_size,filter_sizes,num_filters,hidden_size,
# dro... | /models/__init__.py | from .QA_CNN_pairwise import QA_CNN_extend as CNN
from .QA_RNN_pairwise import QA_RNN_extend as RNN
from .QA_CNN_quantum_pairwise import QA_CNN_extend as QCNN
def setup(opt):
if opt["model_name"]=="cnn":
model=CNN(opt)
elif opt["model_name"]=="rnn":
model=RNN(opt)
elif opt['model_name']=='qcnn':
model=QCNN(opt... | /models/my/nn.py | from my.general import flatten, reconstruct, add_wd, exp_mask
import numpy as np
import tensorflow as tf
_BIAS_VARIABLE_NAME = "bias"
_WEIGHTS_VARIABLE_NAME = "kernel"
def linear(args, output_size, bias, bias_start=0.0, scope=None, squeeze=False, wd=0.0, input_keep_prob=1.0,
is_train=None):#, name_w='',... | /run.py | from tensorflow import flags
import tensorflow as tf
from config import Singleton
import data_helper
import datetime,os
import models
import numpy as np
import evaluation
import sys
import logging
import time
now = int(time.time())
timeArray = time.localtime(now)
timeStamp = time.strftime("%Y%m%d%H%M%S", timeArray)... | /test.py | # -*- coding: utf-8 -*-
from tensorflow import flags
import tensorflow as tf
from config import Singleton
import data_helper
import datetime
import os
import models
import numpy as np
import evaluation
from data_helper import log_time_delta,getLogger
logger=getLogger()
args = Singleton().get_rnn_flag()
#args... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Sssssbo/SDCNet | refs/heads/master | {"/SDCNet.py": ["/model.py", "/datasets.py", "/misc.py"], "/infer_SDCNet.py": ["/model.py", "/datasets.py", "/misc.py"], "/create_free.py": ["/datasets.py", "/misc.py"], "/resnet/__init__.py": ["/resnet/make_model.py"], "/model/make_model.py": ["/model/backbones/resnet.py"]} | └──
├── SDCNet.py
├── count_dataset.py
├── create_free.py
├── datasets.py
├── infer_SDCNet.py
├── misc.py
├── model
│ ├── backbones
│ │ └── resnet.py
│ └── make_model.py
├── model.py
├── resnet
│ ├── __init__.py
│ ├── config.py
│ └── make_model.... | /SDCNet.py | import datetime
import os
import time
import torch
from torch import nn
from torch import optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import transforms
import pandas as pd
import numpy as np
import joint_transforms
from config import msra10k_path, MTDD_train_path... | /count_dataset.py | import numpy as np
import os
import torch
from PIL import Image
from torch.autograd import Variable
from torchvision import transforms
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
import pandas as pd
from tqdm import tqdm
path_list = ['msra10k', 'ECSSD', 'DUT-OMROM', 'DUTS-TR', 'DUTS-TE', '... | /create_free.py | import numpy as np
import os
import torch
from PIL import Image
from torch.autograd import Variable
from torchvision import transforms
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
import pandas as pd
from tqdm import tqdm
import cv2
import numpy as np
from config import ecssd_path, hkuis_pa... | /datasets.py | import os
import os.path
import torch.utils.data as data
from PIL import Image
class ImageFolder_joint(data.Dataset):
# image and gt should be in the same folder and have same filename except extended name (jpg and png respectively)
def __init__(self, label_list, joint_transform=None, transform=None, target_... | /infer_SDCNet.py | import numpy as np
import os
import torch
import torch.nn.functional as F
from PIL import Image
from torch.autograd import Variable
from torchvision import transforms
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
import pandas as pd
from tqdm import tqdm
from misc import check_mkdir, AvgMete... | /misc.py | import numpy as np
import os
import pylab as pl
#import pydensecrf.densecrf as dcrf
class AvgMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
... | /model.py | import torch
import torch.nn.functional as F
from torch import nn
from resnext import ResNeXt101
class R3Net(nn.Module):
def __init__(self):
super(R3Net, self).__init__()
res50 = ResNeXt101()
self.layer0 = res50.layer0
self.layer1 = res50.layer1
self.layer2 = res50.layer2
... | /model/backbones/resnet.py | import math
import torch
from torch import nn
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(s... | /model/make_model.py | import torch
import torch.nn as nn
from .backbones.resnet import ResNet, Comb_ResNet, Pure_ResNet, Jointin_ResNet, Jointout_ResNet, BasicBlock, Bottleneck, GDN_Bottleneck, IN_Bottleneck, IN2_Bottleneck, SNR_Bottleneck, SNR2_Bottleneck, SNR3_Bottleneck
from loss.arcface import ArcFace
from .backbones.resnet_ibn_a import... | /resnet/__init__.py | from .make_model import ResNet50, ResNet50_BIN, ResNet50_LowIN | /resnet/config.py | resnet50_path = './resnet/resnet50-19c8e357.pth'
| /resnet/make_model.py | from .resnet import ResNet, BasicBlock, Bottleneck
import torch
from torch import nn
from .config import resnet50_path
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://downlo... | /resnext/__init__.py | from .resnext101 import ResNeXt101
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
riadghorra/whiteboard-oop-project | refs/heads/master | {"/src/tools.py": ["/src/figures.py"], "/src/white_board.py": ["/src/figures.py", "/src/tools.py"], "/src/client.py": ["/src/white_board.py"], "/src/main.py": ["/src/white_board.py"]} | └──
└── src
├── client.py
├── figures.py
├── main.py
├── serveur.py
├── tools.py
└── white_board.py | /src/client.py | import socket
import json
import sys
import math
from white_board import WhiteBoard, binary_to_dict
'''
Ouverture de la configuration initiale stockée dans config.json qui contient le mode d'écriture, la couleur et
la taille d'écriture.
Ces Paramètres sont ensuite à modifier par l'utisateur dans l'interface pygame
'... | /src/figures.py | """
Module contenant toutes les figures et opérations de base
"""
import pygame
import pygame.draw
from datetime import datetime
def distance(v1, v2):
"""
Calcule la distance euclidienne entre deux vecteurs
"""
try:
return ((v1[0] - v2[0]) ** 2 + (v1[1] - v2[1]) ** 2) ** 0.5
except TypeEr... | /src/main.py | from white_board import WhiteBoard
import json
'''
This file is used to run locally or to debug
'''
with open('config.json') as json_file:
start_config = json.load(json_file)
def main():
board = WhiteBoard("client", start_config)
board.start_local()
if __name__ == '__main__':
main()
| /src/serveur.py | import socket
import sys
import time
from threading import Thread
import json
'''
Les deux fonctions fonctions suivantes permettent de convertir les dictionnaires en binaire et réciproquement.
L'appel de ces dux fonctions permet d'échanger des dictionnaires par socket
'''
def dict_to_binary(dico):
try:
s... | /src/tools.py | """
Module contenant les differents outils de gestion du tableau
"""
import pygame
import pygame.draw
from datetime import datetime
from figures import Point, Line, TextBox, Rectangle, Circle
import time
# =============================================================================
# classes de gestion des changemen... | /src/white_board.py | import pygame
import pygame.draw
import json
import sys
from functools import reduce
import operator
from figures import TextBox, draw_line, draw_point, draw_textbox, draw_rect, draw_circle
from tools import Mode, ColorBox, Auth, Save, FontSizeBox, HandlePoint, HandleLine, HandleText, HandleRect, HandleCircle
import co... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
pyfaddist/yafcorse | refs/heads/main | {"/tests/conftest.py": ["/src/yafcorse/__init__.py"], "/tests/test_ceate_extensions.py": ["/src/yafcorse/__init__.py"], "/tests/test_origins_function.py": ["/src/yafcorse/__init__.py"]} | └──
├── src
│ └── yafcorse
│ └── __init__.py
└── tests
├── conftest.py
├── test_ceate_extensions.py
├── test_default_configuration.py
├── test_origins_function.py
├── test_preflight_request.py
└── test_simple_request.py | /src/yafcorse/__init__.py | import re
from typing import Callable, Iterable
from flask import Flask, Response, request
# Yet Another Flask CORS Extension
# --------------------------------
# Based on https://developer.mozilla.org/de/docs/Web/HTTP/CORS
# DEFAULT_CONFIGURATION = {
# 'origins': '*',
# 'allowed_methods': ['GET', 'HEAD', 'PO... | /tests/conftest.py | import pytest
from flask import Flask
from yafcorse import Yafcorse
@pytest.fixture()
def app():
app = Flask(__name__)
cors = Yafcorse({
'origins': '*',
'allowed_methods': ['GET', 'POST', 'PUT'],
'allowed_headers': ['Content-Type', 'X-Test-Header'],
'allow_credentials': True,... | /tests/test_ceate_extensions.py | from flask.app import Flask
from yafcorse import Yafcorse
def test_extension(app: Flask):
assert app.extensions.get('yafcorse') is not None
assert isinstance(app.extensions.get('yafcorse'), Yafcorse)
| /tests/test_default_configuration.py | # def test_no_cors_enabled():
# assert False | /tests/test_origins_function.py | import pytest
from flask import Flask, Response
from flask.testing import FlaskClient
from yafcorse import Yafcorse
@pytest.fixture()
def local_app():
app = Flask(__name__)
cors = Yafcorse({
'allowed_methods': ['GET', 'POST', 'PUT'],
'allowed_headers': ['Content-Type', 'X-Test-Header'],
... | /tests/test_preflight_request.py | from flask import Response
from flask.testing import FlaskClient
# def test_with_origin(client: FlaskClient):
# response: Response = client.options('/some-request', headers={
# 'Access-Control-Request-Method': 'POST',
# 'Access-Control-Request-Headers': 'Content-Type, X-Custom',
# ... | /tests/test_simple_request.py | from flask import Flask, Response
from flask.testing import FlaskClient
def test_simple_request(client: FlaskClient):
response: Response = client.get('/some-request', headers={
'Origin': 'https://test.org'
})
assert response.status_code == 404
assert 'Access-Control-Allow-Origin'.lower... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
ericfourrier/auto-clean | refs/heads/develop | {"/test.py": ["/autoc/utils/helpers.py", "/autoc/outliersdetection.py", "/autoc/explorer.py", "/autoc/naimputer.py", "/autoc/utils/getdata.py"], "/autoc/explorer.py": ["/autoc/utils/helpers.py", "/autoc/exceptions.py"], "/autoc/naimputer.py": ["/autoc/utils/helpers.py", "/autoc/utils/corrplot.py", "/autoc/explorer.py"]... | └──
├── autoc
│ ├── __init__.py
│ ├── exceptions.py
│ ├── explorer.py
│ ├── naimputer.py
│ ├── outliersdetection.py
│ ├── preprocess.py
│ └── utils
│ ├── corrplot.py
│ ├── getdata.py
│ └── helpers.py
├── setup.py
└── test.py | /autoc/__init__.py | __all__ = ["explorer", "naimputer"]
from .explorer import DataExploration
from .naimputer import NaImputer
from .preprocess import PreProcessor
from .utils.getdata import get_dataset
# from .preprocess import PreProcessor
| /autoc/exceptions.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: efourrier
Purpose : File with all custom exceptions
"""
class NotNumericColumn(Exception):
""" The column should be numeric """
pass
class NumericError(Exception):
""" The column should not be numeric """
pass
# class NotFactor
| /autoc/explorer.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: efourrier
Purpose : This is a framework for Modeling with pandas, numpy and skicit-learn.
The Goal of this module is to rely on a dataframe structure for modelling g
"""
#########################################################
# Import modules and global h... | /autoc/naimputer.py | from autoc.explorer import DataExploration, pd
from autoc.utils.helpers import cserie
import seaborn as sns
import matplotlib.pyplot as plt
#from autoc.utils.helpers import cached_property
from autoc.utils.corrplot import plot_corrmatrix
import numpy as np
from scipy.stats import ttest_ind
from scipy.stats.mstats impor... | /autoc/outliersdetection.py | """
@author: efourrier
Purpose : This is a simple experimental class to detect outliers. This class
can be used to detect missing values encoded as outlier (-999, -1, ...)
"""
from autoc.explorer import DataExploration, pd
import numpy as np
#from autoc.utils.helpers import cserie
from exceptions import NotNumericC... | /autoc/preprocess.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: efourrier
Purpose : The purpose of this class is too automaticely transfrom a DataFrame
into a numpy ndarray in order to use an aglorithm
"""
#########################################################
# Import modules and global helpers
#####################... | /autoc/utils/corrplot.py | import seaborn as sns
import matplotlib.pyplot as plt
def plot_corrmatrix(df, square=True, linewidths=0.1, annot=True,
size=None, figsize=(12, 9), *args, **kwargs):
"""
Plot correlation matrix of the dataset
see doc at https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.he... | /autoc/utils/getdata.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: efourrier
Purpose : Get data from https://github.com/ericfourrier/autoc-datasets
"""
import pandas as pd
def get_dataset(name, *args, **kwargs):
"""Get a dataset from the online repo
https://github.com/ericfourrier/autoc-datasets (requires internet... | /autoc/utils/helpers.py | # -*- coding: utf-8 -*-
"""
@author: efourrier
Purpose : Create toolbox functions to use for the different pieces of code ot the package
"""
from numpy.random import normal
from numpy.random import choice
import time
import pandas as pd
import numpy as np
import functools
def print_section(section_name, width=120):... | /setup.py | from setuptools import setup, find_packages
def readme():
with open('README.md') as f:
return f.read()
setup(name='autoc',
version="0.1",
description='autoc is a package for data cleaning exploration and modelling in pandas',
long_description=readme(),
author=['Eric Fourrier'],
... | /test.py | # -*- coding: utf-8 -*-
"""
@author: efourrier
Purpose : Automated test suites with unittest
run "python -m unittest -v test" in the module directory to run the tests
The clock decorator in utils will measure the run time of the test
"""
#########################################################
# Import Packages an... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
thinkAmi-sandbox/AWS_CDK-sample | refs/heads/master | {"/step_functions/app.py": ["/step_functions/step_functions/step_functions_stack.py"]} | └──
└── step_functions
├── app.py
└── step_functions
├── lambda_function
│ ├── error
│ │ └── lambda_function.py
│ ├── first
│ │ └── lambda_function.py
│ ├── second
│ │ └── lambda_function.py
... | /step_functions/app.py | #!/usr/bin/env python3
from aws_cdk import core
from step_functions.step_functions_stack import StepFunctionsStack
app = core.App()
# CFnのStack名を第2引数で渡す
StepFunctionsStack(app, 'step-functions')
app.synth()
| /step_functions/step_functions/lambda_function/error/lambda_function.py | import json
def lambda_handler(event, context):
# {
# "resource": "arn:aws:lambda:region:id:function:sfn_error_lambda",
# "input": {
# "Error": "Exception",
# "Cause": "{\"errorMessage\": \"\\u5076\\u6570\\u3067\\u3059\",
# \"errorType\": \"Exception\",
# ... | /step_functions/step_functions/lambda_function/first/lambda_function.py | import os
import boto3
from numpy.random import rand
def lambda_handler(event, context):
body = f'{event["message"]} \n value: {rand()}'
client = boto3.client('s3')
client.put_object(
Bucket=os.environ['BUCKET_NAME'],
Key='sfn_first.txt',
Body=body,
)
return {
'bod... | /step_functions/step_functions/lambda_function/second/lambda_function.py | def lambda_handler(event, context):
if event['parallel_no'] % 2 == 0:
raise Exception('偶数です')
return {
'message': event['message'],
'const_value': event['const_value']
}
| /step_functions/step_functions/lambda_function/third/lambda_function.py | def lambda_handler(event, context):
if event['parallel_no'] == 1:
raise Exception('強制的にエラーとします')
return 'only 3rd message.'
| /step_functions/step_functions/settings.example.py | AWS_SCIPY_ARN = 'arn:aws:lambda:region:account_id:layer:AWSLambda-Python37-SciPy1x:2' | /step_functions/step_functions/step_functions_stack.py | import pathlib
from aws_cdk import core
from aws_cdk.aws_iam import PolicyStatement, Effect, ManagedPolicy, ServicePrincipal, Role
from aws_cdk.aws_lambda import AssetCode, LayerVersion, Function, Runtime
from aws_cdk.aws_s3 import Bucket
from aws_cdk.aws_stepfunctions import Task, StateMachine, Parallel
from aws_cdk.... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
greenmato/slackline-spots | refs/heads/master | {"/spots-api/map/urls.py": ["/spots-api/map/api.py", "/spots-api/map/views.py"], "/spots-api/map/api.py": ["/spots-api/map/forms.py", "/spots-api/map/models.py"], "/spots-api/map/forms.py": ["/spots-api/map/models.py"]} | └──
└── spots-api
└── map
├── api.py
├── forms.py
├── migrations
│ ├── 0001_initial.py
│ ├── 0005_auto_20180305_2131.py
│ ├── 0007_auto_20180305_2139.py
│ ├── 0008_auto_20180305_2211.py
│ ├── 0009_auto... | /spots-api/map/api.py | from abc import ABC, ABCMeta, abstractmethod
from django.forms.models import model_to_dict
from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decor... | /spots-api/map/forms.py | from django import forms
from django.forms import ModelForm, Textarea
from map.models import Spot, Rating, Vote
class SpotForm(ModelForm):
class Meta:
model = Spot
fields = ['name', 'description', 'latitude', 'longitude']
widgets = {
'latitude': forms.HiddenInput(),
... | /spots-api/map/migrations/0001_initial.py | # Generated by Django 2.0 on 2017-12-17 18:04
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Spot',
fields=[
('id', models.AutoField(auto_... | /spots-api/map/migrations/0005_auto_20180305_2131.py | # Generated by Django 2.0.1 on 2018-03-05 21:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('map', '0004_ratingtype'),
]
operations = [
migrations.AlterField(
model_name='spot',
name='latitude',
fi... | /spots-api/map/migrations/0007_auto_20180305_2139.py | # Generated by Django 2.0.1 on 2018-03-05 21:39
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('map', '0006_rating'),
]
operations = [
migrations.RenameField(
model_name='rating',
old_name='rating_type_id',
n... | /spots-api/map/migrations/0008_auto_20180305_2211.py | # Generated by Django 2.0.1 on 2018-03-05 22:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('map', '0007_auto_20180305_2139'),
]
operations = [
migrations.RenameField(
model_name='rating',
old_name='rating_typ... | /spots-api/map/migrations/0009_auto_20180305_2215.py | # Generated by Django 2.0.1 on 2018-03-05 22:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('map', '0008_auto_20180305_2211'),
]
operations = [
migrations.CreateModel(
name='Vote',
... | /spots-api/map/migrations/0010_auto_20180306_2119.py | # Generated by Django 2.0.1 on 2018-03-06 21:19
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('map', '0009_auto_20180305_2215'),
]
operations = [
migrations.RenameField(
model_name='rating',
old_name='rating',
... | /spots-api/map/models.py | from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
class Spot(models.Model):
name = models.CharField(max_length=50)
description = models.CharField(max_length=500)
latitude = models.DecimalField(max_digits=10, decimal_places=7)
longitude = models.Decim... | /spots-api/map/urls.py | from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from map.views import MapView
from map.api import SpotsApi, SpotApi, RatingsApi, VotesApi
app_name = 'map'
urlpatterns = [
path('', MapView.as_view(), name='index'),
path('spots/', ... | /spots-api/map/views.py | from django.shortcuts import render
from django.views import View
class MapView(View):
def get(self, request):
return render(request, 'map/index.html')
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
katrii/ohsiha | refs/heads/master | {"/ohjelma/views.py": ["/ohjelma/models.py"]} | └──
└── ohjelma
├── apps.py
├── migrations
│ ├── 0002_song.py
│ ├── 0003_song_release_year.py
│ ├── 0004_track.py
│ ├── 0005_auto_20200329_1313.py
│ ├── 0006_auto_20200329_1329.py
│ ├── 0007_track_track_id.py
│ └── 0009_auto_2020... | /ohjelma/apps.py | from django.apps import AppConfig
class OhjelmaConfig(AppConfig):
name = 'ohjelma'
| /ohjelma/migrations/0002_song.py | # Generated by Django 3.0.2 on 2020-03-13 17:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ohjelma', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Song',
fields=[
('id', mod... | /ohjelma/migrations/0003_song_release_year.py | # Generated by Django 3.0.2 on 2020-03-15 16:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ohjelma', '0002_song'),
]
operations = [
migrations.AddField(
model_name='song',
name='release_year',
fi... | /ohjelma/migrations/0004_track.py | # Generated by Django 3.0.2 on 2020-03-28 23:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ohjelma', '0003_song_release_year'),
]
operations = [
migrations.CreateModel(
name='Track',
fields=[
... | /ohjelma/migrations/0005_auto_20200329_1313.py | # Generated by Django 3.0.2 on 2020-03-29 10:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ohjelma', '0004_track'),
]
operations = [
migrations.AlterField(
model_name='track',
name='track_duration',
... | /ohjelma/migrations/0006_auto_20200329_1329.py | # Generated by Django 3.0.2 on 2020-03-29 10:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ohjelma', '0005_auto_20200329_1313'),
]
operations = [
migrations.AlterField(
model_name='track',
name='track_durati... | /ohjelma/migrations/0007_track_track_id.py | # Generated by Django 3.0.2 on 2020-04-11 18:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ohjelma', '0006_auto_20200329_1329'),
]
operations = [
migrations.AddField(
model_name='track',
name='track_id',
... | /ohjelma/migrations/0009_auto_20200411_2211.py | # Generated by Django 3.0.2 on 2020-04-11 19:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ohjelma', '0008_track_track_danceability'),
]
operations = [
migrations.AddField(
model_name='track',
name='track_ac... | /ohjelma/models.py | from django.db import models
from django.urls import reverse
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('Date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = mode... | /ohjelma/urls.py | from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name = 'home'),
path('songs/', views.SongList.as_view(), name = 'song_list'),
path('view/<int:pk>', views.SongView.as_view(), name = 'song_view'),
path('new', views.SongCreate.as_view(), name = 'song_new'),
path... | /ohjelma/views.py | from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from ohjelma.models import Song
from ohjelma.models import Track
import json
impo... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
lukasld/Flask-Video-Editor | refs/heads/main | {"/app/api/VideoProcessing.py": ["/app/api/decorators.py", "/app/api/errors.py"], "/app/api/videoApi.py": ["/app/api/VideoProcessing.py", "/app/api/errors.py"], "/app/api/decorators.py": ["/app/api/errors.py"]} | └──
├── app
│ ├── __init__.py
│ ├── api
│ │ ├── VideoProcessing.py
│ │ ├── __init__.py
│ │ ├── decorators.py
│ │ ├── errors.py
│ │ ├── help.py
│ │ ├── utils.py
│ │ └── videoApi.py
│ ├── docs
│ │ └── __init__.py
│ └── main
│... | /app/__init__.py | from flask import Flask
from config import config
from flask_caching import Cache
from flask_swagger_ui import get_swaggerui_blueprint
VIDEO_EXTENSION=None
VIDEO_WIDTH=None
VIDEO_HEIGHT=None
VIDEO_UPLOAD_PATH=None
FRAMES_UPLOAD_PATH=None
IMG_EXTENSION=None
HELP_MSG_PATH=None
CACHE=None
def create_app(config_nam... | /app/api/VideoProcessing.py | from werkzeug.utils import secure_filename
from functools import partial
import subprocess as sp
import time
import skvideo.io
import numpy as np
import threading
import ffmpeg
import shlex
import cv2
import re
from PIL import Image
from werkzeug.datastructures import FileStorage as FStorage
from .. import VIDEO_EXT... | /app/api/__init__.py | from flask import Blueprint
api = Blueprint('videoApi', __name__)
from . import videoApi, errors, help
| /app/api/decorators.py | from flask import request, jsonify
from functools import wraps
from .errors import InvalidAPIUsage, InvalidFilterParams, IncorrectVideoFormat
"""
Almost like an Architect - makes decorations
"""
def decorator_maker(func):
def param_decorator(fn=None, does_return=None, req_c_type=None, req_type=None, arg=Non... | /app/api/errors.py | import sys
import traceback
from flask import jsonify, request
from . import api
class InvalidAPIUsage(Exception):
status_code = 400
def __init__(self, message='', status_code=None):
super().__init__()
self.message = message
self.path = request.path
if status_code is None:
... | /app/api/help.py | from flask import jsonify, request, send_from_directory
from . decorators import parameter_check
from . import api
from ..import HELP_MSG_PATH
import json
AV_EP = ["upload", "preview", "download", "stats", "filters"]
AV_FILTERS = ["canny", "greyscale", "laplacian", "gauss"]
@api.route('/help/', methods=['GET'])
@api.... | /app/api/utils.py | import cv2
import math
import string
import random
import numpy as np
import skvideo.io
from PIL import Image
from .. import VIDEO_EXTENSION, VIDEO_UPLOAD_PATH, \
FRAMES_UPLOAD_PATH, IMG_EXTENSION, CACHE
FPS = 23.98
SK_CODEC = 'libx264'
def create_vid_path(name):
return f'{VIDEO_UPLOAD_PATH}/{na... | /app/api/videoApi.py | import os
from flask import Flask, request, redirect, \
url_for, session, jsonify, send_from_directory, make_response, send_file
from . import api
from . import utils
from .. import VIDEO_UPLOAD_PATH, FRAMES_UPLOAD_PATH, IMG_EXTENSION, VIDEO_EXTENSION, CACHE
from . VideoProcessing import Frame, Vide... | /app/docs/__init__.py | from flask_swagger_ui import get_swaggerui_blueprint
swagger_ui = get_swaggerui_blueprint(
'/docs',
'/static/swagger.json',
config={
"app_name": "videoApi"
}
)
| /app/main/errors.py | from flask import redirect, url_for, jsonify
from . import main
@main.app_errorhandler(404)
def page_not_found(e):
return jsonify(error=str(e)), 404
@main.app_errorhandler(405)
def method_not_allowed(e):
return jsonify(error=str(e)), 405
| /config.py | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
"""
"""
SECRET_KEY = os.environ.get('SECRET_KEY')
FLASK_CONFIG = os.environ.get('FLASK_CONFIG')
VIDEO_EXTENSION = os.environ.get('VIDEO_EXTENSION')
VIDEO_WIDTH = os.environ.get('VIDEO_WIDTH')
VIDEO_HEIGHT = os.e... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
junprog/contrastive-baseline | refs/heads/main | {"/linear_eval.py": ["/models/create_linear_eval_model.py", "/utils/visualizer.py", "/datasets/cifar10.py"], "/train.py": ["/utils/contrastive_trainer.py", "/utils/simsiam_trainer.py"], "/utils/contrastive_trainer.py": ["/utils/helper.py", "/models/l2_contrastive_loss.py", "/utils/visualizer.py", "/datasets/spatial.py"... | └──
├── datasets
│ ├── cifar10.py
│ └── spatial.py
├── exp.py
├── linear_eval.py
├── models
│ ├── cosine_contrastive_loss.py
│ ├── create_linear_eval_model.py
│ ├── l2_contrastive_loss.py
│ ├── siamese_net.py
│ └── simple_siamese_net_tmp.py
├── train.py
... | /datasets/cifar10.py | from typing import Callable, Optional
import random
from PIL import Image
import numpy as np
import torch
import torchvision
from torchvision import transforms
from torchvision.datasets import CIFAR10
np.random.seed(765)
random.seed(765)
class SupervisedPosNegCifar10(torch.utils.data.Dataset):
def __init__(self... | /datasets/spatial.py | # in : original image
# out : cropped img1 (anchor)
# cropped img2 (compete)
# target (positive img1 - img2 : 1, negative img1 - img2 : 0)
import os
from glob import glob
import random
import numpy as np
from PIL import Image
from PIL import ImageFilter
import torch
import torch.utils.data as data
impor... | /exp.py | import torch
import torchvision
from PIL import Image
from matplotlib import pyplot as plt
import random
model = torchvision.models.__dict__['vgg19']()
print(model)
img = torch.rand(1,3,256,256)
out = model.features(img)
print(out.size())
import torchvision.transforms as trans
crop = trans.RandomCrop(224)
img = tor... | /linear_eval.py | import os
import argparse
import logging
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
import torchvision.models as models
from datasets.cifar10 import get_simsiam_dataset
f... | /models/cosine_contrastive_loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
def D(p, z, version='simplified'): # negative cosine similarity
if version == 'original':
z = z.detach() # stop gradient
p = F.normalize(p, dim=1) # l2-normalize
z = F.normalize(z, dim=1) # l2-normalize
return -(... | /models/create_linear_eval_model.py | import os
from collections import OrderedDict
import torch
import torch.nn as nn
import torchvision.models as models
class LinearEvalModel(nn.Module):
def __init__(self, arch='vgg19', dim=512, num_classes=10):
super().__init__()
if arch == 'vgg19':
self.features = models.vgg19().featu... | /models/l2_contrastive_loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class L2ContrastiveLoss(nn.Module):
"""
Contrastive loss
Takes embeddings of two samples and a target label == 1 if samples are from the same class and label == 0 otherwise
Args :
output1 & output2 : [N, dim]
target : [... | /models/siamese_net.py | import torch
import torch.nn as nn
class SiameseNetwork(nn.Module):
def __init__(self, model, pretrained=False, simple_model=False):
super(SiameseNetwork, self).__init__()
self.simple_model = simple_model
if simple_model:
self.features = nn.Sequential(nn.Conv2d(3, 32, 5), nn.PRe... | /models/simple_siamese_net_tmp.py | import torch
import torch.nn as nn
class projection_MLP(nn.Module):
def __init__(self, in_dim=512, hidden_dim=512, out_dim=512): # bottleneck structure
super().__init__()
self.layers = nn.Sequential(
nn.Linear(in_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hi... | /train.py | from utils.contrastive_trainer import CoTrainer
from utils.simsiam_trainer import SimSiamTrainer
import argparse
import os
import math
import torch
args = None
def parse_args():
parser = argparse.ArgumentParser(description='Train ')
parser.add_argument('--data-dir', default='/mnt/hdd02/process-ucf',
... | /train_val_split.py | import os
from glob import glob
import numpy as np
import argparse
def parse_args():
parser = argparse.ArgumentParser(description='Test ')
parser.add_argument('--data-dir', default='/mnt/hdd02/shibuya_scramble',
help='original data directory')
args = parser.parse_args()
return ... | /utils/contrastive_trainer.py | import os
import sys
import time
import logging
import numpy as np
import torch
from torch import optim
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
import torchvision.models as models
import torchvision.datasets as datasets
from models.siamese_net import SiameseNetwork
from models.l2... | /utils/helper.py | import os
import numpy as np
import torch
def worker_init_fn(worker_id):
np.random.seed(np.random.get_state()[1][0] + worker_id)
class Save_Handle(object):
"""handle the number of """
def __init__(self, max_num):
self.save_list = []
... | /utils/simsiam_trainer.py | import os
import sys
import time
import logging
import numpy as np
import torch
from torch import optim
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
import torchvision.models as models
import torchvision.datasets as datasets
from models.simple_siamese_net import SiameseNetwork
from mo... | /utils/visualizer.py | import os
import numpy as np
from PIL import Image
import torch
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
### torch テンソル(バッチ)を受け取って、args.div_numに応じて、描画する
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
def invnorm(img, N):
img = img[N,:,:,:].to('c... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Peroxidess/Ablation-Time-Prediction-Model | refs/heads/main | {"/Regression/src/eval.py": ["/Regression/src/model/history_.py"], "/Regression/src/preprocess/plot_tabel.py": ["/Regression/src/model/history_.py"], "/Regression/src/main.py": ["/Regression/src/model/history_.py", "/Regression/src/model/training_.py", "/Regression/src/preprocess/get_dataset.py", "/Regression/src/prepr... | └──
└── Regression
└── src
├── eval.py
├── learn_rewieght
│ ├── mnist_train.py
│ └── reweight.py
├── learn_weight_main.py
├── main.py
├── model
│ ├── bulid_model.py
│ ├── evaluate.py
... | /Regression/src/eval.py | from model.history_ import plot_metric_df
import pandas as pd
import matplotlib.pyplot as plt
import os
xx = os.getcwd()
path_root = '../report/result/'
task_name = 'ablation_time_all'
metric_list = []
metric_list_dir = ['metric_ablation_time_enh_10nrun_1Fold.csv',
'metric_ablation_time_vanilla_10nrun_1Fold.csv',
'me... | /Regression/src/learn_rewieght/mnist_train.py | # Copyright (c) 2017 - 2019 Uber Technologies, Inc.
#
# Licensed under the Uber Non-Commercial License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at the root directory of this project.
#
# See the License for the specific language governing... | /Regression/src/learn_rewieght/reweight.py | # Copyright (c) 2017 - 2019 Uber Technologies, Inc.
#
# Licensed under the Uber Non-Commercial License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at the root directory of this project.
#
# See the License for the specific language governing... | /Regression/src/learn_weight_main.py | # Copyright (c) 2017 - 2019 Uber Technologies, Inc.
#
# Licensed under the Uber Non-Commercial License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at the root directory of this project.
#
# See the License for the specific language governing... | /Regression/src/main.py | import numpy as np
import pandas as pd
import six
from tqdm import tqdm
from sklearn.model_selection import KFold
import matplotlib.pyplot as plt
from preprocess.load_data import load_data_
from preprocess.get_dataset import get_dataset_, data_preprocessing, anomaly_dectection
from model.training_ import training_model... | /Regression/src/model/bulid_model.py | import tensorflow as tf
import numpy as np
import pandas as pd
from keras import backend as K
from keras import regularizers, activations
from keras.layers import Dense, Input, Add, Concatenate, Dropout, \
BatchNormalization, Activation, Multiply, Embedding, Layer, GlobalAveragePooling1D
from keras.models import Mo... | /Regression/src/model/evaluate.py | import numpy as np
import pandas as pd
from sklearn.metrics import mean_absolute_error, mean_squared_error, \
confusion_matrix, precision_score, recall_score, f1_score, r2_score, accuracy_score
from sklearn.preprocessing import MinMaxScaler
def evaluate_classification(model, train_sets, train_label, val_sets, val... | /Regression/src/model/history_.py | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import math
plt.rc('font', family='Times New Roman')
font_size = 16
def plot_metric_df(history_list, task_name, val_flag='test_'):
if 'relapse_risk' in task_name:
metric_list = ['loss', 'f1']
else:
met... | /Regression/src/model/training_.py | import copy
import pandas as pd
import numpy as np
import lightgbm as lgb
from sklearn.linear_model import RidgeClassifierCV, LogisticRegressionCV, RidgeCV, LassoCV, LinearRegression
from keras.models import load_model
from keras import backend as K
from keras.optimizers import Adam, RMSprop, SGD
from keras.callbacks i... | /Regression/src/preprocess/get_dataset.py | from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import LabelEncoder, MinMaxScaler, StandardScaler
import pandas as pd
import numpy as np
from preprocess import plot_tabel
def get_dataset_(nor, train_data, test_data, clean_ratio, test_retio, se... | /Regression/src/preprocess/load_data.py | #coding=gb18030
import numpy as np
import pandas as pd
def load_data_(datasets, task_name='', seed=2020):
if datasets == 'winequality_white':
data_path = '../DataSet/wine/{}.csv'.format(datasets)
data = pd.read_csv(data_path)
data.rename(columns={'quality': 'label'}, inplace=True)
... | /Regression/src/preprocess/plot_tabel.py | import copy
import pandas as pd
import matplotlib.pyplot as plt
from model.history_ import plot_history_df, plot_metric_df
import numpy as np
from scipy.stats import ttest_ind, levene
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
def mape(y_true, y_pred):
return np.mean(np.abs((y_t... | /Regression/src/useless/ave_logsit_baseline.py | import pandas as pd
import numpy as np
from tqdm import tqdm
import six
import tensorflow as tf
from keras import losses
from keras import backend as K
from keras import optimizers
from keras.models import Sequential
from keras.layers import Dense
from sklearn.preprocessing import LabelEncoder, MinMaxScaler
from sklear... | /Regression/src/useless/keras_att.py | import pandas as pd
import numpy as np
from tqdm import tqdm
import six
import tensorflow as tf
from keras import losses
from keras import backend as K
from keras import optimizers
from keras.models import Sequential, Model
from keras.callbacks import EarlyStopping
from keras.layers import Input, Dense, Multiply, Activ... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
shashi/phosphene | refs/heads/master | {"/src/apps/devices/cube.py": ["/src/apps/devices/device.py"], "/src/apps/psychroom.py": ["/src/apps/cube.py", "/src/apps/devices/ledwall.py", "/src/apps/devices/waterfall.py", "/src/apps/devices/discoball.py", "/src/apps/devices/cube.py"], "/src/phosphene/signal.py": ["/src/phosphene/util.py"], "/src/apps/devices/wate... | └──
└── src
├── apps
│ ├── cube.py
│ ├── devices
│ │ ├── __init__.py
│ │ ├── animations.py
│ │ ├── cube.py
│ │ ├── cubelib
│ │ │ ├── __init__.py
│ │ │ └── emulator.py
│ │ ├── device.py
│ │ ... | /src/apps/cube.py | from devices.cubelib import emulator
from devices.cubelib import mywireframe as wireframe
from devices.animations import *
pv = emulator.ProjectionViewer(640,480)
wf = wireframe.Wireframe()
def cubeProcess(cube, signal, count):
pv.createCube(wf)
start = (0, 0, 0)
point = (0,0)
#planeBounce(cube,(count... | /src/apps/devices/__init__.py | __all__ = ["discoball", "cube", "waterfall"]
| /src/apps/devices/animations.py | import numpy
import random
import time
from cubelib import mywireframe
from cubelib import emulator
# TODO:
# shiftPlane(axis, plane, delta)
# moves the plane along the axis by delta steps, if it exceeds dimensions, just clear it out, don't rotate.
# swapPlanes(axis1, plane1, axis2, plane2)
# rain should set random... | /src/apps/devices/cube.py | import serial
import numpy
import math
from device import Device
from cubelib import emulator
from cubelib import mywireframe as wireframe
from animations import *
import time
import threading
# A class for the cube
class Cube(Device):
def __init__(self, port, dimension=10, emulator=False):
Device.__init__... | /src/apps/devices/cubelib/__init__.py | __all__ = ["emulator", "mywireframe"]
| /src/apps/devices/cubelib/emulator.py | #!/bin/env python
#using the wireframe module downloaded from http://www.petercollingridge.co.uk/
import mywireframe as wireframe
import pygame
from pygame import display
from pygame.draw import *
import time
import numpy
key_to_function = {
pygame.K_LEFT: (lambda x: x.translateAll('x', -10)),
pygame.K_RIGHT... | /src/apps/devices/device.py | import serial
import numpy
from threading import Thread
class Device:
def __init__(self, name, port):
self.array = []
try:
self.port = serial.Serial(port)
self.isConnected = True
print "Connected to", name
except Exception as e:
self.port = No... | /src/apps/devices/discoball.py | import device
from phosphene.signal import *
from phosphene.signalutil import *
from phosphene.graphs import *
class DiscoBall(device.Device):
def __init__(self, port):
device.Device.__init__(self, "DiscoBall", port)
def setupSignal(self, signal):
signal.discoball = lift(lambda s: numpymap(lam... | /src/apps/devices/ledwall.py | import device
from phosphene.signal import *
from phosphene.signalutil import *
from phosphene.graphs import *
class LEDWall(device.Device):
def __init__(self, port):
device.Device.__init__(self, "LEDWall", port)
def setupSignal(self, signal):
CHANNELS = 6
val = lambda s: [max(0, scip... | /src/apps/devices/waterfall.py | import device
from phosphene.signal import *
import scipy, numpy
from phosphene.graphs import barGraph
class Waterfall(device.Device):
def __init__(self, port):
device.Device.__init__(self, "Waterfall", port)
def setupSignal(self, signal):
def waterfall(s):
lights = [s.avg8[i] * 15... | /src/apps/pathsetup.py | import os, sys
dirname = os.path.dirname
here = os.path.abspath(__file__)
parentdir = dirname(dirname(here))
sys.path.append(parentdir)
| /src/apps/psychroom.py | #
# This script plays an mp3 file and communicates via serial.Serial
# with devices in the Technites psychedelic room to visualize the
# music on them.
#
# It talks to 4 devices
# WaterFall -- tubes with LEDs and flying stuff fanned to music
# DiscoBall -- 8 60 watt bulbs wrapped in colored paper
# LEDWall -- a... | /src/demo.py | import sys
import pdb
import pygame
from pygame import display
from pygame.draw import *
import scipy
import time
from phosphene import audio, util, signalutil, signal
from phosphene.graphs import barGraph, boopGraph, graphsGraphs
from threading import Thread
if len(sys.argv) < 2:
print "Usage: %s file.mp3" % sy... | /src/phosphene/__init__.py | __all__ = ["audio", "dsp", "signal", "graphs", "util"]
| /src/phosphene/audio.py | import os
from hashlib import sha1
import scipy.io.wavfile as wav
import pygame.mixer
from pygame.sndarray import make_sound
# Set mixer defaults
pygame.mixer.pre_init(44100, 16, 2, 4096)
__all__ = ["read", "makeSound"]
def digest(string):
return sha1(string).hexdigest()
def read(fname):
""" Reads an audio ... | /src/phosphene/dsp.py | import scipy
import numpy
from util import *
def fftIdx(Fs, Hz, n):
assert(Hz <= Fs / 2);
return round(Fs / n * Hz)
memFftIdx = memoize(fftIdx)
def getNotes():
return [0] \
+ [16.35 * pow(2, i/12.0) + 1 for i in range(0, 101)] \
+ [11050, 22100]
def group(n, fft, grouping=lambda i:... | /src/phosphene/graphs.py | import pdb
import scipy
import numpy
import pygame
from pygame import display
from pygame.draw import *
from pygame import Color
import math
def barGraph(data):
"""
drawing contains (x, y, width, height)
"""
def f(surface, rectangle):
x0, y0, W, H = rectangle
try:
l = l... | /src/phosphene/signal.py | import time
import numpy
from util import indexable
__all__ = [
'Signal',
'lift',
'foldp',
'perceive'
]
class lift:
""" Annotate an object as lifted """
def __init__(self, f, t_indexable=None):
self.f = f
if hasattr(f, '__call__'):
self._type = 'lambda'
e... | /src/phosphene/signalutil.py | # Functions to help you lift and fold
from .signal import *
from dsp import *
import numpy
import pdb
import math
def setup(signal, horizon=576):
# Note of awesome: this only sets up dependencies,
# things absolutely necessary are evaluated.
signal.fft = lift(lambda s: \
fft(s.A[-horizon/2:hor... | /src/phosphene/util.py | import numpy
from threading import Thread # this is for the repl
__all__ = ['memoize', 'memoizeBy', 'numpymap', 'indexable', 'reverse']
# Helper functions
def memoize(f, key=None):
mem = {}
def g(*args):
k = str(args)
if mem.has_key(k):
return mem[k]
else:
r = f(... | /src/setup.py | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "phosphene",
version = "0.0.1",
author = "Shashi Gowda",
author_email = "shashigowda91@gmail.com",
description = ("A library for music processing and visuali... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
stvncrn/stockx_api_ref | refs/heads/master | {"/sdk/python/lib/build/lib/io_stockx/models/__init__.py": ["/sdk/python/lib/io_stockx/models/customer_object_merchant.py", "/sdk/python/lib/build/lib/io_stockx/models/portfolio_id_del_request.py", "/sdk/python/lib/build/lib/io_stockx/models/portfolio_id_del_response_portfolio_item_product_shipping.py", "/sdk/python/li... | └──
└── sdk
└── python
├── lib
│ ├── build
│ │ └── lib
│ │ ├── io_stockx
│ │ │ ├── api
│ │ │ │ └── stock_x_api.py
│ │ │ └── models
│ │ │ ├── __init__.p... | /sdk/python/lib/build/lib/io_stockx/api/stock_x_api.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/build/lib/io_stockx/models/__init__.py | # coding: utf-8
# flake8: noqa
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swag... | /sdk/python/lib/build/lib/io_stockx/models/billing_object.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/build/lib/io_stockx/models/portfolio_id_del_request.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/build/lib/io_stockx/models/portfolio_id_del_response_portfolio_item.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/build/lib/io_stockx/models/portfolio_id_del_response_portfolio_item_product_shipping.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/build/lib/io_stockx/models/portfolioitems_id_get_response_portfolio_item_product.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/build/lib/io_stockx/models/product_info_attributes.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/build/lib/io_stockx/models/search_hit_searchable_traits.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/build/lib/io_stockx/models/search_results.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/build/lib/test/test_portfolio_id_del_response_portfolio_item_product_media.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/io_stockx/models/address_object.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/io_stockx/models/customer_object.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/io_stockx/models/customer_object_merchant.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/io_stockx/models/market_data_market.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/io_stockx/models/portfolio_id_del_response_portfolio_item_merchant.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/io_stockx/models/portfolio_request_portfolio_item.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/io_stockx/models/product_info_product_attributes.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/io_stockx/models/search_hit.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/lib/test/test_stock_x_api.py | # coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git... | /sdk/python/src/example_constants.py | from __future__ import print_function
import time
import io_stockx
from io_stockx.rest import ApiException
from pprint import pprint
class ExampleConstants:
AWS_API_KEY = "<API Key>"
STOCKX_USERNAME = "<StockX Username>"
STOCKX_PASSWORD = "<StockX Password>"
DEMO_PRODUCT_ID = "air-jordan-1-retro-hi... | /sdk/python/src/login.py | from __future__ import print_function
import time
import io_stockx
from example_constants import ExampleConstants
from io_stockx.rest import ApiException
from pprint import pprint
# Configure API key authorization: api_key
configuration = io_stockx.Configuration()
configuration.host = "https://gateway.stockx.com/stag... | /sdk/python/src/place_new_lowest_ask_example.py | from __future__ import print_function
import time
import io_stockx
from example_constants import ExampleConstants
from io_stockx.rest import ApiException
from pprint import pprint
# Configure API key authorization: api_key
configuration = io_stockx.Configuration()
configuration.host = "https://gateway.stockx.com/sta... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
jlamonade/splitteroni | refs/heads/master | {"/splitter/urls.py": ["/splitter/views.py"], "/splitter/admin.py": ["/splitter/models.py"], "/splitter/forms.py": ["/splitter/models.py"], "/splitter/tests.py": ["/splitter/models.py"], "/splitter/views.py": ["/splitter/models.py", "/splitter/forms.py"], "/splitter/models.py": ["/splitter/utils.py"]} | └──
├── config
│ └── settings.py
├── pages
│ └── tests.py
├── splitter
│ ├── admin.py
│ ├── apps.py
│ ├── forms.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── 0002_auto_20201007_2310.py
│ │ ├── 0003_auto_20201007_2339.py
│ │ ├── 0004_... | /config/settings.py | """
Django settings for config project.
Generated by 'django-admin startproject' using Django 3.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib imp... | /pages/tests.py | from django.test import TestCase
from django.urls import reverse, resolve
from django.contrib.auth import get_user_model
from .views import HomePageView
# Create your tests here.
class HomepageTests(TestCase):
def setUp(self):
url = reverse('home')
self.response = self.client.get(url)
sel... | /splitter/admin.py | from django.contrib import admin
from .models import Bill, Person, Item
# Register your models here.
admin.site.register(Bill)
admin.site.register(Person)
admin.site.register(Item)
| /splitter/apps.py | from django.apps import AppConfig
class SplitterConfig(AppConfig):
name = 'splitter'
| /splitter/forms.py | from django.forms import forms, ModelForm
from django.utils.translation import gettext_lazy as _
from .models import Bill
class BillCreateForm(ModelForm):
class Meta:
model = Bill
fields = ('title', 'tax_percent', 'tip_percent',)
labels = {
'title': _('Name'),
}
... | /splitter/migrations/0001_initial.py | # Generated by Django 3.1.2 on 2020-10-08 02:57
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | /splitter/migrations/0002_auto_20201007_2310.py | # Generated by Django 3.1.2 on 2020-10-08 03:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('splitter', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='item',
name='title',
fie... | /splitter/migrations/0003_auto_20201007_2339.py | # Generated by Django 3.1.2 on 2020-10-08 03:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('splitter', '0002_auto_20201007_2310'),
]
operations = [
migrations.AlterField(
model_name='bill',
name='tax',
... | /splitter/migrations/0004_auto_20201008_2206.py | # Generated by Django 3.1.2 on 2020-10-09 02:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('splitter', '0003_auto_20201007_2339'),
]
operations = [
migrations.AlterField(
model_name='bill',
name='tax',
... | /splitter/migrations/0005_merge_20201009_1438.py | # Generated by Django 3.1.2 on 2020-10-09 14:38
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('splitter', '0004_auto_20201008_2206'),
('splitter', '0004_auto_20201009_1430'),
]
operations = [
]
| /splitter/migrations/0006_auto_20201009_1603.py | # Generated by Django 3.1.2 on 2020-10-09 16:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('splitter', '0005_merge_20201009_1438'),
]
operations = [
migrations.AddIndex(
model_name='bill',
index=models.Index(... | /splitter/migrations/0007_auto_20201009_1606.py | # Generated by Django 3.1.2 on 2020-10-09 16:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('splitter', '0006_auto_20201009_1603'),
]
operations = [
migrations.AddIndex(
model_name='item',
index=models.Index(f... | /splitter/migrations/0009_merge_20201012_2025.py | # Generated by Django 3.1.2 on 2020-10-12 20:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('splitter', '0008_auto_20201011_1907'),
('splitter', '0008_auto_20201011_0301'),
]
operations = [
]
| /splitter/migrations/0010_bill_tax_percent.py | # Generated by Django 3.1.2 on 2020-10-12 14:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('splitter', '0009_merge_20201012_2025'),
]
operations = [
migrations.AddField(
model_name='bill',
name='tax_percent',... | /splitter/migrations/0011_bill_tip_percent.py | # Generated by Django 3.1.2 on 2020-10-15 04:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('splitter', '0010_bill_tax_percent'),
]
operations = [
migrations.AddField(
model_name='bill',
name='tip_percent',
... | /splitter/migrations/0012_bill_session.py | # Generated by Django 3.1.2 on 2020-10-16 21:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('splitter', '0011_bill_tip_percent'),
]
operations = [
migrations.AddField(
model_name='bill',
name='session',
... | /splitter/mixins.py | class BillUpdateViewMixin(object):
def form_valid(self, form):
bill = get_object_or_404(Bill, id=self.kwargs['pk'])
form.instance.bill = bill
return super().form_valid(form) | /splitter/models.py | import uuid
from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
from decimal import Decimal
from .utils import _check_tip_tax_then_add
# Create your models here.
class Bill(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid... | /splitter/tests.py | from django.test import TestCase, RequestFactory
from django.urls import reverse
from django.contrib.auth import get_user_model
from decimal import Decimal
from .models import Bill, Person, Item
# Create your tests here.
class SplitterTests(TestCase):
def setUp(self):
self.user = get_user_model().object... | /splitter/urls.py | from django.urls import path
from .views import (
BillCreateView,
BillDetailView,
PersonCreateView,
PersonDeleteView,
BillListView,
ItemCreateView,
ItemDeleteView,
SharedItemCreateView,
BillUpdateView,
BillUpdateTaxPercentView,
BillUpdateTaxAmountView,
BillUpdateTipAmoun... | /splitter/utils.py | from decimal import Decimal
def _check_tip_tax_then_add(self):
# Checks to see if tip or tax is null before adding them to total else it returns 0
total = 0
tip = self.get_tip_amount()
tax = self.get_tax_amount()
if tip:
total += tip
if tax:
total += tax
return Decimal(tota... | /splitter/views.py | from django.views.generic import CreateView, DetailView, DeleteView, ListView, UpdateView
from django.shortcuts import get_object_or_404
from django.urls import reverse_lazy
from django.http import Http404
from decimal import Decimal
from .models import Bill, Person, Item
from .forms import (BillCreateForm,
... | /users/tests.py | from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse, resolve
from .forms import CustomUserCreationForm, CustomUserChangeForm
# Create your tests here.
class CustomUserTests(TestCase):
def test_create_user(self):
User = get_user_model()
u... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
trineary/TradeTestingEngine | refs/heads/master | {"/TTE.py": ["/TradeTracking/TradeHistory.py"], "/TTEBootstrapTests/MonteCarloBootstrap.py": ["/TTEBootstrapTests/BootstrapCalcTools.py", "/TTEBootstrapTests/BootstrapABC.py"], "/TTEBootstrapTests/WhiteBootstrap.py": ["/TTEBootstrapTests/BootstrapCalcTools.py", "/TTEBootstrapTests/BootstrapABC.py"], "/TradeTracking/Tra... | └──
├── TTE.py
├── TTEBootstrapTests
│ ├── BootstrapABC.py
│ ├── BootstrapCalcTools.py
│ ├── MonteCarloBootstrap.py
│ └── WhiteBootstrap.py
├── TTEExampleCode.py
├── TTEPaperEx1.py
├── TTEPaperEx2.py
├── TradeTracking
│ ├── TradeDetails.py
│ └── TradeHistory.... | /TTE.py | # --------------------------------------------------------------------------------------------------------------------
#
# Patrick Neary
# Date: 9/21/2016
#
# Fin 5350 / Dr. Tyler J. Brough
# Trade Testing Engine:
#
# tte.py
#
# This file handles the interface to most of the code in this project.
#
# ------------------... | /TTEBootstrapTests/BootstrapABC.py | # --------------------------------------------------------------------------------------------------------------------
#
# Patrick Neary
# Date: 11/12/2016
#
# Fin 5350 / Dr. Tyler J. Brough
# Trade Testing Engine:
#
# BootstrapABC.py
#
# Abstract base class for all tests developed to evaluate rules.
#
# --------------... | /TTEBootstrapTests/BootstrapCalcTools.py | # --------------------------------------------------------------------------------------------------------------------
#
# Patrick Neary
# Date: 11/12/2016
#
# Fin 5350 / Dr. Tyler J. Brough
# Trade Testing Engine:
#
# BootstrapCalcTools.py
#
# This file contains tools common to the bootstrap processes.
#
# -----------... | /TTEBootstrapTests/MonteCarloBootstrap.py | # --------------------------------------------------------------------------------------------------------------------
#
# Patrick Neary
# Date: 11/12/2016
#
# Fin 5350 / Dr. Tyler J. Brough
# Trade Testing Engine:
#
# kWhiteRealityCheck.py
#
# This file is an implementation of White's Reality Check for evaluating the ... | /TTEBootstrapTests/WhiteBootstrap.py | # --------------------------------------------------------------------------------------------------------------------
#
# Patrick Neary
# Date: 11/12/2016
#
# Fin 5350 / Dr. Tyler J. Brough
# Trade Testing Engine:
#
# kWhiteRealityCheck.py
#
# This file is an implementation of White's Reality Check for evaluating the ... | /TTEExampleCode.py | # --------------------------------------------------------------------------------------------------------------------
#
# Patrick Neary
# Date: 9/22/2016
#
# Fin 5350 / Dr. Tyler J. Brough
# Trade Testing Engine:
#
# TestFile.py
#
# This file shows how to use the TTE package
#
# ---------------------------------------... | /TTEPaperEx1.py | # --------------------------------------------------------------------------------------------------------------------
#
# Patrick Neary
# Date: 12/14/2016
#
# Fin 5350 / Dr. Tyler J. Brough
# Trade Testing Engine:
#
# TTEPaperEx1.py
#
# This file shows illustrates an example of trading rules that are active during a t... | /TTEPaperEx2.py | # --------------------------------------------------------------------------------------------------------------------
#
# Patrick Neary
# Date: 12/14/2016
#
# Fin 5350 / Dr. Tyler J. Brough
# Trade Testing Engine:
#
# TTEPaperEx2.py
#
# This file illustrates an example of trading rules that are engaged in a varied env... | /TradeTracking/TradeDetails.py | # --------------------------------------------------------------------------------------------------------------------
# Patrick Neary
# CS 6110
# Project
# 10/6/2016
#
# TradeDetails.py
#
# This file
# --------------------------------------------------------------------------------------------------------------------
... | /TradeTracking/TradeHistory.py | # --------------------------------------------------------------------------------------------------------------------
# Patrick Neary
# Fin5350
# Project
# 10/6/2016
#
# TradeHistory.py
#
# This file
# --------------------------------------------------------------------------------------------------------------------
... | /__init__.py |
from pytte import tte
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Tadaboody/good_smell | refs/heads/master | {"/good_smell/__init__.py": ["/good_smell/lint_smell.py", "/good_smell/flake8_ext.py", "/good_smell/ast_smell.py", "/good_smell/main.py", "/good_smell/smell_warning.py"], "/good_smell/ast_smell.py": ["/good_smell/lint_smell.py", "/good_smell/smell_warning.py"], "/good_smell/main.py": ["/good_smell/lint_smell.py", "/goo... | └──
├── docs
│ └── generate_smell_doc.py
├── good_smell
│ ├── __init__.py
│ ├── ast_smell.py
│ ├── flake8_ext.py
│ ├── lint_smell.py
│ ├── main.py
│ ├── smell_warning.py
│ └── smells
│ ├── __init__.py
│ ├── filter.py
│ ├── join_liter... | /docs/generate_smell_doc.py | from tests.test_collection import collect_tests, test_case_files
def generate_smell_docs():
for example_test in [list(collect_tests(file))[0] for file in test_case_files]:
desc, symbols, before, after = example_test
symbol = list(symbols)[0]
print(
f"""### {desc} ({symbol})
```... | /good_smell/__init__.py | # flake8:noqa
try:
from importlib import metadata
except ImportError:
# Running on pre-3.8 Python; use importlib-metadata package
import importlib_metadata as metadata
__version__ = metadata.version("good-smell")
from .smell_warning import SmellWarning
from .lint_smell import LintSmell
from .ast_smell impo... | /good_smell/ast_smell.py | import abc
import ast
from typing import List, Optional, Type, TypeVar
import astor
from good_smell import LintSmell, SmellWarning
class LoggingTransformer(ast.NodeTransformer, abc.ABC):
"""A subclass of transformer that logs the nodes it transforms"""
def __init__(self, transform):
self.transformed... | /good_smell/flake8_ext.py | import ast
from typing import Generator, Tuple
from good_smell import SmellWarning, implemented_smells, __version__
class LintingFlake8:
"""Entry point good smell to be used as a flake8 linting plugin"""
name = "good-smell"
version = __version__
def __init__(self, tree: ast.AST, filename: str):
... | /good_smell/lint_smell.py | import abc
import ast
import os
from typing import List, Optional
from good_smell import SmellWarning
class LintSmell(abc.ABC):
"""Abstract Base class to represent the sniffing instructions for the linter"""
def __init__(
self,
transform: bool,
path: Optional[str] = None,
tree... | /good_smell/main.py | from pathlib import Path
from typing import Iterable, Type
from fire import Fire
from good_smell import LintSmell, SmellWarning, implemented_smells
def print_smell_warnings(path: str):
"""Prints any warning messages about smells"""
print(
"\n".join(
warning.warning_string()
f... | /good_smell/smell_warning.py | from typing import NamedTuple
FLAKE8_FORMAT = "{path}:{row}:{col} {symbol} {msg}"
PYLINT_FORMAT = "{path}:{line}:{column}: {msg} ({symbol})"
def to_dict(namedtuple: NamedTuple) -> dict:
return dict(zip(namedtuple._fields, list(namedtuple)))
class SmellWarning(NamedTuple):
"""Class to represent a warning me... | /good_smell/smells/__init__.py | from .filter import FilterIterator
from .join_literal import JoinLiteral
from .nested_for import NestedFor
from .range_len_fix import RangeLenSmell
from .yield_from import YieldFrom
implemented_smells = (RangeLenSmell, NestedFor, FilterIterator, YieldFrom, JoinLiteral)
| /good_smell/smells/filter.py | from typing import TypeVar
import ast
from typing import cast
from good_smell import AstSmell, LoggingTransformer
class NameReplacer(ast.NodeTransformer):
def __init__(self, old: ast.Name, new: ast.AST):
self.old = old
self.new = new
def visit_Name(self, node: ast.Name) -> ast.AST:
i... | /good_smell/smells/join_literal.py | import ast
from good_smell import AstSmell, LoggingTransformer
try:
# ast.Str is deprecated in py3.8 and will be removed
StrConst = (ast.Constant, ast.Str)
except AttributeError:
StrConst = (ast.Constant,)
class JoinLiteral(AstSmell):
"""Checks if joining a literal of a sequence."""
@property
... | /good_smell/smells/nested_for.py | import ast
import typing
from good_smell import AstSmell, LoggingTransformer
class NameInNode(LoggingTransformer):
def __init__(self, name: ast.Name):
self.name = name
super().__init__(transform=False)
def is_smelly(self, node: ast.AST) -> bool:
return isinstance(node, ast.Name) and ... | /good_smell/smells/range_len_fix.py | import ast
from good_smell import AstSmell, LoggingTransformer
from typing import Union, Container
class RangeLenSmell(AstSmell):
@property
def transformer_class(self):
return EnumerateFixer
@property
def symbol(self):
return "range-len"
@property
def warning_message(self) -... | /good_smell/smells/yield_from.py | from good_smell import AstSmell, LoggingTransformer
import ast
class YieldFrom(AstSmell):
"""Checks for yields inside for loops"""
@property
def transformer_class(self):
return YieldFromTransformer
@property
def warning_message(self):
return "Consider using yield from instead of ... | /tests/examples/example.py | #: example
# example-symbol,another-one
before = 0
before = 1
# ==>
after = 0
after = 1
# END
#: example
# None
before = 0
before = 1
# ==>
after = 0
after = 1
# END | /tests/examples/filter.py | #: Move if to iterator
# filter-iterator
for i in range(10):
if i == 2:
print(1)
print(2)
# ==>
for i in (x for x in range(10) if x == 2):
print(1)
print(2)
# END
#: Don't move if there's code before
# None
for i in range(10):
print(1)
if pred(i):
print(2)
# ==>
for i in rang... | /tests/examples/join_literal.py | #: Warn when using join on a list of known literals.
# join-literal
a = "foo"
b = "bar"
",".join([a, b])
# ==>
a = "foo"
b = "bar"
"{},{}".format(a, b)
# END
#: Don't warn when joining an iterable
# None
iterable = ["a","b"]
",".join(iterable)
# ==>
iterable = ["a","b"]
",".join(iterable)
# END
#: Don't warn when joini... | /tests/examples/nested_for.py | #: Flatten for-loops using nested comprehensions
# nested-for
for i in seq_a:
for j in seq_b:
print(i, j)
# ==>
for i, j in ((i, j) for i in seq_a for j in seq_b):
print(i, j)
# END
#: Don't work if there's code between the loops (no way to know if it's unsafe)
# None
for i in seq_a:
print(i)
f... | /tests/examples/range_len.py | #: Range len instead of enumerate
# range-len
for i in range(len(sequence)):
a = sequence[i]
print(a)
# ==>
for i, a in enumerate(sequence):
print(a)
# END
#: Replace an empty body with pass
# range-len
for i in range(len(sequence)):
a = sequence[i]
# ==>
for i, a in enumerate(sequence):
pass
# END
... | /tests/examples/yield_from.py | #: Use "yield from" instead of yield inside of a for loop
# yield-from
seq = range(10)
for x in seq:
yield x
# ==>
seq = range(10)
yield from seq
| /tests/test_collection.py | import ast
import itertools
from os import PathLike
from pathlib import Path
from typing import Iterator, NamedTuple, Set
import astor
import black
import pytest
from good_smell import fix_smell, smell_warnings
FILE_DIR = Path(__file__).parent
EXAMPLES_DIR = FILE_DIR / "examples"
def normalize_formatting(code: str... | /tests/test_enumerate_fix.py | from good_smell import fix_smell
from re import match
import pytest
valid_sources = ["""
a = [0]
for i in range(len(a)):
print(a[i])
""",
"""
b = [1]
for i in range(len(a + b)):
print(i)
"""]
@pytest.mark.parametrize("source", valid_sources)
def test_range_len_fix(source):
assert not mat... | /tests/test_no_transform.py | import itertools
import ast
from good_smell.smells import NestedFor
def compare_ast(node1, node2):
"""Compare two ast, adapted from https://stackoverflow.com/a/30581854 to py3"""
if type(node1) is not type(node2):
return False
if isinstance(node1, ast.AST):
for k, v in vars(node1).items():... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
EricHughesABC/T2EPGviewer | refs/heads/master | {"/simple_pandas_plot.py": ["/ImageData.py"], "/visionplot_widgets.py": ["/ImageData.py"]} | └──
├── ImageData.py
├── azzT2paramsDialog.py
├── epgT2paramsDialog.py
├── mriplotwidget.py
├── simple_pandas_plot.py
├── t2fit.py
└── visionplot_widgets.py | /ImageData.py | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 6 14:55:05 2018
@author: ERIC
"""
import os
import numpy as np
import pandas as pd
import nibabel
class T2imageData():
def __init__(self):
self.currentSlice = None
self.currentEcho = None
self.T2imagesDirpath = None
... | /azzT2paramsDialog.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'azz_fit_parameters_dialog.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class AzzT2paramsDialog(object):
def __init__(... | /epgT2paramsDialog.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'epg_fit_parameters_dialog.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
import lmfit as lm
from PyQt5 import QtCore, QtGui, QtWidgets
class EpgT2paramsDialog(object):
... | /mriplotwidget.py | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 17 14:34:43 2019
@author: neh69
"""
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
#import seaborn as sns
from matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5
#import seaborn as sns
if is_pyqt5():
print("... | /simple_pandas_plot.py | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 20 10:29:38 2017
@author: neh69
"""
import os
import sys
import numpy as np
import pandas as pd
import lmfit as lm
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
from PyQt5 import QtCore, QtWidgets
import visionplot_widgets
... | /t2fit.py | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 3 11:30:41 2018
@author: ERIC
"""
import numpy as np
import lmfit
from epg import cpmg_epg_b1 as cpmg_epg_b1_c
from scipy import integrate
mxyz90 = np.fromfile( 'epg/mxyz90.txt', sep=' ' )
mxyz180 = np.fromfile('epg/mxyz180.txt', sep=' ')
mxyz90 = mxyz9... | /visionplot_widgets.py | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 28 13:11:07 2018
@author: neh69
"""
import sys
import numpy as np
#import matplotlib
import pandas as pd
#import mplcursors
from uncertainties import ufloat
import t2fit
import lmfit as lm
from matplotlib import pyplot as plt
#import seaborn as sns
f... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
DiegoArcelli/BlocksWorld | refs/heads/main | {"/launch.py": ["/load_state.py", "/utils.py", "/blocks_world.py"], "/main.py": ["/load_state.py", "/utils.py", "/blocks_world.py"], "/search_algs.py": ["/blocks_world.py"]} | └──
├── blocks_world.py
├── cnn.py
├── launch.py
├── load_state.py
├── main.py
├── search_algs.py
└── utils.py | /blocks_world.py | from aima3.search import *
from utils import *
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
# file che contine l'implementazione del problema basata con AIMA
class BlocksWorld(Problem):
def __init__(self, initial, goal):
super().__init__(initial, goal)
# restituisce il numero... | /cnn.py | import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import mnist
from keras.layers import Conv2D
from keras.layers import MaxPool2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.layers import Dropout
from keras import Sequential
# file per allenare e salvare la rete neur... | /launch.py | import tkinter as tk
from tkinter.filedialog import askopenfilename
from PIL import Image, ImageTk
from load_state import prepare_image
from utils import draw_state
from blocks_world import BlocksWorld
from search_algs import *
# file che contiene l'implementazione dell'interfaccia grafica per utilizzare il programma
... | /load_state.py | import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
import glob
from tensorflow import keras
from math import ceil
deteced = [np.array([]) for x in range(6)] # lista che contiene le immagini delle cifre
poisitions = [None for x in range(6)] # lista che contiene la posizione delle cifre nell'immagine
de... | /main.py | from PIL import Image, ImageTk
from load_state import prepare_image
from utils import draw_state
from blocks_world import BlocksWorld
from search_algs import *
import argparse
from inspect import getfullargspec
# file che definisce lo script da linea di comando per utilizzare il programma
if __name__ == "__main__":
... | /search_algs.py | from aima3.search import *
from utils import *
from collections import deque
from blocks_world import BlocksWorld
import sys
# file che contiene le implementazioni degli algoritmi di ricerca
node_expanded = 0 # numero di nodi espansi durante la ricerca
max_node = 0 # massimo numero di nodi presenti nella frontiera ... | /utils.py | import heapq
import functools
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
class PriorityQueue:
"""A Queue in which the minimum (or maximum) element (as determined by f and
order) is returned first.
If order is 'min', the item with minimum f(x) is
returned first; if order is 'max... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
viaacode/status | refs/heads/master | {"/src/viaastatus/server/wsgi.py": ["/src/viaastatus/server/response.py", "/src/viaastatus/decorators.py"]} | └──
├── locustfile.py
├── setup.py
└── src
└── viaastatus
├── decorators.py
├── prtg
│ └── api.py
└── server
├── cli.py
├── response.py
└── wsgi.py | /locustfile.py | from locust import HttpLocust, TaskSet, task
class WebsiteTasks(TaskSet):
@task
def index(self):
self.client.get("/")
@task
def status(self):
self.client.get("/status")
@task
def hetarchief(self):
self.client.get("/status/hetarchief.png")
@task
def ftp... | /setup.py | from setuptools import setup, find_packages
with open('README.md') as f:
long_description = f.read()
with open('requirements.txt') as f:
requirements = list(map(str.rstrip, f.readlines()))
setup(
name='viaastatus',
url='https://github.com/viaacode/status/',
version='0.0.3',
author='VIAA',
... | /src/viaastatus/decorators.py | from functools import wraps, partial
from flask import request, render_template
def cached(key='view/%s', cache=None, **extra_cache_kwargs):
def decorator(f):
@wraps(f)
def decorated(*args, **kwargs):
cache_key = key % request.path
rv = cache.get(cache_key)
if r... | /src/viaastatus/prtg/api.py | import requests
import json
import functools
import logging
# from collections import defaultdict
# from xml.etree import ElementTree
# ref: https://stackoverflow.com/questions/7684333/converting-xml-to-dictionary-using-elementtree
# def etree_to_dict(t):
# d = {t.tag: {} if t.attrib else None}
# children = l... | /src/viaastatus/server/cli.py | from argparse import ArgumentParser
from viaastatus.server import wsgi
import logging
def argparser():
"""
Get the help and arguments specific to this module
"""
parser = ArgumentParser(prog='status', description='A service that supplies status information about our platforms')
parser.add_argumen... | /src/viaastatus/server/response.py | import os
from flask import jsonify, Response
import flask
class FileResponse(Response):
default_mimetype = 'application/octet-stream'
def __init__(self, filename, **kwargs):
if not os.path.isabs(filename):
filename = os.path.join(flask.current_app.root_path, filename)
with open... | /src/viaastatus/server/wsgi.py | from flask import Flask, abort, Response, send_file, request, flash, session, render_template
from flask import url_for, redirect
from viaastatus.prtg import api
from viaastatus.decorators import cacher, templated
from os import environ
import logging
from configparser import ConfigParser
import re
import hmac
from has... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
digital-sustainability/swiss-procurement-classifier | refs/heads/master | {"/runOldIterations.py": ["/train.py", "/collection.py"], "/runIterations.py": ["/learn.py", "/collection.py"]} | └──
├── collection.py
├── db.py
├── helpers.py
├── learn.py
├── runIterations.py
├── runOldIterations.py
└── train.py | /collection.py | import json
import pandas as pd
import warnings
class Collection():
algorithms = ['gradient_boost', 'decision_tree', 'random_forest']
def __init__(self):
self.list = []
def append(self, item):
self.list.append(item)
def __iter__(self):
return iter(self.list)
def get_al... | /db.py | import configparser
import sqlalchemy
# git update-index --skip-worktree config.ini
config = configparser.ConfigParser()
config.read("config.ini")
connection_string = 'mysql+' + config['database']['connector'] + '://' + config['database']['user'] + ':' + config['database']['password'] + '@' + config['database']['... | /helpers.py | from db import connection, engine
import math
import pandas as pd
import numpy as np
from sklearn import tree
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, accuracy_score, roc_curve, auc
# =====================
# SQL SELECT STATEMENTS
# =====================
# @pa... | /learn.py | import pandas as pd
import numpy as np
import math
import re
from datetime import datetime
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.tree import DecisionTreeClassifi... | /runIterations.py | from learn import ModelTrainer
from collection import Collection
import pandas as pd
import logging
import traceback
import os
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# === THESIS ===
anbieter_config = {
'Construction': [
'Alpiq AG',
'KIBAG',
... | /runOldIterations.py | from train import ModelTrainer
from collection import Collection
import pandas as pd
import logging
import traceback
import os
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# === THESIS ===
anbieter_config = {
'Construction': [
'Alpiq AG',
'Swisscom',
... | /train.py | import pandas as pd
import math
from datetime import datetime
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics impor... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
badgerlordy/smash-bros-reader | refs/heads/master | {"/smash_reader/smash.py": ["/smash_reader/logger.py"], "/smash_reader/smash_game.py": ["/smash_reader/logger.py"], "/smash_reader/smash_utility.py": ["/smash_reader/logger.py"], "/smash_reader/smash_watcher.py": ["/smash_reader/logger.py"]} | └──
└── smash_reader
├── flags.py
├── logger.py
├── smash.py
├── smash_game.py
├── smash_utility.py
├── smash_watcher.py
└── tests.py | /smash_reader/flags.py | import cv2
import datetime
import numpy as np
import os
#import pytesseract as pyt
import time
from datetime import datetime
from PIL import Image, ImageGrab, ImageDraw, ImageChops
COORDS = {
'lobby-flag-screen-id': (379, 281, 1534, 445),
'lobby-flag-screen-player-markers': (70, 820, 1800, 821),
'flag-ar... | /smash_reader/logger.py | from datetime import datetime
import os
from sys import __excepthook__
from time import time
from traceback import format_exception
BASE_DIR = os.path.realpath(os.path.dirname(__file__))
def log_exception(type, value, tb):
error = format_exception(type, value, tb)
filepath = os.path.join(BASE_DIR, 'e... | /smash_reader/smash.py | from datetime import datetime
import json
from logger import log_exception
import numpy as np
import os
from PIL import Image, ImageTk
import platform
from queue import Queue, Empty
import requests
import smash_game
import smash_utility as ut
import smash_watcher
from sys import argv, excepthook
import time
i... | /smash_reader/smash_game.py | import copy
import difflib
import json
from logger import log_exception
import numpy as np
import os
from PIL import Image
import re
import smash_utility as ut
import sys
import threading
import time
sys.excepthook = log_exception
character_name_debugging_enabled = False
output = True
def _print(*args, **kwargs... | /smash_reader/smash_utility.py | import cv2
from datetime import datetime
import json
from logger import log_exception
import matplotlib.pyplot as plt
import mss
import numpy as np
from PIL import Image, ImageChops, ImageDraw
import pytesseract
import random
import requests
from skimage.measure import compare_ssim
import string
import subproce... | /smash_reader/smash_watcher.py | import json
from logger import log_exception
import os
from queue import Empty
import re
import requests
import smash_game
import smash_utility as ut
import sys
import threading
import time
sys.excepthook = log_exception
output = True
def _print(*args, **kwargs):
if output:
args = list(args)
... | /smash_reader/tests.py | import argparse
import cv2
import difflib
import json
import matplotlib.pyplot as plt
import mss
import numpy as np
import os
import re
import requests
import select
import smash_game
import smash_utility as ut
import socket
import struct
import threading
from queue import Empty, Queue
#from matplotlib import pyplot ... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
radrumond/hidra | refs/heads/master | {"/main.py": ["/args.py", "/data_gen/omni_gen.py", "/archs/fcn.py", "/archs/hydra.py"], "/test.py": ["/data_gen/omni_gen.py"], "/train.py": ["/data_gen/omni_gen.py"], "/archs/fcn.py": ["/archs/maml.py"]} | └──
├── archs
│ ├── fcn.py
│ ├── hydra.py
│ └── maml.py
├── args.py
├── data_gen
│ └── omni_gen.py
├── main.py
├── test.py
└── train.py | /archs/fcn.py | # ADAPTED BY Rafael Rego Drumond and Lukas Brinkmeyer
# THIS IMPLEMENTATION USES THE CODE FROM: https://github.com/dragen1860/MAML-TensorFlow
import os
import numpy as np
import tensorflow as tf
from archs.maml import MAML
class Model(MAML):
def __init__(self,train_lr,meta_lr,image_shape,isMIN, label_size=2):
... | /archs/hydra.py | # ADAPTED BY Rafael Rego Drumond and Lukas Brinkmeyer
# THIS IMPLEMENTATION USES THE CODE FROM: https://github.com/dragen1860/MAML-TensorFlow
import numpy as np
import tensorflow as tf
from archs.maml2 import MAML
def getBin(l=10):
x_ = 2
n = 1
while x_ < l:
x_ = x_* 2
n += 1
numbe... | /archs/maml.py | # ADAPTED BY Rafael Rego Drumond and Lukas Brinkmeyer
# THIS IMPLEMENTATION USES THE CODE FROM: https://github.com/dragen1860/MAML-TensorFlow
import os
import numpy as np
import tensorflow as tf
class MAML:
def __init__(self,train_lr,meta_lr,image_shape, isMIN, label_size=2):
self.train_lr = train_lr
... | /args.py | """
Command-line argument parsing.
"""
import argparse
#from functools import partial
import time
import tensorflow as tf
import json
import os
def boolean_string(s):
if s not in {'False', 'True'}:
raise ValueError('Not a valid boolean string')
return s == 'True'
def argument_parser():
"""
G... | /data_gen/omni_gen.py | import numpy as np
import os
import cv2
import pickle
class MiniImgNet_Gen:
def __init__(self,path="/tmp/data/miniimagenet",data_path=None):
if data_path is None:
self.path = path
self.train_paths = ["train/"+x for x in os.listdir(path+"/train")]
... | /main.py | ## Created by Rafael Rego Drumond and Lukas Brinkmeyer
# THIS IMPLEMENTATION USES THE CODE FROM: https://github.com/dragen1860/MAML-TensorFlow
from data_gen.omni_gen import unison_shuffled_copies,OmniChar_Gen, MiniImgNet_Gen
from archs.fcn import Model as mfcn
from archs.hydra import Model as mhyd
from train import ... | /test.py | import numpy as np
import tensorflow as tf
from data_gen.omni_gen import unison_shuffled_copies,OmniChar_Gen, MiniImgNet_Gen
def test(m, data_sampler,
eval_step,
min_classes,
max_classes,
train_shots,
test_shots,
meta_batch,
meta_iters,
na... | /train.py | import numpy as np
import tensorflow as tf
from data_gen.omni_gen import unison_shuffled_copies,OmniChar_Gen, MiniImgNet_Gen
import time
def train( m, mt, # m is the model foir training, mt is the model for testing
data_sampler, # Creates the data generator for training and testing
min_classe... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
sebastianden/alpaca | refs/heads/master | {"/src/cam.py": ["/src/utils.py"], "/src/test_time.py": ["/src/utils.py", "/src/alpaca.py"], "/src/test_use_case.py": ["/src/utils.py", "/src/alpaca.py"], "/src/alpaca.py": ["/src/utils.py"], "/src/main.py": ["/src/utils.py", "/src/alpaca.py"], "/src/test_voting.py": ["/src/utils.py", "/src/alpaca.py"]} | └──
└── src
├── alpaca.py
├── cam.py
├── gridsearch_results.py
├── main.py
├── test_time.py
├── test_use_case.py
├── test_voting.py
└── utils.py | /src/alpaca.py | import warnings
warnings.simplefilter(action='ignore')
import pickle
import pandas as pd
import numpy as np
from utils import TimeSeriesScalerMeanVariance, Flattener, Featuriser, plot_dtc
from sklearn.pipeline import Pipeline
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import Grid... | /src/cam.py | import tensorflow.keras.backend as K
import tensorflow.keras
from tensorflow.keras.layers import Lambda
from tensorflow.keras.models import Model, load_model
tensorflow.compat.v1.disable_eager_execution()
import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from utils import ... | /src/gridsearch_results.py | import pandas as pd
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
def univariant(df, param, quantity='mean_test_score'):
unique = df[param].unique()
scores = []
for i in unique:
scores.append(df[df[param] == i][quantity].mean()... | /src/main.py | import numpy as np
import pandas as pd
from utils import split_df, TimeSeriesResampler, plot_confusion_matrix, Differentiator
from alpaca import Alpaca
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
import matplotlib.pyplot as plt
if __name__ == "__main__":
"""
... | /src/test_time.py | from alpaca import Alpaca
from utils import to_time_series_dataset, to_dataset, split_df, TimeSeriesResampler
import time
import numpy as np
import pandas as pd
from sklearn.pipeline import Pipeline
max_sample = 20
for dataset in ['uc2']:
if dataset == 'uc1':
X, y = split_df(pd.read_pickle('..\\data\\df_... | /src/test_use_case.py | from alpaca import Alpaca
from utils import to_time_series_dataset, split_df, TimeSeriesResampler, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from sklearn.pipeline import Pipeline
import time
import numpy as np
import pandas as pd
# Variables
repetitions = 2... | /src/test_voting.py | from alpaca import Alpaca
from utils import load_test, split_df, TimeSeriesResampler,confusion_matrix
import time
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from sklearn.pipeline import Pipeline
import numpy as np
import pandas as pd
if __name__ == '__main__':
X, y = l... | /src/utils.py | import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from sklearn.utils.multiclass import unique_labels
from scipy.stats import kurtosis, skew
import numpy as np
import pandas as pd
from sklearn.base import TransformerMixin, BaseEstimator
from sklearn import tree
import graphviz
# Load the tes... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
gabilew/Joint-Forecasting-and-Interpolation-of-GS | refs/heads/master | {"/main/seattle_train_sggru_semisupervised.py": ["/data/Load_data.py", "/pytorch_gsp/utils/gsp.py", "/pytorch_gsp/train/train_rnn.py"], "/pytorch_gsp/models/sggru.py": ["/pytorch_gsp/utils/gsp.py"], "/data/Dataloader.py": ["/pytorch_gsp/utils/gsp.py"]} | └──
├── data
│ ├── Dataloader.py
│ └── Load_data.py
├── main
│ ├── __init.py
│ └── seattle_train_sggru_semisupervised.py
├── pytorch_gsp
│ ├── models
│ │ └── sggru.py
│ ├── train
│ │ └── train_rnn.py
│ └── utils
│ └── gsp.py
└── setup.... | /data/Dataloader.py |
import time
import numpy as np
import pandas as pd
import torch
import torch.utils.data as utils
from pytorch_gsp.utils.gsp import complement
def PrepareSequence(data, seq_len = 10, pred_len = 1):
time_len = data.shape[0]
sequences, labels = [], []
for i in range(time_len - seq_len - pred_len)... | /data/Load_data.py | import math
import sys
import time
import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import rbf_kernel
def USA_data(directory ):
""""TODO: include the GSOD dataset"""
signals = pd.read_csv( directory + 'Usa_temp.csv')
if "Unnamed: 0" in signals.columns:
signals.drop(columns="... | /main/__init.py | import os
import sys
current_dir = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0]
sys.path.append(os.path.join(current_dir, 'data'))
print(sys.path) | /main/seattle_train_sggru_semisupervised.py | import os
import time
import torch
import argparse
import numpy as np
import pandas as pd
import time
from data.Load_data import Seattle_data
from data.Dataloader import *
from pytorch_gsp.train.train_rnn import Evaluate, Train
from pytorch_gsp.utils.gsp import ( greedy_e_opt, spectral_components)
from pytorch_gsp.... | /pytorch_gsp/models/sggru.py | import torch.utils.data as utils
import torch.nn.functional as F
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.parameter import Parameter
import numpy as np
import pandas as pd
import time
from pytorch_gsp.utils.gsp import (spectral_components, Reconstruction)
class SpectralGrap... | /pytorch_gsp/train/train_rnn.py | ### training code ####
import sys
import time
import numpy as np
import torch
from torch.autograd import Variable
toolbar_width=20
def Train(model, train_dataloader, valid_dataloader, learning_rate = 1e-5, epochs = 300, patience = 10,
verbose=1, gpu = True, sample = None, optimizer = 'rmsprop'):
if optimize... | /pytorch_gsp/utils/gsp.py | import torch
import torch.nn as nn
import numpy as np
from torch.autograd import Variable
import scipy
from sklearn.metrics.pairwise import rbf_kernel
def complement(S,N):
V = set(np.arange(0,N,1))
return np.array(list(V-set(S)))
class Reconstruction(nn.Module):
def __init__(self,V, sample, freqs, dom... | /setup.py | from setuptools import setup, find_packages
setup(
name='Joint-Forecasting-and-Interpolation-of-Graph-Signals-Using-Deep-Learning',
version='0.1.0',
author='Gabriela Lewenfus',
author_email='gabriela.lewenfus@gmail.com',
packages=find_packages(),
install_requires = ['scipy>=1.4.1', 'pandas>=0.15', '... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
AntLouiz/DatapathWay | refs/heads/master | {"/core.py": ["/control.py", "/logic.py", "/memory.py"], "/instructions.py": ["/utils.py"], "/logic.py": ["/utils.py"], "/memory.py": ["/utils.py"], "/control.py": ["/utils.py"], "/main.py": ["/core.py"]} | └──
├── control.py
├── core.py
├── instructions.py
├── li.py
├── logic.py
├── main.py
├── memory.py
└── utils.py | /control.py | import abc
from utils import to_integer, to_decimalC2
class BaseControl(abc.ABC):
def __init__(self, cpu):
self.cpu = cpu
@abc.abstractmethod
def execute(self):
pass
class ControlAdd(BaseControl):
def execute(self):
instruction = self.cpu.pc.next_instruction
regist... | /core.py | from memory import RegistersBank, Memory
from logic import ALU
from instructions import PC
from control import (
ControlSw,
ControlLw,
ControlAdd,
ControlSub,
ControlAnd,
ControlOr,
)
class CPU:
def __init__(self):
self.alu = ALU()
self.pc = PC()
self.registers = Re... | /instructions.py | from li import FUNCTIONS
from utils import extend_to_bits
class MipsInstruction:
op = None
rs = None
rt = None
rd = None
shamt = None
func = None
offset = None
instruction_type = None
instruction = None
def __init__(self, instruction):
if not (isinstance(instruction, st... | /li.py | # Intruçoes que o programa reconhece
FUNCTIONS = {
'101011': 'sw',
'100011': 'lw',
'100000': 'add',
'100010': 'sub',
'100101': 'or',
'100100': 'and'
}
| /logic.py | from utils import (
extend_to_bits,
to_binary,
to_integer,
to_binaryC2,
to_decimalC2
)
class ALU:
def makeSum(self, a, b):
result = to_decimalC2(a) + to_decimalC2(b)
if result > (2**31 -1) or result < -(2**31):
print("{}OVERFLOW OCURRENCE{}".format("-" * 20, "-... | /main.py | from core import CPU
if __name__ == "__main__":
cpu = CPU()
cpu.execute()
| /memory.py | import random
from utils import to_binary, extend_to_bits, to_binaryC2
class BaseMemory:
def __init__(self):
self.data = {}
def set_value(self, address, value):
"""
Set a value with a given address
"""
self.data[address] = value
return True
def get_valu... | /utils.py | def to_integer(binary_number):
if not isinstance(binary_number, str):
raise Exception()
return int(binary_number, 2)
def to_binary(number):
if not isinstance(number, int):
raise Exception()
return "{:0b}".format(number)
def extend_to_bits(binary_number, bits = 32):
if not isins... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
zhuliyi10/python_demo | refs/heads/master | {"/models/mymodule_demo.py": ["/models/mymodule.py"]} | └──
├── base.py
├── function
│ ├── function.py
│ ├── function_key.py
│ └── total.py
├── if.py
├── input_output
│ ├── pickling.py
│ ├── user_input.py
│ └── using_file.py
└── models
├── mymodule.py
├── mymodule_demo.py
└── using_sys.py | /base.py | age = 20
name = 'zhuly'
print('{0} was {1} years old'.format(name, age))
| /function/function.py | def sayHello():
print('hello world,hello python!')
sayHello() | /function/function_key.py | def func(a, b=5, c=10):
print('a=', a, ' b=', b, ' c=', c)
func(2, 7)
func(2, c=23)
func(c=23,a=9)
| /function/total.py | def total(a=5,*numbers,**phonebook):
print('a',a)
#通过元组遍历全部的参数
for item in numbers:
print('num_item',item)
#通过字典遍历全部的参数
for first,second in phonebook.items():
print(first,second)
total(10,1,2,3,Name='zhuly',age=26)
| /if.py | number = 23
while True:
guess = int(input('请输入一个整数:'))
if guess == number:
print('恭喜,你猜对了。')
break
elif guess < number:
print('你猜小了')
else:
print('你猜大了')
print('end')
| /input_output/pickling.py | import pickle
# 我们将要存储对象的文件名
shoplistfile = 'shoplist.data'
# 购物清单
shoplist = ['苹果', '芒果', '胡萝卜']
# 定到文件
f = open(shoplistfile, 'wb')
pickle.dump(shoplist, f)
f.close()
del shoplist # 释放shoplist变量
# 从仓库读回
f = open(shoplistfile, 'rb')
storedlist = pickle.load(f)
f.close()
print(storedlist)
| /input_output/user_input.py |
def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
something=input('输入文本:')
if is_palindrome(something):
print("是的,这是回文")
else:
print("这不是回文")
| /input_output/using_file.py | poem = '''\
当工作完成时
编程是有趣的
如果想让你的工作有趣
使用Python!
'''
f = open('poem.txt', 'w')
f.write(poem)
f.close()
f = open('poem.txt', 'r')
while(True):
line = f.readline()
if len(line) == 0:
break
print(line, end='')
f.close()
| /models/mymodule.py |
def sayhello():
print('hello wolrd,hello python!')
__version__='0.1'
| /models/mymodule_demo.py | from mymodule import sayhello,__version__
sayhello()
print('version:',__version__)
| /models/using_sys.py | import sys
print('命令行参数是:')
for i in sys.argv:
print(i)
print("python path is in ",sys.path) | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
moddevices/mod-devel-cli | refs/heads/master | {"/modcli/bundle.py": ["/modcli/utils.py"], "/modcli/config.py": ["/modcli/utils.py"]} | └──
├── modcli
│ ├── __init__.py
│ ├── auth.py
│ ├── bundle.py
│ ├── cli.py
│ ├── config.py
│ ├── settings.py
│ └── utils.py
└── setup.py | /modcli/__init__.py | from modcli import config
__version__ = '1.1.3'
context = config.read_context()
| /modcli/auth.py | import socket
import webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib import parse
import click
import requests
from click import Abort
from modcli import __version__
def login(username: str, password: str, api_url: str):
result = requests.post('{0}/users/tokens'.format(api_url)... | /modcli/bundle.py | import os
import shutil
import subprocess
import tempfile
from hashlib import md5
import click
import crayons
import requests
from modcli import context
from modcli.utils import read_json_file
def publish(project_file: str, packages_path: str, keep_environment: bool=False, bundles: list=None,
show_resul... | /modcli/cli.py | import click
import crayons
from modcli import context, auth, __version__, bundle
_sso_disclaimer = '''SSO login requires you have a valid account in MOD Forum (https://forum.moddevices.com).
If your browser has an active session the credentials will be used for this login. Confirm?'''
@click.group(context_settings... | /modcli/config.py | import base64
import json
import os
import stat
import re
from modcli import settings
from modcli.utils import read_json_file
def read_context():
context = CliContext.read(settings.CONFIG_DIR)
if len(context.environments) == 0:
for env_name, urls in settings.URLS.items():
context.add_env... | /modcli/settings.py | import os
CONFIG_DIR = os.path.expanduser('~/.config/modcli')
URLS = {
'labs': ('https://api-labs.moddevices.com/v2', 'https://pipeline-labs.moddevices.com/bundle/'),
'dev': ('https://api-dev.moddevices.com/v2', 'https://pipeline-dev.moddevices.com/bundle/'),
}
DEFAULT_ENV = 'labs'
| /modcli/utils.py | import json
import os
def read_json_file(path: str):
if not os.path.isfile(path):
return {}
with open(path, 'r') as file:
contents = file.read()
return json.loads(contents)
| /setup.py | import re
import sys
from setuptools import setup
with open('modcli/__init__.py', 'r') as fh:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fh.read(), re.MULTILINE).group(1)
if sys.version_info[0] < 3:
raise Exception("Must be using Python 3")
setup(
name='mod-devel-cli',
python_req... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
limkokholefork/Answerable | refs/heads/main | {"/tools/cache.py": ["/tools/log.py"], "/tools/fetcher.py": ["/tools/log.py", "/tools/displayer.py"], "/tools/spider.py": ["/tools/log.py", "/tools/displayer.py"], "/tools/log.py": ["/tools/displayer.py"]} | └──
├── answerable.py
├── models
│ ├── content_based_0.py
│ └── content_based_1.py
└── tools
├── cache.py
├── displayer.py
├── fetcher.py
├── log.py
├── spider.py
└── statistics.py | /answerable.py | import re
import json
import argparse
import datetime
import textwrap
import importlib
from urllib.error import URLError
from tools import fetcher, displayer, log, spider
_current_version = "v1.1"
def latest_version():
try:
res = spider.get(
"https://api.github.com/repos/MiguelMJ/Answerable... | /models/content_based_0.py | """Recommender Tool for Answerable
This file contains the recommendation algorithm.
"""
from bs4 import BeautifulSoup as bs
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.metrics.pairwise import linear_kernel
def recommend(user_qa, feed):
answered = [
x[0]["ti... | /models/content_based_1.py | """Recommender Tool for Answerable
This file contains the recommendation algorithm.
"""
import tools.displayer
from bs4 import BeautifulSoup as bs
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
import numpy as np
import re
def preprocessed_text_from_ht... | /tools/cache.py | """Cache Tool for Answerable
This file contains the functions to access and modify cached content.
It may be used by different modules, so each function requires a category argument
to avoid collisions.
As every function is intended to serve a secondary role in extern functions, the
logs have an extra level of indent... | /tools/displayer.py | """Displayer Tool for Answerable
This file contains the functions and variables used to present the data.
"""
import tools.statistics as st
#
# COLOR RELATED VARIABLES AND FUNCTIONS
#
red = (250, 0, 0)
green = (0, 250, 0)
blue = (0, 0, 250)
cyan = (0, 250, 250)
magenta = (250, 0, 250)
yellow = (250, 250, 0)
"""
wh... | /tools/fetcher.py | """Fetcher Tool for Answerable
This file contains the high level functions in charge of data retrieval.
It provides a interface between the spider/crawler and another level of
cacheable information.
"""
import math
import json
from datetime import timedelta as td
from bs4 import BeautifulSoup
from tools import spid... | /tools/log.py | """Log Tool for Answerable
This file contains the functions used to log control data and debug messages
in a unified format.
"""
import re
import sys
import inspect
from tools.displayer import bold, red, magenta, fg
_logs = [] # list of file handlers
_ansire = re.compile("\\033\[[^m]+m") # ansi escape sequences
... | /tools/spider.py | """Spider Tool for Answerable
This file contains the functions used to wrapp requests following
respecful practices, taking into account robots.txt, conditional
gets, caching contente, etc.
"""
import json
import requests
# from random import random as rnd
from time import sleep
from datetime import timedelta as td
... | /tools/statistics.py | """Statistics Tool for Answerable
This file contains the functions used to analyze user answers.
"""
#
# TAG RELATED METRICS (USING QA)
#
_tags_info = None
def tags_info(qa):
"""Map each tag to its score, acceptance and count"""
global _tags_info
if _tags_info is not None:
return _tags_info
... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
nairita87/Ocean_dir | refs/heads/ocean_coastal | {"/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/tests/winds/test_parameters.py": ["/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/winds/parameters.py", "/testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/winds/wind_model.py"], "/testing_and_setup/compass/ocean/hu... | └──
└── testing_and_setup
└── compass
└── ocean
├── baroclinic_channel
│ └── 4km
│ └── rpe_test
│ └── plot.py
├── drying_slope
│ └── zstar_variableCd
│ └── 1... | /testing_and_setup/compass/ocean/baroclinic_channel/4km/rpe_test/plot.py | import numpy as np
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
fig = plt.gcf()
nRow = 1 # 2
nCol = 5
nu = ['1', '5', '10', '100', '200']
iTime = [0]
time = ['20']
# ---nx,ny for 10 km
#nx = 16
#ny = 50
# ---nx,ny for 4 km
nx = 40
ny = 126
# ---nx,ny for 1 km
... | /testing_and_setup/compass/ocean/drying_slope/zstar_variableCd/1km/analysis/comparison.py | ../comparison.py | /testing_and_setup/compass/ocean/global_ocean/ARM60to6/init/define_base_mesh.py | # /usr/bin/env python
"""
% Create cell width array for this mesh on a regular latitude-longitude grid.
% Outputs:
% cellWidth - m x n array, entries are desired cell width in km
% lat - latitude, vector of length m, with entries between -90 and 90, degrees
% lon - longitude, vector of length n, with entries b... | /testing_and_setup/compass/ocean/global_ocean/CA120to3/build_mesh/define_base_mesh.py | #!/usr/bin/env python
'''
name: define_base_mesh
authors: Phillip J. Wolfram
This function specifies the resolution for a coastal refined mesh for the CA coast from SF to LA for
Chris Jeffrey and Mark Galassi.
It contains the following resolution resgions:
1) a QU 120km global background resolution
2) 3km refinem... | /testing_and_setup/compass/ocean/global_ocean/HI120to12/build_mesh/define_base_mesh.py | #!/usr/bin/env python
'''
name: define_base_mesh
authors: Phillip J. Wolfram
This function specifies a high resolution patch for
Chris Jeffrey.
'''
import numpy as np
def cellWidthVsLatLon():
lat = np.arange(-90, 90.01, 1.0)
lon = np.arange(-180, 180.01, 2.0)
km = 1000.0
# in kms
baseRes = 120.... | /testing_and_setup/compass/ocean/global_ocean/SO60to10wISC/init/define_base_mesh.py | import numpy as np
import jigsaw_to_MPAS.mesh_definition_tools as mdt
from jigsaw_to_MPAS.coastal_tools import signed_distance_from_geojson, \
compute_cell_width
from geometric_features import read_feature_collection
import xarray
# Uncomment to plot the cell size distribution.
# import matplotlib
# matplotlib.use... | /testing_and_setup/compass/ocean/global_ocean/scripts/copy_cell_indices_ISC.py | #!/usr/bin/env python
'''
Script to map cell indices from MPASO noLI mesh to those of the wLI mesh in the runoff mapping file.
Start by building a runoff mapping file that has all the mesh description from wLI mapping file
but the actual mapping from the noLI mapping file:
ncks -x -v S,col,row /project/projectdirs/acme... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/ad_hoc/simple_vector_example.py | import numpy as np
import matplotlib.pyplot as plt
def example():
x,y = np.linspace(-1,1,2), np.linspace(-1,1,2)
A, B = np.zeros((2,2)), np.zeros((2,2))
A[0,0]=1
B[0,0]=-1
A[0,1]=1
B[0,1]=1
A[1,0]=-1
B[1,0]=-1
A[1,1]=-1
B[1,1]=1
fig = plt.figure()
ax = fig.add_subplot(1... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/ad_hoc/wind_vector_example.py | import sys
import numpy as np
import matplotlib.pyplot as plt
#from matplotlib.patches import Circle
import math
def W(x, y):
"""Return the wind vector given a wind speed."""
r = np.sqrt(x*x+y*y)
v = V(r)
if r>0:
costheta = x/r
sintheta = y/r
return [-sintheta*v,costheta*v]
... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/hurricane_model/hurricane.py | import datetime
class Hurricane:
def __init__(self, center: tuple, extent: float, pcentral: float, deltap: float,
vmax: float, b: float, time: float, initial_datetime: datetime.datetime):
self.center = center # Position of the eye (lon,lat) in radians as tuple.
self.exte... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/main.py | from winds_io import import_data
from winds_io import output_data
from structures import geogrid
import sys
import numpy as np
from winds import parameters
from winds import wind_model
def sim_hurricane():
# Read in the input file to check which grid we are using
print('Import user inputs')
traj_filename, ... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/plot_winds_on_mpaso_mesh.py | # Author: Steven Brus
# Date: April, 2020
# Description: Plots syntetic wind/pressure timeseries on MPAS-O mesh
import netCDF4
import matplotlib.pyplot as plt
import numpy as np
import os
import cartopy
import cartopy.crs as ccrs
import cartopy.feature as cfeature
plt.switch_backend('agg')
cartopy.config['pre_existing... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/profile_model/radialprofiles.py | import numpy as np
import math
class RadialProfile():
def __init__(self,n,extent):
self.profile = np.zeros(n,dtype=np.float64)
self.rvals = np.zeros(n,dtype=np.float64)
self.n = n
self.extent = extent
self.dr = extent/(n-1)
for i in range(0,n):
self.rval... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/structures/geogrid.py | import numpy as np
class GeoGrid:
def __init__(self, lon: np.ndarray, lat: np.ndarray):
"""
Constructor.
:param lon: longitude of the grid in radians, as numpy array
:param lat: latitude of the grid in radians, as numpy array
"""
self.lon = lon
self.lat = lat... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/tests/hurricane/test_hurricane.py | import pytest
from hurricane_model.hurricane import Hurricane
def test_hurricane():
center = [1.0,2.0] # Position of the eye (lon,lat) in decimal degrees.
extent = 100.0 # The maximum extent of the hurricane in kilometers.
vforward = [3.0, 4.0] # Forward velocity [ve, vn] in km/hr.
pcentral = 200.0 ... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/tests/structures/test_geogrid.py | from structures.geogrid import GeoGrid
def test_geogrid():
lon = -106.0
lat = 35
nlon = 8
nlat = 4
cellsize = 1.0
defaultValue = -1.0
grid = GeoGrid(lon,lat,nlon,nlat,cellsize,defaultValue = defaultValue)
assert grid.lon == lon
assert grid.lat == lat
assert grid.nlon == nlon
... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/tests/utils/test_gis.py | from geopy.distance import geodesic
from utils.gis import geodistkm
def test_gis():
albuquerque = [35.0844, -106.6504] #(lat,lon)
los_alamos = [35.8800, -106.3031] #(lat,lon)
result1 = geodesic(albuquerque,los_alamos).km
result2 = geodistkm(albuquerque[1],albuquerque[0],los_alamos[1],los_alamos[0])
... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/tests/winds/test_parameters.py | from winds.wind_model import PROFILE_TYPE
from winds.parameters import Parameters
import math
def test_parameters():
gridsize = [10, 10]
nr = 100
wind_profile_type = PROFILE_TYPE.HOLLAND
grid_position = [-106.0,35.0]
cellsize = 2.0
siderealDay = 23.934 # A sidereal day in hrs.
omega = 2.0 ... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/tests/winds/test_velocities.py | from winds.velocities import Velocities
import math
def test_velocities():
# Forward velocity in km/hr.
vfe = -1.0 # Eastward .
vfn = 0.0 # Northward.
vg = 1.0 # Tangential gradient wind speed in km/hr.
veloc = Velocities(vfe,vfn)
r = 1.0 # Unit circle about the origin.
np = 360
dtheta... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/tests/winds/test_velocity_grid.py | import numpy as np
from structures.geogrid import GeoGrid
from profile_model.radialprofiles import HollandWindSpeedProfile
from winds.parameters import Parameters
from winds.velocities import Velocities
import matplotlib.pyplot as plt
def test_velocity_grid():
# Grid of x, y points
n = 50
nr = 200
rmax... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/utils/gis.py | from geopy.distance import geodesic
def geodistkm(x1,y1,x2,y2):
'''
Returns the geodesic distance in km given two pairs of (lon, lat) coordinates.
Note: Because it uses geopy, the coordinate order is reversed to (lat,lon)
before calling the geopy function.
:param x1: lon of the first point.
:pa... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/utils/math.py |
def sign(x):
if(x>=0):
return 1
else:
return -1
| /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/winds/parameters.py | import math
from winds.wind_model import PROFILE_TYPE
class Parameters:
def __init__(self, mean_lat: float, wind_profile_type=PROFILE_TYPE.HOLLAND):
"""
Constructor.
:param mean_lat: mean latitude of the hurricane trajectory to compute the Coroilis factor in radians
Units are km, hr... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/winds/velocities.py | import math
class Velocities:
def __init__(self, vfe, vfn, vmax):
"""
Initialize with the forward velocity components.
:param vfe: Eastward forward velocity (x-component in the Earth frame) in km/hr.
:param vfn: Northward forward velocity component (y-component in the Earth frame)... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/winds/wind_model.py | from enum import Enum
import numpy as np
import winds.parameters as Parameters
import hurricane_model as Hurricane
import structures as Geogrid
import matplotlib.pyplot as plt
import math
class PROFILE_TYPE(Enum):
HOLLAND = 'holland'
WILLOUGHBY = 'willoughby'
class WindModel:
def __init__(self, params: P... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/winds_io/import_data.py | import json
from netCDF4 import Dataset
import numpy as np
import math
from hurricane_model import hurricane
from structures import geogrid
import datetime
def read_grid_file(grid_filename: str, grid_flag: int) -> (float, float):
if grid_flag == 1:
xll, yll, cellsize, numcells_lat, numcells_lon = read_rast... | /testing_and_setup/compass/ocean/hurricane/hurricane_wind_pressure/winds_io/output_data.py | import netCDF4
import numpy as np
import hurricane_model as Hurricane
import structures as Geogrid
import winds_io as WindModel
import matplotlib.pyplot as plt
import datetime
def write_netcdf(filename: str, curr_hurricane: Hurricane, grid: Geogrid, winds: WindModel):
# http://unidata.github.io/netcdf4-python/#se... | /testing_and_setup/compass/ocean/hurricane/scripts/interpolate_time_varying_forcing.py | # Author: Steven Brus
# Date: August, 2019
# Description: Interpolates CFSR atmospheric reanalysis data onto the MPAS-O mesh and
# creates an input file to support time varying atmospheric forcing in the model
import netCDF4
import matplotlib.pyplot as plt
import numpy as np
import glob
import pprint
imp... | /testing_and_setup/compass/ocean/hurricane/scripts/spinup_time_varying_forcing.py | # Author: Steven Brus
# Date April, 2020
# Description:
# This creates a "dummy" time varying forcing file
# with zero wind zero atmospheric pressure perturbation
# for the tidal spinup run.
#
# The tidal spinup is run using this "dummy" atmospheric forcing
# because the time varying atmospheric forcing... | /testing_and_setup/compass/ocean/hurricane/scripts/write_forcing_file.py | # Author: Steven Brus
# Date: April, 2020
# Description: This function writes time-varying forcing data to an input file for the model run.
import os
import numpy as np
import netCDF4
##################################################################################################
###################################... | /testing_and_setup/compass/ocean/internal_waves/5km/rpe_test/plot.py | import numpy
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
fig = plt.gcf()
nRow = 4
nCol = 2
nu = ['0.01', '1', '15', '150']
iTime = [1, 2]
time = ['day 10', 'day 20']
fig, axs = plt.subplots(nRow, nCol, figsize=(
4.0 * nCol, 3.7 * nRow), constrained_layout=Tr... | /testing_and_setup/compass/ocean/jigsaw_to_MPAS/build_mesh.py | #!/usr/bin/env python
"""
This script performs the first step of initializing the global ocean. This
includes:
Step 1. Build cellWidth array as function of latitude and longitude
Step 2. Build mesh using JIGSAW
Step 3. Convert triangles from jigsaw format to netcdf
Step 4. Convert from triangles to MPAS mesh
Step 5. C... | /testing_and_setup/compass/ocean/lock_exchange/0.5km/rpe_test/plot.py | import numpy
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
fig = plt.gcf()
nRow = 6
nCol = 2
iTime = [8, 16]
nu = ['0.01', '0.1', '1', '10', '100', '200']
time = ['hour 8', 'hour 16']
fig, axs = plt.subplots(nRow, nCol, figsize=(
5.3 * nCol, 2.0 * nRow), const... | /testing_and_setup/compass/ocean/overflow/1km/rpe_test/plot.py | import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from netCDF4 import Dataset
import numpy
fig = plt.gcf()
fig.set_size_inches(8.0,10.0)
nRow=1 #6
nCol=2
nu=['0.01','0.1','1','10','100','1000']
iTime=[3,6]
time=['3 hrs','6 hrs']
for iRow in range(nRow):
ncfile = Dataset('output_'+str(iRow+1)+... | /testing_and_setup/compass/ocean/surface_waves/analysis/comparison.py | #!/usr/bin/env python
"""
Tidal channel comparison betewen MPAS-O and analytical forcing result.
Phillip J. Wolfram
04/12/2019
"""
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
# render statically by default
plt.switch_backend('agg')
# analytical case
x = np.linspace(0,24,100)
y = np.sin(... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Powercoders-International/ft-web-dev | refs/heads/main | {"/05-django/solutions/exercise-3-models/shop/admin.py": ["/05-django/solutions/exercise-3-models/shop/models.py"], "/05-django/solutions/exercise-3-models/shop/views.py": ["/05-django/solutions/exercise-3-models/shop/models.py"], "/05-django/solutions/exercise-4-restframework/shop/views.py": ["/05-django/solutions/exe... | └──
└── 05-django
└── solutions
├── exercise-2-static
│ └── shop
│ ├── urls.py
│ └── views.py
├── exercise-3-models
│ └── shop
│ ├── admin.py
│ ├── models.py
│ └── v... | /05-django/solutions/exercise-2-static/shop/urls.py | from django.urls import path
from shop.views import view_article
from shop.views import view_articles
urlpatterns = [
path('articles/', view_articles),
path('articles/<int:id>/', view_article),
]
| /05-django/solutions/exercise-2-static/shop/views.py | from json import loads
from django.http import JsonResponse
from django.http import HttpResponseNotAllowed
def view_articles(request):
""" Handles GET and POST requests for a collection of articles.
curl --include \
http://localhost:8000/shop/articles/
curl --include \
--request POST \
... | /05-django/solutions/exercise-3-models/shop/admin.py | from django.contrib.admin import ModelAdmin, register
from shop.models import Article
@register(Article)
class ArticelAdmin(ModelAdmin):
pass
| /05-django/solutions/exercise-3-models/shop/models.py | from django.db.models import Model
from django.db.models import CharField
class Article(Model):
name = CharField(max_length=50)
| /05-django/solutions/exercise-3-models/shop/views.py | from json import loads
from django.http import JsonResponse
from django.http import HttpResponseNotAllowed
from django.http import HttpResponseNotFound
from shop.models import Article
def view_articles(request):
""" Handles GET and POST requests for a collection of articles.
curl --include \
http://l... | /05-django/solutions/exercise-4-restframework/shop/views.py | from shop.models import Article
from shop.serializers import ArticleSerializer
from rest_framework.viewsets import ModelViewSet
class ArticleViewSet(ModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
| /05-django/solutions/exercise-5-filters/shop/filters.py | from django_filters import FilterSet
from shop.models import Article
class ArticleFilter(FilterSet):
class Meta:
model = Article
fields = ['category']
| /05-django/solutions/exercise-5-filters/shop/serializers.py | from shop.models import Article
from rest_framework.serializers import HyperlinkedModelSerializer
class ArticleSerializer(HyperlinkedModelSerializer):
class Meta:
model = Article
fields = ['id', 'name', 'category']
read_only_fields = ['id']
| /05-django/solutions/exercise-5-filters/shop/urls.py | from shop.views import ArticleViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('articles', ArticleViewSet)
urlpatterns = router.urls
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
krzysztof-dudzic/ProjektPortfolioLab | refs/heads/main | {"/charitydonation/views.py": ["/charitydonation/forms.py", "/charitydonation/models.py"], "/charitydonation/admin.py": ["/charitydonation/models.py"], "/charitydonation/forms.py": ["/charitydonation/models.py"], "/donation/urls.py": ["/accounts/views.py", "/charitydonation/views.py"]} | └──
├── accounts
│ ├── models.py
│ └── views.py
├── charitydonation
│ ├── admin.py
│ ├── forms.py
│ ├── migrations
│ │ ├── 0002_auto_20210909_1554.py
│ │ └── 0003_auto_20210913_1642.py
│ ├── models.py
│ └── views.py
└── donation
└── urls.py | /accounts/models.py | from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser, UserManager
)
#
# class UserManager(BaseUserManager):
# def create_user(self, email, password=None):
# """
# Creates and saves a User with the given email and password.
# """
# ... | /accounts/views.py | from django.shortcuts import render
from django.views import View, generic
from django.contrib.auth import views
# from .forms import RegisterForm
from django.shortcuts import render
from django.views import View, generic
# from charitydonation.models import Donation, Institution
from .forms import CreateUserForm, Logi... | /charitydonation/admin.py | from django.contrib import admin
from .models import Category, Institution, Donation
admin.site.register(Category)
admin.site.register(Institution)
admin.site.register(Donation) | /charitydonation/forms.py | from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import Donation
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.contrib.auth ... | /charitydonation/migrations/0002_auto_20210909_1554.py | # Generated by Django 3.1 on 2021-09-09 15:54
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('charitydonation', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='donation',
nam... | /charitydonation/migrations/0003_auto_20210913_1642.py | # Generated by Django 3.1 on 2021-09-13 16:42
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('charitydonation', '0002_auto_20210909_1554'),
]
operations = [
migrations.AddField(
model_name='donation',
... | /charitydonation/models.py | import datetime
from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import gettext_lazy as _
# from ProjektPortfolioLab.donation import settings
from django.conf import settings
User = settings.AUTH_USER_MODEL
clas... | /charitydonation/views.py | from django.shortcuts import render
from django.views import View, generic
from .models import Donation, Institution, Category
from .forms import AddDonationForm
from django.contrib.auth import login, logout, authenticate, views
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.cont... | /donation/urls.py | """donation 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-base... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
DamienPond001/Udemy_API | refs/heads/master | {"/API/Section5/code/app.py": ["/API/Section7/code/security.py", "/API/Section6/code/NoDB/security.py"], "/API/Section6/code/UseDB/app.py": ["/API/Section7/code/security.py", "/API/Section6/code/UseDB/item.py", "/API/Section6/code/NoDB/security.py", "/API/Section9/1_recap_of_code/start/resources/user.py"], "/API/Sectio... | └──
├── API
│ ├── Section4
│ │ └── code
│ │ └── app.py
│ ├── Section5
│ │ └── code
│ │ └── app.py
│ ├── Section6
│ │ ├── code
│ │ │ ├── NoDB
│ │ │ │ └── security.py
│ │ │ └── UseDB
│ │ │ ├── app.py
│... | /API/Section4/code/app.py | '''This was created after installing virtualenv. This allows use to create a virtual environment that mimics
a fresh Python install. This ensures that any updates to packages don't affect previous applications built on previous package versions.
Run: conda create -n venv python=3.5.0 anaconda
to create a virtual env ... | /API/Section5/code/app.py | '''This was created after installing virtualenv. This allows use to create a virtual environment that mimics
a fresh Python install. This ensures that any updates to packages don't affect previous applications built on previous package versions.
Run: conda create -n venv python=3.5.0 anaconda
to create a virtual env ... | /API/Section6/code/NoDB/security.py | from user import User
from werkzeug.security import safe_str_cmp
#some database
users = [
User(1, "bob", "asdf"),
User(2, "Damien", "bitches")
]
#below allows us to find the user by username or ID without having to iterate over the above list
username_mapping = {u.username : u for u in users} #li... | /API/Section6/code/UseDB/app.py | '''This was created after installing virtualenv. This allows use to create a virtual environment that mimics
a fresh Python install. This ensures that any updates to packages don't affect previous applications built on previous package versions.
Run: conda create -n venv python=3.5.0 anaconda
to create a virtual env ... | /API/Section6/code/UseDB/item.py | from flask_restful import Resource, reqparse
from flask_jwt import jwt_required
import sqlite3
class Item(Resource):
parser = reqparse.RequestParser() #This prevents code duplication and now belongs to the Item class
parser.add_argument('price',
type = float,
... | /API/Section6/test.py | import sqlite3
connection = sqlite3.connect('data.db')
cursor = connection.cursor() #similar to a screen cursor, it allows us to selct and start thinigs. It executes the queries
create_table = "CREATE TABLE users (id int, username text, password text)"
cursor.execute(create_table)
user = (1, "damien", "bitches")... | /API/Section7/code/models/__init__.py | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 7 11:20:39 2018
@author: Damien
"""
| /API/Section7/code/security.py | from models.user import UserModel
from werkzeug.security import safe_str_cmp
def authenticate(username, password):
user = UserModel.find_by_username(username)
if user is not None and safe_str_cmp(user.password, password): #safe_str_cmp() alleviates issues with string comparison
return user
#identity ... | /API/Section9/1_recap_of_code/start/resources/user.py | from flask_restful import Resource, reqparse
from werkzeug.security import safe_str_cmp
from flask_jwt_extended import (
create_access_token,
create_refresh_token,
jwt_refresh_token_required,
get_jwt_identity
)
from models.user import UserModel
class UserRegister(Resource):
parser = ... | /API/app.py | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 24 15:04:52 2018
@author: Damien
"""
from flask import Flask
app = Flask(__name__) #unique __name__ - special python variable
#What requests we need to understand
@app.route('/') #http://www.google.com/ - '/' represents the home page [http://www.google.com/maps repr... | /API/storeapp.py | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 24 16:43:47 2018
@author: Damien
"""
from flask import Flask, jsonify, request, render_template
#NOTE on JSON: JSON are essentially dictionaries but in string format. Thus we need to convert of Python dicts to text
app = Flask(__name__) #unique __name__ - special pyt... | /Datacamp/A_B_testing.py | # Construct arrays of data: dems, reps
dems = np.array([True] * 153 + [False] * 91)
reps = np.array([True] * 136 + [False] * 35)
def frac_yea_dems(dems, reps):
"""Compute fraction of Democrat yea votes."""
frac = np.sum(dems) / len(dems)
return frac
# Acquire permutation samples: perm_replicates
perm_repl... | /Datacamp/EDA_ECDF.py | def ecdf(data):
"""Compute ECDF for a one-dimensional array of measurements."""
# Number of data points: n
n = len(data)
# x-data for the ECDF: x
x = np.sort(data)
# y-data for the ECDF: y
y = np.arange(1, n+1) / n
return x, y
# Compute ECDF for versicolor data: x_vers, y_vers
x_ver... | /Datacamp/EDA_boxplot_percentile.py | import numpy as np
np.mean(data)
np.median(data)
np.var(versicolor_petal_length)
np.std(versicolor_petal_length)
#covariance matrix:
# returns a 2D array where entries [0,1] and [1,0] are the covariances.
# Entry [0,0] is the variance of the data in x, and entry [1,1] is the variance of the data in y
np.cov(versicol... | /Datacamp/EDA_distributions.py | np.random.binomial(trails, probablity_of_success, size=number_of_reps)
np.random.poisson(average_rate, size=number_of_reps)
np.random.normal(mean, std, size=)
# Draw 100000 samples from Normal distribution with stds of interest: samples_std1, samples_std3, samples_std10
samples_std1 = np.random.normal(20,1,size=10000... | /Datacamp/Joining_data.py | #Row concatenation
row_concat = pd.concat([uber1, uber2, uber3])
#where each is a df
#Note though that the original row indices will be maintained
#Use the ignore_index = True to reset the indices in sequential order
#Use the axis =1 to do column concatenation
#If we have many files to concatenate:
# Import necessary... | /Datacamp/Reading_Data.py | #Basics of reading in:
filename = 'file.txt'
file = open(filename, mode = 'r') #'r' is top read, 'w' is to write
text = file.read()
file.close()
with open('huck_finn.txt', 'r') as file: #with is referred to as the context manager
print(file.read())
#Using NumPy - for numeric arrays
#This allows use o... | /Datacamp/SQL.py | SELECT * FROM table
SELECT COUNT(*) FROM table
#counts number of rows
SELECT DISTINCT row FROM table
#selects unique entries in row
SELECT COUNT(row) FROM table
#counts non-null entries
SELECT COUNT(DISTINCT row) FROM table
#returns count of distinct entries
SELECT * FROM table
WHERE column_value = 'some_value' #... | /Datacamp/Working_with_DB.py | # Import necessary module
from sqlalchemy import create_engine
import pandas as pd
# Create engine: engine
engine = create_engine('sqlite:///Chinook.sqlite')
# Save the table names to a list: table_names
table_names = engine.table_names()
# Print the table names to the shell
print(table_names)
#Executing a query
c... | /Datacamp/append_concatdf.py |
# Append names_1981 after names_1881 with ignore_index=True: combined_names
combined_names = names_1881.append(names_1981, ignore_index=True)
#ignore_index resets the index, else the indices from the original dfs are placed on top of one another
# Concatenate weather_max and weather_mean horizontally: weather
weathe... | /Datacamp/bokeh.py | # Import figure from bokeh.plotting
from bokeh.plotting import figure
# Import output_file and show from bokeh.io
from bokeh.io import output_file, show
# Create the figure: p
p = figure(x_axis_label='fertility (children per woman)', y_axis_label='female_literacy (% population)')
# Add a circle glyph to the figure p... | /Datacamp/bokeh_interaction.py | # Create a figure with the "box_select" tool: p
p = figure(x_axis_label='Year', y_axis_label='Time', tools='box_select')
# Add circle glyphs to the figure p with the selected and non-selected properties
p.circle('Year', 'Time', source=source,selection_color='red', nonselection_alpha=0.1)
# Specify the name of the out... | /Datacamp/bokeh_layouts.py | # Import row from bokeh.layouts
from bokeh.layouts import row, column
# Create the first figure: p1
p1 = figure(x_axis_label='fertility (children per woman)', y_axis_label='female_literacy (% population)')
# Add a circle glyph to p1
p1.circle('fertility', 'female_literacy', source=source)
# Create the second figure:... | /Datacamp/bokeh_linked_plots.py | #Link the ranges with panning
# Link the x_range of p2 to p1: p2.x_range
p2.x_range = p1.x_range
# Link the y_range of p2 to p1: p2.y_range
p2.y_range = p1.y_range
# Link the x_range of p3 to p1: p3.x_range
p3.x_range = p1.x_range
# Link the y_range of p4 to p1: p4.y_range
p4.y_range = p1.y_range
# Specify the name... | /Datacamp/bokeh_numpy_pandas.py |
# Import numpy as np
import numpy as np
# Create array using np.linspace: x
x = np.linspace(0,5,100)
# Create array using np.cos: y
y = np.cos(x)
# Add circles at x and y
p.circle(x,y)
# Specify the name of the output file and show the result
output_file('numpy.html')
show(p)
#pandas
# Import pandas as pd
import... | /Datacamp/bokeh_tooltips.py | # Add the first circle glyph to the figure p
p.circle('fertility', 'female_literacy', source=latin_america, size=10, color='red', legend='Latin America')
# Add the second circle glyph to the figure p
p.circle('fertility', 'female_literacy', source=africa, size=10, color='blue', legend='Africa')
# Assign the legend to... | /Datacamp/bootstrapping.py |
for i in range(50):
# Generate bootstrap sample: bs_sample
bs_sample = np.random.choice(rainfall, size=len(rainfall))
# Compute and plot ECDF from bootstrap sample
x, y = ecdf(bs_sample)
_ = plt.plot(x=x, y=y, marker='.', linestyle='none',
color='gray', alpha=0.1)
# Compute and p... | /Datacamp/data-types.py | # Convert the sex column to type 'category'
tips.sex = tips.sex.astype('category') #converting to categorical vars helps with memory and further analysis
# Convert the smoker column to type 'category'
tips.smoker = tips.smoker.astype('category')
# Print the info of tips
print(tips.info())
#sometimes we may need to ... | /Datacamp/data_explore.py | import pandas as pd
df = pd.read_csv('....')
df.head()
df.tail()
df.columns
df.shape
#Display summary stats of numeric columns
df.describe()
#Display frequencies of categorical columns
df['Borough'].value_counts(dropna=False)
#display means and counts of columns
df[['col1', 'col2']].count()
df[['col1', 'col2']].m... | /Datacamp/dataframe_arithmetic.py | # Extract selected columns from weather as new DataFrame: temps_f
temps_f = weather[['Min TemperatureF', 'Mean TemperatureF', 'Max TemperatureF']]
# Convert temps_f to celsius: temps_c
temps_c = (temps_f - 32) * 5/9 #broadcasting
# Rename 'F' in column names with 'C': temps_c.columns
temps_c.columns = ['Min Temperat... | /Datacamp/datetime_indices.py | #To read in
df = pd.read_csv('data.csv', parse_dates=True, index_col='Date)
# Prepare a format string: time_format
time_format = '%Y-%m-%d %H:%M'
# Convert date_list into a datetime object: my_datetimes
my_datetimes = pd.to_datetime(date_list, format=time_format)
# Construct a pandas Series using temperature_list ... | /Datacamp/grouby.py | # Group titanic by 'pclass'
by_class = titanic.groupby('pclass')
# Aggregate 'survived' column of by_class by count
count_by_class = by_class['survived'].count()
# Print count_by_class
print(count_by_class)
# Group titanic by 'embarked' and 'pclass'
by_mult = titanic.groupby(['embarked', 'pclass'])
# Aggregate 'sur... | /Datacamp/hypothesis_testing_with_one_dataset.py | # Make an array of translated impact forces: translated_force_b
translated_force_b = force_b - np.mean(force_b) + 0.55
# Take bootstrap replicates of Frog B's translated impact forces: bs_replicates
bs_replicates = draw_bs_reps(translated_force_b, np.mean, 10000)
# Compute fraction of replicates that are less than th... | /Datacamp/idxmax_idxmin.py | # Create the pivot table: medals_won_by_country
medals_won_by_country = medals.pivot_table(index = 'Edition', columns='NOC', values= "Athlete", aggfunc='count')
# Slice medals_won_by_country: cold_war_usa_urs_medals
cold_war_usa_urs_medals = medals_won_by_country.loc[1952:1988, ['USA','URS']]
NOC USA URS
Edi... | /Datacamp/indexing.py | #indexing as:
df[['...', '....']]
#returns a DataFrame
p_counties = election.loc['Perry':'Potter', :]
# Slice the row labels 'Potter' to 'Perry' in reverse order: p_counties_rev
p_counties_rev = election.loc['Potter':'Perry':-1, :]
# Slice the columns from the starting column to 'Obama': left_columns
left_columns = e... | /Datacamp/manipulating_indices.py | # Import pandas
import pandas as pd
# Read 'monthly_max_temp.csv' into a DataFrame: weather1
weather1 = pd.read_csv('monthly_max_temp.csv', index_col='Month')
# Print the head of weather1
print(weather1.head())
# Sort the index of weather1 in alphabetical order: weather2
weather2 = weather1.sort_index()
# Print the... | /Datacamp/melting.py | #melting restores pivoted dfs
visitors = pd.melt(visitors_by_city_weekday, id_vars=['weekday'], value_name='visitors')
#id_vars specify columns to maintain
#value_names specify name of column containing the values
# Set the new index: users_idx
users_idx = users.set_index(['city', 'weekday'])
# Print the users_idx D... | /Datacamp/merge_ordered.py | #Used for mereging when there is an ordering (eg dates)
# Perform the first ordered merge: tx_weather
tx_weather = pd.merge_ordered(austin, houston)
# Print tx_weather
print(tx_weather)
# Perform the second ordered merge: tx_weather_suff
tx_weather_suff = pd.merge_ordered(austin, houston, on='date', suffixes=['_aus'... | /Datacamp/merging.py | # Merge revenue with managers on 'city': merge_by_city
merge_by_city = pd.merge(revenue, managers, on='city')
# Print merge_by_city
print(merge_by_city)
# Merge revenue with managers on 'branch_id': merge_by_id
merge_by_id = pd.merge(revenue, managers, on='branch_id')
# Print merge_by_id
print(merge_by_id)
# Add 's... | /Datacamp/multi_indexing.py | #Sometimes we may want multiple row indexes in a heirachical order
# Set the index to be the columns ['state', 'month']: sales
sales = sales.set_index(['state', 'month'])
# Sort the MultiIndex: sales
sales = sales.sort_index()
sales =
eggs salt spam
state month
CA 1 47 12.... | /Datacamp/pandas.py | #Dataframes are made up of Series objects. Each Series is labelled 1D numpy array
import pandas as pd
#df is some DataFrame
df.head()
df.tail()
df.iloc[1, :]
df.loc['row_index', :]
#to return column info
df.info()
#to convert DataFrame to numpy array:
df.values
#note though that many numpy methods work on pandas d... | /Datacamp/parameter_optimisation.py | # Seed random number generator
np.random.seed(42)
# Compute mean no-hitter time: tau
tau = np.mean(nohitter_times)
# Draw out of an exponential distribution with parameter tau: inter_nohitter_time
inter_nohitter_time = np.random.exponential(tau, 100000)
# Plot the PDF and label axes
_ = plt.hist(inter_nohitter_time,... | /Datacamp/pivit_tables.py | #pivot tables aggregate data with duplicate indices
weekday city visitors signups
0 Sun Austin 139 7
1 Sun Dallas 237 12
2 Mon Austin 326 3
3 Mon Dallas 456 5
# Create the DataFrame with the appropriate pivot table: by_city_day
by_city_day ... | /Datacamp/pivoting_tables.py | #EG:
id treatment gender response
0 1 A F 5
1 2 A M 3
2 3 B F 8
3 4 B M 9
df.pivot(index = "treatment", columns = "gender", values = "response")
#pivot
gender F M
treatment
A 5 3
B 8 9
#Not s... | /Datacamp/readin_and_cleaning.py |
# Read in the data file with header=None: df_headers
df_headers = pd.read_csv(data_file, header=None)
# Print the output of df_headers.head()
print(df_headers.head())
# Split on the comma to create a list: column_labels_list
column_labels_list = column_labels.split(",")
# Assign the new column labels to the DataFra... | /Datacamp/resampling.py | #If a df is indexed by date-time, we can perform resampling.
#Downsampling is when we go to a lower unit, lower unit being one with fewer units in a period (lowere frequency)
#Downsample from hours to days
#Upsampling is the opposite and will introduce Nana, unless otherwise catered for through filling methods
# Down... | /Datacamp/seaborn.py | # Import plotting modules
import matplotlib.pyplot as plt
import seaborn as sns
# Plot a linear regression between 'weight' and 'hp'
sns.lmplot(x='weight', y='hp', data=auto)
# Display the plot
plt.show()
#RESIDUALS
# Import plotting modules
import matplotlib.pyplot as plt
import seaborn as sns
# Generate a green r... | /Datacamp/seaborn_multivariate.py | kind='scatter' uses a scatter plot of the data points
kind='reg' uses a regression plot (default order 1)
kind='resid' uses a residual plot
kind='kde' uses a kernel density estimate of the joint distribution
kind='hex' uses a hexbin plot of the joint distribution
# Generate a joint plot of 'hp' and 'mpg'
sns.jointplot... | /Datacamp/sqlalchemy.py | # Import create_engine
from sqlalchemy import create_engine
# Create an engine that connects to the census.sqlite file: engine
engine = create_engine('sqlite:///census.sqlite')# Create an engine to the census database
engine = create_engine('mysql+pymysql://'+'student:datacamp'+'@courses.csrrinzqubik.us-east-1.rds.ama... | /Datacamp/sqlalchemy_grouping_labeling.py |
# Build a query to count the distinct states values: stmt
stmt = select([func.count(census.columns.state.distinct())])
# Execute the query and store the scalar result: distinct_state_count
distinct_state_count = connection.execute(stmt).scalar()
# Print the distinct_state_count
print(distinct_state_count)
# Import ... | /Datacamp/sqlalchemy_joins.py | #IF a table has an already defined relationship:
# Build a statement to join census and state_fact tables: stmt
stmt = select([census.columns.pop2000, state_fact.columns.abbreviation])
# Execute the statement and get the first result: result
result = connection.execute(stmt).first()
# Loop over the keys in the result... | /Datacamp/sqlalchemy_more_statements.py | # Create a select query: stmt
stmt = select([census])
# Add a where clause to filter the results to only those for New York
stmt = stmt.where(census.columns.state == 'New York')
# Execute the query to retrieve all the data returned: results
results = connection.execute(stmt).fetchall()
# Loop over the results and pr... | /Datacamp/sqlalchemy_statements.py | # Import create_engine
from sqlalchemy import create_engine
# Create an engine that connects to the census.sqlite file: engine
engine = create_engine('sqlite:///census.sqlite')
connection = engine.connect()
# Build select statement for census table: stmt
stmt = "SELECT * FROM census"
# Execute the statement and fet... | /Datacamp/stack_unstack.py | #stack does something similar to pivot using the indices
# Unstack users by 'weekday': byweekday
users =
visitors signups
city weekday
Austin Mon 326 3
Sun 139 7
Dallas Mon 456 5
Sun 237 12
b... | /Datacamp/tidy_data.py | #Melting data is the process of turning columns of your data into rows of data.
airquality_melt = pd.melt(airquality_melt, id_vars=['Month', 'Day'])
#id_vars = columns not wishing to melt
#value_vars = columns wishing to melt (deafult to all not in id_vars)
#Pivoting data is the opposite of melting it.
airquality_piv... | /Datacamp/twitter_example.py | # Import package
import tweepy
# Store OAuth authentication credentials in relevant variables
access_token = "1092294848-aHN7DcRP9B4VMTQIhwqOYiB14YkW92fFO8k8EPy"
access_token_secret = "X4dHmhPfaksHcQ7SCbmZa2oYBBVSD2g8uIHXsp5CTaksx"
consumer_key = "nZ6EA0FxZ293SxGNg8g8aP0HM"
consumer_secret = "fJGEodwe3KiKUnsYJC3VRndj7... | /Datacamp/web_import.py | # Import package
from urllib.request import urlretrieve
# Import pandas
import pandas as pd
# Assign url of file: url
url = 'https://s3.amazonaws.com/assets.datacamp.com/production/course_1606/datasets/winequality-red.csv'
# Save file locally
urlretrieve(url, 'winequality-red.csv')
# Read file into a DataFrame and ... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
KagenLH/forme-app | refs/heads/main | {"/app/api/form_routes.py": ["/app/models/form.py", "/app/models/field.py"], "/app/models/__init__.py": ["/app/models/form.py", "/app/models/field.py"], "/app/seeds/fields.py": ["/app/models/form.py", "/app/models/field.py"], "/app/seeds/forms.py": ["/app/models/form.py"]} | └──
├── app
│ ├── api
│ │ ├── field_routes.py
│ │ └── form_routes.py
│ ├── forms
│ │ └── signup_form.py
│ ├── models
│ │ ├── __init__.py
│ │ ├── field.py
│ │ └── form.py
│ └── seeds
│ ├── fields.py
│ ├── forms.py
│ ... | /app/api/field_routes.py | # from flask import Blueprint, jsonify, request
# from flask_login import login_required
# from app.models import Field, db
# field_routes = Blueprint('fields', __name__)
# @field_routes.route('/', methods=['POST'])
# def fields():
# if request.method == 'POST':
# # get fields data from request body
# ... | /app/api/form_routes.py | from flask import Blueprint, jsonify, request, session
from flask_login import login_required, current_user
from app.models import Form, db, Field
form_routes = Blueprint("forms", __name__)
# get all forms --- remove this route?
@form_routes.route('/')
# @login_required
def get_forms():
forms = Form.query.all() ... | /app/forms/signup_form.py | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import Email, ValidationError, InputRequired, Length, EqualTo
from app.models import User
def user_exists(form, field):
# Checking if user exists
email = field.data
user = User.query.filter(User.email ==... | /app/models/__init__.py | from .db import db
from .user import User
from .form import Form
from .field import Field
| /app/models/field.py | from .db import db
class Field(db.Model):
__tablename__ = 'fields'
id = db.Column(db.Integer, primary_key=True)
type = db.Column(db.String(255), nullable=False)
label = db.Column(db.String(55), nullable=False)
max_length = db.Column(db.Integer)
required = db.Column(db.Boolean, nullable=False)... | /app/models/form.py | from .db import db
class Form(db.Model):
__tablename__ = 'forms'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50), nullable=False)
owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
description = db.Column(db.Text)
label_placement = db.Colu... | /app/seeds/fields.py | from app.models import db, Field
from app.models import Form
def seed_fields():
form = Form(
title='To Test Fields',
owner_id=1
)
db.session.add(form)
testField = Field(
type="text",
label="Test Field",
required=False,
form=form, # creates the form_id ... | /app/seeds/forms.py | from app.models import db, Form
def seed_forms():
test = Form(
title = "Test Form Render",
owner_id = 1,
description = "",
label_placement = "",
description_align = "",
title_align = "",
)
db.session.add(test)
db.session.commit()... | /app/seeds/users.py | from app.models import db, User
# Adds a demo user, you can add other users here if you want
def seed_users():
demo = User(
username='Demo', email='demo@aa.io', password='password')
marnie = User(
username='marnie', email='marnie@aa.io', password='password')
bobbie = User(
username... | /migrations/versions/20210816_135552_.py | """empty message
Revision ID: fa590b961f4f
Revises: ffdc0a98111c
Create Date: 2021-08-16 13:55:52.581549
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'fa590b961f4f'
down_revision = 'ffdc0a98111c'
branch_labels = None
depends_on = None
def upgrade():
# ... | /migrations/versions/20210820_100009_.py | """empty message
Revision ID: beeeac90e4ba
Revises: d25f4d1b7ea0
Create Date: 2021-08-20 10:00:09.924819
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'beeeac90e4ba'
down_revision = 'd25f4d1b7ea0'
branch_labels = None
depends_on = None
def upgrade():
# ... | /migrations/versions/20210820_100524_.py | """empty message
Revision ID: b8ec5632d693
Revises: beeeac90e4ba
Create Date: 2021-08-20 10:05:24.638509
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b8ec5632d693'
down_revision = 'beeeac90e4ba'
branch_labels = None
depends_on = None
def upgrade():
# ... | /migrations/versions/20210820_103408_.py | """empty message
Revision ID: b05fdd14ae4f
Revises: 4563136888fd
Create Date: 2021-08-20 10:34:08.171553
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b05fdd14ae4f'
down_revision = '4563136888fd'
branch_labels = None
depends_on = None
def upgrade():
# ... | /migrations/versions/20210820_133516_.py | """empty message
Revision ID: b3e721c02f48
Revises: 9aec744a6b98
Create Date: 2021-08-20 13:35:16.871785
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b3e721c02f48'
down_revision = '9aec744a6b98'
branch_labels = None
depends_on = None
def upgrade():
# ... | /migrations/versions/20210820_171546_.py | """empty message
Revision ID: 94f5eda37179
Revises: b3e721c02f48
Create Date: 2021-08-20 17:15:46.455809
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '94f5eda37179'
down_revision = 'b3e721c02f48'
branch_labels = None
depends_on = None
def upgrade():
# ... | /migrations/versions/20210821_113310_.py | """empty message
Revision ID: d0c387e43ca4
Revises: 94f5eda37179
Create Date: 2021-08-21 11:33:10.206199
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd0c387e43ca4'
down_revision = '94f5eda37179'
branch_labels = None
depends_on = None
def upgrade():
# ... | /migrations/versions/20210821_145311_.py | """empty message
Revision ID: 2453c767d036
Revises: d0c387e43ca4
Create Date: 2021-08-21 14:53:11.208418
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2453c767d036'
down_revision = 'd0c387e43ca4'
branch_labels = None
depends_on = None
def upgrade():
# ... | /migrations/versions/20210821_161057_.py | """empty message
Revision ID: 4df12f583573
Revises: 2453c767d036
Create Date: 2021-08-21 16:10:57.556468
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '4df12f583573'
down_revision = '2453c767d036'
branch_labels = None
depends_on = None
def upgrade():
# ... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
folmez/Handsfree-KGS | refs/heads/master | {"/src/__init__.py": ["/src/picture_actions.py", "/src/screenshot_actions.py", "/src/mouse_actions.py"]} | └──
├── auto_goban_detection.py
├── make_goban_speak.py
├── play_handsfree_GO.py
├── setup.py
├── src
│ ├── __init__.py
│ ├── cam_actions.py
│ ├── mouse_actions.py
│ ├── picture_actions.py
│ └── screenshot_actions.py
├── temp
│ ├── plot_save_coordinates_on_cl... | /auto_goban_detection.py | import matplotlib.pyplot as plt
import imageio
import numpy as np
import src
IMG_PATH = 'images/empty_pyshical_goban1.png'
board_corners = []
def onclick(event):
print(event.xdata, event.ydata)
board_corners.append((event.xdata, event.ydata))
# Get RGB matrix of the picture with goban
rgb = imageio.imread(IM... | /make_goban_speak.py | import src
import time
UL_x, UL_y, goban_step = src.get_goban_corners()
prev_stone_set = set()
print("Started scanning the board for moves every 5 seconds...")
while True:
# wait between screenshots
time.sleep(5)
# get board screenshot
board_rgb_screenshot = src.KGS_goban_rgb_screenshot(UL_x, UL_y, go... | /play_handsfree_GO.py | from pynput.mouse import Button, Controller
import cv2
import imageio
import matplotlib.pyplot as plt
import threading
import time
import queue
import os
import numpy as np
import src
frames = queue.Queue(maxsize=10)
class frameGrabber(threading.Thread):
def __init__(self):
# Constructor
threading... | /setup.py | from setuptools import setup, find_packages
setup( name='Handsfree-KGS',
version='0.0',
description='Pay Handsfree Go on KGS',
author='Fatih Olmez',
author_email='folmez@gmail.com',
packages=find_packages())
| /src/__init__.py | from .mouse_actions import get_goban_corners, str_to_integer_coordinates
from .mouse_actions import int_coords_to_screen_coordinates, make_the_move
from .mouse_actions import int_coords_to_str
from .screenshot_actions import KGS_goban_rgb_screenshot, get_digital_goban_state
from .picture_actions import plot_goban_rgb, ... | /src/cam_actions.py | import imageio
def get_pyhsical_goban_state(rgb_pix):
pass
def picture_to_rgb(path):
return misc.imageio(path)
| /src/mouse_actions.py | from pynput.mouse import Button, Controller
import src
import time
def get_goban_corners():
# Obtain mouse controller
mouse = Controller()
# Ask the user to define goban corners
print('Move cursor to upper-left (A19) corner of Goban and keep it there five seconds')
time.sleep(5)
(UL_x, UL_y) =... | /src/picture_actions.py | import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import argrelmin
import imageio
import src
def play_next_move_on_digital_board(mouse, color, i, j, bxy, wxy, \
UL_x, UL_y, goban_step):
if color is not None:
print(f"New move: {color} playe... | /src/screenshot_actions.py | import pyscreeze
import numpy as np
import matplotlib.pyplot as plt
import src
def get_digital_goban_state(rgb_pix, plot_stuff=False):
# RGB of Black = [ 0, 0, 0]
# RGB of White = [255, 255, 255]
# RGB of Orange = [255, 160, 16]
# Use red scale to find out black stones, blue scale to find out whit... | /temp/plot_save_coordinates_on_click.py | import matplotlib.pyplot as plt
xy=[]
def onclick(event):
print(event.xdata, event.ydata)
xy.append((event.xdata, event.ydata))
fig = plt.figure()
plt.plot(range(10))
fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
print(xy)
| /temp/process_pyhsical_goban_pic.py | import matplotlib.pyplot as plt
import imageio
import numpy as np
import src
IMG_PATH = 'images/pyshical_goban_pic1.png'
#IMG_PATH = 'images/pyshical_goban_pic2.png'
#IMG_PATH = 'images/pyshical_goban_pic3.png'
UL_outer_x, UL_outer_y = 315, 24
UR_outer_x, UR_outer_y = 999, 40
BL_outer_x, BL_outer_y = 3, 585
BR_outer_x... | /tests/test_mouse_actions.py | from pynput.mouse import Button, Controller
import time
import sys
import os
import pytest
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import src
def test_str_to_integer_coordinates():
assert src.str_to_integer_coordinates('A19') == (1, 1)
assert src.str_to_integer_coord... | /tests/test_picture_actions.py | import pytest
import imageio
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import src
# stones - upper-left corner is (1,1), lower-left corner is (19,1)
IMG_PATH = ['images/pyshical_goban_pic1.png', 'images/pyshical_goban_pic2.png', \
'images/pyshical_gob... | /tests/test_play_handsfree_GO.py | import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from pynput.mouse import Button, Controller
import pytest
import imageio
import src
# Write a test of play_handsfree_GO.py using already existing frames
img_name = []
folder_name = 'images/sample_game_log/ex1/'
# empty b... | /tests/test_screenshot_actions.py | import imageio
import pytest
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import src
def test_get_digital_goban_state():
rgb_pix = imageio.imread('images/digital_goban.png')
# Process KGS goban grayscale and find the stones
assert src.get_digital_goban_... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
jessehylton/Podrum | refs/heads/master | {"/src/podrum/nbt/NBT.py": ["/src/podrum/nbt/tag/NamedTag.py"], "/src/podrum/network/PacketPool.py": ["/src/podrum/network/protocol/ResourcePacksInfoPacket.py", "/src/podrum/network/protocol/ServerToClientHandshakePacket.py", "/src/podrum/network/protocol/ClientToServerHandshakePacket.py", "/src/podrum/network/protocol... | └──
└── src
└── podrum
├── Player.py
├── Podrum.py
├── Server.py
├── command
│ └── Command.py
├── math
│ └── Facing.py
├── nbt
│ ├── NBT.py
│ └── tag
│ └── Named... | /src/podrum/Player.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public Lice... | /src/podrum/Podrum.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Pub... | /src/podrum/Server.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Pub... | /src/podrum/command/Command.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public Lice... | /src/podrum/math/Facing.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public Lice... | /src/podrum/nbt/NBT.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public Lice... | /src/podrum/nbt/tag/NamedTag.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public Lice... | /src/podrum/network/PacketPool.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public Lice... | /src/podrum/network/protocol/ClientToServerHandshakePacket.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public Lice... | /src/podrum/network/protocol/DisconnectPacket.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public Lice... | /src/podrum/network/protocol/ResourcePacksInfoPacket.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public Lice... | /src/podrum/network/protocol/ServerToClientHandshakePacket.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public Lice... | /src/podrum/resourcepacks/ResourcePack.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public Lice... | /src/podrum/utils/Binary.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public Lice... | /src/podrum/utils/BinaryStream.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public Lice... | /src/podrum/utils/Config.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU L... | /src/podrum/utils/Logger.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU L... | /src/podrum/utils/UUID.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public Lice... | /src/podrum/utils/Utils.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU L... | /src/podrum/utils/bcmath.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public Lice... | /src/podrum/wizard/Parser.py | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of t... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
ddward/ansible | refs/heads/master | {"/app.py": ["/db.py", "/user.py", "/build_dir.py"], "/user.py": ["/db.py"]} | └──
├── app.py
├── build_dir.py
├── db.py
├── penetrationTesting.py
├── sanitize_path.py
└── user.py | /app.py | from cryptography.fernet import Fernet
import datetime
from flask import (flash, Flask, g, Markup, redirect, render_template, request,
send_from_directory, session, url_for)
import functools
import logging
import os
from secrets import token_urlsafe
import sqlite3
import sys
from werkzeug.utils import secure_filena... | /build_dir.py | # build_dir.py
import os
def build_dir(curPath):
directoryDict = {}
with os.scandir(curPath) as directory:
for entry in directory:
#dont include shortcuts and hidden files
if not entry.name.startswith('.'):
#stat dict reference:
#https://docs.pyt... | /db.py | from getpass import getpass
import os
import sqlite3
from werkzeug.security import generate_password_hash
from flask import g
import traceback
import logging
path = os.getcwd()
DATABASE = os.path.join(path, 'ansible.db')
def init_db():
with app.app_context():
db = sqlite3.connect(DATABASE)
with ap... | /penetrationTesting.py | from bs4 import BeautifulSoup
import getpass
import requests
import os
def pTest(attack_string, attack_url, password):
payload = {'password': password}
with requests.Session() as s:
p = s.post(attack_url + 'login', data=payload)
r = requests.Request('GET', attack_url)
prepared = s.prepa... | /sanitize_path.py | import re
def sanitize(path):
# escape nasty double-dots
path = re.sub(r'\.\.', '', path)
# then remove any duplicate slashes
path = re.sub(r'(/)\1+', r'\1', path)
# then remove any leading slashes and dots
while(path and (path[0] == '/' or path[0] == '.')):
path = path[1:]
return p... | /user.py | from db import insert, exists, select_one, update
from werkzeug.security import check_password_hash, generate_password_hash
import logging
import traceback
def create_user(username,password):
try:
formattedUsername = format_username(username)
hashedPassword = generate_password_hash(password)
... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
MatheusLealAquino/meuCanal | refs/heads/master | {"/conteudo/forms.py": ["/conteudo/models.py"], "/conteudo/views.py": ["/conteudo/models.py"]} | └──
├── conteudo
│ ├── forms.py
│ ├── models.py
│ ├── urls.py
│ └── views.py
├── login
│ ├── urls.py
│ └── views.py
└── projeto
└── views.py | /conteudo/forms.py | from django import forms
from conteudo.models import Video, Categoria
class VideoForm(forms.ModelForm):
error_messages = {
'campo invalido' : "Campo inválido"
}
class Meta:
model = Video
fields = ('video_id','categoria', 'nome', 'url', 'capa', 'visualizacao', 'nota', 'sinopse')
... | /conteudo/models.py | from django.db import models
class Categoria(models.Model):
nome = models.CharField(max_length=255, db_index=True)
slug = models.SlugField(max_length=200)
class Meta:
ordering = ('nome',)
verbose_name = 'categoria'
verbose_name_plural = 'categorias'
def __str__(self):
... | /conteudo/urls.py | from django.urls import path
from conteudo import views
app_name = 'conteudo'
urlpatterns = [
path('', views.exibir_catalogo, name='catalogo'),
path('cadastro_video/', views.cadastro_video, name='cadastro_video'),
path('editar_video/<int:id>/', views.editar_video, name='editar_video'),
path('<int:id>/... | /conteudo/views.py | from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render, redirect, get_object_or_404
from conteudo.models import Video, Categoria
def exibir_catalogo(request):
categorias = Categoria.objects.all()
return render(request, 'conteudo/catalogo_videos.html', {'ca... | /login/urls.py | from django.urls import path
from login import views
app_name = 'login'
urlpatterns = [
path('', views.pagina_login, name='pagina_login'),
] | /login/views.py | from django.shortcuts import render
def pagina_login(request):
return render(request, 'login/pagina_login.html')
| /projeto/views.py | from django.shortcuts import render
def pagina_inicial(request):
return render(request, 'index.html') | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
paolapilar/juegos | refs/heads/master | {"/main.py": ["/snake.py", "/collectables.py"], "/world.py": ["/snake.py", "/base.py", "/collectables.py"]} | └──
├── base.py
├── collectables.py
├── main.py
├── screen.py
├── snake.py
├── utils.py
└── world.py | /base.py |
import math
import utils
class Entity( object ) :
def __init__( self, i, j, di, dj, cellSize, canvasWidth, canvasHeight ) :
super( Entity, self ).__init__()
self.i = i
self.j = j
self._cellSize = cellSize
self._canvasWidth = canvasWidth
self._canvasHeight = canva... | /collectables.py |
import pygame
import base
class Apple( base.Entity ) :
def __init__( self, i, j, cellSize, canvasWidth, canvasHeight ) :
super( Apple, self ).__init__( i, j, 1, 1, cellSize, canvasWidth, canvasHeight )
self._color = ( 255, 255, 0 )
self._alive = True
def draw( self, canvas ) :
... | /main.py |
import pygame
import random
import time
from snake import Snake
from collectables import Apple
import screen
class Game :
def __init__( self ) :
pygame.init()
self._canvasWidth = 800
self._canvasHeight = 600
self._canvas = pygame.display.set_mode( ( self._canvasWidth, self._canv... | /screen.py |
import pygame
import world
class Text( object ) :
def __init__( self, x, y, message, size, color ) :
super( Text, self).__init__()
self._message = message
self._textFont = pygame.font.Font( None, size )
self._textSurface = self._textFont.render( message, True, color )
sel... | /snake.py |
import pygame
import base
from collections import deque
class SnakePart( base.Entity ) :
def __init__( self, i, j, color, cellSize, canvasWidth, canvasHeight ) :
super( SnakePart, self ).__init__( i, j, 1, 1, cellSize, canvasWidth, canvasHeight )
self.color = color
self.lasti = i
... | /utils.py |
import math
def grid2screen( i, j, cellSize, canvasWidth, canvasHeight ) :
x = ( i + 0.5 ) * cellSize
y = canvasHeight - ( j + 0.5 ) * cellSize
return x, y
def screen2grid( x, y, cellSize, canvasWidth, canvasHeight ) :
i = math.floor( x / cellSize - 0.5 )
j = math.floor( ( canvasHeight - y ) / ce... | /world.py |
import math
import random
import pygame
from base import Entity
from snake import Snake
from collectables import Apple
class Obstacle( Entity ) :
def __init__( self, i, j, di, dj, cellSize, canvasWidth, canvasHeight ) :
super( Obstacle, self ).__init__( i, j, di, dj, cellSize, canvasWidth, canvasHeight ... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
darshanime/scrapy-tutorials | refs/heads/master | {"/housing/housing/spiders/housing_spider.py": ["/housing/housing/items.py"], "/scrapy 101/scrapy101/spiders/dmoz.py": ["/scrapy 101/scrapy101/items.py"], "/cardekho/cardekho/spiders/cardekho_spider.py": ["/cardekho/cardekho/items.py"]} | └──
├── cardekho
│ └── cardekho
│ ├── items.py
│ └── spiders
│ └── cardekho_spider.py
├── housing
│ └── housing
│ ├── items.py
│ └── spiders
│ └── housing_spider.py
└── scrapy 101
└── scrapy101
├── items.py
... | /cardekho/cardekho/items.py | from scrapy import Item, Field
class CardekhoItem(Item):
title = Field()
price = Field()
distance = Field() | /cardekho/cardekho/spiders/cardekho_spider.py | from cardekho.items import CardekhoItem
from scrapy import Spider
from scrapy.http.request import Request
class CardekhoSpider(Spider):
name = "cardekho"
allowed_domains = ["http://www.cardekho.com"]
start_urls = ["http://www.cardekho.com/used-cars+in+mumbai-all/"]
#This is to not get redirected b... | /housing/housing/items.py | from scrapy import Item, Field
class HousingItemBuy(Item):
ad_id = Field()
ad_title = Field()
ad_price = Field()
ad_area = Field()
ad_url = Field()
ad_date_added = Field()
ad_coordinates = Field()
ad_bedrooms = Field()
ad_toilets = Field()
ad_gas_pipeline = Field()
ad_lift =... | /housing/housing/spiders/housing_spider.py | from housing.items import HousingItemBuy
from scrapy import Spider
from scrapy.http.request import Request
#To parse the JSON received
import json
class HousingSpider(Spider):
name = "housing"
allowed_domains = ["housing.com"]
custom_settings = {'USER_AGENT' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10... | /scrapy 101/scrapy101/items.py | from scrapy import Item, Field
class Scrapy101Item(Item):
title = Field() | /scrapy 101/scrapy101/spiders/dmoz.py | from scrapy.spiders import BaseSpider
from scrapy101.items import Scrapy101Item
class Scrapy101Spider(BaseSpider):
name = "dmoz"
allowed_domains = ["dmoz.org/"]
start_urls = ["http://www.dmoz.org/"]
def parse(self, response):
for div in response.xpath('/html/body/div[3]/div[3]/div[1]/div')... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
gausszh/sae_site | refs/heads/master | {"/views/blog.py": ["/utils/blog_cache.py", "/models/blog.py"], "/utils/__init__.py": ["/models/base.py"], "/utils/user_cache.py": ["/models/base.py", "/models/blog.py", "/utils/__init__.py"], "/views/base.py": ["/models/base.py"], "/utils/blog_cache.py": ["/utils/__init__.py"]} | └──
├── configs
│ └── settings_dev.py
├── flask_app.py
├── models
│ ├── __init__.py
│ ├── base.py
│ └── blog.py
├── utils
│ ├── __init__.py
│ ├── blog_cache.py
│ ├── filters.py
│ └── user_cache.py
└── views
├── base.py
├── blog.py
... | /configs/settings_dev.py | #coding=utf8
import os
# system setting
DEBUG = True
APP_HOST = '127.0.0.1'
APP_PORT = 7020
STORAGE_BUCKET_DOMAIN_NAME = 'blogimg'
# database
if os.environ.get('SERVER_SOFTWARE'):#线上
import sae
DB_SAE_URI = 'mysql://%s:%s@%s:%s/database_name' % (sae.const.MYSQL_USER,
sae.const.MYSQL_PASS, sae.const.MYSQL... | /flask_app.py | #!/usr/bin/python
# coding=utf8
from flask import Flask, render_template, g
import flask_login
from configs import settings
from utils.filters import JINJA2_FILTERS
from utils import user_cache
from views import blog, base, security
def create_app(debug=settings.DEBUG):
app = Flask(__name__)
... | /models/__init__.py | #coding=utf-8
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from configs import settings
sae_engine = create_engine(settings.DB_SAE_URI+'?charset=utf8', encoding='utf-8',
convert_unicode=True, pool_recycle=settings.DB_POOL_RECYC... | /models/base.py | #coding=utf8
"""
基础类--用户信息
"""
from sqlalchemy import (
MetaData, Table, Column, Integer, BigInteger, Float, String, Text, DateTime,
ForeignKey, Date, UniqueConstraint)
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from models import sae_engine
from models im... | /models/blog.py | #!/usr/bin/python
#coding=utf8
import datetime
from sqlalchemy import (
MetaData, Table, Column, Integer, BigInteger, Float, String, Text, DateTime,
ForeignKey, Date, UniqueConstraint)
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from models import sae_engin... | /utils/__init__.py | #coding=utf8
import datetime
import redis
import flask_login
from models.base import User, create_session
from utils import user_cache
from configs import settings
def AnonymousUserMixin():
'''
This is the default object for representing an anonymous user.
'''
session = create_session()
user = ... | /utils/blog_cache.py | # coding=utf8
from configs import settings
from utils import redis_connection
APP = "blog"
def set_draft_blog(uid, markdown):
_cache = redis_connection()
key = str("%s:draft:blog:%s" % (APP, uid))
_cache.set(key, markdown, settings.DRAFT_BLOG_TIMEOUT)
| /utils/filters.py | # coding=utf8
"""
jinja2的过滤器
"""
import markdown
def md2html(md):
"""
@param {unicode} md
@return {unicode html}
"""
return markdown.markdown(md, ['extra', 'codehilite', 'toc', 'nl2br'], safe_mode="escape")
JINJA2_FILTERS = {
'md2html': md2html,
}
| /utils/user_cache.py | # coding=utf8
try:
import simplejson as json
except Exception:
import json
import datetime
from sqlalchemy.sql import or_
from models.base import create_session, User
from models.blog import BlogArticle
from configs import settings
from utils import redis_connection
# import sae.kvdb
APP = "base"
def get_u... | /views/base.py | #coding=utf8
import datetime
from flask import Blueprint, request, jsonify, render_template, redirect
import flask_login
import weibo as sinaweibo
from models.base import create_session, User
from utils import user_cache
from configs import settings
bp_base = Blueprint('base', __name__, url_prefix='/base')
@bp_b... | /views/blog.py | # coding=utf8
import datetime
import urllib
from flask import Blueprint, request, jsonify, render_template, g
import flask_login
from sae.storage import Bucket
from models.blog import create_session, BlogArticle
from utils.blog_cache import set_draft_blog
from configs import settings
bp_blog = Blueprin... | /views/security.py | # coding=utf8
"""
学web安全用到的一些页面
"""
from flask import Blueprint, render_template
from sae.storage import Bucket
from configs import settings
bp_security = Blueprint('security', __name__, url_prefix='/security')
bucket = Bucket(settings.STORAGE_BUCKET_DOMAIN_NAME)
bucket.put()
@bp_security.route('/wanbo/video/')
de... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
liuchao012/myPythonWeb | refs/heads/master | {"/functional_tests/test_simple_list_creation.py": ["/functional_tests/base.py"], "/functional_tests/tests_layout_and_styling.py": ["/functional_tests/base.py"], "/functional_tests/tests_list_item_validation.py": ["/functional_tests/base.py"], "/test/listsss/tests_models.py": ["/listsss/views.py"], "/test/listsss/tests... | └──
├── functional_tests
│ ├── __init__.py
│ ├── base.py
│ ├── test_simple_list_creation.py
│ ├── tests_layout_and_styling.py
│ └── tests_list_item_validation.py
├── listsss
│ ├── apps.py
│ └── views.py
└── test
└── listsss
├── tests_models.py
... | /functional_tests/__init__.py | # -*- coding: utf-8 -*-
# @Time : 2018/6/28 17:06
# @Author : Mat
# @Email : mat_wu@163.com
# @File : __init__.py.py
# @Software: PyCharm
'''
functional_tests,中的文件需要已tests开头系统命令才能读取到测试用例并执行测试
测试执行命令python manage.py test functional_tests,来完成功能测试
如果执行 python manage.py test 那么django 将会执行 功能测试和单元测试
如果想只运行单元测... | /functional_tests/base.py | # -*- coding: utf-8 -*-
# @Time : 2018/6/25 20:15
# @Author : Mat
# @Email : mat_wu@163.com
# @File : functional_tests1.py
# @Software: PyCharm
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from django.test import LiveServerTestCase
from django.contrib.staticfiles.testing impo... | /functional_tests/test_simple_list_creation.py | # -*- coding: utf-8 -*-
# @Time : 2018/6/25 20:15
# @Author : Mat
# @Email : mat_wu@163.com
# @File : functional_tests1.py
# @Software: PyCharm
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from django.test import LiveServerTestCase
from django.contrib.staticfiles.testing impo... | /functional_tests/tests_layout_and_styling.py | # -*- coding: utf-8 -*-
# @Time : 2018/6/25 20:15
# @Author : Mat
# @Email : mat_wu@163.com
# @File : functional_tests1.py
# @Software: PyCharm
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from django.test import LiveServerTestCase
from django.contrib.staticfiles.testing impo... | /functional_tests/tests_list_item_validation.py | # -*- coding: utf-8 -*-
# @Time : 2018/6/25 20:15
# @Author : Mat
# @Email : mat_wu@163.com
# @File : functional_tests1.py
# @Software: PyCharm
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from django.test import LiveServerTestCase
from django.contrib.staticfiles.testing impo... | /listsss/apps.py | from django.apps import AppConfig
class ListsssConfig(AppConfig):
name = 'listsss'
| /listsss/views.py | from django.shortcuts import render, redirect # redirect是python的重定向方法
from django.http import HttpResponse
from listsss.models import Item, List
from django.core.exceptions import ValidationError
# Create your views here.
def home_page(request):
# return HttpResponse("<html><title>To-Do lists</title></html>")
... | /test/listsss/tests_models.py | from django.test import TestCase
from django.urls import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from listsss.models import Item, List
from listsss.views import home_page
import unittest
from django.core.exceptions import ValidationError
class ListAndItemModelsTe... | /test/listsss/tests_views.py | from django.test import TestCase
from django.urls import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.utils.html import escape
from listsss.models import Item, List
from listsss.views import home_page
import unittest
# Create your tests here.
class HomePa... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
daphnejwang/MentoreeMatch | refs/heads/master | {"/Project/endorsements.py": ["/Project/tabledef.py"], "/Project/email_module.py": ["/Project/tabledef.py"], "/Project/linkedin.py": ["/Project/tabledef.py"], "/Project/main.py": ["/Project/tabledef.py"], "/Project/search.py": ["/Project/tabledef.py"], "/Project/topic_seed.py": ["/Project/tabledef.py"]} | └──
├── Project
│ ├── email_.py
│ ├── email_module.py
│ ├── endorsements.py
│ ├── linkedin.py
│ ├── main.py
│ ├── mentorsearch.py
│ ├── search.py
│ ├── tabledef.py
│ └── topic_seed.py
└── server.py | /Project/email_.py | #import tabledef
#from tabledef import User, MentoreeTopic, Topic
import requests
print requests
# import pdb
# def send_message(recipient, subject, text):
# return requests.post(
# "https://api.mailgun.net/v2/samples.mailgun.org/messages",
# auth=("api", "key-21q1narswc35vqr1u3f9upn3vf6ncbb9"),
#... | /Project/email_module.py | import tabledef
from tabledef import User, MentoreeTopic, Topic, Email
import requests
import sqlalchemy
from sqlalchemy import update
import datetime
from flask import Flask, render_template, redirect, jsonify, request, flash, url_for, session
# import pdb
def save_email_info_to_database(sender, mentor, subject, sub... | /Project/endorsements.py | import tabledef
from tabledef import User, MentoreeTopic, Topic, Email, Endorsement
import requests
import sqlalchemy
from sqlalchemy import update
import datetime
from flask import Flask, render_template, redirect, jsonify, request, flash, url_for, session
# import pdb
def save_endorsement_info_to_database(sender, m... | /Project/linkedin.py | from flask_oauthlib.client import OAuth
from flask import Flask, render_template, redirect, jsonify, request, flash, url_for, session
import jinja2
import tabledef
from tabledef import *
from sqlalchemy import update
from xml.dom.minidom import parseString
import os
import urllib
import json
from Project import app
imp... | /Project/main.py | from flask_oauthlib.client import OAuth
from flask import Flask, render_template, redirect, jsonify, request, flash, url_for, session
import jinja2
import tabledef
import search
from tabledef import User, MentoreeTopic, Topic
import linkedin
from xml.dom.minidom import parseString
from Project import app
import json
fr... | /Project/mentorsearch.py | # from flask import Flask, render_template, redirect, request, flash, url_for, session
# import jinja2
# import tabledef
# from tabledef import Users, MentorCareer, MentorSkills
# from xml.dom.minidom import parseString
# import os
# import urllib
# app = Flask(__name__)
# app.secret_key = "topsecretkey"
# app.jinja_e... | /Project/search.py | from flask_oauthlib.client import OAuth
from flask import Flask, render_template, redirect, jsonify, request, flash, url_for, session
import jinja2
import tabledef
from tabledef import User, MentoreeTopic, Topic
import linkedin
from xml.dom.minidom import parseString
import pdb
# from Project import app
def search(sea... | /Project/tabledef.py | from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String, Boolean, Text, DateTime
from sqlalchemy.orm import sessionmaker
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.orm import sessi... | /Project/topic_seed.py | import tabledef
from tabledef import Topic
TOPICS = {1: "Arts & Crafts",
2: "Career & Business",
3: "Community & Environment",
4: "Education & Learning",
5: "Fitness",
6: "Food & Drinks",
7: "Health & Well Being",
8: "Language & Ethnic Identity",
9: "Life Experiences",
10: "Literature & Writing",
1... | /server.py | from Project import app
# app.run(debug=True)
app.run(debug=True)
app.secret_key = 'development'
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
enverbashirov/YOLOv3-mMwave-Radar | refs/heads/master | {"/dataprep/truth.py": ["/dataprep/util.py", "/dataprep/kalman_tracker.py"], "/yolo/__init__.py": ["/yolo/train.py", "/yolo/predict.py"], "/dataprep/__init__.py": ["/dataprep/channel_extraction.py", "/dataprep/truth.py", "/dataprep/processing.py"], "/yolo/predict.py": ["/yolo/darknet.py"], "/yolo/train.py": ["/yolo/dar... | └──
├── __main__.py
├── dataprep
│ ├── __init__.py
│ ├── channel_extraction.py
│ ├── kalman_tracker.py
│ ├── processing.py
│ ├── truth.py
│ └── util.py
├── test.py
└── yolo
├── __init__.py
├── darknet.py
├── dataset.py
├── predict.py
... | /__main__.py | import argparse
import sys
import yolo
import dataprep
def parse_arg():
parser = argparse.ArgumentParser(description='mmWave YOLOv3', add_help=True,
usage='''python . <action> [<args>]
Actions:
train Network training module
predict Object detection module
... | /dataprep/__init__.py | import argparse
import sys, gc
from .channel_extraction import chext
from .processing import proc
from .truth import truth
def parse_arg():
parser = argparse.ArgumentParser(description='Data preprocessing module', add_help=True)
parser.add_argument('--pathin', type=str, required=True,
help="Path for ... | /dataprep/channel_extraction.py | import h5py
import numpy as np
import os, shutil
def chext(args):
rawpath = f'raw/{args.pathin}'
savepath = f'dataset/{args.pathout}/chext' if args.pathout else f'dataset/{args.pathin}/chext'
print(f'[LOG] ChExt | Starting: {args.pathin}')
# Create the subsequent save folders
# if os.path.isdir(sa... | /dataprep/kalman_tracker.py | import matplotlib.animation as animation
import numpy as np
import scipy as sp
from matplotlib import pyplot as plt
class KalmanTracker:
def __init__(self, id_, s0=None, disable_rejection_check=False):
# Filter-related parameters
self.dt = 66.667e-3 # T_int of the radar TX
# s... | /dataprep/processing.py | import os, shutil, gc
from argparse import ArgumentParser
from time import sleep
import h5py
import numpy as np
import scipy as sp
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy import io, signal
from scipy.signal.windows import nuttall, taylor
from .util import *
def proc(ar... | /dataprep/truth.py | import os
# import shutil, time, pickle
# from argparse import ArgumentParser
# import matplotlib
import matplotlib.patches as patches
from matplotlib import pyplot as plt
# from matplotlib import rc
import numpy as np
from sklearn.cluster import DBSCAN
# from .channel_extraction import ChannelExtraction
from .util i... | /dataprep/util.py | import os
import shutil
from dataclasses import dataclass, field
from typing import List
import h5py
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
@dataclass
class Cluster:
# cluster object, contains detected cluster points and additional ... | /test.py | import torch
import numpy as np
import os
l = [{'test': 0, 'test2': 1}, {'test': 3, 'test2': 4}]
print(l)
for i, j in enumerate(l):
print(i)
print(l)
| /yolo/__init__.py | import gc
from .train import train
from .predict import predict
def main(args):
gc.collect()
if args.Action == 'train':
train()
elif args.Action == 'predict':
predict()
gc.collect()
| /yolo/darknet.py | from __future__ import division
import torch, torch.nn as nn, torch.nn.functional as F
# from torch.autograd import Variable
import numpy as np
# import cv2
# from pprint import pprint
from .util import *
# =================================================================
# MAXPOOL (with stride = 1, NOT SURE IF NEE... | /yolo/dataset.py | import torch
import torch.utils.data
from torch.utils.data.dataloader import default_collate
# from torchvision import transforms
import os
# import random
import numpy as np
from PIL import Image
# anchors_wh = np.array([[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],
# [59, 119], [116, 90],... | /yolo/predict.py | import torch
# import torch.nn as nn
# import torch.nn.functional as F
# import torch.optim as optim
# import torchvision
import torchvision.transforms as transforms
import os, sys
# import pickle, time, random
import numpy as np
# from PIL import Image
import argparse
from .darknet import DarkNet
from .dataset imp... | /yolo/train.py | import torch
import torch.nn as nn
# import torch.nn.functional as F
import torch.optim as optim
# import torchvision
import torchvision.transforms as transforms
# import os, pickle, random
import time, sys
import numpy as np
# from PIL import Image
import argparse
from .darknet import DarkNet
from .dataset import *... | /yolo/util.py | from __future__ import division
import torch
import os
from operator import itemgetter
import numpy as np
import cv2
from PIL import Image, ImageDraw
import matplotlib.pyplot as plt
def draw_prediction(img_path, prediction, target, reso, names, pathout, savename):
"""Draw prediction result
Args
- img_pat... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
RoboBrainCode/Backend | refs/heads/master | {"/rest_api/views.py": ["/rest_api/serializer.py", "/feed/models.py"], "/feed/views.py": ["/feed/models.py"], "/rest_api/serializer.py": ["/feed/models.py"], "/feed/models.py": ["/feed/queue_util.py"]} | └──
├── UpdateViewerFeeds
│ └── updateViewerFeed.py
├── auth
│ ├── auth.py
│ └── urls.py
├── fabfile.py
├── feed
│ ├── models.py
│ ├── queue_util.py
│ ├── urls.py
│ └── views.py
└── rest_api
├── serializer.py
├── urls.py
└── views.py | /UpdateViewerFeeds/updateViewerFeed.py | import ConfigParser
import pymongo as pm
from datetime import datetime
import numpy as np
import importlib
import sys
sys.path.insert(0,'/var/www/Backend/Backend/')
def readConfigFile():
"""
Reading the setting file to use.
Different setting files are used on Production and Test robo brain
"""... | /auth/auth.py | from django.http import HttpResponse
import json
from django.contrib.auth.models import User
from django.views.decorators.csrf import ensure_csrf_cookie
from django import forms
from django.contrib.auth import login, logout
from django.contrib.auth import authenticate
from base64 import b64decode
@ensure_csrf_cookie
... | /auth/urls.py | from django.conf.urls import patterns, url
import auth
urlpatterns = patterns('',
url(r'create_user/', auth.create_user_rb, name='create_user'),
url(r'login/', auth.login_rb, name='login'),
url(r'logout/', auth.logout_rb, name='logout')
)
| /fabfile.py | from __future__ import with_statement
from fabric.api import cd, env, local, settings, run, sudo
from fabric.colors import green, red
from fabric.contrib.console import confirm
def prod_deploy(user='ubuntu'):
print(red('Deploying to production at robobrain.me...'))
if not confirm('Are you sure you want to deploy t... | /feed/models.py | from django.db import models
from djangotoolbox.fields import ListField
from datetime import datetime
from django.db.models.signals import post_save
from queue_util import add_feed_to_queue
#from feed.models import BrainFeeds
class GraphFeedback(models.Model):
id_node = models.TextField()
feedback_type = model... | /feed/queue_util.py | #!/usr/bin/python
import boto
import json
import traceback
from boto.sqs.message import RawMessage
from bson import json_util
conn = boto.sqs.connect_to_region(
"us-west-2",
aws_access_key_id='AKIAIDKZIEN24AUR7CJA',
aws_secret_access_key='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')
feed_queue = conn.cre... | /feed/urls.py | from django.conf.urls import patterns, url
from feed import views
urlpatterns = patterns('',
url(r'most_recent/', views.return_top_k_feeds, name='most_recent'),
url(r'infinite_scroll/', views.infinite_scrolling, name='infinite_scrolling'),
url(r'filter/', views.filter_feeds_with_hashtags, name='filter'),
... | /feed/views.py | from django.http import HttpResponse
from feed.models import BrainFeeds, ViewerFeed, GraphFeedback
import json
import numpy as np
from django.core import serializers
import dateutil.parser
from django.views.decorators.csrf import ensure_csrf_cookie
from django.db.transaction import commit_on_success
# This is a tempor... | /rest_api/serializer.py | from django.forms import widgets
from rest_framework import serializers
from feed.models import JsonFeeds
from djangotoolbox.fields import ListField
import drf_compound_fields.fields as drf
from datetime import datetime
class TagFieldS(serializers.Serializer):
media = serializers.CharField(required=False)
c... | /rest_api/urls.py | from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = patterns('rest_api.views',
url(r'^feeds/$', 'feed_list'),
#url(r'^snippets/(?P<pk>[0-9]+)$', 'snippet_detail'),
)
urlpatterns = format_suffix_patterns(urlpatterns)
| /rest_api/views.py | # Create your views here.
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from feed.models import JsonFeeds
from rest_api.serializer import FeedSerializer
from datetime import datetime
from rest_framework import permissions
@api_view(['... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
KAcee77/django_sputnik_map | refs/heads/main | {"/django_sputnik_maps/__init__.py": ["/django_sputnik_maps/widgets.py"], "/sample/admin.py": ["/django_sputnik_maps/widgets.py", "/django_sputnik_maps/fields.py", "/sample/models.py"], "/sample/models.py": ["/django_sputnik_maps/fields.py"]} | └──
├── django_sputnik_maps
│ ├── __init__.py
│ ├── apps.py
│ ├── fields.py
│ └── widgets.py
└── sample
├── admin.py
└── models.py | /django_sputnik_maps/__init__.py | from .widgets import AddressWidget | /django_sputnik_maps/apps.py | from django.apps import AppConfig
class DjangoSputnikMapsConfig(AppConfig):
name = 'django_sputnik_maps'
| /django_sputnik_maps/fields.py | from django.db import models
class AddressField(models.CharField):
pass | /django_sputnik_maps/widgets.py | from django.conf import settings
from django.forms import widgets
class AddressWidget(widgets.TextInput):
'''a map will be drawn after the address field'''
template_name = 'django_sputnik_maps/widgets/mapwidget.html'
class Media:
css = {
'all': ('https://unpkg.com/leaflet@1.0.1/dist/l... | /sample/admin.py | # from django.db import models
from django.contrib import admin
from django_sputnik_maps.fields import AddressField
from django_sputnik_maps.widgets import AddressWidget
from .models import SampleModel
@admin.register(SampleModel)
class SampleModelAdmin(admin.ModelAdmin):
formfield_overrides = {
AddressF... | /sample/models.py | from django.db import models
from django_sputnik_maps.fields import AddressField
# all fields must be present in the model
class SampleModel(models.Model):
region = models.CharField(max_length=100)
place = models.CharField(max_length=100)
street = models.CharField(max_length=100)
house = models.Integer... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
sudheermouni/NeckTie | refs/heads/main | {"/Necktie/necktieapp/admin.py": ["/Necktie/necktieapp/models/patients.py", "/Necktie/necktieapp/models/patent_doctorTb.py", "/Necktie/necktieapp/models/doctors.py"], "/Necktie/necktieapp/models/__init__.py": ["/Necktie/necktieapp/models/patients.py", "/Necktie/necktieapp/models/patent_doctorTb.py", "/Necktie/necktieap... | └──
└── Necktie
└── necktieapp
├── admin.py
├── apps.py
├── management
│ └── commands
│ └── bulk_create.py
├── migrations
│ ├── 0001_initial.py
│ ├── 0002_alter_doctors_d_phone.py
│ ├──... | /Necktie/necktieapp/admin.py | from django.contrib import admin
from .models import Doctors, Patient, PatentDoctorTb
admin.site.register(Doctors)
admin.site.register(Patient)
admin.site.register(PatentDoctorTb)
| /Necktie/necktieapp/apps.py | from django.apps import AppConfig
class NecktieappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'necktieapp'
| /Necktie/necktieapp/management/commands/bulk_create.py | import random
import string
from django.core.management.base import BaseCommand
from django.utils.crypto import get_random_string
from necktieapp.models import Doctors
sample_data = {
'd_surname': get_random_string(),
'd_firstname': get_random_string(),
'd_username': "",
'd_phone': get_random_string(... | /Necktie/necktieapp/migrations/0001_initial.py | # Generated by Django 3.2.8 on 2021-10-27 15:55
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Doctors',
fields=[
('id', models.BigAutoFie... | /Necktie/necktieapp/migrations/0002_alter_doctors_d_phone.py | # Generated by Django 3.2.8 on 2021-10-27 16:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('necktieapp', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='doctors',
name='d_phone',
... | /Necktie/necktieapp/migrations/0003_patient.py | # Generated by Django 3.2.8 on 2021-10-27 16:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('necktieapp', '0002_alter_doctors_d_phone'),
]
operations = [
migrations.CreateModel(
name='Pati... | /Necktie/necktieapp/migrations/0004_auto_20211027_2226.py | # Generated by Django 3.2.8 on 2021-10-27 16:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('necktieapp', '0003_patient'),
]
operations = [
migrations.RemoveField(
model_name='patient',
... | /Necktie/necktieapp/migrations/0005_auto_20211028_1129.py | # Generated by Django 3.2.8 on 2021-10-28 05:59
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('necktieapp', '0004_auto_20211027_2226'),
]
operations = [
migrations.RenameField(
model_name='doctors',
old_name='d_state',
... | /Necktie/necktieapp/migrations/0006_alter_patient_doctor.py | # Generated by Django 3.2.8 on 2021-10-28 06:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('necktieapp', '0005_auto_20211028_1129'),
]
operations = [
migrations.AlterField(
model_name='patient',
name='doctor'... | /Necktie/necktieapp/models/__init__.py | from .doctors import Doctors
from .patients import Patient
from .patent_doctorTb import PatentDoctorTb
| /Necktie/necktieapp/models/doctors.py | from django.db import models
from model_utils import Choices
SPECIALIZATIONS = Choices(
("CD", "Cardiology"),
("GS", "General Surgery"),
("EC", "Endocrinology"),
("NT", "Neonatology"),
)
class Doctors(models.Model):
d_surname = models.CharField(max_length=20, blank=True, null=True)
d_firstnam... | /Necktie/necktieapp/models/patent_doctorTb.py | from django.db import models
from .doctors import Doctors
from .patients import Patient
class PatentDoctorTb(models.Model):
'''
we can add extra fields here
'''
doctor = models.ForeignKey(Doctors, blank=False, null=False, on_delete=models.CASCADE)
patient = models.ForeignKey(Patient, blank=False... | /Necktie/necktieapp/models/patients.py | from django.db import models
from .doctors import Doctors
class Patient(models.Model):
p_surname = models.CharField(max_length=20, blank=True, null=True)
doctor = models.ManyToManyField(Doctors, through="PatentDoctorTb", null=True, blank=True)
p_fullname = models.CharField(max_length=20, blank=True, null... | /Necktie/necktieapp/serializers/__init__.py | from .doctor_serializer import DoctorSerializer
from .patient_serializer import PatientSerializer | /Necktie/necktieapp/serializers/doctor_serializer.py | from rest_framework import serializers
from necktieapp.models import Doctors
class DoctorSerializer(serializers.ModelSerializer):
class Meta:
model = Doctors
fields = "__all__" | /Necktie/necktieapp/tests/test_doctors.py | from django.test import TestCase, TransactionTestCase
from necktieapp.models import Doctors
sample_data = {
'd_surname': "sudheer",
'd_firstname': "mandi",
'd_username': "smre",
'd_phone': "7702231789",
'd_address': "Ramalingapuram",
'd_country': "India",
'd_specialization': "CD",
'd_pi... | /Necktie/necktieapp/urls.py | from rest_framework.routers import DefaultRouter
from django.conf.urls import url, include
from necktieapp import views
router = DefaultRouter(trailing_slash=False)
router.register(r'doctors', views.DoctorViewset)
router.register(r'patients', views.PatientViewset)
urlpatterns = [
url(r'^v1/', include(router.urls... | /Necktie/necktieapp/views/__init__.py | from .doctor_view import DoctorViewset # noqa: F401
from .patient_view import PatientViewset # noqa: F401 | /Necktie/necktieapp/views/doctor_view.py | from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets, filters
from rest_framework.permissions import IsAuthenticated
from necktieapp.models import Doctors
from necktieapp.serializers import DoctorSerializer
class DoctorViewset(viewsets.ModelViewSet):
permission_classes... | /Necktie/necktieapp/views/patient_view.py | from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets, filters
from rest_framework.permissions import IsAuthenticated
from necktieapp.models import Patient
from necktieapp.serializers import PatientSerializer
class PatientViewset(viewsets.ModelViewSet):
permission_class... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
briis/unifiprotect | refs/heads/master | {"/custom_components/unifiprotect/__init__.py": ["/custom_components/unifiprotect/services.py"], "/custom_components/unifiprotect/binary_sensor.py": ["/custom_components/unifiprotect/models.py", "/custom_components/unifiprotect/utils.py"], "/custom_components/unifiprotect/models.py": ["/custom_components/unifiprotect/u... | └──
└── custom_components
└── unifiprotect
├── __init__.py
├── binary_sensor.py
├── button.py
├── models.py
├── services.py
└── utils.py | /custom_components/unifiprotect/__init__.py | """UniFi Protect Platform."""
from __future__ import annotations
import asyncio
from datetime import timedelta
import logging
from aiohttp import CookieJar
from aiohttp.client_exceptions import ServerDisconnectedError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_HOST... | /custom_components/unifiprotect/binary_sensor.py | """This component provides binary sensors for UniFi Protect."""
from __future__ import annotations
from copy import copy
from dataclasses import dataclass
import logging
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
BinarySensorEntityDescription,
)
from ... | /custom_components/unifiprotect/button.py | """Support for Ubiquiti's UniFi Protect NVR."""
from __future__ import annotations
import logging
from homeassistant.components.button import ButtonDeviceClass, ButtonEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform imp... | /custom_components/unifiprotect/models.py | """The unifiprotect integration models."""
from __future__ import annotations
from collections.abc import Callable, Coroutine
from dataclasses import dataclass
import logging
from typing import Any
from homeassistant.helpers.entity import EntityDescription
from pyunifiprotect.data import NVR, ProtectAdoptableDeviceMo... | /custom_components/unifiprotect/services.py | """UniFi Protect Integration services."""
from __future__ import annotations
import asyncio
import functools
from typing import Any
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_DEVICE_ID
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassi... | /custom_components/unifiprotect/utils.py | """UniFi Protect Integration utils."""
from __future__ import annotations
from enum import Enum
from typing import Any
def get_nested_attr(obj: Any, attr: str) -> Any:
"""Fetch a nested attribute."""
attrs = attr.split(".")
value = obj
for key in attrs:
if not hasattr(value, key):
... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
beichao1314/TREC2016 | refs/heads/master | {"/run2_crawlerA/crawler.py": ["/run1_crawlerA/process_profile.py", "/run2_crawlerA/estimate_time.py", "/run2_crawlerA/Rest.py", "/run2_crawlerA/rewritesummary.py", "/run2_crawlerA/extension.py"]} | └──
├── run1_crawlerA
│ └── process_profile.py
└── run2_crawlerA
├── Rest.py
├── crawler.py
├── estimate_time.py
├── extension.py
└── rewritesummary.py | /run1_crawlerA/process_profile.py | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 7 16:17:49 2016
@author: xiaobei
"""
import nltk
from nltk.corpus import stopwords
import re
def removeStopWords_1(originSegs):
stops = set(stopwords.words('english'))
resultStr = [seg.lower() for seg in originSegs if seg.lower() not in stops and seg.isalpha()... | /run2_crawlerA/Rest.py | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 8 19:37:33 2016
@author: xiaobei
"""
import pycurl
import requests
import json
import logging
logging.basicConfig(level=logging.INFO)
class REST(object):
def __init__(self,clientid):
self.clientid=clientid
self.c = pycurl.Curl()
self.c.setopt... | /run2_crawlerA/crawler.py | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 7 17:10:58 2016
@author: xiaobei
"""
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import logging.handlers
from rewritesummary import PushSummary
from Rest import REST
import json
from estimate_time import Time
fro... | /run2_crawlerA/estimate_time.py | # from datetime import datetime
import datetime
import time as T
from email.utils import parsedate
class Time(object):
def __init__(self, firsttime):
self.firsttime = parsedate(firsttime)
self.firsttime = datetime.datetime.fromtimestamp(T.mktime(self.firsttime))
def calculatetime(self, time):... | /run2_crawlerA/extension.py | from py_bing_search import PyBingWebSearch
# s1= 9uCkTYlAG9x4iPdxAeDuQipYvc2vEn6oUbPKZJnFlVY
# s2=3L8LwEROeBFVSA1FwUVKLfIO+Ue979rarr+Y4mBZwaE
s3 = 'E+ok1GP7qpi6xgtE0yfsbrQFZSElgMBK2ZD1kwf/WXA'
s4 = 'AKvk0/D9XzJuCQA9n/a+TFbqwOFder9xd9Yj/22ivA8'
s5='r8OUqrE+DW/W4qs8ShfN2ljAU8214AkuksvYy7iMPGk'
def search(search_term):... | /run2_crawlerA/rewritesummary.py | import pymysql
from process import preprocess
import time as T
import nltk
import math
import operator
class PushSummary():
def __init__(self, lemda, interest_files, time, rest, fa, topicid):
self.topicid = topicid
self.L = len(self.topicid)
self.SumOfLenthOfStream = 0
self.wordInS... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
nurtai00/WebDevProjectBack | refs/heads/main | {"/projectback/api/admin.py": ["/projectback/api/models.py"], "/projectback/api/serializers.py": ["/projectback/api/models.py"], "/projectback/api/views.py": ["/projectback/api/models.py", "/projectback/api/serializers.py"], "/projectback/api/urls.py": ["/projectback/api/views.py"]} | └──
└── projectback
└── api
├── admin.py
├── migrations
│ └── 0002_auto_20210508_0140.py
├── models.py
├── serializers.py
├── urls.py
└── views.py | /projectback/api/admin.py | from django.contrib import admin
from api.models import Product, Category, Cart, User
# Register your models here.
admin.site.register(Product),
admin.site.register(Category),
admin.site.register(Cart),
admin.site.register(User)
| /projectback/api/migrations/0002_auto_20210508_0140.py | # Generated by Django 3.2.2 on 2021-05-07 19:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Category',
... | /projectback/api/models.py | from django.db import models
class Category(models.Model):
name = models.CharField(max_length=200)
description = models.TextField(max_length=500, default='')
def to_json(self):
return {
'id': self.id,
'name': self.name,
'description': self.descriptio... | /projectback/api/serializers.py | from rest_framework import serializers
from api.models import Category, Product, Cart, User
class CategoryModelSerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'name', 'description')
class ProductSerializer(serializers.Serializer):
class Meta:
... | /projectback/api/urls.py | from django.urls import path
from api import views
from api.views import product_list, product_detail, category_list, product2_list, category2_list
urlpatterns = [
path('api/product', product_list),
path('api/product/<int:product_id>/', product_detail),
path('api/category', category_list),
... | /projectback/api/views.py | from api.models import Product, Category
from django.http.response import JsonResponse
from api.serializers import CategoryModelSerializer, ProductSerializer, CartSerializer, UserModelSerializer
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from res... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
vanya2143/ITEA-tasks | refs/heads/master | {"/hw-6/task_2.py": ["/hw-6/task_1.py"]} | └──
├── hw-1
│ ├── task_1.py
│ ├── task_2.py
│ └── task_3.py
├── hw-2
│ ├── task_1.py
│ └── task_2.py
├── hw-3
│ └── task_1.py
├── hw-4
│ └── task_1.py
├── hw-5
│ └── task_1.py
├── hw-6
│ ├── task_1.py
│ └── task_2.py
└── hw-7
... | /hw-1/task_1.py | """
1. Определить количество четных и нечетных чисел в заданном списке.
Оформить в виде функции, где на вход будет подаваться список с целыми числами.
Результат функции должен быть 2 числа, количество четных и нечетных соответственно.
"""
def list_check(some_list):
even_numb = 0
not_even_numb = 0
for e... | /hw-1/task_2.py | """
Написать функцию, которая принимает 2 числа.
Функция должна вернуть сумму всех элементов числового ряда между этими двумя числами.
(если подать 1 и 5 на вход, то результат должен считаться как 1+2+3+4+5=15)
"""
def all_numbers_sum(num1, num2):
return sum([num for num in range(num1, num2 + 1)])
if __name__ =... | /hw-1/task_3.py | """
Реализовать алгоритм бинарного поиска на python.
На вход подается упорядоченный список целых чисел, а так же элемент,
который необходимо найти и указать его индекс,
в противном случае – указать что такого элемента нет в заданном списке.
"""
def search_item(some_list, find_item):
some_list.sort()
list_leng... | /hw-2/task_1.py | """
1. Написать функцию, которая будет принимать на вход натуральное число n,
и возращать сумму его цифр. Реализовать используя рекурсию
(без циклов, без строк, без контейнерных типов данных).
Пример: get_sum_of_components(123) -> 6 (1+2+3)
"""
def get_sum_of_components_two(n):
return 0 if not n else n % 10 + get... | /hw-2/task_2.py | """
2. Написать декоратор log, который будет выводить на экран все аргументы,
которые передаются вызываемой функции.
@log
def my_sum(*args):
return sum(*args)
my_sum(1,2,3,1) - выведет "Функция была вызвана с - 1, 2, 3, 1"
my_sum(22, 1) - выведет "Функция была вызвана с - 22, 1"
"""
def log(func):
def wrappe... | /hw-3/task_1.py | """
Реализовать некий класс Matrix, у которого:
1. Есть собственный конструктор, который принимает в качестве аргумента - список списков,
копирует его (то есть при изменении списков, значения в экземпляре класса не должны меняться).
Элементы списков гарантированно числа, и не пустые.
2. Метод size без аргументов, кото... | /hw-4/task_1.py | """
К реализованному классу Matrix в Домашнем задании 3 добавить следующее:
1. __add__ принимающий второй экземпляр класса Matrix и возвращающий сумму матриц,
если передалась на вход матрица другого размера - поднимать исключение MatrixSizeError
(по желанию реализовать так, чтобы текст ошибки содержал размерность 1 и 2... | /hw-5/task_1.py | # Реализовать пример использования паттерна Singleton
from random import choice
# Генератор событий
def gen_events(instance, data, count=2):
for i in range(count):
event = choice(data)
instance.add_event(f'Event-{event}-{i}', event)
# Singleton на примере списка событий
class EventsMeta(type):
... | /hw-6/task_1.py | """
1. Реализовать подсчёт елементов в классе Matrix с помощью collections.Counter.
Можно реализовать протоколом итератора и тогда будет такой вызов - Counter(maxtrix).
Либо сделать какой-то метод get_counter(), который будет возвращать объект Counter и подсчитывать все элементы
внутри матрицы. Какой метод - ваш выбор.... | /hw-6/task_2.py | # 2. Используя модуль unittests написать тесты: сложения двух матриц, умножения матрицы и метод transpose
import unittest
from .task_1 import Matrix, MatrixSizeError
class TestMatrix(unittest.TestCase):
def setUp(self) -> None:
self.matrix_1 = Matrix([[1, 2, 9], [3, 4, 0], [5, 6, 4]])
self.matrix... | /hw-7/task_1.py | """
Сделать скрипт, который будет делать GET запросы на следующие ресурсы:
"http://docs.python-requests.org/",
"https://httpbin.org/get",
"https://httpbin.org/",
"https://api.github.com/",
"https://example.com/",
"https://www.python.org/",
"https://www.google.com.ua/",
"https://regex101.... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
xmlabs-io/xmlabs-python | refs/heads/master | {"/xmlabs/aws_lambda/handler.py": ["/xmlabs/aws_lambda/env.py", "/xmlabs/aws_lambda/config.py"], "/tests/test_aws_lambda_integration.py": ["/xmlabs/aws_lambda/handler.py"], "/xmlabs/__init__.py": ["/xmlabs/aws_lambda/handler.py"], "/xmlabs/aws_lambda/__init__.py": ["/xmlabs/aws_lambda/handler.py"]} | └──
├── example
│ └── aws_lambda
│ └── app.py
├── tests
│ ├── test_aws_lambda_integration.py
│ ├── test_aws_lambda_settings.py
│ └── test_dynaconf.py
└── xmlabs
├── __init__.py
├── aws_lambda
│ ├── __init__.py
│ ├── config.py
│ ... | /example/aws_lambda/app.py | from xmlabs.aws_lambda import lambda_handler
@lambda_handler
def main(event, context, config):
print(config.STRIPE_API_SECRET_KEY)
pass
if __name__ == "__main__":
main({"headers":{"X-Environment": "dev"}}, {})
main({"headers":{"X-Environment": "prod"}}, {})
main({"headers":{"X-Environment": "dev"}... | /tests/test_aws_lambda_integration.py |
import pytest
from xmlabs import xmlabs_lambda_handler
@xmlabs_lambda_handler
def lambda_handler(event, context, config):
assert(config)
def test_lambda_handler():
lambda_handler({},{})
| /tests/test_aws_lambda_settings.py | import pytest
from xmlabs.aws_lambda.config import settings
def test_xmlabs_aws_lambda_config():
"""Assert Settings"""
assert settings
| /tests/test_dynaconf.py | from dynaconf import Dynaconf
def test_dynaconf_settingsenv():
settingsenv = Dynaconf(environments=True)
assert settingsenv
def test_dynaconf_settings():
settings = Dynaconf()
assert settings
| /xmlabs/__init__.py | from .aws_lambda import xmlabs_lambda_handler
| /xmlabs/aws_lambda/__init__.py | from .handler import xmlabs_lambda_handler
| /xmlabs/aws_lambda/config.py | from dynaconf import Dynaconf
from dynaconf.constants import DEFAULT_SETTINGS_FILES
LOADERS_FOR_DYNACONF = [
'dynaconf.loaders.env_loader', #Inorder to configure AWS_SSM_PREFIX we need to load it from environment
'xmlabs.dynaconf.aws_ssm_loader',
'dynaconf.loaders.env_loader', #Good to load environment las... | /xmlabs/aws_lambda/env.py | import os
import logging
logger = logging.getLogger()
def get_environment(event, context=None):
valid_envs = ["stage", "prod", "dev"]
env = None
# default_env = os.getenv("DEFAULT_ENV", "dev")
default_env = os.getenv("APP_ENV", os.getenv("DEFAULT_ENV", "dev"))
override_env = os.getenv("ENV")
... | /xmlabs/aws_lambda/handler.py | from .config import xmlabs_settings
from .env import get_environment
from functools import wraps
def xmlabs_lambda_handler(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
env, config = None , None
try:
env = get_environment(*args, **kwargs)
if not env:
rai... | /xmlabs/dynaconf/aws_ec2_userdata_loader.py | from .base import ConfigSource
import logging
import requests
logger = logging.getLogger()
class ConfigSourceAwsEc2UserData(ConfigSource):
def load(self):
if self._running_in_ec2():
#TODO: fetch EC2 USERDATA
raise Exception("ConfigSourceEC2UserData Load Unimplemented")
... | /xmlabs/dynaconf/aws_ssm_loader.py | import boto3
import logging
import requests
from functools import lru_cache
from dynaconf.utils.parse_conf import parse_conf_data
logger = logging.getLogger()
IDENTIFIER = 'aws_ssm'
def load(obj, env=None, silent=True, key=None, filename=None):
"""
Reads and loads in to "obj" a single key or all keys from ... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
acheng6845/PuzzleSolver | refs/heads/master | {"/PADScreen.py": ["/Board_Screen.py", "/PAD_Monster.py", "/PAD_Team.py", "/Calculator_Screen.py"], "/Board_Screen.py": ["/PAD_Monster.py", "/PAD_Team.py"], "/Calculator_Screen.py": ["/PAD_Monster.py", "/PAD_Team.py"], "/PAD_Team.py": ["/PAD_Monster.py"], "/PAD_GUI.py": ["/PADScreen.py"]} | └──
├── Board_Screen.py
├── Calculator_Screen.py
├── PADCompleter.py
├── PADScreen.py
├── PAD_GUI.py
├── PAD_Monster.py
├── PAD_Team.py
└── image_updater.py | /Board_Screen.py | __author__ = 'Aaron'
from PyQt5.QtWidgets import (QVBoxLayout, QWidget, QLabel, QGridLayout, QSplitter,
QPushButton, QHBoxLayout)
from PyQt5.QtCore import Qt, QMimeData
from PyQt5.QtGui import QPixmap, QDrag
import os
from PAD_Monster import PADMonster
from PAD_Team import PADTeam
from func... | /Calculator_Screen.py | __author__ = 'Aaron'
# Class Description:
# Create framework for the split screens used in PAD_GUI
# import necessary files
import os
import json
from functools import partial
from PyQt5.QtWidgets import (QLabel, QWidget, QHBoxLayout,
QFrame, QSplitter, QStyleFactory,
... | /PADCompleter.py | __author__ = 'Aaron'
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5 import QtWidgets, QtCore, QtGui
class PADCompleter(QCompleter):
def __init__(self):
super().__init__()
self.prefix = ''
self.model = None
def _set_model_(self, model):
... | /PADScreen.py | __author__ = 'Aaron'
from Calculator_Screen import CalculatorScreen
from Board_Screen import BoardScreen
from PAD_Monster import PADMonster
from PAD_Team import PADTeam
from PyQt5.QtWidgets import (QVBoxLayout, QHBoxLayout, QWidget, QPushButton, QSplitter, QAction,
QFileDialog, QMainWindow... | /PAD_GUI.py | __author__ = 'Aaron'
# import necessary files
from PyQt5 import PyQt5
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QHBoxLayout,
QFrame, QSplitter, QStyleFactory,
QMainWindow, QStackedWidget)
from PyQt5.QtCore import Qt
from PADScreen import P... | /PAD_Monster.py | __author__ = 'Aaron'
# Class Description:
# Our Monster Class where we hold all of the Monster's stats and calculate the values needed with those stats
import os
import json
class PADMonster:
def __init__(self):
# initialize the Class's stats
# _max, _min, and _scale are used for when the mon... | /PAD_Team.py | __author__ = 'Aaron'
import os
from PAD_Monster import PADMonster
class PADTeam:
def __init__(self, team):
"""
Initializes the PADTeam Class.
:param team: an array containing 6 PADMonster Classes
"""
# self.team = [PADMonster() for monster in range(6)] -> how the team shoul... | /image_updater.py | __author__ = 'Aaron'
# Class Description:
# Update our monsters.txt file and our images folder
from urllib3 import urllib3
import shutil
import os
import json
class image_updater():
def __init__(self):
# update monsters.txt here:
self.json_file = open(os.path.realpath('./monsters.txt'), 'r')... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
guanjz20/MM21_FME_solution | refs/heads/master | {"/main_cls.py": ["/model/network.py", "/dataset/me_dataset.py"]} | └──
├── config.py
├── dataset
│ ├── me_dataset.py
│ ├── params.py
│ └── utils.py
├── main_cls.py
├── model
│ ├── network.py
│ └── utils.py
├── paths.py
├── preprocess
│ ├── CNN_feature_extraction.py
│ ├── casme_2_label_generation.py
│ ├── openface... | /config.py | import argparse
parser = argparse.ArgumentParser(description="x")
parser.add_argument('--store_name', type=str, default="")
parser.add_argument('--save_root', type=str, default="")
parser.add_argument('--tag', type=str, default="")
parser.add_argument('--snap', type=str, default="")
parser.add_argument('--dataset',
... | /dataset/me_dataset.py | from unicodedata import name
import cv2
import os
import pdb
import torch
import time
import pywt
import glob
import numpy as np
import os.path as osp
from tqdm import tqdm
from torch.utils.data import Dataset
from torch import nn as nn
from . import params
from . import utils
WT_CHANNEL = 4
sm_kernel = np.load(param... | /dataset/params.py | SAMM_ROOT = '/data/gjz_mm21/SAMM'
CASME_2_LABEL_DIR = '/data/gjz_mm21/CASME_2_LongVideoFaceCropped/CASME_2_longVideoFaceCropped/labels'
# kernel path
GAUSS_KERNEL_PATH = {
'sm_kernel': '/home/gjz/lry_kernels/gauss2D-smooth.npy',
'dr1_kernel': '/home/gjz/lry_kernels/gauss1D-derivative1.npy',
'dr2_kernel': '... | /dataset/utils.py | from albumentations.augmentations.transforms import GaussNoise
import cv2
import os
import numpy as np
import os.path as osp
import albumentations as alb
# from torch._C import Ident
# from torch.nn.modules.linear import Identity
class IsotropicResize(alb.DualTransform):
def __init__(self,
max_si... | /main_cls.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from genericpath import exists
import os
from typing import Final
import cv2
import sys
from matplotlib.pyplot import xcorr
from numpy.random import f, sample, shuffle
from torch.utils.data import dataset
from config import parser
if len(sys.argv) > 1:
# use shell a... | /model/network.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import glob
import os
import os.path as osp
from torch.serialization import load
class MLP(nn.Module):
def __init__(self, hidden_units, dropout=0.3):
super(MLP, self).__init__()
input_feature_dim = hidden_units[... | /model/utils.py | import torch.nn as nn
def init_weights(model):
for k, m in model.named_modules():
if isinstance(m, nn.Conv3d) or isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight,
mode='fan_out',
nonlinearity='relu')
#... | /paths.py | # SAMM
SAMM_ROOT = '/data/gjz_mm21/SAMM'
SAMM_LABEL_DIR = SAMM_ROOT
SAMM_VIDEO_DIR = '/data/gjz_mm21/SAMM/SAMM_longvideos'
# CASME_2
CASME_2_ROOT = '/data/gjz_mm21/CASME_2_LongVideoFaceCropped/CASME_2_longVideoFaceCropped'
CASME_2_LABEL_DIR = '/data/gjz_mm21/CASME_2_LongVideoFaceCropped/CASME_2_longVideoFaceCropped/la... | /preprocess/CNN_feature_extraction.py | from __future__ import division
from typing import Iterable
import cv2
import os
import time
import six
import sys
from tqdm import tqdm
import argparse
import pickle
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import torch.utils.data
import os.path as osp
import torch.backends.cudnn as cu... | /preprocess/casme_2_label_generation.py | '''
generate the emotion intensity of each frame
'''
# %%
import pdb
import os
import os.path as osp
from numpy.core.numeric import ones, ones_like
from numpy.lib.function_base import percentile
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import params
# %% ID2NAME and NAME2ID
# CASME_2_P... | /preprocess/openface/face_crop_align.py | import os
import os.path as osp
from tqdm import tqdm
from glob import glob
from video_processor import Video_Processor
import params
# OpenFace parameters
save_size = 224
OpenFace_exe = params.OpenFace_exe
quiet = True
nomask = True
grey = False
tracked_vid = False
noface_save = False
# dataset
video_root = params.... | /preprocess/params.py | # CASME_2
CASME_2_ROOT = '/data/gjz_mm21/CASME_2_LongVideoFaceCropped/CASME_2_longVideoFaceCropped'
CASME_2_LABEL_DIR = '/data/gjz_mm21/CASME_2_LongVideoFaceCropped/CASME_2_longVideoFaceCropped/labels'
CASME_2_VIDEO_DIR = '/data/gjz_mm21/CASME_2_LongVideoFaceCropped/CASME_2_longVideoFaceCropped/longVideoFaceCropped'
#... | /preprocess/samm_2_label_generation.py | '''
generate the emotion intensity of each frame
'''
# %%
import os
import pdb
import os.path as osp
from numpy.core.numeric import ones
from numpy.lib.function_base import percentile
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import params
# %% main
anno_dict = {} # intensity
label_dict... | /submit.py | import pandas as pd
import numpy as np
import os.path as osp
dataset = 'CASME_2'
# dataset = 'SAMM'
submit_name = 'submit_{}.csv'.format(dataset)
result_dir_name = 'results'
submit_npy_name = 'match_regions_record_all.npy'
submit_id = 'done_exp_cls_ca_20210708-215035'
def convert_key(k, dataset):
if dataset == '... | /trainer_cls.py | import time
from matplotlib.pyplot import winter
import torch
import torch.nn.functional as F
import numpy as np
import utils
import dataset.utils as dataset_utils
import dataset.params as DATASET_PARAMS
def train(dataloader, model, criterion, optimizer, epoch, logger, args,
amp_autocast, loss_scaler):
... | /utils.py | import os
import sys
import cv2
from timm.utils import reduce_tensor
import torch
import shutil
import numpy as np
import os.path as osp
import torch.nn.functional as F
import matplotlib.pyplot as plt
import torch.distributed as dist
from torch.nn.modules import loss
from datetime import datetime
import paths
import d... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
liuhongbo830117/ntire2018_adv_rgb2hs | refs/heads/master | {"/data/icvl_dataset.py": ["/util/spectral_color.py"]} | └──
├── data
│ ├── aligned_dataset.py
│ └── icvl_dataset.py
├── eval
│ ├── evaluation.py
│ └── select_model.py
├── models
│ └── mylosses.py
└── util
└── spectral_color.py | /data/aligned_dataset.py | import os.path
import random
import torchvision.transforms as transforms
import torch
from data.base_dataset import BaseDataset
from data.image_folder import make_dataset
from PIL import Image
| /data/icvl_dataset.py | import os.path
import random
import torchvision.transforms as transforms
import torch
# import torch.nn.functional as F
from data.base_dataset import BaseDataset
from data.image_folder import make_dataset_from_dir_list
from PIL import Image, ImageOps
import h5py
import numpy as np
import spectral
from tqdm import tqdm
... | /eval/evaluation.py | # Evaluation script for the NTIRE 2018 Spectral Reconstruction Challenge
#
# * Provide input and output directories as arguments
# * Validation files should be found in the '/ref' subdirectory of the input dir
# * Input validation files are expected in the v7.3 .mat format
import h5py as h5py
import numpy as np
impor... | /eval/select_model.py | # -*- coding: utf-8 -*-
import pandas as pd
import os
import sacred
import glob
from sacred import Experiment
ex = Experiment('rename_to_samename')
@ex.config
def config():
results_home_dir = os.path.abspath('/home/aitor/dev/adv_rgb2hs_pytorch/results')
@ex.automain
def select_model(results_home_dir):
res_dir... | /models/mylosses.py | # -*- coding: utf-8 -*-
import numpy as np
from torch.nn.modules import loss
from torch.nn import functional as F
import torch
from torch.autograd import Variable
class RelMAELoss(loss._Loss):
r"""Creates a criterion that measures the mean squared error between
`n` elements in the input `x` and target `y`.
... | /util/spectral_color.py | # -*- coding: utf-8 -*-
import os
import numpy as np
from colour.plotting import *
import colour
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from skimage.color import colorconv
from spectral import *
### to avoid importing pyresources.assemple data
def dim_ordering_tf2th(img_list_ndarray):... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
eric-z-lin/DIAYN-PyTorch | refs/heads/main | {"/Common/__init__.py": ["/Common/play.py", "/Common/config.py", "/Common/logger.py"], "/main.py": ["/Common/play.py", "/Brain/agent.py", "/Common/config.py", "/Common/logger.py"], "/Brain/__init__.py": ["/Brain/agent.py"], "/Brain/agent.py": ["/Brain/replay_memory.py", "/Brain/model.py"]} | └──
├── Brain
│ ├── __init__.py
│ ├── agent.py
│ ├── model.py
│ └── replay_memory.py
├── Common
│ ├── __init__.py
│ ├── config.py
│ ├── logger.py
│ └── play.py
└── main.py | /Brain/__init__.py | from .agent import SACAgent | /Brain/agent.py | import numpy as np
from .model import PolicyNetwork, QvalueNetwork, ValueNetwork, Discriminator
import torch
from .replay_memory import Memory, Transition
from torch import from_numpy
from torch.optim.adam import Adam
from torch.nn.functional import log_softmax
class SACAgent:
def __init__(self,
... | /Brain/model.py | from abc import ABC
import torch
from torch import nn
from torch.nn import functional as F
from torch.distributions import Normal
def init_weight(layer, initializer="he normal"):
if initializer == "xavier uniform":
nn.init.xavier_uniform_(layer.weight)
elif initializer == "he normal":
nn.init.... | /Brain/replay_memory.py | import random
from collections import namedtuple
Transition = namedtuple('Transition', ('state', 'z', 'done', 'action', 'next_state'))
class Memory:
def __init__(self, buffer_size, seed):
self.buffer_size = buffer_size
self.buffer = []
self.seed = seed
random.seed(self.seed)
... | /Common/__init__.py | from .config import get_params
from .play import Play
from .logger import Logger | /Common/config.py | import argparse
def get_params():
parser = argparse.ArgumentParser(
description="Variable parameters based on the configuration of the machine or user's choice")
parser.add_argument("--env_name", default="BipedalWalker-v3", type=str, help="Name of the environment.")
parser.add_argument("--interva... | /Common/logger.py | import time
import numpy as np
import psutil
from torch.utils.tensorboard import SummaryWriter
import torch
import os
import datetime
import glob
class Logger:
def __init__(self, agent, **config):
self.config = config
self.agent = agent
self.log_dir = self.config["env_name"][:-3] + "/" + d... | /Common/play.py | # from mujoco_py.generated import const
from mujoco_py import GlfwContext
import cv2
import numpy as np
import os
GlfwContext(offscreen=True)
class Play:
def __init__(self, env, agent, n_skills):
self.env = env
self.agent = agent
self.n_skills = n_skills
self.agent.set_policy_net_... | /main.py | import gym
from Brain import SACAgent
from Common import Play, Logger, get_params
import numpy as np
from tqdm import tqdm
import mujoco_py
def concat_state_latent(s, z_, n):
z_one_hot = np.zeros(n)
z_one_hot[z_] = 1
return np.concatenate([s, z_one_hot])
if __name__ == "__main__":
params = get_param... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
CellProfiling/cpias | refs/heads/master | {"/cpias/__init__.py": ["/cpias/server.py", "/cpias/message.py"], "/cpias/cli/server.py": ["/cpias/server.py", "/cpias/cli/common.py"], "/cpias/commands/hello.py": ["/cpias/server.py", "/cpias/commands/__init__.py", "/cpias/process.py", "/cpias/message.py"], "/cpias/process.py": ["/cpias/server.py", "/cpias/exceptions.... | └──
├── cpias
│ ├── __init__.py
│ ├── cli
│ │ ├── __init__.py
│ │ ├── client.py
│ │ ├── common.py
│ │ └── server.py
│ ├── client.py
│ ├── commands
│ │ ├── __init__.py
│ │ └── hello.py
│ ├── const.py
│ ├── exceptions.py
│ ├── ... | /cpias/__init__.py | """Provide a server for image analysis."""
from .const import VERSION
from .message import Message
from .server import CPIAServer
__all__ = ["Message", "CPIAServer"]
__version__ = VERSION
| /cpias/cli/__init__.py | # type: ignore
"""Provide a CLI."""
import logging
import click
from cpias import __version__
from cpias.cli.client import run_client
from cpias.cli.server import start_server
SETTINGS = dict(help_option_names=["-h", "--help"])
@click.group(
options_metavar="", subcommand_metavar="<command>", context_settings=... | /cpias/cli/client.py | # type: ignore
"""Provide a CLI to start a client."""
import asyncio
import click
from cpias.cli.common import common_tcp_options
from cpias.client import tcp_client
DEFAULT_MESSAGE = '{"cli": "client-1", "cmd": "hello", "dta": {"planet": "world"}}\n'
@click.command(options_metavar="<options>")
@click.option("--me... | /cpias/cli/common.py | # type: ignore
"""Provide common CLI options."""
import click
def common_tcp_options(func):
"""Supply common tcp connection options."""
func = click.option(
"-p",
"--port",
default=8555,
show_default=True,
type=int,
help="TCP port of the connection.",
)(func... | /cpias/cli/server.py | # type: ignore
"""Provide a CLI to start the server."""
import asyncio
import click
from cpias.cli.common import common_tcp_options
from cpias.server import CPIAServer
@click.command(options_metavar="<options>")
@common_tcp_options
@click.pass_context
def start_server(ctx, host, port):
"""Start an async tcp ser... | /cpias/client.py | """Provide a test client for the CPIAServer."""
import asyncio
from cpias.const import LOGGER
async def tcp_client(message: str, host: str = "127.0.0.1", port: int = 8555) -> None:
"""Connect to server and send message."""
reader, writer = await asyncio.open_connection(host, port)
data = await reader.rea... | /cpias/commands/__init__.py | """Provide commands to the server."""
from functools import wraps
from types import ModuleType
from typing import Callable, Mapping
import pkg_resources
import voluptuous as vol
from voluptuous.humanize import humanize_error
from cpias.const import LOGGER
from cpias.message import Message
def get_commands() -> Mapp... | /cpias/commands/hello.py | """Provide the hello command."""
from typing import TYPE_CHECKING, Callable, Optional, Tuple
from cpias.commands import validate
from cpias.const import LOGGER
from cpias.message import Message
from cpias.process import ReceiveError, create_process
if TYPE_CHECKING:
from cpias.server import CPIAServer
# pylint: ... | /cpias/const.py | """Provide constants for cpias."""
import logging
from pathlib import Path
VERSION = (Path(__file__).parent / "VERSION").read_text().strip()
API_VERSION = "1.0.0"
LOGGER = logging.getLogger(__package__)
| /cpias/exceptions.py | """Provide exceptions."""
class CPIASError(Exception):
"""Represent a generic CPIAS exception."""
| /cpias/message.py | """Provide a model for messages sent and received by the server."""
from __future__ import annotations
import json
from enum import Enum
from typing import Optional, cast
from .const import LOGGER
class Message:
"""Represent a client/server message."""
def __init__(self, *, client: str, command: str, data:... | /cpias/process.py | """Provide process tools."""
import asyncio
import signal
from multiprocessing import Pipe, Process
from multiprocessing.connection import Connection
from time import sleep
from typing import TYPE_CHECKING, Any, Callable, Dict, Tuple
from cpias.const import LOGGER
from cpias.exceptions import CPIASError
if TYPE_CHECK... | /cpias/server.py | """Provide an image analysis server."""
import asyncio
import concurrent.futures
import logging
from typing import Any, Callable, Coroutine, Dict, Optional
from .commands import get_commands
from .const import API_VERSION, LOGGER, VERSION
from .message import Message
class CPIAServer:
"""Represent an image analy... | /setup.py | """Set up file for cpias package."""
from pathlib import Path
from setuptools import find_packages, setup
PROJECT_DIR = Path(__file__).parent.resolve()
README_FILE = PROJECT_DIR / "README.md"
LONG_DESCR = README_FILE.read_text(encoding="utf-8")
VERSION = (PROJECT_DIR / "cpias" / "VERSION").read_text().strip()
GITHUB_... | /tests/test_message.py | """Provide tests for message."""
from cpias.message import Message
def test_message_decode():
"""Test message decode."""
msg = Message.decode(
'{"cli": "client-1", "cmd": "hello", "dta": {"param1": "world"}}'
)
assert msg.client == "client-1"
assert msg.command == "hello"
assert msg.d... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Kw4dr4t/WebMovies | refs/heads/master | {"/WebMovies/admin.py": ["/WebMovies/models.py"], "/WebMovies/views.py": ["/WebMovies/models.py"]} | └──
└── WebMovies
├── admin.py
├── apps.py
├── migrations
│ ├── 0003_movie_description.py
│ ├── 0004_auto_20210204_0835.py
│ ├── 0005_auto_20210209_0759.py
│ └── 0006_auto_20210209_1401.py
├── models.py
└── views.py | /WebMovies/admin.py | from django.contrib import admin
from .models import AdditionalInfo, Movie
# Register your models here.
# admin.site.register(Movie)
@admin.register(Movie)
class MovieAdmin(admin.ModelAdmin):
# fields = ["Title", "Description", "Year"]
# exclude = ["Description"]
list_display = ["title", "imdb_rating", "... | /WebMovies/apps.py | from django.apps import AppConfig
class WebmoviesConfig(AppConfig):
name = 'WebMovies'
| /WebMovies/migrations/0003_movie_description.py | # Generated by Django 3.1.6 on 2021-02-04 08:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('WebMovies', '0002_auto_20210204_0806'),
]
operations = [
migrations.AddField(
model_name='movie',
name='description'... | /WebMovies/migrations/0004_auto_20210204_0835.py | # Generated by Django 3.1.6 on 2021-02-04 08:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('WebMovies', '0003_movie_description'),
]
operations = [
migrations.AddField(
model_name='movie',
name='imdb_rating',... | /WebMovies/migrations/0005_auto_20210209_0759.py | # Generated by Django 3.1.6 on 2021-02-09 07:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('WebMovies', '0004_auto_20210204_0835'),
]
operations = [
migrations.CreateModel(
name='Addition... | /WebMovies/migrations/0006_auto_20210209_1401.py | # Generated by Django 3.1.6 on 2021-02-09 14:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('WebMovies', '0005_auto_20210209_0759'),
]
operations = [
migrations.AlterField(
model_name='additionalinfo',
name='g... | /WebMovies/models.py | from django.db import models
class AdditionalInfo(models.Model):
GENRES = {
(0, "Other"),
(1, "Action"),
(2, "Animation"),
(3, "Comedy"),
(4, "Crime"),
(5, "Drama"),
(6, "Experimental"),
(7, "Fantasy"),
(8, "Historical"),
(9, "Horror"... | /WebMovies/views.py | from django.shortcuts import get_object_or_404, render, redirect
from django.http import HttpResponse
from WebMovies.models import Movie
from .forms import MovieForm
from django.contrib.auth.decorators import login_required
def all_movies(request):
movies_all = Movie.objects.all()
return render(request, "movi... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
tduproject/kagikko2 | refs/heads/master | {"/tdu/profiles/views.py": ["/tdu/profiles/forms.py", "/tdu/profiles/models.py"], "/tdu/accounts/views.py": ["/tdu/accounts/forms.py", "/tdu/profiles/models.py"], "/tdu/keijiban/views.py": ["/tdu/profiles/models.py", "/tdu/keijiban/forms.py", "/tdu/polls/models.py", "/tdu/keijiban/models.py"], "/tdu/profiles/admin.py":... | └──
└── tdu
├── accounts
│ ├── aes.py
│ ├── forms.py
│ └── views.py
├── app
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ └── 0002_auto_20170708_0057.py
│ ├── models.py
│ ├── urls.py
│ └── views.py
... | /tdu/accounts/aes.py | import codecs
from Crypto.Cipher import AES
class aesEncryption:
# def PaddingMes(self,mes):
# mes_length = len(mes)
# len = round(mes_length / 16) #四捨五入
# new_mes = mes + " "*len
# return new_mes
def Encrypt(self,mes1):
secret = (b'\xf0\x0e3nE\xa1\x9a\xff\x7f\xf6r\x... | /tdu/accounts/forms.py | from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, PasswordChangeForm, PasswordResetForm, SetPasswordForm
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.http im... | /tdu/accounts/views.py | from django.conf import settings
from django.contrib.auth import views as auth_views
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
#from myUserModel.models import User
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcu... | /tdu/app/migrations/0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-20 00:08
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Create... | /tdu/app/migrations/0002_auto_20170708_0057.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-08 00:57
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0001_initial'),
]
operations = [
migrations.AddField(
mode... | /tdu/app/models.py | from datetime import datetime
from django.db import models
class Post(models.Model):
title = models.CharField('曜日', max_length=255)
text = models.CharField('時間', max_length=255)
sub = models.CharField('科目名', max_length=255)
category = models.CharField('カテゴリ名', max_length=255 ,default='SOME STRING')
... | /tdu/app/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^csv_import/$', views.csv_import, name='csv_import'),
url(r'^csv_export/$', views.csv_export, name='csv_export'),
]
| /tdu/app/views.py | import csv
from io import TextIOWrapper, StringIO
from django.http import HttpResponse
from django.shortcuts import redirect
from django.views import generic
from .models import Post
from polls.models import Poll ,Choice
class IndexView(generic.ListView):
model = Post
def csv_import(request):
q_array = ['q1... | /tdu/home/views.py | from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect
from keijiban.models import Posting
from polls.models import Poll
from .models import Contact
from .forms import ContactForm
# Create your views here.
def show(request):
#最新スレッド5件を表示する処理
#全てのデータを1つの... | /tdu/keijiban/admin.py | from django.contrib import admin
from keijiban.models import Posting
from keijiban.models import PostingSubject
# Register your models here.
admin.site.register(Posting)
admin.site.register(PostingSubject)
| /tdu/keijiban/forms.py | from django import forms
from .models import Posting
from .models import PostingSubject
class PostingForm(forms.ModelForm):
name = forms.CharField(label="名前", required=True)
message = forms.CharField(label="メッセージ", widget=forms.Textarea)
class Meta:
model = Posting
fields = ('name','messa... | /tdu/keijiban/models.py | from django.db import models
class Posting(models.Model):
name = models.CharField(
max_length=64,
verbose_name='名前',
help_text='あなたの名前を入力してください',
)
message = models.TextField(
verbose_name='メッセージ',
help_text='メッセージを入力してください',
null=True,
)
subjec... | /tdu/keijiban/urls.py | from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='list'),
url(r'^index/(?P<pk>[0-9]+)/$', views.index, name='index'),
]
| /tdu/keijiban/views.py | # ページネーター
from django.core.paginator import (
Paginator, # ページネーター本体のクラス
EmptyPage, # ページ番号が範囲外だった場合に発生する例外クラス
PageNotAnInteger # ページ番号が数字でなかった場合に発生する例外クラス
)
from django.shortcuts import (
render,
redirect,
)
from .models import Posting
from .forms import PostingForm
from .models import PostingSu... | /tdu/polls/admin.py | from django.contrib import admin
from polls.models import Poll , Choice
admin.site.register(Poll)
admin.site.register(Choice)
| /tdu/polls/models.py | # coding: UTF-8
from django.db import models
#
# アンケート質問モデル
#
class Poll(models.Model):
subname = models.CharField(max_length=200)
question1 = models.CharField(max_length=200)
question2 = models.CharField(max_length=200)
question3 = models.CharField(max_length=200)
def __str__(self):
return self.subname
... | /tdu/polls/urls.py | # coding: UTF-8
from django.conf.urls import url
from polls import views
urlpatterns = [
url(r'^$', views.poll_list, name = 'poll_list'),
url(r'^poll/(?P<pk>[0-9]+)/$', views.poll_detail, name = 'poll_detail'),
# ex: /polls/5/
# ex: /polls/5/results/
url(r'^vote/$', views.vote, name='vote'),
# ex: /polls/... | /tdu/polls/views.py | # coding: UTF-8
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django.views import generic
from polls.models import Poll, Choice
#
# 一覧表示
#
def poll_list(request):
posts = Poll.objects.all()
re... | /tdu/profiles/admin.py | from django.contrib import admin
from .models import UserProfile #UserProfileモデルをインポート
admin.site.register(UserProfile) #モデルをadminページで見るにはこれで登録
| /tdu/profiles/forms.py | from django import forms
from .models import UserProfile
GRADE_CHOICES = (
('1年', '1年生'),
('2年', '2年生'),
('3年', '3年生'),
('4年', '4年生'),
('院1年', '院1年生'),
('院2年', '院2年生'),
('教員', '教員'),
)
MAJOR_CHOICES = (
('RB', 'RB'),
('RD', 'RD'),
('RG', 'RG'),
('RT', 'RT'),
('RU', 'R... | /tdu/profiles/migrations/0003_auto_20170703_1040.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-03 10:40
from __future__ import unicode_literals
from django.db import migrations
import encrypted_fields.fields
class Migration(migrations.Migration):
dependencies = [
('profiles', '0002_userprofile_email'),
]
operations = [
... | /tdu/profiles/migrations/0004_auto_20170703_1043.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-03 10:43
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0003_auto_20170703_1040'),
]
operations = [
migrations.AlterField... | /tdu/profiles/migrations/0005_auto_20170703_1142.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-03 11:42
from __future__ import unicode_literals
from django.db import migrations
import encrypted_fields.fields
class Migration(migrations.Migration):
dependencies = [
('profiles', '0004_auto_20170703_1043'),
]
operations = [
... | /tdu/profiles/migrations/0006_auto_20170703_2051.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-03 20:51
from __future__ import unicode_literals
from django.db import migrations
import encrypted_fields.fields
class Migration(migrations.Migration):
dependencies = [
('profiles', '0005_auto_20170703_1142'),
]
operations = [
... | /tdu/profiles/migrations/0007_auto_20170703_2053.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-03 20:53
from __future__ import unicode_literals
from django.db import migrations, models
import encrypted_fields.fields
class Migration(migrations.Migration):
dependencies = [
('profiles', '0006_auto_20170703_2051'),
]
operations = ... | /tdu/profiles/models.py | from django.db import models
from django.utils import timezone
from encrypted_fields import EncryptedTextField ,EncryptedEmailField,EncryptedCharField,EncryptedIntegerField
class UserProfile(models.Model):
name = EncryptedCharField(max_length = 254)
email = models.EmailField(max_length= 254 , default = 'exampl... | /tdu/profiles/urls.py | #profilesの全てのviewをインポートするよ
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^detail/(?P<pk>[0-9]+)/$', views.profile_detail, name = 'profile_detail'),
url(r'^edit/$', views.profile_edit, name='profile_edit'),
url(r'^mydetail/$', views.prof... | /tdu/profiles/views.py | from django.shortcuts import render
from .models import UserProfile
from django.shortcuts import render, get_object_or_404
from .forms import UserProfileForm
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http impor... | /tdu/timetable/admin.py | from django.contrib import admin
from .models import Timetable1,Timetable2
admin.site.register(Timetable1)
admin.site.register(Timetable2)
| /tdu/timetable/migrations/0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-08 00:57
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Timetabl... | /tdu/timetable/models.py | from datetime import datetime
from django.db import models
class Timetable1(models.Model):
username = models.CharField('名前', max_length=255)
day = models.CharField('曜日', max_length=255)
time = models.CharField('時間', max_length=255)
sub = models.CharField('科目名', max_length=255)
when = models.CharFie... | /tdu/timetable/urls.py | from django.conf.urls import url
from .import views
urlpatterns = [
url(r'^$', views.time_table, name = 'table'), #追加 7/9 山田
url(r'^timeedit/$', views.time_table2, name='edit'),
url(r'^result/$', views.show, name='result'),
]
| /tdu/timetable/views.py | from django.shortcuts import render
from app.models import Post
from .models import Timetable1,Timetable2
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
# Create your views here.
def time_table(request):
... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
shawntan/predict-forum-pgm | refs/heads/master | {"/lib/evaluation/evaluate.py": ["/lib/io/reader.py", "/lib/evaluation/pairwise.py", "/lib/interfaces/model_utils.py", "/lib/evaluation/sliding_window.py", "/lib/io/reporting.py"], "/lib/evaluation/evaluate_window.py": ["/lib/io/reader.py", "/lib/interfaces/model_utils.py", "/lib/io/reporting.py"], "/lib/interfaces/ext... | └──
├── generate_plots
├── hist_to_probdist.py
├── learn_topics
├── lib
│ ├── evaluation
│ │ ├── analyse_bins.py
│ │ ├── evaluate.py
│ │ ├── evaluate_window.py
│ │ ├── pairwise.py
│ │ ├── play.py
│ │ └── sliding_window.py
│ ├── graphs.py
│... | /generate_plots | #!/bin/python2
import cPickle as pickle
import lib.io.pickled_globals
import lib.graphs as graphs
for i in range(1,10):
hist = pickle.load(open('graphs/histograms/w%d_histograms'%(i+1),'rb'))
graphs.plot_hist(20,hist, upper = 50,directory='hist_%d_topics'%(i+1))
| /hist_to_probdist.py | #!/usr/bin/python2
import os
import numpy as np
import cPickle as pickle
from collections import defaultdict
import lib.io.pickled_globals
import lib.graphs as graphs
def main():
directory = 'graphs/prob_dist'
if not os.path.exists(directory): os.makedirs(directory)
for i in range(1,10):
hist = pickle.load(open(... | /learn_topics | #!/usr/bin/python
from algo.lda import LDASampler
from lib.io.reader import windowed,filter_tokenise
import pickle
import sys
from collections import defaultdict
window_size_max = int(sys.argv[1])
num_topics_max = int(sys.argv[2])
documents = ["data/%s"%i.strip() for i in open(sys.argv[3])]
output = sys.argv[-1]
wi... | /lib/evaluation/analyse_bins.py | import sys,operator
import shelve
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import bsddb3
from collections import defaultdict
K = int(sys.argv[1])
output_file = sys.argv[2]
transit_file = sys.argv[3]
bins = shelve.BsdDbShelf(bsddb3.hashopen('bins.data', 'r'))
#bins = shelve.open('b... | /lib/evaluation/evaluate.py | #!/usr/bin/python2
from lib.io.reader import windowed
from lib.io.reporting import reporting_init,timestamp_log
from lib.io.util import *
from lib.options import *
from lib.interfaces.model_utils import unpickle_model
from lib.evaluation.sliding_window import SlidingWindow
from lib.evaluation.pairwise imp... | /lib/evaluation/evaluate_window.py | #!/usr/bin/python2
from lib.io.reader import windowed
from lib.io.reporting import reporting_init,timestamp_log
from lib.io.util import *
from lib.options import *
from lib.interfaces.model_utils import unpickle_model
def evaluate(threadfile, model, extractor, window_size = 1, bandwidth = 1000000, LAG_TIM... | /lib/evaluation/pairwise.py | import math
class PairwiseScoring():
def __init__(self,scoring = {
('visit','visit') : lambda e1,e2: math.exp(0.01*(e1-e2)),
('post', 'visit') : lambda e1,e2: 1-math.exp(0.01*(e1-e2)),
('post', 'post' ) : lambda e1,e2: 0 ,
('visit','post' ) : lambda e1,e2: 0}):
self.total_score = 0
self.count = 0
... | /lib/evaluation/play.py | from lib.io.reporting import set_directory
from lib.io.util import load_from_file
from lib.options import *
from lib.interfaces.model_utils import unpickle_model
import os
import glob
import matplotlib as mpl
mpl.use('Agg')
from matplotlib import pyplot
import numpy as np
def plot(values,output,
x_axis = 'Values',
... | /lib/evaluation/sliding_window.py | class SlidingWindow():
def __init__(self,K = 60, alpha = 0.5):
self.window = []
self.low = 0
self.window_size = K
self.alpha = alpha
self.phi_count = 0
self.psi_count = 0
self.ref_count = 0
self.all_count = 0
def event(self,event_type,time):
time = int(time)
if time >= self.low + self.window_siz... | /lib/graphs.py | import os
def plot_hist(bin_size, bin_list, directory=None, upper=None):
if not os.path.exists(directory): os.makedirs(directory)
import matplotlib.pyplot as plt
count = 1
for bins in bin_list:
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
up_bound = upper or max(bins)
x = [i for i in range(up_bound+1)]
... | /lib/interfaces/extractor_utils.py | '''
Created on Jul 19, 2012
@author: shawn
'''
from lib.io.reporting import get_directory
from lib.options import read_options
from lib.io.reader import windowed
from lib.io.util import load_from_file
import pickle
def save_model(filename,model):
f = open("%s/%s"%(get_directory(),filename),'wb')
pickle.dump(mode... | /lib/interfaces/generic_model.py | '''
Created on Jul 17, 2012
@author: shawn
'''
import md5
from model_utils import save_model
from collections import defaultdict
class GenericModel(object):
epsilon = 0.1
def __init__(self,o):
self.options = o
self.experiments = defaultdict(list)
def predict(self,feature_vec = None, d_t = None, current_d_t =... | /lib/interfaces/model_utils.py | '''
Created on Jul 19, 2012
@author: shawn
'''
from lib.io.reporting import get_directory
import pickle
def save_model(filename,model):
fullpath = "%s/%s"%(get_directory(),filename)
f = open(fullpath,'wb')
pickle.dump(model,f)
f.close()
return fullpath
def unpickle_model(filepath):
return pickle.load(filepath)... | /lib/io/__init__.py | import pickled_globals
import writer
| /lib/io/dataset.py | import numpy as np
from sklearn import linear_model
from itertools import permutations
from lang_model import Extractor
from utils.reader import *
import csv,sys
count = 0
clf = linear_model.LinearRegression()
filenames = [sys.argv[1]]
filename_x = "X"
filename_y = "Y"
window_size = 15
e = Extractor()
count = sum(1 ... | /lib/io/pickled_globals.py | import cPickle as pickle
class pickled_globals(object):
def __init__(self,pg_dir):
self.pg_dir = pg_dir
def __getattr__(self, attr_name):
"""
Loads the file from pg_dir into an object,
then caches the object in memory.
"""
obj = pickle.load(open('%s/%s'%(self.pg_dir,attr_name),'rb'))
self.__setattr__(a... | /lib/io/reader.py | #!/usr/bin/python2
import nltk,re
from nltk.stem.porter import PorterStemmer
import time
bin_size = 10
users = set()
def text_tdelta(input_file):
prev_tup = None
for line in open(input_file):
tup = line.split('\t')
if prev_tup: yield (
(float(tup[0])-float(prev_tup[0]))/60,
tup[1].strip(),
tup[2].st... | /lib/io/reporting.py | REPORTS = None
SUBDIR = None
import sys,os
from datetime import datetime
def set_directory(directory):
global SUBDIR
SUBDIR = directory
def get_directory():
global SUBDIR
return SUBDIR
def reporting_init(options,directory):
global SUBDIR,REPORTS
REPORTS = directory
SUBDIR = '%s/%s'%(directory,datetime.now().st... | /lib/io/util.py | from reader import windowed
import sys, imp, traceback, md5, pickle
def load_from_file(filepath,class_name,*params):
class_inst = None
"""
mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1])
if file_ext.lower() == '.py':
py_mod = imp.load_source(mod_name, filepath)
elif file_ext.lower() == '.pyc'... | /lib/io/writer.py | '''
Created on Sep 24, 2012
@author: shawn
'''
from lib.options.config import configuration as config
import __builtin__
class FileWrapper(object):
def __init__(self,obj):
self._obj = obj
def close(self,*args,**kwargs):
print "Closing file..."
self._obj.close(*args,**kwargs)
def __getattr__(self, attr):
... | /lib/options/__init__.py | import options,config
| /lib/options/config.py | import ConfigParser
from collections import namedtuple
sections = ['dirs','filename_formats']
def subconf(section):
Conf = namedtuple(section,(k for k,_ in c.items(section)))
conf = Conf(**dict(c.items(section)))
return conf
c = ConfigParser.RawConfigParser()#allow_no_value=True)
c.readfp(open('config','r'))
PConf =... | /lib/options/options.py | from optparse import OptionParser
from random import random
opts,args = None,None
p_opts = None
def read_options():
global opts,args
p = OptionParser()
p.add_option("-M","--model",metavar = "MODEL_PATH.py",
action = "store",
dest = "model_name",
help = "Model to be used for current experiment"... | /lib/training/test.py | import lda
from utils.reader import windowed,filter_tokenise
import sys
import matplotlib.pyplot as plt
from collections import defaultdict
def plot_hist(bin_size,bin_list, upper =None):
for bins in bin_list:
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
up_bound = upper or max(bins)
x = [i for i in range(up_... | /lib/training/trainer.py | from utils.reader import windowed
from utils.reporting import *
from utils.util import *
from regression_performance import performance
import pickle,math,getopt
def train(model,extractor,filenames,window_size,iterations = 1):
for _ in range(iterations):
for f in filenames:
try:
model.train(extracted... | /lib/training/trainer_test.py | from utils.reader import windowed
from utils.reporting import *
from utils.util import *
import pickle,math,getopt
from evaluate_window import evaluate as evaluate_window
from utils.options import read_options, read_model_extractor_options
def train(model,extractor,iterator,window_size,iterations = 1):
for _ i... | /preamble.py | import cPickle as pickle
import lib.io.pickled_globals
import lib.graphs as graphs
| /predictor.py | import cPickle as pickle
import sys
import lib.io.pickled_globals
import lib.graphs as graphs
from hist_to_probdist import time_dist
from lib.io.reader import windowed,filter_tokenise
window_size = 15
time_bin = 20
def load_model(topics):
timdist = pickle.load(open('graphs/prob_dist/dist_t%03d'%topics,'rb'))
lda =... | /print_topics | #!/bin/python2
import cPickle as pickle
import lib.io.pickled_globals
import lib.graphs as graphs
for i in range(1,10):
print "Loading pickled topic model with %d topics ..."%(i+1)
lda = pickle.load(open('global_objs/w15_t%d_learnt_topics'%(i+1),'rb'))
print "Retrieving topics..."
top_tok = lda.topic_keys(num_... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
supasate/FBPCS | refs/heads/main | {"/fbpcs/decorator/error_handler.py": ["/fbpcs/error/mapper/aws.py"], "/tests/error/mapper/test_aws.py": ["/fbpcs/error/mapper/aws.py"], "/fbpcs/service/log_cloudwatch.py": ["/fbpcs/gateway/cloudwatch.py", "/fbpcs/service/log.py"], "/tests/gateway/test_cloudwatch.py": ["/fbpcs/gateway/cloudwatch.py"], "/fbpcs/entity/mp... | └──
├── fbpcs
│ ├── decorator
│ │ └── error_handler.py
│ ├── entity
│ │ ├── container_instance.py
│ │ ├── instance_base.py
│ │ ├── mpc_instance.py
│ │ └── vpc_instance.py
│ ├── error
│ │ └── mapper
│ │ └── aws.py
│ ├── gateway
... | /fbpcs/decorator/error_handler.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable
from botocore.exceptions import ClientError
from fbpcs.error.mapper.aws import map_aws_err... | /fbpcs/entity/container_instance.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from dataclasses import dataclass
from enum import Enum
from typing import Optional
from dataclasses_js... | /fbpcs/entity/instance_base.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import abc
class InstanceBase(abc.ABC):
@abc.abstractmethod
def get_instance_id(self) -> str:
... | /fbpcs/entity/mpc_instance.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from dataclasses import dataclass
from enum import Enum
from typing import Any, Dict, List, Mapping, Opt... | /fbpcs/entity/vpc_instance.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict
from dataclasses... | /fbpcs/error/mapper/aws.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from botocore.exceptions import ClientError
from fbpcs.error.pcs import PcsError
from fbpcs.error.thrott... | /fbpcs/gateway/cloudwatch.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from typing import Any, Dict, Optional
import boto3
from fbpcs.decorator.error_handler import error_han... | /fbpcs/gateway/ec2.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from typing import Any, Dict, List, Optional
import boto3
from fbpcs.decorator.error_handler import err... | /fbpcs/gateway/ecs.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from typing import Any, Dict, List, Optional
import boto3
from fbpcs.decorator.error_handler import err... | /fbpcs/gateway/s3.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import os
from typing import Any, Dict, List, Optional
import boto3
from fbpcs.decorator.error_handler ... | /fbpcs/mapper/aws.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from functools import reduce
from typing import Any, Dict, List
from fbpcs.entity.cluster_instance impo... | /fbpcs/repository/instance_s3.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import pickle
from fbpcs.entity.instance_base import InstanceBase
from fbpcs.service.storage_s3 import ... | /fbpcs/repository/mpc_game_repository.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import abc
from fbpcs.entity.mpc_game_config import MPCGameConfig
class MPCGameRepository(abc.ABC):
... | /fbpcs/repository/mpc_instance_local.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from typing import cast
from fbpcs.entity.mpc_instance import MPCInstance
from fbpcs.repository.instanc... | /fbpcs/service/container.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import abc
from typing import List
from fbpcs.entity.container_instance import ContainerInstance
clas... | /fbpcs/service/container_aws.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import asyncio
from typing import Any, Dict, List, Optional, Tuple
from fbpcs.entity.container_instance... | /fbpcs/service/log.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import abc
from typing import Any, Dict
class LogService(abc.ABC):
@abc.abstractmethod
def fet... | /fbpcs/service/log_cloudwatch.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from typing import Any, Dict, Optional
from fbpcs.gateway.cloudwatch import CloudWatchGateway
from fbpc... | /fbpcs/service/mpc.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import asyncio
import logging
from typing import Any, Dict, List, Optional
from fbpcs.entity.container_... | /fbpcs/service/onedocker.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import asyncio
import logging
from typing import List, Optional
from fbpcs.entity.container_instance im... | /fbpcs/service/storage.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import abc
from enum import Enum
class PathType(Enum):
Local = 1
S3 = 2
class StorageService... | /fbpcs/service/storage_s3.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import os
from os import path
from os.path import join, normpath, relpath
from typing import Any, Dict, ... | /fbpcs/util/reflect.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from importlib import import_module
from typing import Any
# pyre-ignore
def get_class(class_path: str... | /fbpcs/util/s3path.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import re
from typing import Tuple
class S3Path:
region: str
bucket: str
key: str
def... | /fbpcs/util/typing.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from typing import Type, TypeVar
T = TypeVar("T")
V = TypeVar("V")
# pyre-fixme[34]: `T` isn't prese... | /fbpcs/util/yaml.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from pathlib import Path
from typing import Any, Dict
import yaml
def load(file_path: Path) -> Dict[s... | /onedocker/env.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# This is the repository path that OneDocker downloads binaries from
ONEDOCKER_REPOSITORY_PATH = "ONEDOCKER_REPOSITORY_... | /onedocker/onedocker_runner.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
CLI for running an executable in one docker
Usage:
onedocker-runner <package_name> --cmd=<cmd> [options]
Op... | /onedocker/tests/test_util.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import subprocess
import unittest
from util import run_cmd
class TestUtil(unittest.TestCase):
def test_run_cmd(s... | /onedocker/util.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import signal
import subprocess
from typing import Optional
def run_cmd(cmd: str, timeout: Optional[int]) -... | /setup.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from setuptools import setup, find_packages
install_requires = [
"boto3==1.11.11",
"dataclasses-json==0.5.2",... | /tests/decorator/test_error_handler.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from botocore.exceptions import ClientError
from fbpcs.decorator.error_handler import error_handler
fr... | /tests/error/mapper/test_aws.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from botocore.exceptions import ClientError
from fbpcs.error.mapper.aws import map_aws_error
from fbpc... | /tests/gateway/test_cloudwatch.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from unittest.mock import MagicMock, patch
from fbpcs.gateway.cloudwatch import CloudWatchGateway
cl... | /tests/gateway/test_ec2.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from unittest.mock import MagicMock, patch
from fbpcs.entity.vpc_instance import Vpc, VpcState
from fb... | /tests/gateway/test_ecs.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from unittest.mock import MagicMock, patch
from fbpcs.entity.cluster_instance import ClusterStatus, Cl... | /tests/gateway/test_s3.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from unittest.mock import MagicMock, patch
from fbpcs.gateway.s3 import S3Gateway
class TestS3Gatewa... | /tests/mapper/test_aws.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from fbpcs.entity.cluster_instance import ClusterStatus, Cluster
from fbpcs.entity.container_instance ... | /tests/repository/test_instance_s3.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import pickle
import unittest
import uuid
from unittest.mock import MagicMock
from fbpcs.entity.mpc_instance import MP... | /tests/service/test_container_aws.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from unittest.mock import MagicMock, patch
from fbpcs.service.container_aws import (
ContainerInst... | /tests/service/test_log_cloudwatch.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from unittest.mock import MagicMock, patch
from fbpcs.service.log_cloudwatch import CloudWatchLogServi... | /tests/service/test_mpc.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from unittest.mock import AsyncMock, MagicMock, patch
from fbpcs.entity.container_instance import Cont... | /tests/service/test_onedocker.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from unittest.mock import AsyncMock, patch
from fbpcs.entity.container_instance import ContainerInstan... | /tests/service/test_storage.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from fbpcs.service.storage import PathType, StorageService
class TestStorageService(unittest.TestCas... | /tests/service/test_storage_s3.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import unittest
from unittest.mock import call, MagicMock, patch
from fbpcs.service.storage_s3 import S3Stor... | /tests/util/test_reflect.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from fbpcs.util.reflect import get_class
from fbpcs.util.s3path import S3Path
TEST_CLASS_PATH = "fbpc... | /tests/util/test_s3path.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from fbpcs.util.s3path import S3Path
class TestS3Path(unittest.TestCase):
def test_s3path_no_sub... | /tests/util/test_typing.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from fbpcs.util.typing import checked_cast
TEST_STR = "test"
TEST_NUM = 123
class TestTyping(unitte... | /tests/util/test_yaml.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import json
import unittest
from unittest.mock import patch, mock_open
from fbpcs.util.yaml import load, dump
TEST_FI... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
estebanfloresf/testcases | refs/heads/master | {"/testcases/spiders/createTestCase.py": ["/testcases/items.py"], "/testcases/spiders/testSpider.py": ["/testcases/items.py"]} | └──
├── testcases
│ ├── items.py
│ ├── main.py
│ ├── spiders
│ │ ├── createTestCase.py
│ │ └── testSpider.py
│ └── variables.py
└── utils
├── generateTC.py
├── readFiles.py
└── readTestCases.py | /testcases/items.py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class TestCasesItem(scrapy.Item):
component = scrapy.Field()
requirements = scrapy.Field()
responsive = scrapy.Field()
pass
class Requ... | /testcases/main.py | from scrapy import cmdline
import os
import inspect
import logging
path = os.path.abspath(os.path.join(os.path.dirname(
os.path.realpath(__file__)), os.pardir)) # script directory
# To generate the verified labels from the input excel (uncomment line below)
# os.system('python '+path+'\\utils\\generateTC.py')
... | /testcases/spiders/createTestCase.py | # -*- coding: utf-8 -*-
import scrapy
from scrapy.utils.project import get_project_settings
from ..items import TestCasesItem
from scrapy.loader import ItemLoader
class createTestCaseSpider(scrapy.Spider):
name = "createTestCase"
settings = get_project_settings()
http_user = settings.get('HTTP_USER')
... | /testcases/spiders/testSpider.py | # -*- coding: utf-8 -*-
import scrapy
from scrapy import Request
from scrapy.utils.project import get_project_settings
from ..items import TestCasesItem, Responsive, Requirements
from scrapy.spidermiddlewares.httperror import HttpError
from twisted.internet.error import DNSLookupError
from twisted.internet.error import... | /testcases/variables.py | USER='Esteban.Flores'
PASS='estebanFS10' | /utils/generateTC.py | from openpyxl import load_workbook
#import the pandas library and aliasing as pd and numpy as np
import pandas as pd
import numpy as np
import os
class createTestCase():
def __init__(self):
self.dir_path = os.path.dirname(os.path.realpath(__file__))
self.wb = load_workbook(self.dir_path+... | /utils/readFiles.py | import os
import re
path = os.chdir('C://Users//503025052//Documents//GE//GE TestCases')
filenames = os.listdir(path)
for index,filename in enumerate(filenames):
try:
extension = os.path.splitext(filename)[1][1:]
if(extension=='xlsx'):
number =re.findall(r'\d+', str(filename))
... | /utils/readTestCases.py | from openpyxl import load_workbook
import re
import json
class readFile():
def __init__(self):
path = 'C:\\Users\\Esteban.Flores\\Documents\\1 Verndale\\2 Projects\\GE-GeneralElectric\\GE TestCases\\0942-(QA) Course Registration Module.xlsx'
self.wb = load_workbook(path, data_only=True)
sel... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
RobMurray98/BribeNet | refs/heads/master | {"/src/BribeNet/graph/generation/generator.py": ["/src/BribeNet/graph/generation/__init__.py"], "/src/BribeNet/graph/generation/flatWeightGenerator.py": ["/src/BribeNet/graph/generation/__init__.py", "/src/BribeNet/graph/generation/weightedGenerator.py"], "/src/BribeNet/graph/generation/unweightedGenerator.py": ["/src/... | └──
├── setup.py
├── src
│ ├── BribeNet
│ │ ├── bribery
│ │ │ ├── briber.py
│ │ │ ├── static
│ │ │ │ ├── briber.py
│ │ │ │ ├── influentialNodeBriber.py
│ │ │ │ ├── nonBriber.py
│ │ │ │ ├── oneMoveInfluentialNodeBriber.py
│ ... | /setup.py | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="BribeNet",
version="1.0.0",
author="Robert Murray",
author_email="R.Murray.1@warwick.ac.uk",
description="Simulation of networks of bribers and consumers",
long_description=long_descri... | /src/BribeNet/bribery/briber.py | from abc import ABC
from typing import Optional
from BribeNet.helpers.bribeNetException import BribeNetException
class BriberyGraphNotSetException(BribeNetException):
pass
class BriberyGraphAlreadySetException(BribeNetException):
pass
class BriberNotRegisteredOnGraphException(BribeNetException):
pass... | /src/BribeNet/bribery/static/briber.py | from abc import ABC, abstractmethod
from BribeNet.bribery.briber import Briber, BriberyGraphNotSetException
from BribeNet.helpers.bribeNetException import BribeNetException
class GraphNotSubclassOfStaticRatingGraphException(BribeNetException):
pass
class StaticBriber(Briber, ABC):
"""
Static bribers pe... | /src/BribeNet/bribery/static/influentialNodeBriber.py | from BribeNet.bribery.static.briber import StaticBriber
from BribeNet.helpers.override import override
class InfluentialNodeBriber(StaticBriber):
def __init__(self, u0, k=0.1):
super().__init__(u0)
self._k = k # will be reassigned when graph set
@override
def _set_graph(self, g):
... | /src/BribeNet/bribery/static/nonBriber.py | from BribeNet.bribery.static.briber import StaticBriber
# performs no bribery
class NonBriber(StaticBriber):
def _next_bribe(self):
pass
| /src/BribeNet/bribery/static/oneMoveInfluentialNodeBriber.py | from BribeNet.bribery.briber import BriberyGraphNotSetException
from BribeNet.bribery.static.briber import StaticBriber
from BribeNet.helpers.override import override
class OneMoveInfluentialNodeBriber(StaticBriber):
def __init__(self, u0, k=0.1):
super().__init__(u0)
self.influencers = []
... | /src/BribeNet/bribery/static/oneMoveRandomBriber.py | import random
import numpy as np
from BribeNet.bribery.static.briber import StaticBriber
class OneMoveRandomBriber(StaticBriber):
def _next_bribe(self):
customers = self.get_graph().get_customers()
# pick random customer from list
c = random.choice(customers)
max_rating = self.g... | /src/BribeNet/bribery/static/randomBriber.py | import random
from BribeNet.bribery.static.briber import StaticBriber
DELTA = 0.001 # ensures total bribes do not exceed budget
class RandomBriber(StaticBriber):
def _next_bribe(self):
customers = self.get_graph().get_customers()
# array of random bribes
bribes = [random.uniform(0.0, 1... | /src/BribeNet/bribery/temporal/action/__init__.py | from BribeNet.helpers.bribeNetException import BribeNetException
class BribeMustBeGreaterThanZeroException(BribeNetException):
pass
class NodeDoesNotExistException(BribeNetException):
pass
class BriberDoesNotExistException(BribeNetException):
pass
class BriberyActionExceedsAvailableUtilityException(... | /src/BribeNet/bribery/temporal/action/briberyAction.py | from abc import ABC, abstractmethod
from typing import List
from BribeNet.helpers.bribeNetException import BribeNetException
class BriberyActionExecutedMultipleTimesException(BribeNetException):
pass
class BriberyActionTimeNotCorrectException(BribeNetException):
pass
class BriberyAction(ABC):
def __... | /src/BribeNet/bribery/temporal/action/multiBriberyAction.py | import sys
from typing import Dict, Optional, List
from BribeNet.bribery.temporal.action import BribeMustBeGreaterThanZeroException, NodeDoesNotExistException, \
BriberDoesNotExistException, BriberyActionExceedsAvailableUtilityException
from BribeNet.bribery.temporal.action.briberyAction import BriberyAction
from ... | /src/BribeNet/bribery/temporal/action/singleBriberyAction.py | import sys
from typing import Dict, Optional
from BribeNet.bribery.temporal.action import BribeMustBeGreaterThanZeroException, NodeDoesNotExistException, \
BriberyActionExceedsAvailableUtilityException
from BribeNet.bribery.temporal.action.briberyAction import BriberyAction
class SingleBriberyAction(BriberyActio... | /src/BribeNet/bribery/temporal/briber.py | from abc import ABC, abstractmethod
from BribeNet.bribery.briber import Briber, BriberyGraphNotSetException
from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.helpers.bribeNetException import BribeNetException
class GraphNotSubclassOfTemporalRatingGraphException(BribeN... | /src/BribeNet/bribery/temporal/mostInfluentialNodeBriber.py | import sys
import numpy as np
from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.bribery.temporal.briber import TemporalBriber
class MostInfluentialNodeBriber(TemporalBriber):
def __init__(self, u0: float, k: float = 0.1, i: int = 7):
"""
Construct... | /src/BribeNet/bribery/temporal/nonBriber.py | from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.bribery.temporal.briber import TemporalBriber
class NonBriber(TemporalBriber):
def _next_action(self) -> SingleBriberyAction:
return SingleBriberyAction(self)
| /src/BribeNet/bribery/temporal/oneMoveEvenBriber.py | import random
import numpy as np
from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.bribery.temporal.briber import TemporalBriber
class OneMoveEvenBriber(TemporalBriber):
def _next_action(self) -> SingleBriberyAction:
customers = self.get_graph().get_cust... | /src/BribeNet/bribery/temporal/pGreedyBriber.py | import sys
import numpy as np
from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.bribery.temporal.briber import TemporalBriber
"""
IMPORTANT!
This briber cheats and uses the direct influential node information.
This is for testing whether trust is powerful enough to bea... | /src/BribeNet/bribery/temporal/randomBriber.py | import random
from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.bribery.temporal.briber import TemporalBriber
DELTA = 0.001 # ensures total bribes do not exceed budget
class RandomBriber(TemporalBriber):
def _next_action(self) -> SingleBriberyAction:
cu... | /src/BribeNet/graph/generation/__init__.py | import enum
from networkit.generators import WattsStrogatzGenerator, BarabasiAlbertGenerator
from BribeNet.graph.generation.algo.compositeGenerator import CompositeGenerator
from BribeNet.helpers.bribeNetException import BribeNetException
class GraphGenerationAlgoNotDefinedException(BribeNetException):
pass
@... | /src/BribeNet/graph/generation/algo/compositeGenerator.py | from math import floor, log, ceil
from random import gauss, sample, random
import networkit as nk
# noinspection PyUnresolvedReferences
from networkit import Graph
from networkit.generators import BarabasiAlbertGenerator, WattsStrogatzGenerator
def _make_complete(n: int):
g_ = Graph(n)
for i in g_.iterNodes(... | /src/BribeNet/graph/generation/flatWeightGenerator.py | import networkit as nk
import networkit.nxadapter as adap
from BribeNet.graph.generation import GraphGeneratorAlgo
from BribeNet.graph.generation.weightedGenerator import WeightedGraphGenerator
class FlatWeightedGraphGenerator(WeightedGraphGenerator):
def __init__(self, a: GraphGeneratorAlgo, *args, **kwargs):
... | /src/BribeNet/graph/generation/generator.py | import abc
# noinspection PyUnresolvedReferences
from networkit import Graph
from BribeNet.graph.generation import GraphGeneratorAlgo, algo_to_constructor
class GraphGenerator(abc.ABC):
def __init__(self, a: GraphGeneratorAlgo, *args, **kwargs):
"""
Thin wrapper class for NetworKit graph genera... | /src/BribeNet/graph/generation/unweightedGenerator.py | from BribeNet.graph.generation import GraphGeneratorAlgo
from BribeNet.graph.generation.generator import GraphGenerator
class UnweightedGraphGenerator(GraphGenerator):
def __init__(self, a: GraphGeneratorAlgo, *args, **kwargs):
super().__init__(a, *args, **kwargs)
def generate(self):
return ... | /src/BribeNet/graph/generation/weightedGenerator.py | import abc
from BribeNet.graph.generation import GraphGeneratorAlgo
from BribeNet.graph.generation.generator import GraphGenerator
class WeightedGraphGenerator(GraphGenerator, abc.ABC):
def __init__(self, a: GraphGeneratorAlgo, *args, **kwargs):
"""
Thin wrapper class for NetworKit graph generat... | /src/BribeNet/graph/ratingGraph.py | import random
from abc import ABC
from copy import deepcopy
from typing import Tuple, Optional, List, Any, Set
import networkit as nk
import numpy as np
from weightedstats import weighted_mean, weighted_median, mean, median
from BribeNet.graph.generation import GraphGeneratorAlgo
from BribeNet.graph.generation.flatWe... | /src/BribeNet/graph/ratingMethod.py | import enum
@enum.unique
class RatingMethod(enum.Enum):
O_RATING = 0
P_RATING = 1
MEDIAN_P_RATING = 2
SAMPLE_P_RATING = 3
P_GAMMA_RATING = 4
WEIGHTED_P_RATING = 5
WEIGHTED_MEDIAN_P_RATING = 6
| /src/BribeNet/graph/static/ratingGraph.py | import random
from typing import Tuple, Union, Any
import numpy as np
from BribeNet.graph.ratingGraph import RatingGraph, DEFAULT_GEN, BribersAreNotTupleException, NoBriberGivenException
from BribeNet.helpers.bribeNetException import BribeNetException
from BribeNet.helpers.override import override
DEFAULT_NON_VOTER_... | /src/BribeNet/graph/static/ratingGraphBuilder.py | import enum
import sys
from typing import List
from BribeNet.bribery.briber import Briber
from BribeNet.bribery.static.influentialNodeBriber import InfluentialNodeBriber
from BribeNet.bribery.static.mostInfluentialNodeBriber import MostInfluentialNodeBriber
from BribeNet.bribery.static.nonBriber import NonBriber
from ... | /src/BribeNet/graph/temporal/action/actionType.py | import enum
@enum.unique
class ActionType(enum.Enum):
NONE = 0
BRIBED = 1
SELECT = 2
| /src/BribeNet/graph/temporal/action/customerAction.py | from typing import Dict, Any, Tuple, List
import numpy as np
from BribeNet.bribery.temporal.action.briberyAction import BriberyAction
from BribeNet.bribery.temporal.briber import GraphNotSubclassOfTemporalRatingGraphException
from BribeNet.graph.temporal.action.actionType import ActionType
from BribeNet.helpers.bribe... | /src/BribeNet/graph/temporal/noCustomerActionGraph.py | from BribeNet.graph.ratingGraph import DEFAULT_GEN
from BribeNet.graph.temporal.action.customerAction import CustomerAction
from BribeNet.graph.temporal.ratingGraph import TemporalRatingGraph
class NoCustomerActionGraph(TemporalRatingGraph):
"""
A temporal rating graph solely for testing purposes.
"""
... | /src/BribeNet/graph/temporal/ratingGraph.py | import abc
import random
from sys import maxsize
from typing import Tuple, Union, Any, Optional, List
import numpy as np
from BribeNet.bribery.temporal.action.briberyAction import BriberyAction
from BribeNet.bribery.temporal.action.multiBriberyAction import MultiBriberyAction
from BribeNet.graph.ratingGraph import DE... | /src/BribeNet/graph/temporal/thresholdGraph.py | import random
from typing import List
import numpy as np
from BribeNet.graph.ratingGraph import DEFAULT_GEN
from BribeNet.graph.temporal.action.actionType import ActionType
from BribeNet.graph.temporal.action.customerAction import CustomerAction
from BribeNet.graph.temporal.ratingGraph import TemporalRatingGraph, Bri... | /src/BribeNet/graph/temporal/weighting/communityWeighting.py | import random
# noinspection PyUnresolvedReferences
from networkit import Graph
# noinspection PyUnresolvedReferences
from networkit.community import PLM
def get_communities(graph: Graph) -> [[int]]:
"""
Gets the underlying communities of the graph, as sets of nodes.
"""
communities = PLM(graph, refi... | /src/BribeNet/graph/temporal/weighting/traverseWeighting.py | from random import gauss
# noinspection PyUnresolvedReferences
from networkit import Graph
from numpy import mean as average
def assign_traverse_averaged(graph: Graph, mean: float, std_dev: float = 0.2) -> [float]:
"""
Assign node 0 with the mean. Then assign all of its neighbours with a value
close to t... | /src/BribeNet/gui/apps/main.py | import tkinter as tk
class Main(tk.Frame):
"""
Frame for the main menu of the GUI
"""
def __init__(self, master, *args, **kwargs):
tk.Frame.__init__(self, master=master, *args, **kwargs)
title_text = tk.Label(self, text="Bribery Networks", font=("Calibri", 16, "bold"), pady=20)
... | /src/BribeNet/gui/apps/static/briber_wizard/frame.py | import tkinter as tk
class StaticBriberWizardFrame(tk.Frame):
"""
Frame for pop-up wizard for adding a static briber
"""
pass
| /src/BribeNet/gui/apps/static/briber_wizard/window.py | import tkinter as tk
class StaticBriberWizardWindow(tk.Toplevel):
"""
Window for pop-up wizard for adding a static briber
"""
pass
| /src/BribeNet/gui/apps/static/graph.py | import tkinter as tk
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.colors import rgb2hex
from networkit.nxadapter import nk2nx
from networkit.viztasks import drawGraph
from networkx import spring_layout
class GraphFrame(tk.Frame):
... | /src/BribeNet/gui/apps/static/result.py | import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class ResultsFrame(tk.Frame):
"""
Frame for showing the current results of the static model being run
"""
def __init__(self, parent, controller):
tk.Frame.__init__(self, paren... | /src/BribeNet/gui/apps/static/static.py | import tkinter as tk
from BribeNet.bribery.static.oneMoveInfluentialNodeBriber import OneMoveInfluentialNodeBriber
from BribeNet.bribery.static.oneMoveRandomBriber import OneMoveRandomBriber
from BribeNet.graph.generation import GraphGeneratorAlgo
from BribeNet.graph.generation.flatWeightGenerator import FlatWeightedG... | /src/BribeNet/gui/apps/static/wizard/algos/barabasi_albert.py | import tkinter as tk
from BribeNet.gui.classes.param_list_frame import ParamListFrame
class BarabasiAlbert(ParamListFrame):
name = "Barabási-Albert"
def __init__(self, parent):
super().__init__(parent)
self.params = {
'k': tk.DoubleVar(self, value=5),
'n_max': tk.Int... | /src/BribeNet/gui/apps/static/wizard/algos/composite.py | import tkinter as tk
from BribeNet.gui.classes.param_list_frame import ParamListFrame
class Composite(ParamListFrame):
name = "Composite"
def __init__(self, parent):
super().__init__(parent)
self.params = {
'n_nodes': tk.IntVar(self, value=50),
'n_communities': tk.In... | /src/BribeNet/gui/apps/static/wizard/algos/watts_strogatz.py | import tkinter as tk
from BribeNet.gui.classes.param_list_frame import ParamListFrame
class WattsStrogatz(ParamListFrame):
name = "Watts-Strogatz"
def __init__(self, parent):
super().__init__(parent)
self.params = {
'n_nodes': tk.IntVar(self, value=30),
'n_neighbours... | /src/BribeNet/gui/apps/static/wizard/generation.py | import tkinter as tk
from BribeNet.gui.apps.static.wizard.algos.barabasi_albert import BarabasiAlbert
from BribeNet.gui.apps.static.wizard.algos.composite import Composite
from BribeNet.gui.apps.static.wizard.algos.watts_strogatz import WattsStrogatz
ALGO_SUBFRAMES = (BarabasiAlbert, Composite, WattsStrogatz)
ALGO_DI... | /src/BribeNet/gui/apps/static/wizard/wizard.py | import tkinter as tk
class WizardFrame(tk.Frame):
"""
Frame for the wizard to construct a static model run
"""
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
gtype = tk.StringVar(parent)
gtype.set("L")
btyp... | /src/BribeNet/gui/apps/temporal/briber_wizard/frame.py | import tkinter as tk
from BribeNet.gui.apps.temporal.briber_wizard.strategies.budget import BudgetFrame
from BribeNet.gui.apps.temporal.briber_wizard.strategies.even import EvenFrame
from BribeNet.gui.apps.temporal.briber_wizard.strategies.influential import InfluentialFrame
from BribeNet.gui.apps.temporal.briber_wiza... | /src/BribeNet/gui/apps/temporal/briber_wizard/strategies/p_greedy.py | import tkinter as tk
from BribeNet.gui.classes.param_list_frame import ParamListFrame
class PGreedyFrame(ParamListFrame):
name = "P-Greedy"
def __init__(self, parent):
super().__init__(parent)
self.params = {
'u_0': tk.DoubleVar(self, value=10),
'true_average': tk.Do... | /src/BribeNet/gui/apps/temporal/briber_wizard/window.py | import tkinter as tk
from BribeNet.gui.apps.temporal.briber_wizard.frame import TemporalBriberWizardFrame
from BribeNet.helpers.override import override
class TemporalBriberWizardWindow(tk.Toplevel):
"""
Window for pop-up wizard for adding a temporal briber
"""
def __init__(self, controller):
... | /src/BribeNet/gui/apps/temporal/graph.py | import tkinter as tk
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.colors import rgb2hex
from networkit.viztasks import drawGraph
from BribeNet.gui.apps.temporal.results_wizard.window import TemporalResultsWizardWindow
class GraphF... | /src/BribeNet/gui/apps/temporal/main.py | import tkinter as tk
import os
from networkit.nxadapter import nk2nx
from networkx import spring_layout
from BribeNet.bribery.temporal.budgetNodeBriber import BudgetNodeBriber
from BribeNet.bribery.temporal.influentialNodeBriber import InfluentialNodeBriber
from BribeNet.bribery.temporal.mostInfluentialNodeBriber imp... | /src/BribeNet/gui/apps/temporal/result.py | import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from BribeNet.gui.apps.temporal.results_wizard.window import TemporalResultsWizardWindow
class ResultsFrame(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, pare... | /src/BribeNet/gui/apps/temporal/results_wizard/frame.py | import tkinter as tk
class TemporalResultsWizardFrame(tk.Frame):
"""
Frame for pop-up wizard for selecting results displayed
"""
def __init__(self, parent, results):
super().__init__(parent)
self.parent = parent
self.x_string_var = tk.StringVar(self)
self.y_string_var... | /src/BribeNet/gui/apps/temporal/results_wizard/results.py | class ResultsStore:
"""
Class for storing results during runs, identified by keys, seperated to xs and ys
"""
def __init__(self, xs, ys):
self.xs = xs
self.ys = ys
self.data = {k: [] for k in (xs + ys)}
def add(self, k, v):
self.data[k].append(v)
def get(self, ... | /src/BribeNet/gui/apps/temporal/results_wizard/window.py | import tkinter as tk
from BribeNet.gui.apps.temporal.results_wizard.frame import TemporalResultsWizardFrame
class TemporalResultsWizardWindow(tk.Toplevel):
"""
Window for pop-up wizard for selecting results displayed
"""
def __init__(self, controller, results):
super().__init__(controller)
... | /src/BribeNet/gui/apps/temporal/wizard/bribers.py | import tkinter as tk
from BribeNet.gui.apps.temporal.briber_wizard.window import TemporalBriberWizardWindow
from BribeNet.helpers.override import override
class TemporalBribers(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.briber_wizard = None
self.bribers_list = ... | /src/BribeNet/gui/apps/temporal/wizard/generation.py | from BribeNet.gui.apps.static.wizard.generation import StaticGeneration
class TemporalGeneration(StaticGeneration):
pass
| /src/BribeNet/gui/apps/temporal/wizard/rating_method.py | import tkinter as tk
from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.apps.temporal.wizard.rating_methods.median_p_rating import MedianPRating
from BribeNet.gui.apps.temporal.wizard.rating_methods.o_rating import ORating
from BribeNet.gui.apps.temporal.wizard.rating_methods.p_gamma_rating import ... | /src/BribeNet/gui/apps/temporal/wizard/rating_methods/median_p_rating.py | from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.apps.temporal.wizard.rating_methods.rating_method_frame import RatingMethodFrame
class MedianPRating(RatingMethodFrame):
enum_value = RatingMethod.MEDIAN_P_RATING
name = 'median_p_rating'
| /src/BribeNet/gui/apps/temporal/wizard/rating_methods/o_rating.py | from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.apps.temporal.wizard.rating_methods.rating_method_frame import RatingMethodFrame
class ORating(RatingMethodFrame):
enum_value = RatingMethod.O_RATING
name = 'o_rating'
| /src/BribeNet/gui/apps/temporal/wizard/rating_methods/p_gamma_rating.py | import tkinter as tk
from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.apps.temporal.wizard.rating_methods.rating_method_frame import RatingMethodFrame
class PGammaRating(RatingMethodFrame):
enum_value = RatingMethod.P_GAMMA_RATING
name = 'p_gamma_rating'
def __init__(self, parent):... | /src/BribeNet/gui/apps/temporal/wizard/rating_methods/p_rating.py | from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.apps.temporal.wizard.rating_methods.rating_method_frame import RatingMethodFrame
class PRating(RatingMethodFrame):
enum_value = RatingMethod.P_RATING
name = 'p_rating'
| /src/BribeNet/gui/apps/temporal/wizard/rating_methods/rating_method_frame.py | import abc
from typing import Optional
from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.classes.param_list_frame import ParamListFrame
class RatingMethodFrame(ParamListFrame, abc.ABC):
enum_value: Optional[RatingMethod] = None
def __init__(self, parent):
super().__init__(parent... | /src/BribeNet/gui/apps/temporal/wizard/rating_methods/weighted_median_p_rating.py | from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.apps.temporal.wizard.rating_methods.rating_method_frame import RatingMethodFrame
class WeightedMedianPRating(RatingMethodFrame):
enum_value = RatingMethod.WEIGHTED_MEDIAN_P_RATING
name = 'weighted_median_p_rating'
| /src/BribeNet/gui/apps/temporal/wizard/rating_methods/weighted_p_rating.py | from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.apps.temporal.wizard.rating_methods.rating_method_frame import RatingMethodFrame
class WeightedPRating(RatingMethodFrame):
enum_value = RatingMethod.WEIGHTED_P_RATING
name = 'weighted_p_rating'
| /src/BribeNet/gui/apps/temporal/wizard/settings.py | import tkinter as tk
from BribeNet.gui.classes.param_list_frame import ParamListFrame
class TemporalSettings(ParamListFrame):
name = 'Model Parameters'
def __init__(self, parent):
super().__init__(parent)
self.descriptions = {
'non_voter_proportion': 'the proportion of customers... | /src/BribeNet/gui/apps/temporal/wizard/wizard.py | import tkinter as tk
import numpy as np
from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.apps.temporal.wizard.bribers import TemporalBribers
from BribeNet.gui.apps.temporal.wizard.generation import TemporalGeneration
from BribeNet.gui.apps.temporal.wizard.rating_method import TemporalRatingMetho... | /src/BribeNet/gui/classes/param_list_frame.py | import abc
import os
import tkinter as tk
from PIL import ImageTk, Image
from BribeNet.gui.classes.tooltip import ToolTip
class ParamListFrame(tk.Frame, abc.ABC):
name = "ABC"
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.params = {}
self.des... | /src/BribeNet/gui/classes/tooltip.py | import tkinter as tk
# noinspection PyUnusedLocal
class ToolTip(object):
"""
Show a tooltip
from https://stackoverflow.com/a/56749167/5539184
"""
def __init__(self, widget, text):
self.widget = widget
self.tip_window = None
self.id = None
self.x = self.y = 0
... | /src/BribeNet/gui/main.py | import tkinter as tk
from BribeNet.gui.apps.main import Main
from BribeNet.gui.apps.static.static import StaticGUI
from BribeNet.gui.apps.temporal.main import TemporalGUI
from BribeNet.helpers.override import override
class GUI(tk.Tk):
"""
Main menu window for the GUI
Self-withdraws when model wizard ope... | /src/BribeNet/helpers/bribeNetException.py | class BribeNetException(Exception):
pass
| /src/BribeNet/prediction/parameterPrediction.py | # noinspection PyUnresolvedReferences
from networkit.centrality import LocalClusteringCoefficient
# noinspection PyUnresolvedReferences
from networkit.distance import APSP
from networkit.generators import WattsStrogatzGenerator
from numpy import logspace
from numpy import sum as np_sum
TRIALS = 5
INFINITY = float("inf... | /src/docker_main.py | from sys import exit
from BribeNet.gui.main import GUI
"""
Due to a bug where app.mainloop() will not exit on closing of the root Tk instance if a Toplevel was at any stage
instantiated, we use sys.exit(0) to 'hard exit' such that the Docker container does not hang after closing.
"""
def hard_exit(tk_app):
tk_a... | /test/BribeNet/bribery/static/briberTestCase.py | from abc import ABC, abstractmethod
from unittest import TestCase
from BribeNet.bribery.static.nonBriber import NonBriber
from BribeNet.graph.static.ratingGraph import StaticRatingGraph
class BriberTestCase(TestCase, ABC):
@abstractmethod
def setUp(self) -> None:
self.briber = NonBriber(1)
s... | /test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py | from copy import deepcopy
from BribeNet.bribery.static.oneMoveInfluentialNodeBriber import OneMoveInfluentialNodeBriber
from BribeNet.graph.static.ratingGraph import StaticRatingGraph
from test.BribeNet.bribery.static.briberTestCase import BriberTestCase
class TestOneMoveInfluentialNodeBriber(BriberTestCase):
d... | /test/BribeNet/bribery/static/test_oneMoveRandomBriber.py | from copy import deepcopy
from BribeNet.bribery.static.oneMoveRandomBriber import OneMoveRandomBriber
from BribeNet.graph.static.ratingGraph import StaticRatingGraph
from test.BribeNet.bribery.static.briberTestCase import BriberTestCase
class TestOneMoveInfluentialNodeBriber(BriberTestCase):
def setUp(self) -> ... | /test/BribeNet/bribery/static/test_randomBriber.py | from BribeNet.bribery.static.randomBriber import RandomBriber
from BribeNet.graph.static.ratingGraph import StaticRatingGraph
from test.BribeNet.bribery.static.briberTestCase import BriberTestCase
class TestRandomBriber(BriberTestCase):
def setUp(self) -> None:
self.briber = RandomBriber(10)
self... | /test/BribeNet/bribery/temporal/action/test_briberyAction.py | from unittest import TestCase
from unittest.mock import MagicMock
from BribeNet.bribery.temporal.action.briberyAction import BriberyActionTimeNotCorrectException, \
BriberyActionExecutedMultipleTimesException
from BribeNet.bribery.temporal.nonBriber import NonBriber
from BribeNet.bribery.temporal.action.singleBrib... | /test/BribeNet/bribery/temporal/action/test_multiBriberyAction.py | from unittest import TestCase
from BribeNet.bribery.temporal.action.multiBriberyAction import MultiBriberyAction, \
BriberyActionsAtDifferentTimesException, BriberyActionsOnDifferentGraphsException, \
NoActionsToFormMultiActionException
from BribeNet.bribery.temporal.action import *
from BribeNet.bribery.tempo... | /test/BribeNet/bribery/temporal/action/test_singleBriberyAction.py | from unittest import TestCase
from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.bribery.temporal.nonBriber import NonBriber
from BribeNet.graph.temporal.noCustomerActionGraph import NoCustomerActionGraph
from BribeNet.bribery.temporal.action import *
class TestSingleB... | /test/BribeNet/bribery/temporal/briberTestCase.py | from abc import ABC, abstractmethod
from unittest import TestCase
from BribeNet.bribery.temporal.nonBriber import NonBriber
from BribeNet.graph.temporal.noCustomerActionGraph import NoCustomerActionGraph
class BriberTestCase(TestCase, ABC):
@abstractmethod
def setUp(self) -> None:
self.briber = NonB... | /test/BribeNet/bribery/temporal/test_budgetBriber.py | from BribeNet.bribery.temporal.budgetNodeBriber import BudgetNodeBriber
from BribeNet.graph.temporal.noCustomerActionGraph import NoCustomerActionGraph
from test.BribeNet.bribery.temporal.briberTestCase import BriberTestCase
from unittest.mock import MagicMock
class TestBudgetBriber(BriberTestCase):
def setUp(se... | /test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py | from BribeNet.bribery.temporal.mostInfluentialNodeBriber import MostInfluentialNodeBriber
from BribeNet.graph.temporal.noCustomerActionGraph import NoCustomerActionGraph
from test.BribeNet.bribery.temporal.briberTestCase import BriberTestCase
from unittest.mock import MagicMock
TEST_I = 7
class TestMostInfluentialBr... | /test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py | from BribeNet.bribery.temporal.oneMoveRandomBriber import OneMoveRandomBriber
from BribeNet.graph.temporal.noCustomerActionGraph import NoCustomerActionGraph
from test.BribeNet.bribery.temporal.briberTestCase import BriberTestCase
class TestOneMoveRandomBriber(BriberTestCase):
def setUp(self) -> None:
se... | /test/BribeNet/bribery/temporal/test_randomBriber.py | from BribeNet.bribery.temporal.randomBriber import RandomBriber
from BribeNet.graph.temporal.noCustomerActionGraph import NoCustomerActionGraph
from test.BribeNet.bribery.temporal.briberTestCase import BriberTestCase
class TestRandomBriber(BriberTestCase):
def setUp(self) -> None:
self.briber = RandomBri... | /test/BribeNet/bribery/test_briber.py | import random
from test.BribeNet.bribery.static.briberTestCase import BriberTestCase
from BribeNet.bribery.briber import BriberyGraphAlreadySetException, BriberyGraphNotSetException
from BribeNet.bribery.static.nonBriber import NonBriber
class TestBriber(BriberTestCase):
def setUp(self) -> None:
super()... | /test/BribeNet/graph/generation/test_unweightedGenerator.py | from unittest import TestCase
from BribeNet.graph.generation.unweightedGenerator import UnweightedGraphGenerator
from BribeNet.graph.generation import GraphGeneratorAlgo
class TestUnweightedGraphGenerator(TestCase):
def test_generate_ws(self):
graph_gen = UnweightedGraphGenerator(GraphGeneratorAlgo.WATTS... | /test/BribeNet/graph/generation/test_weightedGenerator.py | from unittest import TestCase
from BribeNet.graph.generation.flatWeightGenerator import FlatWeightedGraphGenerator
from BribeNet.graph.generation import GraphGeneratorAlgo
class TestFlatWeightedGraphGenerator(TestCase):
def test_generate_ws(self):
graph_gen = FlatWeightedGraphGenerator(GraphGeneratorAlgo... | /test/BribeNet/graph/static/test_multiBriberRatingGraph.py | from copy import deepcopy
from unittest import TestCase
from BribeNet.bribery.static.nonBriber import NonBriber
from BribeNet.bribery.static.randomBriber import RandomBriber
from BribeNet.graph.static.ratingGraph import StaticRatingGraph
class TestMultiBriberRatingGraph(TestCase):
def setUp(self) -> None:
... | /test/BribeNet/graph/static/test_ratingGraphBuilder.py | from unittest import TestCase
from BribeNet.bribery.static.influentialNodeBriber import InfluentialNodeBriber
from BribeNet.bribery.static.mostInfluentialNodeBriber import MostInfluentialNodeBriber
from BribeNet.bribery.static.nonBriber import NonBriber
from BribeNet.bribery.static.oneMoveInfluentialNodeBriber import ... | /test/BribeNet/graph/static/test_singleBriberRatingGraph.py | from copy import deepcopy
from unittest import TestCase
from BribeNet.bribery.static.nonBriber import NonBriber
from BribeNet.graph.static.ratingGraph import StaticRatingGraph
class TestSingleBriberRatingGraph(TestCase):
def setUp(self) -> None:
self.rg = StaticRatingGraph(NonBriber(0))
def tearDow... | /test/BribeNet/graph/temporal/action/test_customerAction.py | from unittest import TestCase
from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.graph.temporal.action.customerAction import CustomerAction, CustomerActionExecutedMultipleTimesException,\
CustomerActionTimeNotCorrectException
from BribeNet.bribery.temporal.nonBriber i... | /test/BribeNet/graph/temporal/test_multiBriberRatingGraph.py | from copy import deepcopy
from unittest import TestCase
from BribeNet.bribery.temporal.nonBriber import NonBriber
from BribeNet.bribery.temporal.randomBriber import RandomBriber
from BribeNet.graph.temporal.noCustomerActionGraph import NoCustomerActionGraph
class TestMultiBriberRatingGraph(TestCase):
def setUp(... | /test/BribeNet/graph/temporal/test_ratingGraphBuilder.py | from unittest import TestCase
class TestRatingGraphBuilder(TestCase):
pass
| /test/BribeNet/graph/temporal/test_thresholdGraph.py | from unittest import TestCase
from BribeNet.bribery.temporal.nonBriber import NonBriber
from BribeNet.graph.temporal.action.actionType import ActionType
from BribeNet.graph.temporal.thresholdGraph import ThresholdGraph
from unittest.mock import MagicMock
class TestThresholdGraph(TestCase):
def setUp(self) -> No... | /test/BribeNet/graph/test_ratingGraph.py | from unittest import TestCase
class TestRatingGraph(TestCase):
"""
See test/graph/static/test_singleBriberRatingGraph and test/graph/static/test_multiBriberRatingGraph
"""
pass
| /test/BribeNet/prediction/test_parameterPrediction.py | from unittest import TestCase
from networkit.generators import WattsStrogatzGenerator
from numpy import logspace
from BribeNet.prediction.parameterPrediction import ParameterPrediction
class TestParameterPrediction(TestCase):
def setUp(self) -> None:
self.generator = WattsStrogatzGenerator(50, 6, 0.1)... |
constable-ldp/gym_management_app | refs/heads/main | {"/console.py": ["/models/member.py", "/models/gym_class.py", "/models/room.py", "/models/instructor.py", "/models/schedule.py"], "/controllers/member_controller.py": ["/models/member.py"], "/repositories/member_repository.py": ["/models/member.py"], "/tests/member_test.py": ["/models/member.py"], "/run_test.py": ["/te... | └──
├── app.py
├── console.py
├── controllers
│ ├── class_controller.py
│ ├── instructor_controller.py
│ ├── member_controller.py
│ ├── room_controller.py
│ └── schedule_controller.py
├── models
│ ├── gym_class.py
│ ├── instructor.py
│ ├── member.py
│... | /app.py | from flask import Flask, render_template
from controllers.class_controller import classes_blueprint
from controllers.member_controller import members_blueprint
from controllers.room_controller import rooms_blueprint
from controllers.instructor_controller import instructors_blueprint
from controllers.schedule_controlle... | /console.py | from models.gym_class import GymClass
from models.member import Member
from models.room import Room
from models.instructor import InstructorDetails, InstructorSchedule, InstructorTimetable
from models.schedule import Schedule
import repositories.gym_class_repository as class_repository
import repositories.member_reposi... | /controllers/class_controller.py | from flask import Blueprint, Flask, redirect, render_template, request
from models.gym_class import GymClass
import repositories.gym_class_repository as class_repository
classes_blueprint = Blueprint('classes', __name__)
@classes_blueprint.route('/classes')
def classes():
classes = class_repository.select_all()
... | /controllers/instructor_controller.py | from flask import Blueprint, Flask, redirect, render_template, request
from models.instructor import InstructorTimetable, InstructorDetails, InstructorSchedule
import repositories.instructor_timetable_repository as timetable_repository
import repositories.instructor_details_repository as details_repository
import repos... | /controllers/member_controller.py | from flask import Blueprint, Flask, redirect, render_template, request
from models.member import Member
import repositories.member_repository as member_repository
import datetime
members_blueprint = Blueprint('members', __name__)
@members_blueprint.route('/members')
def members():
members = member_repository.sele... | /controllers/room_controller.py | from flask import Blueprint, Flask, redirect, render_template, request
from models.room import Room
import repositories.room_repository as room_repository
rooms_blueprint = Blueprint('rooms', __name__)
@rooms_blueprint.route('/rooms')
def rooms():
rooms = room_repository.select_all()
return render_template('r... | /controllers/schedule_controller.py | from flask import Blueprint, Flask, redirect, render_template, request
from models.schedule import Schedule
from models.schedule_member import ScheduleMember
import repositories.schedule_repository as schedule_repository
import repositories.instructor_details_repository as details_repository
import repositories.gym_cla... | /models/gym_class.py | class GymClass:
def __init__(self, class_name, description, max_time, capacity, id=None):
self.class_name = class_name
self.description = description
self.max_time = max_time
self.capacity = capacity
self.id = id | /models/instructor.py | class InstructorDetails:
def __init__(self, first_name, last_name, date_of_birth, id=None) :
self.first_name = first_name
self.last_name = last_name
self.date_of_birth = date_of_birth
self.id = id
class InstructorSchedule:
def __init__(self, nickname, monday, tuesday, wednesda... | /models/member.py | class Member:
def __init__(self, first_name, last_name, email, phone, date_of_birth, membership=False,
premium=False, member_since=None, member_until=None, id=None):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.phone = phone
... | /models/room.py | class Room:
def __init__(self, room_name, capacity, descripton=None, id=None):
self.room_name = room_name
self.capacity = capacity
self.description = descripton
self.id = id | /models/schedule.py | class Schedule:
def __init__(self, class_date, start_time, length_mins, instructor, gym_class, room, id=None):
self.class_date = class_date
self.start_time = start_time
self.length_mins = length_mins
self.instructor = instructor
self.gym_class = gym_class
self.room =... | /models/schedule_member.py | class ScheduleMember:
def __init__(self, member, schedule, id=None):
self.member = member
self.schedule = schedule
self.id = id | /repositories/gym_class_repository.py | from database.run_sql import run_sql
from models.gym_class import GymClass
def save(gym_class):
sql = """INSERT INTO classes
(class_name, description, max_time, capacity)
VALUES ( %s, %s, %s, %s )
RETURNING id"""
values = [gym_class.class_name, gym_class.description, gy... | /repositories/instructor_details_repository.py | from database.run_sql import run_sql
from models.instructor import InstructorDetails
def save(instructor):
sql = """INSERT INTO instructor_details
(first_name, last_name, date_of_birth)
VALUES ( %s, %s, %s )
RETURNING id"""
values = [instructor.first_name, instructor.la... | /repositories/instructor_schedule_repository.py | from database.run_sql import run_sql
from models.instructor import InstructorSchedule
def save(instructor):
sql = """INSERT INTO instructor_schedules
(nickname, monday, tuesday, wednesday, thursday, friday,
saturday, sunday, start_time, end_time)
VALUES (%s, %s, %s, %s, %s,... | /repositories/instructor_timetable_repository.py | from database.run_sql import run_sql
from models.instructor import InstructorDetails, InstructorSchedule, InstructorTimetable
import repositories.instructor_details_repository as details_repository
import repositories.instructor_schedule_repository as schedule_repository
def save(timetable):
sql = """INSERT INTO ... | /repositories/member_repository.py | from database.run_sql import run_sql
from models.member import Member
import repositories.schedule_repository as schedule_repository
from datetime import date
def save(member):
sql = """INSERT INTO members
(first_name, last_name, email, phone, date_of_birth,
membership, premium, member_s... | /repositories/room_repository.py | from database.run_sql import run_sql
from models.room import Room
def save(room):
sql = """INSERT INTO rooms
(room_name, capacity, description)
VALUES (%s, %s, %s)
RETURNING id"""
values = [room.room_name, room.capacity, room.description]
results = run_sql(sql, value... | /repositories/schedule_repository.py | from database.run_sql import run_sql
from models.schedule import Schedule
from models.instructor import InstructorDetails
from models.gym_class import GymClass
from models.room import Room
from models.schedule_member import ScheduleMember
import repositories.instructor_details_repository as instructor_repository
import... | /run_test.py | import unittest
from tests.member_test import TestMember
from tests.gym_class_test import TestGymClass
from tests.instructor_test import TestInstructorDetails, TestInstructorSchedule
from tests.room_test import TestRoom
from tests.schedule_test import TestSchedule
if __name__ == '__main__':
unittest.main() | /tests/gym_class_test.py | import unittest
from models.gym_class import GymClass
class TestGymClass(unittest.TestCase):
def setUp(self):
self.gym_class = GymClass('Hot Yoga', 'Yoga performed in a very warm studio', 60, 16)
def test_class_has_name(self):
self.assertEqual('Hot Yoga', self.gym_class.class_name)
def t... | /tests/instructor_test.py | import unittest
from models.instructor import InstructorDetails, InstructorSchedule
import datetime
class TestInstructorDetails(unittest.TestCase):
def setUp(self):
self.instructor = InstructorDetails('Mary', 'Jones', datetime.date(1992, 3, 12))
def test_instructor_has_first_name(self):
self.... | /tests/member_test.py | import unittest
import datetime
from models.member import Member
class TestMember(unittest.TestCase):
def setUp(self):
self.member = Member('John', 'Smith', 'johnsmith@gmail.com', '07595964019',
datetime.date(1997, 5, 17), True, False, datetime.date(2021, 3, 21),
... | /tests/room_test.py | import unittest
from models.room import Room
class TestRoom(unittest.TestCase):
def setUp(self):
self.room = Room('Room 1', 24, 'Large Room')
def test_room_has_name(self):
self.assertEqual('Room 1', self.room.room_name)
def test_room_has_capacity(self):
self.assertEqual(24, self.r... | /tests/schedule_test.py | import unittest
from models.schedule import Schedule
import datetime
class TestSchedule(unittest.TestCase):
def setUp(self):
self.schedule = Schedule(datetime.date(2021, 3, 21), 45)
def test_schedule_has_class_date(self):
self.assertEqual('2021-03-21', str(self.schedule.class_date))
def t... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Redent0r/Libra | refs/heads/master | {"/master_admin.py": ["/gui_move.py", "/gui_client.py", "/gui_sale.py", "/gui_inventory.py", "/gui_purchase.py"], "/main_login.py": ["/mec_login.py", "/gui_login.py"]} | └──
├── gui_client.py
├── gui_inventory.py
├── gui_login.py
├── gui_move.py
├── gui_purchase.py
├── gui_sale.py
├── main_login.py
├── master_admin.py
├── mec_inventory.py
└── mec_login.py | /gui_client.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui_cliente.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s... | /gui_inventory.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui_inventory.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8... | /gui_login.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui_login.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):... | /gui_move.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui_mover.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):... | /gui_purchase.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui_compra.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s)... | /gui_sale.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui_venta.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):... | /main_login.py |
import sys
import sqlite3
from PyQt4 import QtCore, QtGui, QtSql
from gui_login import Ui_Dialog as LoginGui
import master_admin
import mec_login
from mec_login import check_login # tengo que importarlo
class Login(QtGui.QDialog, LoginGui):
def __init__(self, parent=None):
QtGui.QDi... | /master_admin.py |
### std lib ###
import sys
import sqlite3
import time
import os
### PyQt4 ###
from PyQt4 import QtCore, QtGui, QtSql
### GUIs ###
from gui_inventory import Ui_MainWindow as InventoryGui
from gui_purchase import Ui_Dialog as PurchaseGui
from gui_sale import Ui_Dialog as SaleGui
from gui_client import Ui... | /mec_inventory.py |
"""
Author:Christopher Holder
"""
def create_tables(connection,cursor):
"""
This function creates the neccessary tables in the database.
"""
cursor.execute("CREATE TABLE IF NOT EXISTS OrdinalNumber(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,num TEXT NOT NULL)")
cursor.execute('CREATE... | /mec_login.py | """
Author:Christopher Holder
Project : Version 1.0(Login)
"""
import sqlite3
import sys
def create_login_table(cursor,connection):#Creates login table.
cursor.execute("CREATE TABLE IF NOT EXISTS login(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, User TEXT NOT NULL, Pass TEXT NOT NULL,class TEXT NOT NULL... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
gouravsaini021/maruti | refs/heads/master | {"/maruti/deepfake/dataset.py": ["/maruti/utils.py", "/maruti/sizes.py", "/maruti/vision/video.py"], "/maruti/deepfake/models.py": ["/maruti/torch/utils.py"], "/maruti/__init__.py": ["/maruti/torch/utils.py", "/maruti/deepfake/dataset.py"], "/maruti/vision/__init__.py": ["/maruti/vision/image.py"], "/maruti/deepfake/__... | └──
├── maruti
│ ├── __init__.py
│ ├── deepfake
│ │ ├── __init__.py
│ │ ├── dataset.py
│ │ ├── models.py
│ │ └── utils.py
│ ├── imports
│ │ ├── __init__.py
│ │ ├── general.py
│ │ └── ml.py
│ ├── kaggle.py
│ ├── sizes.py
│ ├... | /maruti/__init__.py | from . import utils
from . import sizes
from . import vision
from . import deepfake
from . import kaggle
from . import torch
from .utils import *
from .sizes import *
from .deepfake import ImageReader
from .torch import Learner
| /maruti/deepfake/__init__.py | from . import dataset
from . import models
from .dataset import VideoDataset, DeepfakeDataset, ImageReader
from .dataset import transform, group_transform
| /maruti/deepfake/dataset.py | import pathlib
from warnings import warn
import subprocess
import maruti
import os
from os.path import join
from PIL import Image
import torch
import shlex
import time
from collections import defaultdict
from ..vision.video import get_frames_from_path, get_frames
import random
from ..utils import unzip, read_json
from ... | /maruti/deepfake/models.py | import torch.nn as nn
import torchvision
from ..torch.utils import freeze
from torch.nn.utils.rnn import PackedSequence, pack_sequence
import itertools
from .dataset import group_transform
def resnext50(feature=False, pretrained=False):
model = torchvision.models.resnext50_32x4d(pretrained)
if feature:
... | /maruti/deepfake/utils.py | # from torch_lr_finder import LRFinder
from tqdm.auto import tqdm
from functools import partial
import torch
import time
tqdm_nl = partial(tqdm, leave=False)
class Callback:
pass
def _limit_string(string, length):
string = str(string)
if length > len(string):
return string
else:
ret... | /maruti/imports/__init__.py | from . import general
from . import ml
| /maruti/imports/general.py | import os
import shutil
from glob import glob
from tqdm.auto import tqdm
import itertools
import random
import time
from functools import partial
__all__ = ['time','random','os', 'shutil', 'glob', 'tqdm', 'itertools', 'partial']
| /maruti/imports/ml.py | from .general import *
from .general import __all__ as gen_all
import torch
import torch.nn as nn
import torchvision.transforms as torch_transforms
import torchvision
import maruti.torch as mtorch
import maruti.deepfake.dataset as mdata
import maruti
import maruti.deepfake as mfake
import numpy as np
import cv2
import ... | /maruti/kaggle.py | import os
import subprocess
from pathlib import Path
import zipfile
def set_variables(credentials: 'lists[str,str]=[username, token]'):
os.environ['KAGGLE_USERNAME'] = credentials[0]
os.environ['KAGGLE_KEY'] = credentials[1]
def update_dataset(path, slug, message='new version', clean=False):
folder = os... | /maruti/sizes.py | from sys import getsizeof
import os
__all__ = ['dir_size','file_size','var_size']
def byte_to_mb(size):
return size/(1024**2)
def dir_size(start_path='.'):
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
... | /maruti/torch/__init__.py | from . import utils
from . import metrics
from .utils import *
| /maruti/torch/callback.py | import os
from datetime import datetime, timezone, timedelta
from torch.utils.tensorboard import SummaryWriter
from copy import deepcopy
class Callback:
def on_epoch_end(self, losses, metrics, extras, epoch):
"""
extras-> dict ['time']['model']
"""
pass
def on_epoch_start(self... | /maruti/torch/utils.py | # from torch_lr_finder import LRFinder
from tqdm.auto import tqdm
from functools import partial
import torch
import time
import numpy as np
from collections import Counter
from torchvision import transforms as torch_transforms
from . import callback as mcallback
tqdm_nl = partial(tqdm, leave=False)
__all__ = ['unfreez... | /maruti/utils.py | import json
import zipfile
import time
from tqdm.auto import tqdm
__all__ = ['rep_time', 'read_json', 'write_json', 'unzip']
def rep_time(seconds):
if seconds >= 3600:
return time.strftime('%H:%M:%S', time.gmtime(seconds))
else:
return time.strftime('%M:%S', time.gmtime(seconds))
def read_j... | /maruti/vision/__init__.py | from . import image
from . import video
from .image import make_grid
from .video import *
| /maruti/vision/image.py | import numpy as np
import cv2
from functools import lru_cache
from functools import partial
from os.path import join
import os
from PIL import Image
import torch
__all__ = ['brightness_score', 'adjust_brightness',
'crop_around_point', 'make_grid']
DATA_PATH = join(os.path.dirname(__file__), 'data')
def ... | /maruti/vision/video.py | import cv2
import numpy as np
from .. import vision as mvis
from facenet_pytorch import MTCNN
import torch
from PIL import Image
from collections import defaultdict
device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
class Video(cv2.VideoCapture):
def __enter__(self):
return self
def __exit__(s... | /setup.py | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="maruti",
version="1.3.4",
author="Ankit Saini",
author_email="ankitsaini100205@gmail.com",
description="Maruti Library",
long_description=long_description,
long_description_content... | /tests/test_sizes.py | import unittest
import tempfile
import os
from maruti import sizes
class DeepfakeTest(unittest.TestCase):
def test_byte_to_mb(self):
self.assertEqual(sizes.byte_to_mb(1024*1024), 1)
self.assertAlmostEqual(sizes.byte_to_mb(1024),
0.0009765624, delta=1e-8)
def te... | /tests/test_utils.py | import maruti
import unittest
import tempfile
from maruti import utils
import os
class UtilsTests(unittest.TestCase):
def test_read_write_json(self):
with tempfile.TemporaryDirectory() as dir:
# creating dictionary
sample = {'h': 3, 'd': {'j': 4}}
path = os.path.join(d... | /tests/torch/test_utils.py | import unittest
import tempfile
import os
import torchvision
import torch
from maruti.torch import utils
class TorchUtilsTest(unittest.TestCase):
def setUp(self):
self.model = torchvision.models.resnet18(False)
def tearDown(self):
self.model = None
def test_freeze_unfreeze(self):
... | /tests/vision/test_image.py | import unittest
import cv2
from cv2 import dnn_Net
from maruti.vision import image
import os
TEST_DATA_PATH = 'test_data'
class ImageTests(unittest.TestCase):
def setUp(self):
self.img_path = os.path.join(TEST_DATA_PATH, 'img1.jpeg')
self.img = cv2.imread(self.img_path)
def test_create_net(s... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
RainGod6/SDET11-LY | refs/heads/master | {"/test_appium_page_object/page/app.py": ["/test_appium_page_object/page/main.py", "/test_appium_page_object/page/base_page.py"], "/test_appium_page_object/page/main.py": ["/test_appium_page_object/page/apply_etc_card/apply_credit_card.py", "/test_appium_page_object/page/base_page.py"], "/test_appium_page_object/page/a... | └──
├── leetcode
│ └── Solution.py
├── test_appium
│ ├── YMM_APP
│ │ ├── TestYmm.py
│ │ └── TestYmmPY.py
│ ├── hcb_app
│ │ ├── test_hcb_demo.py
│ │ └── test_hcb_home.py
│ ├── testApiDemo.py
│ └── test_xueqiu.py
├── test_appium_page_object
│ ... | /leetcode/Solution.py | """
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
"""
from typing import List
class Solution(object):
def two... | /test_appium/YMM_APP/TestYmm.py | # This sample code uses the Appium python client
# pip install Appium-Python-Client
# Then you can paste this into a file and simply run with Python
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
caps = {}
caps["platformName"] = "android"
caps["deviceName"] = "xiaomi5"
caps["appPac... | /test_appium/YMM_APP/TestYmmPY.py | # This sample code uses the Appium python client
# pip install Appium-Python-Client
# Then you can paste this into a file and simply run with Python
from time import sleep
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.common.touch_action import TouchAction
fro... | /test_appium/hcb_app/test_hcb_demo.py | from time import sleep
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
class TestHcbDemo:
def setup(self):
c... | /test_appium/hcb_app/test_hcb_home.py | from time import sleep
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
class TestHcb:
def setup(self):
caps = {}
caps['platformName'] = 'android'
caps['deviceName'] = '28d6f388'
caps['appPackage'] = 'com.wlqq'
caps['appActivity'] = 'com.... | /test_appium/testApiDemo.py | from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
class TestApiDemo:
def setup(self):
caps = {}
caps['platformName'] = "android"
caps['deviceName'] = "小米5"
caps['appPackage'] = "io.appium.android.apis"
caps['appActivity'] = ".ApiDemos"
... | /test_appium/test_xueqiu.py | # This sample code uses the Appium python client
# pip install Appium-Python-Client
# Then you can paste this into a file and simply run with Python
from time import sleep
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support import expected_conditions
from s... | /test_appium_page_object/page/app.py | from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from test_appium_page_object.page.base_page import BasePage
from test_appium_page_object.page.main import Main
class A... | /test_appium_page_object/page/apply_etc_card/apply_credit_card.py | from appium.webdriver.common.mobileby import MobileBy
from test_appium_page_object.page.base_page import BasePage
class ApplyCreditCard(BasePage):
_name_apply_card_element = (MobileBy.ID, "com.wlqq.phantom.plugin.etc:id/tv_online_open_card")
_name_nfc_element = (MobileBy.ID, "com.wlqq:id/btn_back")
def ... | /test_appium_page_object/page/base_page.py | import yaml
from appium.webdriver import WebElement
from appium.webdriver.webdriver import WebDriver
import logging
class BasePage:
logging.basicConfig(level=logging.INFO) # 使用logging
_driver: WebDriver
_black_list = []
_error_max = 5
_error_count = 0
def __init__(self, driver: WebDriver = N... | /test_appium_page_object/page/main.py | from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from test_appium_page_object.page.apply_etc_card.apply_credit_card import ApplyCreditCard
from test_appium_page_object.page.base_page import BasePag... | /test_appium_page_object/testcase/test_apply_credit_card.py | from test_appium_page_object.page.app import App
class TestApplyCreditCard:
def setup(self):
self.main = App().start().main()
def test_apply_credit_card(self):
self.main.goto_etc_home().apply_credit_card() | /test_yaml/test_yaml.py | import pytest
import yaml
class TestYaml:
def test_yaml(self):
print(yaml.load("""
- Hesperiidae
- Papilionidae
- Apatelodidae
- Epiplemidae
"""))
@pytest.mark.parametrize("a,b", yaml.safe_load(open("testyaml.yaml", encoding='utf-8')))
d... | /unit/test_unit.py | import unittest
class TestSum(unittest.TestCase):
def test_sum(self):
assert 1 + 2 == 3
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
aharley/neural_3d_mapping | refs/heads/master | {"/model_carla_static.py": ["/nets/emb3dnet.py", "/nets/viewnet.py", "/nets/emb2dnet.py"], "/main.py": ["/model_carla_static.py", "/model_carla_ego.py", "/model_carla_det.py"], "/model_carla_det.py": ["/nets/detnet.py"], "/model_carla_ego.py": ["/nets/egonet.py"]} | └──
├── archs
│ ├── bottle2D.py
│ ├── encoder2d.py
│ ├── encoder3d.py
│ └── pixelshuffle3d.py
├── backend
│ └── saverloader.py
├── exp_base.py
├── exp_carla_det.py
├── exp_carla_ego.py
├── exp_carla_static.py
├── hyperparams.py
├── main.py
├── model_car... | /archs/bottle2D.py | import torch
import torch.nn as nn
import time
# import hyperparams as hyp
# from utils_basic import *
import torch.nn.functional as F
class Bottle2D(nn.Module):
def __init__(self, in_channel, pred_dim, chans=64):
super(Bottle2D, self).__init__()
conv2d = []
# self.out_chans = [chans, 2*ch... | /archs/encoder2d.py | import torch
import torch.nn as nn
# import hyperparams as hyp
# from utils_basic import *
class Skipnet2d(nn.Module):
def __init__(self, in_chans, mid_chans=64, out_chans=1):
super(Skipnet2d, self).__init__()
conv2d = []
conv2d_transpose = []
up_bn = []
self.down_in_dims ... | /archs/encoder3d.py | import torch
import torch.nn as nn
import time
import torch.nn.functional as F
import archs.pixelshuffle3d
class Skipnet3d(nn.Module):
def __init__(self, in_dim, out_dim, chans=64):
super(Skipnet3d, self).__init__()
conv3d = []
up_bn = [] # batch norm for deconv
conv3d_transpose = [... | /archs/pixelshuffle3d.py |
'''
reference: http://www.multisilicon.com/blog/a25332339.html
'''
import torch.nn as nn
class PixelShuffle3d(nn.Module):
'''
This class is a 3d version of pixelshuffle.
'''
def __init__(self, scale):
'''
:param scale: upsample scale
'''
super().__init__()
self.... | /backend/saverloader.py | import torch
import os,pathlib
import hyperparams as hyp
import numpy as np
def load_total(model, optimizer):
start_iter = 0
if hyp.total_init:
print("TOTAL INIT")
print(hyp.total_init)
start_iter = load(hyp.total_init, model, optimizer)
if start_iter:
print("loaded... | /exp_base.py | import pretrained_nets_carla as pret_carla
exps = {}
groups = {}
############## training settings ##############
groups['train_feat3d'] = [
'do_feat3d = True',
'feat3d_dim = 32',
# 'feat3d_smooth_coeff = 0.01',
]
groups['train_det'] = [
'do_det = True',
'det_prob_coeff = 1.0',
'det_reg_coeff =... | /exp_carla_det.py | from exp_base import *
############## choose an experiment ##############
current = 'det_builder'
current = 'det_trainer'
mod = '"det00"' # go
mod = '"det01"' # rescore with inbound
mod = '"det02"' # show scores
mod = '"det03"' # show bev too
mod = '"det04"' # narrower bounds, to see
mod = '"det05"' # print scoreli... | /exp_carla_ego.py | from exp_base import *
############## choose an experiment ##############
current = 'builder'
current = 'debugger'
current = 'trainer'
mod = '"eg00"' # nothing; builder
mod = '"eg01"' # deleted junk
mod = '"eg02"' # added hyps
mod = '"eg03"' # train a while
mod = '"eg04"' # 1 scale
mod = '"eg05"' # no synth
mod = '"... | /exp_carla_static.py | from exp_base import *
############## choose an experiment ##############
current = 'builder'
current = 'trainer'
# current = 'tester_basic'
mod = '"sta00"' # nothing; builder
mod = '"sta01"' # just prep and return
mod = '"sta02"' # again, fewer prints
mod = '"sta03"' # run feat3d forward; drop the sparse stuff
mod ... | /hyperparams.py | import os
# from munch import Munch
H = 240 # height
W = 320 # width
Z = 128
Y = 64
X = 128
Z_val = 128
Y_val = 64
X_val = 128
Z_test = 128
Y_test = 64
X_test = 128
PH = int(128/4)
PW = int(384/4)
ZY = 32
ZX = 32
ZZ = 32
N = 8 # number of boxes per npz
K = 1 # number of boxes to actually use
# S = 2 # seq length
#... | /main.py | from model_carla_static import CARLA_STATIC
from model_carla_ego import CARLA_EGO
from model_carla_det import CARLA_DET
import hyperparams as hyp
import os
import logging
logger = logging.Logger('catch_all')
def main():
checkpoint_dir_ = os.path.join("checkpoints", hyp.name)
if hyp.do_carla_static:
... | /model_carla_det.py | import time
import torch
import torch.nn as nn
import hyperparams as hyp
import numpy as np
import os
from model_base import Model
from nets.feat3dnet import Feat3dNet
from nets.detnet import DetNet
import utils.vox
import utils.samp
import utils.geom
import utils.misc
import utils.improc
import utils.basic
# import ... | /model_carla_ego.py | import torch
import torch.nn as nn
import hyperparams as hyp
import numpy as np
# import imageio,scipy
from model_base import Model
from nets.feat3dnet import Feat3dNet
from nets.egonet import EgoNet
import torch.nn.functional as F
import utils.vox
import utils.samp
import utils.geom
import utils.improc
import utils... | /model_carla_static.py | import torch
import torch.nn as nn
import hyperparams as hyp
import numpy as np
# import imageio,scipy
from model_base import Model
from nets.occnet import OccNet
from nets.feat2dnet import Feat2dNet
from nets.feat3dnet import Feat3dNet
from nets.emb2dnet import Emb2dNet
from nets.emb3dnet import Emb3dNet
from nets.vi... | /nets/detnet.py | import numpy as np
import torch
import torch.nn as nn
import torchvision
import torchvision.ops as ops
import utils.basic
import utils.geom
import utils.misc
import hyperparams as hyp
import archs.encoder3d
def smooth_l1_loss(deltas, targets, sigma=3.0):
sigma2 = sigma * sigma
diffs = deltas - targets
sm... | /nets/egonet.py | import numpy as np
import hyperparams as hyp
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.ops as ops
import utils.basic
import utils.improc
import utils.geom
import utils.misc
import utils.samp
EPS = 1e-6
# acknowledgement:
# Niles Christensen and Sohil Sam... | /nets/emb2dnet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
sys.path.append("..")
import archs.encoder2d as encoder2d
import hyperparams as hyp
import utils.basic
import utils.misc
import utils.improc
class Emb2dNet(nn.Module):
def __init__(self):
super(Emb2dNet, self).__init__()
... | /nets/emb3dnet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
sys.path.append("..")
import hyperparams as hyp
import utils.improc
import utils.misc
import utils.vox
import utils.basic
class Emb3dNet(nn.Module):
def __init__(self):
super(Emb3dNet, self).__init__()
print('Emb3dNet.... | /nets/flownet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
# from spatial_correlation_sampler import SpatialCorrelationSampler
import numpy as np
# import sys
# sys.path.append("..")
import archs.encoder3D
import hyperparams as hyp
import utils_basic
import utils_improc
import utils_misc
import utils_samp
imp... | /nets/viewnet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
sys.path.append("..")
import archs.renderer
import hyperparams as hyp
from utils.basic import *
import utils.improc
import utils.basic
import utils.misc
import utils.geom
class ViewNet(nn.Module):
def __init__(self):
super(View... | /pretrained_nets_carla.py | ckpt = '02_s2_m128x32x128_p64x192_1e-3_F2_d32_F3_d32_s.01_O_c1_s.01_V_d32_e1_E2_e.1_n4_d32_c1_E3_n2_c1_mags7i3t_sta41'
ckpt = '02_s2_m128x32x128_1e-3_F3_d32_s.01_O_c2_s.1_E3_n2_c.1_mags7i3t_sta48'
feat3d_init = ckpt
feat3d_dim = 32
occ_init = ckpt
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
SarthakJShetty/pyResearchInsights | refs/heads/master | {"/pyResearchInsights/__init__.py": ["/pyResearchInsights/Analyzer.py", "/pyResearchInsights/Cleaner.py", "/pyResearchInsights/Scraper.py", "/pyResearchInsights/common_functions.py", "/pyResearchInsights/NLP_Engine.py", "/pyResearchInsights/system_functions.py"], "/pyResearchInsights/example.py": ["/pyResearchInsights/... | └──
└── pyResearchInsights
├── Analyzer.py
├── Cleaner.py
├── NLP_Engine.py
├── Scraper.py
├── Visualizer.py
├── __init__.py
├── common_functions.py
├── example.py
└── system_functions.py | /pyResearchInsights/Analyzer.py | '''This code is part of the larger pyResearchInsights project, where we aim
to study the research themes being discussed in scientific publications.
This portion of the code analyzes the contents of the .txt file developed
by the Scraper.py and saves it to a .csv for later visualization by the
soon to be built Visuali... | /pyResearchInsights/Cleaner.py | '''
Hello! This script is part of the larger pyResearchInsights project that you can check out here: https://github.com/SarthakJShetty/pyResearchInsights
We are trying to build an end-to-end ACA tool here
-Sarthak
(03/10/2019)
Purpose of this script:
Clean the corpus of special character'''
'''Importing the status lo... | /pyResearchInsights/NLP_Engine.py | '''Hello! This module of code is a part of the larger pyResearchInsights project.
This file was earlier named as Temp_Gensim_Code; code is now bifurcated into Gensim code (this) and a seperate
visualization code that will be added to the repository as well.
Checkout the Bias README.md for an overview of the project.
... | /pyResearchInsights/Scraper.py | '''The aim of this script is to scrape abstracts, author names and date of publication from Springer
Sarthak J. Shetty
04/08/2018'''
'''Adding the libraries to be used here.'''
'''Importing urllib.request to use urlopen'''
from urllib.request import build_opener, HTTPCookieProcessor
''''Importing urllib.error to hand... | /pyResearchInsights/Visualizer.py | '''Hello! This code code is part of the pyResearchInsights project.
We will be displaying the results from the NLP_Engine.py code here, using primarily using pyLDAvis library.
Check out the repository README.md for a high-level overview of the project and the objective.
Sarthak J. Shetty
24/11/2018'''
from pyResearc... | /pyResearchInsights/__init__.py | from pyResearchInsights.Scraper import scraper_main
from pyResearchInsights.Cleaner import cleaner_main
from pyResearchInsights.Analyzer import analyzer_main
from pyResearchInsights.NLP_Engine import nlp_engine_main
from pyResearchInsights.common_functions import pre_processing, arguments_parser, end_process
from pyRes... | /pyResearchInsights/common_functions.py | '''Hello! This script contains functions that are resued by other pieces of code and scripts belonging to this
project as well.
Checkout the README.md for more details regarding the project itself.
Sarthak J Shetty
12/09/2018'''
'''datetime is used while building the database logs'''
from datetime import datetime
''... | /pyResearchInsights/example.py | '''Hello! We have decided to modularize the entire code, and run it off of one common script.
In the future, the Analyzer.py and the Visualizer.py scripts will be called here as well.
Check out the build-log.md for a detailed changes implemented.
Check out the README.md for more details about the project.
Sarthak J. ... | /pyResearchInsights/system_functions.py | '''Hello! This portion of the code that acts as the processing code corroborating with the main scripts [re: Scraper, Analyzer+NLP_Engine, Visualizer]
- Sarthak J. Shetty
06/02/2019
This script has been renamed as the system_functions.py to carry out OS level interactions, such as:
1. tarballing the LOGS generated to... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
lbarchive/b.py | refs/heads/master | {"/bpy/services/base.py": ["/bpy/handlers/__init__.py"], "/bpy/services/wordpress.py": ["/bpy/handlers/__init__.py", "/bpy/services/base.py"], "/tests/test_bpy_handlers_mkd.py": ["/bpy/handlers/mkd.py"], "/b.py": ["/bpy/services/__init__.py"], "/tests/test_bpy_handlers_text.py": ["/bpy/handlers/text.py"], "/tests/test_... | └──
├── b.py
├── bpy
│ ├── handlers
│ │ ├── __init__.py
│ │ ├── asciidoc.py
│ │ ├── base.py
│ │ ├── html.py
│ │ ├── mkd.py
│ │ ├── rst.py
│ │ └── text.py
│ └── services
│ ├── __init__.py
│ ├── base.py
│ ├── blogge... | /b.py | #!/usr/bin/env python
# Copyright (C) 2013-2016 by Yu-Jie Lin
#
# 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, mo... | /bpy/handlers/__init__.py | # Copyright (C) 2013 by Yu-Jie Lin
#
# 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, distr... | /bpy/handlers/asciidoc.py | #!/usr/bin/env python
# Copyright (C) 2013, 2014 Yu-Jie Lin
#
# 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, modi... | /bpy/handlers/base.py | # Copyright (C) 2013-2015 Yu-Jie Lin
#
# 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, dis... | /bpy/handlers/html.py | # Copyright (C) 2013, 2014 Yu-Jie Lin
#
# 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, di... | /bpy/handlers/mkd.py | # Copyright (C) 2013, 2014 Yu-Jie Lin
#
# 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, di... | /bpy/handlers/rst.py | # Copyright (C) 2011-2014 Yu-Jie Lin
#
# 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, dis... | /bpy/handlers/text.py | # Copyright (C) 2013, 2014 Yu-Jie Lin
#
# 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, di... | /bpy/services/__init__.py | # Copyright (C) 2013 by Yu-Jie Lin
#
# 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, distr... | /bpy/services/base.py | # Copyright (C) 2013 by Yu-Jie Lin
#
# 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, distr... | /bpy/services/blogger.py | # Copyright (C) 2013-2016 by Yu-Jie Lin
#
# 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, ... | /bpy/services/wordpress.py | # Copyright (C) 2013, 2014, 2016 by Yu-Jie Lin
#
# 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, pu... | /tests/test_bpy_handlers_base.py | # Copyright (C) 2013, 2014 Yu-Jie Lin
#
# 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, di... | /tests/test_bpy_handlers_mkd.py | # Copyright (C) 2013, 2014 Yu-Jie Lin
#
# 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, di... | /tests/test_bpy_handlers_rst.py | # Copyright (C) 2013, 2014 Yu-Jie Lin
#
# 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, di... | /tests/test_bpy_handlers_text.py | # Copyright (C) 2013, 2014 Yu-Jie Lin
#
# 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, di... | /tests/test_setup.py | # Copyright (C) 2013 by Yu-Jie Lin
#
# 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, distr... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Ashafix/argparse2HTML | refs/heads/master | {"/blueprints/celery_task.py": ["/args.py"], "/blueprints/subprocess_task.py": ["/args.py"], "/server.py": ["/argparse2dict.py"], "/args.py": ["/example_argparser.py"]} | └──
├── argparse2dict.py
├── args.py
├── blueprints
│ ├── celery_task.py
│ └── subprocess_task.py
├── config.py
├── example_argparser.py
└── server.py | /argparse2dict.py | import argparse
from collections import OrderedDict
def argparser_to_dict(parser):
"""
Converts an ArgumentParser from the argparse module to a dictionary
:param parser: ArgumentParser, argparser which should be converted to a dictionary
:return: dict, key: argparser.dest, value: dict with key: argpar... | /args.py | from example_argparser import parser1, simple_math
from example_argparser import parser_cycler, cycler
from example_argparser import parser_wrapper, wrapper
from collections import namedtuple
Parser = namedtuple('CLI', ('name', 'parser', 'function'))
parsers = [Parser(name=parser1.prog,
parser=par... | /blueprints/celery_task.py | import os
import logging
import contextlib
import dill
import binascii
from flask import request, jsonify, Response
from flask import Blueprint, redirect, url_for
from celery import Celery
from args import get_cli
from config import JOB_FOLDER, CELERY_BROKER_URL, RESULT_BACKEND
celery = Celery('argparser_server', bro... | /blueprints/subprocess_task.py | import sys
import os
import uuid
import psutil
import subprocess
from flask import request, jsonify, Response
from flask import Blueprint, redirect, url_for
from args import get_cli
from config import JOB_FOLDER
FILENAME_LOG = os.path.join(JOB_FOLDER, '{}.log')
FILENAME_PID = os.path.join(JOB_FOLDER, '{}.pid')
SEP =... | /config.py | import os
CELERY_BROKER_URL = 'redis://localhost:6379/0'
RESULT_BACKEND = 'redis://localhost:6379/0'
USE_CELERY = False
SERVER_PORT = 5000
JOB_FOLDER = os.path.join(os.getcwd(), 'jobs')
os.makedirs(JOB_FOLDER, exist_ok=True)
| /example_argparser.py | import argparse
import itertools
import time
import builtins
parser1 = argparse.ArgumentParser(prog='simple math', description='a simple math command line interface')
parser1.add_argument('x', help='first value',
default='2',
type=int)
parser1.add_argument('y', help='second va... | /server.py | import os
from collections import OrderedDict
import importlib
import socket
from flask import Flask, request, url_for, redirect
import jinja2
import args
from argparse2dict import argparser_to_dict
from config import CELERY_BROKER_URL, RESULT_BACKEND, USE_CELERY, SERVER_PORT
app = Flask(__name__)
if USE_CELERY:
... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
marvin939/ZombiePygame | refs/heads/master | {"/tests/test_effects.py": ["/game.py", "/effects.py"], "/tests/test_projectile.py": ["/weapon.py"], "/tests/test_warhead.py": ["/weapon.py"], "/demo/demo_projectile.py": ["/weapon.py"], "/demo/demo_weapon.py": ["/weapon.py", "/entity.py"], "/mobs.py": ["/weapon.py"], "/demo/demo_effects.py": ["/manager.py"], "/demo/de... | └──
├── demo
│ ├── demo_effects.py
│ ├── demo_image_manager.py
│ ├── demo_projectile.py
│ ├── demo_rotate_towards_mouse.py
│ ├── demo_turret_rotate.py
│ └── demo_weapon.py
├── effects.py
├── entity.py
├── game.py
├── manager.py
├── mobs.py
├── run.py
... | /demo/demo_effects.py | import time
import sys
import pygame
from game import *
from effects import *
from pygame.locals import *
from manager import ImageManager
GREEN = (0, 255, 0)
FPS = 30
"""
bullet_travel = BulletTravelEffect(world, Vector2(0, 0), Vector2(320, 240))
world.add_entity(bullet_travel)
"""
image_dude = None
def main():
... | /demo/demo_image_manager.py | from manager import ImageManager
import sys
import os
import pygame
import time
# Add 1-dir-up to path (contains manager.py, and errors.py)
# sys.path += [os.path.join(os.getcwd(), '..')]
'''No need to do; just change the working directory of the file @ Run->Edit Configurations...
Don't forget to change relative paths... | /demo/demo_projectile.py | import sys
import pygame
from pygame.math import Vector2
from game import *
from pygame.locals import *
from weapon import Projectile
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption('Projectile object demonstration')
clock = pygame.time.Clock()
world = World()
CENTER_VEC = Vector... | /demo/demo_rotate_towards_mouse.py | import pygame
from manager import ImageManager
from game import *
from pygame.locals import *
from pygame.math import Vector2
def main():
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
clock = pygame.time.Clock()
image_manager = ImageManager('../data/images')
sprite_image = image_mana... | /demo/demo_turret_rotate.py | from encodings.punycode import selective_find
import pygame
from manager import ImageManager
from game import *
from pygame.locals import *
from pygame.math import Vector2
from mobs import *
image_manager = None
def main():
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
clock = pygame.time.C... | /demo/demo_weapon.py | import sys
import pygame
from pygame.math import Vector2
from game import *
from pygame.locals import *
from weapon import Projectile, WeaponSimplified
from entity import GameEntity
import utilities
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption('Projectile object demonstration'... | /effects.py | """This is where effects go. eg. Explosions, bullet effects, etc. that disappear in time"""
from entity import GameEntity
from game import *
import math
class BulletTravelEffect(GameEntity):
def __init__(self, world, origin, destination, color=YELLOW, speed=1000, length=50, duration=math.inf):
super()._... | /entity.py | from pygame.math import Vector2
import math
import pygame
import utilities
#from mobs import *
class GameEntity:
"""GameEntity that has states"""
def __init__(self, world, name, image, location=None, destination=None, speed=0):
self.world = world
self.name = name
self.image = image
... | /game.py | import copy
import math
import pygame
from pygame.math import Vector2
FPS = 60
SCREEN_WIDTH, SCREEN_HEIGHT = SCREEN_SIZE = (640, 480)
SCREEN_CENTER = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)
TICK_SECOND = 1000 / FPS / 1000
# Colors
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255,... | /manager.py | import os
import pygame
from errors import *
class ImageManager:
"""The thing that manages images"""
def __init__(self, dir='.'):
self.image_directory = os.path.abspath(dir)
self.surf_dict = {}
if pygame.display.get_surface() is None:
raise ScreenNotInitialized('ImageMan... | /mobs.py | from random import randint
from entity import *
from game import *
from pygame.math import Vector2
import math
import utilities
from effects import *
from weapon import WeaponSimplified
class Zombie(SentientEntity):
"""A Zombie wandering aimlessly"""
NAME = 'zombie'
def __init__(self, world, image, locat... | /run.py | import pygame
from pygame.locals import *
from game import *
import sys
import mobs
from manager import ImageManager
from random import randint
image_dude = None
TITLE = 'Zombie Defence v0.0.0'
def main():
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption(TITLE)
c... | /tests/test_effects.py | import copy
from effects import BulletTravelEffect, ExplosionEffect
from game import World
import unittest
from pygame.math import Vector2
from game import *
TICK_SECOND = 1000 / 30 / 1000 # One tick represented by 30 frames per second; 33 milliseconds
class BulletTravelEffectTestCase(unittest.TestCase):
def se... | /tests/test_entity.py | import unittest
from pygame.math import Vector2
from game import *
from entity import *
class GameEntityTestCase(unittest.TestCase):
def setUp(self):
self.world = World()
self.ENTITY_WIDTH, self.ENTITY_HEIGHT = self.ENTITY_SIZE = (32, 32)
self.entity_image = pygame.Surface(self.ENTITY_SIZE... | /tests/test_image_manager.py | import unittest
from manager import ImageManager
import pygame
import os
from errors import *
class ImageManagerTestCaseA(unittest.TestCase):
def test_try_making_imagemanager(self):
"""ImageManager should raise an error if the screen surface has not been initialised yet"""
with self.assertRaises(... | /tests/test_mobs.py | import unittest
from manager import ImageManager
import time
from mobs import *
from game import *
from pygame.math import Vector2
class SentryGunTestCase(unittest.TestCase):
def setUp(self):
pygame.init()
self.screen = pygame.display.set_mode(SCREEN_SIZE)
self.image_manager = ImageManage... | /tests/test_projectile.py | from weapon import Weapon, Projectile, Warhead
from unittest import TestCase
from game import *
import utilities
class DestinationProjectileTestCase(TestCase):
def setUp(self):
self.warhead = None
self.speed = 100
self.world = World()
self.location = Vector2(SCREEN_WIDTH / 2, SCRE... | /tests/test_utilities.py | import math
import unittest
import utilities
class UtilitiesTestCase(unittest.TestCase):
def test_unit_circle_angle(self):
angles = list(range(-20, 20))
hypotenuse = 5
assumed_angles = {}
for angle in angles:
opposite = hypotenuse * math.sin(angle)
assumed_a... | /tests/test_warhead.py | from weapon import Weapon, Projectile, Warhead
import unittest
from game import *
class WarheadTestCase(unittest.TestCase):
"""Warheads should be reusable for different projectiles of same type"""
def setUp(self):
"""
self.warhead = None
self.speed = 100
self.world = World()
... | /tests/test_weapon.py | import unittest
import utilities
from weapon import *
from game import *
class WeaponSimplifiedTestCase(unittest.TestCase):
def setUp(self):
self.fire_rate = 3 # bullets per second
self.world = World()
self.owner_location = Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)
self.owner =... | /tests/test_world.py | from mobs import *
from random import randint, random
import unittest
from game import *
import pygame
NUM_ZOMBIES = 10
NUM_SURVIVORS = 5
NUM_SENTRY_GUNS = 2
class WorldTestCase(unittest.TestCase):
def setUp(self):
self.world = World()
dummy_surface = pygame.Surface((16, 16))
w, h = dummy... | /utilities.py | import math
'''
def unit_angle(angle):
"""Convert radians to unit circle radians' range of 0 to 6.28"""
one_rev = math.pi * 2
if angle > 0:
return divmod(angle, math.pi * 2)[1]
if angle < 0:
angle = divmod(angle, one_rev)[1]
if angle < 0:
return angle + one_rev
r... | /weapon.py | from random import *
from entity import *
from game import *
'''
self.pistol = Weapon(self.weap_damage, \
self.weap_clip, \
self.weap_reload_rate, \
self.weap_fire_rate, \
self.weap_spread, \
self.weap_rounds_per_s... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Tarun-yadav777/Djanjo-Project-Schemer- | refs/heads/master | {"/schemegen/admin.py": ["/schemegen/models.py"], "/schemegen/views.py": ["/schemegen/models.py"]} | └──
└── schemegen
├── admin.py
├── migrations
│ ├── 0001_initial.py
│ ├── 0002_delete_genre.py
│ └── 0003_auto_20201116_1718.py
├── models.py
├── urls.py
└── views.py | /schemegen/admin.py | from django.contrib import admin
from .models import Schemegen, User_info
admin.site.register(Schemegen)
admin.site.register(User_info)
| /schemegen/migrations/0001_initial.py | # Generated by Django 3.0.8 on 2020-11-13 11:23
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Genre',
fields=[
('id', models.AutoField(au... | /schemegen/migrations/0002_delete_genre.py | # Generated by Django 3.0.8 on 2020-11-13 11:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('schemegen', '0001_initial'),
]
operations = [
migrations.DeleteModel(
name='Genre',
),
]
| /schemegen/migrations/0003_auto_20201116_1718.py | # Generated by Django 3.0.8 on 2020-11-16 11:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schemegen', '0002_delete_genre'),
]
operations = [
migrations.AlterField(
model_name='schemegen',
name='type',
... | /schemegen/models.py | from django.db import models
class Schemegen(models.Model):
choices = [
("Women's Development", "Women's Development"),
("Social Justice", "Social Justice"),
("Sports", "Sports"),
("Ruler Development", "Ruler Development"),
("Child Development", "Child Development")
]
... | /schemegen/urls.py | from django.urls import path
from schemegen import views
urlpatterns = [
path('', views.index, name='index'),
path('adhaar', views.adhaar, name='adhaar'),
path('requirements', views.requirements, name='requirements'),
path('detail', views.detail, name='detail'),
path('adhaar-hindi', views.adhaar_h... | /schemegen/views.py | from django.shortcuts import render
from django.http import HttpResponse
from .models import Schemegen
def index(request):
return render(request, 'Index.html')
def adhaar(request):
return render(request, 'Adhaar.html')
def requirements(request):
return render(request, 'Requirements.html')
def detail(... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
lqy9860/qy_code | refs/heads/master | {"/\u7f51\u7edc\u53cc\u4eba\u5bf9\u6218\u4e94\u5b50\u68cb/Gobang_tcp/main.py": ["/\u7f51\u7edc\u53cc\u4eba\u5bf9\u6218\u4e94\u5b50\u68cb/gobang2_client/engine.py", "/\u7f51\u7edc\u53cc\u4eba\u5bf9\u6218\u4e94\u5b50\u68cb/Gobang_tcp/engine.py", "/\u7f51\u7edc\u53cc\u4eba\u5bf9\u6218\u4e94\u5b50\u68cb/gobang2_client/comp... | └──
└── 网络双人对战五子棋
├── Gobang_tcp
│ ├── chessboard.py
│ ├── chessman.py
│ ├── computergothread.py
│ ├── engine.py
│ ├── main.py
│ ├── main_tcpserver.py
│ ├── test.py
│ └── usergothread.py
└── gobang2_client
├... | /网络双人对战五子棋/Gobang_tcp/chessboard.py | from chessman import ChessMan
class ChessBoard(object):
BOAED_SIZE=15
def __init__(self):
# 初始化
self.__board=[[0 for i in range(ChessBoard.BOAED_SIZE+1)]
for i in range(ChessBoard.BOAED_SIZE+1)]
# 清空棋盘
def initBoard(self):
# 忽略第一行
fo... | /网络双人对战五子棋/Gobang_tcp/chessman.py | import threading
class ChessMan(object):
# 棋子类
def __init__(self):
self.__pos=[0,0]
self.__color='+'
self.con=threading.Condition()
def NOTIFY(self):
# 对notify进行封装
self.con.acquire()
self.con.notify()
self.con.release()
def WAIT(s... | /网络双人对战五子棋/Gobang_tcp/computergothread.py | import threading
import re
class ComputerGoThread(threading.Thread):
def __init__(self, chessman, engine,client_socker):
super().__init__()
self.chessman = chessman
self.engine = engine
self.client_socker=client_socker
self.con = threading.Condition()
def run... | /网络双人对战五子棋/Gobang_tcp/engine.py | import random
import re
from chessboard import ChessBoard
from chessman import ChessMan
class Engine(object):
def __init__(self,chessboard):
self.__chessboard=chessboard
def computerGo(self,chessman):
if not isinstance(chessman,ChessMan):
raise Exception('第一个参数必须为Ches... | /网络双人对战五子棋/Gobang_tcp/main.py | from chessboard import ChessBoard
from chessman import ChessMan
from engine import Engine
from usergothread import UserGoThread
from computergothread import ComputerGoThread
def test1():
# 初始化棋盘
chessboard = ChessBoard()
chessboard.initBoard()
chessboard.printBoard()
def test2():
# 初... | /网络双人对战五子棋/Gobang_tcp/main_tcpserver.py | import socket
import threading
from chessboard import ChessBoard
from chessman import ChessMan
from engine import Engine
from usergothread import RECV_UserGoThread,UserGoThread
if __name__ == '__main__':
# tcp套接字
server_socker = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定端... | /网络双人对战五子棋/Gobang_tcp/test.py | import pygame
import time
def isWon():
bcolor=[(250, 198, 115, 255),(250, 199, 108, 255),(249, 201, 101, 255)]
wcolor = [(195, 164, 142, 255), ]
if __name__ == '__main__':
# 初始化
pygame.init()
#创建窗口(必须)
# set_mode会返回一个Surface对象,代表了在桌面上出现的那个窗口,三个参数第一个为元祖,代表分 辨率(必须);第二个是一个标志位,具体意思见下表,如... | /网络双人对战五子棋/Gobang_tcp/usergothread.py | import threading
import time
import re
class RECV_UserGoThread(threading.Thread):
def __init__(self,chessman,engine,client_socker):
super().__init__()
self.chessman=chessman
self.engine=engine
self.client_socker=client_socker
self.con=threading.Condition()
... | /网络双人对战五子棋/gobang2_client/chessboard.py | # -*- coding: utf-8 -*-
# @Time : 2020/7/30 9:21
# @Author : LQY
""" chessboard"""
from chessman import *
class ChessBoard(object):
# 类属性
BOARD_SIZE = 15 # 棋盘的大小
def __init__(self):
# 棋盘的下标从0到15,申请内存
self.__board = [[0 for i in range(ChessBoard.BOARD_SIZE+1)]
... | /网络双人对战五子棋/gobang2_client/chessman.py | # -*- coding: utf-8 -*-
# @Time : 2020/7/30 10:25
# @Author : LQY
""" chessname"""
import threading
class ChessMan(object):
'''
棋子类
'''
def __init__(self):
self.__pos = [0,0]
self.__color = '+'
self.con = threading.Condition()
def setPos(self,pos):
... | /网络双人对战五子棋/gobang2_client/clientRecv.py | # -*- coding: utf-8 -*-
# @Time : 2020/8/1 12:58
# @Author : LQY
""" clientserverRecv"""
import threading
from chessman import *
from engine import *
from chessboard import *
import re
class ClientRecvThread(threading.Thread):
def __init__(self,chessboard,chesswhite,engine,client_socket): # 服务端收发要用... | /网络双人对战五子棋/gobang2_client/computergothread.py | # -*- coding: utf-8 -*-
# @Time : 2020/7/31 10:29
# @Author : LQY
""" computergothread"""
import threading
from chessman import *
from engine import *
from chessboard import *
import re
class ComputerGoThread(threading.Thread):
'''电脑下棋的线程'''
def __init__(self,chessboard,chessmanUser,engine,cl... | /网络双人对战五子棋/gobang2_client/engine.py | # -*- coding: utf-8 -*-
# @Time : 2020/7/30 11:15
# @Author : LQY
""" engine"""
import random
from chessman import *
import re
from chessboard import *
class Engine():
def __init__(self,chessboard):
self.__chessboard = chessboard
def computerGo(self,chessman):
'''
电脑... | /网络双人对战五子棋/gobang2_client/main.py | # -*- coding: utf-8 -*-
# @Time : 2020/7/30 9:27
# @Author : LQY
""" main"""
from chessboard import *
from chessman import *
from engine import *
import threading
import time
import random
def test1():
chessboard = ChessBoard()
chessboard.initBoard()
chessboard.printBoard()
def test2()... | /网络双人对战五子棋/gobang2_client/usergothread.py | # -*- coding: utf-8 -*-
# @Time : 2020/7/31 10:29
# @Author : LQY
""" usergothread"""
import threading
from chessman import *
from engine import *
from chessboard import *
class UserGoThread(threading.Thread):
'''用户下棋的线程'''
def __init__(self,chessblack,engine,client_socket):
'''初始化'... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
astonshane/Alien-Spoilers | refs/heads/master | {"/alienspoilers/subs/oauthHelpers.py": ["/alienspoilers/subs/subreddit.py", "/alienspoilers/subs/forms.py", "/alienspoilers/subs/models.py"], "/alienspoilers/subs/renderings.py": ["/alienspoilers/subs/subreddit.py", "/alienspoilers/subs/models.py"], "/alienspoilers/subs/views.py": ["/alienspoilers/subs/subreddit.py", ... | └──
├── alienspoilers
│ ├── home
│ │ └── views.py
│ └── subs
│ ├── admin.py
│ ├── forms.py
│ ├── migrations
│ │ └── 0006_auto_20150204_1435.py
│ ├── models.py
│ ├── oauthHelpers.py
│ ├── renderings.py
│ ├── subred... | /alienspoilers/home/views.py | from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from subs.forms import UserForm, UserProfileForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from uuid import uuid4
from django.contrib.auth.models imp... | /alienspoilers/subs/admin.py | from django.contrib import admin
from subs.models import Event
from subs.models import UserProfile
class EventAdmin(admin.ModelAdmin):
list_display = ('title', 'creator', 'subreddit', 'subreddit_fullname', 'start_date', 'end_date', 'pub_date', 'repeat', 'repeat_type', 'was_published_recently')
# Register your mod... | /alienspoilers/subs/forms.py | from django import forms
from django.contrib.auth.models import User
from subs.models import UserProfile, Event
import datetime
from django.utils import timezone
from django.contrib.admin import widgets
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
... | /alienspoilers/subs/migrations/0006_auto_20150204_1435.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('subs', '0005_auto_20150204_1432'),
]
operations = [
migrations.RemoveField(
model_name='userprofile',
... | /alienspoilers/subs/models.py | import datetime
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.contrib import admin
import uuid
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User, related... | /alienspoilers/subs/oauthHelpers.py | from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from subs.forms import UserForm, UserProfileForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from uuid import uuid4
from django.contrib.auth.models imp... | /alienspoilers/subs/renderings.py | from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from uuid import uuid4
from django.contrib.auth.models import User
from subs.models import UserProfile, Event
from django.utils import timezone
import datetime
import urllib
import requests
from subreddit import Subreddit
imp... | /alienspoilers/subs/subreddit.py | class Subreddit:
def __init__(self, name, fullname):
self.name = name
self.fullname = fullname
self.url = "http://www.reddit.com" + name
def __str__(self):
print self.name
| /alienspoilers/subs/urls.py | from django.conf.urls import patterns, url
from subs import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.user_login, name='login'),
url(r'^logout/$', views.user_logout, name='logout'),
url(r'^au... | /alienspoilers/subs/views.py | from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from subs.forms import UserForm, UserProfileForm, CreateEventForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from uuid import uuid4
from django.contri... | /old/subscribe.py | import praw
import sys
def is_subscribed(subreddit):
r = praw.Reddit(user_agent = "Alien Spoilers: v0.0.1")
r.login()
subs = r.get_my_subreddits()
for sub in subs:
if str(sub) == subreddit:
return True
return False
def subscribe(subreddit):
r = praw.Reddit(user_agent = "A... | /old/toggle_sub.py | import praw
import sys
try:
r = praw.Reddit(user_agent = "astonshane - test praw")
r.login()
subs = r.get_my_subreddits()
found = False
for sub in subs:
s = str(sub)
if s.lower() == "python":
found = True
if found:
r.get_subreddit('python').unsubscribe()
... | /test.py | import praw
s = '/r/sarah'
s = s.replace("/r/","")
r = praw.Reddit('test by astonshane')
x = ""
try:
x = r.get_subreddit(s, fetch=True)
print "succeeded"
except:
print x, "failed"
#fullname = x.fullname.encode('utf-8')
#print fullname
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
gaosui/Biazza | refs/heads/master | {"/backend/main.py": ["/backend/search.py"]} | └──
└── backend
├── build_cache.py
├── main.py
├── piazza_api
│ └── __init__.py
├── save_model.py
├── search.py
└── test.py | /backend/build_cache.py | from piazza_api import Piazza
from html.parser import HTMLParser
import json
class MyParser(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True)
self.data = []
def handle_data(self, d):
self.data.append(d)
def feed(self, d):
super().feed(d + '<div>&nbs... | /backend/main.py | from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import sys
import urllib.parse as up
from search import predict
from gensim.models import KeyedVectors
model = KeyedVectors.load("vectors.kv", mmap='r')
print('model loaded')
f = open('cache.json')
cache = json.load(f)
f.close()
print('cache loade... | /backend/piazza_api/__init__.py | from piazza_api.piazza import Piazza
__version__ = "0.8.0"
| /backend/save_model.py | from gensim.test.utils import get_tmpfile
from gensim.models import KeyedVectors
model = KeyedVectors.load_word2vec_format("./GoogleNews-vectors-negative300.bin", binary=True)
print("finish loading start saving")
fname = "vectors.kv"
model.save(fname)
print("reload")
word_vectors = KeyedVectors.load("vectors.kv", mmap... | /backend/search.py | import nltk
from nltk.corpus import stopwords
import re
import numpy as np
import string
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from scipy.spatial.distance import cosine
from gensim.models import KeyedVectors
from gensim.test.utils import datap... | /backend/test.py | import json
import sys
import search
from gensim.models import KeyedVectors
#model = KeyedVectors.load_word2vec_format("./GoogleNews-vectors-negative300.bin", binary=True)
model = KeyedVectors.load("vectors.kv", mmap='r')
f = open('cache.json')
cache = json.load(f)
f.close()
#for i in range()
cids = list(cache['jml6... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
valexandersaulys/flask-ladder | refs/heads/master | {"/app/csrf_protect.py": ["/app/utils.py"]} | └──
├── app
│ ├── __init__.py
│ ├── accounts.py
│ ├── csrf_protect.py
│ ├── forms.py
│ ├── models.py
│ ├── utils.py
│ └── views.py
├── config.py
├── fabric_scripts
│ ├── fabfile.py
│ └── setup_server.py
├── manage.py
└── run.py | /app/__init__.py | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# alternatively, from flask_mongoengine import MongoEngine
import os
from config import BASEDIR
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
# db = MongoEngine(app)
# User Authentication Dictionary (would be Redis-cache in... | /app/accounts.py | # 'User' Model (for MySQL)
from app import app, db
from werkzeug.security import generate_password_hash, \
check_password_hash
class User(db.Model):
# All models should have an 'id'
id = db.Column(db.Integer, index=True, primary_key=True)
# Standard user stuff
username = db.Column(db.String(1... | /app/csrf_protect.py | from . import app
from .utils import hash_generator
@app.before_request
def csrf_protect():
if request.method == "POST":
token = session.pop("_csrf_token", None);
if not token or token != request.form.get("_csrf_token"):
abort(403);
def generate_csrf_token():
if "_csrf_token" not i... | /app/forms.py |
# def?
class LoginForm():
"""
For the login forms
"""
| /app/models.py | from app import db
from werkzeug.security import generate_password_hash, \
check_password_hash
class SimpleModel(db.Model):
id = db.Column(db.Integer, index=True, primary_key=True)
def __repr__(self):
return "<ID #%r>" % (self.id);
| /app/utils.py | # Any utility functions would go here
import string, random
def hash_generator(size=8,
chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
| /app/views.py | import os, datetime
from app import app, db, logger
from flask import render_template, flash, redirect, session, url_for, \
request, g, send_from_directory
# - - - - - - - Custom Routing
@app.errorhandler(404)
def error_404():
# Haven't actually tried this yet
return render_template("404.html")
# - - ... | /config.py | import os
SECRET_KEY = "beautiful_little_world_is_mine"
BASEDIR = os.path.abspath(os.path.dirname(__file__))
# = = = = = = = For the Database Configuration
# Separate out into a 'db_config.py' for larger projects
if os.environ.get('DATABASE_URI') is None:
DATABASE_URL = 'sqlite:///' + os.path.join(BASEDIR, 'app.d... | /fabric_scripts/fabfile.py | # Python script: run with `$ fab ___command___`
# Imports from nearby files
from fabric.api import *
from setup_server import *
# Environmental Stuff
env.hosts = [
'server.domaind.tld', # name or ip address of server
]
env.user = 'root' # name of user, you'll have to supply password at execution
| /fabric_scripts/setup_server.py | from fabric.api import *
import string,random
def update_upgrade():
"""Updates & Upgrades the server"""
sudo("apt-get update");
sudo("apt-get -y upgrade");
def install_nginx():
"""Install nginx"""
sudo("apt-get install nginx");
def install_python():
"""Install python, dev, etc."""
sudo("... | /manage.py | #!.venv/bin/python
"""
This can be pretty much kept straight
"""
from app import db, app
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__=="__main__":
manager.run()
| /run.py | #!.venv/bin/python
from app import app
app.run(host='0.0.0.0') # Does __not__ run as a debug! For use with gunicorn
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
dmodena/projetoextensao | refs/heads/main | {"/core/views.py": ["/core/utils.py", "/core/forms.py", "/core/models.py"], "/core/forms.py": ["/core/models.py"]} | └──
├── core
│ ├── forms.py
│ ├── migrations
│ │ └── 0001_initial.py
│ ├── models.py
│ ├── templatetags
│ │ └── custom_filters.py
│ ├── urls.py
│ ├── utils.py
│ └── views.py
└── projetoextensao
└── settings
├── dev.py
└──... | /core/forms.py | from django.forms import ModelForm
from core.models import Edital, Aluno
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class EditalForm(ModelForm):
class Meta:
model = Edital
fields = ['titulo', 'descricao', 'inicio_inscricoes', 'fim_inscricoes',... | /core/migrations/0001_initial.py | # Generated by Django 2.0.1 on 2018-03-15 16:16
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUT... | /core/models.py | from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Edital(models.Model):
titulo = models.CharField(max_length = 100)
descricao = models.TextField()
inicio_inscricoes = models.DateField()
fim_inscricoes = models.DateField()
inicio_curso =... | /core/templatetags/custom_filters.py | from django import template
register = template.Library()
@register.filter
def date_mask(value):
return value.strftime('%d/%m/%Y')
@register.filter
def datefull_mask(value):
mes = ""
if value.month == 1:
mes = "Janeiro"
elif value.month == 2:
mes = "Fevereiro"
elif value.month == 3... | /core/urls.py | from django.urls import path
from core import views
urlpatterns = [
path('', views.r_editais),
path('editais/', views.editais, name='editais'),
path('editais/novo/', views.edital_create, name='editais/novo'),
path('editais/editar/<id>', views.edital_edit, name='editais/editar'),
path('editais/excl... | /core/utils.py | from django.conf import settings
def static_files_url():
return settings.STATIC_FILES_URL
| /core/views.py | from django.shortcuts import render, redirect
from core.models import Edital, Aluno, Inscrito
from core.forms import EditalForm, AlunoForm
from core.utils import static_files_url
from django.utils import timezone
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
... | /projetoextensao/settings/dev.py | from projetoextensao.settings.base import *
from decouple import config
DEBUG = True
ALLOWED_HOSTS = []
SECRET_KEY = config('SECRET_KEY')
# Base url for static files
STATIC_FILES_URL = config('STATIC_FILES_URL')
| /projetoextensao/settings/prod.py | from projetoextensao.settings.base import *
import dj_database_url
DEBUG = False
ALLOWED_HOSTS = ['projetoextensao.herokuapp.com']
SECRET_KEY = os.environ['DJANGO_KEY']
DATABASES['default'] = dj_database_url.config()
# Base url for static files
STATIC_FILES_URL = os.environ['STATIC_FILES_URL']
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
pratikaher88/BookStoreProject | refs/heads/master | {"/cart/views.py": ["/coreapp/models.py", "/coreapp/forms.py"], "/coreapp/admin.py": ["/coreapp/models.py"], "/coreapp/forms.py": ["/coreapp/models.py"], "/coreapp/views.py": ["/coreapp/models.py", "/coreapp/forms.py"], "/search/forms.py": ["/coreapp/models.py"], "/search/views.py": ["/coreapp/models.py", "/search/form... | └──
├── cart
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── 0002_auto_20190105_0448.py
│ │ └── 0003_auto_20190105_0511.py
│ ├── urls.py
│ └── views.py
├── coreapp
│ ├── admin.py
│ ├── forms.py
│ ├── migrations
│ │ ├── 0003_auto_20181231_1340... | /cart/migrations/0001_initial.py | # Generated by Django 2.1.4 on 2019-01-04 05:50
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('coreapp', '0022_auto_20190104_0550'),
]
operations = [
migrations.CreateModel(
... | /cart/migrations/0002_auto_20190105_0448.py | # Generated by Django 2.1.4 on 2019-01-05 04:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cart', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='orderitem',
name='book',
),
... | /cart/migrations/0003_auto_20190105_0511.py | # Generated by Django 2.1.4 on 2019-01-05 05:11
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cart', '0002_auto_20190105_0448'),
]
operations = [
migrations.RemoveField(
model_name='order',
name='items',
),
... | /cart/urls.py | from cart import views
from django.urls import path
app_name='cart'
urlpatterns = [
path('<int:item_id>/add', views.add_to_cart, name='add_to_cart'),
path('cart/', views.cart_list_entries_view, name='cart_items'),
path('<int:item_id>/delete', views.delete_from_cart, name='delete_item'),
path('cart/<in... | /cart/views.py | from django.shortcuts import render
from django.shortcuts import render, redirect, get_object_or_404
from django.views import generic
from django.urls import reverse_lazy, reverse
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from coreapp.models import Book, Profile, Orde... | /coreapp/admin.py | from django.contrib.admin import actions
from django.contrib import admin
from coreapp.models import Book, Profile, UserCollection, Order, Requests, Transaction, ShippingAddress, FinalBuyOrder, OldRequests, CompletedBuyOrder, CompletedTransaction
from import_export.admin import ImportExportModelAdmin
from django.contri... | /coreapp/forms.py | from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from coreapp.models import Book, Profile, ShippingAddress
from dal import autocomplete
class UserCreationForm(UserCreationForm):
email = forms.EmailField(required=True, label='Email')
c... | /coreapp/migrations/0003_auto_20181231_1340.py | # Generated by Django 2.1.4 on 2018-12-31 13:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0002_book_price'),
]
operations = [
migrations.AddField(
model_name='book',
name='condition',
... | /coreapp/migrations/0022_auto_20190104_0550.py | # Generated by Django 2.1.4 on 2019-01-04 05:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0021_auto_20190104_0332'),
]
operations = [
migrations.RemoveField(
model_name='order',
name='items',
... | /coreapp/migrations/0024_auto_20190104_0743.py | # Generated by Django 2.1.4 on 2019-01-04 07:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0023_usercollection'),
]
operations = [
migrations.CreateModel(
name='UserCollection... | /coreapp/migrations/0025_auto_20190104_0748.py | # Generated by Django 2.1.4 on 2019-01-04 07:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0024_auto_20190104_0743'),
]
operations = [
migrations.RenameField(
model_name='usercollection',
old_name='user',... | /coreapp/migrations/0026_order.py | # Generated by Django 2.1.4 on 2019-01-05 05:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0025_auto_20190104_0748'),
]
operations = [
migrations.CreateModel(
name='Order',
... | /coreapp/migrations/0027_auto_20190105_0523.py | # Generated by Django 2.1.4 on 2019-01-05 05:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0026_order'),
]
operations = [
migrations.RemoveField(
model_name='order',
... | /coreapp/migrations/0030_auto_20190105_0549.py | # Generated by Django 2.1.4 on 2019-01-05 05:49
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0029_auto_20190105_0530'),
]
operations = [
migrations.RemoveField(
model_name='user... | /coreapp/migrations/0033_auto_20190105_2116.py | # Generated by Django 2.1.4 on 2019-01-05 21:16
import coreapp.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0032_auto_20190105_0613'),
]
operations = [
migrations.AlterField(
model_name='book',
... | /coreapp/migrations/0035_oldrequests_requests_shippingaddress_transaction.py | # Generated by Django 2.1.4 on 2019-01-08 15:24
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('coreapp', '0034_auto_201... | /coreapp/migrations/0036_auto_20190111_0747.py | # Generated by Django 2.1.4 on 2019-01-11 07:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0035_oldrequests_requests_shippingaddress_transaction'),
]
operations = [
migrations.RenameField(
model_name='transaction',
... | /coreapp/migrations/0042_auto_20190111_1406.py | # Generated by Django 2.1.4 on 2019-01-11 14:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0041_auto_20190111_1357'),
]
operations = [
migrations.AlterField(
model_name='shippingaddress',
name='ad... | /coreapp/migrations/0043_auto_20190111_1551.py | # Generated by Django 2.1.4 on 2019-01-11 15:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0042_auto_20190111_1406'),
]
operations = [
migrations.AlterField(
model_name='shipp... | /coreapp/migrations/0044_auto_20190112_0402.py | # Generated by Django 2.1.4 on 2019-01-12 04:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0043_auto_20190111_1551'),
]
operations = [
migrations.AlterField(
model_name='shippingaddress',
name='zi... | /coreapp/migrations/0047_auto_20190112_0429.py | # Generated by Django 2.1.4 on 2019-01-12 04:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0046_shippingaddress_phone_number'),
]
operations = [
migrations.AlterField(
model_name='shippingaddress',
... | /coreapp/migrations/0049_remove_shippingaddress_country.py | # Generated by Django 2.1.4 on 2019-01-12 04:38
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0048_auto_20190112_0433'),
]
operations = [
migrations.RemoveField(
model_name='shippingaddress',
name='country',... | /coreapp/migrations/0051_auto_20190116_0910.py | # Generated by Django 2.1.4 on 2019-01-16 09:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0050_book_buy_or_exchange'),
]
operations = [
migrations.RemoveField(
model_name='book',
name='buy_or_exc... | /coreapp/migrations/0053_auto_20190116_1608.py | # Generated by Django 2.1.4 on 2019-01-16 16:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0052_auto_20190116_1519'),
]
operations = [
migrations.AlterField(
model_name='book',
name='price',
... | /coreapp/migrations/0054_finalbuyorder.py | # Generated by Django 2.1.4 on 2019-01-17 03:32
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('coreapp', '0053_auto_201... | /coreapp/migrations/0056_auto_20190117_1332.py | # Generated by Django 2.1.4 on 2019-01-17 13:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0055_auto_20190117_0425'),
]
operations = [
migrations.RenameField(
model_name='finalbuyorder',
old_name=... | /coreapp/migrations/0057_auto_20190117_1338.py | # Generated by Django 2.1.4 on 2019-01-17 13:38
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0056_auto_20190117_1332'),
]
operations = [
migrations.RenameField(
model_name='finalbuyorder',
old_name='Book',
... | /coreapp/migrations/0059_auto_20190118_1650.py | # Generated by Django 2.1.4 on 2019-01-18 16:50
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0058_auto_20190118_1647'),
]
operations = [
migrations.AlterFie... | /coreapp/migrations/0061_auto_20190119_1345.py | # Generated by Django 2.1.4 on 2019-01-19 13:45
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0060_auto_20190118_1651'),
]
operations = [
migrations.AddField(
model_name='transac... | /coreapp/migrations/0062_auto_20190119_1352.py | # Generated by Django 2.1.4 on 2019-01-19 13:52
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0061_auto_20190119_1345'),
]
operations = [
migrations.RenameField(
model_name='transaction',
old_name='selleradd... | /coreapp/migrations/0063_auto_20190119_1409.py | # Generated by Django 2.1.4 on 2019-01-19 14:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0062_auto_20190119_1352'),
]
operations = [
migrations.AlterField(
model_name='shippingaddress',
name='zi... | /coreapp/migrations/0064_auto_20190119_1412.py | # Generated by Django 2.1.4 on 2019-01-19 14:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0063_auto_20190119_1409'),
]
operations = [
migrations.AlterField(
model_name='book',
name='sell_or_excha... | /coreapp/migrations/0065_auto_20190119_1415.py | # Generated by Django 2.1.4 on 2019-01-19 14:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0064_auto_20190119_1412'),
]
operations = [
migrations.AlterField(
model_name='book',
name='book_name',
... | /coreapp/migrations/0066_finalbuyorder_total_price.py | # Generated by Django 2.1.4 on 2019-01-19 14:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0065_auto_20190119_1415'),
]
operations = [
migrations.AddField(
model_name='finalbuyorder',
name='total_... | /coreapp/migrations/0067_auto_20190119_1549.py | # Generated by Django 2.1.4 on 2019-01-19 15:49
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0066_finalbuyorder_total_price'),
]
operations = [
migrations.AlterField(
model_name='b... | /coreapp/migrations/0068_auto_20190120_1419.py | # Generated by Django 2.1.4 on 2019-01-20 14:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0067_auto_20190119_1549'),
]
operations = [
migrations.AlterField(
model_name='book',
name='price',
... | /coreapp/migrations/0069_completedbuyorder_completedtransaction.py | # Generated by Django 2.1.4 on 2019-01-22 12:38
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('coreapp', '0068_auto_201... | /coreapp/migrations/0070_auto_20190125_0250.py | # Generated by Django 2.1.4 on 2019-01-25 02:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0069_completedbuyorder_completedtransaction'),
]
operations = [
migrations.RemoveField(
model_name='completedbuyorder... | /coreapp/migrations/0071_auto_20190125_0309.py | # Generated by Django 2.1.4 on 2019-01-25 03:09
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | /coreapp/migrations/0073_auto_20190125_0324.py | # Generated by Django 2.1.4 on 2019-01-25 03:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0072_completedbuyorder_user'),
]
operations = [
migrations.RemoveField(
model_name='completedtransaction',
... | /coreapp/migrations/0074_book_image_url.py | # Generated by Django 2.1.4 on 2019-01-26 11:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0073_auto_20190125_0324'),
]
operations = [
migrations.AddField(
model_name='book',
name='image_url',
... | /coreapp/migrations/0075_auto_20190126_1146.py | # Generated by Django 2.1.4 on 2019-01-26 11:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0074_book_image_url'),
]
operations = [
migrations.AlterField(
model_name='book',
name='image_url',
... | /coreapp/migrations/0076_auto_20190129_0437.py | # Generated by Django 2.1.4 on 2019-01-29 04:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0075_auto_20190126_1146'),
]
operations = [
migrations.AlterModelOptions(
name='requests',
options={'verbose_name... | /coreapp/migrations/0077_auto_20190129_0438.py | # Generated by Django 2.1.4 on 2019-01-29 04:38
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0076_auto_20190129_0437'),
]
operations = [
migrations.AlterModelOptions(
name='oldrequests',
options={'verbose_n... | /coreapp/migrations/0078_auto_20190129_1355.py | # Generated by Django 2.1.4 on 2019-01-29 13:55
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0077_auto_20190129_0438'),
]
operations = [
migrations.AlterField(
model_name='book',
... | /coreapp/migrations/0081_auto_20190207_1821.py | # Generated by Django 2.1.4 on 2019-02-07 18:21
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0080_auto_20190130_0336'),
]
operations = [
migrations.AlterField(
model_name='shipping... | /coreapp/models.py | from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save, post_delete ,pre_delete
from django.dispatch import receiver
from PIL import Image
from random import choice
from os.path import join as path_join
from os import listdir
import os
import requests
fro... | /coreapp/urls.py | from django.conf.urls import url
from coreapp import views
from django.urls import path
app_name='coreapp'
urlpatterns = [
path('', views.BookListView.as_view(), name='list_entries'),
path('buy/', views.BuyListView.as_view(), name='buy_entries'),
path('exchange/', views.ExchangeListView.as_view(), na... | /coreapp/views.py | from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import CreateView, ListView, DetailView, UpdateView, DeleteView
from django.views.generic.edit import FormView
from django.urls import reverse_lazy, reverse
from .forms import UserCreationForm, NewEntryForm, UserForm, ProfileForm... | /nofapapp/context_processors.py | from coreapp.models import Transaction, ShippingAddress, Requests, Profile, Order, FinalBuyOrder, UserCollection
from django.shortcuts import get_object_or_404
from coreapp.forms import ShippingAddressForm
from django.db.models import Q
def add_variable_to_context(request):
if request.user.id:
requester_... | /nofapapp/urls.py | from django.conf.urls import url,include
from django.contrib import admin
from django.contrib.auth.views import LoginView, LogoutView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = ... | /search/forms.py | from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from coreapp.models import Book, Profile
from dal import autocomplete
class SearchForm(forms.Form):
search = forms.CharField(
max_length=100, widget=autocomplete.ModelSelect2(url='co... | /search/urls.py | from django.urls import path
from search import views
app_name = 'searchapp'
urlpatterns = [
path('', views.SearchListView.as_view(), name='search'),
# path('', views.search_form , name='search'),
path('content-autocomplete/', views.ContentAutoComplete.as_view(),name='content-autocomplete'),
# path('s... | /search/views.py | from django.shortcuts import render
from dal import autocomplete
from django.views import generic
from django.views.generic.edit import FormView
from django.urls import reverse_lazy, reverse
from search.forms import SearchForm
from django.contrib import messages
from django.contrib.auth.decorators import login_required... | /transaction/transaction/templatetags/user_books_tag.py | from django import template
from coreapp.models import Profile, Transaction, FinalBuyOrder
from django.shortcuts import get_object_or_404
register = template.Library()
@register.filter
def user_books_for_user(collection_all, user_username):
ordered_books = FinalBuyOrder.objects.values_list('book')
requester_b... | /transaction/urls.py | from django.conf.urls import url
from transaction import views
from django.urls import path
app_name = 'transaction'
urlpatterns = [
path('<int:book_id>/add', views.add_request, name='add_request'),
path('requests/', views.RequestListView.as_view(), name='requests_view'),
path('requests/<int:pk>/delete',... | /transaction/views.py | from django.shortcuts import render
from django.views.generic import ListView
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from coreapp.models import Book, Requests, Transaction, UserCollection, FinalBuyOrder, OldRequests, Profile, ShippingAd... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Therapoid/django-assent | refs/heads/master | {"/assent/views/assent.py": ["/assent/views/forms.py", "/assent/models.py"], "/assent/admin.py": ["/assent/models.py"], "/tests/conftest.py": ["/assent/models.py"], "/assent/views/forms.py": ["/assent/models.py"], "/assent/urls.py": ["/assent/views/assent.py"]} | └──
├── assent
│ ├── admin.py
│ ├── migrations
│ │ └── 0001_initial.py
│ ├── models.py
│ ├── urls.py
│ └── views
│ ├── __init__.py
│ ├── assent.py
│ └── forms.py
├── tasks.py
└── tests
├── conftest.py
└── test_models.py | /assent/admin.py | # -*- coding: utf-8 -*-
from django import forms
from django.contrib import admin
from django.utils.translation import ugettext as _
from transcode.conf import get_content_formatters
from .models import Agreement, AgreementUser, AgreementVersion
ContentFormat = get_content_formatters('ASSENT_FORMATTERS')
# ===== ... | /assent/migrations/0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-15 03:43
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
depe... | /assent/models.py | # -*- coding: utf-8 -*-
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from transcode.render import render
class Agreement(models.Model):
document_key = models.Ch... | /assent/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls import url, include
from .views import (
AgreementDetailView,
AgreementListView,
AgreementFormView,
)
urlpatterns = [
url(r'^$', AgreementListView.as_view(), name='agreement_list'),
url(r'^(?P<slug>[^/]+)/$', AgreementDetailView.as_view(), name='agr... | /assent/views/__init__.py | # -*- coding: utf-8 -*-
from .assent import *
| /assent/views/assent.py | # -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.utils.functional import cached_property
f... | /assent/views/forms.py | # -*- coding: utf-8 -*-
from django import forms
from ..models import AgreementUser
class AgreementForm(forms.ModelForm):
hidden_fields = (
'user', 'agreement_version', 'ip_address', 'acceptance_date', )
class Meta:
model = AgreementUser
fields = (
'user', 'agreement_ver... | /tasks.py | # -*- coding: utf-8 -*-
import os
import sys
from invoke import task
BUILDDIR = "build"
PROJECT = "assent"
@task
def clean(ctx):
"""Removes all the cache files"""
ctx.run("find . -type d -name __pycache__ | xargs rm -rf")
ctx.run('rm -rf ./.cache')
builddir = os.path.join(__file__, BUILDDIR)
if o... | /tests/conftest.py | # -*- coding: utf-8 -*-
import os
import pytest
from django import setup
from django.utils import timezone
from django.contrib.auth import get_user_model
from assent.models import Agreement, AgreementUser, AgreementVersion
def pytest_configure():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'example.setting... | /tests/test_models.py | # -*- coding: utf-8 -*-
import pytest
@pytest.mark.django_db
class TestAgreement:
def test_str(self, agreement):
assert str(agreement) == 'test key'
@pytest.mark.django_db
class TestAgreementVersion:
def test_str(self, agreement_version):
timestamp = agreement_version.release_date
a... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
luoyuan3316/mhc2flurry | refs/heads/master | {"/test/test_class2_neural_network.py": ["/mhc2flurry/allele_encoding_pair.py", "/mhc2flurry/testing_utils.py"]} | └──
├── downloads-generation
│ ├── allele_sequences
│ │ ├── assign_pdb_sequences_to_alpha_or_beta.py
│ │ ├── extract_pdb_sequences.py
│ │ ├── filter_sequences.py
│ │ └── make_pseudosequences.py
│ ├── data_curated
│ │ ├── annotate_proteins.py
│ │ ├── curat... | /downloads-generation/allele_sequences/assign_pdb_sequences_to_alpha_or_beta.py | # Assign PDB sequences (searched by mmseqs against IMGT sequences)
# to alpha vs beta based on mmseqs results
import argparse
import sys
import pandas
import os
from mhc2flurry.fasta import read_fasta_to_dataframe
parser = argparse.ArgumentParser()
parser.add_argument(
"pdb_sequences",
metavar="FASTA",
h... | /downloads-generation/allele_sequences/extract_pdb_sequences.py | # Given a set of PDB .cif.gz files, write out a fasta with the sequences of
# each chain. This will be used to align MHC II PDB structures against
# sequences from IMDB and other sources.
import argparse
import sys
import json
import os
import glob
import atomium
parser = argparse.ArgumentParser()
parser.add_argumen... | /downloads-generation/allele_sequences/filter_sequences.py | """
Filter and combine class II sequence fastas.
"""
from __future__ import print_function
import sys
import argparse
from mhc2flurry.common import normalize_allele_name
import Bio.SeqIO # pylint: disable=import-error
parser = argparse.ArgumentParser(usage=__doc__)
parser.add_argument(
"fastas",
nargs="+... | /downloads-generation/allele_sequences/make_pseudosequences.py | """
Select allele sequences for pan-class II models by analyzing distances between
each MHC residue and the peptide across a set of structures from PDB.
"""
from __future__ import print_function
import sys
import argparse
import collections
import os
import operator
import numpy
import pandas
import tqdm
import ato... | /downloads-generation/data_curated/annotate_proteins.py | """
Given a CSV where some column indicates peptides, add a column indicating which
protein(s) from some specified proteome contain that peptide.
"""
import argparse
import time
import sys
import tqdm
import pandas
import numpy
import shellinford
from mhc2flurry.fasta import read_fasta_to_dataframe
parser = argpars... | /downloads-generation/data_curated/curate_ms_by_pmid.py | """
Filter and combine various peptide/MHC datasets to derive a composite training set,
optionally including eluted peptides identified by mass-spec.
The handle_pmid_XXXX functions should return a DataFrame with columns:
- peptide
- sample_id
- hla [space separated list of alleles]
- pulldown_antibody
- format [m... | /downloads-generation/data_curated/curate_t_cell_epitopes.py | """
Curate IEDB T cell epitopes. Currently this doesn't do much except rename the
peptide column from "Description" to "peptide".
"""
import sys
import argparse
import pandas
from mhc2flurry.amino_acid import COMMON_AMINO_ACIDS
parser = argparse.ArgumentParser(usage=__doc__)
parser.add_argument(
"--data-iedb",
... | /downloads-generation/data_pdb/make_pdb_query.py | # Just print a JSON PDB query to stdout
# Doing this in a python script so we have comments.
import json
sequences = []
# DRA1*01:01
sequences.append(
"MAISGVPVLGFFIIAVLMSAQESWAIKEEHVIIQAEFYLNPDQSGEFMFDFDGDEIFHVDMAKKETVWRLEEFGRF"
"ASFEAQGALANIAVDKANLEIMTKRSNYTPITNVPPEVTVLTNSPVELREPNVLICFIDKFTPPVVNVTWLRNGKP"
"V... | /downloads-generation/data_pdb/parse_results.py | # From a PDB results json, print out a comma separated list of PDB IDs
import argparse
import sys
import json
parser = argparse.ArgumentParser()
parser.add_argument("results", metavar="JSON")
parser.add_argument("out", metavar="FILE")
args = parser.parse_args(sys.argv[1:])
parsed = json.load(open(args.results))
prin... | /downloads-generation/data_proteomes/index_fasta.py | """
Write a shellinford index for a fasta.
"""
import argparse
import time
import sys
import shellinford
from mhc2flurry.fasta import read_fasta_to_dataframe
parser = argparse.ArgumentParser(usage=__doc__)
parser.add_argument(
"input",
metavar="FASTA",
help="Input file")
parser.add_argument(
"outpu... | /mhc2flurry/__init__.py | """
Class II MHC ligand prediction package
"""
#from .class2_affinity_predictor import Class2AffinityPredictor
#from .class2_neural_network import Class2NeuralNetwork
from .version import __version__
__all__ = [
"__version__",
# "Class2AffinityPredictor",
# "Class2NeuralNetwork",
]
| /mhc2flurry/allele_encoding_pair.py | from .allele_encoding import AlleleEncoding
class AlleleEncodingPair(object):
def __init__(
self,
alpha_allele_encoding,
beta_allele_encoding):
"""
"""
self.alpha_allele_encoding = alpha_allele_encoding
self.beta_allele_encoding = beta_allele_en... | /mhc2flurry/downloads.py | """
Manage local downloaded data.
"""
from __future__ import (
print_function,
division,
absolute_import,
)
import logging
import yaml
from os.path import join, exists
from os import environ
from pipes import quote
from collections import OrderedDict
from appdirs import user_data_dir
from pkg_resources imp... | /mhc2flurry/testing_utils.py | """
Utilities used in MHC2flurry unit tests.
"""
from .common import configure_tensorflow
def startup():
"""
Configure Keras backend for running unit tests.
"""
configure_tensorflow("tensorflow-cpu", num_threads=2)
def cleanup():
"""
Clear tensorflow session and other process-wide resources.... | /test/test_class2_neural_network.py | import logging
logging.getLogger('tensorflow').disabled = True
logging.getLogger('matplotlib').disabled = True
import numpy
import tensorflow.random
numpy.random.seed(0)
tensorflow.random.set_seed(0)
import pandas
from sklearn.metrics import roc_auc_score
import mhcgnomes
from mhc2flurry.allele_encoding_pair import... | /test/test_common.py | from mhc2flurry.common import make_allele_pairs
def test_allele_pairs():
alleles = [
"HLA-DRB1*07:01",
"HLA-DRB1*16:01",
"HLA-DRB4*01:03",
"HLA-DRB5*02:02",
"HLA-DPA1*01:03",
"HLA-DPB1*02:01",
"HLA-DPB1*23:01",
"HLA-DQA1*01:02",
"HLA-DQA1*02:... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
strahman/django-niftyurls | refs/heads/master | {"/niftyurls/admin.py": ["/niftyurls/models.py"], "/niftyurls/management/commands/niftyurls_feeds.py": ["/niftyurls/models.py", "/niftyurls/fetch_feed.py"], "/niftyurls/templatetags/niftyurls_tags.py": ["/niftyurls/models.py"]} | └──
├── demo_project
│ └── views.py
├── niftyurls
│ ├── admin.py
│ ├── fetch_feed.py
│ ├── management
│ │ └── commands
│ │ └── niftyurls_feeds.py
│ ├── models.py
│ ├── settings.py
│ └── templatetags
│ └── niftyurls_tags.py
└── setup.py | /demo_project/views.py | from django.http import Http404, HttpResponse
from django.views.generic.simple import direct_to_template
def home(request):
return direct_to_template(request, 'home.html')
| /niftyurls/admin.py | from django.contrib import admin
from models import Source, Feed, Entry, MetaData
class FeedAdmin(admin.ModelAdmin):
#prepopulated_fields = {"slug": ("title",)}
pass
class EntryAdmin(admin.ModelAdmin):
#date_hierarchy = 'date'
list_display = ('title', 'feed')
search_fields = ['title', 'description... | /niftyurls/fetch_feed.py | import socket
socket.setdefaulttimeout(60)
import datetime, time, urllib2, urlparse #, sys, json, zlib, signal
import feedparser
class NiftyUrlsException(Exception):
pass
class FetchFeed(object):
def __init__(self, link, page_url=None):
self.link = link
self.page_url = page_url # useful for de... | /niftyurls/management/commands/niftyurls_feeds.py | # -*- coding: UTF-8 -*-
import signal, datetime, logging, os, sys, time, json, base64 #zlib, bz2,
from optparse import make_option
from django.core.management.base import BaseCommand
from django.contrib.contenttypes.models import ContentType
from niftyurls.fetch_feed import FetchFeed
from niftyurls.models import Feed, ... | /niftyurls/models.py | import datetime
from django.utils.translation import ugettext as _
from django.db import models
from django.contrib.sites.models import Site
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.auth.models import User
from django.template.default... | /niftyurls/settings.py | import os
from django.conf import settings
temp_settings = {'example.com': {'rows': '3', 'title': 'Welcome', 'h1': 'Hello'}}
temp_settings.update(getattr(settings, 'NIFTYURLS_SETTINGS', {}))
NIFTYURLS_MEDIA = getattr(settings, 'NIFTYURLS_MEDIA',
os.path.join(settings.MEDIA_URL, 'niftyurls... | /niftyurls/templatetags/niftyurls_tags.py | import re, sys
from django.contrib.sites.models import RequestSite
from django.contrib.sites.models import Site
from django import template
from niftyurls.models import Feed
from niftyurls.settings import NIFTYURLS_SETTINGS, NIFTYURLS_JS, \
NIFTYURLS_CSS, NIFTYURLS_MEDIA
register = te... | /setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup, find_packages
setup(
name='django-niftyurls',
version='1.0.0-alpha',
description='A popurls style Django application.',
author='Florentin Sardan',
author_email='florentinwww@gmail.com',
long_description=open('README... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
AklerQ/python_training | refs/heads/master | {"/data/contact_data.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/generator/contact_gen.py": ["/model/contact.py"], "/test/test_add_contact_to_group.py": ["/model/contact.py"], "/test/test_contact_data_validation.py": ["/model/contact.py"], "/test/test_del_contact.py": ["/model/contact.py... | └──
├── data
│ └── contact_data.py
├── fixture
│ ├── contact.py
│ ├── group.py
│ └── navigation.py
├── generator
│ └── contact_gen.py
├── model
│ └── contact.py
└── test
├── test_add_contact_to_group.py
├── test_contact_data_validation.py
... | /data/contact_data.py | from model.contact import Contact
import random
import string
def random_string(prefix, maxlen):
symbols = string.ascii_letters + string.digits + " "*10
return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))])
def random_number(maxlen):
symbols = string.digits + ")" + "... | /fixture/contact.py | # -*- coding: utf-8 -*-
from model.contact import Contact
import re
class ContactHelper:
def __init__(self, app):
self.app = app
def create(self, contact):
wd = self.app.wd
self.app.navigation.turn_to_home_page()
# create new contact
wd.find_element_by_link_text("add n... | /fixture/group.py | # -*- coding: utf-8 -*-
from model.group import Group
class GroupHelper:
def __init__(self, app):
self.app = app
def create(self, group):
wd = self.app.wd
self.app.navigation.open_groups_page()
# init group creation
wd.find_element_by_name("new").click()
# fil... | /fixture/navigation.py | # -*- coding: utf-8 -*-
class NavigationHelper:
def __init__(self, app):
self.app = app
def open_home_page(self):
wd = self.app.wd
if not ((len(wd.find_elements_by_link_text("Create account")) > 0)
and (len(wd.find_elements_by_link_text("Forgot password")) > 0)):
... | /generator/contact_gen.py | from model.contact import Contact
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of contacts", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f = "data/contacts.json"
for ... | /model/contact.py | from sys import maxsize
class Contact:
def __init__(self, firstname=None, middlename=None, lastname=None, nickname=None, companyname=None, address=None,
homenumber=None, worknumber=None, mobilenumber=None, faxnumber=None, email=None, email2=None,
birth_date=None, birth_month=Non... | /test/test_add_contact_to_group.py | # -*- coding: utf-8 -*-
from model.group import Group
from model.contact import Contact
from fixture.orm import ORMfixture
import random
orm = ORMfixture(host="127.0.0.1", name="addressbook", user="root", password="root")
def test_add_contact_to_group(app, db):
# Проверка на наличие групп
if len(db.get_group... | /test/test_contact_data_validation.py | import re
from random import randrange
from model.contact import Contact
def test_random_contact_data_on_home_page(app):
contacts = app.contact.get_contact_list()
index = randrange(len(contacts))
contact_from_home_page = app.contact.get_contact_list()[index]
contact_from_edit_page = app.contact.get_co... | /test/test_db_matches_ui.py | from model.group import Group
def test_group_list(app, db):
ui_list = app.group.get_group_list()
db_list = map(app.group.clean, db.get_group_list())
assert sorted(ui_list, key=Group.id_or_max) == sorted(db_list, key=Group.id_or_max)
| /test/test_del_contact.py | # -*- coding: utf-8 -*-
from model.contact import Contact
import random
def test_delete_first_contact(app, db, check_ui):
if app.contact.count_contacts() == 0:
app.contact.create(Contact(firstname="Тест_имени", lastname="Тест_фамилии",
birth_date="//div[@id='content']/form/selec... | /test/test_del_contact_from_group.py | # -*- coding: utf-8 -*-
from model.group import Group
from model.contact import Contact
from fixture.orm import ORMfixture
import random
db = ORMfixture(host="127.0.0.1", name="addressbook", user="root", password="")
def test_del_contact_from_group(app):
# Проверка на наличие групп
if len(db.get_group_list()... | /test/test_edit_contact.py | # -*- coding: utf-8 -*-
from model.contact import Contact
import random
def test_edit_contact_by_index(app, db, check_ui):
if app.contact.count_contacts() == 0:
app.contact.create(Contact(firstname="For modify", birth_date="//div[@id='content']/form/select[1]//option[1]",
birth_... | /test/test_edit_group.py | # -*- coding: utf-8 -*-
from model.group import Group
import random
def test_edit_first_group_footer(app, db, check_ui):
if len(db.get_group_list()) == 0:
app.group.create(Group(name="For modification", header="For modification", footer="For modification"))
old_groups = db.get_group_list()
group =... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
smartgang/KViewer | refs/heads/master | {"/Indexer/__init__.py": ["/Indexer/IndexerWidget.py", "/Indexer/DMI.py", "/Indexer/MACD.py", "/Indexer/KDJ.py", "/Indexer/EMA.py", "/Indexer/HullRsi.py", "/Indexer/ATR.py", "/Indexer/RSI.py"], "/KViewer_new.py": ["/ChildGraph.py"], "/kviewer_app.py": ["/indexer.py"], "/Indexer/ATR.py": ["/Indexer/IndexerBase.py"], "/I... | └──
├── ChildGraph.py
├── DataInterface
│ └── DataInterface.py
├── Indexer
│ ├── ATR.py
│ ├── DMI.py
│ ├── EMA.py
│ ├── HullRsi.py
│ ├── IndexerBase.py
│ ├── IndexerWidget.py
│ ├── KDJ.py
│ ├── MACD.py
│ ├── RSI.py
│ └── __init__.py
├── ... | /ChildGraph.py | # -*- coding: utf-8 -*-
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from Indexer import *
import pyqtgraph as pg
import pandas as pd
class ChildGraph(QWidget):
main_child_plt_changed = pyqtSignal(name='main_child_plt_changed')
def __init__(self, child=True):... | /DataInterface/DataInterface.py | # -*- coding: utf-8 -*-
import pandas as pd
import time
import os
# 读取中文路径
Collection_Path = unicode('D:\\002 MakeLive\DataCollection\\', 'utf-8')
PUBLIC_DATA_PATH = unicode('D:\\002 MakeLive\DataCollection\public data\\', 'utf-8')
RAW_DATA_PATH = unicode('D:\\002 MakeLive\DataCollection\\raw data\\', 'utf-8')
TICKS_D... | /Indexer/ATR.py | # -*- coding: utf-8 -*-
from IndexerBase import IndexerBase
import numpy as np
class ATR(IndexerBase):
indexer_name = 'ATR'
indexer_name_list = ['ATR', 'TR']
default_para_dic = {
'N': 26,
}
def __init__(self, raw_data, plt):
super(ATR, self).__init__(raw_data, plt)
self.ind... | /Indexer/DMI.py | # -*- coding: utf-8 -*-
from IndexerBase import IndexerBase
import numpy as np
import pandas as pd
class DMI(IndexerBase):
indexer_name = 'DMI'
indexer_name_list = ['PDI', 'MDI', 'ADX', 'ADXR']
default_para_dic = {
'N': 14,
'M': 6,
}
def __init__(self, raw_data, plt):
super... | /Indexer/EMA.py | # -*- coding: utf-8 -*-
from IndexerBase import IndexerBase
class EMA(IndexerBase):
indexer_name = 'EMA'
indexer_name_list = [] # MA的指标名和参数名都跟参数有关,所以要随参数进行设置
default_para_dic = {
'N1': 5,
'N2': 10,
'N3': 15,
'N4': 30,
'N5': 50
}
def __init__(self, raw_data... | /Indexer/HullRsi.py | # -*- coding: utf-8 -*-
from IndexerBase import IndexerBase
import numpy as np
import talib
class HULL_RSI(IndexerBase):
indexer_name = 'HULL_RSI'
indexer_name_list = ['RSI']
default_para_dic = {
'N1': 5,
'M1': 5,
'M2': 9,
'N': 8
}
def __init__(self, raw_data, plt)... | /Indexer/IndexerBase.py | # -*- coding: utf-8 -*-
"""
指标类,用于管理指标相内容:
"""
class IndexerBase(object):
color_list = ['blue', 'magenta', 'cyan', 'red', 'green']
indexer_name = ''
indexer_name_list = []
default_para_dic = {}
para_dic = {}
indexer_color_dic = {} # 各指标对应的显示颜色
def __init__(self, raw_data, plt):
se... | /Indexer/IndexerWidget.py | # -*- coding: utf-8 -*-
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from Indexer import *
class IndexerWidget(QWidget):
signal_para_changed = pyqtSignal(str,dict, name='para_changed')
def __init__(self, all_indexer_para_dic, current_indexer_name):
sup... | /Indexer/KDJ.py | # -*- coding: utf-8 -*-
from IndexerBase import IndexerBase
import numpy as np
import talib
class KDJ(IndexerBase):
indexer_name = 'KDJ'
indexer_name_list = ['K', 'D', 'J']
default_para_dic = {
'N': 9,
'M1': 3,
'M2': 3
}
def __init__(self, raw_data, plt):
super(KDJ... | /Indexer/MACD.py | # -*- coding: utf-8 -*-
from IndexerBase import IndexerBase
import pyqtgraph as pg
class MACD(IndexerBase):
indexer_name = 'MACD'
indexer_name_list = ['DIF', 'DEA', 'HIST'] # MA的指标名和参数名都跟参数有关,所以要随参数进行设置
default_para_dic = {
'Short':12,
'Mid':9,
'Long':26
}
def __init__(sel... | /Indexer/RSI.py | # -*- coding: utf-8 -*-
from IndexerBase import IndexerBase
import numpy as np
import talib
class RSI(IndexerBase):
indexer_name = 'RSI'
indexer_name_list = ['RSI']
default_para_dic = {
'N': 5,
}
def __init__(self, raw_data, plt):
super(RSI, self).__init__(raw_data, plt)
s... | /Indexer/__init__.py | # -*- coding: utf-8 -*-
from IndexerWidget import IndexerWidget
from MA import MA
from MACD import MACD
from RSI import RSI
from ATR import ATR
from HullMacd import HULL_MACD
from EMA import EMA
from HullRsi import HULL_RSI
from KDJ import KDJ
from DMI import DMI
indexer_mapping_dic = {
'MA': MA,
'EMA': EMA,
... | /KViewer_new.py | # -*- coding: utf-8 -*-
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from Indexer import *
import pyqtgraph as pg
import pandas as pd
from ChildGraph import ChildGraph
import DataInterface.DataInterface as DI
class KViewer(QWidget):
def __init__(self,):
su... | /MainFrame.py | # -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import *
from KViewer_new import KViewer
class KViewerMainWindow(QMainWindow):
def __init__(self, parent=None):
super(KViewerMainWindow, self).__init__(parent)
self.resize(800,600)
self.setWindowTitle('KViewer')
self.tab_widg... | /complex.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'complex.ui'
#
# Created: Sat Jul 14 20:48:01 2018
# by: pyside-uic 0.2.15 running on PySide 1.2.4
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(s... | /complex2.py | # -*- coding: utf-8 -*-
#from PySide import QtCore, QtGui
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(803, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self... | /complexExample.py | # -*- coding: utf-8 -*-
import complex2
from PyQt5 import QtCore, QtWidgets, QtGui
import sys
import time
import pyqtgraph as pg
import pandas as pd
import tushare as ts
import datetime
from matplotlib.pylab import date2num
class MainWindow(object):
def __init__(self):
app = QtWidgets.QApplication(sys.ar... | /decouple_window.py | # -*- coding: utf-8 -*-
import nullWindow
from PyQt5 import QtCore, QtWidgets, QtGui
if __name__=='__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = nullWindow.Ui_MainWindow()
ui.setupUi(MainWindow)
ui.tableWidget.setItem(0,0,QtWidgets.QTab... | /indexer.py | # -*- coding: utf-8 -*-
"""
指标类,用于管理指标相内容:
1.参数,包括参数控件的内容
para_name:参数名列表
para_dic: 参数字典,键为参数名,值为参数值
para_widgets_dic: 参数按键字典, 键为参数名,值为控件名
2.数据
data_dic:数据字典,键为参数名,值为数据
3.画图
plt:主图控件
plt_dic:子图控件字典,键为参数名,值为子图控件
"""
class IndexerBase(object):
color_list = ['w', 'y', 'c', 'r', 'g']
def ... | /kviewer1.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'kviewer.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.... | /kviewer2.py | # -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
sizePolicy = QtWidgets.QSizePolicy(Qt... | /kviewer_app.py | # -*- coding: utf-8 -*-
import kviewer2
from indexer import Indexer_MA
import parameter2
from PyQt5 import QtCore, QtWidgets, QtGui
import sys
import time
import pyqtgraph as pg
import pandas as pd
import numpy as np
#import tushare as ts
import datetime
from matplotlib.pylab import date2num
#import DATA_CONSTANTS as... | /nullWindow.py | # -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(641, 405)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("cen... | /parameter.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'parameter.ui'
#
# Created: Sat Jul 21 16:49:46 2018
# by: pyside-uic 0.2.15 running on PySide 1.2.4
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_Form(object):
def setupUi(self,... | /parameter2.py | # -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(398, 494)
self.verticalLayout = QtWidgets.QVBoxLayout(Form)
self.verticalLayout.setObjectName("verticalLayout")
self.gro... | /untitled.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created: Wed Jul 11 23:51:04 2018
# by: pyside-uic 0.2.15 running on PySide 1.2.4
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(s... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
saadjansari/KymoAnalysis | refs/heads/main | {"/src/Features.py": ["/src/node_graph.py"], "/src/Kymograph.py": ["/src/node_graph.py"], "/src/Track.py": ["/src/node_graph.py"], "/src/Strain.py": ["/src/Load.py", "/src/Kymograph.py"]} | └──
├── KymographAnalysis.py
└── src
├── Features.py
├── Kymograph.py
├── Load.py
├── ReadFiles.py
├── Strain.py
├── Track.py
├── breakBipolar.py
├── node_graph.py
└── smooth_test.py | /KymographAnalysis.py | #!/usr/bin/env python
import os, pdb, sys
import matplotlib.pyplot as plt
import matplotlib
import pandas as pd
import numpy as np
import seaborn as sns
import math, random
import glob, yaml, copy, shutil
from src.Strain import *
"""
Name: KymographAnalysis.py
Description: Parses and combines tracks from multiple ky... | /src/Features.py | #!/usr/bin/env python
import os, pdb
import numpy as np
from scipy import interpolate, signal
from .node_graph import Graph
import matplotlib.pyplot as plt
import math
import uuid
# Superclass for Poles and tracks that stores positional and intensity information
class Feature:
def __init__(self, time, position, i... | /src/Kymograph.py | #!/usr/bin/env python
import os, pdb
import math
import numpy as np
from scipy import interpolate
from .node_graph import Graph
import matplotlib.pyplot as plt
from .Features import *
from .ReadFiles import *
'''
Name: Kymograph.py
Description: Parses general, poles and feature information for a single kymograph and... | /src/Load.py | #!/usr/bin/env python
import os, pdb
import yaml
import glob
'''
Name: Load.py
Description: loads and splits the tracks saved by the trackBuilder (kyman.mlapp) into general, poles and feature sections to be parsed by Kymograph.py
'''
# Class to load data from files
class Load:
def __init__(self, verbose=0):
... | /src/ReadFiles.py | #!/usr/bin/env python
import os, pdb
import math
import numpy as np
from .Track import *
import matplotlib.pyplot as plt
def ReadTxt( fname, verbose=0):
# Read data from files and parse into general, poles and feature information
if verbose:
PrintFile( fname)
# Initialize lists
geninfo = []
... | /src/Strain.py | #!/usr/bin/env python
import os, pdb
from .Load import Load
from .Kymograph import Kymograph
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
import math, random
import pickle
from pathlib import Path
from scipy import interpolate, signal
class Strain:
def __init__(sel... | /src/Track.py | #!/usr/bin/env python
import os, pdb
import numpy as np
from scipy import interpolate, signal
from .node_graph import Graph
import matplotlib.pyplot as plt
import math
import uuid
# Superclass for Poles and tracks that stores positional and intensity information
class Feature:
def __init__(self, time, position, i... | /src/breakBipolar.py | #!/usr/bin/env python
import os, pdb
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
from .Kymograph import *
import shutil
from random import sample
import seaborn as sns
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.mi... | /src/node_graph.py | #!/usr/bin/env python
# Python program to print connected
# components in an undirected graph
# This code is contributed by Abhishek Valsan
# Updated by Saad Ansari for a directed graph application
import pdb
class Graph:
# init function to declare class variables
def __init__(self,V):
... | /src/smooth_test.py | #!/usr/bin/env python
import os, pdb
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
from .Kymograph import *
import shutil
'''
Name: breakBipolar.py
Description: Plots the pole separation of a bipolar file
'''
folds = ['wild type']
savepath = Path('/Users/saadjansari/Documents/Projects/I... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Edinburgh-Genome-Foundry/Geneblocks | refs/heads/master | {"/geneblocks/DiffBlocks/DiffBlocks.py": ["/geneblocks/DiffBlocks/DiffBlock.py", "/geneblocks/Location.py", "/geneblocks/DiffBlocks/DiffRecordTranslator.py", "/geneblocks/biotools.py", "/geneblocks/CommonBlocks/CommonBlocks.py", "/geneblocks/DiffBlocks/diffblocks_tools.py"], "/geneblocks/DiffBlocks/__init__.py": ["/gen... | └──
├── examples
│ ├── common_blocks.py
│ ├── complex_sequences.py
│ ├── diff_blocks.py
│ └── features_transfer.py
├── geneblocks
│ ├── CommonBlocks
│ │ ├── CommonBlocks.py
│ │ ├── CommonBlocksRecordTranslator.py
│ │ ├── __init__.py
│ │ └── commonbl... | /examples/common_blocks.py | from geneblocks import CommonBlocks
from geneblocks.biotools import reverse_complement, random_dna_sequence
C1, A, B, C2, C3, D, E, F = [random_dna_sequence(100 * L) for L in range(1, 9)]
sequences = {
"a": C1 + A + C2,
"b": B + D + C2 + C3,
"c": E + C1 + C2,
"d": C2 + C1 + F + C3,
"e": C3 + rever... | /examples/complex_sequences.py | from geneblocks import DiffBlocks, CommonBlocks, random_dna_sequence
import geneblocks.sequence_modification_utils as smu
import matplotlib.pyplot as plt
import numpy
numpy.random.seed(1) # ensures the sequences will be the same at each run
# GENERATE 2 "SISTER" SEQUENCES FOR THE EXAMPLE
seq1 = random_dna_sequence(5... | /examples/diff_blocks.py | import os
from geneblocks import DiffBlocks, load_record
seq_1 = load_record(os.path.join("sequences", "sequence1.gb"))
seq_2 = load_record(os.path.join("sequences", "sequence2.gb"))
diff_blocks = DiffBlocks.from_sequences(seq_1, seq_2)
ax1, ax2 = diff_blocks.plot(figure_width=8)
ax1.figure.savefig("diff_blocks.png",... | /examples/features_transfer.py | import os
from geneblocks import CommonBlocks, load_record
from dna_features_viewer import BiopythonTranslator
import matplotlib.pyplot as plt
# LOAD THE TWO RECORDS
part_path = os.path.join("sequences", "features_transfer", "part.gb")
part = load_record(part_path, name="part")
plasmid_path = os.path.join(
"seque... | /geneblocks/CommonBlocks/CommonBlocks.py | """Defines central class BlockFinder."""
import itertools
from collections import OrderedDict
from copy import deepcopy
from .CommonBlocksRecordTranslator import CommonBlocksRecordTranslator
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from ..biotools import annotate_record
from .commonblocks_tools im... | /geneblocks/CommonBlocks/CommonBlocksRecordTranslator.py | from dna_features_viewer import BiopythonTranslator
class CommonBlocksRecordTranslator(BiopythonTranslator):
ignored_features_types = ("diff_equal",)
default_box_color = None
def compute_feature_color(self, f):
if f.qualifiers.get("is_block", False):
return BiopythonTranslator.comput... | /geneblocks/CommonBlocks/__init__.py | from .CommonBlocks import CommonBlocks
__all__ = ['CommonBlocks'] | /geneblocks/CommonBlocks/commonblocks_tools.py | """Algorithmic methods for the selection of common blocks in DiffBlocks
- select_common_blocks
-
- segments_difference
"""
import re
import tempfile
import subprocess
from collections import defaultdict, OrderedDict
import numpy as np
from ..biotools import reverse_complement, sequence_to_record
def format_seq... | /geneblocks/DiffBlocks/DiffBlock.py | from ..Location import Location
from ..biotools import sequences_differences
class DiffBlock:
"""Class to represent a segment that differs between sequences.
Parameters
----------
operation
One of "insert", "delete", "replace", or "equal".
s1_location
The Location(start, end) of the ... | /geneblocks/DiffBlocks/DiffBlocks.py | from copy import deepcopy
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
from ..Location import Location
from ..biotools import sequence_to_record
from ..CommonBlocks import CommonBlocks
from .DiffBlock import DiffBlock
from .DiffRecordTranslator import DiffRecordTranslator... | /geneblocks/DiffBlocks/DiffRecordTranslator.py | from dna_features_viewer import BiopythonTranslator
class DiffRecordTranslator(BiopythonTranslator):
ignored_features_types = ("diff_equal",)
default_box_color = None
@staticmethod
def compute_feature_color(f):
return dict(
diff_delete="#E76F51", # RED
diff_insert="#... | /geneblocks/DiffBlocks/__init__.py | from .DiffBlocks import DiffBlocks, DiffBlock
from .DiffRecordTranslator import DiffRecordTranslator
__all__ = ['DiffBlocks', 'DiffBlock', 'DiffRecordTranslator'] | /geneblocks/DiffBlocks/diffblocks_tools.py | from copy import deepcopy
import networkx as nx
import Levenshtein
from ..Location import Location
from .DiffBlock import DiffBlock
def compute_levenshtein_blocks(seq1, seq2, max_complexity=1e8):
"""Compute the Levenshtein blocks of insertion, deletion, replacement.
"""
# TODO: better method for dealin... | /geneblocks/Location.py | from .biotools import reverse_complement
from Bio.SeqFeature import SeqFeature, FeatureLocation
class Location:
def __init__(
self, start, end, strand=None, sequence=None, sequence_id=None
):
self.start = start
self.end = end
self.strand = strand
self.sequence = sequen... | /geneblocks/__init__.py | """ geneblocks/__init__.py """
# __all__ = []
from .CommonBlocks import CommonBlocks
from .DiffBlocks import DiffBlocks, DiffRecordTranslator
from .biotools import load_record, random_dna_sequence, reverse_complement
from .utils import sequences_are_circularly_equal
from .version import __version__
__all__ = [
... | /geneblocks/biotools.py | import tempfile
import subprocess
import numpy as np
try:
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.SeqFeature import SeqFeature, FeatureLocation
from Bio import SeqIO
BIOPYTHON_AVAILABLE = True
except ImportError:
BIOPYTHON_AVAILABLE = False
try:
# Biopython <... | /geneblocks/sequence_modification_utils.py | """These methods are only useful to build examples and tests for Geneblocks."""
from .biotools import reverse_complement
def change(seq, start, end, change):
"""Return the sequence with ``seq[start:end]`` replaced by ``change``"""
return seq[:start] + change + seq[end:]
def insert(seq, pos, inserted):
... | /geneblocks/utils.py | from .CommonBlocks import CommonBlocks
from .biotools import sequence_to_record
def _turn_sequence_into_record_if_necessary(sequence, record_id="id"):
if hasattr(sequence, "seq"):
return sequence
else:
return sequence_to_record(sequence, record_id=record_id)
def sequences_are_circularly_equa... | /setup.py | import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
exec(open("geneblocks/version.py").read()) # loads __version__
setup(
name="geneblocks",
version=__version__,
author="Zulko",
description="Library to compare DNA sequences (diff, common blocks, etc.)",
long_de... | /tests/test_base_diff_cases.py | from geneblocks.DiffBlocks import DiffBlock, DiffBlocks
from geneblocks.biotools import random_dna_sequence
def diff_string(seq1, seq2, contract_under=0):
return str(DiffBlocks.from_sequences(seq1, seq2))
flanks_dict = {
'short': 10 * "A",
'long': random_dna_sequence(10000)
}
def flanked(seq, flanks='shor... | /tests/test_complex_sequences.py | from geneblocks import DiffBlocks, CommonBlocks, random_dna_sequence
import geneblocks.sequence_modification_utils as smu
import matplotlib.pyplot as plt
def test_complex_sequences():
seq1 = random_dna_sequence(50000, seed=123)
seq1 = smu.copy(seq1, 25000, 30000, 50000)
seq2 = seq1
seq2 = smu.insert(... | /tests/test_scenarios.py | import os
import matplotlib
import networkx as nx
from geneblocks import CommonBlocks, DiffBlocks, load_record
from geneblocks.biotools import reverse_complement, random_dna_sequence
from geneblocks.DiffBlocks import DiffBlock
from geneblocks.Location import Location
matplotlib.use("Agg")
def test_CommonBlocks_basic... | /tests/test_utils.py | from geneblocks.utils import sequences_are_circularly_equal
from Bio import SeqIO
import os
this_directory = os.path.dirname(os.path.realpath(__file__))
def test_sequences_are_circularly_equal():
block_1 = "ATGTGCACACGCACCGTGTGTGCACACACGTGTGCACACACGTGCACACGGTGT"
block_2 = "ACACACATATACGCGTGCGTGCAAAACACATTTT... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
doctor-budoka/shared-expenses-site | refs/heads/master | {"/expenses_app/auth/auth.py": ["/expenses_app/models.py", "/expenses_app/auth/forms.py"], "/expenses_app/commands.py": ["/expenses_app/models.py"], "/expenses_app/group/group.py": ["/expenses_app/models.py", "/expenses_app/group/forms.py"]} | └──
├── config.py
└── expenses_app
├── __init__.py
├── auth
│ ├── auth.py
│ └── forms.py
├── commands.py
├── group
│ ├── forms.py
│ └── group.py
└── models.py | /config.py | from os import environ
from pathlib import Path
from dotenv import load_dotenv
BASE_DIRECTORY = Path(__file__).parent
load_dotenv(BASE_DIRECTORY / ".env")
class Config:
FLASK_ENV = "development"
TESTING = True
DEBUG = True
SECRET_KEY = environ.get("SECRET_KEY")
STATIC_FOLDER = "stati... | /expenses_app/__init__.py | from flask import Flask
from expenses_app.models import db
from flask_login import LoginManager
login_manager = LoginManager()
def create_app():
app = Flask(__name__, template_folder="templates")
app.config.from_object("config.Config")
db.init_app(app)
login_manager.init_app(app)
wi... | /expenses_app/auth/auth.py | from flask import url_for, flash, render_template, make_response
from flask import Blueprint
from flask_login import login_user, login_required, logout_user
from werkzeug.utils import redirect
from expenses_app import db, login_manager
from expenses_app.auth.forms import LogInForm, Register
from expenses_app.mo... | /expenses_app/auth/forms.py | from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import InputRequired, Email, EqualTo
class LogInForm(FlaskForm):
email = StringField("Email", [
InputRequired(message="You must provide an email address to continue"),
Email(... | /expenses_app/commands.py | import click
from flask import current_app as app
from expenses_app.models import db, AuthorisedEmail, User
@app.cli.command("reset-db")
def reset_db():
"""Used to reset the db for the app"""
click.echo("Resetting db...")
db.drop_all()
db.create_all()
click.echo("Done")
@app.cli.co... | /expenses_app/group/forms.py | from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField, FloatField, BooleanField
from wtforms.validators import InputRequired
class CreateGroup(FlaskForm):
name = StringField("Name", [InputRequired(message="You must provide a name for the group!")])
create = SubmitFie... | /expenses_app/group/group.py | from flask import render_template, redirect, url_for, flash, Blueprint
from flask_login import login_required, current_user
from expenses_app.group.forms import CreateGroup, AddUserToGroup, RemoveUserFromGroup, AddAccountToGroup, RemoveAccountFromGroup
from expenses_app.models import db, User, Group, Account
grp_... | /expenses_app/models.py | import datetime as dt
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
db = SQLAlchemy()
class AuthorisedEmail(db.Model):
email_id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.Stri... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
blackout314/myrecon.py | refs/heads/master | {"/myrecon.py": ["/modules/resolve.py", "/modules/subdomains.py", "/modules/app.py"]} | └──
├── modules
│ ├── app.py
│ ├── functions.py
│ ├── openredirect.py
│ ├── resolve.py
│ ├── screenshot.py
│ └── subdomains.py
└── myrecon.py | /modules/app.py | # I don't believe in license.
# You can do whatever you want with this program.
import os
import sys
import time
from colored import fg, bg, attr
class App( object ):
mods = []
d_output = ''
f_domains = ''
f_hosts = ''
f_tmphosts = ''
f_dead = ''
f_ips = ''
f_urls ... | /modules/functions.py | # I don't believe in license.
# You can do whatever you want with this program.
import os
import sys
import argparse
import tldextract
def parseargs( app, t_available_mods ):
parser = argparse.ArgumentParser()
parser.add_argument( "-d","--domain",help="domain, single, multiples or files", action="append" )
... | /modules/openredirect.py | # I don't believe in license.
# You can do whatever you want with this program.
import os
import sys
import subprocess
from colored import fg, bg, attr
def run( app ):
sys.stdout.write( '[+] running mod: openredirect\n' )
cmd = 'open-redirect.py -o ' + app.f_hosts + ' 2>&1 >/dev/null &'
os.system( cmd )... | /modules/resolve.py | # I don't believe in license.
# You can do whatever you want with this program.
import re
import sys
import subprocess
from colored import fg, bg, attr
from functools import partial
from multiprocessing.dummy import Pool
class Resolve( object ):
ips = []
n_ips = 0
dead_host = []
n_dead = 0
full_o... | /modules/screenshot.py | # I don't believe in license.
# You can do whatever you want with this program.
import os
import sys
import subprocess
from colored import fg, bg, attr
def run( app ):
sys.stdout.write( '[+] running mod: screenshots\n' )
cmd = 'EyeWitness --headless -f "' + app.f_urls + '" --user-agent "Mozilla/5.0 (X11; Lin... | /modules/subdomains.py | # I don't believe in license.
# You can do whatever you want with this program.
import re
import sys
import subprocess
from colored import fg, bg, attr
from functools import partial
from multiprocessing.dummy import Pool
class Subdomains( object ):
hosts = []
n_hosts = 0
def run( self, t_domains ):
... | /myrecon.py | #!/usr/bin/python3.5
# I don't believe in license.
# You can do whatever you want with this program.
t_available_mods = ['resolve', 'screenshot', 'quickhits', 'crlf', 'openredirect']
#
# init app
#
from modules import functions as func
from modules.app import App
app = App()
func.parseargs( app, t_available_mods )... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
peteramazonian/simulation_project | refs/heads/master | {"/main_multi_run.py": ["/logger_multi_run.py", "/number_generator.py", "/service_station.py", "/movement.py", "/system_arrival.py", "/time_generator.py"], "/main_single_run.py": ["/number_generator.py", "/logger_single_run.py", "/service_station.py", "/movement.py", "/system_arrival.py", "/time_generator.py"], "/movem... | └──
├── logger_multi_run.py
├── logger_single_run.py
├── main_multi_run.py
├── main_single_run.py
├── movement.py
├── number_generator.py
├── service_station.py
├── system_arrival.py
├── time_generator.py
└── time_management.py | /logger_multi_run.py | import xlsxwriter
from datetime import datetime
class LoggerMR:
def __init__(self, ss_names, replications):
self.total_replications = replications
self.ss_names = ss_names # Setting list of service ServiceStations
time = datetime.now().strftime("%d-%m-%Y--%H-%M-%S")
self.wb = xlsx... | /logger_single_run.py | import xlsxwriter
from datetime import datetime
class LoggerSR:
def __init__(self, s_list):
self.s_list = s_list # Setting list of service ServiceStations
self.system_arrival = __import__('system_arrival').SystemArrival # Importing SystemArrival class. It
# should be imported inside init... | /main_multi_run.py | import sys
import importlib
from service_station import ServiceStation
from system_arrival import SystemArrival
from movement import Movement
from time_generator import TimeGenerator
from number_generator import NumberGenerator
import time_management
from logger_multi_run import LoggerMR
replications = 100
result = [... | /main_single_run.py | from service_station import ServiceStation
from system_arrival import SystemArrival
from movement import Movement
from time_generator import TimeGenerator
from number_generator import NumberGenerator
import time_management
from logger_single_run import LoggerSR
# Its our simulation's main file.
# Here we import class... | /movement.py | import time_management
from time_management import add_to_fel
from system_arrival import SystemArrival
ss_list = __import__('service_station').ServiceStation.list
class Movement():
list = []
@classmethod
def check(cls):
x = len(ss_list)
if len(cls.list) == x + 1:
return
... | /number_generator.py | import random
from math import exp
class NumberGenerator:
class Discrete(random.Random):
def __init__(self, x: tuple, fx: tuple, **kwargs):
self.x = None
self.fx_list = fx
self.x_list = x
if len(self.x_list) != len(self.fx_list):
raise ValueE... | /service_station.py | import time_management
from time_management import add_to_fel, postponed_rest_log_editor
# ----------------------------------------------------------------
# Creating class ServiceStation
# Our service stations are objects of this class
# Costumer arrivals, departures, servers leaving for rest and getting back to wor... | /system_arrival.py | import time_management
from time_management import add_to_fel
__id__ = 10000
# TODO new arrivals in fel dont have id?!?
def id_generator():
global __id__
__id__ += 1
return __id__
class SystemArrival:
list = []
costumers_inside_dict = {}
costumers_departured = 0
costumers_total_time = ... | /time_generator.py | """ Random time generators to be used for inter arrival time or activity time in simulation models.
"""
import random
from math import sqrt, log
class TimeGenerator:
class Uniform(random.Random):
def __init__(self, lower_limit=0, upper_limit=1, **kwargs):
self.x = None
self.lower_... | /time_management.py | import bisect
# ----------------------------------------------------------------------------------------------------------------
# In this module we handle anything related to FEL and clock. in another word this module is the engine that makes
# the code to move.
# ----------------------------------------------------... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
leonsooi/ngskintoolsplus | refs/heads/master | {"/ngSkinToolsPlus/ngSkinToolsPlus/utilities/copyLayers.py": ["/ngSkinToolsPlus/ngSkinToolsPlus/utilities/influenceAssociation.py"]} | └──
└── ngSkinToolsPlus
└── ngSkinToolsPlus
├── lib
│ └── weights.py
├── misc
│ └── tests.py
└── utilities
├── __init__.py
├── copyLayers.py
├── influenceAssociation.py
└── surfac... | /ngSkinToolsPlus/ngSkinToolsPlus/lib/weights.py | '''
Created on Mar 25, 2014
@author: Leon
'''
import maya.cmds as mc
import pymel.core as pm
import utils.rigging as rt
mel = pm.language.Mel()
def smoothLayerMask(mll, layerId, intensity=1.0):
'''
'''
mll.setCurrentLayer(layerId)
mll.ngSkinLayerCmd(cpt='mask')
# if intens... | /ngSkinToolsPlus/ngSkinToolsPlus/misc/tests.py | '''
Created on Mar 22, 2014
@author: Leon
'''
import maya.cmds as mc
# assign weights by nearest joint
args = {}
args['bnj'] = True
selJnts = ['joint1', 'joint2']
args['ij'] = '/'.join(selJnts)
args['intensity'] = 1.0
# must select mesh or components first
# must select layer or mll.setCurrentLayer(... | /ngSkinToolsPlus/ngSkinToolsPlus/utilities/__init__.py | from ngSkinTools.mllInterface import MllInterface
from ngSkinTools.importExport import LayerData, Layer, Influence
from ngSkinTools.importExport import XmlImporter
import maya.cmds as cmds
import pymel.core as pm
'''
Quick hacks just to get the job done when needed. Should be modularized properly some time...... | /ngSkinToolsPlus/ngSkinToolsPlus/utilities/copyLayers.py | '''
Created on 31/08/2013
@author: Leon
'''
from ngSkinTools.mllInterface import MllInterface
from ngSkinToolsPlus.utilities.influenceAssociation import InfluenceAssociation
import re
class CopyLayers:
'''
Copy layers across mesh utility
'''
def __init__(self):
'''
... | /ngSkinToolsPlus/ngSkinToolsPlus/utilities/influenceAssociation.py | '''
Created on 01/09/2013
@author: Leon
'''
class InfluenceAssociation():
'''
classdocs
'''
def __init__(self, srcInfluences, destInfluences, method):
'''
srcInfluences and destInfluences are iterators returned
from mll.listLayerInfluences(layerId, activeInfluenc... | /ngSkinToolsPlus/ngSkinToolsPlus/utilities/surfaceAssociation.py | '''
Created on 01/09/2013
@author: Leon
'''
import pymel.core as pm
class SurfaceAssociation():
'''
classdocs
'''
def __init__(self, srcMesh, destMesh, method):
'''
Constructor
'''
# create dictionary with the format -
# {vertexId o... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
praneshsaminathan/url_shortener | refs/heads/main | {"/core/serializers.py": ["/core/models.py"], "/core/views.py": ["/core/models.py", "/core/serializers.py"], "/core/urls.py": ["/shorturl/utils/apps.py", "/core/views.py"]} | └──
├── core
│ ├── migrations
│ │ └── 0001_initial.py
│ ├── models.py
│ ├── serializers.py
│ ├── urls.py
│ └── views.py
└── shorturl
└── utils
└── apps.py | /core/migrations/0001_initial.py | # Generated by Django 3.1.7 on 2021-03-01 15:58
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='URLInfo',
fields=[
('id', models.AutoField(... | /core/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
class URLInfo(models.Model):
full_url = models.URLField(unique=True, null=False, blank=False, help_text=_('full url'))
url_hash = models.URLField(unique=True, null=False, blank=False, help_text=_('short url'))
clicks = mo... | /core/serializers.py | from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from core.models import URLInfo
class ShorterIRLSerializer(serializers.Serializer):
url = serializers.URLField(max_length=250, min_length=None, allow_blank=False, label=_('URL'), help_text=_('URL'))
| /core/urls.py | from django.urls import path, include
from shorturl.utils.apps import get_api_url
from .views import (
ShorterAPIView, GetFullURLAPIView
)
urlpatterns = [
path(get_api_url(url_name='url-shorten'), ShorterAPIView.as_view(), name='api-url_shorten'),
path(get_api_url(url_name='full-url/<str:url_hash>'), GetF... | /core/views.py | from hashlib import md5
from django.shortcuts import render
from rest_framework.permissions import AllowAny
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from core.serializers import ShorterIRLSerializer
from .models import URLInfo
class Shor... | /shorturl/utils/apps.py |
from django.conf import settings
def get_api_url(name='api', version=settings.API_VERSION, app_name='', url_name=''):
url = '{0}/{1}/'.format(name, version)
if app_name and url_name:
url = '{0}{1}/{2}/'.format(url, app_name, url_name)
elif app_name and not url_name:
url = '{0}{1}/'.form... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
shacharr/roomba_sim | refs/heads/master | {"/roomba_model.py": ["/cleaning_robot_model.py"], "/controller.py": ["/simulator.py"]} | └──
├── arena_model.py
├── arena_view.py
├── cleaning_robot_model.py
├── controller.py
├── helper_functions.py
├── roomba_model.py
└── simulator.py | /arena_model.py | import pygame
from helper_functions import *
class RoomModel(object):
DIRTY_COLOR = (0,255,0)
CLEAN_COLOR = (0,0,255)
DEAD_ZONE_COLOR = (0,0,0)
def __init__(self, polygon, obstacles=[]):
self.polygon = polygon
self.obstacles = obstacles
max_x = max([x[0] for x in polygon])
... | /arena_view.py | import time
import pygame
import math
from helper_functions import *
class ScreenView(object):
WHITE = (255,255,255)
BLACK = ( 0, 0, 0)
BLUE = ( 0, 0,255)
GREEN = ( 0,255, 0)
RED = (255, 0, 0)
ARROW_RELATIVE_COORDS = ((0,0.8),(0.4,0.5),(0.2,0.5),(0.2,-0.6),
... | /cleaning_robot_model.py | import math
from helper_functions import *
class CleaningRobotModel(object):
TURN_STEP_FOR_DRAWING = math.pi/18.
def __init__(self, location, size, cleaning_head_size, direction, speed, room):
self.loc = location
self.direction = direction
self.speed = speed
self.size = size
... | /controller.py | import matplotlib.pyplot
from simulator import run_simulation
from helper_functions import *
#ROOM_POLYGON = [(0,0),(640,0),(640,480),(0,480)]
#ROOM_POLYGON = [(0,0),(640,0),(640,480),(320,480),(320,240),(0,240)]
ROOM_POLYGON = [(0,0),(640,0),(640,480),(320,480),(250,240),(0,240)]
SMALL_SQUARE = [(0,0),(10,0),(10,1... | /helper_functions.py | import math
class Point(object):
def __init__(self,coords):
self.x = coords[0]
self.y = coords[1]
def delta(self,other):
return Point([self.x-other.x,self.y-other.y])
def dot(self,other):
return self.x*other.x + self.y*other.y
def rotate(coords, direction):
# from htt... | /roomba_model.py | import math
import random
from cleaning_robot_model import CleaningRobotModel
from helper_functions import *
class RoombaModel(CleaningRobotModel):
MODE_TIME_LIMIT = [500,2000]
TURN_SIZE_ON_WALL_FOLLOW = math.pi/180.
MAX_TURN_STEPS = 360
SPIRAL_ANGLE_INIT = math.pi/18.
SPIRAL_ANGLE_RATIO = 0.995... | /simulator.py | import time
import pygame
import math
import random
import itertools
import arena_model
import arena_view
import roomba_model
def run_simulation(robot_params={}, room_params={}, stop_conditions={}, visual_feedback=True, draw_final_result=True):
stats = []
room_polygon = room_params["ROOM_POLYGON"]
obste... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
gheinrich/DIGITS | refs/heads/master | {"/digits/model/images/classification/forms.py": ["/digits/model/images/forms.py"], "/digits/model/images/generic/forms.py": ["/digits/model/images/forms.py"]} | └──
└── digits
├── config
│ └── __init__.py
├── dataset
│ └── tasks
│ └── __init__.py
├── model
│ ├── images
│ │ ├── classification
│ │ │ └── forms.py
│ │ ├── forms.py
│ │ └── generic
│ │... | /digits/config/__init__.py | # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
# Create this object before importing the following imports, since they edit the list
option_list = {}
from . import caffe
from . import gpu_list
from . import jobs_dir
from . import log_file
from . import torc... | /digits/dataset/tasks/__init__.py | # Copyright (c) 2014-2016, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
from .analyze_db import AnalyzeDbTask
from .create_db import CreateDbTask
from .create_generic_db import CreateGenericDbTask
from .parse_folder import ParseFolderTask
| /digits/model/images/classification/forms.py | # Copyright (c) 2014-2016, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
import wtforms
from wtforms import validators
from ..forms import ImageModelForm
class ImageClassificationModelForm(ImageModelForm):
"""
Defines the form used to create a new ImageClassificationModelJo... | /digits/model/images/forms.py | # Copyright (c) 2014-2016, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
import wtforms
from wtforms import validators
from ..forms import ModelForm
from digits import utils
class ImageModelForm(ModelForm):
"""
Defines the form used to create a new ImageModelJob
"""
... | /digits/model/images/generic/forms.py | # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
import wtforms
from wtforms import validators
from ..forms import ImageModelForm
class GenericImageModelForm(ImageModelForm):
"""
Defines the form used to create a new GenericImageModelJob
"""
... | /digits/model/tasks/__init__.py | # Copyright (c) 2014-2016, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
from .caffe_train import CaffeTrainTask
from .torch_train import TorchTrainTask
from .train import TrainTask
| /digits/model/tasks/test_caffe_train.py | # Copyright (c) 2014-2016, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
from . import caffe_train
from digits import test_utils
def test_caffe_imports():
test_utils.skipIfNotFramework('caffe')
import numpy
import google.protobuf
| /digits/pretrained_model/__init__.py | # Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
from .job import PretrainedModelJob
| /digits/pretrained_model/tasks/__init__.py | # Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
from .upload_pretrained import UploadPretrainedModelTask
from .caffe_upload import CaffeUploadTask
from .torch_upload import TorchUploadTask
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
welloderx/wechat-2021-BigDataChallenge | refs/heads/master | {"/src/deepctr_ext/utils.py": ["/src/deepctr_ext/feat.py", "/src/deepctr_ext/layers.py"], "/src/main.py": ["/src/core/entrypoint.py"], "/src/core/entrypoint.py": ["/src/core/tasks/lgb.py"]} | └──
└── src
├── core
│ ├── entrypoint.py
│ └── tasks
│ └── lgb.py
├── deepctr_ext
│ ├── feat.py
│ ├── layers.py
│ └── utils.py
└── main.py | /src/core/entrypoint.py | from core.tasks.deepfm import DeepFM_Manager
from core.tasks.lgb import LightGBM_Manager
class EntryPoint(object):
def __init__(self, cfg):
self.cfg = cfg
def start(self):
if self.cfg.task == 'DeepFM':
task = DeepFM_Manager(self.cfg)
task.start()
elif self.cfg.... | /src/core/tasks/lgb.py | """
LightGBM
"""
import lightgbm as lgb
import pandas
from utils import DecoratorTimer
class LightGBM_Manager(object):
model_name = 'LightGBM'
def __init__(self, cfg):
self.cfg = cfg
self.yml_cfg = self.cfg.yml_cfg
self.model_cfg = self.yml_cfg[self.model_name]
assert self.cfg... | /src/deepctr_ext/feat.py | from collections import namedtuple
class SparseFeat(namedtuple('SparseFeat',
['name', 'vocabulary_size', 'embedding_dim', 'use_hash', 'dtype', 'embedding_name'])):
__slots__ = ()
def __new__(cls, name, vocabulary_size, embedding_dim=4, use_hash=False, dtype="int32", embedding_name... | /src/deepctr_ext/layers.py | import torch.nn as nn
import torch
class FM(nn.Module):
"""Factorization Machine models pairwise (order-2) feature interactions
without linear term and bias.
Input shape
- 3D tensor with shape: ``(batch_size,field_size,embedding_size)``.
Output shape
- 2D tensor with shape: ``(batc... | /src/deepctr_ext/utils.py | from collections import OrderedDict
from .feat import SparseFeat, DenseFeat, VarLenSparseFeat
import torch.nn as nn
import numpy as np
import torch
from .layers import SequencePoolingLayer
def get_feature_names(feature_columns):
features = build_input_features(feature_columns)
return list(features.keys())
de... | /src/main.py | from utils import UnionConfig, LoggerUtil, DecoratorTimer, PathUtil, add_argument_from_dict_format
from conf import settings
from core.entrypoint import EntryPoint
import os
import argparse
import logging
import shutil
import traceback
import copy
import sys
registered_task_list = ['DeepFM', 'LightGBM']
def get_con... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
JiTao3/hierarchical_attention | refs/heads/master | {"/model/decoder.py": ["/util/prase_tree2node_leaf.py", "/model/encoder.py", "/util/plan_to_tree.py"], "/model/encoder.py": ["/util/prase_tree2node_leaf.py", "/util/plan_to_tree.py", "/util/dataset.py"], "/util/dataset.py": ["/util/prase_tree2node_leaf.py", "/util/plan_to_tree.py"], "/train.py": ["/model/encoder.py", "... | └──
├── model
│ ├── decoder.py
│ └── encoder.py
├── train.py
└── util
├── __init__.py
├── dataset.py
├── plan_to_tree.py
├── prase_tree2node_leaf.py
├── qerror.py
└── result.py | /model/decoder.py | from torch.autograd import Variable
import time
import copy
import math
import torch.nn.functional as F
import torch.nn as nn
import torch
import numpy as np
import os
import sys
sys.path.append(os.path.abspath(os.getcwd()))
print(sys.path)
from util.plan_to_tree import Node, parse_dep_tree_text
from util.prase_tree2... | /model/encoder.py | import copy
import math
import torch.nn.functional as F
import torch.nn as nn
import torch
import numpy as np
import os
import sys
sys.path.append(os.path.abspath(os.getcwd()))
# print(sys.path)
from util.plan_to_tree import Node, parse_dep_tree_text
from util.prase_tree2node_leaf import treeInterpolation, upward_ca,... | /train.py | import math
from model.encoder import Encoder
from util.dataset import PlanDataset
import torch
import torch.optim as optim
import torch.nn as nn
from torch.utils.data import DataLoader, random_split
from torchsummary import summary
# device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
dataset = P... | /util/__init__.py |
__all__=[
'plan_to_tree',
'prase_tree2node_leaf'
] | /util/dataset.py | import time
import copy
import math
import torch.nn.functional as F
import torch.nn as nn
import torch
import numpy as np
import os
import sys
from torch.utils.data import Dataset, DataLoader
sys.path.append(os.path.abspath(os.getcwd()))
# print(sys.path)
from util.plan_to_tree import Node, parse_dep_tree_text, tree... | /util/plan_to_tree.py | import os
import numpy as np
operators = [
"Merge Join",
"Hash",
"Index Only Scan using title_pkey on title t",
"Sort",
"Seq Scan",
"Index Scan using title_pkey on title t",
"Materialize",
"Nested Loop",
"Hash Join",
]
columns = [
"ci.movie_id",
"t.id",
"mi_idx.movie_id"... | /util/prase_tree2node_leaf.py | from typing import List
from collections import deque
import copy
import numpy as np
import torch
from util.plan_to_tree import Node, parse_dep_tree_text
def add_node_index(root: Node) -> Node:
# add an index tu the tree to identify a node uniquely
# so that we can jsutufy the ancenstral relationship betwee... | /util/qerror.py | from typing import List
import numpy as np
def cal_q_error(predict, label, log=True):
if log:
predict = np.e**predict
label = np.e**label
if predict > label:
q_error = predict / label
else:
q_error = label / predict
return q_error
def print_qerror(q_error: List):
... | /util/result.py |
import sys
import os
import numpy as np
sys.path.append(os.path.abspath(os.getcwd()))
from util.qerror import cal_q_error, print_qerror
with open("/home/jitao/hierarchical_attention/data/dmodel512/resutlv1.0-e10-N4-lr0.001.txt", 'r') as f:
lines = f.readlines()
label_output = [line.split(' ') for line in ... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
RobinHeath-Albuquerque/robin_heath_RPSLS | refs/heads/main | {"/main.py": ["/Spock.py", "/Scissors.py", "/Lizard.py", "/Paper.py", "/Game.py", "/Players.py"], "/rpsls.py": ["/Computer.py", "/Game.py"], "/Computer.py": ["/Game.py", "/Players.py"], "/Human.py": ["/Players.py"]} | └──
├── Computer.py
├── Game.py
├── Human.py
├── Lizard.py
├── Paper.py
├── Players.py
├── Scissors.py
├── Spock.py
├── main.py
└── rpsls.py | /Computer.py | from Players import Players
import random
from Game import Game, my_gestures
class Computer(Players):
def __init__(self, choice):
self.choice = random.choice
def make_gesture(self):
print(self.choice)
computer = Computer
| /Game.py | from random import randrange, random
class Game:
def __init__(self, gestures, rules,):
self.name = ()
self.gestures = my_gestures
self.rules = my_rules
my_gestures = ['rock', 'Spock', 'paper', 'lizard', 'scissors']
my_rules = ['Rock crushes Scissors' 'Scissors cuts Paper', 'Paper cover... | /Human.py | from Players import Players
class Human(Players):
def make_gesture(self):
print(self.gestures)
playerOne = Human()
playerOne.make_gesture()
playerTwo = Human()
| /Lizard.py | class Lizard:
def __init__(self):
self.name = 'Lizard'
self.loses_to = ['Rock', 'Scissors']
| /Paper.py | class Paper:
def __init__(self):
self.name = 'Paper'
self.loses_to = ['Scissors', 'Lizard']
| /Players.py |
class Players:
def __init__(self, types):
self.choice = ''
self.types = my_players
my_players = ['human', 'computer']
| /Scissors.py | class Scissors:
def __init__(self):
self.name = 'Scissors'
self.loses_to = ['Rock', 'Spock']
| /Spock.py | class Spock:
def __init__(self):
self.name = 'Spock'
self.loses_to = ['Lizard', 'Paper']
| /main.py | import RPSLS
from Game import Game
from Players import Players
from Lizard import Lizard
from Spock import Spock
from Paper import Paper
from Scissors import Scissors
from Rock import Rock
if __name__ == '__main__':
game = Game()
game.run_game()
RPSLS.rpsls("rock")
RPSLS.rpsls("Spock")
RPSLS.rpsls("pape... | /rpsls.py | import random
from Game import Game, my_rules, my_gestures
from Computer import Computer, computer
from unittest import result
x = input('Please enter your name:')
print('Hello, ' + x + '. Good luck!')
print()
print('Here are the rules:')
for x in my_rules:
print(x)
print()
print('The best of 3 will win the game!'... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
qcscine/conan-recipes | refs/heads/master | {"/artifactory-scripts/delete-old-pkgs.py": ["/artifactory-scripts/artifactory_api.py"]} | └──
├── artifactory-scripts
│ ├── artifactory_api.py
│ ├── delete-old-pkgs.py
│ └── rehost.py
├── irc
│ └── conanfile.py
├── mongo-cxx-driver
│ └── conanfile.py
├── nauty
│ └── conanfile.py
├── serenity
│ └── conanfile.py
└── xtb
└── conanfile.p... | /artifactory-scripts/artifactory_api.py | __copyright__ = """This code is licensed under the 3-clause BSD license.
Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
See LICENSE.txt for details.
"""
import pytz
import requests
import sys
from datetime import datetime, timedelta
class ArtifactoryAPI(object):
def __init__(self, api_base... | /artifactory-scripts/delete-old-pkgs.py | __copyright__ = """This code is licensed under the 3-clause BSD license.
Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
See LICENSE.txt for details.
"""
from artifactory_api import ArtifactoryAPI
import sys
"""
NOTE:
- Conan package order: name/version@user/channel
E.g. scine_molassembler/1.0... | /artifactory-scripts/rehost.py | __copyright__ = """This code is licensed under the 3-clause BSD license.
Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
See LICENSE.txt for details.
"""
from conans.client.command import Command, Conan
import sys
rehost_packages = [
"boost_assert/1.69.0@bincrafters/stable",
"boost_base/... | /irc/conanfile.py | __copyright__ = """This code is licensed under the 3-clause BSD license.
Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
See LICENSE.txt for details.
"""
from conans import ConanFile, CMake, tools
import shutil
class IrcConanfile(ConanFile):
name = "irc"
version = "6d5c7c37"
descrip... | /mongo-cxx-driver/conanfile.py | __copyright__ = """This code is licensed under the 3-clause BSD license.
Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
See LICENSE.txt for details.
"""
from conans import ConanFile, CMake, tools
from conans.errors import ConanInvalidConfiguration
import os
class MongoCxxConan(ConanFile):
... | /nauty/conanfile.py | __copyright__ = """This code is licensed under the 3-clause BSD license.
Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
See LICENSE.txt for details.
"""
import os
from conans import ConanFile, CMake, tools
class NautyConanfile(ConanFile):
name = "nauty"
version = "2.7r1"
descriptio... | /serenity/conanfile.py | __copyright__ = """This code is licensed under the 3-clause BSD license.
Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
See LICENSE.txt for details.
"""
import os
from conans import ConanFile, CMake, tools
import shutil
def microarch(conanfile):
""" Determine microarch of compiler and os ... | /xtb/conanfile.py | __copyright__ = """This code is licensed under the 3-clause BSD license.
Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
See LICENSE.txt for details.
"""
import os
from conans import ConanFile, CMake, tools
class XtbConanfile(ConanFile):
name = "xtb"
version = "6.3.2"
description = ... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
chengyan1984/cdk-gui | refs/heads/master | {"/BaseUtil.py": ["/cookie_test.py", "/Util.py"], "/CDKCookieUtil.py": ["/cookie_test.py", "/BaseUtil.py"], "/MIUtil.py": ["/cookie_test.py", "/BaseUtil.py"], "/MideaCookieUtil.py": ["/cookie_test.py", "/BaseUtil.py"], "/SuningUtil.py": ["/cookie_test.py", "/BaseUtil.py"], "/TCSMCookieUtil.py": ["/cookie_test.py", "/Ba... | └──
├── BaseUtil.py
├── CDKCookieUtil.py
├── CDKUtil.py
├── ChromeCookie.py
├── ConkaUtil.py
├── GreeUtil.py
├── JDUtil.py
├── MIUtil.py
├── MideaCookieUtil.py
├── MideaUtil.py
├── SuningUtil.py
├── TCSMCookieUtil.py
├── Util.py
├── aesgcm.py
├── asdfsd.py
... | /BaseUtil.py | import re
from urllib.parse import urlparse
import json
import requests
from bs4 import BeautifulSoup
from datetime import date, timedelta, datetime
from Util import Util
from cookie_test import fetch_chrome_cookie
class BaseUtil(Util):
def __init__(self, username, passwd, adminid='15870', factoryid='1', baseurl... | /CDKCookieUtil.py | import datetime
import json
import re
import time
from urllib import parse
from urllib.parse import urlparse
import requests
from BaseUtil import BaseUtil
from cookie_test import fetch_chrome_cookie
class CDKCookieUtil(BaseUtil):
def __init__(self, username='', passwd='', adminid='24', factoryid='18', baseurl='... | /CDKUtil.py | import datetime
import json
import os
import re
import random
import sys
from urllib import parse
from urllib.parse import urlparse
import requests
from PIL import Image
from io import BytesIO
from bs4 import BeautifulSoup
# from useragent import agents
class CDKUtil:
def __init__(self, username='', passwd='D... | /ChromeCookie.py | import os
import json
import base64
import win32crypt
from Crypto.Cipher import AES
import sqlite3
'''
[(0, 'creation_utc', 'INTEGER', 1, None, 0), (1, 'host_key', 'TEXT', 1, None, 0), (2, 'name', 'TEXT', 1, None, 0), (3, 'value', '
TEXT', 1, None, 0), (4, 'path', 'TEXT', 1, None, 0), (5, 'expires_utc', 'INTEGER', 1, ... | /ConkaUtil.py | import json
from urllib.parse import urlparse
import requests
class ConkaUtil:
def __init__(self, username, passwd, adminid='15870', factoryid='1', baseurl='https://crm.konka.com',
bjdomain='http://north.bangjia.me'):
parsed_uri = urlparse(baseurl)
self.host = parsed_uri.netloc
... | /GreeUtil.py | import json
from datetime import date, timedelta
from urllib.parse import urlparse, urlencode, unquote
import requests
from Util import Util
class GreeUtil(Util):
def __init__(self, username, passwd, adminid='15870', factoryid='1', baseurl='http://116.6.118.169:7909',
bjdomain='http://fatest.ba... | /JDUtil.py | import json
import os
import re
import sys
import time
import requests
from hyper.tls import init_context
from BaseUtil import BaseUtil
from hyper import HTTPConnection, HTTP20Connection
businessTypes = {"1": "上门安装", "2": "送货服务", "3": "提货送装", "4": "拆卸包装", "5": "退货服务"}
statusTypes = {"1": "新订单", "2": "自动分配失败", "3": "... | /MIUtil.py | import datetime
import json
import re
import time
from urllib import parse
from urllib.parse import urlparse
import requests
# from requests_html import HTMLSession
# from utils.ChromeCookie import fetch_chrome_cookie
from BaseUtil import BaseUtil
from cookie_test import fetch_chrome_cookie
class MIUtil(BaseUtil):
... | /MideaCookieUtil.py | import json
import time
from datetime import date, timedelta
import requests
from BaseUtil import BaseUtil
from cookie_test import fetch_chrome_cookie
class MideaUtil(BaseUtil):
def __init__(self, username, passwd, adminid='24', factoryid='4', baseurl='https://cs.midea.com/c-css/',
bjdomain='h... | /MideaUtil.py | import json
import time
from datetime import date, timedelta
import requests
from BaseUtil import BaseUtil
class MideaUtil(BaseUtil):
def __init__(self, username, passwd, adminid='24', factoryid='4', baseurl='https://cs.midea.com/c-css/',
bjdomain='http://yxgtest.bangjia.me'):
super(Mi... | /SuningUtil.py | import json
import re
import time
from datetime import date, timedelta
from urllib import parse
from urllib.parse import urlencode, urlparse
import requests
from BaseUtil import BaseUtil
from cookie_test import fetch_chrome_cookie
class SuningUtil(BaseUtil):
def __init__(self, username, passwd, adminid='24', f... | /TCSMCookieUtil.py | import io
import json
import re
import sys
import unicodedata
from datetime import date, timedelta
from urllib import parse
import chardet
import requests
from idna import unicode
from BaseUtil import BaseUtil
from cookie_test import fetch_chrome_cookie
class TCSMUtil(BaseUtil):
def __init__(self, username, pa... | /Util.py | import json
import requests
from bs4 import BeautifulSoup
class Util(object):
@staticmethod
def get_value(element):
return element["value"]
@staticmethod
def get_selected(element):
results = element.select('option[selected="selected"]')
if results and len(results) > 0:
... | /aesgcm.py | import os
import sys
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import (
Cipher, algorithms, modes
)
NONCE_BYTE_SIZE = 12
def encrypt(cipher, plaintext, nonce):
cipher.mode = modes.GCM(nonce)
encryptor = cipher.encryptor()
ciphertext = encryp... | /asdfsd.py | # 载入必要的模块
import wx
import os
import pygame
from pygame.locals import *
import itertools
import random
# 创建类
class Example(wx.Frame):
def __init__(self, parent, title):
# 继承父类wx.Frame的初始化方法,并设置窗口大小为320*220
super(Example, self).__init__(parent, title=title, size=(320, 220))
self.InitUI()
... | /chrome_cookies_old.py | import os
import sqlite3
from collections import defaultdict
# from win32.win32crypt import CryptUnprotectData
'''
实际使用场景请自行修改Cookies/cookies.sqlite位置,下面代码均为默认安装的位置,有些绿色版的文件夹位置以及老版本的渗透版火狐浏览器位置需要自行修改
'''
# # 获取chrome浏览器的cookies
# def getcookiefromchrome():
# cookiepath = os.environ['LOCALAPPDATA'] + r"\Google\Chr... | /cookie_test.py | import os
import sys
import sqlite3
import http.cookiejar as cookiejar
import json, base64
import requests
import aesgcm
sql = """
SELECT
host_key, name, path,encrypted_value as value
FROM
cookies
"""
def dpapi_decrypt(encrypted):
import ctypes
import ctypes.wintypes
class DATA_BLOB(ctypes.Str... | /huadi_zb.py | # -*- coding: utf-8 -*-
import requests
import json
from bs4 import BeautifulSoup
import re
from datetime import date, timedelta, datetime
from Util import Util
class HDScrap(Util):
def __init__(self, username='01007544', pwd='160324', baseurl="http://cc.vatti.com.cn:8180", adminid='3',
bjdomain=... | /login.py | import datetime
import json
import os
import sys
import time
import wx
import wx.adv
import wx.lib.mixins.inspection
from apscheduler.triggers import interval
from CDKUtil import CDKUtil
from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler()
AppTitle = "CDK抓单"
VERSION = ... | /master.py | import os
import sys
import time
from datetime import datetime
from datetime import timedelta
import wx
import wx.adv
import wx.lib.mixins.inspection
import wx.lib.mixins.listctrl as listmix
import searchutil
AppTitle = "报表管理"
VERSION = 0.1
class MyListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
def __in... | /searchutil.py | import json
import requests
base_url = "http://114.55.168.6/"
search_api = base_url + "es-test/essearch.php"
oper_api = base_url + "es-test/oper-search.php"
# 操作类别:1:建单 2:派单 3:审核 4:结算 5:回访
def getAdminids():
params = dict()
params['method'] = 'search'
params['index'] = 'yxgoper'
params['from'] = 0
... | /test/http2.py | import asyncio
import json
import os
import sys
import httpx
from hyper import HTTPConnection, HTTP20Connection
# conn = HTTPConnection('http2bin.org:443')
# conn.request('GET', '/get')
# resp = conn.get_response()
#
# print(resp.read())
from hyper.tls import init_context
from BaseUtil import BaseUtil
agent = "Mozi... | /test/test_re.py | import re
string = "originOrgId: 'WDCN02431',"
print(re.findall(re.compile(r"originOrgId: ['](.*?)[']", re.S), string)[0])
| /test_text.py | #!/usr/bin/env python
import time
import wx
import wx.adv
#----------------------------------------------------------------------
class TestPanel(wx.Panel):
def __init__(self, parent, log):
self.log = log
wx.Panel.__init__(self, parent, -1)
textSizer = wx.BoxSizer(wx.VERTICAL)
# s... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
joshharper64/frost | refs/heads/master | {"/resident_reports/admin.py": ["/resident_reports/models.py"], "/resident_reports/views.py": ["/resident_reports/models.py"]} | └──
├── homepage
│ └── views.py
└── resident_reports
├── admin.py
├── apps.py
├── migrations
│ └── 0003_auto_20170517_0033.py
├── models.py
├── urls.py
└── views.py | /homepage/views.py | from django.shortcuts import render
def index(request):
"""Homepage"""
return render(request, 'homepage/index.html')
def about(request):
"""About Section"""
return render(request, 'homepage/about.html')
| /resident_reports/admin.py | from django.contrib import admin
from resident_reports.models import Report
admin.site.register(Report)
| /resident_reports/apps.py | from django.apps import AppConfig
class ResidentReportsConfig(AppConfig):
name = 'resident_reports'
| /resident_reports/migrations/0003_auto_20170517_0033.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-05-17 00:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('resident_reports', '0002_report'),
]
operations = [
migrations.RemoveField(
... | /resident_reports/models.py | from django.db import models
from django.contrib.auth.models import User
class Report(models.Model):
""" Report by User """
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
user_name = models.ForeignKey(User)
class Meta:
verbose_name_plural = 'reports'
def... | /resident_reports/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^allreports/$', views.allreports, name='allreports'),
url(r'^new_report/$', views.new_report, name='new_report'),
url(r'^edit_report/(?P<report_id>\d+)/$', views.edit_report, name='edit_report'),
]
| /resident_reports/views.py | from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from .models import Report
from .forms import ReportForm
def allreports(request):
"... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
nforsch/SSCP19-mechanics-project7 | refs/heads/master | {"/compute_displacement_subset.py": ["/demo.py"], "/compute_surface_nodes.py": ["/demo.py"]} | └──
├── compute_displacement_subset.py
├── compute_surface_nodes.py
├── create_ellipsoid.py
├── demo.py
├── lhs.py
└── pca.py | /compute_displacement_subset.py | import os
import numpy as np
import dolfin as df
import pulse
import ldrb
import matplotlib.pyplot as plt
from scipy import spatial
from demo import load_geometry
pi = np.pi
def cart2prolate( focalLength, XYZ ):
# Convert Cartesian XYZ to Prolate TML
# TML[0] = theta, TML[1] = mu, TML[2] = lambda
X = XYZ... | /compute_surface_nodes.py | import dolfin as df
from demo import load_geometry
geometry = load_geometry()
endo_coordinates = []
endo_marker = geometry.markers['ENDO'][0]
# Loop over the facets
for facet in df.facets(geometry.mesh):
# If the facet markers matched that of ENDO
if geometry.ffun[facet] == endo_marker:
# Loop over ... | /create_ellipsoid.py | import os
import numpy as np
import dolfin as df
import pulse
import ldrb
def create_geometry(h5name):
"""
Create an lv-ellipsoidal mesh and fiber fields using LDRB algorithm
An ellipsoid is given by the equation
.. math::
\frac{x^2}{a} + \frac{y^2}{b} + \frac{z^2}{c} = 1
We create two... | /demo.py | import os
import numpy as np
import dolfin as df
import pulse
import ldrb
import matplotlib.pyplot as plt
def create_geometry(h5name):
"""
Create an lv-ellipsoidal mesh and fiber fields using LDRB algorithm
An ellipsoid is given by the equation
.. math::
\frac{x^2}{a} + \frac{y^2}{b} + \fra... | /lhs.py | from pyDOE import *
from scipy.stats.distributions import norm
# Latin Hypercube Sampling
# see: https://pythonhosted.org/pyDOE/randomized.html
# Run LHS for n factors
X = lhs(4, samples=100) # lhs(n, [samples, criterion, iterations])
# Transform factors to normal distributions with means and standard deviations
mea... | /pca.py | # PCA demo
# Uses PCA from sklearn.decomposition: http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html
get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
import numpy as np
import seaborn as sns; sns.set()
# Data
X_tr... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
aaronn/django-rest-framework-passwordless | refs/heads/master | {"/drfpasswordless/admin.py": ["/drfpasswordless/models.py"], "/drfpasswordless/serializers.py": ["/drfpasswordless/models.py", "/drfpasswordless/utils.py"], "/drfpasswordless/signals.py": ["/drfpasswordless/models.py", "/drfpasswordless/services.py"], "/drfpasswordless/utils.py": ["/drfpasswordless/models.py"], "/drfp... | └──
├── drfpasswordless
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ ├── 0003_callbacktoken_type.py
│ │ └── 0004_auto_20200125_0853.py
│ ├── models.py
│ ├── serializers.py
│ ├── services.py
│ ├── settings.py
│ ├── signals.... | /drfpasswordless/__init__.py | # -*- coding: utf-8 -*-
__title__ = 'drfpasswordless'
__version__ = '1.5.8'
__author__ = 'Aaron Ng'
__license__ = 'MIT'
__copyright__ = 'Copyright 2022 Aaron Ng'
# Version synonym
VERSION = __version__
default_app_config = 'drfpasswordless.apps.DrfpasswordlessConfig'
| /drfpasswordless/admin.py | from django.contrib import admin
from django.urls import reverse
from drfpasswordless.models import CallbackToken
class UserLinkMixin(object):
"""
A mixin to add a linkable list_display user field.
"""
LINK_TO_USER_FIELD = 'link_to_user'
def link_to_user(self, obj):
link = reverse('admin:... | /drfpasswordless/apps.py | from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class DrfpasswordlessConfig(AppConfig):
name = 'drfpasswordless'
verbose = _("DRF Passwordless")
def ready(self):
import drfpasswordless.signals
| /drfpasswordless/migrations/0003_callbacktoken_type.py | # Generated by Django 3.0.2 on 2020-01-22 08:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('drfpasswordless', '0002_auto_20200122_0424'),
]
operations = [
migrations.AddField(
model_name='callbacktoken',
name... | /drfpasswordless/migrations/0004_auto_20200125_0853.py | # Generated by Django 3.0.2 on 2020-01-25 08:53
from django.db import migrations, models
import drfpasswordless.models
class Migration(migrations.Migration):
dependencies = [
('drfpasswordless', '0003_callbacktoken_type'),
]
operations = [
migrations.AlterField(
model_name='... | /drfpasswordless/models.py | import uuid
from django.db import models
from django.conf import settings
import string
from django.utils.crypto import get_random_string
def generate_hex_token():
return uuid.uuid1().hex
def generate_numeric_token():
"""
Generate a random 6 digit string of numbers.
We use this formatting to allow le... | /drfpasswordless/serializers.py | import logging
from django.utils.translation import gettext_lazy as _
from django.contrib.auth import get_user_model
from django.core.exceptions import PermissionDenied
from django.core.validators import RegexValidator
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from drf... | /drfpasswordless/services.py | from django.utils.module_loading import import_string
from drfpasswordless.settings import api_settings
from drfpasswordless.utils import (
create_callback_token_for_user,
)
class TokenService(object):
@staticmethod
def send_token(user, alias_type, token_type, **message_payload):
token = create_ca... | /drfpasswordless/settings.py | from django.conf import settings
from rest_framework.settings import APISettings
USER_SETTINGS = getattr(settings, 'PASSWORDLESS_AUTH', None)
DEFAULTS = {
# Allowed auth types, can be EMAIL, MOBILE, or both.
'PASSWORDLESS_AUTH_TYPES': ['EMAIL'],
# URL Prefix for Authentication Endpoints
'PASSWORDLES... | /drfpasswordless/signals.py | import logging
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.dispatch import receiver
from django.db.models import signals
from drfpasswordless.models import CallbackToken
from drfpasswordless.models import generate_numeric_token
from drfpasswordless.setti... | /drfpasswordless/urls.py | from drfpasswordless.settings import api_settings
from django.urls import path
from drfpasswordless.views import (
ObtainEmailCallbackToken,
ObtainMobileCallbackToken,
ObtainAuthTokenFromCallbackToken,
VerifyAliasFromCallbackToken,
ObtainEmailVerificationCallbackToken,
ObtainMobileVerifica... | /drfpasswordless/utils.py | import logging
import os
from django.contrib.auth import get_user_model
from django.core.exceptions import PermissionDenied
from django.core.mail import send_mail
from django.template import loader
from django.utils import timezone
from rest_framework.authtoken.models import Token
from drfpasswordless.models import Cal... | /drfpasswordless/views.py | import logging
from django.utils.module_loading import import_string
from rest_framework import parsers, renderers, status
from rest_framework.response import Response
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.views import APIView
from drfpasswordless.models import CallbackTo... | /tests/models.py | from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager
from django.core.validators import RegexValidator
from django.db import models
phone_regex = RegexValidator(regex=r'^\+[1-9]\d{1,14}$',
message="Mobile number must be entered in t... | /tests/test_authentication.py | from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from drfpasswordless.settings import api_settings, DEFAULTS
from drfpasswordless.utils import CallbackToken
Use... | /tests/test_verification.py | from rest_framework import status
from rest_framework.authtoken.models import Token
from django.utils.translation import gettext_lazy as _
from rest_framework.test import APITestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from drfpasswordless.settings import api_settings, DEFAULT... | /tests/urls.py | from django.urls import path, include
from rest_framework.urlpatterns import format_suffix_patterns
from drfpasswordless.settings import api_settings
from drfpasswordless.views import (ObtainEmailCallbackToken,
ObtainMobileCallbackToken,
ObtainAuthTo... | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.