id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
164,005
from zss import simple_distance, Node from space.utils.decorators import ignore_nodes def str_dist(a, b): if a == b: return 0 else: return 1
null
164,006
from zss import simple_distance, Node from space.utils.decorators import ignore_nodes The provided code snippet includes necessary dependencies for implementing the `reorder` function. Write a Python function `def reorder(root)` to solve the following problem: reorder Here is the function: def reorder(root): """...
reorder
164,007
from zss import simple_distance, Node from space.utils.decorators import ignore_nodes The provided code snippet includes necessary dependencies for implementing the `reorder_` function. Write a Python function `def reorder_(root)` to solve the following problem: reorder in place 但__str__函数无法修正 Here is the function: ...
reorder in place 但__str__函数无法修正
164,008
from zss import simple_distance, Node from space.utils.decorators import ignore_nodes def jaccard_dis_sim(x, y): """ Jaccard Distance Similarity """ res = len(set.intersection(*[set(x), set(y)])) union_cardinality = len(set.union(*[set(x), set(y)])) if union_cardinality: return res / flo...
null
164,009
import math, logging, copy, json from collections import Counter, OrderedDict import numpy as np from nltk.util import ngrams from sklearn.metrics import f1_score def DAEvaluate(preds, labels): preds = np.array(preds) labels = np.array(labels) results = {} # for avg_name in ['micro', 'macro', 'weighted...
null
164,010
import json import re from tqdm import tqdm from utils_dst import (DSTExample, convert_to_unicode) LABEL_MAPS = {} def load_acts(input_file): with open(input_file) as f: acts = json.load(f) s_dict = {} for d in acts: for t in acts[d]: if int(t) % 2 == 0: continue ...
Read a DST json file into a list of DSTExample.
164,011
import json import re from utils_dst import (DSTExample, convert_to_unicode) LABEL_MAPS = {} def load_acts(input_file): with open(input_file) as f: acts = json.load(f) s_dict = {} for d in acts: for t in acts[d]: # Only process, if turn has annotation if isinstance(ac...
Read a DST json file into a list of DSTExample.
164,012
import glob import json import sys import numpy as np import re def load_dataset_config(dataset_config): with open(dataset_config, "r", encoding='utf-8') as f: raw_config = json.load(f) return raw_config['class_types'], raw_config['slots'], raw_config['label_maps']
null
164,013
import glob import json import sys import numpy as np import re def tokenize(text): if "\u0120" in text: text = re.sub(" ", "", text) text = re.sub("\u0120", " ", text) text = text.strip() return ' '.join([tok for tok in map(str.strip, re.split("(\W+)", text)) if len(tok) > 0]) def check...
null
164,014
import json import re from utils_dst import (DSTExample, convert_to_unicode) LABEL_MAPS = {} LABEL_FIX = {'centre': 'center', 'areas': 'area', 'phone number': 'number', 'price range': 'price_range'} def delex_utt(utt, values): utt_norm = utt.copy() for s, v in values.items(): if v != 'none': ...
Read a DST json file into a list of DSTExample.
164,015
import json from utils_dst import (DSTExample) def get_turn_label(turn, prev_dialogue_state, slot_list, dial_id, turn_id, delexicalize_sys_utts=False, slot_last_occurrence=True): """Make turn_label a dictionary of slot with value positions or being dontcare / none: Turn label contains: ...
Read a DST json file into a list of DSTExample.
164,016
import argparse import logging import os import random import glob import json import math import re import numpy as np import torch from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler) from torch.utils.data.distributed import DistributedSampler from tqdm import tqdm, trange from transformers imp...
null
164,017
import argparse import logging import os import random import glob import json import math import re import numpy as np import torch from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler) from torch.utils.data.distributed import DistributedSampler from tqdm import tqdm, trange from transformers imp...
Train the model
164,018
import argparse import logging import os import random import glob import json import math import re import numpy as np import torch from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler) from torch.utils.data.distributed import DistributedSampler from tqdm import tqdm, trange from transformers imp...
null
164,019
import logging import six import numpy as np import json logger = logging.getLogger(__name__) class InputFeatures(object): """A single set of features of data.""" def __init__(self, input_ids, input_ids_unmasked, input_mask, segment_ids, ...
Loads a data file into a list of `InputBatch`s.
164,020
import torch from collections import OrderedDict BERT_VOCAB_SIZE = 30522 def get_match_value(name, state_dict_numpy, prefix): """ Need be overridden towards different models, here for UnifiedTransformer Model """ if name == 'embedder.token_embedding.weight': return state_dict_numpy[f'{prefix}emb...
null
164,021
import os import torch from collections import OrderedDict def get_match_value(name, state_dict_numpy): def space2hug(input_template, input_pt, output_pt, restore=True): state_dict_pytorch = OrderedDict() state_dict_init_template = torch.load(input_template, map_location=lambda storage, loc: storage) state...
null
164,022
import time from statistics import mean, stdev import torch from torch import nn from fastai.text.all import * def Accuracy(axis=-1): return AvgMetric(partial(accuracy, axis=axis))
null
164,023
import random, re, os from functools import partial from fastai.text.all import * from hugdatafast.transform import CombineTransform import json import numpy as np def adam_no_correction_step(p, lr, mom, step, sqr_mom, grad_avg, sqr_avg, eps, **kwargs): p.data.addcdiv_(grad_avg, (sqr_avg).sqrt() + eps, value = -lr)...
A `Optimizer` for Adam with `lr`, `mom`, `sqr_mom`, `eps` and `params`
164,024
import random, re, os from functools import partial from fastai.text.all import * from hugdatafast.transform import CombineTransform import json import numpy as np The provided code snippet includes necessary dependencies for implementing the `linear_warmup_and_decay` function. Write a Python function `def linear_warm...
pct (float): fastai count it as ith_step/num_epoch*len(dl), so we can't just use pct when our num_epoch is fake.he ith_step is count from 0,
164,025
import random, re, os from functools import partial from fastai.text.all import * from hugdatafast.transform import CombineTransform import json import numpy as np The provided code snippet includes necessary dependencies for implementing the `linear_warmup_and_then_decay` function. Write a Python function `def linear...
pct (float): fastai count it as ith_step/num_epoch*len(dl), so we can't just use pct when our num_epoch is fake.he ith_step is count from 0,
164,026
import random, re, os from functools import partial from fastai.text.all import * from hugdatafast.transform import CombineTransform import json import numpy as np The provided code snippet includes necessary dependencies for implementing the `load_part_model` function. Write a Python function `def load_part_model(fil...
assume `model` is part of (child attribute at any level) of model whose states save in `file`.
164,027
import random, re, os from functools import partial from fastai.text.all import * from hugdatafast.transform import CombineTransform import json import numpy as np The provided code snippet includes necessary dependencies for implementing the `load_model_` function. Write a Python function `def load_model_(learn, file...
if multiple file passed, then load and create an ensemble. Load normally otherwise
164,030
import copy, math import torch import torch.nn as nn import torch.nn.utils.rnn as rnn_utils def lens2mask2(lens,max_len): bsize = lens.numel() masks = torch.arange(0, max_len).type_as(lens).to(lens.device).repeat(bsize, 1).lt(lens.unsqueeze(1)) masks.requires_grad = False return masks
null
164,034
from functools import partial from pathlib import Path import json from tqdm import tqdm from torch.nn.utils.rnn import pad_sequence import datasets from fastai.text.all import * The provided code snippet includes necessary dependencies for implementing the `_show_title` function. Write a Python function `def _show_ti...
Set title of `ax` to `o`, or print `o` if `ax` is `None`
164,035
from functools import partial from pathlib import Path import json from tqdm import tqdm from torch.nn.utils.rnn import pad_sequence import datasets from fastai.text.all import * def show_batch(x:tuple, y, samples, ctxs=None, max_n=9, **kwargs): if ctxs is None: ctxs = get_empty_df(min(len(samples), max_n)) ctxs =...
null
164,036
from functools import partial from pathlib import Path import json from tqdm import tqdm from torch.nn.utils.rnn import pad_sequence import datasets from fastai.text.all import * def show_results(x: tuple, y, samples, outs, ctxs=None, max_n=10, trunc_at=150, **kwargs): if ctxs is None: ctxs = get_empty_df(min(len(sa...
null
164,037
from multiprocessing import context import os, sys, random from pathlib import Path from functools import partial from datetime import datetime, timezone, timedelta import numpy as np import torch from torch import nn import torch.nn.functional as F import datasets from fastai.text.all import * from transformers import...
Prepare masked tokens inputs/labels for masked language modeling: (1-replace_prob-orginal_prob)% MASK, replace_prob% random, orginal_prob% original within mlm_probability% of tokens in the sentence. * ignore_index in nn.CrossEntropy is default to -100, so you don't need to specify ignore_index in loss
164,053
import os, sys import json import sqlite3 import traceback import argparse from process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def eval_where(pred, label): pred_conds = [unit for unit in pred['where'][::2]] label_conds = [unit for unit in label['where'][::2]] label_wo_agg =...
null
164,059
import os, sys import json import sqlite3 import traceback import argparse from process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def get_keywords(sql): def eval_keywords(pred, label): pred_keywords = get_keywords(pred) label_keywords = get_keywords(label) pred_total = len(pre...
null
164,061
import os, sys import json import sqlite3 import traceback import argparse from process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def get_nestedSQL(sql): nested = [] for cond_unit in sql['from']['conds'][::2] + sql['where'][::2] + sql['having'][::2]: if type(cond_unit[3]) i...
null
164,064
import os, sys import json import sqlite3 import traceback import argparse from process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql class Evaluator: def __init__(self): def eval_hardness(self, sql): def eval_exact_match(self, pred, label): def eval_partial_match(self, pre...
null
164,086
import os, sys import json import sqlite3 import traceback import argparse from process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql class Evaluator: """A simple evaluator""" def __init__(self): self.partial_scores = None def eval_hardness(self, sql): count_comp1_ ...
null
164,093
import json import tqdm from preprocess.parse_sql.get_label_diff import * def get_label(sql,column_len): def get_language_slot(col_slot): from_dict = {1:'One',2:'Two',3:'Three',4:'Four',5:'Five',6:'Six'} def get_sql_label(sql, column_len): schema_label = [[l for l in get_label(sql, column_len) if l != '']] sql...
null
164,094
STRUCT_KEYWORDS = ["WHERE", "GROUP_BY", "HAVING", "ORDER_BY", "SELECT"] NEST_KEYWORDS = ["NONE","OP_SEL"] UEI_KEYWORDS = ["NONE","INTERSECT","UNION","EXCEPT"] def get_label_split(label): label_split = [] temp = '' UEI = False NEST = False Continue = False for idx,tok in enumerate(label.split())...
null
164,095
STRUCT_KEYWORDS = ["WHERE", "GROUP_BY", "HAVING", "ORDER_BY", "SELECT"] NEST_KEYWORDS = ["NONE","OP_SEL"] UEI_KEYWORDS = ["NONE","INTERSECT","UNION","EXCEPT"] ALL_OPS = ["NONE","NOT_IN", "IN", "BETWEEN", "=", ">", "<", ">=", "<=", "LIKE", "!="] AGGS = ["NONE","COUNT", "MAX", "MIN", "SUM", "AVG"] DASCS = ["NONE","ASC", ...
null
164,096
STRUCT_KEYWORDS = ["WHERE", "GROUP_BY", "HAVING", "ORDER_BY", "SELECT"] ALL_OPS = ["NOT_IN", "IN", "BETWEEN", "=", ">", "<", ">=", "<=", "LIKE", "!="] AGGS = ["COUNT", "MAX", "MIN", "SUM", "AVG"] DASCS = ["ASC", "DESC"] NEST_KEYWORDS = ["EXCEPT", "UNION", "INTERSECT"] def get_labels(sql): sql_tokens = sql.upper()....
null
164,097
import os, json, pickle, argparse, sys, time from asdl.asdl import ASDLGrammar from asdl.transition_system import TransitionSystem from asdl.action_info import get_action_infos from preprocess.common_utils import Preprocessor def process_tables(processor, tables_list, output_path=None, verbose=False): tables = {} ...
null
164,098
import os, json, pickle, argparse, sys, time from asdl.asdl import ASDLGrammar from asdl.transition_system import TransitionSystem from asdl.action_info import get_action_infos from preprocess.common_utils import Preprocessor def process_example(processor, entry, db, trans, verbose=False): # preprocess raw tokens, ...
null
164,099
import os, sqlite3 import numpy as np import stanza, torch from nltk.corpus import stopwords from itertools import product, combinations from utils.constants import MAX_RELATIVE_DIST from transformers import RobertaTokenizer import nltk def is_number(s): try: float(s) return True except ValueEr...
null
164,100
import os, sqlite3 import numpy as np import stanza, torch from nltk.corpus import stopwords from itertools import product, combinations from utils.constants import MAX_RELATIVE_DIST from transformers import RobertaTokenizer import nltk The provided code snippet includes necessary dependencies for implementing the `qu...
Normalize all usage of quotation marks into a separate \"
164,103
import argparse import os import sys import pickle import json import shutil import sqlparse def read_database_schema(database_schema, schema_tokens, column_names, database_schemas_dict): def get_schema_tokens(table_schema): column_names_surface_form = [] column_names = [] column_names_orig...
null
164,104
import argparse import os import sys import pickle import json import shutil import sqlparse def get_candidate_tables(format_sql, schema): candidate_tables = [] tokens = format_sql.split() for i, token in enumerate(tokens): if '.' in token: table_name = token.split('.')[0] ca...
null
164,105
import argparse, os, sys, pickle, json from collections import Counter def construct_vocab_from_dataset(*data_paths, table_path='data/table_s.bin', mwf=4, reference_file=None, output_path=None, sep='\t'): words = [] tables = pickle.load(open(table_path, 'rb')) for fp in data_paths: dataset = pickle...
null
164,108
import sys, os, time, json, gc, pickle from argparse import Namespace from utils.args import init_args from utils.hyperparams import hyperparam_path from utils.initialization import * from utils.example import Example from utils.batch import Batch from utils.optimization import set_optimizer from model.model_utils impo...
null
164,109
import sys, os, time, json, gc, pickle from argparse import Namespace from utils.args import init_args from utils.hyperparams import hyperparam_path from utils.initialization import * from utils.example import Example from utils.batch import Batch from utils.optimization import set_optimizer from model.model_utils impo...
null
164,121
import os, pickle, json import torch, random import numpy as np from asdl.asdl import ASDLGrammar from asdl.transition_system import TransitionSystem from utils.constants import UNK, GRAMMAR_FILEPATH, SCHEMA_TYPES, RELATIONS from utils.graph_example import GraphFactory from utils.vocab import Vocab from utils.word2vec ...
null
164,130
import sys, os def hyperparam_path_text2sql(args): def hyperparam_path(args): if args.read_model_path and args.testing: return args.read_model_path exp_path = hyperparam_path_text2sql(args) if not os.path.exists(exp_path): os.makedirs(exp_path) return exp_path
null
164,131
import argparse import sys def add_argument_base(arg_parser): #### General configuration #### arg_parser.add_argument('--task', default='text2sql', help='task name') arg_parser.add_argument('--seed', default=999, type=int, help='Random seed') arg_parser.add_argument('--device', type=int, default=0, help...
null
164,155
import os, sys import json import sqlite3 import traceback import argparse from process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql def eval_nested(pred, label): def eval_IUEN(pred, label): lt1, pt1, cnt1 = eval_nested(pred['intersect'], label['intersect']) lt2, pt2, cnt2 = eval_nes...
null
164,161
import os, sys import json import sqlite3 import traceback import argparse from process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql class Evaluator: """A simple evaluator""" def __init__(self): self.partial_scores = None def eval_hardness(self, sql): count_comp1_ ...
null
164,183
import os, sys import json import sqlite3 import traceback import argparse from process_sql import tokenize, get_schema, get_tables_with_alias, Schema, get_sql class Evaluator: """A simple evaluator""" def __init__(self): self.partial_scores = None def eval_hardness(self, sql): count_comp1_ ...
null
164,205
import sys, os, time, json, gc, pickle from argparse import Namespace from utils.args import init_args from utils.hyperparams import hyperparam_path from utils.initialization import * from utils.example import Example from utils.batch import Batch from utils.optimization import set_optimizer from model.model_utils impo...
null
164,206
import sys, os, time, json, gc, pickle from argparse import Namespace from utils.args import init_args from utils.hyperparams import hyperparam_path from utils.initialization import * from utils.example import Example from utils.batch import Batch from utils.optimization import set_optimizer from model.model_utils impo...
null
164,220
import logging import re, math import torch from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from torch.nn.utils import clip_grad_norm_ from collections import defaultdict schedule_dict = { "constant": get_constant_schedule, "linear": get_linear_schedule_with_warmup, "ratsql":...
null
164,234
import logging import math import os from dataclasses import dataclass, field from typing import Optional import torch from transformers import ( MODEL_WITH_LM_HEAD_MAPPING, AutoTokenizer, HfArgumentParser, PreTrainedTokenizer, set_seed, ) from generator.models.relogic import RelogicModel from generator...
null
164,235
import logging import math import os from dataclasses import dataclass, field from typing import Optional import torch from transformers import ( MODEL_WITH_LM_HEAD_MAPPING, AutoTokenizer, HfArgumentParser, PreTrainedTokenizer, set_seed, ) from generator.models.relogic import RelogicModel from generator...
null
164,236
import logging import math import os from dataclasses import dataclass, field from typing import Optional import torch from transformers import ( MODEL_WITH_LM_HEAD_MAPPING, AutoTokenizer, HfArgumentParser, PreTrainedTokenizer, set_seed, ) from generator.models.relogic import RelogicModel from generator...
null
164,237
import logging import math import os from dataclasses import dataclass, field from typing import Optional import torch from transformers import ( MODEL_WITH_LM_HEAD_MAPPING, AutoTokenizer, HfArgumentParser, PreTrainedTokenizer, set_seed, ) from generator.models.relogic import RelogicModel from generator...
null
164,238
import logging import math import os import random import re import shutil import warnings from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import torch from packaging import version from torch import nn fr...
null
164,239
import logging import math import os import random import re import shutil import warnings from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import torch from packaging import version from torch import nn fr...
null
164,240
import logging import math import os import random import re import shutil import warnings from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import torch from packaging import version from torch import nn fr...
null
164,241
import logging import math import os import random import re import shutil import warnings from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import torch from packaging import version from torch import nn fr...
Decorator to make all processes in distributed training wait for each local_master to do something.
164,242
import logging import math import os import random import re import shutil import warnings from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import torch from packaging import version from torch import nn fr...
null
164,243
import torch def pad_and_tensorize_sequence(sequences, padding_value = None, tensorize = False): if tensorize: return torch.tensor(sequences, dtype=torch.long) max_size = max([len(sequence) for sequence in sequences]) padded_sequences = [] for sequence in sequences: padded_sequence = se...
null
164,244
import json import torch import os from sklearn.metrics import accuracy_score,f1_score,roc_curve,auc,recall_score,precision_score def is_rank_0(): if torch.distributed.is_initialized(): if torch.distributed.get_rank() == 0: return True else: return True return False
null
164,245
import dataclasses import json import logging import os from dataclasses import dataclass, field from typing import Any, Dict, Optional, Tuple from transformers.file_utils import cached_property, is_torch_available, is_torch_tpu_available, torch_required The provided code snippet includes necessary dependencies for im...
Same default as PyTorch
164,247
from setuptools import setup, find_packages import unittest import codecs def test_suite(): test_loader = unittest.TestLoader() test_suite = test_loader.discover('subword_nmt/tests', pattern='test_*.py') return test_suite
null
164,248
from __future__ import print_function import os import sys import inspect import warnings import argparse import codecs from collections import Counter from io import open argparse.open = open def create_parser(subparsers=None): if subparsers: parser = subparsers.add_parser('get-vocab', format...
null
164,249
from __future__ import print_function import os import sys import inspect import warnings import argparse import codecs from collections import Counter from io import open def get_vocab(train_file, vocab_file): c = Counter() for line in train_file: for word in line.strip('\r\n ').split(' '): ...
null
164,250
from __future__ import print_function, unicode_literals, division import sys import codecs import io import argparse from collections import defaultdict from io import open argparse.open = open def create_parser(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, ...
null
164,251
from __future__ import print_function, unicode_literals, division import sys import codecs import io import argparse from collections import defaultdict from io import open def extract_ngrams(words, max_length=4, spaces=False): if not spaces: words = ''.join(words.split()) else: words = words....
null
164,252
from __future__ import print_function, unicode_literals, division import sys import codecs import io import argparse from collections import defaultdict from io import open def get_correct(ngrams_ref, ngrams_test, correct, total): for rank in ngrams_test: for chain in ngrams_test[rank]: total[...
null
164,253
from __future__ import print_function, unicode_literals, division import sys import codecs import io import argparse from collections import defaultdict from io import open def f1(correct, total_hyp, total_ref, max_length, beta=3, smooth=0): precision = 0 recall = 0 for i in range(max_length): if t...
null
164,254
from __future__ import unicode_literals, division import sys import codecs import argparse from io import open argparse.open = open def create_parser(subparsers=None): if subparsers: parser = subparsers.add_parser('segment-char-ngrams', formatter_class=argparse.RawDescriptionHelpFormatter, ...
null
164,255
from __future__ import unicode_literals, division import sys import codecs import argparse from io import open def segment_char_ngrams(args): vocab = [line.split()[0] for line in args.vocab if len(line.split()) == 2] vocab = dict((y,x) for (x,y) in enumerate(vocab)) for line in args.input: for word...
null
164,258
from __future__ import unicode_literals import os import sys import inspect import codecs import re import copy import argparse import warnings import tempfile from multiprocessing import Pool, cpu_count from collections import defaultdict, Counter from io import open argparse.open = open def create_parser(subparsers=...
null
164,259
from __future__ import unicode_literals, division import sys import os import inspect import codecs import io import argparse import re import warnings import random import tempfile from multiprocessing import Pool, cpu_count from io import open def _process_lines(bpe, filename, outfile, dropout, begin, end): if i...
null
164,260
from __future__ import unicode_literals, division import sys import os import inspect import codecs import io import argparse import re import warnings import random import tempfile from multiprocessing import Pool, cpu_count from io import open argparse.open = open def create_parser(subparsers=None): if subparse...
null
164,261
from __future__ import unicode_literals, division import sys import os import inspect import codecs import io import argparse import re import warnings import random import tempfile from multiprocessing import Pool, cpu_count from io import open def check_vocab_and_split(orig, bpe_codes, vocab, separator): """Check...
Encode word based on list of BPE merge operations, which are applied consecutively
164,262
from __future__ import unicode_literals, division import sys import os import inspect import codecs import io import argparse import re import warnings import random import tempfile from multiprocessing import Pool, cpu_count from io import open The provided code snippet includes necessary dependencies for implementin...
read vocabulary file produced by get_vocab.py, and filter according to frequency threshold.
164,263
from __future__ import unicode_literals, division import sys import os import inspect import codecs import io import argparse import re import warnings import random import tempfile from multiprocessing import Pool, cpu_count from io import open The provided code snippet includes necessary dependencies for implementin...
Isolate a glossary present inside a word. Returns a list of subwords. In which all 'glossary' glossaries are isolated For example, if 'USA' is the glossary and '1934USABUSA' the word, the return value is: ['1934', 'USA', 'B', 'USA']
164,264
from __future__ import unicode_literals import sys import os import inspect import codecs import argparse import tempfile import warnings from collections import Counter from multiprocessing import cpu_count from io import open argparse.open = open def create_parser(subparsers=None): if subparsers: parser...
null
164,265
from __future__ import unicode_literals import sys import os import inspect import codecs import argparse import tempfile import warnings from collections import Counter from multiprocessing import cpu_count from io import open def learn_bpe(infile, outfile, num_symbols, min_frequency=2, verbose=False, is_dict=False, ...
null
164,266
import re import sys import collections for i in range(num_merges): pairs = get_stats(vocab) try: best = max(pairs, key=pairs.get) except ValueError: break if pairs[best] < 2: sys.stderr.write('no pair has frequency > 1. Stopping\n') break vocab = merge_vocab(best, vocab) print(best) def ...
null
164,267
import re import sys import collections def merge_vocab(pair, v_in): v_out = {} bigram_pattern = re.escape(' '.join(pair)) p = re.compile(r'(?<!\S)' + bigram_pattern + r'(?!\S)') for word in v_in: w_out = p.sub(''.join(pair), word) v_out[w_out] = v_in[word] return v_out
null
164,276
import logging import math import os import random import re import shutil import warnings from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import torch from packaging import version from torch import nn fr...
null
164,277
import logging import math import os import random import re import shutil import warnings from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import torch from packaging import version from torch import nn fr...
null
164,278
import logging import math import os import random import re import shutil import warnings from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import torch from packaging import version from torch import nn fr...
null
164,279
import logging import math import os import random import re import shutil import warnings from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import torch from packaging import version from torch import nn fr...
Decorator to make all processes in distributed training wait for each local_master to do something.
164,280
import logging import math import os import random import re import shutil import warnings from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import torch from packaging import version from torch import nn fr...
null
164,286
import json import torch from bleu import list_bleu import os def is_rank_0(): if torch.distributed.is_initialized(): if torch.distributed.get_rank() == 0: return True else: return True return False
null
164,288
import torch def pad_and_tensorize_sequence(sequences, padding_value): max_size = max([len(sequence) for sequence in sequences]) padded_sequences = [] for sequence in sequences: padded_sequence = sequence + [padding_value] * (max_size - len(sequence)) padded_sequences.append(padded_sequence) return tor...
null
164,289
import torch import torch.nn as nn from transformers.modeling_bart import BartForConditionalGeneration from transformers.tokenization_bart import BartTokenizer from generator.keywords.keywords import SKETCH_KEYWORDS, KEYWORDS import logging import os def pad_and_tensorize_sequence(sequences, padding_value = None, tens...
null
164,290
from moz_sql_parser import parse import json import re from mo_future import string_types, text, first, long, is_text import random from sql_formatter.keywords import RESERVED, reserved_keywords, join_keywords, precedence, binary_ops VALID = re.compile(r'^[a-zA-Z_]\w*$') reserved_keywords = [] The provided code snipp...
Return true if a given identifier should be quoted. This is usually true when the identifier: - is a reserved word - contain spaces - does not match the regex `[a-zA-Z_]\\w*`
164,291
from moz_sql_parser import parse import json import re from mo_future import string_types, text, first, long, is_text import random from sql_formatter.keywords import RESERVED, reserved_keywords, join_keywords, precedence, binary_ops def split_field(field): """ RETURN field AS ARRAY OF DOT-SEPARATED FIELDS ...
Escape identifiers. ANSI uses single quotes, but many databases use back quotes.
164,292
from moz_sql_parser import parse import json import re from mo_future import string_types, text, first, long, is_text import random from sql_formatter.keywords import RESERVED, reserved_keywords, join_keywords, precedence, binary_ops binary_ops = { "||": "concat", "*": "mul", "/": "div", "%": "mod", ...
null
164,293
import json import sqlite3 import os import random from tqdm import tqdm import json import time import signal import multiprocessing from multiprocessing import Manager alpha = 0.5 beta = 0.5 gamma = 0.6 theta = 0.15 db_dir = "/ai/conceptflow/data/examples/semantic-parsing/text-to-sql/spider/spider/database" sql_dict ...
null
164,294
import json import sqlite3 import os import random from tqdm import tqdm import json import time import signal import multiprocessing from multiprocessing import Manager def handler(signum, frame): raise AssertionError
null
164,295
import os import re import json import pickle import random from template_config import * from collections import defaultdict from nltk.stem.porter import PorterStemmer from nltk.stem.wordnet import WordNetLemmatizer import nltk def read_in_all_data(data_path=DATA_PATH): training_data = json.load(open(os.path.join...
null