repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
liualexiang/liualexiang.github.io | generate_front_matter.py | import os,re
def get_docs_list():
docs_list=[]
for path, subdirs, files in os.walk("."):
for name in files:
if len(name.split(".")) == 2 and name.split(".")[1] == "md":
docs_list.append(os.path.join(path, name))
return docs_list
def get_doc_title(file):
with open(fi... |
crangelsmith/synthetic-data-tutorial | tutorial/synthesise.py | '''
This generates synthetic data from the hospital_ae_data_deidentify.csv
file. It generates three types of synthetic data and saves them in
different files.
'''
import random
import os
import time
import pandas as pd
import numpy as np
import filepaths
from DataDescriber import DataDescriber
from DataGenerator ... |
crangelsmith/synthetic-data-tutorial | DataSynthesizer/datatypes/utils/AttributeLoader.py | from pandas import Series
from datatypes.DateTimeAttribute import DateTimeAttribute
from datatypes.FloatAttribute import FloatAttribute
from datatypes.IntegerAttribute import IntegerAttribute
from datatypes.SocialSecurityNumberAttribute import SocialSecurityNumberAttribute
from datatypes.StringAttribute import StringA... |
crangelsmith/synthetic-data-tutorial | DataSynthesizer/datatypes/IntegerAttribute.py | <gh_stars>10-100
from typing import Union
from pandas import Series
from datatypes.AbstractAttribute import AbstractAttribute
from datatypes.utils.DataType import DataType
class IntegerAttribute(AbstractAttribute):
def __init__(self, name: str, is_candidate_key, is_categorical, histogram_size: Union[int, str], ... |
crangelsmith/synthetic-data-tutorial | tutorial/generate.py | """
Script that generates hospital A&E data to use in the synthetic data tutorial.
Columns of data inpired by NHS+ODI Leeds blog post:
https://odileeds.org/blog/2019-01-24-exploring-methods-for-creating-synthetic-a-e-data
"""
import os
import random
from datetime import datetime, timedelta
import uuid
import random,... |
crangelsmith/synthetic-data-tutorial | DataSynthesizer/ModelInspector.py | from typing import List
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from lib.utils import pairwise_attributes_mutual_information, normalize_given_distribution
matplotlib.rc('xtick', labelsize=20)
matplotlib.rc('ytick', labelsize=20)
sns.set()
clas... |
crangelsmith/synthetic-data-tutorial | DataSynthesizer/DataGenerator.py | import numpy as np
import pandas as pd
from datatypes.utils.AttributeLoader import parse_json
from lib.utils import set_random_seed, read_json_file, generate_random_string
class DataGenerator(object):
def __init__(self):
self.n = 0
self.synthetic_dataset = None
self.description = {}
... |
crangelsmith/synthetic-data-tutorial | tutorial/filepaths.py | <reponame>crangelsmith/synthetic-data-tutorial
import os
import sys
from pathlib import Path
this_filepath = Path(os.path.realpath(__file__))
project_root = str(this_filepath.parents[1])
data_dir = os.path.join(project_root, 'data/')
# add the DataSynthesizer repo to the pythonpath
data_synthesizer_dir = os.path.joi... |
chickenjohn/bit-rnn | bit_utils.py | import functools
import tensorflow as tf
from tensorflow.python.ops import variable_scope
_origin_get_variable = tf.get_variable
_object_stack = []
def _new_get_variable(*args, **kwargs):
v = _origin_get_variable(*args, **kwargs)
if len(_object_stack) != 0:
return _object_stack[-1]._fn(v)
else:... |
chickenjohn/bit-rnn | config/gru.py | <filename>config/gru.py<gh_stars>10-100
class Config(object):
learning_rate = 1e-3
max_grad_norm = 10
num_layers = 1
num_steps = 20
hidden_size = 300
max_epoch = 100
keep_prob = 0.5
batch_size = 20
vocab_size = 10000
nr_epoch_first_stage = 40
nr_epoch_second_stage = 80
w_... |
chickenjohn/bit-rnn | train.py | import time
import functools
import importlib
import numpy as np
import tensorflow as tf
import reader
import bit_utils
from bit_rnn_cell import BitGRUCell
from model import PTBModel
flags = tf.flags
logging = tf.logging
flags.DEFINE_string('data_path', None, 'data_path')
flags.DEFINE_string('config', None, 'confi... |
chickenjohn/bit-rnn | model.py | <gh_stars>10-100
import time
import functools
import numpy as np
import tensorflow as tf
import reader
import bit_utils
from bit_rnn_cell import BitGRUCell, BitLSTMCell
class PTBModel(object):
"""The PTB model."""
def __init__(self, is_training, config):
self.batch_size = batch_size = config.batch... |
openvinotoolkit/mmaction2 | mmaction/datasets/samplers/balanced_distributed_sampler.py | <filename>mmaction/datasets/samplers/balanced_distributed_sampler.py
import copy
import math
import torch
from torch.utils.data import DistributedSampler as _DistributedSampler
class BalancedDistributedSampler(_DistributedSampler):
def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True, num_insta... |
openvinotoolkit/mmaction2 | mmaction/core/ops/conv.py | import torch.nn as nn
from .conv3d import Conv3d
def conv_kxkxk_bn(in_planes, out_planes, spatial_k=3, temporal_k=3,
spatial_stride=1, temporal_stride=1, groups=1,
as_list=True, norm='none', center_weight=None):
layers = [Conv3d(in_planes, out_planes, bias=False, groups=groups... |
openvinotoolkit/mmaction2 | mmaction/integration/nncf/utils.py | <filename>mmaction/integration/nncf/utils.py
import torch
from collections import OrderedDict
from contextlib import contextmanager
try:
import nncf
_is_nncf_enabled = True
except ImportError:
_is_nncf_enabled = False
except RuntimeError as _e:
_is_nncf_enabled = False
print('Attention: RuntimeErro... |
openvinotoolkit/mmaction2 | mmaction/datasets/video_dataset.py | import os.path as osp
from .recognition_dataset import RecognitionDataset
from .registry import DATASETS
@DATASETS.register_module()
class VideoDataset(RecognitionDataset):
"""Video dataset for action recognition.
The dataset loads raw videos and apply specified transforms to return a
dict containing th... |
openvinotoolkit/mmaction2 | mmaction/models/necks/__init__.py | <reponame>openvinotoolkit/mmaction2
from .video_aligner import VideoAligner
from .self_feature_regularizer import SelfFeatureRegularizer
from .emd_regularizer import EMDRegularizer
__all__ = [
'VideoAligner',
'SelfFeatureRegularizer',
'EMDRegularizer',
]
|
openvinotoolkit/mmaction2 | mmaction/core/ops/__init__.py | from .conv2d import Conv2d
from .conv3d import Conv3d
from .conv import conv_kxkxk_bn, conv_1xkxk_bn, conv_kx1x1_bn, conv_1x1x1_bn
from .linear import AngleMultipleLinear, SymmetricalLayer
from .kernelzed import KernelizedClassifier, kernel_prod
from .nonlinearities import HSigmoid, HSwish
from .dropout import Dropout,... |
openvinotoolkit/mmaction2 | mmaction/core/ops/linear.py | import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
from .math import normalize
class AngleMultipleLinear(nn.Module):
"""Based on SoftTriplet loss: https://arxiv.org/pdf/1909.05235.pdf
"""
def __init__(self, in_features, num_c... |
openvinotoolkit/mmaction2 | mmaction/datasets/rawframe_dataset.py | import os.path as osp
from .recognition_dataset import RecognitionDataset
from .registry import DATASETS
@DATASETS.register_module()
class RawframeDataset(RecognitionDataset):
"""RawframeDataset dataset for action recognition.
The dataset loads raw frames and apply specified transforms to return a
dict ... |
openvinotoolkit/mmaction2 | mmaction/models/heads/cls_head.py | <reponame>openvinotoolkit/mmaction2
import itertools
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import constant_init, kaiming_init
from .base import BaseHead
from ..registry import HEADS
from ...core.ops import (conv_1x1x1_bn, normalize, AngleMultipleLinear, K... |
openvinotoolkit/mmaction2 | mmaction/models/spatial_temporal_modules/__init__.py | from .aggregator_spatial_temporal_module import AggregatorSpatialTemporalModule
from .average_spatial_temporal_module import AverageSpatialTemporalModule
from .trg_spatial_temporal_module import TRGSpatialTemporalModule
from .non_local import NonLocalModule
from .bert import BERTSpatialTemporalModule
__all__ = [
'... |
openvinotoolkit/mmaction2 | mmaction/core/data/sample_info_aggregator.py | import torch
import torch.distributed as dist
from mmcv.runner.hooks import HOOKS, Hook
@HOOKS.register_module()
class SampleInfoAggregatorHook(Hook):
def __init__(self, warmup_epochs=0):
self.warmup_epochs = int(warmup_epochs)
assert self.warmup_epochs >= 0
def after_train_iter(self, runner... |
openvinotoolkit/mmaction2 | tools/export.py | <filename>tools/export.py<gh_stars>1-10
import sys
import argparse
import json
from os import makedirs
from os.path import exists, dirname, basename, splitext, join
from subprocess import run, CalledProcessError, DEVNULL
import torch
import onnx
import mmcv
from mmcv.runner import set_random_seed
from mmaction.apis i... |
openvinotoolkit/mmaction2 | mmaction/models/losses/metric_learning_base.py | <reponame>openvinotoolkit/mmaction2<filename>mmaction/models/losses/metric_learning_base.py
from abc import abstractmethod
import numpy as np
import torch
import torch.nn.functional as F
from .base import BaseWeightedLoss
from .. import builder
from ...core.ops import entropy
class BaseMetricLearningLoss(BaseWeight... |
openvinotoolkit/mmaction2 | mmaction/datasets/builder.py | import platform
import random
from functools import partial
from copy import deepcopy
import numpy as np
from mmcv.parallel import collate
from mmcv.runner import get_dist_info
from mmcv.utils import build_from_cfg
from torch.utils.data import DataLoader
from .dataset_wrappers import RepeatDataset
from .registry impo... |
openvinotoolkit/mmaction2 | mmaction/models/backbones/mobilenetv3_lgd.py | <gh_stars>1-10
import torch
import torch.nn as nn
from ...core.ops import HSwish, conv_1x1x1_bn, Dropout
from ..registry import BACKBONES
from .mobilenetv3_s3d import MobileNetV3_S3D
class ContextPool3d(nn.Module):
def __init__(self, in_channels):
super(ContextPool3d, self).__init__()
self.encod... |
openvinotoolkit/mmaction2 | tools/data/custom/prepare_annot.py | <filename>tools/data/custom/prepare_annot.py<gh_stars>1-10
import json
from os import makedirs
from os.path import exists, join
from argparse import ArgumentParser
from collections import defaultdict
from random import shuffle
CLASS_MAP = {
'digit_0': 0,
'digit_1': 1,
'digit_1_hand_to_the_camera': 1,
... |
openvinotoolkit/mmaction2 | tools/collect_data_stat.py | # Copyright (C) 2021 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
openvinotoolkit/mmaction2 | mmaction/models/spatial_temporal_modules/bert.py | """
Original repo: https://github.com/artest08/LateTemporalModeling3DCNN
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..registry import SPATIAL_TEMPORAL_MODULES
from ...core.ops import conv_1x1x1_bn
class LayerNorm(nn.Module):
def __init__(self, features, eps=1e-6):
... |
openvinotoolkit/mmaction2 | tools/data/dump_frames.py | import subprocess
from os import makedirs, listdir, walk, popen
from os.path import exists, join, isfile, abspath
from shutil import rmtree
from argparse import ArgumentParser
from tqdm import tqdm
VIDEO_EXTENSIONS = 'avi', 'mp4', 'mov', 'webm', 'mkv'
def create_dirs(dir_path, override=False):
if override:
... |
openvinotoolkit/mmaction2 | tools/rename_layers.py | from os.path import exists
from argparse import ArgumentParser
import torch
def main():
parser = ArgumentParser()
parser.add_argument('--input', '-i', type=str, required=True)
parser.add_argument('--output', '-o', type=str, required=True)
args = parser.parse_args()
assert exists(args.input)
... |
openvinotoolkit/mmaction2 | mmaction/models/necks/self_feature_regularizer.py | <filename>mmaction/models/necks/self_feature_regularizer.py
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import constant_init, kaiming_init
from ..registry import NECKS
from ...core.ops import conv_1x1x1_bn, HSwish
class ChannelReducer(nn.Module):
def __init__(self, dim=1, ke... |
openvinotoolkit/mmaction2 | mmaction/integration/nncf/compression_hooks.py | <filename>mmaction/integration/nncf/compression_hooks.py
from mmcv.runner.hooks.hook import HOOKS, Hook
from mmcv.runner.dist_utils import master_only
@HOOKS.register_module()
class CompressionHook(Hook):
def __init__(self, compression_ctrl=None):
self.compression_ctrl = compression_ctrl
def after_tra... |
openvinotoolkit/mmaction2 | mmaction/integration/nncf/compression.py | <reponame>openvinotoolkit/mmaction2
import os
import pathlib
import tempfile
from functools import partial
import mmcv
import torch
from mmaction.utils import get_root_logger
from .utils import (check_nncf_is_enabled, get_nncf_version, is_nncf_enabled,
load_checkpoint, no_nncf_trace)
def get_nnc... |
openvinotoolkit/mmaction2 | tools/data/copy_data.py | <reponame>openvinotoolkit/mmaction2
from os import makedirs
from os.path import exists, join, isfile
from shutil import copyfile, copytree
from argparse import ArgumentParser
from tqdm import tqdm
def load_sources(file_path, root_dir):
sources = []
with open(file_path) as input_stream:
for line in in... |
openvinotoolkit/mmaction2 | mmaction/models/params/freeze_layers_hook.py | <reponame>openvinotoolkit/mmaction2<filename>mmaction/models/params/freeze_layers_hook.py<gh_stars>1-10
from mmcv.runner.hooks import Hook
import torch
from ..registry import PARAMS_MANAGERS
@PARAMS_MANAGERS.register_module()
class FreezeLayers(Hook):
def __init__(self, epochs=0, open_layers=None, **kwargs):
... |
openvinotoolkit/mmaction2 | mmaction/models/necks/video_aligner.py | <filename>mmaction/models/necks/video_aligner.py<gh_stars>1-10
import torch
import torch.nn as nn
from mmcv.cnn import constant_init, kaiming_init
from ..registry import NECKS
from ...core.ops import conv_1x1x1_bn, HSwish, Normalize, soft_dtw
@NECKS.register_module()
class VideoAligner(nn.Module):
"""
Imple... |
openvinotoolkit/mmaction2 | tools/data/dump_skeletons.py | import json
import math
import argparse
from os import makedirs, listdir
from os.path import exists, join, isfile, isdir
from collections import OrderedDict, defaultdict
from operator import itemgetter
import cv2
import numpy as np
import torch
import torch.nn as nn
from tqdm import tqdm
TRG_KPT_IDS = [4, 7]
NET_STR... |
openvinotoolkit/mmaction2 | mmaction/models/losses/local_push_loss.py | <reponame>openvinotoolkit/mmaction2<filename>mmaction/models/losses/local_push_loss.py
import torch
from ..registry import LOSSES
from .base import BaseWeightedLoss
@LOSSES.register_module()
class LocalPushLoss(BaseWeightedLoss):
def __init__(self, margin=0.1, smart_margin=True, **kwargs):
super(LocalPus... |
openvinotoolkit/mmaction2 | mmaction/core/ops/soft_dtw.py | """
The original repo: https://github.com/Maghoumi/pytorch-softdtw-cuda
"""
import numpy as np
import torch
def compute_softdtw(D, gamma, bandwidth):
B = D.shape[0]
N = D.shape[1]
M = D.shape[2]
scale = -1.0 / gamma
R = np.ones((B, N + 2, M + 2)) * np.inf
R[:, 0, 0] = 0
for b in range(... |
openvinotoolkit/mmaction2 | mmaction/apis/fake_input.py | <filename>mmaction/apis/fake_input.py
# Copyright (C) 2021 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... |
openvinotoolkit/mmaction2 | mmaction/models/necks/emd_regularizer.py | <reponame>openvinotoolkit/mmaction2
import cv2
import torch
import torch.nn as nn
from mmcv.cnn import constant_init, kaiming_init
from ..registry import NECKS
from ...core.ops import conv_1x1x1_bn, normalize
@NECKS.register_module()
class EMDRegularizer(nn.Module):
""" Based on the paper: https://arxiv.org/abs... |
openvinotoolkit/mmaction2 | mmaction/datasets/recognition_dataset.py | from abc import ABCMeta, abstractmethod
from collections import defaultdict
from os.path import exists, join
import torch
from mmcv.utils import print_log
from ..core import (mean_class_accuracy, top_k_accuracy, mean_top_k_accuracy,
mean_average_precision, ranking_mean_average_precision,
... |
openvinotoolkit/mmaction2 | mmaction/core/ops/labels.py | <gh_stars>1-10
import torch
import torch.nn as nn
from .math import normalize
class PRISM(nn.Module):
"""Filters labels according to the distance to set of class centers.
The original paper: https://arxiv.org/abs/2103.16047
"""
def __init__(self, num_classes, feature_length, buffer_size=1, min_num_... |
openvinotoolkit/mmaction2 | mmaction/integration/nncf/__init__.py | <reponame>openvinotoolkit/mmaction2
from .compression import (check_nncf_is_enabled, get_nncf_config_from_meta,
get_nncf_metadata, get_uncompressed_model,
is_checkpoint_nncf, wrap_nncf_model)
from .compression_hooks import CompressionHook
from .utils import get_nncf_v... |
openvinotoolkit/mmaction2 | tools/test.py | <gh_stars>1-10
import argparse
import os
import shutil
import mmcv
import torch
from mmcv.cnn import fuse_conv_bn
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import get_dist_info, init_dist, set_random_seed
from mmcv.runner.fp16_utils import wrap_fp16_model
from mmaction.apis ... |
openvinotoolkit/mmaction2 | mmaction/datasets/samplers/__init__.py | <filename>mmaction/datasets/samplers/__init__.py
from .distributed_sampler import DistributedSampler
from .balanced_distributed_sampler import BalancedDistributedSampler
__all__ = [
'DistributedSampler',
'BalancedDistributedSampler',
]
|
openvinotoolkit/mmaction2 | mmaction/models/losses/clip_mixing_loss.py | import torch
from ..registry import LOSSES
from .base import BaseWeightedLoss
@LOSSES.register_module()
class ClipMixingLoss(BaseWeightedLoss):
MODES = 'embd', 'logits'
def __init__(self, mode='', default_scale=10.0, num_clips=2, reweight_targets=False, **kwargs):
super(ClipMixingLoss, self).__init_... |
openvinotoolkit/mmaction2 | tools/data/custom/prepare_data.py | import json
from os import walk, makedirs
from os.path import exists, join, basename
from shutil import copyfile
from collections import defaultdict
from argparse import ArgumentParser
from lxml import etree
from tqdm import tqdm
NUM_CLASSES = 12
VIDEO_FILE_EXTENSIONS = 'webm'
XML_FRAGMENT_TEMPLATE = '<annotations>\... |
brockar1999/E02a-Control-Structures | main10.py | #!/usr/bin/env python3
import sys, random
assert sys.version_info >= (3,7), "This script requires at least Python 3.7"
print('Greetings!') #printing the given string
colors = ['red','orange','yellow','green','blue','violet','purple'] #creating a list of possible colors
play_again = '' #initializing a play_again vari... |
ryanwang520/graphql-core | src/graphql/utilities/value_from_ast_untyped.py | from math import nan
from typing import Any, Callable, Dict, Optional, Union
from ..language import (
ValueNode,
BooleanValueNode,
EnumValueNode,
FloatValueNode,
IntValueNode,
ListValueNode,
NullValueNode,
ObjectValueNode,
StringValueNode,
VariableNode,
)
from ..pyutils import ... |
dbrgn/superblock | superblock.py | #!/usr/bin/env python2
"""
Analyze superblock in ext2/ext3 filesystem.
Author: <NAME> <<EMAIL>>
License: MIT License
"""
import sys
import string
from binascii import hexlify
from datetime import datetime
BLOCKSIZE = 512
def dump(filename):
def nonprintable_replace(char):
if char not in string.printab... |
dbrgn/superblock | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(name='superblock',
version='0.2.1',
description='A script written in Python 2 to analyze the superblock of an ' + \
'ext2/ext3 formatted file.',
author='<NAME>',
author_email='<EMA... |
sisyphe-re/traces | python_src/nodes.py | # Copyright 2021 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
sisyphe-re/traces | python_src/main.py | <filename>python_src/main.py<gh_stars>0
#!/usr/bin/python3
#
# Copyright 2021 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2... |
datahappy1/czech_language_sentiment_analyzer | utils/utilities.py | """
utilities module
"""
import os
import re
import functools
from itertools import groupby, product
from data_preparation import czech_stemmer
CZECH_STOPWORDS_FILE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..',
'data_preparation', 'czech_... |
datahappy1/czech_language_sentiment_analyzer | ml_models/logistic_regression/data_processor_logistic_regression.py | """
data processor for logistic regression
"""
import random
import pickle
import os
from langdetect import detect, lang_detect_exception
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import model_selection, linear_model
from utils.utilities import ProjectCommon
CZECH_STOPWORDS_FILE_PATH = o... |
datahappy1/czech_language_sentiment_analyzer | ml_models/naive_bayes/data_processor_naive_bayes.py | """
data processor for logistic regression
"""
import random
import pickle
import os
from langdetect import detect, lang_detect_exception
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn import metrics, model_selection
from utils.utilities import Pro... |
datahappy1/czech_language_sentiment_analyzer | ml_models/webapp_interface.py | """
ml models interface for Flask web application
"""
import os
import pickle
def _pickle_load(model_type, file_name):
"""
load pickled data model file function
:param model_type:
:param file_name:
:return:
"""
return pickle.load(
open(os.path.abspath(os.path.join(os.path.dirname(_... |
datahappy1/czech_language_sentiment_analyzer | tests/webapp_test.py | """
Flask app Pytest testing suite
"""
from flask_webapp.app import APP
API_PREFIX = APP.config['api_prefix']
def test_main_get():
APP.testing = True
response = APP.test_client().get('/')
assert response.status_code == 200
assert b'<title>Czech sentiment analyzer Datahappy \xc2\xa92019</title>' in re... |
datahappy1/czech_language_sentiment_analyzer | data_preparation/data_collector_movie_review_scraper.py | <reponame>datahappy1/czech_language_sentiment_analyzer
"""
data collector
"""
from random import randint
from time import sleep
import csv
import re
import concurrent.futures
import datetime
from bs4 import BeautifulSoup
import urllib3
import requests
from utils.utilities import ProjectCommon
OUTPUT_FILE_PATH = 'revie... |
datahappy1/czech_language_sentiment_analyzer | flask_webapp/database/conn_remote_postgres.py | """
remote postgres db connection module
"""
import os
import urllib.parse as urlparse
import psycopg2
class Connect:
"""
connect Postgres class
"""
def __init__(self):
""" create a database connection to the Postgres database
specified by db_url
:return: Connection object... |
datahappy1/czech_language_sentiment_analyzer | flask_webapp/app.py | <gh_stars>1-10
"""
__main__.py
"""
import os
from datetime import date, datetime, timedelta
from flask import Flask, render_template, send_from_directory, request, jsonify, g
from flaskext.markdown import Markdown
from flask_caching import Cache
from waitress import serve
from langdetect import detect
from flask_webapp... |
datahappy1/czech_language_sentiment_analyzer | flask_webapp/database/__init__.py | <filename>flask_webapp/database/__init__.py
"""
init module
"""
import os
if os.environ.get('DATABASE_URL'):
__env__ = 'remote'
else:
__env__ = 'local'
|
datahappy1/czech_language_sentiment_analyzer | flask_webapp/database/conn_local_sqlite.py | <filename>flask_webapp/database/conn_local_sqlite.py
"""
local sqlite db connection module
"""
import os
import sqlite3
class Connect:
"""
connect sqlite3 class
"""
def __init__(self):
""" create a database connection to the SQLite database
specified by db_file
:return: Con... |
datahappy1/czech_language_sentiment_analyzer | flask_webapp/database/database_interface.py | """
database interface module
"""
from flask_webapp.database import conn_local_sqlite, conn_remote_postgres
def _connect_from_environment(environment):
"""
_connect_from_environment mapping function
:param environment:
:return:
"""
try:
_mapping = {
"local": {
... |
datahappy1/czech_language_sentiment_analyzer | flask_webapp/exceptions.py | <filename>flask_webapp/exceptions.py<gh_stars>1-10
"""
exceptions.py
"""
class NotEnoughNonStopWordsException(Exception):
"""
Not Enough Non Stop Words Exception Class
"""
class NotEnoughWordsLengthException(Exception):
"""
Not Enough Words Length Exception Class
"""
class InvalidDetectedL... |
datahappy1/czech_language_sentiment_analyzer | ml_models/support_vector_machine/data_processor_support_vector_machine.py | <gh_stars>1-10
"""
data processor for logistic regression
"""
import random
import pickle
import numpy as np
import os
from langdetect import detect, lang_detect_exception
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn import metrics, model_select... |
shc558/wwyfcs | wwyfcs/utils/create_examples.py | <filename>wwyfcs/utils/create_examples.py<gh_stars>1-10
# -*- coding: utf-8 -*-
import argparse
import os
import pandas as pd
from sklearn.model_selection import train_test_split
# load data and tag lines with source characters' names
def load_data(args):
data = pd.read_csv(args.file_path)
data['id:data'] = data[a... |
shc558/wwyfcs | wwyfcs/app/generate_conversations.py | # -*- coding: utf-8 -*-
import os
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
import streamlit as st
from PIL import Image
tokenizer = AutoTokenizer.from_pretrained('microsoft/DialoGPT-small')
st.title('WWYFCS')
st.header('What would your favorite character say?')
total_steps = st.sideb... |
shc558/wwyfcs | flaskapp/app.py | import numpy as np
import uuid
from flask import Flask, request, make_response
from flask_cors import cross_origin
import json
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from datetime import... |
shc558/wwyfcs | wwyfcs/trainer/train_language_model.py | # -*- coding: utf-8 -*-
"""
Fine-tuning DialoGPT using language modeling based on
Huggingface transformers run_language_modeling.py &
tutorial from <NAME>
"""
import pandas as pd
import logging
import math
import os
import pickle
from dataclasses import dataclass, field
from typing import Optional, Dict, List, Tuple, U... |
tuseef123/Django-CRUD-OPERATIONS | crud/crudapp/urls.py | <reponame>tuseef123/Django-CRUD-OPERATIONS
from django.contrib import admin
from django.urls import path,include
from .import views
urlpatterns = [
path('',views.index,name="index"),
path('record',views.records,name="record"),
path('show/',views.show,name="show"),
path('edit/<int:pk>/',views.update,name... |
tuseef123/Django-CRUD-OPERATIONS | crud/crudapp/migrations/0003_auto_20210112_1816.py | <filename>crud/crudapp/migrations/0003_auto_20210112_1816.py
# Generated by Django 3.1.5 on 2021-01-12 13:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('crudapp', '0002_remove_record_date'),
]
operations = [
migrations.RenameField(
... |
tuseef123/Django-CRUD-OPERATIONS | crud/crudapp/admin.py | <reponame>tuseef123/Django-CRUD-OPERATIONS
from django.contrib import admin
from crudapp.models import record
# Register your models here.
admin.site.register(record) |
tuseef123/Django-CRUD-OPERATIONS | message/messages_show/apps.py | from django.apps import AppConfig
class MessagesShowConfig(AppConfig):
name = 'messages_show'
|
tuseef123/Django-CRUD-OPERATIONS | crud/crudapp/models.py | from django.db import models
# Create your models here.
class record(models.Model):
p_name=models.CharField(max_length=40)
catagory=models.CharField(max_length=40)
quantity=models.IntegerField()
quality=models.CharField(max_length=50)
room=models.IntegerField()
def __str__(self):
return ... |
tuseef123/Django-CRUD-OPERATIONS | crud/crudapp/migrations/0004_auto_20210112_1820.py | <filename>crud/crudapp/migrations/0004_auto_20210112_1820.py
# Generated by Django 3.1.5 on 2021-01-12 13:20
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('crudapp', '0003_auto_20210112_1816'),
]
operations = [
migrations.RenameField(
... |
tuseef123/Django-CRUD-OPERATIONS | message/messages_show/views.py | from django.shortcuts import render,redirect
from django.contrib import messages
from .models import Profile
from .forms import AddData
# Create your views here.
def home(request):
profile = Profile.objects.all()
if request.method =='POST':
form = AddData(request.POST)
if form.is_valid():
... |
tuseef123/Django-CRUD-OPERATIONS | crud/crudapp/forms.py | from crudapp.models import record
from django import forms
class colform(forms.ModelForm):
class Meta:
model = record
fields= '__all__' |
tuseef123/Django-CRUD-OPERATIONS | message/messages_show/models.py | from django.db import models
# Create your models here.
class Profile(models.Model):
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=60)
handle = models.CharField(max_length=50)
def __str__(self):
return self.handle |
tuseef123/Django-CRUD-OPERATIONS | crud/crudapp/views.py | from django.shortcuts import render,redirect
from crudapp.models import record
from .forms import colform
from django.contrib import messages
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request,'index.html')
def records(request):
if request.method=="POST":
... |
tuseef123/Django-CRUD-OPERATIONS | message/messages_show/migrations/0001_initial.py | <gh_stars>0
# Generated by Django 3.1.5 on 2021-01-14 15:29
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', model... |
tuseef123/Django-CRUD-OPERATIONS | message/messages_show/forms.py | from django.forms import ModelForm
from .models import Profile
class AddData(ModelForm):
class Meta:
model = Profile
fields = '__all__' |
tuseef123/Django-CRUD-OPERATIONS | message/messages_show/urls.py | <reponame>tuseef123/Django-CRUD-OPERATIONS<gh_stars>0
from django.urls import path,include
from . import views
urlpatterns=[
path('',views.home,name ='home'),
path('edit/<int:pk>/',views.edit,name='edit'),
path('delete/<int:pk>/',views.delete,name='delete'),
] |
conormuldoon/unison | back-end/src/main/python/switch_model.py | <filename>back-end/src/main/python/switch_model.py
import switch_list_items
if __name__ == "__main__":
matchlist = ["api.timezone", "api.uri", "api.fog"]
switch_list_items.switchitems(matchlist)
|
conormuldoon/unison | back-end/src/main/python/switch_list_items.py | import shutil
CURRENT = "../resources/application.properties"
SWITCHED = "../resources/application.tmppy"
def switchitems(matchlist):
f0 = open(CURRENT, "r")
f1 = open(SWITCHED , "w+")
contents = f0.readlines()
for line in contents:
addline = True
for matchitem in matchlist:
... |
conormuldoon/unison | back-end/src/main/python/switch_db_config.py | <reponame>conormuldoon/unison
import switch_list_items
if __name__ == "__main__":
matchlist = ["driverClassName", "hibernate.dialect",
"datasource.url", "hibernate.ddl"]
switch_list_items.switchitems(matchlist)
|
conormuldoon/unison | back-end/src/main/python/change_db_password.py | import shutil
import sys
CURRENT = "../resources/application.properties"
SWITCHED = "../resources/application.tmppy"
DS_PASSWORD = "<PASSWORD>"
def changepassord(password):
f0 = open(CURRENT, "r")
f1 = open(SWITCHED, "w+")
contents = f0.readlines()
for line in contents:
if line.startswith... |
rootrl/Flask-demo-with-mysql | wsgi.py | from app import create_app
application = app = create_app('default')
|
rootrl/Flask-demo-with-mysql | migrations/versions/e8f7ab64277e_.py | """empty message
Revision ID: e8f7ab64277e
Revises: <KEY>
Create Date: 2019-12-21 16:23:23.140105
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = 'e8f7ab64277e'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
... |
rootrl/Flask-demo-with-mysql | app/models.py | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask import current_app
from . import db
# can't set a default value
class Article(db.Model):
id = db.Column(db.Integer, primary_key=True)
# article_id = db.Column(db.Integer, nullable=False, server_default=0) # can't work
article_id = db.Column... |
rootrl/Flask-demo-with-mysql | migrations/versions/e28f15c8bc0f_.py | <filename>migrations/versions/e28f15c8bc0f_.py
"""empty message
Revision ID: e28f15c8bc0f
Revises: <PASSWORD>
Create Date: 2019-12-21 16:04:54.553769
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<... |
rootrl/Flask-demo-with-mysql | app/__init__.py | <reponame>rootrl/Flask-demo-with-mysql
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import config
db = SQLAlchemy()
def create_app(config_name):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
# 初始化app配置
app.config.from_obj... |
rootrl/Flask-demo-with-mysql | app/frontend/__init__.py | <filename>app/frontend/__init__.py
# from app import app
# from . import article
# app.register_blueprint(article.bp)
|
rootrl/Flask-demo-with-mysql | app/frontend/article.py | import functools
import random
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from app import create_app, db
from app.models import Article
bp = Blueprint('article', __name__, url_prefix='/article')
@bp.route('/show', methods=["GET"])
def show():
serial_id = re... |
rootrl/Flask-demo-with-mysql | config.py | # -*- coding: utf-8 -*-
# @Author: Rootrl
# @Date: 2019-12-21 13:42:41
import os
from time import strftime
import logging
log_name = os.path.join(
os.getenv('HOME'), 'log/flask/log_{}.log'.format(strftime('%Y%m%d')))
FLASK_LOG_FILE = os.getenv('FLASK_LOG_FILE') or log_name
if not os.path.exists(os.path.dirname... |
bAmpT/muzero-pytorch | core/test.py | <filename>core/test.py
import os
import torch
from .mcts import MCTS, Node
from .utils import select_action
import multiprocessing
def _test(config, model, ep_i, device, render, save_video, save_path, ep_data):
with torch.no_grad():
env = config.new_game(save_video=save_video, save_path=save_path,
... |
bAmpT/muzero-pytorch | scripts/aggregate_summaries.py | <gh_stars>100-1000
import os
from tensorboard.backend.event_processing import event_accumulator as ea
from torch.utils.tensorboard import SummaryWriter
def aggregate_summaries(logdir: str, exp_path: str, ):
# we recognize all files which have tfevents
scalars_info = {}
for root, dirs, files in os.walk(log... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.