id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
13,516
from minichain import show, prompt, OpenAI, Python, GradioConf import gradio as gr def math_prompt(model, question ): "Prompt to call GPT with a Jinja template" return model(dict(question=question)) def python(model, code): "Prompt to call Python interpreter" code = "\n".join(code.strip(...
Chain them together
13,517
import trio from minichain import TemplatePrompt, show_log, start_chain The provided code snippet includes necessary dependencies for implementing the `chunk` function. Write a Python function `def chunk(f, width=4000, overlap=800)` to solve the following problem: Split a documents into 4800 character overlapping chun...
Split a documents into 4800 character overlapping chunks
13,518
from dataclasses import dataclass, replace from typing import Optional from minichain import prompt, show, OpenAI, Google, transform class State: question: str history: str = "" next_query: Optional[str] = None final_answer: Optional[str] = None template_file = "selfask.pmpt.tpl") def self_ask(...
null
13,519
from minichain import prompt, show, OpenAI, transform from dataclasses import dataclass, is_dataclass, fields from typing import List, Type, Dict, Any, get_origin, get_args from enum import Enum from jinja2 import select_autoescape, FileSystemLoader, Environment import json def type_to_prompt(out: type) -> str: tmp...
null
13,520
from minichain import prompt, show, OpenAI, transform from dataclasses import dataclass, is_dataclass, fields from typing import List, Type, Dict, Any, get_origin, get_args from enum import Enum from jinja2 import select_autoescape, FileSystemLoader, Environment import json class Player: player: str stats: List...
null
13,521
import datasets import numpy as np from minichain import prompt, show, HuggingFaceEmbed, OpenAI, transform def embed(model, inp): return model(inp) def get_neighbors(embedding, k=1): res = gatsby.get_nearest_examples("embeddings", np.array(embedding), k) return res.examples["passages"] def ask(model, query,...
null
13,522
import pandas as pd from minichain import prompt, Mock, show, OpenAI, GradioConf import minichain import json import gradio as gr import requests names = { '3-pointer percentage': 'FG3_PCT', '3-pointers attempted': 'FG3A', '3-pointers made': 'FG3M', 'Assists': 'AST', 'Blocks': 'BLK', 'Field goal...
null
13,523
import pandas as pd from minichain import prompt, Mock, show, OpenAI, GradioConf import minichain import json import gradio as gr import requests import os def make_html(out): return "<table><tr><td>" + out.replace("\t", "</td><td>").replace("\n", "</td></tr><tr><td>") + "</td></td></table>"
null
13,524
import pandas as pd from minichain import prompt, Mock, show, OpenAI, GradioConf import minichain import json import gradio as gr import requests def extract(model, passage, typ): return model(dict(player_keys=names.items(), examples=examples, passage=passage, type=typ)) import os def run(query): return extrac...
null
13,525
from minichain import Id, prompt, OpenAI, show, transform, Mock, Break from gradio_tools.tools import StableDiffusionTool, ImageCaptioningTool, ImageToMusicTool def agent(model, query, history): return model(dict(tools=[(str(tool.__class__.__name__), tool.description) for tool in tools]...
null
13,526
import datasets import numpy as np from minichain import prompt, transform, show, OpenAIEmbed, OpenAI from manifest import Manifest def embed(model, inp): return model(inp) def get_neighbors(inp, k): res = olympics.get_nearest_examples("embeddings", np.array(inp), k) return res.examples["content"] def get_r...
null
13,527
from minichain import prompt, show, GradioConf, OpenAI, Python import gradio as gr def pal_prompt(model, question): def python(model, inp): def pal(question): return python(pal_prompt(question))
null
13,528
from minichain import show, prompt, OpenAI, GradioConf import gradio as gr from gradio_tools.tools import StableDiffusionTool, ImageCaptioningTool def picture(model, query): return model(query) gradio_conf=GradioConf( block_output= lambda: gr.Image(), block_input= lambda: gr.Textbox(...
null
13,529
from minichain import show, prompt, OpenAI, Bash def cli_prompt(model, query): def bash_run(model, x): def bash(query): return bash_run(cli_prompt(query))
null
13,530
from minichain import prompt, transform, show, OpenAI import json def ner_extract(model, kwargs): return model(kwargs) def to_json(chat_output): return json.loads(chat_output) def team_describe(model, inp): query = "Can you describe these basketball teams? " + \ " ".join([i["E"] for i in inp if i["T...
null
13,543
from minichain import prompt, show, GradioConf, OpenAI, Python import gradio as gr def pal_prompt(model, question): return model(dict(question=question)) gradio_conf=GradioConf(block_input = lambda: gr.Code(language="python"))) def python(model, inp): return model(inp + "\nprint(solution())") def pal(q...
null
13,545
from minichain import show, prompt, OpenAI, Bash def cli_prompt(model, query): return model(dict(question=query)) def bash_run(model, x): x = "\n".join(x.strip().split("\n")[1:-1]) return model(x) def bash(query): return bash_run(cli_prompt(query))
null
13,547
import os import subprocess import time from dataclasses import dataclass from types import TracebackType from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Tuple from eliot import start_action, to_file def set_minichain_log(name: str) -> None: to_file(open(f"{name}.log", "w"))
null
13,548
from dataclasses import asdict, dataclass from itertools import count from typing import ( Any, Callable, Generic, Iterable, Iterator, List, Optional, TypeVar, Union, ) from jinja2 import Environment, FileSystemLoader, Template from .backend import Backend, MinichainContext, PromptSn...
null
13,549
import inspect import os from dataclasses import dataclass, field from typing import Any, Callable, Dict, List, Set, Tuple, Union import gradio as gr from gradio.blocks import Block from minichain import start_chain from .backend import MinichainContext from .base import Prompt CSS = """ #clean div.form {border: 0px} #...
Constructs a gradio component to show a prompt chain. Args: prompt: A prompt or prompt chain to display. examples: A list of example inputs, either string or tuples of fields subprompts: The `Prompt` objects to display. fields: The names of the field input to the prompt. initial_state: For stateful prompts, the initial...
13,550
import os import sys from datetime import date import subprocess def git_authors(): result = subprocess.run( ["git", "shortlog", "--summary", "HEAD"], stdout = subprocess.PIPE, check = True) names = [ line.strip().split("\t")[1] for line in result.stdout.decode("ut...
null
13,551
import os import sys from datetime import date import subprocess def prose_list(items): if not items: return "" if len(items) == 1: return items[0] elif len(items) == 2: return " and ".join(items) else: return ", ".join([*items[0:-1], "and " + items[-1]])
null
13,552
import logging import hashlib import collections.abc as abc import os import shutil import sys import errno def _make_dir_recursively(dir_): try: os.makedirs(dir_) except OSError as ex: from errno import EEXIST if ex.errno != EEXIST: raise
null
13,553
import logging import hashlib import collections.abc as abc import os import shutil import sys import errno def update_checksum(checksum, obj): if isinstance(obj, str): checksum.update(obj.encode("utf8")) else: checksum.update(obj)
null
13,554
import argparse from augur.io import open_file, read_metadata from Bio import SeqIO import csv import sys def parse_args(): parser = argparse.ArgumentParser( description=""" Custom script to combine metadata files from different origins. In the case where metadata files specify different va...
null
13,555
import argparse import json import re from numpy import linspace from math import floor The provided code snippet includes necessary dependencies for implementing the `adjust_coloring_for_epiweeks` function. Write a Python function `def adjust_coloring_for_epiweeks(dataset)` to solve the following problem: If an auspi...
If an auspice JSON specifies a colouring with the key "epiweek" (case sensitive) then we create a categorical colorscale which evenly spaces the canonical nextstrain rainbow across the observed time window. NOTE: epiweek must be in CDC format ("YYYYMM") but this may be relaxed to include ISO format in the future.
13,556
import argparse import sys from datetime import datetime import pandas as pd import numpy as np INSERT_BEFORE_THIS_COLUMN = "pango_lineage" column_map = { "clade": "Nextstrain_clade", "Nextclade_pango": "Nextclade_pango", "totalMissing": "missing_data", "totalSubstitutions": "divergence", "totalNonA...
Moves the new clade column after a specified column
13,557
import argparse import sys from datetime import datetime import pandas as pd import numpy as np def parse_args(): parser = argparse.ArgumentParser( description="Joins metadata file with Nextclade clade output", ) parser.add_argument("first_file") parser.add_argument("second_file") parser.ad...
null
13,558
import argparse import sys from datetime import datetime import pandas as pd import numpy as np def datestr_to_ordinal(x): try: return datetime.strptime(x,"%Y-%m-%d").toordinal() except: return np.nan
null
13,559
import argparse import sys from datetime import datetime import pandas as pd import numpy as np def isfloat(value): try: float(value) return True except ValueError: return False
null
13,560
import argparse from augur.io import open_file, read_sequences, write_sequences import hashlib from pathlib import Path import re import sys from utils import stream_tar_file_contents The provided code snippet includes necessary dependencies for implementing the `rename_sequences` function. Write a Python function `de...
Rename the given sequences' ids by replacing the given patterns with the empty string.
13,561
import argparse from augur.io import open_file, read_sequences, write_sequences import hashlib from pathlib import Path import re import sys from utils import stream_tar_file_contents class DuplicateSequenceError(ValueError): pass The provided code snippet includes necessary dependencies for implementing the `drop...
Identify and drop duplicate sequences from the given iterator. Parameters ---------- sequences : Iterator Yields ------ Bio.SeqIO.Seq : Unique sequence records Raises ------ DuplicateSequenceError : If `error_on_duplicates` is True and any duplicate records are found, raises an exception with a comma-delimited list of ...
13,562
from io import TextIOWrapper import lzma from pathlib import Path import sys import tarfile import tempfile EXTENSION_BY_FILETYPE = { "metadata": ".tsv", "sequences": ".fasta", } The provided code snippet includes necessary dependencies for implementing the `extract_tar_file_contents` function. Write a Python ...
Try to extract the contents of a given file type (e.g., metadata or sequences) from the given tar filename. Parameters ---------- filename : str or Path-like Path to the tar archive to search for the given file type. filetype : str Type of file to search for in the given tar archive based on the associated file extensi...
13,563
from io import TextIOWrapper import lzma from pathlib import Path import sys import tarfile import tempfile EXTENSION_BY_FILETYPE = { "metadata": ".tsv", "sequences": ".fasta", } The provided code snippet includes necessary dependencies for implementing the `stream_tar_file_contents` function. Write a Python f...
Try to extract the contents of a given file type (e.g., metadata or sequences) from the given tar filename. Parameters ---------- filename : str or Path-like Path to the tar archive to search for the given file type. filetype : str Type of file to search for in the given tar archive based on the associated file extensi...
13,564
import argparse import json from Bio import Phylo from collections import defaultdict def attach_labels(d, labeled_nodes): if "children" in d: for c in d["children"]: if c["name"] in labeled_nodes: if "labels" not in c["branch_attrs"]: c["branch_attrs"]["labe...
null
13,565
import argparse from datetime import datetime from augur.io import read_metadata import json def get_recency(date_str, ref_date): date_submitted = datetime.strptime(date_str, '%Y-%m-%d').toordinal() ref_day = ref_date.toordinal() delta_days = ref_day - date_submitted if delta_days<=0: return '...
null
13,566
import argparse import numpy as np import pandas as pd from datetime import datetime, timedelta def isfloat(value): try: float(value) return True except ValueError: return False
null
13,567
import argparse import numpy as np import pandas as pd from datetime import datetime, timedelta def datestr_to_ordinal(x, minus_weeks=0): try: return (datetime.strptime(x,"%Y-%m-%d") - timedelta(weeks=minus_weeks)).toordinal() except: return np.nan def earliest_clade_date(Nextstrain_clade, clad...
null
13,568
import argparse from augur.io import open_file, read_sequences, write_sequences import Bio import Bio.SeqIO from Bio.Seq import Seq def mask_terminal_gaps(seq): L = len(seq) seq_trimmed = seq.lstrip('-') left_gaps = L - len(seq_trimmed) seq_trimmed = seq_trimmed.rstrip('-') right_gaps = L - len(seq...
null
13,569
import argparse import json def update_strain_names(n): # closure if "NODE_" not in n["name"] and args.prefix not in n["name"]: n["name"] = args.prefix + n["name"] if "children" in n: for c in n["children"]: update_strain_names(c)
null
13,570
import argparse from augur.frequency_estimators import logit_transform from augur.utils import annotate_parents_for_tree, read_node_data, read_tree, write_json import Bio.Phylo from collections import defaultdict import json import math import numpy as np from scipy.stats import linregress import sys The provided code...
Returns a dictionary of frequencies and their parameters indexed by strain name from a given auspice tip frequencies file.
13,571
import argparse, os, glob from augur.io import open_file from Bio import SeqIO, SeqFeature, Seq from Bio.SeqIO.FastaIO import SimpleFastaParser import numpy as np import pandas as pd def read_reference(fname, genemap): try: ref = str(SeqIO.read(fname, 'fasta').seq) except: with open(fname, 'r')...
null
13,572
import argparse, os, glob from augur.io import open_file from Bio import SeqIO, SeqFeature, Seq from Bio.SeqIO.FastaIO import SimpleFastaParser import numpy as np import pandas as pd def summarise_differences(ref, query, isAA): """ Summarise the differences between a provided reference and a query (both of ...
null
13,573
import argparse from augur.io import read_sequences from random import shuffle from collections import defaultdict import Bio import numpy as np from Bio.SeqIO.FastaIO import SimpleFastaParser from Bio.Seq import Seq from Bio import AlignIO, SeqIO from scipy import sparse import sys def compactify_sequences(sparse_mat...
null
13,574
import argparse from augur.io import read_sequences from random import shuffle from collections import defaultdict import Bio import numpy as np from Bio.SeqIO.FastaIO import SimpleFastaParser from Bio.Seq import Seq from Bio import AlignIO, SeqIO from scipy import sparse import sys INITIALISATION_LENGTH = 1000000 def ...
null
13,575
import argparse from augur.io import read_sequences from random import shuffle from collections import defaultdict import Bio import numpy as np from Bio.SeqIO.FastaIO import SimpleFastaParser from Bio.Seq import Seq from Bio import AlignIO, SeqIO from scipy import sparse import sys def calculate_distance_matrix(spars...
null
13,576
import argparse from augur.io import open_file, read_metadata import csv import os from pathlib import Path import pandas as pd import re import shutil import sys from tempfile import NamedTemporaryFile from utils import extract_tar_file_contents The provided code snippet includes necessary dependencies for implementi...
Parse the mapping of current to new column names from the given list of renaming rules. Parameters ---------- renaming_rules : list[str] A list of strings mapping an old column name to a new one delimited by an equal symbol (e.g., "old_column=new_column"). Returns ------- dict : A mapping of new column names for each o...
13,577
import argparse from augur.io import open_file, read_metadata import csv import os from pathlib import Path import pandas as pd import re import shutil import sys from tempfile import NamedTemporaryFile from utils import extract_tar_file_contents The provided code snippet includes necessary dependencies for implementi...
Parse location string from GISAID into the given separate geographic scales and return a dictionary of parse values by scale. Parameters ---------- location_string : str location_fields : list Returns ------- dict : dictionary of geographic fields parsed from the given string >>> location_fields = ["region", "country",...
13,578
import argparse from augur.io import open_file, read_metadata import csv import os from pathlib import Path import pandas as pd import re import shutil import sys from tempfile import NamedTemporaryFile from utils import extract_tar_file_contents class MissingColumnException(Exception): """An exception caused by a ...
Get a mapping of all database ids for each strain name. Parameters ---------- metadata_file : str or Path-like or file object Path or file object for a metadata file to process. metadata_id_columns : list[str] A list of potential id columns for strain names in the metadata. database_id_columns : list[str] A list of pot...
13,579
import argparse from augur.io import open_file, read_metadata import csv import os from pathlib import Path import pandas as pd import re import shutil import sys from tempfile import NamedTemporaryFile from utils import extract_tar_file_contents The provided code snippet includes necessary dependencies for implementi...
Filter duplicate records by the strain name in the given data frame index using the given file containing a mapping of strain names to database ids. Database ids allow us to identify duplicate records that need to be excluded. We prefer the latest record for a given strain name across all possible database ids and filt...
13,580
import argparse import json from Bio import Phylo, SeqIO from Bio.Align import MultipleSeqAlignment from treetime import TreeAnc from augur.utils import load_features def annotation_json(features, reference): annotations = {} for fname, feat in features.items(): annotations[fname] = {'seqid':reference....
null
13,581
from os import listdir from pathlib import Path import argparse from collections import defaultdict def cut(s): key = s.split(":")[0] content = ":".join(s.split(":")[1:])[1:] return (key, content) def read_data(path): additional_info = {} for file in sorted(listdir(path)): if file == '.DS...
null
13,582
from os import listdir from pathlib import Path import argparse from collections import defaultdict def bold(s): return('\033[1m' + s + '\033[0m') def read_simple_file(name): with open(name) as myfile: data_file = myfile.readlines() return [l.strip() for l in data_file] def read_dict(name): with...
null
13,583
import sys import datetime import pandas as pd from pathlib import Path import os def bold(s): return('\033[1m' + s + '\033[0m') def read_excel_lab_file(table_file_name): if not os.path.exists(table_file_name): print(bold("Missing input file: " + table_file_name)) return None excel_table ...
null
13,584
import sys import datetime import pandas as pd from pathlib import Path import os def read_metadata(filename, date_g, tweet): uk_divisions = ["England", "Wales", "Northern Ireland", "Scotland", "United Kingdom"] year_g = date_g[:4] month_g = date_g[5:7] if month_g == "12": year_gplus = str(in...
null
13,585
import sys import datetime import pandas as pd from pathlib import Path import os def collect_labs(labs, lab_dictionary, old): lab_collection = {} for region in labs: if region not in lab_collection: lab_collection[region] = {} for country in sorted(labs[region]): if co...
null
13,586
import sys import datetime import pandas as pd from pathlib import Path import os path_to_outputs = "scripts/curate_metadata/outputs_new_sequences/" def print_labs(lab_collection, data): output_file = path_to_outputs + "twitter_handles_" + data + ".txt" with open(output_file, "w") as out: for region in...
null
13,587
import sys import datetime import pandas as pd from pathlib import Path import os path_to_outputs = "scripts/curate_metadata/outputs_new_sequences/" def generate_tweet(new_seqs_count, lab_collection, lab_collection_old, new_countries, data): known_handles = [] for region in lab_collection_old: for coun...
null
13,588
import os import matplotlib.pyplot as plt import pandas as pd from pandas.plotting import register_matplotlib_converters import random import numpy as np import math import datetime def cut(s): key = s.split(":")[0] content = ":".join(s.split(":")[1:])[1:] return (key, content) def read_data(path): da...
null
13,589
import os import matplotlib.pyplot as plt import pandas as pd from pandas.plotting import register_matplotlib_converters import random import numpy as np import math import datetime def bold(s): return('\033[1m' + s + '\033[0m') def read_excel_lab_file(table_file_name): excel_table = pd.read_excel(table_file_na...
null
13,590
import os import matplotlib.pyplot as plt import pandas as pd from pandas.plotting import register_matplotlib_converters import random import numpy as np import math import datetime def check_dates(data, today): clade_dates = { "19A": "2019-12-01", "19B": "2019-12-01", "20A": "2020-01-20", ...
null
13,591
import os import matplotlib.pyplot as plt import pandas as pd from pandas.plotting import register_matplotlib_converters import random import numpy as np import math import datetime def bold(s): return('\033[1m' + s + '\033[0m') flagged_properties = {"originating_lab": ["Synlab Haut de France"]} path_to_outputs = "...
null
13,592
import os import matplotlib.pyplot as plt import pandas as pd from pandas.plotting import register_matplotlib_converters import random import numpy as np import math import datetime def plot_dates(data, path): dates_by_country = {} for id in data: country = data[id]["country"] date = datetime....
null
13,593
import os import matplotlib.pyplot as plt import pandas as pd from pandas.plotting import register_matplotlib_converters import random import numpy as np import math import datetime path_to_outputs = "scripts/curate_metadata/outputs_new_sequences/" def print_counts(data): counts = {} for id in data: co...
null
13,594
import os import matplotlib.pyplot as plt import pandas as pd from pandas.plotting import register_matplotlib_converters import random import numpy as np import math import datetime def bold(s): return('\033[1m' + s + '\033[0m') def strike(s): return('\u0336'.join(s) + '\u0336') def read_excel_lab_file(table_fi...
null
13,595
import os import matplotlib.pyplot as plt import pandas as pd from pandas.plotting import register_matplotlib_converters import random import numpy as np import math import datetime def overview_with_dates(data, file_name): data_sorted = {} for id in data: strain = data[id]["strain"] submissio...
null
13,596
import os import matplotlib.pyplot as plt import pandas as pd from pandas.plotting import register_matplotlib_converters import random import numpy as np import math import datetime def filter_for_date_region(data, path_to_outputs, params): (region, month) = params special_strains = {} for id in data: ...
null
13,597
import os import matplotlib.pyplot as plt import pandas as pd from pandas.plotting import register_matplotlib_converters import random import numpy as np import math import datetime path_to_outputs = "scripts/curate_metadata/outputs_new_sequences/" def prepare_tweet(counts, total_lab_collection, lab_collection): ...
null
13,598
import os import matplotlib.pyplot as plt import pandas as pd from pandas.plotting import register_matplotlib_converters import random import numpy as np import math import datetime def prepare_tweet_new_format(counts, rare_labs): links = { "Africa": "nextstrain.org/ncov/africa", "Asia": "nextstrai...
null
13,599
import os from difflib import SequenceMatcher from pathlib import Path from geopy.geocoders import Nominatim from collections import Counter path_to_metadata = "data/" def read_metadata(metadata_filename, data, geo_location_occurences, genbank=False): with open(path_to_metadata + metadata_filename) as f: ...
null
13,600
import os from difflib import SequenceMatcher from pathlib import Path from geopy.geocoders import Nominatim from collections import Counter def bold(s): return('\033[1m' + s + '\033[0m') def read_local_file(file_name): path_file_name = path_to_config_files + file_name with open(path_file_name) as myfile: ...
null
13,601
import os from difflib import SequenceMatcher from pathlib import Path from geopy.geocoders import Nominatim from collections import Counter def bold(s): return('\033[1m' + s + '\033[0m') def read_local_file(file_name): path_file_name = path_to_config_files + file_name with open(path_file_name) as myfile: ...
null
13,602
import os from difflib import SequenceMatcher from pathlib import Path from geopy.geocoders import Nominatim from collections import Counter def bold(s): return('\033[1m' + s + '\033[0m') def check_division_inconsistency(data): for region in data: for country in data[region]: for division i...
null
13,603
import os from difflib import SequenceMatcher from pathlib import Path from geopy.geocoders import Nominatim from collections import Counter def bold(s): def read_local_file(file_name): region_order = ["Asia", "Oceania", "Africa", "Europe", "South America", "North America"] def check_duplicates(data, abbreviations_fil...
null
13,604
import os from difflib import SequenceMatcher from pathlib import Path from geopy.geocoders import Nominatim from collections import Counter def read_latlongs(path): with open(path + latlongs_file) as myfile: file_content = myfile.readlines() latlongs = {"location": {}, "division": {}, "country": {}, "r...
null
13,605
import os from difflib import SequenceMatcher from pathlib import Path from geopy.geocoders import Nominatim from collections import Counter def bold(s): return('\033[1m' + s + '\033[0m') def print_missing_places(missing_latlongs): ### DIVISION ### print("\n----------\n") if missing_latlongs['division'...
null
13,606
import os from difflib import SequenceMatcher from pathlib import Path from geopy.geocoders import Nominatim from collections import Counter def bold(s): return('\033[1m' + s + '\033[0m') def clean_string(s): s = s.lower() for c in replace_special_char: s = s.replace(c, replace_special_char[c]) ...
null
13,607
import os from difflib import SequenceMatcher from pathlib import Path from geopy.geocoders import Nominatim from collections import Counter def find_place(geo_level, place, full_place, geolocator, region = "*"): typed_place = full_place redo = True tries = 0 while redo == True: if tries < 5: ...
null
13,608
import os from difflib import SequenceMatcher from pathlib import Path from geopy.geocoders import Nominatim from collections import Counter def bold(s): def read_ordering(path): def read_latlongs(path): def sort_by_coordinates(data, coordinates): path_to_default_files = "defaults/" path_to_output_files = "scripts/cura...
null
13,609
import os from difflib import SequenceMatcher from pathlib import Path from geopy.geocoders import Nominatim from collections import Counter path_to_annotations = "../ncov-ingest/source-data/" def read_annotations(annotationsFile, gisaid): types = {"geography": ["location", "division", "country", "region", "divisi...
null
13,610
import os from difflib import SequenceMatcher from pathlib import Path from geopy.geocoders import Nominatim from collections import Counter path_to_metadata = "data/" def create_annotations(metadata_filename, applied_rules_geoLocation, applied_rules_manual, gisaid): geoLocationAnnotations = {} manualAnnotatio...
null
13,611
import os from difflib import SequenceMatcher from pathlib import Path from geopy.geocoders import Nominatim from collections import Counter def bold(s): return('\033[1m' + s + '\033[0m') def find_conflicting_annotations(annotations, geoLocationAnnotations, manualAnnotations, gisaid): for id in annotations["ge...
null
13,612
import os from difflib import SequenceMatcher from pathlib import Path from geopy.geocoders import Nominatim from collections import Counter def bold(s): path_to_metadata = "data/" def special_metadata_checks(metadata_filename, annotations, gisaid): special_annotations = {} unknown_clades = [] with open(p...
null
13,613
import os from difflib import SequenceMatcher from pathlib import Path from geopy.geocoders import Nominatim from collections import Counter path_to_output_files = "scripts/curate_metadata/output_curate_metadata/" def write_annotations(annotations, annotationsFile): with open(path_to_output_files + annotationsFile...
null
13,614
from datetime import datetime import math import struct import sys def scramble(data): acc = 0 nacc = 0 t = 0x2953 u = 0xD9C2 v = 0x3FF1 x = 1 it = 0 while it < len(data): t0 = t & 1 t1 = (t >> 1) & 1 u0 = u & 1 u1 = (u >> 1) & 1 v0 = v & 1 ...
null
13,615
from datetime import datetime import math import struct import sys def flatten_dol(data): header = struct.unpack(">64I", data[:256]) dol_min = min(a for a in header[18:36] if a) dol_max = max(a + s for a, s in zip(header[18:36], header[36:54])) img = bytearray(dol_max - dol_min) for offset, addr...
null
13,616
from datetime import datetime import math import struct import sys def bytes_to_c_array(data): p_list = [data[i:i + 4] for i in range(0, len(data), 4)] return ["0x%08x" % int.from_bytes(b, byteorder='big', signed=False) for b in p_list]
null
13,617
from datetime import datetime import math import struct import sys def generate_header_file(elements, executable, input_file, output_file, size): output = '#include <stdio.h>\n\n' output += '//\n' output += '// Command: {0} {1} {2}\n'.format(executable, input_file, output_file) output += '//\n' out...
null
13,618
from datetime import datetime import math import struct import sys The provided code snippet includes necessary dependencies for implementing the `process_scrambled_ipl` function. Write a Python function `def process_scrambled_ipl(ipl, size)` to solve the following problem: Does additional processing to scrambled IPL ...
Does additional processing to scrambled IPL payload. Payload used by PicoBoot has to be preprocessed. Whole payload has to be aligned to 1K blocks then every bit needs to be duplicated 4 times.
13,619
import os import sys import torch from d2l import torch as d2l from torch import nn import d2lutil.common as common def dropout_layer(X, dropout): assert 0 <= dropout <= 1 # 在本情况中,所有元素都被丢弃。 if dropout == 1: return torch.zeros_like(X) # 在本情况中,所有元素都被保留。 if dropout == 0: return X m...
null
13,620
import os import sys import torch from torch import nn import d2lutil.common as common batch_size = min(10, train_labels.shape[0]) dataset = torch.utils.data.TensorDataset(train_features, train_labels) train_iter = torch.utils.data.DataLoader(dataset, batch_size, shuffle=True) net = nn.Linear(train_feat...
null
13,621
import os import sys import torch from d2l import torch as d2l from torch import nn def init_weights(m): if type(m) == nn.Linear: nn.init.normal_(m.weight, std=0.01)
null
13,622
import hashlib import os import tarfile import zipfile import requests import numpy as np import pandas as pd import torch from torch import nn from d2l import torch as d2l def download(name, cache_dir=os.path.join('..', 'data')): # @save """下载一个DATA_HUB中的文件,返回本地文件名""" assert name in DATA_HUB, f"{name} 不存在于 {D...
下载并解压zip/tar文件
13,623
import hashlib import os import tarfile import zipfile import requests import numpy as np import pandas as pd import torch from torch import nn from d2l import torch as d2l DATA_HUB = dict() def download(name, cache_dir=os.path.join('..', 'data')): # @save """下载一个DATA_HUB中的文件,返回本地文件名""" assert name in DATA_HUB...
下载DATA_HUB中的所有文件
13,625
import os import sys import numpy as np import torch from d2l import torch as d2l import d2lutil.common as common train_features, test_features = features[:n_train, :], features[n_train:, :] train_labels, test_labels = labels[:n_train], labels[n_train:] train_iter = torch.utils.data.DataLoader(dataset, batch_size, shuf...
null
13,627
import os import sys import numpy as np import torch from d2l import torch as d2l import d2lutil.common as common train_features, test_features = features[:n_train, :], features[n_train:, :] train_labels, test_labels = labels[:n_train], labels[n_train:] def init_params(): w = torch.randn((num_inputs, 1), requires_g...
null
13,628
import math import os import numpy as np import torch from d2l import torch as d2l def normal(x, mu, sigma): p = 1 / math.sqrt(2 * math.pi * sigma ** 2) return p * np.exp((- 0.5 / sigma ** 2) * (x - mu) ** 2)
null
13,629
import sys import os import matplotlib.pyplot as plt import torch import torchvision from torchvision import transforms from torch.utils import data from d2l import torch as d2l import d2lutil.common as common -shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt', 'sneaker', 'bag', 'a...
返回Fashion-MNIST数据集的文本标签。
13,630
import sys import os import matplotlib.pyplot as plt import torch import torchvision from torchvision import transforms from torch.utils import data from d2l import torch as d2l import d2lutil.common as common d2l.use_svg_display() (images), figsize=(12, 12)) for f, img, lbl in zip(figs, images, labels): ...
null
13,631
import sys import os import matplotlib.pyplot as plt import torch import torchvision from torchvision import transforms from torch.utils import data from d2l import torch as d2l import d2lutil.common as common W = torch.normal(0, 0.01, size=(num_inputs, num_outputs), requires_grad=True) b = torch.zeros(num_outputs, req...
null