name stringclasses 844
values | input_types listlengths 0 100 | output_type stringlengths 1 419 | code stringlengths 34 233k | dependencies listlengths 0 6 | lib_used listlengths 0 11 | imports listlengths 0 66 | line_count int64 3 199 | full_code stringlengths 39 1.01M | input_type_defs listlengths 1 12 ⌀ |
|---|---|---|---|---|---|---|---|---|---|
v0 | [
"argparse.Namespace"
] | None | def v0(v1: argparse.Namespace) -> None:
v1.fixed_model_name = None
v1.store_uncompressed = False
v1.dry_run = False | [] | [] | [] | 4 | import argparse
import logging
import os
from typing import List, Optional, Text
from rasa import model
from rasa.cli import SubParsersAction
from rasa.cli.arguments import interactive as arguments
import rasa.cli.train as train
import rasa.cli.utils
from rasa.shared.constants import DEFAULT_ENDPOINTS_PATH, DEFAULT_MO... | null |
v0 | [
"str"
] | typing.Dict[str, str] | def v0(v1: str) -> typing.Dict[str, str]:
v2 = {}
for v3 in v1.split(';'):
(v4, v5, v6) = v3.strip().partition('=')
v2[v4] = v6
return v2 | [] | [] | [] | 6 | import asyncio
import codecs
import dataclasses
import ipaddress
import json as _json
import re
import socket
import typing
import urllib.error
import urllib.parse
import uuid
import bs4
import netifaces
import requests
import tornado.httpclient
from src import IRCBot, utils
REGEX_URL = re.compile("https?://\S+", r... | null |
v63 | [
"v0"
] | v27 | def v63(self, v64: v0) -> v27:
v64.cookies.update(self._cookies)
v65 = v48(v64)
self._cookies.update(v65.cookies)
return v65 | [
{
"name": "v38",
"input_types": [
"typing.Dict[str, str]",
"bytes"
],
"output_type": "typing.Optional[str]",
"code": "def v38(v39: typing.Dict[str, str], v40: bytes) -> typing.Optional[str]:\n if 'Content-Type' in v39:\n v41 = _split_content(v39['Content-Type'])\n if... | [] | [] | 5 | import asyncio
import codecs
import dataclasses
import ipaddress
import json as _json
import re
import socket
import typing
import urllib.error
import urllib.parse
import uuid
import bs4
import netifaces
import requests
import tornado.httpclient
from src import IRCBot, utils
REGEX_URL = re.compile("https?://\S+", r... | [
"@dataclasses.dataclass\nclass v0(object):\n v1: str\n v2: typing.Optional[str] = None\n v3: str = 'GET'\n v4: typing.Dict[str, str] = dataclasses.field(default_factory=dict)\n v5: typing.Any = None\n v6: typing.Dict[str, str] = dataclasses.field(default_factory=dict)\n v7: typing.Dict[str, str... |
v0 | [
"str"
] | typing.List[str] | def v0(v1: str) -> typing.List[str]:
try:
v2 = socket.getaddrinfo(v1, None, 0, socket.SOCK_STREAM)
except:
return []
return [address[-1][0] for v3 in v2] | [] | [
"socket"
] | [
"import socket"
] | 6 | import asyncio
import codecs
import dataclasses
import ipaddress
import json as _json
import re
import socket
import typing
import urllib.error
import urllib.parse
import uuid
import bs4
import netifaces
import requests
import tornado.httpclient
from src import IRCBot, utils
REGEX_URL = re.compile("https?://\S+", r... | null |
v0 | [] | typing.Any | def v0(self) -> typing.Any:
if not self.post_data == None:
if self.content_type == 'application/json' or self.json_body:
return _json.dumps(self.post_data)
else:
return self.post_data
else:
return None | [] | [
"json"
] | [
"import json as _json"
] | 8 | import asyncio
import codecs
import dataclasses
import ipaddress
import json as _json
import re
import socket
import typing
import urllib.error
import urllib.parse
import uuid
import bs4
import netifaces
import requests
import tornado.httpclient
from src import IRCBot, utils
REGEX_URL = re.compile("https?://\S+", r... | null |
v0 | [
"List[int]",
"List[str]",
"List[str]"
] | Any | def v0(v1: List[int], v2: List[str], v3: List[str]):
for v4 in range(1, len(v1)):
v3.append(v3[-1])
v2.append(v2[-1]) | [] | [] | [] | 4 | import os
import time
from abc import ABC, abstractmethod
from enum import Enum
from pathlib import Path
from typing import List, Dict, Tuple, Union
import loguru
import numpy as np
import pandas as pd
from nilmtk import MeterGroup
from pandas import DataFrame
from sklearn.base import ClassifierMixin
from sklearn.metr... | null |
v0 | [
"Union[str, List[str]]",
"Union[str, List[str]]"
] | Any | def v0(v1: Union[str, List[str]], v2: Union[str, List[str]]):
if not isinstance(v2, list):
v2 = [v2]
if not isinstance(v1, list):
v1 = [v1]
return (v1, v2) | [] | [] | [] | 6 | import os
import time
from abc import ABC, abstractmethod
from enum import Enum
from pathlib import Path
from typing import List, Dict, Tuple, Union
import loguru
import numpy as np
import pandas as pd
from nilmtk import MeterGroup
from pandas import DataFrame
from sklearn.base import ClassifierMixin
from sklearn.metr... | null |
v0 | [
"Union[str, ClassifierMixin]"
] | Any | def v0(self, v1: Union[str, ClassifierMixin]):
if isinstance(v1, str):
self.is_deep_classifier = True
self.multilabel_clf = v1
else:
self.multilabel_clf = v1 | [] | [] | [] | 6 | import os
import time
from abc import ABC, abstractmethod
from enum import Enum
from pathlib import Path
from typing import List, Dict, Tuple, Union
import loguru
import numpy as np
import pandas as pd
from nilmtk import MeterGroup
from pandas import DataFrame
from sklearn.base import ClassifierMixin
from sklearn.metr... | null |
v5 | [] | v0 | def v5(self) -> v0:
if self.ts_transformer is None:
raise Exception('TimeSeriesTransformer has not been placed!')
return self.ts_transformer.get_type() | [] | [] | [] | 4 | import os
import time
from abc import ABC, abstractmethod
from enum import Enum
from pathlib import Path
from typing import List, Dict, Tuple, Union
import loguru
import numpy as np
import pandas as pd
from nilmtk import MeterGroup
from pandas import DataFrame
from sklearn.base import ClassifierMixin
from sklearn.metr... | [
"class v0(Enum):\n v1 = 1\n v2 = 2\n v3 = 3\n v4 = 4"
] |
v139 | [
"v0"
] | Any | def v139(self, v140: v0):
self.train_end_date = v140.train_end_date
self.train_start_date = v140.train_start_date
self.train_sample_period = v140.train_sample_period
self.train_building = v140.train_building
self.train_datasource_name = v140.train_datasource.get_name() | [] | [] | [] | 6 | import os
import time
from abc import ABC, abstractmethod
from enum import Enum
from pathlib import Path
from typing import List, Dict, Tuple, Union
import loguru
import numpy as np
import pandas as pd
from nilmtk import MeterGroup
from pandas import DataFrame
from sklearn.base import ClassifierMixin
from sklearn.metr... | [
"class v0:\n\n def __init__(self, v1: Datasource, v2: Union[int, List[int]], v3: Union[str, str], v4: Union[str, List[str]], v5: Union[str, List[str]], v6: int=6, v7: List=None, v8=False):\n \"\"\"\n Constructs a new Environment with the given parameters.\n Args:\n datasource (Dat... |
v0 | [] | None | def v0(self) -> None:
if self.real is not None:
v1 = ['begin', 'end', 'bins']
for v2 in v1:
for (v3, v4) in self.real.items():
assert v2 in v4
assert float(v4['begin']) <= float(v4['end'])
if self.integer is not None:
v5 = ['begin', 'end', 'bin... | [] | [] | [] | 18 | import numpy as np
from collections.abc import Mapping, Iterable
from functools import partial, reduce
import operator
from itertools import product
from typing import Optional, List
from ..space import HyperSpace
class GridSpace(HyperSpace):
def __init__(
self,
real: Optional[dict] = None,
... | null |
v0 | [] | List[dict] | def v0(self) -> List[dict]:
v1 = []
if self.categorical is not None:
for (v2, v3) in self.categorical.items():
v4 = {'name': v2, 'type': 'categorical', 'extra': str(v3)}
v1.append(v4)
if self.real is not None:
for (v2, v3) in self.real.items():
v4 = {'name... | [] | [] | [] | 15 | import numpy as np
from collections.abc import Mapping, Iterable
from functools import partial, reduce
import operator
from itertools import product
from typing import Optional, List
from ..space import HyperSpace
class GridSpace(HyperSpace):
def __init__(
self,
real: Optional[dict] = None,
... | null |
v0 | [
"dict"
] | bool | def v0(self, v1: dict) -> bool:
for (v2, v3) in v1.items():
if not v3 in self.param_range[v2]:
return False
return True | [] | [] | [] | 5 | import numpy as np
from collections.abc import Mapping, Iterable
from functools import partial, reduce
import operator
from itertools import product
from typing import Optional, List
from ..space import HyperSpace
class GridSpace(HyperSpace):
def __init__(
self,
real: Optional[dict] = None,
... | null |
v0 | [] | bool | def v0(self) -> bool:
v1 = self.get_count(self.unit_type, False, include_not_ready=False)
v2 = 0
for v3 in self.cache.own(self.unit_type).not_ready:
v2 = max(v2, v3.build_progress)
v1 += v2
return v1 >= self.count | [] | [] | [] | 7 | import warnings
from sc2 import UnitTypeId
from sharpy.plans.require.require_base import RequireBase
class UnitReady(RequireBase):
"""Condition for how many units must be ready. Used mostly for buildings."""
def __init__(self, unit_type: UnitTypeId, count: float = 1):
assert unit_type is not None and... | null |
v1 | [
"'list'"
] | Any | def v1(v2: 'list'):
v0()
for v3 in v2:
logging.getLogger(v3).setLevel(level=logging.WARNING) | [
{
"name": "v0",
"input_types": [],
"output_type": "Any",
"code": "def v0():\n logging.basicConfig(level=logging.INFO, format='[%(asctime)s %(filename)s:%(lineno)d %(levelname).1s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S')",
"dependencies": []
}
] | [
"logging"
] | [
"import logging"
] | 4 | #!/usr/local/bin/python3
# coding: utf-8
# ytdlbot - utils.py
# 9/1/21 22:50
#
__author__ = "Benny <benny.think@gmail.com>"
import logging
from db import SQLite
def apply_log_formatter():
logging.basicConfig(
level=logging.INFO,
format='[%(asctime)s %(filename)s:%(lineno)d %(levelname).1s] %(m... | null |
v0 | [
"'str'"
] | Any | def v0(v1: 'str'):
if v1.startswith('https://www.youtube.com/') or v1.startswith('https://youtu.be/'):
return True | [] | [] | [] | 3 | #!/usr/local/bin/python3
# coding: utf-8
# ytdlbot - utils.py
# 9/1/21 22:50
#
__author__ = "Benny <benny.think@gmail.com>"
import logging
from db import SQLite
def apply_log_formatter():
logging.basicConfig(
level=logging.INFO,
format='[%(asctime)s %(filename)s:%(lineno)d %(levelname).1s] %(m... | null |
v7 | [
"'str'",
"'str'",
"'list'"
] | Any | def v7(v8: 'str', v9: 'str', v10: 'list'):
v11 = {'high': [], 'medium': [480], 'low': [240, 360]}
v12 = v0(v8)
if v12 and v5(v9):
for v13 in v11.get(v12[1], []):
v10.insert(0, f'bestvideo[ext=mp4][height={v13}]+bestaudio[ext=m4a]')
v10.insert(1, f'bestvideo[vcodec^=avc][heigh... | [
{
"name": "v0",
"input_types": [
"'str'"
],
"output_type": "'tuple'",
"code": "def v0(v1: 'str') -> 'tuple':\n v2 = MySQL()\n v3 = v2.cur\n v3.execute('SELECT * FROM settings WHERE user_id = %s', (v1,))\n v4 = v3.fetchone()\n if v4 is None:\n return (100, 'high', 'vid... | [] | [] | 9 | #!/usr/local/bin/python3
# coding: utf-8
# ytdlbot - utils.py
# 9/1/21 22:50
#
__author__ = "Benny <benny.think@gmail.com>"
import contextlib
import inspect as pyinspect
import logging
import os
import pathlib
import subprocess
import time
import uuid
import ffmpeg
import psutil
from config import ENABLE_CELERY
fr... | null |
v0 | [
"Text",
"Text"
] | Any | def v0(self, v1: Text, v2: Text) -> Any:
if v1 is None:
return None
elif v2 == 'BOOLEAN':
if v1.lower() not in ['true', 'false']:
raise ValueError("{} must have value 'true' or 'false'".format(v1))
return v1.lower() == 'true'
elif v2 == 'INTEGER':
return int(v1)
... | [] | [] | [] | 13 | # coding=utf-8
# Copyright 2021 Google LLC..
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | null |
v0 | [
"Dict[Text, Any]"
] | List[Dict[Text, Any]] | def v0(self, v1: Dict[Text, Any]) -> List[Dict[Text, Any]]:
v2 = [field['name'] for v3 in v1['schema']['fields']]
v4 = [v3['type'] for v3 in v1['schema']['fields']]
v5 = v1.get('rows', [])
v6 = []
for v7 in v5:
v8 = [cell['v'] for v9 in v7['f']]
v10 = [self._str_to_bq_type(value, typ... | [] | [] | [] | 11 | # coding=utf-8
# Copyright 2021 Google LLC..
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | null |
v1 | [
"Dict[ops.Qid, v0]",
"Sequence['cirq.Qid']"
] | None | def v1(self, v2: Dict[ops.Qid, v0], v3: Sequence['cirq.Qid']) -> None:
v4 = self.permutation()
v5 = tuple(v4.keys())
v6 = [v3[v4[i]] for v7 in v5]
v8 = [v2.get(v3[v7]) for v7 in v5]
for (v9, v10) in zip(v6, v8):
if v10 is None:
if v9 in v2:
del v2[v9]
else... | [] | [] | [] | 11 | # Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | [
"v0 = TypeVar('LogicalIndex', int, ops.Qid)"
] |
v11 | [
"'cirq.Circuit'",
"'cirq.Gate'"
] | None | def v11(v12: 'cirq.Circuit', v13: 'cirq.Gate'=ops.SWAP) -> None:
v14 = sorted(v12.all_qubits())
v15 = len(v14)
v16 = {q: i for (v17, v18) in enumerate(v14)}
v1(v16, v12.all_operations())
v19 = {v17: v16[v18] for (v17, v18) in enumerate(v14)}
v20 = LinearPermutationGate(v15, v19, v13)(*v14)
v... | [
{
"name": "v1",
"input_types": [
"Dict[ops.Qid, v0]",
"Sequence['cirq.Qid']"
],
"output_type": "None",
"code": "def v1(self, v2: Dict[ops.Qid, v0], v3: Sequence['cirq.Qid']) -> None:\n v4 = self.permutation()\n v5 = tuple(v4.keys())\n v6 = [v3[v4[i]] for v7 in v5]\n v8 = ... | [] | [] | 8 | # Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | [
"v0 = TypeVar('LogicalIndex', int, ops.Qid)"
] |
v0 | [
"str"
] | Any | def v0(self, v1: str):
v2 = cv2.imread(v1)
self.img = v2
v3 = v2.copy()
(v4, v5, v6) = v3.shape
v7 = cv2.dnn.blobFromImage(v3, 1 / 255, (416, 416), (0, 0, 0), swapRB=True, crop=False)
self.net.setInput(v7)
v8 = self.net.getUnconnectedOutLayersNames()
v9 = self.net.forward(v8)
v10 = [... | [] | [
"cv2",
"numpy"
] | [
"import cv2",
"import numpy as np"
] | 41 | import argparse
import math
import cv2
import easyocr
import numpy as np
def parse_option():
parser = argparse.ArgumentParser('arguments for predictions')
parser.add_argument('--gpu', type=bool, default=True)
parser.add_argument('--pth_image', type=str, default="./images/5.jpg")
parser.add_argument('... | null |
v0 | [
"np.ndarray"
] | None | def v0(self, v1: np.ndarray) -> None:
self.returns = self.returns * self.gamma + v1
self.ret_rms.update(self.returns) | [] | [] | [] | 3 | import pickle
import warnings
from copy import deepcopy
from typing import Any, Dict, List, Optional, Union
import gym
import numpy as np
from stable_baselines3.common import utils
from stable_baselines3.common.running_mean_std import RunningMeanStd
from stable_baselines3.common.vec_env.base_vec_env import (
VecE... | null |
v0 | [
"Union[np.ndarray, Dict[str, np.ndarray]]"
] | Union[np.ndarray, Dict[str, np.ndarray]] | def v0(self, v1: Union[np.ndarray, Dict[str, np.ndarray]]) -> Union[np.ndarray, Dict[str, np.ndarray]]:
v2 = deepcopy(v1)
if self.norm_obs:
if isinstance(v1, dict) and isinstance(self.obs_rms, dict):
for v3 in self.obs_rms.keys():
v2[v3] = self._normalize_obs(v1[v3], self.obs... | [] | [
"copy",
"numpy"
] | [
"from copy import deepcopy",
"import numpy as np"
] | 9 | import pickle
from copy import deepcopy
from typing import Any, Dict, Union
import gym
import numpy as np
from pytorch_agents.common import utils
from pytorch_agents.common.running_mean_std import RunningMeanStd
from pytorch_agents.common.vec_env.base_vec_env import VecEnv, VecEnvStepReturn, VecEnvWrapper
class Vec... | null |
v0 | [
"np.ndarray"
] | np.ndarray | def v0(self, v1: np.ndarray) -> np.ndarray:
if self.norm_reward:
v1 = np.clip(v1 / np.sqrt(self.ret_rms.var + self.epsilon), -self.clip_reward, self.clip_reward)
return v1 | [] | [
"numpy"
] | [
"import numpy as np"
] | 4 | import pickle
import warnings
from copy import deepcopy
from typing import Any, Dict, List, Optional, Union
import gym
import numpy as np
from stable_baselines3.common import utils
from stable_baselines3.common.running_mean_std import RunningMeanStd
from stable_baselines3.common.vec_env.base_vec_env import (
VecE... | null |
v0 | [] | Union[np.ndarray, Dict[str, np.ndarray]] | def v0(self) -> Union[np.ndarray, Dict[str, np.ndarray]]:
v1 = self.venv.reset()
self.old_obs = v1
self.returns = np.zeros(self.num_envs)
if self.training and self.norm_obs:
if isinstance(v1, dict) and isinstance(self.obs_rms, dict):
for v2 in self.obs_rms.keys():
sel... | [] | [
"numpy"
] | [
"import numpy as np"
] | 11 | import pickle
import warnings
from copy import deepcopy
from typing import Any, Dict, List, Optional, Union
import gym
import numpy as np
from stable_baselines3.common import utils
from stable_baselines3.common.running_mean_std import RunningMeanStd
from stable_baselines3.common.vec_env.base_vec_env import VecEnv, Ve... | null |
v0 | [
"str"
] | None | def v0(self, v1: str) -> None:
with open(v1, 'wb') as v2:
pickle.dump(self._listDataObject, v2, pickle.HIGHEST_PROTOCOL)
os.chdir(self._strRootPath) | [] | [
"os",
"pickle"
] | [
"import os",
"import pickle"
] | 4 | """
Module implementing a class for handling all data operations while running the
FreiStat interface
"""
__author__ = "Mark Jasper"
__contact__ = "University of Freiburg, IMTEK, Jochen Kieninger"
__credits__ = "Mark Jasper"
__version__ = "1.0.0"
__maintainer__ = "Mark Jasper"
__email__ = "mark.jasper@imtek.uni-frei... | null |
v7 | [
"plt.Axes",
"Any"
] | Any | def v7(v8: plt.Axes, v9=None):
if v9 is None:
v9 = np.array([v8.get_xlim3d(), v8.get_ylim3d(), v8.get_zlim3d()])
v10 = np.mean(v9, axis=1)
v11 = 0.5 * np.max(np.abs(v9[:, 1] - v9[:, 0]))
v0(v8, v10, v11) | [
{
"name": "v0",
"input_types": [
"Any",
"Any",
"Any"
],
"output_type": "Any",
"code": "def v0(v1, v2, v3):\n (v4, v5, v6) = v2\n v1.set_xlim3d([v4 - v3, v4 + v3])\n v1.set_ylim3d([v5 - v3, v5 + v3])\n v1.set_zlim3d([v6 - v3, v6 + v3])",
"dependencies": []
}
] | [
"numpy"
] | [
"import numpy as np"
] | 6 | import os
import json
import numpy as np
import itertools
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Line3DCollection
from mpl_toolkits import mplot3d
def liver_dump_init(env, name = None):
liver = {'x':[],'Fes':[],'Fis':[],'Ficp':[],'volume':[],'col_p_n':[],'crash':[]}
l... | null |
v0 | [
"str",
"Set[str]",
"Set[str]"
] | str | def v0(v1: str, v2: Set[str], v3: Set[str]) -> str:
v4 = any((word in v1 for v5 in v2))
v6 = any((v5 in v1 for v5 in v3))
if v4 == v6:
v7 = 'neutral'
elif v4:
v7 = 'male'
else:
v7 = 'female'
return v7 | [] | [] | [] | 10 | import json
import logging
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Tuple, List, Set
import torch
from fairseq.hub_utils import GeneratorHubInterface
# Translation data are currently not released
data_path = ...
source_tokenized_path = ... | null |
v0 | [] | List | def v0(self) -> List:
v1 = sum([count for ((v2, v3), v4) in self.average_movements.items() if v2 == 'original_male'])
v5 = sum([v4 for ((v2, v3), v4) in self.average_movements.items() if v2 == 'original_neutral'])
v6 = sum([v4 for ((v2, v3), v4) in self.average_movements.items() if v2 == 'original_female'])... | [] | [] | [] | 8 | import json
import logging
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Tuple, List, Set
import torch
from fairseq.hub_utils import GeneratorHubInterface
# Translation data are currently not released
data_path = ...
source_tokenized_path = ... | null |
v0 | [
"str"
] | str | def v0(self, v1: str) -> str:
v2 = self.hub_interface.tokenize(v1)
return self.hub_interface.apply_bpe(v2) | [] | [] | [] | 3 | import json
import logging
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Tuple, List, Set
import torch
from fairseq.hub_utils import GeneratorHubInterface
# Translation data are currently not released
data_path = ...
source_tokenized_path = ... | null |
v0 | [
"str",
"int"
] | bool | def v0(self, v1: str, v2: int) -> bool:
return self.use_hash_val(v1, v2)
if not v1:
return False
v3 = len(v1)
v4 = set()
for v5 in range(v3 - v2 + 1):
v6 = v1[v5:v5 + v2]
v4.add(v6)
if len(v4) == 2 ** v2:
return True
return False | [] | [] | [] | 12 | # https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/
# Given a binary string s and an integer k.
# Return true if every binary code of length k is a substring of s. Otherwise,
# return false.
################################################################################
# check e... | null |
v0 | [
"DataFrame",
"Any",
"Any"
] | DataFrame | def v0(v1: DataFrame, v2='score_val', v3='pred_time_val_full') -> DataFrame:
v1 = v1.sort_values(by=[v2, v3], ascending=[False, True]).reset_index(drop=True)
v4 = v1.drop_duplicates(subset=[v2])
v5 = []
v6 = None
for (v7, v8) in v4.iterrows():
if v8[v3] is None or v8[v2] is None:
... | [] | [] | [] | 13 | import logging
import multiprocessing
import subprocess
import os
import math
import pickle
import time
import sys
from typing import Callable
from datetime import datetime
import numpy as np
import pandas as pd
import psutil
import scipy.stats
from pandas import DataFrame, Series
from sklearn.model_selection import K... | null |
v0 | [
"DataFrame",
"Any",
"Any"
] | Any | def v0(v1: DataFrame, v2=0, v3=True):
v4 = v1.shape[0]
np.random.seed(v2)
v5 = np.random.randint(0, v4, size=v4)
v6 = v1.iloc[v5]
if v3:
v6.reset_index(inplace=True, drop=True)
return v6 | [] | [
"numpy"
] | [
"import numpy as np"
] | 8 | import logging
import multiprocessing
import subprocess
import os
import math
import pickle
import time
import sys
from typing import Callable
from datetime import datetime
import numpy as np
import pandas as pd
import psutil
import scipy.stats
from pandas import DataFrame, Series
from sklearn.model_selection import K... | null |
v0 | [
"list",
"list"
] | Any | def v0(v1: list, v2: list):
v2 = set(v2)
v3 = set()
for v4 in v1:
if isinstance(v4, tuple):
v5 = v4[0]
v6 = v4[1]
v7 = set(v6)
if len(v7) != len(v6):
raise ValueError(f'Feature list contains duplicate features:\n{v6}')
for v... | [] | [] | [] | 20 | import logging
import multiprocessing
import subprocess
import os
import math
import pickle
import time
import sys
from typing import Callable
from datetime import datetime
import numpy as np
import pandas as pd
import psutil
import scipy.stats
from pandas import DataFrame, Series
from sklearn.model_selection import K... | null |
v7 | [
"dict",
"Any"
] | DataFrame | def v7(v8: dict, v9=False) -> DataFrame:
v10 = list(v8.keys())
v11 = dict()
v12 = dict()
v13 = dict()
v14 = dict()
for v15 in v10:
(v11[v15], v12[v15], v13[v15], v14[v15]) = v0(v8[v15])
if v9:
v11[v15] = v8[v15]
v11 = pd.Series(v11).sort_values(ascending=False)
... | [
{
"name": "v0",
"input_types": [
"list"
],
"output_type": "Any",
"code": "def v0(v1: list):\n v2 = np.mean(v1)\n v3 = len(v1)\n v4 = np.nan\n v5 = np.std(v1, ddof=1) if v3 > 1 else np.nan\n if v5 != np.nan and v5 != 0:\n v6 = v2 / (v5 / math.sqrt(v3))\n v4 = sc... | [
"math",
"numpy",
"pandas"
] | [
"import math",
"import numpy as np",
"import pandas as pd",
"from pandas import DataFrame, Series"
] | 19 | import logging
import multiprocessing
import subprocess
import os
import math
import pickle
import time
import sys
from typing import Callable
from datetime import datetime
import numpy as np
import pandas as pd
import psutil
import scipy.stats
from pandas import DataFrame, Series
from sklearn.model_selection import K... | null |
v0 | [
"Any",
"Any"
] | int | def v0(v1, v2) -> int:
(v3, v4) = v1.get_pos()
(v5, v6) = v2.get_pos()
return abs(v3 - v5) + abs(v4 - v6) | [] | [] | [] | 4 | import pygame
import math
from queue import PriorityQueue
# todo move to config
WIDTH=500
# the more rows the smaller cubes
ROWS = 20
WIN=pygame.display.set_mode((WIDTH,WIDTH))
pygame.display.set_caption("A-star pathing algorithm")
# todo move to separate file
RED = (255, 0, 0) # closed color
GREEN = (0, 255, 0)
BL... | null |
v0 | [
"int"
] | int | def v0(self, v1: int) -> int:
if v1 < 0:
return 0
if v1 < 3:
return v1
(v2, v3) = (1, 2)
for v4 in range(2, v1):
(v2, v3) = (v3, v2 + v3)
return v3 | [] | [] | [] | 9 | class Solution:
def climbStairs(self, n: int) -> int:
if n < 0: return 0
if n < 3: return n
a, b = 1, 2
for _ in range(2, n):
a, b = b, a + b
return b
| null |
v0 | [
"List[int]",
"int"
] | Any | def v0(self, v1: List[int], v2: int):
v2 = min(v2, self.max_seq_length)
v1 = v1[:v2]
v3 = [self.cls_token_id] + v1 + [self.sep_token_id]
v4 = len(v3)
v2 += 2
v5 = [0] * len(v3)
v6 = [1] * len(v3)
v7 = [0] * (v2 - len(v3))
v3 += v7
v5 += v7
v6 += v7
assert len(v3) == v2
... | [] | [
"numpy"
] | [
"import numpy as np"
] | 16 | from torch import Tensor
from torch import nn
from transformers import BertModel, BertTokenizer
import json
from typing import Union, Tuple, List, Dict
import os
import numpy as np
import logging
class BERT(nn.Module):
"""BERT model to generate token embeddings.
Each token is mapped to an output ... | null |
v0 | [
"str"
] | Any | def v0(self, v1: str):
self.camembert.save_pretrained(v1)
self.tokenizer.save_pretrained(v1)
with open(os.path.join(v1, 'sentence_camembert_config.json'), 'w') as v2:
json.dump(self.get_config_dict(), v2, indent=2) | [] | [
"json",
"os"
] | [
"import json",
"import os"
] | 5 | from torch import Tensor
from torch import nn
from transformers import CamembertModel, CamembertTokenizer
import json
from typing import Union, Tuple, List, Dict
import os
import numpy as np
import logging
class CamemBERT(nn.Module):
"""CamemBERT model to generate token embeddings.
Each token is mapped to an... | null |
v0 | [] | None | def v0(self) -> None:
self.add('/admins.super.add', self.add_super_admin())
self.add('/admins.super.remove', self.remove_super_admin())
self.add('/admins.super.list', self.list_super_admin())
self.add('/admins.community.add', self.add_community_admin())
self.add('/admins.community.remove', self.remo... | [] | [] | [] | 9 | """Handler file for all routes pertaining to admins"""
from _main_.utils.route_handler import RouteHandler
import _main_.utils.common as utils
from _main_.utils.common import get_request_contents, rename_field, parse_bool, parse_location, parse_list, validate_fields, parse_string
from api.services.admin import AdminSe... | null |
v0 | [] | None | def v0(self) -> None:
for v1 in self.embedding.parameters():
v1.requires_grad = False
self.embedding.eval()
for v1 in self.decoder.parameters():
v1.requires_grad = False
self.decoder.eval()
for v1 in self.log_softmax.parameters():
v1.require_grad = False
self.log_softmax.... | [] | [] | [] | 10 | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | null |
v0 | [] | None | def v0(self) -> None:
for v1 in self.embedding.parameters():
v1.requires_grad = True
self.embedding.train()
for v1 in self.decoder.parameters():
v1.requires_grad = True
self.decoder.train()
for v1 in self.log_softmax.parameters():
v1.require_grad = True
self.log_softmax.t... | [] | [] | [] | 10 | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | null |
v0 | [] | None | def v0(self) -> None:
self.subscribe_following()
self.subscribe_followed_by()
self.subscribe_stream_changed() | [] | [] | [] | 4 | import requests
from requests.compat import urlencode
from errors import TwitchAPIError
from utils import join_urls
class TwitchSubscribeClient:
"""Streamer event subscriptions manager.
Allows to subscribe to streamer's updates.
Subscribable events:
* Streamer starts following some channe;;
... | null |
v0 | [
"Any",
"Optional[List[str]]",
"bool",
"bool"
] | None | def v0(self, v1, v2: Optional[List[str]]=None, v3: bool=True, v4: bool=False) -> None:
if v2 is None:
v2 = set()
else:
v2 = set(v2)
v2.add('gpdt')
v2.add('bgpdt')
v2.add('eqexin')
v2.add('psds')
if not self.read_mode == v1.read_mode:
self.log.warning('self.read_mode=%... | [] | [] | [] | 33 | #pylint: disable=W0201,W0223,R0901,R0902,R0904
"""
Defines the main OP2 class. Defines:
- read_op2(op2_filename=None, combine=True, subcases=None,
exclude_results=None, include_results=None,
log=None, debug=True, debug_file=None, build_dataframe=False,
skip_undefined_matrices=True... | null |
v0 | [
"str",
"Any",
"Any",
"Any",
"bool",
"bool"
] | bool | def v0(self, v1: str, v2, v3, v4, v5: bool=True, v6: bool=False) -> bool:
v7 = v3.__class__.__name__
v8 = v4.__class__.__name__
if not v7 == v8:
self.log.warning('type(a)=%s type(b)=%s' % (v7, v8))
return False
if v7 == 'PARAM':
return True
if not any((word in v7 for v9 in ['... | [] | [] | [] | 21 | #pylint: disable=W0201,W0223,R0901,R0902,R0904
"""
Defines the main OP2 class. Defines:
- read_op2(op2_filename=None, combine=True, subcases=None,
exclude_results=None, include_results=None,
log=None, debug=True, debug_file=None, build_dataframe=None,
skip_undefined_matrices=True,... | null |
v0 | [
"str"
] | Any | def v0(self, v1: str):
if v1 is None:
return
if v1 == 'nasa95':
self.set_as_nasa95() | [] | [] | [] | 5 | #pylint: disable=W0201,W0223,R0901,R0902,R0904
"""
Defines the main OP2 class. Defines:
- read_op2(op2_filename=None, combine=True, subcases=None,
exclude_results=None, include_results=None,
log=None, debug=True, debug_file=None, build_dataframe=False,
skip_undefined_matrices=True... | null |
v0 | [
"str"
] | None | def v0(self, v1: str) -> None:
if v1.lower() == 'msc':
self.set_as_msc()
elif v1.lower() == 'nx':
self.set_as_nx()
elif v1.lower() == 'autodesk':
self.set_as_autodesk()
elif v1.lower() == 'nasa95':
self.set_as_nasa95()
elif v1.lower() == 'optistruct':
self.set... | [] | [] | [] | 13 | #pylint: disable=W0201,W0223,R0901,R0902,R0904
"""
Defines the main OP2 class. Defines:
- read_op2(op2_filename=None, combine=True, subcases=None,
exclude_results=None, include_results=None,
log=None, debug=True, debug_file=None, build_dataframe=False,
skip_undefined_matrices=True... | null |
v0 | [
"Any"
] | None | def v0(self, v1='') -> None:
if self.is_msc:
self.log.warning(f'switching to NX{v1}')
self.set_as_nx()
self.set_table_type() | [] | [] | [] | 5 | #pylint: disable=W0201,W0223,R0901,R0902,R0904
"""
Defines the main OP2 class. Defines:
- read_op2(op2_filename=None, combine=True, subcases=None,
exclude_results=None, include_results=None,
log=None, debug=True, debug_file=None, build_dataframe=False,
skip_undefined_matrices=True... | null |
v0 | [
"Any"
] | None | def v0(self, v1='') -> None:
if self.is_nx:
self.log.warning(f'switching to MSC{v1}')
self.set_as_msc() | [] | [] | [] | 4 | #pylint: disable=W0201,W0223,R0901,R0902,R0904
"""
Defines the main OP2 class. Defines:
- read_op2(op2_filename=None, combine=True, subcases=None,
exclude_results=None, include_results=None,
log=None, debug=True, debug_file=None, build_dataframe=False,
skip_undefined_matrices=True... | null |
v0 | [
"Optional[List[str]]",
"Optional[List[str]]"
] | None | def v0(self, v1: Optional[List[str]]=None, v2: Optional[List[str]]=None) -> None:
if v1 and v2:
v3 = 'exclude_results or include_results must be None\nexclude_results=%r\ninclude_results=%r\n' % (v1, v2)
raise RuntimeError(v3)
if v1:
self.remove_results(v1)
elif v2:
self.set_... | [] | [] | [] | 8 | #pylint: disable=W0201,W0223,R0901,R0902,R0904
"""
Defines the main OP2 class. Defines:
- read_op2(op2_filename=None, combine=True, subcases=None,
exclude_results=None, include_results=None,
log=None, debug=True, debug_file=None, build_dataframe=None,
skip_undefined_matrices=True,... | null |
v0 | [
"str",
"bool"
] | None | def v0(self, v1: str='model.obj', v2: bool=True) -> None:
if hasattr(self, 'generalized_tables'):
del self.generalized_tables
if hasattr(self, 'op2_reader'):
del self.op2_reader
with open(v1, 'wb') as v3:
dump(self, v3) | [] | [
"pickle"
] | [
"from pickle import load, dump, dumps"
] | 7 | #pylint: disable=W0201,W0223,R0901,R0902,R0904
"""
Defines the main OP2 class. Defines:
- read_op2(op2_filename=None, combine=True, subcases=None,
exclude_results=None, include_results=None,
log=None, debug=True, debug_file=None, build_dataframe=False,
skip_undefined_matrices=True... | null |
v5 | [
"str"
] | None | def v5(self, v6: str='model.obj') -> None:
with open(v6, 'rb') as v7:
v8 = v5(v7)
v9 = ['ask', 'binary_debug', '_close_op2', '_data_factor', '_count', '_results', '_table_mapper', 'additional_matrices', 'apply_symmetry', 'debug_file', 'expected_times', 'f', 'generalized_tables', 'is_all_subcases', 'is_d... | [
{
"name": "v0",
"input_types": [
"str",
"Optional[List[str]]",
"bool"
],
"output_type": "List[str]",
"code": "def v0(self, v1: str='public', v2: Optional[List[str]]=None, v3: bool=False) -> List[str]:\n if v2 is None:\n v2 = []\n v4 = ['object_methods', 'object_att... | [
"pickle"
] | [
"from pickle import load, dump, dumps"
] | 21 | #pylint: disable=W0201,W0223,R0901,R0902,R0904
"""
Defines the main OP2 class. Defines:
- read_op2(op2_filename=None, combine=True, subcases=None,
exclude_results=None, include_results=None,
log=None, debug=True, debug_file=None, build_dataframe=False,
skip_undefined_matrices=True... | null |
v0 | [] | None | def v0(self) -> None:
if hasattr(self, 'subcase'):
del self.subcase
v1 = self.get_table_types()
for v2 in v1:
if v2 in ['params', 'gpdt', 'bgpdt', 'eqexin', 'psds', 'monitor1', 'monitor3'] or v2.startswith('responses.'):
continue
v3 = self.get_result(v2)
try:
... | [] | [] | [] | 19 | #pylint: disable=W0201,W0223,R0901,R0902,R0904
"""
Defines the main OP2 class. Defines:
- read_op2(op2_filename=None, combine=True, subcases=None,
exclude_results=None, include_results=None,
log=None, debug=True, debug_file=None, build_dataframe=False,
skip_undefined_matrices=True... | null |
v0 | [] | None | def v0(self) -> None:
v1 = ['RealEigenvalues', 'ComplexEigenvalues', 'BucklingEigenvalues']
v2 = self.get_table_types()
if len(self.matrices):
for (v3, v4) in sorted(self.matrices.items()):
if hasattr(v4, 'build_dataframe'):
v4.build_dataframe()
else:
... | [] | [] | [] | 47 | #pylint: disable=W0201,W0223,R0901,R0902,R0904
"""
Defines the main OP2 class. Defines:
- read_op2(op2_filename=None, combine=True, subcases=None,
exclude_results=None, include_results=None,
log=None, debug=True, debug_file=None, build_dataframe=False,
skip_undefined_matrices=True... | null |
v0 | [] | List[Tuple[int, int, int, int, int, str]] | def v0(self) -> List[Tuple[int, int, int, int, int, str]]:
v1 = []
v2 = self.get_table_types()
v3 = ['gpdt', 'bgpdt', 'eqexin', 'grid_point_weight', 'psds', 'monitor1', 'monitor3']
for v4 in sorted(v2):
if v4 in v3 or v4.startswith('responses.'):
continue
v5 = self.get_result... | [] | [] | [] | 68 | #pylint: disable=W0201,W0223,R0901,R0902,R0904
"""
Defines the main OP2 class. Defines:
- read_op2(op2_filename=None, combine=True, subcases=None,
exclude_results=None, include_results=None,
log=None, debug=True, debug_file=None, build_dataframe=False,
skip_undefined_matrices=True... | null |
v0 | [] | None | def v0(self) -> None:
self.log.info('---self.subcase_key---')
for (v1, v2) in sorted(self.subcase_key.items()):
if len(v2) == 1:
self.log.info(f'subcase_id={v1} : keys={v2}')
else:
self.log.info(f'subcase_id={v1}')
for v3 in v2:
self.log.info('... | [] | [] | [] | 9 | #pylint: disable=W0201,W0223,R0901,R0902,R0904
"""
Defines the main OP2 class. Defines:
- read_op2(op2_filename=None, combine=True, subcases=None,
exclude_results=None, include_results=None,
log=None, debug=True, debug_file=None, build_dataframe=False,
skip_undefined_matrices=True... | null |
v0 | [
"int",
"int"
] | int | def v0(self, v1: int, v2: int) -> int:
v3 = 0
for v4 in range(32):
v3 += v1 & 1 ^ v2 & 1
v1 >>= 1
v2 >>= 1
return v3 | [] | [] | [] | 7 | class Solution_3:
"""
It optimized the previous solution
It uses the trick:
"""
def hammingDistance(self, x: int, y: int) -> int:
# 1. Find x's and y's bits that are different
x ^= y
# 2. Count the number of 1
bit_1_count = 0
whi... | null |
v0 | [
"str"
] | bool | def v0(v1: str) -> bool:
if re.match('[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', str(v1)):
return True
else:
return False | [] | [
"re"
] | [
"import re"
] | 5 | import re
import subprocess
from collections import defaultdict
from typing import DefaultDict, List
from usb.core import USB
def check_if_sandbox_uuid(sandbox_id: str) -> bool:
"""
Check if sandbox_id is a UUID.
:return: True if sandbox_is is UUID, else if it is a sandbox name -> return false
:rtyp... | null |
v0 | [] | bool | def v0() -> bool:
v1 = subprocess.Popen(['groups'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(v2, v3) = v1.communicate()
v1 = v2.decode('UTF-8').splitlines()
for v4 in v1:
if v4.find('vboxusers') != -1:
return True
return False | [] | [
"subprocess"
] | [
"import subprocess"
] | 8 | import re
import subprocess
from collections import defaultdict
from typing import DefaultDict, List
from usb.core import USB
def check_if_sandbox_uuid(sandbox_id: str) -> bool:
"""
Check if sandbox_id is a UUID.
:return: True if sandbox_is is UUID, else if it is a sandbox name -> return false
:rtyp... | null |
v0 | [] | List[str] | def v0() -> List[str]:
v1 = subprocess.Popen(['ip', 'link', 'show'], stdout=subprocess.PIPE)
v1 = subprocess.check_output(['grep', '-oE', '[0-9]{1,2}:.*: <'], stdin=v1.stdout)
v1 = v1.decode('UTF-8').splitlines()
v1 = [re.search(': (.*):', x).group(1) for v2 in v1]
return v1 | [] | [
"re",
"subprocess"
] | [
"import re",
"import subprocess"
] | 6 | import re
import subprocess
from collections import defaultdict
from typing import DefaultDict, List
from usb.core import USB
def check_if_sandbox_uuid(sandbox_id: str) -> bool:
"""
Check if sandbox_id is a UUID.
:return: True if sandbox_is is UUID, else if it is a sandbox name -> return false
:rtyp... | null |
v0 | [
"str"
] | bool | def v0(v1: str) -> bool:
v2 = subprocess.Popen(['vboxmanage', 'list', 'runningvms'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(v3, v4) = v2.communicate()
v2 = v3.decode('UTF-8').splitlines()
v2 = [re.search('[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', x).group(0) for v5 in v2]
... | [] | [
"re",
"subprocess"
] | [
"import re",
"import subprocess"
] | 9 | import re
import subprocess
from collections import defaultdict
from typing import DefaultDict, List
from usb.core import USB
def check_if_sandbox_uuid(sandbox_id: str) -> bool:
"""
Check if sandbox_id is a UUID.
:return: True if sandbox_is is UUID, else if it is a sandbox name -> return false
:rtyp... | null |
v0 | [] | DefaultDict[int, list] | def v0() -> DefaultDict[int, list]:
v1 = ['idVendor', 'idProduct', 'iSerial', 'bInterfaceClass']
v2 = subprocess.Popen('lsusb', stdout=subprocess.PIPE)
v2 = subprocess.check_output(['grep', '-oE', 'ID [a-f0-9]{4}:[a-f0-9]{4}'], stdin=v2.stdout)
v3 = subprocess.Popen(['lsusb', '-v'], stdout=subprocess.PI... | [] | [
"collections",
"subprocess"
] | [
"import subprocess",
"from collections import defaultdict"
] | 20 | import re
import subprocess
from collections import defaultdict
from typing import DefaultDict, List
from usb.core import USB
def check_if_sandbox_uuid(sandbox_id: str) -> bool:
"""
Check if sandbox_id is a UUID.
:return: True if sandbox_is is UUID, else if it is a sandbox name -> return false
:rtyp... | null |
v0 | [
"List[str]"
] | Any | def v0(self, v1: List[str]):
v2 = []
for v3 in v1:
assert v3 in self.metrics, f'Model {v3} does not exist.'
v2.append(set([agg for v4 in self.aggregators[v3]]))
return set.intersection(*[set(e) for v5 in v2]) | [] | [] | [] | 6 | from __future__ import annotations
import inspect
import json
import logging
import pathlib
from typing import Callable, Collection, Dict, List, Union
import dill
import pandas as pd
from fuzzywuzzy import process
from tqdm import tqdm
from robustnessgym.core.constants import (
ATTACK,
AUGMENTATION,
CURA... | null |
v0 | [
"Dict[str, Dict[str, Callable]]"
] | None | def v0(self, v1: Dict[str, Dict[str, Callable]]) -> None:
for (v2, v3) in v1.items():
for (v4, v5) in v3.items():
assert isinstance(v5, Callable), f'Aggregators must be functions, but {v5} is not.'
v6 = inspect.getfullargspec(v5).args
assert len(v6) == 1, f'Aggregators mu... | [] | [
"inspect",
"typing"
] | [
"import inspect",
"from typing import Callable, Collection, Dict, List, Union"
] | 10 | from __future__ import annotations
import inspect
import json
import logging
import pathlib
from typing import Callable, Collection, Dict, List, Union
import dill
import pandas as pd
from fuzzywuzzy import process
from tqdm import tqdm
from robustnessgym.core.constants import (
ATTACK,
AUGMENTATION,
CURA... | null |
v0 | [] | None | def v0(self) -> None:
for v1 in self.aggregators:
if v1 not in self.metrics:
self.metrics[v1] = {}
for v2 in self.slices:
if str(v2.identifier) not in self.metrics[v1]:
self.metrics[v1][str(v2.identifier)] = {}
for (v3, v4) in self.aggregators[v1].... | [] | [] | [] | 10 | from __future__ import annotations
import inspect
import json
import logging
import pathlib
from typing import Callable, Collection, Dict, List, Union
import dill
import pandas as pd
from fuzzywuzzy import process
from tqdm import tqdm
from robustnessgym.core.constants import (
ATTACK,
AUGMENTATION,
CURA... | null |
v0 | [
"Dict[str, Any]"
] | None | def v0(self, v1: Dict[str, Any]) -> None:
self._learn_model.load_state_dict(v1['model'])
self._target_model.load_state_dict(v1['target_model'])
self._optimizer_actor.load_state_dict(v1['optimizer_actor'])
self._optimizer_critic.load_state_dict(v1['optimizer_critic']) | [] | [] | [] | 5 | from typing import List, Dict, Any, Tuple, Union
from collections import namedtuple
import torch
import copy
from ding.torch_utils import Adam, to_device
from ding.rl_utils import v_1step_td_data, v_1step_td_error, get_train_sample
from ding.model import model_wrap
from ding.utils import POLICY_REGISTRY
from ding.util... | null |
v0 | [
"np.ndarray",
"np.ndarray"
] | NoReturn | def v0(self, v1: np.ndarray, v2: np.ndarray) -> NoReturn:
v3 = -1
for v4 in range(v1.shape[1]):
for v5 in [-1, 1]:
(v6, v7) = self._find_threshold(v1[:, v4], v2, v5)
if v3 == -1 or v7 < v3:
self.j_ = v4
self.sign_ = v5
self.threshol... | [] | [] | [] | 10 | from __future__ import annotations
from typing import Tuple, NoReturn
from ...base import BaseEstimator
import numpy as np
from itertools import product
class DecisionStump(BaseEstimator):
"""
A decision stump classifier for {-1,1} labels according to the CART algorithm
Attributes
----------
self... | null |
v0 | [
"np.ndarray",
"np.ndarray",
"int"
] | Tuple[float, float] | def v0(self, v1: np.ndarray, v2: np.ndarray, v3: int) -> Tuple[float, float]:
v4 = v1.argsort()
(v1, v2) = (v1[v4], v2[v4])
v1 = np.concatenate([[-np.inf], v1, [np.inf]])
v2 = np.concatenate([[-v3], v2, [v3]])
v5 = np.cumsum(v2[::-1])[::-1] * v3 + np.cumsum(np.insert(v2[:-1], 0, 0)) * -v3
v6 = n... | [] | [
"numpy"
] | [
"import numpy as np"
] | 10 | from __future__ import annotations
from typing import Tuple, NoReturn
import pandas as pd
from ...base import BaseEstimator
import numpy as np
class DecisionStump(BaseEstimator):
"""
A decision stump classifier for {-1,1} labels according to the CART algorithm
Attributes
----------
self.thresh... | null |
v0 | [] | str | def v0(self) -> str:
self.run(f'docker run -td --init --net=none --hostname {self.name} --name {self.name} --sysctl net.ipv6.conf.all.disable_ipv6=0 --privileged {self.image} /bin/bash')
self.pid = self.get_pid()
return self.pid | [] | [] | [] | 4 | import json
import logging
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING, Callable, Dict, Optional
from core import utils
from core.emulator.distributed import DistributedServer
from core.emulator.enumerations import NodeTypes
from core.errors import CoreCommandError... | null |
v0 | [] | str | def v0(self) -> str:
v1 = f"docker inspect -f '{{{{.State.Pid}}}}' {self.name}"
v2 = self.run(v1)
self.pid = v2
logging.debug('node(%s) pid: %s', self.name, self.pid)
return v2 | [] | [
"logging"
] | [
"import logging"
] | 6 | import json
import logging
import os
from tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING, Callable, Dict
from core import utils
from core.emulator.distributed import DistributedServer
from core.emulator.enumerations import NodeTypes
from core.errors import CoreCommandError
from core.nodes.base imp... | null |
v0 | [
"str",
"str"
] | str | def v0(self, v1: str, v2: str) -> str:
v3 = f'docker cp {v1} {self.name}:{v2}'
return self.run(v3) | [] | [] | [] | 3 | import json
import logging
import os
from tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING, Callable, Dict
from core import utils
from core.emulator.distributed import DistributedServer
from core.emulator.enumerations import NodeTypes
from core.errors import CoreCommandError
from core.nodes.base imp... | null |
v0 | [] | None | def v0(self) -> None:
if not self.up:
return
with self.lock:
self._netif.clear()
self.client.stop_container()
self.up = False | [] | [] | [] | 7 | import json
import logging
import os
from tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING, Callable, Dict
from core import utils
from core.emulator.distributed import DistributedServer
from core.emulator.enumerations import NodeTypes
from core.errors import CoreCommandError
from core.nodes.base imp... | null |
v0 | [
"str"
] | None | def v0(self, v1: str) -> None:
logging.debug('creating node dir: %s', v1)
v2 = f'mkdir -p {v1}'
self.cmd(v2) | [] | [
"logging"
] | [
"import logging"
] | 4 | import json
import logging
import os
from tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING, Callable, Dict
from core import utils
from core.emulator.distributed import DistributedServer
from core.emulator.enumerations import NodeTypes
from core.errors import CoreCommandError
from core.nodes.base imp... | null |
v0 | [
"str",
"str"
] | None | def v0(self, v1: str, v2: str) -> None:
logging.debug('mounting source(%s) target(%s)', v1, v2)
raise Exception('not supported') | [] | [
"logging"
] | [
"import logging"
] | 3 | import json
import logging
import os
from tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING, Callable, Dict
from core import utils
from core.emulator.distributed import DistributedServer
from core.emulator.enumerations import NodeTypes
from core.errors import CoreCommandError
from core.nodes.base imp... | null |
v0 | [
"str",
"str",
"int"
] | None | def v0(self, v1: str, v2: str, v3: int=420) -> None:
logging.debug('nodefile filename(%s) mode(%s)', v1, v3)
v4 = os.path.dirname(v1)
v5 = NamedTemporaryFile(delete=False)
v5.write(v2.encode('utf-8'))
v5.close()
if v4:
self.cmd(f'mkdir -m {493:o} -p {v4}')
if self.server is not None:... | [] | [
"logging",
"os",
"tempfile"
] | [
"import logging",
"import os",
"from tempfile import NamedTemporaryFile"
] | 16 | import json
import logging
import os
from tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING, Callable, Dict
from core import utils
from core.emulator.distributed import DistributedServer
from core.emulator.enumerations import NodeTypes
from core.errors import CoreCommandError
from core.nodes.base imp... | null |
v0 | [
"str",
"str",
"int"
] | None | def v0(self, v1: str, v2: str, v3: int=None) -> None:
logging.info('node file copy file(%s) source(%s) mode(%s)', v1, v2, v3)
v4 = os.path.dirname(v1)
self.cmd(f'mkdir -p {v4}')
if self.server is None:
v5 = v2
else:
v6 = NamedTemporaryFile(delete=False)
v5 = v6.name
s... | [] | [
"logging",
"os",
"tempfile"
] | [
"import logging",
"import os",
"from tempfile import NamedTemporaryFile"
] | 12 | import json
import logging
import os
from tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING, Callable, Dict
from core import utils
from core.emulator.distributed import DistributedServer
from core.emulator.enumerations import NodeTypes
from core.errors import CoreCommandError
from core.nodes.base imp... | null |
v0 | [
"requests.models.Response"
] | None | def v0(self, v1: requests.models.Response) -> None:
try:
v1.raise_for_status()
except HTTPError:
self.log.error(v1.json().get('exception'))
raise | [] | [
"requests"
] | [
"import requests",
"from requests import HTTPError"
] | 6 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | null |
v10 | [
"str",
"bool"
] | T.List[str] | def v10(v11: str='1.8.2', v12: bool=False) -> T.List[str]:
v13 = v0(v11, v12)
return v13[0] if v13 else None | [
{
"name": "v0",
"input_types": [
"str",
"bool"
],
"output_type": "T.Tuple[T.List[str], str]",
"code": "def v0(v1: str='1.8.2', v2: bool=False) -> T.Tuple[T.List[str], str]:\n v3 = os.environ.get('NINJA', None)\n for v4 in [v3] if v3 else ['ninja', 'ninja-build', 'samu']:\n ... | [
"os"
] | [
"import os, platform, re, sys, shutil"
] | 3 | # Copyright 2012-2020 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agree... | null |
v0 | [
"str"
] | T.List[str] | def v0(v1: str) -> T.List[str]:
v2 = ['', '-12', '12', '-11', '11', '-10', '10', '-9', '90', '-8', '80', '-7', '70', '-6.0', '60', '-5.0', '50', '-4.0', '40', '-3.9', '39', '-3.8', '38', '-3.7', '37', '-3.6', '36', '-3.5', '35', '-13', '-devel']
v3 = []
for v4 in v2:
v3.append(v1 + v4)
return v3 | [] | [] | [] | 6 | # Copyright 2012-2020 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agree... | null |
v5 | [] | typing.List[str] | def v5() -> typing.List[str]:
v6 = v0('clang-format')
for v7 in v6:
v8 = shutil.which(v7)
if v8 is not None:
return [v8]
return [] | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "typing.List[str]",
"code": "def v0(v1: str) -> typing.List[str]:\n v2 = ['', '-9', '90', '-8', '80', '-7', '70', '-6.0', '60', '-5.0', '50', '-4.0', '40', '-3.9', '39', '-3.8', '38', '-3.7', '37', '-3.6', '36', '-3.5', '35', '-10... | [
"shutil"
] | [
"import os, platform, re, sys, shutil, subprocess, typing"
] | 7 | # Copyright 2012-2016 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agree... | null |
v3 | [
"v0"
] | str | def v3(v4: v0) -> str:
v5 = v1()
if v5 == 'x86':
return v5
for v6 in v4.values():
if v6.id == 'msvc' and (v6.target == 'x86' or v6.target == '80x86'):
return 'x86'
if v6.id == 'clang-cl' and v6.target == 'x86':
return 'x86'
if v6.id == 'gcc' and v6.has... | [
{
"name": "v1",
"input_types": [],
"output_type": "Any",
"code": "def v1():\n v2 = os.environ.get('PROCESSOR_ARCHITEW6432', '').lower()\n if not v2:\n try:\n v2 = os.environ['PROCESSOR_ARCHITECTURE'].lower()\n except KeyError:\n raise EnvironmentException('U... | [
"os"
] | [
"import os, platform, re, sys, shutil, subprocess"
] | 12 | # Copyright 2012-2016 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agree... | [
"v0 = T.Dict[str, Compiler]"
] |
v0 | [
"str"
] | str | def v0(v1: str) -> str:
v2 = re.compile('\n (?<! # Zero-width negative lookbehind assertion\n (\n \\d # One digit\n | \\. # Or one period\n ) # One occurrence\n )\n # Following pattern must not follow a digit or period\n (\... | [] | [
"re"
] | [
"import os, platform, re, sys, shutil, subprocess"
] | 10 | # Copyright 2012-2016 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agree... | null |
v0 | [] | str | def v0(self) -> str:
v1 = self.machines.host
if v1.is_windows() or v1.is_cygwin():
return self.get_bindir()
return self.get_libdir() | [] | [] | [] | 5 | # Copyright 2012-2016 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agree... | null |
v0 | [
"List[Tuple[str, str, Any]]"
] | List[str] | def v0(self, v1: List[Tuple[str, str, Any]]) -> List[str]:
try:
return self._table.files_by_partitions(v1)
except TypeError:
raise ValueError('Only the type String is currently allowed inside the partition filters.') | [] | [] | [] | 5 | import os
import warnings
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, List, Optional, Tuple
from urllib.parse import urlparse
import pyarrow
from pyarrow.dataset import dataset, partitioning
from pyarrow.fs import FileSystem
if TYPE_CHECKING:
import pandas
from .deltalake import RawD... | null |
v0 | [] | List[str] | def v0(self) -> List[str]:
warnings.warn('Call to deprecated method file_paths. Please use file_uris instead.', category=DeprecationWarning, stacklevel=2)
return self.file_uris() | [] | [
"warnings"
] | [
"import warnings"
] | 3 | import os
import warnings
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, List, Optional, Tuple
from urllib.parse import urlparse
import pyarrow
from pyarrow.dataset import dataset, partitioning
from pyarrow.fs import FileSystem
if TYPE_CHECKING:
import pandas
from .deltalake import RawD... | null |
v0 | [
"Optional[int]",
"bool"
] | List[str] | def v0(self, v1: Optional[int]=None, v2: bool=True) -> List[str]:
if v1:
if v1 < 0:
raise ValueError('The retention periods should be positive.')
return self._table.vacuum(v2, v1) | [] | [] | [] | 5 | import json
import os
import warnings
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse
import pyarrow
from pyarrow.dataset import dataset, partitioning
from pyarrow.fs import FileSystem
if TYPE_CHECKING:
import pandas
from .dat... | null |
v0 | [
"'asyncio.AbstractEventLoop'"
] | Any | def v0(v1: 'asyncio.AbstractEventLoop'):
asyncio.set_event_loop(v1)
if not v1.is_running():
v1.run_forever()
v2 = asyncio.all_tasks(v1)
if v2:
v1.run_until_complete(asyncio.gather(*v2))
if not v1.is_running():
v1.close() | [] | [
"asyncio"
] | [
"import asyncio"
] | 9 | __copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import asyncio
import functools
import inspect
import threading
from concurrent import futures
from grpc import _server
from ..helper import use_uvloop, typename
from ..logging import default_logger
use_uvloop()
... | null |
v0 | [
"Any",
"Any"
] | bool | def v0(v1: Any, v2: Any) -> bool:
v3 = v1 == v2
v4 = v1 != v2
assert v3 != v4, f'__eq__ is inconsistent with __ne__ between {v1!r} and {v2!r}'
return v3 | [] | [] | [] | 5 | # Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | null |
v0 | [] | str | def v0(self) -> str:
v1 = [self.id, self.version]
if self.full_version:
v1 += ['"%s"' % self.full_version]
return '(%s)' % ' '.join(v1) | [] | [] | [] | 5 | # Copyright 2012-2019 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agree... | null |
v0 | [
"str",
"str"
] | str | def v0(v1: str, v2: str) -> str:
if v2 is not None and v1.startswith(v2):
return v1[len(v2):]
else:
return v1 | [] | [] | [] | 5 | import os
import os.path
import sys
import traceback
from collections import OrderedDict, defaultdict
from typing import Tuple, List, TypeVar, Set, Dict, Optional
T = TypeVar('T')
class ErrorInfo:
"""Representation of a single error message."""
# Description of a sequence of imports that refer to the sour... | null |
v0 | [] | None | def v0(self) -> None:
if self.save_path is not None:
os.makedirs(self.save_path, exist_ok=True)
if self.latest_path is not None:
os.makedirs(self.latest_path, exist_ok=True) | [] | [
"os"
] | [
"import os"
] | 5 | import os
import gym
import gym
from gym import wrappers, logger
import gym_panda
from gym_panda.wrapper_env.wrapper import *
# import gym_circle_move
import numpy as np
import matplotlib.pyplot as plt
from stable_baselines import DDPG,PPO2,TRPO
from stable_baselines.common.policies import MlpPolicy
from stable_base... | null |
v0 | [
"List[str]",
"List[List[rlt.BaseDataClass]]",
"List[Dict[str, rlt.IdMappingConfig]]"
] | Any | def v0(v1: List[str], v2: List[List[rlt.BaseDataClass]], v3: List[Dict[str, rlt.IdMappingConfig]]):
v4 = {}
for (v5, v6, v7) in zip(v1, v2, v3):
v4[v5] = {config.feature_id: v7[config.id_mapping_name].embedding_table_size for v8 in v6}
return v4 | [] | [] | [] | 5 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import logging
from typing import Callable, List, Optional, Dict
import numpy as np
import reagent.core.types as rlt
import torch
import torch.nn.functional as F
from reagent.core.parameters import NormalizationData
from re... | null |
v0 | [
"List[str]",
"List[List[rlt.BaseDataClass]]"
] | Any | def v0(v1: List[str], v2: List[List[rlt.BaseDataClass]]):
v3 = {}
for (v4, v5) in zip(v1, v2):
v3[v4] = {config.feature_id: config.name for v6 in v5}
return v3 | [] | [] | [] | 5 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import logging
from typing import Callable, List, Optional, Dict
import numpy as np
import reagent.core.types as rlt
import torch
import torch.nn.functional as F
from reagent.core.parameters import NormalizationData
from re... | null |
v0 | [
"List[torch.Tensor]",
"int"
] | List[torch.Tensor] | def v0(v1: List[torch.Tensor], v2: int) -> List[torch.Tensor]:
if v2 >= 0:
v3 = [v2] * len(v1)
else:
v3 = [t.ndim + v2 for v4 in v1]
v5 = [list(v4.shape) for v4 in v1]
for (v6, v7) in zip(v5, v3):
v6.pop(v7)
v8 = [tuple(v6) for v6 in v5]
v9 = torch.broadcast_shapes(*v8)
... | [] | [
"torch"
] | [
"import torch",
"import torch.nn.functional as F"
] | 15 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import logging
from typing import Callable, List, Optional, Dict
import numpy as np
import reagent.core.types as rlt
import torch
import torch.nn.functional as F
from reagent.core.parameters import NormalizationData
from re... | null |
v0 | [
"Mapping"
] | str | def v0(v1: Mapping) -> str:
v2 = ', '.join(('{}: {}'.format(repr(k)[1:] if repr(k).startswith("u'") or repr(k).startswith('u"') else repr(k), v) for (v3, v4) in sorted(v1.items())))
return '{%s}' % v2 | [] | [] | [] | 3 | r"""Colored strings that behave mostly like strings
>>> s = fmtstr("Hey there!", 'red')
>>> s
red('Hey there!')
>>> s[4:7]
red('the')
>>> red_on_blue = fmtstr('hello', 'red', 'on_blue')
>>> blue_on_red = fmtstr('there', fg='blue', bg='red')
>>> green = fmtstr('!', 'green')
>>> full = red_on_blue + ' ' + blue_on_red + ... | null |
v0 | [
"int",
"int",
"int",
"int"
] | int | def v0(v1: int, v2: int, v3: int, v4: int) -> int:
if v2 <= v3 or v1 >= v4:
return 0
elif v3 <= v1 <= v4:
return min(v2, v4) - v1
elif v3 <= v2 <= v4:
return v2 - max(v1, v3)
elif v1 >= v3 and v2 <= v4:
return v2 - v1
else:
assert False | [] | [] | [] | 11 | r"""Colored strings that behave mostly like strings
>>> s = fmtstr("Hey there!", 'red')
>>> s
red('Hey there!')
>>> s[4:7]
red('the')
>>> red_on_blue = fmtstr('hello', 'red', 'on_blue')
>>> blue_on_red = fmtstr('there', fg='blue', bg='red')
>>> green = fmtstr('!', 'green')
>>> full = red_on_blue + ' ' + blue_on_red + ... | null |
v0 | [
"int",
"Union[int, slice]"
] | slice | def v0(v1: int, v2: Union[int, slice]) -> slice:
v3 = False
if isinstance(v2, int):
v3 = True
v2 = slice(v2, v2 + 1)
if v2.start is None:
v2 = slice(0, v2.stop, v2.step)
if v2.stop is None:
v2 = slice(v2.start, v1, v2.step)
if v2.start < -1:
v2 = slice(v1 - v2... | [] | [] | [] | 19 | r"""Colored strings that behave mostly like strings
>>> s = fmtstr("Hey there!", 'red')
>>> s
red('Hey there!')
>>> s[4:7]
red('the')
>>> red_on_blue = fmtstr('hello', 'red', 'on_blue')
>>> blue_on_red = fmtstr('there', fg='blue', bg='red')
>>> green = fmtstr('!', 'green')
>>> full = red_on_blue + ' ' + blue_on_red + ... | null |
v0 | [
"int",
"int",
"Union[str, 'FmtStr']",
"int"
] | 'FmtStr' | def v0(self, v1: int, v2: int, v3: Union[str, 'FmtStr'], v4: int) -> 'FmtStr':
if len(self) < v1:
v3 = ' ' * (v1 - len(self)) + v3
if len(self) > v2:
v3 = v3 + ' ' * (v2 - v1 - len(v3))
assert len(v3) == v2 - v1, (len(v3), v1, v2)
v5 = self.splice(v3, v1, v2)
if len(v5) > v4:
... | [] | [] | [] | 10 | r"""Colored strings that behave mostly like strings
>>> s = fmtstr("Hey there!", 'red')
>>> s
red('Hey there!')
>>> s[4:7]
red('the')
>>> red_on_blue = fmtstr('hello', 'red', 'on_blue')
>>> blue_on_red = fmtstr('there', fg='blue', bg='red')
>>> green = fmtstr('!', 'green')
>>> full = red_on_blue + ' ' + blue_on_red + ... | null |
v0 | [
"Optional[str]",
"Optional[int]",
"bool"
] | List['FmtStr'] | def v0(self, v1: Optional[str]=None, v2: Optional[int]=None, v3: bool=False) -> List['FmtStr']:
if v2 is not None:
raise NotImplementedError('no maxsplit yet')
v4 = self.s
if v1 is None:
v1 = '\\s+'
elif not v3:
v1 = re.escape(v1)
v5 = list(re.finditer(v1, v4))
return [se... | [] | [
"re"
] | [
"import re"
] | 10 | r"""Colored strings that behave mostly like strings
>>> s = fmtstr("Hey there!", 'red')
>>> s
red('Hey there!')
>>> s[4:7]
red('the')
>>> red_on_blue = fmtstr('hello', 'red', 'on_blue')
>>> blue_on_red = fmtstr('there', fg='blue', bg='red')
>>> green = fmtstr('!', 'green')
>>> full = red_on_blue + ' ' + blue_on_red + ... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.