repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
anandakelvin/instagrump | instagrump/__init__.py | from instagrump.Profile import Profile
from instagrump.Content import Content |
anandakelvin/instagrump | instagrump/Content.py | import requests
class Content:
def __init__(self, url):
api_endp = '__a=1'
if not api_endp in url:
if url[-1] != '/':
url += '/'
if '?' in url:
url += '&%s' % api_endp
else:
url += '?%s' % api_endp
self.data = requests.get(url).json()['graphql']['shortcode_media']
self.type = self.data... |
anurag-ks/check-pep8 | plugin.py | <reponame>anurag-ks/check-pep8
import sublime
import sublime_plugin
import subprocess
import os
class Pep8Command(sublime_plugin.TextCommand):
"""pep8 command"""
def run(self, view):
if self.view.is_dirty():
sublime.message_dialog("Please save the file")
else:
filename ... |
kayru/librush | Scripts/embed_shaders.py | <gh_stars>10-100
import codecs
from collections import namedtuple
import os
import subprocess
import sys
import textwrap
BinText = namedtuple('BinText', 'declaration, definition')
def bin2cpp(filename, variableName):
s = open(filename, 'rb').read()
s = codecs.encode(s, "hex").decode().upper()
t=",".join(["0x"+x+y... |
jakobjassmann/ecodes-dk-lidar | scripts/fill_processing_gaps.py | # fix_processing_gaps.py
# short script to fix missing tiles for each variable
# to be run post completion of processing with process_tiles.py
# <NAME> <EMAIL> 11 May 2021
# NB: uses scandir for speed, on OPALS Shell an install might be required with
# python -m pip install scandir --user
# Dependencies
import os
imp... |
jakobjassmann/ecodes-dk-lidar | scripts/generate_tile_footprints.py | ### DK Nationwide LiDAR - A short R script to generate the tile footprints file.
### <NAME> <EMAIL> 27 October 2021
import os
import subprocess
import re
import ogr
from dklidar import settings
# Status update
print('#' * 80)
print(' EcoDes-DK15 generating tile_footprint variable\n')
print(' 1. Creating output folde... |
jakobjassmann/ecodes-dk-lidar | dklidar/dtm.py | ### Functions for DTM raster file handling for DK Lidar project
### <NAME> <EMAIL> 29 January 2019
import os
import subprocess
import re
import pandas
import opals
import glob
import time
import shutil
from dklidar import settings
from dklidar import common
#### Function definitions
## Generate tile footprint
def d... |
jakobjassmann/ecodes-dk-lidar | scripts/archive_outputs.py | <reponame>jakobjassmann/ecodes-dk-lidar
# Quick helper script to archive all main variable folders
# <NAME> j.assmann
# Zip all folders
import shutil
import glob
import re
import multiprocessing
import os
from dklidar import settings
# Function to archive folders using shutil
def zip_folder(folder_path):
# Set fo... |
jakobjassmann/ecodes-dk-lidar | scripts/check_vrt_completeness.py | # EcoDes-DK15 check validity of outputs based on whether gdal can open the file.
# <NAME> <EMAIL> 2 December 2021
# Dependencies
import scandir
import pandas
import re
import os
import tqdm
import itertools
import multiprocessing
from osgeo import gdal
from dklidar import settings
# Switch on gdal Python exceptions
g... |
jakobjassmann/ecodes-dk-lidar | documentation/source_data/merger_scripts/merge_outputs.py | <reponame>jakobjassmann/ecodes-dk-lidar
## EcoDes-DK output merger
## This script is used to merge the outputs of the various EcoDes processing
## runs to create the merged dataset based on the DHM_201415 merger.
## <NAME> <EMAIL>
# Dependencies
import os
import shutil
import pandas
import glob
import re
import scandi... |
jakobjassmann/ecodes-dk-lidar | scripts/generate_dems.py | import multiprocessing
import pandas
import subprocess
import re
import datetime
import os
import opals
from dklidar import settings
# initate opals
opals.loadAllModules()
# make folder for temp odms
os.mkdir('temp_odms')
os.chdir('temp_odms')
# load missing tiles
missing_dtms = pandas.read_csv(settings.dtm_folder +... |
jakobjassmann/ecodes-dk-lidar | scripts/check_outputs_integrity.py | # EcoDes-DK15 check validity of outputs based on whether gdal can open the file.
# <NAME> <EMAIL> 2 December 2021
# Dependencies
import scandir
import pandas
import re
import tqdm
from osgeo import gdal
import multiprocessing
from dklidar import settings
# Switch on gdal Python exceptions
gdal.UseExceptions()
## 1) ... |
jakobjassmann/ecodes-dk-lidar | scripts/download_files.py | <reponame>jakobjassmann/ecodes-dk-lidar
import multiprocessing
import pandas
import subprocess
import re
import datetime
import os
from dklidar import settings
remote_url_laz = "https://download.kortforsyningen.dk/system/files/Statsaftalen/DANMARK/3_HOJDEDATA/PUNKTSKY/"
remote_url_dtm = "https://download.kortforsyning... |
jakobjassmann/ecodes-dk-lidar | scripts/process_tiles.py | <filename>scripts/process_tiles.py
### Script to rasterise point clouds for the DK nationwide lidar re-processing
### <NAME> <EMAIL> 29 January 2019
## Imports
import glob
import re
import os
import shutil
import datetime
import time
import multiprocessing
import pandas
import opals
from dklidar import points
from dk... |
jakobjassmann/ecodes-dk-lidar | dklidar/settings.py | ### Settings file for the DK Lidar project
### <NAME> <EMAIL> 29 January 2019
# This file is used to provide global variables to all scripts in the DK nationwide lidar project.
# Path to python executable
python_exec_path = 'C:/Program Files/opals_nightly_2.3.2/opals/python.exe'
# Set paths to gdal executables / bin... |
jakobjassmann/ecodes-dk-lidar | scripts/debug.py | # Script for debugging of dklidar module functons
# <NAME> <EMAIL> 18 February 2021
# This script requires the input files (dtms and laz) to be stored
# in the folders specified in dklidar/settings.py
# This also applies to the binaries specified in the same file
## Preparations
print('Preparing environment\n')
# Dep... |
jakobjassmann/ecodes-dk-lidar | scripts/fix_na_tile_data_type.py | <gh_stars>0
# EcoDes-DK - Fix files missing from VRTs
# <NAME> <EMAIL> 2 December 2021
# Most files missing from the VRTs are missing because they are the wrong raster
# file type (e.g. Int16 instead of float32) - the only tiles affected seem to
# be NA tiles.
# These originate from the processing workflow and OPALS ... |
jakobjassmann/ecodes-dk-lidar | documentation/source_data/merger_scripts/check_merged_outputs.py | ## EcoDes-DK output merger
## This script is used to merge the outputs of the various EcoDes processing
## runs to create the merged dataset based on the DHM_201415 merger.
## <NAME> <EMAIL>
# Dependencies
import os
import shutil
import pandas
import glob
import re
import scandir
import hashlib
# Status
print('#' * 8... |
jakobjassmann/ecodes-dk-lidar | scripts/generate_list_of_vrts.py | # Short script to generate a list of all vrt files
import glob
import re
from dklidar import settings
# list vrts
vrts = glob.glob(settings.output_folder + '*/*.vrt')
more_vrts = glob.glob(settings.output_folder + '*/*/*.vrt')
for vrt in more_vrts:
vrts.append(vrt)
# Clean up file paths
vrts = [re.sub(settings.ou... |
jakobjassmann/ecodes-dk-lidar | dklidar/points.py | <reponame>jakobjassmann/ecodes-dk-lidar
### Functions for point cloud handling for the DK Lidar project
### <NAME> <EMAIL> 29 January 2019
## Imports
import re
import os
import opals
import subprocess
import numpy
import glob
import shutil
from osgeo import gdal_array
from datetime import datetime, timedelta
from dk... |
jakobjassmann/ecodes-dk-lidar | dklidar/common.py | ### Common module for the dklidar reporcessing - general functions likely used by all scripts
### <NAME> <EMAIL> 29 January 2019
# Imports
import os
import glob
import pandas
import re
import shutil
import datetime
import subprocess
from dklidar import settings
## Function definitons
## Logging function to initalis... |
jakobjassmann/ecodes-dk-lidar | scripts/remove_missing_tiles.py | # Short script to remove tiles that have missing point cloud or dtm data
# This script can be run after executing checksum_qa.py and directly uses the output files
# generated by the script.
# <NAME> <EMAIL> 16 January 2020
import os
from dklidar import settings
# Prompt user input
confirmation_string = raw_input('Ar... |
jakobjassmann/ecodes-dk-lidar | scripts/checksum_qa.py | <gh_stars>0
# Short script to confirm transferred file integrity using md5 checksums.
# Prerequisite is that checsum were generated using create_checksums.bat
# A comparsions of the sets of laz tiles and dtm tiles is also carried out.
# <NAME> <EMAIL> 16 January 2020
# Imports
import os
import glob
import numpy as np
... |
jakobjassmann/ecodes-dk-lidar | scripts/progress_monitor.py | ### Script to mointor progress of the process_tiles.py script
### Execute in separate terminal in when running process_tile.py
### <NAME> <EMAIL> 20 April 2020
## Imports
import glob
import os
import datetime
import time
from dklidar import settings
# Set working directory
os.chdir(settings.wd)
# Set number of para... |
jakobjassmann/ecodes-dk-lidar | documentation/source_data/merger_scripts/copy_files.py | <reponame>jakobjassmann/ecodes-dk-lidar
## DHM2018+ and DHM2015 merger
## Script to copy the files and create a physical version of the merger
## using the outputs from dhm201415_merger.R
## <NAME> <EMAIL>
## Dependencies
import os
import shutil
import pandas
import glob
import re
## Status
print('\n' + '#' * 80)
pri... |
murfrosoft/pygame-demos | pygame02_Animation.py | <filename>pygame02_Animation.py
import pygame
# initalize pygame modules
pygame.init()
clock = pygame.time.Clock() # create a clock to control update speed
# create a screen on which to draw
width, height = 500, 400
screensize = [width, height] # [width, height] in pixels
screen = pygame.display.set_mode(s... |
murfrosoft/pygame-demos | pygame03_AnimationTranslation.py | <filename>pygame03_AnimationTranslation.py
import pygame
# initalize pygame modules
pygame.init()
clock = pygame.time.Clock() # create a clock to control update speed
# create a screen on which to draw
width, height = 500, 400
screensize = [width, height] # [width, height] in pixels
screen = pygame.display... |
murfrosoft/pygame-demos | pygame04_ScrollingBackground.py | <reponame>murfrosoft/pygame-demos
import pygame
# initalize pygame modules
pygame.init()
clock = pygame.time.Clock() # create a clock to control update speed
# create a screen on which to draw
width, height = 500, 300
screensize = [width, height] # [width, height] in pixels
screen = pygame.display.set_mode... |
murfrosoft/pygame-demos | pygame01_HelloWorld.py | <filename>pygame01_HelloWorld.py
import pygame
# initalize pygame modules
pygame.init()
clock = pygame.time.Clock() # create a clock to control update speed
# create a screen on which to draw
screensize = [300, 200] # [width, height] in pixels
screen = pygame.display.set_mode(screensize)
pygame.display.set... |
weynelucas/drf-nested-views | drf_nested_views/mixins.py | """
Basic building blocks for generic class based views.
Use theese mixins with GenericAPIView from drf_nested_views.
With exception of CreateModelMixin and UpdateModelMixin,
other mixins does not perform or override any action of
his parents (rest_framework.mixins). Use them for track
future changes.
"""
from rest... |
weynelucas/drf-nested-views | drf_nested_views/generics.py | <reponame>weynelucas/drf-nested-views
from rest_framework.serializers import ModelSerializer
from rest_framework import generics
from rest_framework_nested.serializers import NestedHyperlinkedModelSerializer
class GenericAPIView(generics.GenericAPIView):
"""
Base class for all other generic views that are nes... |
dave-s477/SoMeNLP | somenlp/utils/time_marker.py | <gh_stars>0
import datetime
def get_time_marker(format='full'):
"""Get current time as a formatted string.
Args:
format (string): full (with time) vs. short (only date)
Returns:
string: current time
"""
if format=='full':
out_s = datetime.datetime.now().strftime("%d-%m-%Y_... |
dave-s477/SoMeNLP | somenlp/entity_disambiguation/feature_calculator.py | <filename>somenlp/entity_disambiguation/feature_calculator.py
import numpy as np
import pandas as pd
import time
import re
import torch
import json
import nltk
nltk.download('stopwords')
from itertools import combinations
from nltk.corpus import stopwords
from multiprocessing import Pool
from os.path import join, exi... |
dave-s477/SoMeNLP | somenlp/feature_engineering/candidate_rules.py | <reponame>dave-s477/SoMeNLP
first_char_lower = lambda s: s[:1].lower() + s[1:] if s else ''
def pan_top_1(x):
'''use <> software'''
left_context = ['use']
right_context = ['software']
left_lemmas = x.sentence.get_left_tokens(x.start_idx, size=1, style='lemma')
right_lemmas = x.sentence.ge... |
dave-s477/SoMeNLP | somenlp/feature_engineering/word_rules.py | def upper_cased(x):
if x.isalpha() and x.isupper():
return True
else:
return False
def first_char_upper(x):
if x.isalpha() and x[0].isupper():
if all(c.islower() for c in x[1:]):
return True
return False
def mixed_case(x):
if x.isalpha():
if any([c.isupp... |
dave-s477/SoMeNLP | somenlp/utils/gpu_setup.py | <gh_stars>0
import torch
import subprocess, re
# Nvidia-smi GPU memory parsing.
# Tested on nvidia-smi 370.23
def run_command(cmd):
"""Run command, return output as string."""
output = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()[0]
return output.decode("ascii")
def list_availa... |
dave-s477/SoMeNLP | somenlp/NER/models/combined_lstm.py | <gh_stars>0
import torch
import torch.nn as nn
from .crf import CRF
class CombinedLSTM(nn.Module):
def __init__(self, device, char_size, word_size, tag2idx, emb_vecs, char_config, emb_config, drop_config, gen_config, **kwargs):
super(CombinedLSTM, self).__init__()
self.device = device
sel... |
dave-s477/SoMeNLP | somenlp/distant_supervision/perform_wiki_data_queries.py | import re
import json
import requests
import xml.etree.ElementTree as ET
from bs4 import BeautifulSoup
from urllib.parse import quote_plus
WIKIDATA_ID = re.compile(r'Q\d{5,}')
def parse_query(plain_query, lang, default_address='https://query.wikidata.org/bigdata/namespace/wdq/sparql?query='):
"""Encode Wikidata... |
dave-s477/SoMeNLP | somenlp/NER/data_handler.py | import re
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import json
import math
import random
import copy
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
from pathlib import Path
from gensim.models import Keye... |
dave-s477/SoMeNLP | setup.py | <reponame>dave-s477/SoMeNLP
import sys
if sys.version_info <= (3,7):
sys.exit('Python >= 3.7 is required')
from setuptools import setup
def readme():
with open('Readme.md') as f:
return f.read()
setup(name='SoMeNLP',
version='0.1',
description='NLP procedures for scientific articles and s... |
dave-s477/SoMeNLP | somenlp/RE/RE_model.py | <filename>somenlp/RE/RE_model.py
import pandas as pd
import numpy as np
import pickle
from torch import cross
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import confusion_matrix, classificati... |
dave-s477/SoMeNLP | somenlp/word_embedding/calculate_embedding.py |
import os
import gensim
import random
import logging
from pathlib import Path
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
class SentenizedInput(object):
"""Simple linebased iterator for data.
Assumes sentences are split by newline character
and tokens are... |
dave-s477/SoMeNLP | read_data.py | <gh_stars>0
#!/usr/bin/env python
import tensorflow as tf
import argparse
import sys
import numpy as np
from os import write
from pathlib import Path
from tensorflow.python.summary.summary_iterator import summary_iterator
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
def format_latex_string(values,... |
dave-s477/SoMeNLP | somenlp/word_embedding/__init__.py | from .calculate_embedding import train_embedding, resume_training_embedding |
dave-s477/SoMeNLP | somenlp/entity_disambiguation/linking_data.py | <gh_stars>0
from hashlib import new
import json
import sys
import random
import re
import numpy as np
from articlenizer import articlenizer
from nltk.corpus import stopwords
random.seed(42)
STOPS = stopwords.words('english')
def normalize(s):
norm_s = re.sub('[^0-9a-zA-Z]+', ' ', s.casefold()).rstrip('0123456789... |
dave-s477/SoMeNLP | somenlp/distant_supervision/packages.py | import json
import urllib.request
import os
from pathlib import Path
from bs4 import BeautifulSoup
def get_pypi_package_names(default_address='https://pypi.org/simple/'):
"""Download PyPi package names
Args:
default_address (str, optional): url for pypi. Defaults to 'https://pypi.org/simple/'.
R... |
dave-s477/SoMeNLP | somenlp/NER/tuner.py | <reponame>dave-s477/SoMeNLP
import json
import copy
from pathlib import Path
from somenlp.utils import find_type_in_dict, getFromDict, setInDict, get_abbr
class Tuner():
def __init__(self, config, time):
self.config = config
self.values_to_vary = find_type_in_dict(self.config, list)
self.... |
dave-s477/SoMeNLP | somenlp/distant_supervision/combine_info.py | <gh_stars>0
import json
from articlenizer import articlenizer as art
def load_dicts(locations):
"""Load and merge information from json dictionaries
Args:
locations (list of Posix paths): locations to json files
Returns:
dictionary: dictionary merged from json files
"""
results ... |
dave-s477/SoMeNLP | somenlp/NER/models/crf.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import os
os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
class CRF(nn.Module):
def __init__(self, tagset_size, device, init_parameters=None):
super(CRF, self).__init__()
self.device = device
if init_parameters is None:
... |
dave-s477/SoMeNLP | somenlp/utils/__init__.py | import torch
import argparse
import operator
from functools import reduce
from .time_marker import get_time_marker
def str2bool(v):
"""Tranform a string value into bool
Args:
v (str): string indicating a bool value
Raises:
argparse.ArgumentTypeError: str is unsuited for parsing to boole... |
dave-s477/SoMeNLP | somenlp/NER/__init__.py | from .output_handler import OutputHandler
from .tuner import Tuner
from .LSTM_dataset import LSTMDataset
from .BERT_dataset import BERTDataset, BERTMultiDataset
from .data_handler import DataHandler
from .model_wrapper import ModelWrapper
from .models import BiLSTM_CRF, FeatureLSTM, CombinedLSTM
from .trainer import Tr... |
dave-s477/SoMeNLP | somenlp/NER/tuning_wrapper_lstm.py | <filename>somenlp/NER/tuning_wrapper_lstm.py
import pickle
import random
import argparse
import json
from os.path import exists, join
from shutil import copytree
from itertools import product
import main_lstm as lstm
import main_lstm_with_features as feat_lstm
import main_lstm_combined as comb_lstm
def generate_al... |
dave-s477/SoMeNLP | somenlp/NER/seqeval_custom/__init__.py | from .metrics.sequence_labeling import classification_report, precision_recall_fscore_support |
dave-s477/SoMeNLP | somenlp/NER/output_handler.py | <reponame>dave-s477/SoMeNLP
import json
from torch.utils.tensorboard import SummaryWriter
from pathlib import Path
from sklearn.metrics import confusion_matrix
from articlenizer.formatting import bio_to_brat
class OutputHandler():
def __init__(self, name, time='0_0_0', checkpoint={}, log_dir='logs', save_dir='sa... |
dave-s477/SoMeNLP | somenlp/feature_engineering/__init__.py | <filename>somenlp/feature_engineering/__init__.py
from .gen_custom_features import calculate_features_parallel |
dave-s477/SoMeNLP | somenlp/distant_supervision/gen_sequences.py | from itertools import product
GEN_SYMBOLS = ['T', 'C', 'G', 'A']
def generate_triplets():
"""Generate all possible triples
Returns:
dictionary: dictionary with list of possible GEN triplets
"""
gen_triplets = [''.join(seq) for seq in product(GEN_SYMBOLS, repeat = 3)]
return {'gen_triplets... |
dave-s477/SoMeNLP | somenlp/entity_disambiguation/efficient_prediction.py | <gh_stars>0
import torch
import torch.nn as nn
import os
import json
import pickle
import random
import copy
import time
import re
import math
import numpy as np
import nltk
import itertools
nltk.download('stopwords')
from functools import partial
from nltk.corpus import stopwords
from torch.utils.data import DataLoad... |
dave-s477/SoMeNLP | somenlp/entity_disambiguation/clustering.py | import numpy as np
import math
import time
import bisect
import sys
from statistics import mean
from multiprocessing import Pool
class SimpleCluster:
"""Cluster a set of entites
"""
def __init__(self, config, entities, features):
"""Init
Args:
entities (list): list of entity m... |
dave-s477/SoMeNLP | somenlp/entity_disambiguation/feature_writer.py | import json
import os
import numpy as np
class FeatureWriter:
def __init__(self, save_dir):
self.output_path = save_dir
def read_features(self, path):
with open(path, 'r') as j_in:
feature_locations = json.load(j_in)
feature_matrices = {}
for k,v in feature_location... |
dave-s477/SoMeNLP | somenlp/NER/BERT_dataset.py | <reponame>dave-s477/SoMeNLP
import torch
import numpy as np
import pandas as pd
from torch.utils.data import Dataset
class BERTDataset(Dataset):
"""PyTorch Dataset for BERT data
"""
def __init__(self, ids, tags, masks, transforms=None):
self.ids = ids
self.tags = tags
self.masks = ... |
dave-s477/SoMeNLP | somenlp/entity_disambiguation/model.py | import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from torch.utils.data import Dataset
from sklearn.metrics import classification_report
from torch.utils.tensorboard import SummaryWriter
class DisambiguationModel(nn.Module):
def __init__(self, dim, layer_sizes, drop_outs):
... |
dave-s477/SoMeNLP | somenlp/RE/__init__.py | <filename>somenlp/RE/__init__.py
from .features import FeatureGenerator
from .RE_model import REmodel |
dave-s477/SoMeNLP | somenlp/feature_engineering/distant_supervision_rules.py | <reponame>dave-s477/SoMeNLP
import numpy as np
def distant_supervision_by_dict(candidate, dictionary, mapping):
result = np.zeros(len(mapping), dtype=np.bool)
span_to_examine = candidate.base_span
values = [mapping[x] for x in dictionary[span_to_examine]] if span_to_examine in dictionary.keys() else []
... |
dave-s477/SoMeNLP | somenlp/feature_engineering/sentence_rep.py | <gh_stars>0
import string
import nltk
import re
import unicodedata
import numpy as np
from nltk.corpus import wordnet
from . import word_rules
lemmatizer = nltk.stem.WordNetLemmatizer()
URL = re.compile(r"^(https?\:\/\/[a-zA-Z0-9\-\.]+[\w\/\._\-\:~\?=#%]*[\w\/_\-\:~\?=#%]|ftp\:\/\/[a-zA-Z0-9\-\.]+[\w\/\._\-\:~\?=#%... |
dave-s477/SoMeNLP | somenlp/entity_disambiguation/__init__.py | from .linking_data import LinkingData
from .feature_writer import FeatureWriter
from .feature_calculator import EntityDisambiguationFeatureGenerator
from .model import ModelWrapper
from .clustering import Clustering, IntervalClustering, SimpleCluster
from .ed_main import main
from .efficient_prediction import ReducedSa... |
dave-s477/SoMeNLP | somenlp/entity_disambiguation/ed_main.py | from somenlp.entity_disambiguation.efficient_prediction import BLOCK_SIZE
import torch
import torch.nn as nn
import torch.optim as optim
torch.multiprocessing.set_sharing_strategy('file_system')
import json
import math
import pickle
import os
from somenlp.entity_disambiguation.model import DisambiguationModel
import sy... |
dave-s477/SoMeNLP | somenlp/RE/features.py | import re
import numpy as np
from gensim.models import KeyedVectors
from itertools import combinations
from articlenizer import CUSTOM_STOPWORDS
from articlenizer.formatting import bio_to_brat
class FeatureGenerator():
def __init__(self, data_handler, embedding_location, emb_dim=200):
self.main_entities =... |
dave-s477/SoMeNLP | somenlp/NER/models/__init__.py | <gh_stars>0
from .crf import CRF
from .lstm import BiLSTM_CRF
from .feature_lstm import FeatureLSTM
from .combined_lstm import CombinedLSTM
from .multi_bert import BERTMultiTask, BERTMultiTaskOpt2, BERTMultiTaskCRF, BERTMultiTaskOpt2CRF
|
dave-s477/SoMeNLP | somenlp/RE/run_relation_extraction.py | <filename>somenlp/RE/run_relation_extraction.py<gh_stars>0
from somenlp.NER import OutputHandler, DataHandler, Tuner
from . import REmodel, FeatureGenerator
def main(model_config, data_config, time, data_file_ext, ent_file_ext, rel_file_ext):
"""Main function for performing relation extraction training
Args:
... |
dave-s477/SoMeNLP | somenlp/feature_engineering/gen_custom_features.py | <gh_stars>0
import json
import numpy as np
from multiprocessing import Pool
from functools import partial
from . import candidate_rules
from . import distant_supervision_rules
from .sentence_rep import SentenceRepresentation, Candidate
FUNCTION_NAMES = [
'pan_top_1', 'pan_top_2', 'pan_top_3', 'pan_top_4', 'pan_... |
dave-s477/SoMeNLP | somenlp/distant_supervision/__init__.py | <reponame>dave-s477/SoMeNLP
from .packages import load_package_names
from .perform_wiki_data_queries import query_wikidata
from .gen_sequences import generate_triplets
from .gen_wiktionary_dict import load_wiktionary
from .combine_info import merge_results, load_dicts |
dave-s477/SoMeNLP | somenlp/NER/LSTM_dataset.py | <gh_stars>0
import torch
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import Dataset
class LSTMDataset(Dataset):
"""PyTorch dataset for LSTM input data
"""
def __init__(self, characters, ids, tags, features, character2idx, padding, max_word_length, max_sent_length, transforms=None):
... |
dave-s477/SoMeNLP | somenlp/distant_supervision/gen_wiktionary_dict.py | import json
import wget
from pathlib import Path
def load_wiktionary(download_location='/tmp/', default_address='https://kaikki.org/dictionary/English/kaikki.org-dictionary-English.json'):
"""Download a pre-processed wiktionary dump to generate an english dictionary for distant supervision.
Args:
do... |
cjavaphp/keybinder3 | examples/example.py | #!/usr/bin/env python
"""
example.py
Created in 2010 by <NAME> <<EMAIL>>
This work is placed in the public domain.
"""
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Keybinder', '3.0')
from gi.repository import Gtk
from gi.repository import Keybinder
def callback(keystr, user_data):
print "Handling... |
lvrbanec/100DaysOfCode_Python | Project06, Beginner, Hangman/main.py | <reponame>lvrbanec/100DaysOfCode_Python
# 02.01.21, Frollo
# level: Beginner
# Project: Create a Hangman game
import random
from hangman_words import word_list #import wordlist
from hangman_art import logo, stages # imports pictures of a stages of hanging man
# pick a word randomly
chosen_word = random.choice(word_li... |
lvrbanec/100DaysOfCode_Python | Project07, Beginner, caesar ciphone/main.py | # 02.02.2021, Frollo
# project: create Casear Cipher
# level Beginner
from art import logo
print(logo)
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',... |
lvrbanec/100DaysOfCode_Python | Project15, Intermediate, Plagiate D.Hirst Painting/main.py | # 08.02.2021, Frollo
# Level: Intermediate
# Project: Create a Damien Hirst painting using module turtle
import turtle
import random
turtle.colormode(255) # change the module to use the rgb color code
tim = turtle.Turtle()
tim.speed("fastest")
tim.penup() # remove the lines connecting the dots
tim.hideturt... |
lvrbanec/100DaysOfCode_Python | Project12, Beginner, HigherLowerGame/main.py | <reponame>lvrbanec/100DaysOfCode_Python<gh_stars>0
# 05/02/2021, Frollo
# Level: Beginner
# Project: Higher Lower game
import art
from game_data import data
import random
from replit import clear
# select a random datapoint
def select_datapoint():
""""Selects a random datapoint from a list, returns it as a dicti... |
lvrbanec/100DaysOfCode_Python | Project11, Beginner, NumberGuess/art.py | logo = """"
_______
(_______)
_ ___ _ _ _____ ___ ___
| | (_ | | | | ___ |/___)/___)
| |___) | |_| | ____|___ |___ |
\_____/|____/|_____(___/(___/
_ | |
_| |_| |__ _____
(_ ... |
lvrbanec/100DaysOfCode_Python | Project04, Beginner, FizzBuzz/main.py | # 01.02.2021
# level: Beginner
# computer solves the Fizz Buzz game from number 1 to 100 (if the number is devisible by 3, print Fizz. If the number is devisible by 5 print Buzz. If its devisible by both, print FizzBuzz. Otherwise print the number.)
for number in range(1, 101):
if number % 3 == 0 and number ... |
lvrbanec/100DaysOfCode_Python | Project11, Beginner, NumberGuess/main.py | # 05.02.2021, Frollo
# Level Beginner
# Project: Number Guessing Game
# computer randlomly picks an integer between 1 and 100, player needs to guess the number
import random
from art import logo
EASY_LEVEL_TURNS = 10 # constants are accessible in functions
HARD_LEVEL_TURNS = 5
# compare two numbers
def compare(numb... |
lvrbanec/100DaysOfCode_Python | Project16, Intermediate, TurtleRace using turtle module/main.py | # 08.02.2021, Frollo
# Level: Intermediate
# Project: Make a turtle race betting game
from turtle import Turtle, Screen
import random
is_race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ")
co... |
lvrbanec/100DaysOfCode_Python | Project09, Beginner, Calculator/main.py | # 03.02.21, Frollo
# Level: beginner
# Project: Easy calculator
from art import logo
print(logo)
# Operations
# Add
def add(n1, n2):
return n1 + n2
# Substract
def substract(n1, n2):
return n1 - n2
# Multipy
def multipy(n1, n2):
return n1 * n2
# Divide
def divide(n1, n2):
return n1 / n2
operations = {
"+... |
lvrbanec/100DaysOfCode_Python | Project14, Intermediate, KnowledgeQuiy, OOP/quiz_brain.py | <filename>Project14, Intermediate, KnowledgeQuiy, OOP/quiz_brain.py
class QuizBrain:
# load in the question list of objects, set the question number as 0
def __init__(self, question_list):
self.question_number = 0
self.score = 0
self.question_list = question_list
# check if... |
lvrbanec/100DaysOfCode_Python | Project14, Intermediate, KnowledgeQuiy, OOP/main.py | from question_model import Question
from data import question_data
from quiz_brain import QuizBrain
# Reformat the data: create a list of objects containing .question and .answer
# from a list of dictionaries with "question" and "answer"
question_bank = []
for dictionary in question_data:
question = dictio... |
lvrbanec/100DaysOfCode_Python | Project02, Beginner, Camel Game/main.py | <reponame>lvrbanec/100DaysOfCode_Python
# 30.01.2021
# level Beginner
# The point of the game is to find the water in the deser to escape Mr. Death
print('''
**********************************************************************
###
... |
lvrbanec/100DaysOfCode_Python | Project10, Beginner, Balckjack game/main.py | # 04.02.2021, Frollo
# Level: Beginner
# project: simulation of a blackjack game
############### Our Blackjack House Rules #####################
## The deck is unlimited in size.
## There are no jokers.
## The Jack/Queen/King all count as 10.
## The the Ace can count as 11 if sum < 21 or 1 if sum > 21.
## The car... |
lvrbanec/100DaysOfCode_Python | Project01, Beginner, Love Calculator/main.py | <gh_stars>0
# 30.01.2021
# level: Beginner
# The aim of this code is to create a love calculator, which "predicts" how well two people match based on their names. The logic is based on the game we played as a kids, and is explained at https://www.buzzfeed.com/ariannarebolini/what-are-the-chances-your-crush-is-actua... |
lvrbanec/100DaysOfCode_Python | Project05, Beginner, Password Generator/main.py | <filename>Project05, Beginner, Password Generator/main.py
# 01.02.2021
# Lever: Beginner
# Password Generator Project
# generate a password with the number of letters, numbers and symbols specified by a subject
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', ... |
lvrbanec/100DaysOfCode_Python | Project08. Beginner, Blind bid decision/main.py | # 03.02.21, Frollo
# level: Beginner
# project: Create a blind bid program
from replit import clear
from art import logo
print(logo)
# add a new bidder function
bidder_info = [] # could be also saved as {name1: amount1, name2: amount2}
def add_bidder_info(val_name, val_bid):
new_bidder = {"name": val_name, "bid"... |
SubZero12556/Cats2dogs_ONNX | networks.py | <filename>networks.py
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
class ResnetGenerator(nn.Module):
def __init__(self, input_nc, output_nc, ngf=64, n_blocks=6, img_size=256, light=False):
assert(n_blocks >= 0)
super(ResnetGenerator, self).__init__()
... |
SubZero12556/Cats2dogs_ONNX | utils.py | from scipy import misc
import os, cv2, torch
import numpy as np
def load_test_data(image_path, size=256):
img = misc.imread(image_path, mode='RGB')
img = misc.imresize(img, [size, size])
img = np.expand_dims(img, axis=0)
img = preprocessing(img)
return img
def preprocessing(x):
x... |
jamesstidard/pipenv-sublime | vendor/pipenvlib.py | <gh_stars>10-100
import os
import json
from . import toml
from . import delegator
class Dependency(object):
"""A Dependency."""
def __init__(self, name, constraint, locked=False):
self.name = name
self.constraint = constraint
self.locked = locked
def __repr__(self):
retu... |
jamesstidard/pipenv-sublime | subl_pipenv.py | import os
import sublime
import sublime_plugin
from .vendor import requests
from .vendor import parse
from .vendor import pipenvlib
TEMPLATE = "<a href='{0}'>{0}</a><br/>"
ALL_PACKAGES = list()
def plugin_loaded():
pass
class PipenvIsEnabledMixin:
def is_enabled(self):
open_files = [view.file_na... |
philskillz-coder/discord-py-paginator | examples/normal_list.py | from abc import ABC
from discord import app_commands, Embed, Color, Interaction
from discord.ext.paginator import paginator
class ColorPaginator(paginator.Paginator, ABC):
pass
@app_commands.command(
name="colors",
description="Show some colors"
)
async def show_colors(interaction: Interaction):
... |
philskillz-coder/discord-py-paginator | discord/ext/paginator/button.py | from __future__ import annotations
from typing import Any, Dict, Callable, List, Coroutine, Type, Optional, Union
from discord import ButtonStyle, Emoji, PartialEmoji, Interaction
from discord.ui import Button
from . import errors
EH = Callable[[Any, Interaction, errors.ButtonException], Coroutine[Any, Any, Any]]
C... |
philskillz-coder/discord-py-paginator | discord/ext/paginator/modals.py | from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from discord import User, Interaction, ui
from discord.utils import MISSING
if TYPE_CHECKING:
from .paginator import Paginator
class QuickNav(ui.Modal, title='Quick Navigation'):
def __init__(self, *, parent: Paginator, user: Use... |
philskillz-coder/discord-py-paginator | discord/ext/paginator/view_buttons.py | <gh_stars>1-10
from __future__ import annotations
from abc import ABC
from discord import ButtonStyle, User, Interaction
from discord.ext.commands import Bot
from . import button, errors, modals
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .paginator import Paginator
class FirstElement(button.Bette... |
philskillz-coder/discord-py-paginator | discord/ext/paginator/paginator.py | <filename>discord/ext/paginator/paginator.py
from discord import ui, User, Interaction, Webhook, Client, ButtonStyle
from discord.ext.commands import Bot
from . import view_buttons
from typing import Dict, Any, List, Union, Optional, Callable, Coroutine
GCP_TYPE = Callable[[Interaction, int], Coroutine[Any, Any, Di... |
philskillz-coder/discord-py-paginator | examples/default.py | <reponame>philskillz-coder/discord-py-paginator
from discord import app_commands, Embed, Color, Interaction
from discord.ext.paginator import paginator
from typing import Dict, Any
class GuildPaginator(paginator.Paginator):
async def get_page_count(self, interaction: Interaction) -> int:
return len(self.c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.