partition stringclasses 3 values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1 value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | download_data | Download `url` to destination `fname`. | fastai/datasets.py | def download_data(url:str, fname:PathOrStr=None, data:bool=True, ext:str='.tgz') -> Path:
"Download `url` to destination `fname`."
fname = Path(ifnone(fname, _url2tgz(url, data, ext=ext)))
os.makedirs(fname.parent, exist_ok=True)
if not fname.exists():
print(f'Downloading {url}')
download_url(f'{url}{ext}', fname)
return fname | def download_data(url:str, fname:PathOrStr=None, data:bool=True, ext:str='.tgz') -> Path:
"Download `url` to destination `fname`."
fname = Path(ifnone(fname, _url2tgz(url, data, ext=ext)))
os.makedirs(fname.parent, exist_ok=True)
if not fname.exists():
print(f'Downloading {url}')
download_url(f'{url}{ext}', fname)
return fname | [
"Download",
"url",
"to",
"destination",
"fname",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/datasets.py#L206-L213 | [
"def",
"download_data",
"(",
"url",
":",
"str",
",",
"fname",
":",
"PathOrStr",
"=",
"None",
",",
"data",
":",
"bool",
"=",
"True",
",",
"ext",
":",
"str",
"=",
"'.tgz'",
")",
"->",
"Path",
":",
"fname",
"=",
"Path",
"(",
"ifnone",
"(",
"fname",
",",
"_url2tgz",
"(",
"url",
",",
"data",
",",
"ext",
"=",
"ext",
")",
")",
")",
"os",
".",
"makedirs",
"(",
"fname",
".",
"parent",
",",
"exist_ok",
"=",
"True",
")",
"if",
"not",
"fname",
".",
"exists",
"(",
")",
":",
"print",
"(",
"f'Downloading {url}'",
")",
"download_url",
"(",
"f'{url}{ext}'",
",",
"fname",
")",
"return",
"fname"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | untar_data | Download `url` to `fname` if `dest` doesn't exist, and un-tgz to folder `dest`. | fastai/datasets.py | def untar_data(url:str, fname:PathOrStr=None, dest:PathOrStr=None, data=True, force_download=False) -> Path:
"Download `url` to `fname` if `dest` doesn't exist, and un-tgz to folder `dest`."
dest = url2path(url, data) if dest is None else Path(dest)/url2name(url)
fname = Path(ifnone(fname, _url2tgz(url, data)))
if force_download or (fname.exists() and url in _checks and _check_file(fname) != _checks[url]):
print(f"A new version of the {'dataset' if data else 'model'} is available.")
if fname.exists(): os.remove(fname)
if dest.exists(): shutil.rmtree(dest)
if not dest.exists():
fname = download_data(url, fname=fname, data=data)
if url in _checks:
assert _check_file(fname) == _checks[url], f"Downloaded file {fname} does not match checksum expected! Remove that file from {Config().data_archive_path()} and try your code again."
tarfile.open(fname, 'r:gz').extractall(dest.parent)
return dest | def untar_data(url:str, fname:PathOrStr=None, dest:PathOrStr=None, data=True, force_download=False) -> Path:
"Download `url` to `fname` if `dest` doesn't exist, and un-tgz to folder `dest`."
dest = url2path(url, data) if dest is None else Path(dest)/url2name(url)
fname = Path(ifnone(fname, _url2tgz(url, data)))
if force_download or (fname.exists() and url in _checks and _check_file(fname) != _checks[url]):
print(f"A new version of the {'dataset' if data else 'model'} is available.")
if fname.exists(): os.remove(fname)
if dest.exists(): shutil.rmtree(dest)
if not dest.exists():
fname = download_data(url, fname=fname, data=data)
if url in _checks:
assert _check_file(fname) == _checks[url], f"Downloaded file {fname} does not match checksum expected! Remove that file from {Config().data_archive_path()} and try your code again."
tarfile.open(fname, 'r:gz').extractall(dest.parent)
return dest | [
"Download",
"url",
"to",
"fname",
"if",
"dest",
"doesn",
"t",
"exist",
"and",
"un",
"-",
"tgz",
"to",
"folder",
"dest",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/datasets.py#L221-L234 | [
"def",
"untar_data",
"(",
"url",
":",
"str",
",",
"fname",
":",
"PathOrStr",
"=",
"None",
",",
"dest",
":",
"PathOrStr",
"=",
"None",
",",
"data",
"=",
"True",
",",
"force_download",
"=",
"False",
")",
"->",
"Path",
":",
"dest",
"=",
"url2path",
"(",
"url",
",",
"data",
")",
"if",
"dest",
"is",
"None",
"else",
"Path",
"(",
"dest",
")",
"/",
"url2name",
"(",
"url",
")",
"fname",
"=",
"Path",
"(",
"ifnone",
"(",
"fname",
",",
"_url2tgz",
"(",
"url",
",",
"data",
")",
")",
")",
"if",
"force_download",
"or",
"(",
"fname",
".",
"exists",
"(",
")",
"and",
"url",
"in",
"_checks",
"and",
"_check_file",
"(",
"fname",
")",
"!=",
"_checks",
"[",
"url",
"]",
")",
":",
"print",
"(",
"f\"A new version of the {'dataset' if data else 'model'} is available.\"",
")",
"if",
"fname",
".",
"exists",
"(",
")",
":",
"os",
".",
"remove",
"(",
"fname",
")",
"if",
"dest",
".",
"exists",
"(",
")",
":",
"shutil",
".",
"rmtree",
"(",
"dest",
")",
"if",
"not",
"dest",
".",
"exists",
"(",
")",
":",
"fname",
"=",
"download_data",
"(",
"url",
",",
"fname",
"=",
"fname",
",",
"data",
"=",
"data",
")",
"if",
"url",
"in",
"_checks",
":",
"assert",
"_check_file",
"(",
"fname",
")",
"==",
"_checks",
"[",
"url",
"]",
",",
"f\"Downloaded file {fname} does not match checksum expected! Remove that file from {Config().data_archive_path()} and try your code again.\"",
"tarfile",
".",
"open",
"(",
"fname",
",",
"'r:gz'",
")",
".",
"extractall",
"(",
"dest",
".",
"parent",
")",
"return",
"dest"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | Config.get_key | Get the path to `key` in the config file. | fastai/datasets.py | def get_key(cls, key):
"Get the path to `key` in the config file."
return cls.get().get(key, cls.DEFAULT_CONFIG.get(key,None)) | def get_key(cls, key):
"Get the path to `key` in the config file."
return cls.get().get(key, cls.DEFAULT_CONFIG.get(key,None)) | [
"Get",
"the",
"path",
"to",
"key",
"in",
"the",
"config",
"file",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/datasets.py#L140-L142 | [
"def",
"get_key",
"(",
"cls",
",",
"key",
")",
":",
"return",
"cls",
".",
"get",
"(",
")",
".",
"get",
"(",
"key",
",",
"cls",
".",
"DEFAULT_CONFIG",
".",
"get",
"(",
"key",
",",
"None",
")",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | Config.get | Retrieve the `Config` in `fpath`. | fastai/datasets.py | def get(cls, fpath=None, create_missing=True):
"Retrieve the `Config` in `fpath`."
fpath = _expand_path(fpath or cls.DEFAULT_CONFIG_PATH)
if not fpath.exists() and create_missing: cls.create(fpath)
assert fpath.exists(), f'Could not find config at: {fpath}. Please create'
with open(fpath, 'r') as yaml_file: return yaml.safe_load(yaml_file) | def get(cls, fpath=None, create_missing=True):
"Retrieve the `Config` in `fpath`."
fpath = _expand_path(fpath or cls.DEFAULT_CONFIG_PATH)
if not fpath.exists() and create_missing: cls.create(fpath)
assert fpath.exists(), f'Could not find config at: {fpath}. Please create'
with open(fpath, 'r') as yaml_file: return yaml.safe_load(yaml_file) | [
"Retrieve",
"the",
"Config",
"in",
"fpath",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/datasets.py#L165-L170 | [
"def",
"get",
"(",
"cls",
",",
"fpath",
"=",
"None",
",",
"create_missing",
"=",
"True",
")",
":",
"fpath",
"=",
"_expand_path",
"(",
"fpath",
"or",
"cls",
".",
"DEFAULT_CONFIG_PATH",
")",
"if",
"not",
"fpath",
".",
"exists",
"(",
")",
"and",
"create_missing",
":",
"cls",
".",
"create",
"(",
"fpath",
")",
"assert",
"fpath",
".",
"exists",
"(",
")",
",",
"f'Could not find config at: {fpath}. Please create'",
"with",
"open",
"(",
"fpath",
",",
"'r'",
")",
"as",
"yaml_file",
":",
"return",
"yaml",
".",
"safe_load",
"(",
"yaml_file",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | Config.create | Creates a `Config` from `fpath`. | fastai/datasets.py | def create(cls, fpath):
"Creates a `Config` from `fpath`."
fpath = _expand_path(fpath)
assert(fpath.suffix == '.yml')
if fpath.exists(): return
fpath.parent.mkdir(parents=True, exist_ok=True)
with open(fpath, 'w') as yaml_file:
yaml.dump(cls.DEFAULT_CONFIG, yaml_file, default_flow_style=False) | def create(cls, fpath):
"Creates a `Config` from `fpath`."
fpath = _expand_path(fpath)
assert(fpath.suffix == '.yml')
if fpath.exists(): return
fpath.parent.mkdir(parents=True, exist_ok=True)
with open(fpath, 'w') as yaml_file:
yaml.dump(cls.DEFAULT_CONFIG, yaml_file, default_flow_style=False) | [
"Creates",
"a",
"Config",
"from",
"fpath",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/datasets.py#L173-L180 | [
"def",
"create",
"(",
"cls",
",",
"fpath",
")",
":",
"fpath",
"=",
"_expand_path",
"(",
"fpath",
")",
"assert",
"(",
"fpath",
".",
"suffix",
"==",
"'.yml'",
")",
"if",
"fpath",
".",
"exists",
"(",
")",
":",
"return",
"fpath",
".",
"parent",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"with",
"open",
"(",
"fpath",
",",
"'w'",
")",
"as",
"yaml_file",
":",
"yaml",
".",
"dump",
"(",
"cls",
".",
"DEFAULT_CONFIG",
",",
"yaml_file",
",",
"default_flow_style",
"=",
"False",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | MixUpCallback.on_batch_begin | Applies mixup to `last_input` and `last_target` if `train`. | fastai/callbacks/mixup.py | def on_batch_begin(self, last_input, last_target, train, **kwargs):
"Applies mixup to `last_input` and `last_target` if `train`."
if not train: return
lambd = np.random.beta(self.alpha, self.alpha, last_target.size(0))
lambd = np.concatenate([lambd[:,None], 1-lambd[:,None]], 1).max(1)
lambd = last_input.new(lambd)
shuffle = torch.randperm(last_target.size(0)).to(last_input.device)
x1, y1 = last_input[shuffle], last_target[shuffle]
if self.stack_x:
new_input = [last_input, last_input[shuffle], lambd]
else:
new_input = (last_input * lambd.view(lambd.size(0),1,1,1) + x1 * (1-lambd).view(lambd.size(0),1,1,1))
if self.stack_y:
new_target = torch.cat([last_target[:,None].float(), y1[:,None].float(), lambd[:,None].float()], 1)
else:
if len(last_target.shape) == 2:
lambd = lambd.unsqueeze(1).float()
new_target = last_target.float() * lambd + y1.float() * (1-lambd)
return {'last_input': new_input, 'last_target': new_target} | def on_batch_begin(self, last_input, last_target, train, **kwargs):
"Applies mixup to `last_input` and `last_target` if `train`."
if not train: return
lambd = np.random.beta(self.alpha, self.alpha, last_target.size(0))
lambd = np.concatenate([lambd[:,None], 1-lambd[:,None]], 1).max(1)
lambd = last_input.new(lambd)
shuffle = torch.randperm(last_target.size(0)).to(last_input.device)
x1, y1 = last_input[shuffle], last_target[shuffle]
if self.stack_x:
new_input = [last_input, last_input[shuffle], lambd]
else:
new_input = (last_input * lambd.view(lambd.size(0),1,1,1) + x1 * (1-lambd).view(lambd.size(0),1,1,1))
if self.stack_y:
new_target = torch.cat([last_target[:,None].float(), y1[:,None].float(), lambd[:,None].float()], 1)
else:
if len(last_target.shape) == 2:
lambd = lambd.unsqueeze(1).float()
new_target = last_target.float() * lambd + y1.float() * (1-lambd)
return {'last_input': new_input, 'last_target': new_target} | [
"Applies",
"mixup",
"to",
"last_input",
"and",
"last_target",
"if",
"train",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/mixup.py#L15-L33 | [
"def",
"on_batch_begin",
"(",
"self",
",",
"last_input",
",",
"last_target",
",",
"train",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"train",
":",
"return",
"lambd",
"=",
"np",
".",
"random",
".",
"beta",
"(",
"self",
".",
"alpha",
",",
"self",
".",
"alpha",
",",
"last_target",
".",
"size",
"(",
"0",
")",
")",
"lambd",
"=",
"np",
".",
"concatenate",
"(",
"[",
"lambd",
"[",
":",
",",
"None",
"]",
",",
"1",
"-",
"lambd",
"[",
":",
",",
"None",
"]",
"]",
",",
"1",
")",
".",
"max",
"(",
"1",
")",
"lambd",
"=",
"last_input",
".",
"new",
"(",
"lambd",
")",
"shuffle",
"=",
"torch",
".",
"randperm",
"(",
"last_target",
".",
"size",
"(",
"0",
")",
")",
".",
"to",
"(",
"last_input",
".",
"device",
")",
"x1",
",",
"y1",
"=",
"last_input",
"[",
"shuffle",
"]",
",",
"last_target",
"[",
"shuffle",
"]",
"if",
"self",
".",
"stack_x",
":",
"new_input",
"=",
"[",
"last_input",
",",
"last_input",
"[",
"shuffle",
"]",
",",
"lambd",
"]",
"else",
":",
"new_input",
"=",
"(",
"last_input",
"*",
"lambd",
".",
"view",
"(",
"lambd",
".",
"size",
"(",
"0",
")",
",",
"1",
",",
"1",
",",
"1",
")",
"+",
"x1",
"*",
"(",
"1",
"-",
"lambd",
")",
".",
"view",
"(",
"lambd",
".",
"size",
"(",
"0",
")",
",",
"1",
",",
"1",
",",
"1",
")",
")",
"if",
"self",
".",
"stack_y",
":",
"new_target",
"=",
"torch",
".",
"cat",
"(",
"[",
"last_target",
"[",
":",
",",
"None",
"]",
".",
"float",
"(",
")",
",",
"y1",
"[",
":",
",",
"None",
"]",
".",
"float",
"(",
")",
",",
"lambd",
"[",
":",
",",
"None",
"]",
".",
"float",
"(",
")",
"]",
",",
"1",
")",
"else",
":",
"if",
"len",
"(",
"last_target",
".",
"shape",
")",
"==",
"2",
":",
"lambd",
"=",
"lambd",
".",
"unsqueeze",
"(",
"1",
")",
".",
"float",
"(",
")",
"new_target",
"=",
"last_target",
".",
"float",
"(",
")",
"*",
"lambd",
"+",
"y1",
".",
"float",
"(",
")",
"*",
"(",
"1",
"-",
"lambd",
")",
"return",
"{",
"'last_input'",
":",
"new_input",
",",
"'last_target'",
":",
"new_target",
"}"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | make_date | Make sure `df[field_name]` is of the right date type. | fastai/tabular/transform.py | def make_date(df:DataFrame, date_field:str):
"Make sure `df[field_name]` is of the right date type."
field_dtype = df[date_field].dtype
if isinstance(field_dtype, pd.core.dtypes.dtypes.DatetimeTZDtype):
field_dtype = np.datetime64
if not np.issubdtype(field_dtype, np.datetime64):
df[date_field] = pd.to_datetime(df[date_field], infer_datetime_format=True) | def make_date(df:DataFrame, date_field:str):
"Make sure `df[field_name]` is of the right date type."
field_dtype = df[date_field].dtype
if isinstance(field_dtype, pd.core.dtypes.dtypes.DatetimeTZDtype):
field_dtype = np.datetime64
if not np.issubdtype(field_dtype, np.datetime64):
df[date_field] = pd.to_datetime(df[date_field], infer_datetime_format=True) | [
"Make",
"sure",
"df",
"[",
"field_name",
"]",
"is",
"of",
"the",
"right",
"date",
"type",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/transform.py#L10-L16 | [
"def",
"make_date",
"(",
"df",
":",
"DataFrame",
",",
"date_field",
":",
"str",
")",
":",
"field_dtype",
"=",
"df",
"[",
"date_field",
"]",
".",
"dtype",
"if",
"isinstance",
"(",
"field_dtype",
",",
"pd",
".",
"core",
".",
"dtypes",
".",
"dtypes",
".",
"DatetimeTZDtype",
")",
":",
"field_dtype",
"=",
"np",
".",
"datetime64",
"if",
"not",
"np",
".",
"issubdtype",
"(",
"field_dtype",
",",
"np",
".",
"datetime64",
")",
":",
"df",
"[",
"date_field",
"]",
"=",
"pd",
".",
"to_datetime",
"(",
"df",
"[",
"date_field",
"]",
",",
"infer_datetime_format",
"=",
"True",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | cyclic_dt_feat_names | Return feature names of date/time cycles as produced by `cyclic_dt_features`. | fastai/tabular/transform.py | def cyclic_dt_feat_names(time:bool=True, add_linear:bool=False)->List[str]:
"Return feature names of date/time cycles as produced by `cyclic_dt_features`."
fs = ['cos','sin']
attr = [f'{r}_{f}' for r in 'weekday day_month month_year day_year'.split() for f in fs]
if time: attr += [f'{r}_{f}' for r in 'hour clock min sec'.split() for f in fs]
if add_linear: attr.append('year_lin')
return attr | def cyclic_dt_feat_names(time:bool=True, add_linear:bool=False)->List[str]:
"Return feature names of date/time cycles as produced by `cyclic_dt_features`."
fs = ['cos','sin']
attr = [f'{r}_{f}' for r in 'weekday day_month month_year day_year'.split() for f in fs]
if time: attr += [f'{r}_{f}' for r in 'hour clock min sec'.split() for f in fs]
if add_linear: attr.append('year_lin')
return attr | [
"Return",
"feature",
"names",
"of",
"date",
"/",
"time",
"cycles",
"as",
"produced",
"by",
"cyclic_dt_features",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/transform.py#L18-L24 | [
"def",
"cyclic_dt_feat_names",
"(",
"time",
":",
"bool",
"=",
"True",
",",
"add_linear",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"str",
"]",
":",
"fs",
"=",
"[",
"'cos'",
",",
"'sin'",
"]",
"attr",
"=",
"[",
"f'{r}_{f}'",
"for",
"r",
"in",
"'weekday day_month month_year day_year'",
".",
"split",
"(",
")",
"for",
"f",
"in",
"fs",
"]",
"if",
"time",
":",
"attr",
"+=",
"[",
"f'{r}_{f}'",
"for",
"r",
"in",
"'hour clock min sec'",
".",
"split",
"(",
")",
"for",
"f",
"in",
"fs",
"]",
"if",
"add_linear",
":",
"attr",
".",
"append",
"(",
"'year_lin'",
")",
"return",
"attr"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | cyclic_dt_features | Calculate the cos and sin of date/time cycles. | fastai/tabular/transform.py | def cyclic_dt_features(d:Union[date,datetime], time:bool=True, add_linear:bool=False)->List[float]:
"Calculate the cos and sin of date/time cycles."
tt,fs = d.timetuple(), [np.cos, np.sin]
day_year,days_month = tt.tm_yday, calendar.monthrange(d.year, d.month)[1]
days_year = 366 if calendar.isleap(d.year) else 365
rs = d.weekday()/7, (d.day-1)/days_month, (d.month-1)/12, (day_year-1)/days_year
feats = [f(r * 2 * np.pi) for r in rs for f in fs]
if time and isinstance(d, datetime) and type(d) != date:
rs = tt.tm_hour/24, tt.tm_hour%12/12, tt.tm_min/60, tt.tm_sec/60
feats += [f(r * 2 * np.pi) for r in rs for f in fs]
if add_linear:
if type(d) == date: feats.append(d.year + rs[-1])
else:
secs_in_year = (datetime(d.year+1, 1, 1) - datetime(d.year, 1, 1)).total_seconds()
feats.append(d.year + ((d - datetime(d.year, 1, 1)).total_seconds() / secs_in_year))
return feats | def cyclic_dt_features(d:Union[date,datetime], time:bool=True, add_linear:bool=False)->List[float]:
"Calculate the cos and sin of date/time cycles."
tt,fs = d.timetuple(), [np.cos, np.sin]
day_year,days_month = tt.tm_yday, calendar.monthrange(d.year, d.month)[1]
days_year = 366 if calendar.isleap(d.year) else 365
rs = d.weekday()/7, (d.day-1)/days_month, (d.month-1)/12, (day_year-1)/days_year
feats = [f(r * 2 * np.pi) for r in rs for f in fs]
if time and isinstance(d, datetime) and type(d) != date:
rs = tt.tm_hour/24, tt.tm_hour%12/12, tt.tm_min/60, tt.tm_sec/60
feats += [f(r * 2 * np.pi) for r in rs for f in fs]
if add_linear:
if type(d) == date: feats.append(d.year + rs[-1])
else:
secs_in_year = (datetime(d.year+1, 1, 1) - datetime(d.year, 1, 1)).total_seconds()
feats.append(d.year + ((d - datetime(d.year, 1, 1)).total_seconds() / secs_in_year))
return feats | [
"Calculate",
"the",
"cos",
"and",
"sin",
"of",
"date",
"/",
"time",
"cycles",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/transform.py#L26-L41 | [
"def",
"cyclic_dt_features",
"(",
"d",
":",
"Union",
"[",
"date",
",",
"datetime",
"]",
",",
"time",
":",
"bool",
"=",
"True",
",",
"add_linear",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"float",
"]",
":",
"tt",
",",
"fs",
"=",
"d",
".",
"timetuple",
"(",
")",
",",
"[",
"np",
".",
"cos",
",",
"np",
".",
"sin",
"]",
"day_year",
",",
"days_month",
"=",
"tt",
".",
"tm_yday",
",",
"calendar",
".",
"monthrange",
"(",
"d",
".",
"year",
",",
"d",
".",
"month",
")",
"[",
"1",
"]",
"days_year",
"=",
"366",
"if",
"calendar",
".",
"isleap",
"(",
"d",
".",
"year",
")",
"else",
"365",
"rs",
"=",
"d",
".",
"weekday",
"(",
")",
"/",
"7",
",",
"(",
"d",
".",
"day",
"-",
"1",
")",
"/",
"days_month",
",",
"(",
"d",
".",
"month",
"-",
"1",
")",
"/",
"12",
",",
"(",
"day_year",
"-",
"1",
")",
"/",
"days_year",
"feats",
"=",
"[",
"f",
"(",
"r",
"*",
"2",
"*",
"np",
".",
"pi",
")",
"for",
"r",
"in",
"rs",
"for",
"f",
"in",
"fs",
"]",
"if",
"time",
"and",
"isinstance",
"(",
"d",
",",
"datetime",
")",
"and",
"type",
"(",
"d",
")",
"!=",
"date",
":",
"rs",
"=",
"tt",
".",
"tm_hour",
"/",
"24",
",",
"tt",
".",
"tm_hour",
"%",
"12",
"/",
"12",
",",
"tt",
".",
"tm_min",
"/",
"60",
",",
"tt",
".",
"tm_sec",
"/",
"60",
"feats",
"+=",
"[",
"f",
"(",
"r",
"*",
"2",
"*",
"np",
".",
"pi",
")",
"for",
"r",
"in",
"rs",
"for",
"f",
"in",
"fs",
"]",
"if",
"add_linear",
":",
"if",
"type",
"(",
"d",
")",
"==",
"date",
":",
"feats",
".",
"append",
"(",
"d",
".",
"year",
"+",
"rs",
"[",
"-",
"1",
"]",
")",
"else",
":",
"secs_in_year",
"=",
"(",
"datetime",
"(",
"d",
".",
"year",
"+",
"1",
",",
"1",
",",
"1",
")",
"-",
"datetime",
"(",
"d",
".",
"year",
",",
"1",
",",
"1",
")",
")",
".",
"total_seconds",
"(",
")",
"feats",
".",
"append",
"(",
"d",
".",
"year",
"+",
"(",
"(",
"d",
"-",
"datetime",
"(",
"d",
".",
"year",
",",
"1",
",",
"1",
")",
")",
".",
"total_seconds",
"(",
")",
"/",
"secs_in_year",
")",
")",
"return",
"feats"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | add_cyclic_datepart | Helper function that adds trigonometric date/time features to a date in the column `field_name` of `df`. | fastai/tabular/transform.py | def add_cyclic_datepart(df:DataFrame, field_name:str, prefix:str=None, drop:bool=True, time:bool=False, add_linear:bool=False):
"Helper function that adds trigonometric date/time features to a date in the column `field_name` of `df`."
make_date(df, field_name)
field = df[field_name]
prefix = ifnone(prefix, re.sub('[Dd]ate$', '', field_name))
series = field.apply(partial(cyclic_dt_features, time=time, add_linear=add_linear))
columns = [prefix + c for c in cyclic_dt_feat_names(time, add_linear)]
df_feats = pd.DataFrame([item for item in series], columns=columns, index=series.index)
df = pd.concat([df, df_feats], axis=1)
if drop: df.drop(field_name, axis=1, inplace=True)
return df | def add_cyclic_datepart(df:DataFrame, field_name:str, prefix:str=None, drop:bool=True, time:bool=False, add_linear:bool=False):
"Helper function that adds trigonometric date/time features to a date in the column `field_name` of `df`."
make_date(df, field_name)
field = df[field_name]
prefix = ifnone(prefix, re.sub('[Dd]ate$', '', field_name))
series = field.apply(partial(cyclic_dt_features, time=time, add_linear=add_linear))
columns = [prefix + c for c in cyclic_dt_feat_names(time, add_linear)]
df_feats = pd.DataFrame([item for item in series], columns=columns, index=series.index)
df = pd.concat([df, df_feats], axis=1)
if drop: df.drop(field_name, axis=1, inplace=True)
return df | [
"Helper",
"function",
"that",
"adds",
"trigonometric",
"date",
"/",
"time",
"features",
"to",
"a",
"date",
"in",
"the",
"column",
"field_name",
"of",
"df",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/transform.py#L43-L53 | [
"def",
"add_cyclic_datepart",
"(",
"df",
":",
"DataFrame",
",",
"field_name",
":",
"str",
",",
"prefix",
":",
"str",
"=",
"None",
",",
"drop",
":",
"bool",
"=",
"True",
",",
"time",
":",
"bool",
"=",
"False",
",",
"add_linear",
":",
"bool",
"=",
"False",
")",
":",
"make_date",
"(",
"df",
",",
"field_name",
")",
"field",
"=",
"df",
"[",
"field_name",
"]",
"prefix",
"=",
"ifnone",
"(",
"prefix",
",",
"re",
".",
"sub",
"(",
"'[Dd]ate$'",
",",
"''",
",",
"field_name",
")",
")",
"series",
"=",
"field",
".",
"apply",
"(",
"partial",
"(",
"cyclic_dt_features",
",",
"time",
"=",
"time",
",",
"add_linear",
"=",
"add_linear",
")",
")",
"columns",
"=",
"[",
"prefix",
"+",
"c",
"for",
"c",
"in",
"cyclic_dt_feat_names",
"(",
"time",
",",
"add_linear",
")",
"]",
"df_feats",
"=",
"pd",
".",
"DataFrame",
"(",
"[",
"item",
"for",
"item",
"in",
"series",
"]",
",",
"columns",
"=",
"columns",
",",
"index",
"=",
"series",
".",
"index",
")",
"df",
"=",
"pd",
".",
"concat",
"(",
"[",
"df",
",",
"df_feats",
"]",
",",
"axis",
"=",
"1",
")",
"if",
"drop",
":",
"df",
".",
"drop",
"(",
"field_name",
",",
"axis",
"=",
"1",
",",
"inplace",
"=",
"True",
")",
"return",
"df"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | add_datepart | Helper function that adds columns relevant to a date in the column `field_name` of `df`. | fastai/tabular/transform.py | def add_datepart(df:DataFrame, field_name:str, prefix:str=None, drop:bool=True, time:bool=False):
"Helper function that adds columns relevant to a date in the column `field_name` of `df`."
make_date(df, field_name)
field = df[field_name]
prefix = ifnone(prefix, re.sub('[Dd]ate$', '', field_name))
attr = ['Year', 'Month', 'Week', 'Day', 'Dayofweek', 'Dayofyear', 'Is_month_end', 'Is_month_start',
'Is_quarter_end', 'Is_quarter_start', 'Is_year_end', 'Is_year_start']
if time: attr = attr + ['Hour', 'Minute', 'Second']
for n in attr: df[prefix + n] = getattr(field.dt, n.lower())
df[prefix + 'Elapsed'] = field.astype(np.int64) // 10 ** 9
if drop: df.drop(field_name, axis=1, inplace=True)
return df | def add_datepart(df:DataFrame, field_name:str, prefix:str=None, drop:bool=True, time:bool=False):
"Helper function that adds columns relevant to a date in the column `field_name` of `df`."
make_date(df, field_name)
field = df[field_name]
prefix = ifnone(prefix, re.sub('[Dd]ate$', '', field_name))
attr = ['Year', 'Month', 'Week', 'Day', 'Dayofweek', 'Dayofyear', 'Is_month_end', 'Is_month_start',
'Is_quarter_end', 'Is_quarter_start', 'Is_year_end', 'Is_year_start']
if time: attr = attr + ['Hour', 'Minute', 'Second']
for n in attr: df[prefix + n] = getattr(field.dt, n.lower())
df[prefix + 'Elapsed'] = field.astype(np.int64) // 10 ** 9
if drop: df.drop(field_name, axis=1, inplace=True)
return df | [
"Helper",
"function",
"that",
"adds",
"columns",
"relevant",
"to",
"a",
"date",
"in",
"the",
"column",
"field_name",
"of",
"df",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/transform.py#L55-L66 | [
"def",
"add_datepart",
"(",
"df",
":",
"DataFrame",
",",
"field_name",
":",
"str",
",",
"prefix",
":",
"str",
"=",
"None",
",",
"drop",
":",
"bool",
"=",
"True",
",",
"time",
":",
"bool",
"=",
"False",
")",
":",
"make_date",
"(",
"df",
",",
"field_name",
")",
"field",
"=",
"df",
"[",
"field_name",
"]",
"prefix",
"=",
"ifnone",
"(",
"prefix",
",",
"re",
".",
"sub",
"(",
"'[Dd]ate$'",
",",
"''",
",",
"field_name",
")",
")",
"attr",
"=",
"[",
"'Year'",
",",
"'Month'",
",",
"'Week'",
",",
"'Day'",
",",
"'Dayofweek'",
",",
"'Dayofyear'",
",",
"'Is_month_end'",
",",
"'Is_month_start'",
",",
"'Is_quarter_end'",
",",
"'Is_quarter_start'",
",",
"'Is_year_end'",
",",
"'Is_year_start'",
"]",
"if",
"time",
":",
"attr",
"=",
"attr",
"+",
"[",
"'Hour'",
",",
"'Minute'",
",",
"'Second'",
"]",
"for",
"n",
"in",
"attr",
":",
"df",
"[",
"prefix",
"+",
"n",
"]",
"=",
"getattr",
"(",
"field",
".",
"dt",
",",
"n",
".",
"lower",
"(",
")",
")",
"df",
"[",
"prefix",
"+",
"'Elapsed'",
"]",
"=",
"field",
".",
"astype",
"(",
"np",
".",
"int64",
")",
"//",
"10",
"**",
"9",
"if",
"drop",
":",
"df",
".",
"drop",
"(",
"field_name",
",",
"axis",
"=",
"1",
",",
"inplace",
"=",
"True",
")",
"return",
"df"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | cont_cat_split | Helper function that returns column names of cont and cat variables from given df. | fastai/tabular/transform.py | def cont_cat_split(df, max_card=20, dep_var=None)->Tuple[List,List]:
"Helper function that returns column names of cont and cat variables from given df."
cont_names, cat_names = [], []
for label in df:
if label == dep_var: continue
if df[label].dtype == int and df[label].unique().shape[0] > max_card or df[label].dtype == float: cont_names.append(label)
else: cat_names.append(label)
return cont_names, cat_names | def cont_cat_split(df, max_card=20, dep_var=None)->Tuple[List,List]:
"Helper function that returns column names of cont and cat variables from given df."
cont_names, cat_names = [], []
for label in df:
if label == dep_var: continue
if df[label].dtype == int and df[label].unique().shape[0] > max_card or df[label].dtype == float: cont_names.append(label)
else: cat_names.append(label)
return cont_names, cat_names | [
"Helper",
"function",
"that",
"returns",
"column",
"names",
"of",
"cont",
"and",
"cat",
"variables",
"from",
"given",
"df",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/transform.py#L106-L113 | [
"def",
"cont_cat_split",
"(",
"df",
",",
"max_card",
"=",
"20",
",",
"dep_var",
"=",
"None",
")",
"->",
"Tuple",
"[",
"List",
",",
"List",
"]",
":",
"cont_names",
",",
"cat_names",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"label",
"in",
"df",
":",
"if",
"label",
"==",
"dep_var",
":",
"continue",
"if",
"df",
"[",
"label",
"]",
".",
"dtype",
"==",
"int",
"and",
"df",
"[",
"label",
"]",
".",
"unique",
"(",
")",
".",
"shape",
"[",
"0",
"]",
">",
"max_card",
"or",
"df",
"[",
"label",
"]",
".",
"dtype",
"==",
"float",
":",
"cont_names",
".",
"append",
"(",
"label",
")",
"else",
":",
"cat_names",
".",
"append",
"(",
"label",
")",
"return",
"cont_names",
",",
"cat_names"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | Categorify.apply_train | Transform `self.cat_names` columns in categorical. | fastai/tabular/transform.py | def apply_train(self, df:DataFrame):
"Transform `self.cat_names` columns in categorical."
self.categories = {}
for n in self.cat_names:
df.loc[:,n] = df.loc[:,n].astype('category').cat.as_ordered()
self.categories[n] = df[n].cat.categories | def apply_train(self, df:DataFrame):
"Transform `self.cat_names` columns in categorical."
self.categories = {}
for n in self.cat_names:
df.loc[:,n] = df.loc[:,n].astype('category').cat.as_ordered()
self.categories[n] = df[n].cat.categories | [
"Transform",
"self",
".",
"cat_names",
"columns",
"in",
"categorical",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/transform.py#L135-L140 | [
"def",
"apply_train",
"(",
"self",
",",
"df",
":",
"DataFrame",
")",
":",
"self",
".",
"categories",
"=",
"{",
"}",
"for",
"n",
"in",
"self",
".",
"cat_names",
":",
"df",
".",
"loc",
"[",
":",
",",
"n",
"]",
"=",
"df",
".",
"loc",
"[",
":",
",",
"n",
"]",
".",
"astype",
"(",
"'category'",
")",
".",
"cat",
".",
"as_ordered",
"(",
")",
"self",
".",
"categories",
"[",
"n",
"]",
"=",
"df",
"[",
"n",
"]",
".",
"cat",
".",
"categories"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | Normalize.apply_train | Compute the means and stds of `self.cont_names` columns to normalize them. | fastai/tabular/transform.py | def apply_train(self, df:DataFrame):
"Compute the means and stds of `self.cont_names` columns to normalize them."
self.means,self.stds = {},{}
for n in self.cont_names:
assert is_numeric_dtype(df[n]), (f"""Cannot normalize '{n}' column as it isn't numerical.
Are you sure it doesn't belong in the categorical set of columns?""")
self.means[n],self.stds[n] = df[n].mean(),df[n].std()
df[n] = (df[n]-self.means[n]) / (1e-7 + self.stds[n]) | def apply_train(self, df:DataFrame):
"Compute the means and stds of `self.cont_names` columns to normalize them."
self.means,self.stds = {},{}
for n in self.cont_names:
assert is_numeric_dtype(df[n]), (f"""Cannot normalize '{n}' column as it isn't numerical.
Are you sure it doesn't belong in the categorical set of columns?""")
self.means[n],self.stds[n] = df[n].mean(),df[n].std()
df[n] = (df[n]-self.means[n]) / (1e-7 + self.stds[n]) | [
"Compute",
"the",
"means",
"and",
"stds",
"of",
"self",
".",
"cont_names",
"columns",
"to",
"normalize",
"them",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/transform.py#L183-L190 | [
"def",
"apply_train",
"(",
"self",
",",
"df",
":",
"DataFrame",
")",
":",
"self",
".",
"means",
",",
"self",
".",
"stds",
"=",
"{",
"}",
",",
"{",
"}",
"for",
"n",
"in",
"self",
".",
"cont_names",
":",
"assert",
"is_numeric_dtype",
"(",
"df",
"[",
"n",
"]",
")",
",",
"(",
"f\"\"\"Cannot normalize '{n}' column as it isn't numerical.\n Are you sure it doesn't belong in the categorical set of columns?\"\"\"",
")",
"self",
".",
"means",
"[",
"n",
"]",
",",
"self",
".",
"stds",
"[",
"n",
"]",
"=",
"df",
"[",
"n",
"]",
".",
"mean",
"(",
")",
",",
"df",
"[",
"n",
"]",
".",
"std",
"(",
")",
"df",
"[",
"n",
"]",
"=",
"(",
"df",
"[",
"n",
"]",
"-",
"self",
".",
"means",
"[",
"n",
"]",
")",
"/",
"(",
"1e-7",
"+",
"self",
".",
"stds",
"[",
"n",
"]",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | def_emb_sz | Pick an embedding size for `n` depending on `classes` if not given in `sz_dict`. | fastai/tabular/data.py | def def_emb_sz(classes, n, sz_dict=None):
"Pick an embedding size for `n` depending on `classes` if not given in `sz_dict`."
sz_dict = ifnone(sz_dict, {})
n_cat = len(classes[n])
sz = sz_dict.get(n, int(emb_sz_rule(n_cat))) # rule of thumb
return n_cat,sz | def def_emb_sz(classes, n, sz_dict=None):
"Pick an embedding size for `n` depending on `classes` if not given in `sz_dict`."
sz_dict = ifnone(sz_dict, {})
n_cat = len(classes[n])
sz = sz_dict.get(n, int(emb_sz_rule(n_cat))) # rule of thumb
return n_cat,sz | [
"Pick",
"an",
"embedding",
"size",
"for",
"n",
"depending",
"on",
"classes",
"if",
"not",
"given",
"in",
"sz_dict",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/data.py#L17-L22 | [
"def",
"def_emb_sz",
"(",
"classes",
",",
"n",
",",
"sz_dict",
"=",
"None",
")",
":",
"sz_dict",
"=",
"ifnone",
"(",
"sz_dict",
",",
"{",
"}",
")",
"n_cat",
"=",
"len",
"(",
"classes",
"[",
"n",
"]",
")",
"sz",
"=",
"sz_dict",
".",
"get",
"(",
"n",
",",
"int",
"(",
"emb_sz_rule",
"(",
"n_cat",
")",
")",
")",
"# rule of thumb",
"return",
"n_cat",
",",
"sz"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | tabular_learner | Get a `Learner` using `data`, with `metrics`, including a `TabularModel` created using the remaining params. | fastai/tabular/data.py | def tabular_learner(data:DataBunch, layers:Collection[int], emb_szs:Dict[str,int]=None, metrics=None,
ps:Collection[float]=None, emb_drop:float=0., y_range:OptRange=None, use_bn:bool=True, **learn_kwargs):
"Get a `Learner` using `data`, with `metrics`, including a `TabularModel` created using the remaining params."
emb_szs = data.get_emb_szs(ifnone(emb_szs, {}))
model = TabularModel(emb_szs, len(data.cont_names), out_sz=data.c, layers=layers, ps=ps, emb_drop=emb_drop,
y_range=y_range, use_bn=use_bn)
return Learner(data, model, metrics=metrics, **learn_kwargs) | def tabular_learner(data:DataBunch, layers:Collection[int], emb_szs:Dict[str,int]=None, metrics=None,
ps:Collection[float]=None, emb_drop:float=0., y_range:OptRange=None, use_bn:bool=True, **learn_kwargs):
"Get a `Learner` using `data`, with `metrics`, including a `TabularModel` created using the remaining params."
emb_szs = data.get_emb_szs(ifnone(emb_szs, {}))
model = TabularModel(emb_szs, len(data.cont_names), out_sz=data.c, layers=layers, ps=ps, emb_drop=emb_drop,
y_range=y_range, use_bn=use_bn)
return Learner(data, model, metrics=metrics, **learn_kwargs) | [
"Get",
"a",
"Learner",
"using",
"data",
"with",
"metrics",
"including",
"a",
"TabularModel",
"created",
"using",
"the",
"remaining",
"params",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/data.py#L170-L176 | [
"def",
"tabular_learner",
"(",
"data",
":",
"DataBunch",
",",
"layers",
":",
"Collection",
"[",
"int",
"]",
",",
"emb_szs",
":",
"Dict",
"[",
"str",
",",
"int",
"]",
"=",
"None",
",",
"metrics",
"=",
"None",
",",
"ps",
":",
"Collection",
"[",
"float",
"]",
"=",
"None",
",",
"emb_drop",
":",
"float",
"=",
"0.",
",",
"y_range",
":",
"OptRange",
"=",
"None",
",",
"use_bn",
":",
"bool",
"=",
"True",
",",
"*",
"*",
"learn_kwargs",
")",
":",
"emb_szs",
"=",
"data",
".",
"get_emb_szs",
"(",
"ifnone",
"(",
"emb_szs",
",",
"{",
"}",
")",
")",
"model",
"=",
"TabularModel",
"(",
"emb_szs",
",",
"len",
"(",
"data",
".",
"cont_names",
")",
",",
"out_sz",
"=",
"data",
".",
"c",
",",
"layers",
"=",
"layers",
",",
"ps",
"=",
"ps",
",",
"emb_drop",
"=",
"emb_drop",
",",
"y_range",
"=",
"y_range",
",",
"use_bn",
"=",
"use_bn",
")",
"return",
"Learner",
"(",
"data",
",",
"model",
",",
"metrics",
"=",
"metrics",
",",
"*",
"*",
"learn_kwargs",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | TabularDataBunch.from_df | Create a `DataBunch` from `df` and `valid_idx` with `dep_var`. `kwargs` are passed to `DataBunch.create`. | fastai/tabular/data.py | def from_df(cls, path, df:DataFrame, dep_var:str, valid_idx:Collection[int], procs:OptTabTfms=None,
cat_names:OptStrList=None, cont_names:OptStrList=None, classes:Collection=None,
test_df=None, bs:int=64, val_bs:int=None, num_workers:int=defaults.cpus, dl_tfms:Optional[Collection[Callable]]=None,
device:torch.device=None, collate_fn:Callable=data_collate, no_check:bool=False)->DataBunch:
"Create a `DataBunch` from `df` and `valid_idx` with `dep_var`. `kwargs` are passed to `DataBunch.create`."
cat_names = ifnone(cat_names, []).copy()
cont_names = ifnone(cont_names, list(set(df)-set(cat_names)-{dep_var}))
procs = listify(procs)
src = (TabularList.from_df(df, path=path, cat_names=cat_names, cont_names=cont_names, procs=procs)
.split_by_idx(valid_idx))
src = src.label_from_df(cols=dep_var) if classes is None else src.label_from_df(cols=dep_var, classes=classes)
if test_df is not None: src.add_test(TabularList.from_df(test_df, cat_names=cat_names, cont_names=cont_names,
processor = src.train.x.processor))
return src.databunch(path=path, bs=bs, val_bs=val_bs, num_workers=num_workers, device=device,
collate_fn=collate_fn, no_check=no_check) | def from_df(cls, path, df:DataFrame, dep_var:str, valid_idx:Collection[int], procs:OptTabTfms=None,
cat_names:OptStrList=None, cont_names:OptStrList=None, classes:Collection=None,
test_df=None, bs:int=64, val_bs:int=None, num_workers:int=defaults.cpus, dl_tfms:Optional[Collection[Callable]]=None,
device:torch.device=None, collate_fn:Callable=data_collate, no_check:bool=False)->DataBunch:
"Create a `DataBunch` from `df` and `valid_idx` with `dep_var`. `kwargs` are passed to `DataBunch.create`."
cat_names = ifnone(cat_names, []).copy()
cont_names = ifnone(cont_names, list(set(df)-set(cat_names)-{dep_var}))
procs = listify(procs)
src = (TabularList.from_df(df, path=path, cat_names=cat_names, cont_names=cont_names, procs=procs)
.split_by_idx(valid_idx))
src = src.label_from_df(cols=dep_var) if classes is None else src.label_from_df(cols=dep_var, classes=classes)
if test_df is not None: src.add_test(TabularList.from_df(test_df, cat_names=cat_names, cont_names=cont_names,
processor = src.train.x.processor))
return src.databunch(path=path, bs=bs, val_bs=val_bs, num_workers=num_workers, device=device,
collate_fn=collate_fn, no_check=no_check) | [
"Create",
"a",
"DataBunch",
"from",
"df",
"and",
"valid_idx",
"with",
"dep_var",
".",
"kwargs",
"are",
"passed",
"to",
"DataBunch",
".",
"create",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/data.py#L87-L101 | [
"def",
"from_df",
"(",
"cls",
",",
"path",
",",
"df",
":",
"DataFrame",
",",
"dep_var",
":",
"str",
",",
"valid_idx",
":",
"Collection",
"[",
"int",
"]",
",",
"procs",
":",
"OptTabTfms",
"=",
"None",
",",
"cat_names",
":",
"OptStrList",
"=",
"None",
",",
"cont_names",
":",
"OptStrList",
"=",
"None",
",",
"classes",
":",
"Collection",
"=",
"None",
",",
"test_df",
"=",
"None",
",",
"bs",
":",
"int",
"=",
"64",
",",
"val_bs",
":",
"int",
"=",
"None",
",",
"num_workers",
":",
"int",
"=",
"defaults",
".",
"cpus",
",",
"dl_tfms",
":",
"Optional",
"[",
"Collection",
"[",
"Callable",
"]",
"]",
"=",
"None",
",",
"device",
":",
"torch",
".",
"device",
"=",
"None",
",",
"collate_fn",
":",
"Callable",
"=",
"data_collate",
",",
"no_check",
":",
"bool",
"=",
"False",
")",
"->",
"DataBunch",
":",
"cat_names",
"=",
"ifnone",
"(",
"cat_names",
",",
"[",
"]",
")",
".",
"copy",
"(",
")",
"cont_names",
"=",
"ifnone",
"(",
"cont_names",
",",
"list",
"(",
"set",
"(",
"df",
")",
"-",
"set",
"(",
"cat_names",
")",
"-",
"{",
"dep_var",
"}",
")",
")",
"procs",
"=",
"listify",
"(",
"procs",
")",
"src",
"=",
"(",
"TabularList",
".",
"from_df",
"(",
"df",
",",
"path",
"=",
"path",
",",
"cat_names",
"=",
"cat_names",
",",
"cont_names",
"=",
"cont_names",
",",
"procs",
"=",
"procs",
")",
".",
"split_by_idx",
"(",
"valid_idx",
")",
")",
"src",
"=",
"src",
".",
"label_from_df",
"(",
"cols",
"=",
"dep_var",
")",
"if",
"classes",
"is",
"None",
"else",
"src",
".",
"label_from_df",
"(",
"cols",
"=",
"dep_var",
",",
"classes",
"=",
"classes",
")",
"if",
"test_df",
"is",
"not",
"None",
":",
"src",
".",
"add_test",
"(",
"TabularList",
".",
"from_df",
"(",
"test_df",
",",
"cat_names",
"=",
"cat_names",
",",
"cont_names",
"=",
"cont_names",
",",
"processor",
"=",
"src",
".",
"train",
".",
"x",
".",
"processor",
")",
")",
"return",
"src",
".",
"databunch",
"(",
"path",
"=",
"path",
",",
"bs",
"=",
"bs",
",",
"val_bs",
"=",
"val_bs",
",",
"num_workers",
"=",
"num_workers",
",",
"device",
"=",
"device",
",",
"collate_fn",
"=",
"collate_fn",
",",
"no_check",
"=",
"no_check",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | TabularList.from_df | Get the list of inputs in the `col` of `path/csv_name`. | fastai/tabular/data.py | def from_df(cls, df:DataFrame, cat_names:OptStrList=None, cont_names:OptStrList=None, procs=None, **kwargs)->'ItemList':
"Get the list of inputs in the `col` of `path/csv_name`."
return cls(items=range(len(df)), cat_names=cat_names, cont_names=cont_names, procs=procs, inner_df=df.copy(), **kwargs) | def from_df(cls, df:DataFrame, cat_names:OptStrList=None, cont_names:OptStrList=None, procs=None, **kwargs)->'ItemList':
"Get the list of inputs in the `col` of `path/csv_name`."
return cls(items=range(len(df)), cat_names=cat_names, cont_names=cont_names, procs=procs, inner_df=df.copy(), **kwargs) | [
"Get",
"the",
"list",
"of",
"inputs",
"in",
"the",
"col",
"of",
"path",
"/",
"csv_name",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/data.py#L119-L121 | [
"def",
"from_df",
"(",
"cls",
",",
"df",
":",
"DataFrame",
",",
"cat_names",
":",
"OptStrList",
"=",
"None",
",",
"cont_names",
":",
"OptStrList",
"=",
"None",
",",
"procs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"'ItemList'",
":",
"return",
"cls",
"(",
"items",
"=",
"range",
"(",
"len",
"(",
"df",
")",
")",
",",
"cat_names",
"=",
"cat_names",
",",
"cont_names",
"=",
"cont_names",
",",
"procs",
"=",
"procs",
",",
"inner_df",
"=",
"df",
".",
"copy",
"(",
")",
",",
"*",
"*",
"kwargs",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | TabularList.get_emb_szs | Return the default embedding sizes suitable for this data or takes the ones in `sz_dict`. | fastai/tabular/data.py | def get_emb_szs(self, sz_dict=None):
"Return the default embedding sizes suitable for this data or takes the ones in `sz_dict`."
return [def_emb_sz(self.classes, n, sz_dict) for n in self.cat_names] | def get_emb_szs(self, sz_dict=None):
"Return the default embedding sizes suitable for this data or takes the ones in `sz_dict`."
return [def_emb_sz(self.classes, n, sz_dict) for n in self.cat_names] | [
"Return",
"the",
"default",
"embedding",
"sizes",
"suitable",
"for",
"this",
"data",
"or",
"takes",
"the",
"ones",
"in",
"sz_dict",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/data.py#L129-L131 | [
"def",
"get_emb_szs",
"(",
"self",
",",
"sz_dict",
"=",
"None",
")",
":",
"return",
"[",
"def_emb_sz",
"(",
"self",
".",
"classes",
",",
"n",
",",
"sz_dict",
")",
"for",
"n",
"in",
"self",
".",
"cat_names",
"]"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | TabularList.show_xys | Show the `xs` (inputs) and `ys` (targets). | fastai/tabular/data.py | def show_xys(self, xs, ys)->None:
"Show the `xs` (inputs) and `ys` (targets)."
from IPython.display import display, HTML
items,names = [], xs[0].names + ['target']
for i, (x,y) in enumerate(zip(xs,ys)):
res = []
cats = x.cats if len(x.cats.size()) > 0 else []
conts = x.conts if len(x.conts.size()) > 0 else []
for c, n in zip(cats, x.names[:len(cats)]):
res.append(x.classes[n][c])
res += [f'{c:.4f}' for c in conts] + [y]
items.append(res)
items = np.array(items)
df = pd.DataFrame({n:items[:,i] for i,n in enumerate(names)}, columns=names)
with pd.option_context('display.max_colwidth', -1):
display(HTML(df.to_html(index=False))) | def show_xys(self, xs, ys)->None:
"Show the `xs` (inputs) and `ys` (targets)."
from IPython.display import display, HTML
items,names = [], xs[0].names + ['target']
for i, (x,y) in enumerate(zip(xs,ys)):
res = []
cats = x.cats if len(x.cats.size()) > 0 else []
conts = x.conts if len(x.conts.size()) > 0 else []
for c, n in zip(cats, x.names[:len(cats)]):
res.append(x.classes[n][c])
res += [f'{c:.4f}' for c in conts] + [y]
items.append(res)
items = np.array(items)
df = pd.DataFrame({n:items[:,i] for i,n in enumerate(names)}, columns=names)
with pd.option_context('display.max_colwidth', -1):
display(HTML(df.to_html(index=False))) | [
"Show",
"the",
"xs",
"(",
"inputs",
")",
"and",
"ys",
"(",
"targets",
")",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/data.py#L136-L151 | [
"def",
"show_xys",
"(",
"self",
",",
"xs",
",",
"ys",
")",
"->",
"None",
":",
"from",
"IPython",
".",
"display",
"import",
"display",
",",
"HTML",
"items",
",",
"names",
"=",
"[",
"]",
",",
"xs",
"[",
"0",
"]",
".",
"names",
"+",
"[",
"'target'",
"]",
"for",
"i",
",",
"(",
"x",
",",
"y",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"xs",
",",
"ys",
")",
")",
":",
"res",
"=",
"[",
"]",
"cats",
"=",
"x",
".",
"cats",
"if",
"len",
"(",
"x",
".",
"cats",
".",
"size",
"(",
")",
")",
">",
"0",
"else",
"[",
"]",
"conts",
"=",
"x",
".",
"conts",
"if",
"len",
"(",
"x",
".",
"conts",
".",
"size",
"(",
")",
")",
">",
"0",
"else",
"[",
"]",
"for",
"c",
",",
"n",
"in",
"zip",
"(",
"cats",
",",
"x",
".",
"names",
"[",
":",
"len",
"(",
"cats",
")",
"]",
")",
":",
"res",
".",
"append",
"(",
"x",
".",
"classes",
"[",
"n",
"]",
"[",
"c",
"]",
")",
"res",
"+=",
"[",
"f'{c:.4f}'",
"for",
"c",
"in",
"conts",
"]",
"+",
"[",
"y",
"]",
"items",
".",
"append",
"(",
"res",
")",
"items",
"=",
"np",
".",
"array",
"(",
"items",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"{",
"n",
":",
"items",
"[",
":",
",",
"i",
"]",
"for",
"i",
",",
"n",
"in",
"enumerate",
"(",
"names",
")",
"}",
",",
"columns",
"=",
"names",
")",
"with",
"pd",
".",
"option_context",
"(",
"'display.max_colwidth'",
",",
"-",
"1",
")",
":",
"display",
"(",
"HTML",
"(",
"df",
".",
"to_html",
"(",
"index",
"=",
"False",
")",
")",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | load_model | Load the classifier and int to string mapping
Args:
itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl)
classifier_filename (str): The filename of the trained classifier
Returns:
string to int mapping, trained classifer model | courses/dl2/imdb_scripts/predict_with_classifier.py | def load_model(itos_filename, classifier_filename, num_classes):
"""Load the classifier and int to string mapping
Args:
itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl)
classifier_filename (str): The filename of the trained classifier
Returns:
string to int mapping, trained classifer model
"""
# load the int to string mapping file
itos = pickle.load(Path(itos_filename).open('rb'))
# turn it into a string to int mapping (which is what we need)
stoi = collections.defaultdict(lambda:0, {str(v):int(k) for k,v in enumerate(itos)})
# these parameters aren't used, but this is the easiest way to get a model
bptt,em_sz,nh,nl = 70,400,1150,3
dps = np.array([0.4,0.5,0.05,0.3,0.4])*0.5
vs = len(itos)
model = get_rnn_classifer(bptt, 20*70, num_classes, vs, emb_sz=em_sz, n_hid=nh, n_layers=nl, pad_token=1,
layers=[em_sz*3, 50, num_classes], drops=[dps[4], 0.1],
dropouti=dps[0], wdrop=dps[1], dropoute=dps[2], dropouth=dps[3])
# load the trained classifier
model.load_state_dict(torch.load(classifier_filename, map_location=lambda storage, loc: storage))
# put the classifier into evaluation mode
model.reset()
model.eval()
return stoi, model | def load_model(itos_filename, classifier_filename, num_classes):
"""Load the classifier and int to string mapping
Args:
itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl)
classifier_filename (str): The filename of the trained classifier
Returns:
string to int mapping, trained classifer model
"""
# load the int to string mapping file
itos = pickle.load(Path(itos_filename).open('rb'))
# turn it into a string to int mapping (which is what we need)
stoi = collections.defaultdict(lambda:0, {str(v):int(k) for k,v in enumerate(itos)})
# these parameters aren't used, but this is the easiest way to get a model
bptt,em_sz,nh,nl = 70,400,1150,3
dps = np.array([0.4,0.5,0.05,0.3,0.4])*0.5
vs = len(itos)
model = get_rnn_classifer(bptt, 20*70, num_classes, vs, emb_sz=em_sz, n_hid=nh, n_layers=nl, pad_token=1,
layers=[em_sz*3, 50, num_classes], drops=[dps[4], 0.1],
dropouti=dps[0], wdrop=dps[1], dropoute=dps[2], dropouth=dps[3])
# load the trained classifier
model.load_state_dict(torch.load(classifier_filename, map_location=lambda storage, loc: storage))
# put the classifier into evaluation mode
model.reset()
model.eval()
return stoi, model | [
"Load",
"the",
"classifier",
"and",
"int",
"to",
"string",
"mapping"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/courses/dl2/imdb_scripts/predict_with_classifier.py#L6-L38 | [
"def",
"load_model",
"(",
"itos_filename",
",",
"classifier_filename",
",",
"num_classes",
")",
":",
"# load the int to string mapping file",
"itos",
"=",
"pickle",
".",
"load",
"(",
"Path",
"(",
"itos_filename",
")",
".",
"open",
"(",
"'rb'",
")",
")",
"# turn it into a string to int mapping (which is what we need)",
"stoi",
"=",
"collections",
".",
"defaultdict",
"(",
"lambda",
":",
"0",
",",
"{",
"str",
"(",
"v",
")",
":",
"int",
"(",
"k",
")",
"for",
"k",
",",
"v",
"in",
"enumerate",
"(",
"itos",
")",
"}",
")",
"# these parameters aren't used, but this is the easiest way to get a model",
"bptt",
",",
"em_sz",
",",
"nh",
",",
"nl",
"=",
"70",
",",
"400",
",",
"1150",
",",
"3",
"dps",
"=",
"np",
".",
"array",
"(",
"[",
"0.4",
",",
"0.5",
",",
"0.05",
",",
"0.3",
",",
"0.4",
"]",
")",
"*",
"0.5",
"vs",
"=",
"len",
"(",
"itos",
")",
"model",
"=",
"get_rnn_classifer",
"(",
"bptt",
",",
"20",
"*",
"70",
",",
"num_classes",
",",
"vs",
",",
"emb_sz",
"=",
"em_sz",
",",
"n_hid",
"=",
"nh",
",",
"n_layers",
"=",
"nl",
",",
"pad_token",
"=",
"1",
",",
"layers",
"=",
"[",
"em_sz",
"*",
"3",
",",
"50",
",",
"num_classes",
"]",
",",
"drops",
"=",
"[",
"dps",
"[",
"4",
"]",
",",
"0.1",
"]",
",",
"dropouti",
"=",
"dps",
"[",
"0",
"]",
",",
"wdrop",
"=",
"dps",
"[",
"1",
"]",
",",
"dropoute",
"=",
"dps",
"[",
"2",
"]",
",",
"dropouth",
"=",
"dps",
"[",
"3",
"]",
")",
"# load the trained classifier",
"model",
".",
"load_state_dict",
"(",
"torch",
".",
"load",
"(",
"classifier_filename",
",",
"map_location",
"=",
"lambda",
"storage",
",",
"loc",
":",
"storage",
")",
")",
"# put the classifier into evaluation mode",
"model",
".",
"reset",
"(",
")",
"model",
".",
"eval",
"(",
")",
"return",
"stoi",
",",
"model"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | softmax | Numpy Softmax, via comments on https://gist.github.com/stober/1946926
>>> res = softmax(np.array([0, 200, 10]))
>>> np.sum(res)
1.0
>>> np.all(np.abs(res - np.array([0, 1, 0])) < 0.0001)
True
>>> res = softmax(np.array([[0, 200, 10], [0, 10, 200], [200, 0, 10]]))
>>> np.sum(res, axis=1)
array([ 1., 1., 1.])
>>> res = softmax(np.array([[0, 200, 10], [0, 10, 200]]))
>>> np.sum(res, axis=1)
array([ 1., 1.]) | courses/dl2/imdb_scripts/predict_with_classifier.py | def softmax(x):
'''
Numpy Softmax, via comments on https://gist.github.com/stober/1946926
>>> res = softmax(np.array([0, 200, 10]))
>>> np.sum(res)
1.0
>>> np.all(np.abs(res - np.array([0, 1, 0])) < 0.0001)
True
>>> res = softmax(np.array([[0, 200, 10], [0, 10, 200], [200, 0, 10]]))
>>> np.sum(res, axis=1)
array([ 1., 1., 1.])
>>> res = softmax(np.array([[0, 200, 10], [0, 10, 200]]))
>>> np.sum(res, axis=1)
array([ 1., 1.])
'''
if x.ndim == 1:
x = x.reshape((1, -1))
max_x = np.max(x, axis=1).reshape((-1, 1))
exp_x = np.exp(x - max_x)
return exp_x / np.sum(exp_x, axis=1).reshape((-1, 1)) | def softmax(x):
'''
Numpy Softmax, via comments on https://gist.github.com/stober/1946926
>>> res = softmax(np.array([0, 200, 10]))
>>> np.sum(res)
1.0
>>> np.all(np.abs(res - np.array([0, 1, 0])) < 0.0001)
True
>>> res = softmax(np.array([[0, 200, 10], [0, 10, 200], [200, 0, 10]]))
>>> np.sum(res, axis=1)
array([ 1., 1., 1.])
>>> res = softmax(np.array([[0, 200, 10], [0, 10, 200]]))
>>> np.sum(res, axis=1)
array([ 1., 1.])
'''
if x.ndim == 1:
x = x.reshape((1, -1))
max_x = np.max(x, axis=1).reshape((-1, 1))
exp_x = np.exp(x - max_x)
return exp_x / np.sum(exp_x, axis=1).reshape((-1, 1)) | [
"Numpy",
"Softmax",
"via",
"comments",
"on",
"https",
":",
"//",
"gist",
".",
"github",
".",
"com",
"/",
"stober",
"/",
"1946926"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/courses/dl2/imdb_scripts/predict_with_classifier.py#L41-L61 | [
"def",
"softmax",
"(",
"x",
")",
":",
"if",
"x",
".",
"ndim",
"==",
"1",
":",
"x",
"=",
"x",
".",
"reshape",
"(",
"(",
"1",
",",
"-",
"1",
")",
")",
"max_x",
"=",
"np",
".",
"max",
"(",
"x",
",",
"axis",
"=",
"1",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
")",
")",
"exp_x",
"=",
"np",
".",
"exp",
"(",
"x",
"-",
"max_x",
")",
"return",
"exp_x",
"/",
"np",
".",
"sum",
"(",
"exp_x",
",",
"axis",
"=",
"1",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
")",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | predict_text | Do the actual prediction on the text using the
model and mapping files passed | courses/dl2/imdb_scripts/predict_with_classifier.py | def predict_text(stoi, model, text):
"""Do the actual prediction on the text using the
model and mapping files passed
"""
# prefix text with tokens:
# xbos: beginning of sentence
# xfld 1: we are using a single field here
input_str = 'xbos xfld 1 ' + text
# predictions are done on arrays of input.
# We only have a single input, so turn it into a 1x1 array
texts = [input_str]
# tokenize using the fastai wrapper around spacy
tok = Tokenizer().proc_all_mp(partition_by_cores(texts))
# turn into integers for each word
encoded = [stoi[p] for p in tok[0]]
# we want a [x,1] array where x is the number
# of words inputted (including the prefix tokens)
ary = np.reshape(np.array(encoded),(-1,1))
# turn this array into a tensor
tensor = torch.from_numpy(ary)
# wrap in a torch Variable
variable = Variable(tensor)
# do the predictions
predictions = model(variable)
# convert back to numpy
numpy_preds = predictions[0].data.numpy()
return softmax(numpy_preds[0])[0] | def predict_text(stoi, model, text):
"""Do the actual prediction on the text using the
model and mapping files passed
"""
# prefix text with tokens:
# xbos: beginning of sentence
# xfld 1: we are using a single field here
input_str = 'xbos xfld 1 ' + text
# predictions are done on arrays of input.
# We only have a single input, so turn it into a 1x1 array
texts = [input_str]
# tokenize using the fastai wrapper around spacy
tok = Tokenizer().proc_all_mp(partition_by_cores(texts))
# turn into integers for each word
encoded = [stoi[p] for p in tok[0]]
# we want a [x,1] array where x is the number
# of words inputted (including the prefix tokens)
ary = np.reshape(np.array(encoded),(-1,1))
# turn this array into a tensor
tensor = torch.from_numpy(ary)
# wrap in a torch Variable
variable = Variable(tensor)
# do the predictions
predictions = model(variable)
# convert back to numpy
numpy_preds = predictions[0].data.numpy()
return softmax(numpy_preds[0])[0] | [
"Do",
"the",
"actual",
"prediction",
"on",
"the",
"text",
"using",
"the",
"model",
"and",
"mapping",
"files",
"passed"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/courses/dl2/imdb_scripts/predict_with_classifier.py#L64-L100 | [
"def",
"predict_text",
"(",
"stoi",
",",
"model",
",",
"text",
")",
":",
"# prefix text with tokens:",
"# xbos: beginning of sentence",
"# xfld 1: we are using a single field here",
"input_str",
"=",
"'xbos xfld 1 '",
"+",
"text",
"# predictions are done on arrays of input.",
"# We only have a single input, so turn it into a 1x1 array",
"texts",
"=",
"[",
"input_str",
"]",
"# tokenize using the fastai wrapper around spacy",
"tok",
"=",
"Tokenizer",
"(",
")",
".",
"proc_all_mp",
"(",
"partition_by_cores",
"(",
"texts",
")",
")",
"# turn into integers for each word",
"encoded",
"=",
"[",
"stoi",
"[",
"p",
"]",
"for",
"p",
"in",
"tok",
"[",
"0",
"]",
"]",
"# we want a [x,1] array where x is the number",
"# of words inputted (including the prefix tokens)",
"ary",
"=",
"np",
".",
"reshape",
"(",
"np",
".",
"array",
"(",
"encoded",
")",
",",
"(",
"-",
"1",
",",
"1",
")",
")",
"# turn this array into a tensor",
"tensor",
"=",
"torch",
".",
"from_numpy",
"(",
"ary",
")",
"# wrap in a torch Variable",
"variable",
"=",
"Variable",
"(",
"tensor",
")",
"# do the predictions",
"predictions",
"=",
"model",
"(",
"variable",
")",
"# convert back to numpy",
"numpy_preds",
"=",
"predictions",
"[",
"0",
"]",
".",
"data",
".",
"numpy",
"(",
")",
"return",
"softmax",
"(",
"numpy_preds",
"[",
"0",
"]",
")",
"[",
"0",
"]"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | predict_input | Loads a model and produces predictions on arbitrary input.
:param itos_filename: the path to the id-to-string mapping file
:param trained_classifier_filename: the filename of the trained classifier;
typically ends with "clas_1.h5"
:param num_classes: the number of classes that the model predicts | courses/dl2/imdb_scripts/predict_with_classifier.py | def predict_input(itos_filename, trained_classifier_filename, num_classes=2):
"""
Loads a model and produces predictions on arbitrary input.
:param itos_filename: the path to the id-to-string mapping file
:param trained_classifier_filename: the filename of the trained classifier;
typically ends with "clas_1.h5"
:param num_classes: the number of classes that the model predicts
"""
# Check the itos file exists
if not os.path.exists(itos_filename):
print("Could not find " + itos_filename)
exit(-1)
# Check the classifier file exists
if not os.path.exists(trained_classifier_filename):
print("Could not find " + trained_classifier_filename)
exit(-1)
stoi, model = load_model(itos_filename, trained_classifier_filename, num_classes)
while True:
text = input("Enter text to analyse (or q to quit): ")
if text.strip() == 'q':
break
else:
scores = predict_text(stoi, model, text)
print("Result id {0}, Scores: {1}".format(np.argmax(scores), scores)) | def predict_input(itos_filename, trained_classifier_filename, num_classes=2):
"""
Loads a model and produces predictions on arbitrary input.
:param itos_filename: the path to the id-to-string mapping file
:param trained_classifier_filename: the filename of the trained classifier;
typically ends with "clas_1.h5"
:param num_classes: the number of classes that the model predicts
"""
# Check the itos file exists
if not os.path.exists(itos_filename):
print("Could not find " + itos_filename)
exit(-1)
# Check the classifier file exists
if not os.path.exists(trained_classifier_filename):
print("Could not find " + trained_classifier_filename)
exit(-1)
stoi, model = load_model(itos_filename, trained_classifier_filename, num_classes)
while True:
text = input("Enter text to analyse (or q to quit): ")
if text.strip() == 'q':
break
else:
scores = predict_text(stoi, model, text)
print("Result id {0}, Scores: {1}".format(np.argmax(scores), scores)) | [
"Loads",
"a",
"model",
"and",
"produces",
"predictions",
"on",
"arbitrary",
"input",
".",
":",
"param",
"itos_filename",
":",
"the",
"path",
"to",
"the",
"id",
"-",
"to",
"-",
"string",
"mapping",
"file",
":",
"param",
"trained_classifier_filename",
":",
"the",
"filename",
"of",
"the",
"trained",
"classifier",
";",
"typically",
"ends",
"with",
"clas_1",
".",
"h5",
":",
"param",
"num_classes",
":",
"the",
"number",
"of",
"classes",
"that",
"the",
"model",
"predicts"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/courses/dl2/imdb_scripts/predict_with_classifier.py#L103-L129 | [
"def",
"predict_input",
"(",
"itos_filename",
",",
"trained_classifier_filename",
",",
"num_classes",
"=",
"2",
")",
":",
"# Check the itos file exists",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"itos_filename",
")",
":",
"print",
"(",
"\"Could not find \"",
"+",
"itos_filename",
")",
"exit",
"(",
"-",
"1",
")",
"# Check the classifier file exists",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"trained_classifier_filename",
")",
":",
"print",
"(",
"\"Could not find \"",
"+",
"trained_classifier_filename",
")",
"exit",
"(",
"-",
"1",
")",
"stoi",
",",
"model",
"=",
"load_model",
"(",
"itos_filename",
",",
"trained_classifier_filename",
",",
"num_classes",
")",
"while",
"True",
":",
"text",
"=",
"input",
"(",
"\"Enter text to analyse (or q to quit): \"",
")",
"if",
"text",
".",
"strip",
"(",
")",
"==",
"'q'",
":",
"break",
"else",
":",
"scores",
"=",
"predict_text",
"(",
"stoi",
",",
"model",
",",
"text",
")",
"print",
"(",
"\"Result id {0}, Scores: {1}\"",
".",
"format",
"(",
"np",
".",
"argmax",
"(",
"scores",
")",
",",
"scores",
")",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _make_w3c_caps | Makes a W3C alwaysMatch capabilities object.
Filters out capability names that are not in the W3C spec. Spec-compliant
drivers will reject requests containing unknown capability names.
Moves the Firefox profile, if present, from the old location to the new Firefox
options object.
:Args:
- caps - A dictionary of capabilities requested by the caller. | py/selenium/webdriver/remote/webdriver.py | def _make_w3c_caps(caps):
"""Makes a W3C alwaysMatch capabilities object.
Filters out capability names that are not in the W3C spec. Spec-compliant
drivers will reject requests containing unknown capability names.
Moves the Firefox profile, if present, from the old location to the new Firefox
options object.
:Args:
- caps - A dictionary of capabilities requested by the caller.
"""
caps = copy.deepcopy(caps)
profile = caps.get('firefox_profile')
always_match = {}
if caps.get('proxy') and caps['proxy'].get('proxyType'):
caps['proxy']['proxyType'] = caps['proxy']['proxyType'].lower()
for k, v in caps.items():
if v and k in _OSS_W3C_CONVERSION:
always_match[_OSS_W3C_CONVERSION[k]] = v.lower() if k == 'platform' else v
if k in _W3C_CAPABILITY_NAMES or ':' in k:
always_match[k] = v
if profile:
moz_opts = always_match.get('moz:firefoxOptions', {})
# If it's already present, assume the caller did that intentionally.
if 'profile' not in moz_opts:
# Don't mutate the original capabilities.
new_opts = copy.deepcopy(moz_opts)
new_opts['profile'] = profile
always_match['moz:firefoxOptions'] = new_opts
return {"firstMatch": [{}], "alwaysMatch": always_match} | def _make_w3c_caps(caps):
"""Makes a W3C alwaysMatch capabilities object.
Filters out capability names that are not in the W3C spec. Spec-compliant
drivers will reject requests containing unknown capability names.
Moves the Firefox profile, if present, from the old location to the new Firefox
options object.
:Args:
- caps - A dictionary of capabilities requested by the caller.
"""
caps = copy.deepcopy(caps)
profile = caps.get('firefox_profile')
always_match = {}
if caps.get('proxy') and caps['proxy'].get('proxyType'):
caps['proxy']['proxyType'] = caps['proxy']['proxyType'].lower()
for k, v in caps.items():
if v and k in _OSS_W3C_CONVERSION:
always_match[_OSS_W3C_CONVERSION[k]] = v.lower() if k == 'platform' else v
if k in _W3C_CAPABILITY_NAMES or ':' in k:
always_match[k] = v
if profile:
moz_opts = always_match.get('moz:firefoxOptions', {})
# If it's already present, assume the caller did that intentionally.
if 'profile' not in moz_opts:
# Don't mutate the original capabilities.
new_opts = copy.deepcopy(moz_opts)
new_opts['profile'] = profile
always_match['moz:firefoxOptions'] = new_opts
return {"firstMatch": [{}], "alwaysMatch": always_match} | [
"Makes",
"a",
"W3C",
"alwaysMatch",
"capabilities",
"object",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L65-L95 | [
"def",
"_make_w3c_caps",
"(",
"caps",
")",
":",
"caps",
"=",
"copy",
".",
"deepcopy",
"(",
"caps",
")",
"profile",
"=",
"caps",
".",
"get",
"(",
"'firefox_profile'",
")",
"always_match",
"=",
"{",
"}",
"if",
"caps",
".",
"get",
"(",
"'proxy'",
")",
"and",
"caps",
"[",
"'proxy'",
"]",
".",
"get",
"(",
"'proxyType'",
")",
":",
"caps",
"[",
"'proxy'",
"]",
"[",
"'proxyType'",
"]",
"=",
"caps",
"[",
"'proxy'",
"]",
"[",
"'proxyType'",
"]",
".",
"lower",
"(",
")",
"for",
"k",
",",
"v",
"in",
"caps",
".",
"items",
"(",
")",
":",
"if",
"v",
"and",
"k",
"in",
"_OSS_W3C_CONVERSION",
":",
"always_match",
"[",
"_OSS_W3C_CONVERSION",
"[",
"k",
"]",
"]",
"=",
"v",
".",
"lower",
"(",
")",
"if",
"k",
"==",
"'platform'",
"else",
"v",
"if",
"k",
"in",
"_W3C_CAPABILITY_NAMES",
"or",
"':'",
"in",
"k",
":",
"always_match",
"[",
"k",
"]",
"=",
"v",
"if",
"profile",
":",
"moz_opts",
"=",
"always_match",
".",
"get",
"(",
"'moz:firefoxOptions'",
",",
"{",
"}",
")",
"# If it's already present, assume the caller did that intentionally.",
"if",
"'profile'",
"not",
"in",
"moz_opts",
":",
"# Don't mutate the original capabilities.",
"new_opts",
"=",
"copy",
".",
"deepcopy",
"(",
"moz_opts",
")",
"new_opts",
"[",
"'profile'",
"]",
"=",
"profile",
"always_match",
"[",
"'moz:firefoxOptions'",
"]",
"=",
"new_opts",
"return",
"{",
"\"firstMatch\"",
":",
"[",
"{",
"}",
"]",
",",
"\"alwaysMatch\"",
":",
"always_match",
"}"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.file_detector_context | Overrides the current file detector (if necessary) in limited context.
Ensures the original file detector is set afterwards.
Example:
with webdriver.file_detector_context(UselessFileDetector):
someinput.send_keys('/etc/hosts')
:Args:
- file_detector_class - Class of the desired file detector. If the class is different
from the current file_detector, then the class is instantiated with args and kwargs
and used as a file detector during the duration of the context manager.
- args - Optional arguments that get passed to the file detector class during
instantiation.
- kwargs - Keyword arguments, passed the same way as args. | py/selenium/webdriver/remote/webdriver.py | def file_detector_context(self, file_detector_class, *args, **kwargs):
"""
Overrides the current file detector (if necessary) in limited context.
Ensures the original file detector is set afterwards.
Example:
with webdriver.file_detector_context(UselessFileDetector):
someinput.send_keys('/etc/hosts')
:Args:
- file_detector_class - Class of the desired file detector. If the class is different
from the current file_detector, then the class is instantiated with args and kwargs
and used as a file detector during the duration of the context manager.
- args - Optional arguments that get passed to the file detector class during
instantiation.
- kwargs - Keyword arguments, passed the same way as args.
"""
last_detector = None
if not isinstance(self.file_detector, file_detector_class):
last_detector = self.file_detector
self.file_detector = file_detector_class(*args, **kwargs)
try:
yield
finally:
if last_detector is not None:
self.file_detector = last_detector | def file_detector_context(self, file_detector_class, *args, **kwargs):
"""
Overrides the current file detector (if necessary) in limited context.
Ensures the original file detector is set afterwards.
Example:
with webdriver.file_detector_context(UselessFileDetector):
someinput.send_keys('/etc/hosts')
:Args:
- file_detector_class - Class of the desired file detector. If the class is different
from the current file_detector, then the class is instantiated with args and kwargs
and used as a file detector during the duration of the context manager.
- args - Optional arguments that get passed to the file detector class during
instantiation.
- kwargs - Keyword arguments, passed the same way as args.
"""
last_detector = None
if not isinstance(self.file_detector, file_detector_class):
last_detector = self.file_detector
self.file_detector = file_detector_class(*args, **kwargs)
try:
yield
finally:
if last_detector is not None:
self.file_detector = last_detector | [
"Overrides",
"the",
"current",
"file",
"detector",
"(",
"if",
"necessary",
")",
"in",
"limited",
"context",
".",
"Ensures",
"the",
"original",
"file",
"detector",
"is",
"set",
"afterwards",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L168-L194 | [
"def",
"file_detector_context",
"(",
"self",
",",
"file_detector_class",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"last_detector",
"=",
"None",
"if",
"not",
"isinstance",
"(",
"self",
".",
"file_detector",
",",
"file_detector_class",
")",
":",
"last_detector",
"=",
"self",
".",
"file_detector",
"self",
".",
"file_detector",
"=",
"file_detector_class",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"yield",
"finally",
":",
"if",
"last_detector",
"is",
"not",
"None",
":",
"self",
".",
"file_detector",
"=",
"last_detector"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.start_session | Creates a new session with the desired capabilities.
:Args:
- browser_name - The name of the browser to request.
- version - Which browser version to request.
- platform - Which platform to request the browser on.
- javascript_enabled - Whether the new session should support JavaScript.
- browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object. Only used if Firefox is requested. | py/selenium/webdriver/remote/webdriver.py | def start_session(self, capabilities, browser_profile=None):
"""
Creates a new session with the desired capabilities.
:Args:
- browser_name - The name of the browser to request.
- version - Which browser version to request.
- platform - Which platform to request the browser on.
- javascript_enabled - Whether the new session should support JavaScript.
- browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object. Only used if Firefox is requested.
"""
if not isinstance(capabilities, dict):
raise InvalidArgumentException("Capabilities must be a dictionary")
if browser_profile:
if "moz:firefoxOptions" in capabilities:
capabilities["moz:firefoxOptions"]["profile"] = browser_profile.encoded
else:
capabilities.update({'firefox_profile': browser_profile.encoded})
w3c_caps = _make_w3c_caps(capabilities)
parameters = {"capabilities": w3c_caps,
"desiredCapabilities": capabilities}
response = self.execute(Command.NEW_SESSION, parameters)
if 'sessionId' not in response:
response = response['value']
self.session_id = response['sessionId']
self.capabilities = response.get('value')
# if capabilities is none we are probably speaking to
# a W3C endpoint
if self.capabilities is None:
self.capabilities = response.get('capabilities')
# Double check to see if we have a W3C Compliant browser
self.w3c = response.get('status') is None
self.command_executor.w3c = self.w3c | def start_session(self, capabilities, browser_profile=None):
"""
Creates a new session with the desired capabilities.
:Args:
- browser_name - The name of the browser to request.
- version - Which browser version to request.
- platform - Which platform to request the browser on.
- javascript_enabled - Whether the new session should support JavaScript.
- browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object. Only used if Firefox is requested.
"""
if not isinstance(capabilities, dict):
raise InvalidArgumentException("Capabilities must be a dictionary")
if browser_profile:
if "moz:firefoxOptions" in capabilities:
capabilities["moz:firefoxOptions"]["profile"] = browser_profile.encoded
else:
capabilities.update({'firefox_profile': browser_profile.encoded})
w3c_caps = _make_w3c_caps(capabilities)
parameters = {"capabilities": w3c_caps,
"desiredCapabilities": capabilities}
response = self.execute(Command.NEW_SESSION, parameters)
if 'sessionId' not in response:
response = response['value']
self.session_id = response['sessionId']
self.capabilities = response.get('value')
# if capabilities is none we are probably speaking to
# a W3C endpoint
if self.capabilities is None:
self.capabilities = response.get('capabilities')
# Double check to see if we have a W3C Compliant browser
self.w3c = response.get('status') is None
self.command_executor.w3c = self.w3c | [
"Creates",
"a",
"new",
"session",
"with",
"the",
"desired",
"capabilities",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L228-L262 | [
"def",
"start_session",
"(",
"self",
",",
"capabilities",
",",
"browser_profile",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"capabilities",
",",
"dict",
")",
":",
"raise",
"InvalidArgumentException",
"(",
"\"Capabilities must be a dictionary\"",
")",
"if",
"browser_profile",
":",
"if",
"\"moz:firefoxOptions\"",
"in",
"capabilities",
":",
"capabilities",
"[",
"\"moz:firefoxOptions\"",
"]",
"[",
"\"profile\"",
"]",
"=",
"browser_profile",
".",
"encoded",
"else",
":",
"capabilities",
".",
"update",
"(",
"{",
"'firefox_profile'",
":",
"browser_profile",
".",
"encoded",
"}",
")",
"w3c_caps",
"=",
"_make_w3c_caps",
"(",
"capabilities",
")",
"parameters",
"=",
"{",
"\"capabilities\"",
":",
"w3c_caps",
",",
"\"desiredCapabilities\"",
":",
"capabilities",
"}",
"response",
"=",
"self",
".",
"execute",
"(",
"Command",
".",
"NEW_SESSION",
",",
"parameters",
")",
"if",
"'sessionId'",
"not",
"in",
"response",
":",
"response",
"=",
"response",
"[",
"'value'",
"]",
"self",
".",
"session_id",
"=",
"response",
"[",
"'sessionId'",
"]",
"self",
".",
"capabilities",
"=",
"response",
".",
"get",
"(",
"'value'",
")",
"# if capabilities is none we are probably speaking to",
"# a W3C endpoint",
"if",
"self",
".",
"capabilities",
"is",
"None",
":",
"self",
".",
"capabilities",
"=",
"response",
".",
"get",
"(",
"'capabilities'",
")",
"# Double check to see if we have a W3C Compliant browser",
"self",
".",
"w3c",
"=",
"response",
".",
"get",
"(",
"'status'",
")",
"is",
"None",
"self",
".",
"command_executor",
".",
"w3c",
"=",
"self",
".",
"w3c"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.create_web_element | Creates a web element with the specified `element_id`. | py/selenium/webdriver/remote/webdriver.py | def create_web_element(self, element_id):
"""Creates a web element with the specified `element_id`."""
return self._web_element_cls(self, element_id, w3c=self.w3c) | def create_web_element(self, element_id):
"""Creates a web element with the specified `element_id`."""
return self._web_element_cls(self, element_id, w3c=self.w3c) | [
"Creates",
"a",
"web",
"element",
"with",
"the",
"specified",
"element_id",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L277-L279 | [
"def",
"create_web_element",
"(",
"self",
",",
"element_id",
")",
":",
"return",
"self",
".",
"_web_element_cls",
"(",
"self",
",",
"element_id",
",",
"w3c",
"=",
"self",
".",
"w3c",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.execute | Sends a command to be executed by a command.CommandExecutor.
:Args:
- driver_command: The name of the command to execute as a string.
- params: A dictionary of named parameters to send with the command.
:Returns:
The command's JSON response loaded into a dictionary object. | py/selenium/webdriver/remote/webdriver.py | def execute(self, driver_command, params=None):
"""
Sends a command to be executed by a command.CommandExecutor.
:Args:
- driver_command: The name of the command to execute as a string.
- params: A dictionary of named parameters to send with the command.
:Returns:
The command's JSON response loaded into a dictionary object.
"""
if self.session_id is not None:
if not params:
params = {'sessionId': self.session_id}
elif 'sessionId' not in params:
params['sessionId'] = self.session_id
params = self._wrap_value(params)
response = self.command_executor.execute(driver_command, params)
if response:
self.error_handler.check_response(response)
response['value'] = self._unwrap_value(
response.get('value', None))
return response
# If the server doesn't send a response, assume the command was
# a success
return {'success': 0, 'value': None, 'sessionId': self.session_id} | def execute(self, driver_command, params=None):
"""
Sends a command to be executed by a command.CommandExecutor.
:Args:
- driver_command: The name of the command to execute as a string.
- params: A dictionary of named parameters to send with the command.
:Returns:
The command's JSON response loaded into a dictionary object.
"""
if self.session_id is not None:
if not params:
params = {'sessionId': self.session_id}
elif 'sessionId' not in params:
params['sessionId'] = self.session_id
params = self._wrap_value(params)
response = self.command_executor.execute(driver_command, params)
if response:
self.error_handler.check_response(response)
response['value'] = self._unwrap_value(
response.get('value', None))
return response
# If the server doesn't send a response, assume the command was
# a success
return {'success': 0, 'value': None, 'sessionId': self.session_id} | [
"Sends",
"a",
"command",
"to",
"be",
"executed",
"by",
"a",
"command",
".",
"CommandExecutor",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L298-L324 | [
"def",
"execute",
"(",
"self",
",",
"driver_command",
",",
"params",
"=",
"None",
")",
":",
"if",
"self",
".",
"session_id",
"is",
"not",
"None",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"'sessionId'",
":",
"self",
".",
"session_id",
"}",
"elif",
"'sessionId'",
"not",
"in",
"params",
":",
"params",
"[",
"'sessionId'",
"]",
"=",
"self",
".",
"session_id",
"params",
"=",
"self",
".",
"_wrap_value",
"(",
"params",
")",
"response",
"=",
"self",
".",
"command_executor",
".",
"execute",
"(",
"driver_command",
",",
"params",
")",
"if",
"response",
":",
"self",
".",
"error_handler",
".",
"check_response",
"(",
"response",
")",
"response",
"[",
"'value'",
"]",
"=",
"self",
".",
"_unwrap_value",
"(",
"response",
".",
"get",
"(",
"'value'",
",",
"None",
")",
")",
"return",
"response",
"# If the server doesn't send a response, assume the command was",
"# a success",
"return",
"{",
"'success'",
":",
"0",
",",
"'value'",
":",
"None",
",",
"'sessionId'",
":",
"self",
".",
"session_id",
"}"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_element_by_id | Finds an element by id.
:Args:
- id\\_ - The id of the element to be found.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_id('foo') | py/selenium/webdriver/remote/webdriver.py | def find_element_by_id(self, id_):
"""Finds an element by id.
:Args:
- id\\_ - The id of the element to be found.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_id('foo')
"""
return self.find_element(by=By.ID, value=id_) | def find_element_by_id(self, id_):
"""Finds an element by id.
:Args:
- id\\_ - The id of the element to be found.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_id('foo')
"""
return self.find_element(by=By.ID, value=id_) | [
"Finds",
"an",
"element",
"by",
"id",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L344-L361 | [
"def",
"find_element_by_id",
"(",
"self",
",",
"id_",
")",
":",
"return",
"self",
".",
"find_element",
"(",
"by",
"=",
"By",
".",
"ID",
",",
"value",
"=",
"id_",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_elements_by_id | Finds multiple elements by id.
:Args:
- id\\_ - The id of the elements to be found.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_id('foo') | py/selenium/webdriver/remote/webdriver.py | def find_elements_by_id(self, id_):
"""
Finds multiple elements by id.
:Args:
- id\\_ - The id of the elements to be found.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_id('foo')
"""
return self.find_elements(by=By.ID, value=id_) | def find_elements_by_id(self, id_):
"""
Finds multiple elements by id.
:Args:
- id\\_ - The id of the elements to be found.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_id('foo')
"""
return self.find_elements(by=By.ID, value=id_) | [
"Finds",
"multiple",
"elements",
"by",
"id",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L363-L379 | [
"def",
"find_elements_by_id",
"(",
"self",
",",
"id_",
")",
":",
"return",
"self",
".",
"find_elements",
"(",
"by",
"=",
"By",
".",
"ID",
",",
"value",
"=",
"id_",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_element_by_xpath | Finds an element by xpath.
:Args:
- xpath - The xpath locator of the element to find.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_xpath('//div/td[1]') | py/selenium/webdriver/remote/webdriver.py | def find_element_by_xpath(self, xpath):
"""
Finds an element by xpath.
:Args:
- xpath - The xpath locator of the element to find.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_xpath('//div/td[1]')
"""
return self.find_element(by=By.XPATH, value=xpath) | def find_element_by_xpath(self, xpath):
"""
Finds an element by xpath.
:Args:
- xpath - The xpath locator of the element to find.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_xpath('//div/td[1]')
"""
return self.find_element(by=By.XPATH, value=xpath) | [
"Finds",
"an",
"element",
"by",
"xpath",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L381-L399 | [
"def",
"find_element_by_xpath",
"(",
"self",
",",
"xpath",
")",
":",
"return",
"self",
".",
"find_element",
"(",
"by",
"=",
"By",
".",
"XPATH",
",",
"value",
"=",
"xpath",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_elements_by_xpath | Finds multiple elements by xpath.
:Args:
- xpath - The xpath locator of the elements to be found.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_xpath("//div[contains(@class, 'foo')]") | py/selenium/webdriver/remote/webdriver.py | def find_elements_by_xpath(self, xpath):
"""
Finds multiple elements by xpath.
:Args:
- xpath - The xpath locator of the elements to be found.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_xpath("//div[contains(@class, 'foo')]")
"""
return self.find_elements(by=By.XPATH, value=xpath) | def find_elements_by_xpath(self, xpath):
"""
Finds multiple elements by xpath.
:Args:
- xpath - The xpath locator of the elements to be found.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_xpath("//div[contains(@class, 'foo')]")
"""
return self.find_elements(by=By.XPATH, value=xpath) | [
"Finds",
"multiple",
"elements",
"by",
"xpath",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L401-L417 | [
"def",
"find_elements_by_xpath",
"(",
"self",
",",
"xpath",
")",
":",
"return",
"self",
".",
"find_elements",
"(",
"by",
"=",
"By",
".",
"XPATH",
",",
"value",
"=",
"xpath",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_element_by_link_text | Finds an element by link text.
:Args:
- link_text: The text of the element to be found.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_link_text('Sign In') | py/selenium/webdriver/remote/webdriver.py | def find_element_by_link_text(self, link_text):
"""
Finds an element by link text.
:Args:
- link_text: The text of the element to be found.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_link_text('Sign In')
"""
return self.find_element(by=By.LINK_TEXT, value=link_text) | def find_element_by_link_text(self, link_text):
"""
Finds an element by link text.
:Args:
- link_text: The text of the element to be found.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_link_text('Sign In')
"""
return self.find_element(by=By.LINK_TEXT, value=link_text) | [
"Finds",
"an",
"element",
"by",
"link",
"text",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L419-L437 | [
"def",
"find_element_by_link_text",
"(",
"self",
",",
"link_text",
")",
":",
"return",
"self",
".",
"find_element",
"(",
"by",
"=",
"By",
".",
"LINK_TEXT",
",",
"value",
"=",
"link_text",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_elements_by_link_text | Finds elements by link text.
:Args:
- link_text: The text of the elements to be found.
:Returns:
- list of webelement - a list with elements if any was found. an
empty list if not
:Usage:
::
elements = driver.find_elements_by_link_text('Sign In') | py/selenium/webdriver/remote/webdriver.py | def find_elements_by_link_text(self, text):
"""
Finds elements by link text.
:Args:
- link_text: The text of the elements to be found.
:Returns:
- list of webelement - a list with elements if any was found. an
empty list if not
:Usage:
::
elements = driver.find_elements_by_link_text('Sign In')
"""
return self.find_elements(by=By.LINK_TEXT, value=text) | def find_elements_by_link_text(self, text):
"""
Finds elements by link text.
:Args:
- link_text: The text of the elements to be found.
:Returns:
- list of webelement - a list with elements if any was found. an
empty list if not
:Usage:
::
elements = driver.find_elements_by_link_text('Sign In')
"""
return self.find_elements(by=By.LINK_TEXT, value=text) | [
"Finds",
"elements",
"by",
"link",
"text",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L439-L455 | [
"def",
"find_elements_by_link_text",
"(",
"self",
",",
"text",
")",
":",
"return",
"self",
".",
"find_elements",
"(",
"by",
"=",
"By",
".",
"LINK_TEXT",
",",
"value",
"=",
"text",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_element_by_partial_link_text | Finds an element by a partial match of its link text.
:Args:
- link_text: The text of the element to partially match on.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_partial_link_text('Sign') | py/selenium/webdriver/remote/webdriver.py | def find_element_by_partial_link_text(self, link_text):
"""
Finds an element by a partial match of its link text.
:Args:
- link_text: The text of the element to partially match on.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_partial_link_text('Sign')
"""
return self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text) | def find_element_by_partial_link_text(self, link_text):
"""
Finds an element by a partial match of its link text.
:Args:
- link_text: The text of the element to partially match on.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_partial_link_text('Sign')
"""
return self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text) | [
"Finds",
"an",
"element",
"by",
"a",
"partial",
"match",
"of",
"its",
"link",
"text",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L457-L475 | [
"def",
"find_element_by_partial_link_text",
"(",
"self",
",",
"link_text",
")",
":",
"return",
"self",
".",
"find_element",
"(",
"by",
"=",
"By",
".",
"PARTIAL_LINK_TEXT",
",",
"value",
"=",
"link_text",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_elements_by_partial_link_text | Finds elements by a partial match of their link text.
:Args:
- link_text: The text of the element to partial match on.
:Returns:
- list of webelement - a list with elements if any was found. an
empty list if not
:Usage:
::
elements = driver.find_elements_by_partial_link_text('Sign') | py/selenium/webdriver/remote/webdriver.py | def find_elements_by_partial_link_text(self, link_text):
"""
Finds elements by a partial match of their link text.
:Args:
- link_text: The text of the element to partial match on.
:Returns:
- list of webelement - a list with elements if any was found. an
empty list if not
:Usage:
::
elements = driver.find_elements_by_partial_link_text('Sign')
"""
return self.find_elements(by=By.PARTIAL_LINK_TEXT, value=link_text) | def find_elements_by_partial_link_text(self, link_text):
"""
Finds elements by a partial match of their link text.
:Args:
- link_text: The text of the element to partial match on.
:Returns:
- list of webelement - a list with elements if any was found. an
empty list if not
:Usage:
::
elements = driver.find_elements_by_partial_link_text('Sign')
"""
return self.find_elements(by=By.PARTIAL_LINK_TEXT, value=link_text) | [
"Finds",
"elements",
"by",
"a",
"partial",
"match",
"of",
"their",
"link",
"text",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L477-L493 | [
"def",
"find_elements_by_partial_link_text",
"(",
"self",
",",
"link_text",
")",
":",
"return",
"self",
".",
"find_elements",
"(",
"by",
"=",
"By",
".",
"PARTIAL_LINK_TEXT",
",",
"value",
"=",
"link_text",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_element_by_name | Finds an element by name.
:Args:
- name: The name of the element to find.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_name('foo') | py/selenium/webdriver/remote/webdriver.py | def find_element_by_name(self, name):
"""
Finds an element by name.
:Args:
- name: The name of the element to find.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_name('foo')
"""
return self.find_element(by=By.NAME, value=name) | def find_element_by_name(self, name):
"""
Finds an element by name.
:Args:
- name: The name of the element to find.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_name('foo')
"""
return self.find_element(by=By.NAME, value=name) | [
"Finds",
"an",
"element",
"by",
"name",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L495-L513 | [
"def",
"find_element_by_name",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"find_element",
"(",
"by",
"=",
"By",
".",
"NAME",
",",
"value",
"=",
"name",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_elements_by_name | Finds elements by name.
:Args:
- name: The name of the elements to find.
:Returns:
- list of webelement - a list with elements if any was found. an
empty list if not
:Usage:
::
elements = driver.find_elements_by_name('foo') | py/selenium/webdriver/remote/webdriver.py | def find_elements_by_name(self, name):
"""
Finds elements by name.
:Args:
- name: The name of the elements to find.
:Returns:
- list of webelement - a list with elements if any was found. an
empty list if not
:Usage:
::
elements = driver.find_elements_by_name('foo')
"""
return self.find_elements(by=By.NAME, value=name) | def find_elements_by_name(self, name):
"""
Finds elements by name.
:Args:
- name: The name of the elements to find.
:Returns:
- list of webelement - a list with elements if any was found. an
empty list if not
:Usage:
::
elements = driver.find_elements_by_name('foo')
"""
return self.find_elements(by=By.NAME, value=name) | [
"Finds",
"elements",
"by",
"name",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L515-L531 | [
"def",
"find_elements_by_name",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"find_elements",
"(",
"by",
"=",
"By",
".",
"NAME",
",",
"value",
"=",
"name",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_element_by_tag_name | Finds an element by tag name.
:Args:
- name - name of html tag (eg: h1, a, span)
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_tag_name('h1') | py/selenium/webdriver/remote/webdriver.py | def find_element_by_tag_name(self, name):
"""
Finds an element by tag name.
:Args:
- name - name of html tag (eg: h1, a, span)
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_tag_name('h1')
"""
return self.find_element(by=By.TAG_NAME, value=name) | def find_element_by_tag_name(self, name):
"""
Finds an element by tag name.
:Args:
- name - name of html tag (eg: h1, a, span)
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_tag_name('h1')
"""
return self.find_element(by=By.TAG_NAME, value=name) | [
"Finds",
"an",
"element",
"by",
"tag",
"name",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L533-L551 | [
"def",
"find_element_by_tag_name",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"find_element",
"(",
"by",
"=",
"By",
".",
"TAG_NAME",
",",
"value",
"=",
"name",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_elements_by_tag_name | Finds elements by tag name.
:Args:
- name - name of html tag (eg: h1, a, span)
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_tag_name('h1') | py/selenium/webdriver/remote/webdriver.py | def find_elements_by_tag_name(self, name):
"""
Finds elements by tag name.
:Args:
- name - name of html tag (eg: h1, a, span)
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_tag_name('h1')
"""
return self.find_elements(by=By.TAG_NAME, value=name) | def find_elements_by_tag_name(self, name):
"""
Finds elements by tag name.
:Args:
- name - name of html tag (eg: h1, a, span)
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_tag_name('h1')
"""
return self.find_elements(by=By.TAG_NAME, value=name) | [
"Finds",
"elements",
"by",
"tag",
"name",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L553-L569 | [
"def",
"find_elements_by_tag_name",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"find_elements",
"(",
"by",
"=",
"By",
".",
"TAG_NAME",
",",
"value",
"=",
"name",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_element_by_class_name | Finds an element by class name.
:Args:
- name: The class name of the element to find.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_class_name('foo') | py/selenium/webdriver/remote/webdriver.py | def find_element_by_class_name(self, name):
"""
Finds an element by class name.
:Args:
- name: The class name of the element to find.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_class_name('foo')
"""
return self.find_element(by=By.CLASS_NAME, value=name) | def find_element_by_class_name(self, name):
"""
Finds an element by class name.
:Args:
- name: The class name of the element to find.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_class_name('foo')
"""
return self.find_element(by=By.CLASS_NAME, value=name) | [
"Finds",
"an",
"element",
"by",
"class",
"name",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L571-L589 | [
"def",
"find_element_by_class_name",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"find_element",
"(",
"by",
"=",
"By",
".",
"CLASS_NAME",
",",
"value",
"=",
"name",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_elements_by_class_name | Finds elements by class name.
:Args:
- name: The class name of the elements to find.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_class_name('foo') | py/selenium/webdriver/remote/webdriver.py | def find_elements_by_class_name(self, name):
"""
Finds elements by class name.
:Args:
- name: The class name of the elements to find.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_class_name('foo')
"""
return self.find_elements(by=By.CLASS_NAME, value=name) | def find_elements_by_class_name(self, name):
"""
Finds elements by class name.
:Args:
- name: The class name of the elements to find.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_class_name('foo')
"""
return self.find_elements(by=By.CLASS_NAME, value=name) | [
"Finds",
"elements",
"by",
"class",
"name",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L591-L607 | [
"def",
"find_elements_by_class_name",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"find_elements",
"(",
"by",
"=",
"By",
".",
"CLASS_NAME",
",",
"value",
"=",
"name",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_element_by_css_selector | Finds an element by css selector.
:Args:
- css_selector - CSS selector string, ex: 'a.nav#home'
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_css_selector('#foo') | py/selenium/webdriver/remote/webdriver.py | def find_element_by_css_selector(self, css_selector):
"""
Finds an element by css selector.
:Args:
- css_selector - CSS selector string, ex: 'a.nav#home'
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_css_selector('#foo')
"""
return self.find_element(by=By.CSS_SELECTOR, value=css_selector) | def find_element_by_css_selector(self, css_selector):
"""
Finds an element by css selector.
:Args:
- css_selector - CSS selector string, ex: 'a.nav#home'
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_element_by_css_selector('#foo')
"""
return self.find_element(by=By.CSS_SELECTOR, value=css_selector) | [
"Finds",
"an",
"element",
"by",
"css",
"selector",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L609-L627 | [
"def",
"find_element_by_css_selector",
"(",
"self",
",",
"css_selector",
")",
":",
"return",
"self",
".",
"find_element",
"(",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"value",
"=",
"css_selector",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_elements_by_css_selector | Finds elements by css selector.
:Args:
- css_selector - CSS selector string, ex: 'a.nav#home'
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_css_selector('.foo') | py/selenium/webdriver/remote/webdriver.py | def find_elements_by_css_selector(self, css_selector):
"""
Finds elements by css selector.
:Args:
- css_selector - CSS selector string, ex: 'a.nav#home'
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_css_selector('.foo')
"""
return self.find_elements(by=By.CSS_SELECTOR, value=css_selector) | def find_elements_by_css_selector(self, css_selector):
"""
Finds elements by css selector.
:Args:
- css_selector - CSS selector string, ex: 'a.nav#home'
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_css_selector('.foo')
"""
return self.find_elements(by=By.CSS_SELECTOR, value=css_selector) | [
"Finds",
"elements",
"by",
"css",
"selector",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L629-L645 | [
"def",
"find_elements_by_css_selector",
"(",
"self",
",",
"css_selector",
")",
":",
"return",
"self",
".",
"find_elements",
"(",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"value",
"=",
"css_selector",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.execute_script | Synchronously Executes JavaScript in the current window/frame.
:Args:
- script: The JavaScript to execute.
- \\*args: Any applicable arguments for your JavaScript.
:Usage:
::
driver.execute_script('return document.title;') | py/selenium/webdriver/remote/webdriver.py | def execute_script(self, script, *args):
"""
Synchronously Executes JavaScript in the current window/frame.
:Args:
- script: The JavaScript to execute.
- \\*args: Any applicable arguments for your JavaScript.
:Usage:
::
driver.execute_script('return document.title;')
"""
converted_args = list(args)
command = None
if self.w3c:
command = Command.W3C_EXECUTE_SCRIPT
else:
command = Command.EXECUTE_SCRIPT
return self.execute(command, {
'script': script,
'args': converted_args})['value'] | def execute_script(self, script, *args):
"""
Synchronously Executes JavaScript in the current window/frame.
:Args:
- script: The JavaScript to execute.
- \\*args: Any applicable arguments for your JavaScript.
:Usage:
::
driver.execute_script('return document.title;')
"""
converted_args = list(args)
command = None
if self.w3c:
command = Command.W3C_EXECUTE_SCRIPT
else:
command = Command.EXECUTE_SCRIPT
return self.execute(command, {
'script': script,
'args': converted_args})['value'] | [
"Synchronously",
"Executes",
"JavaScript",
"in",
"the",
"current",
"window",
"/",
"frame",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L647-L669 | [
"def",
"execute_script",
"(",
"self",
",",
"script",
",",
"*",
"args",
")",
":",
"converted_args",
"=",
"list",
"(",
"args",
")",
"command",
"=",
"None",
"if",
"self",
".",
"w3c",
":",
"command",
"=",
"Command",
".",
"W3C_EXECUTE_SCRIPT",
"else",
":",
"command",
"=",
"Command",
".",
"EXECUTE_SCRIPT",
"return",
"self",
".",
"execute",
"(",
"command",
",",
"{",
"'script'",
":",
"script",
",",
"'args'",
":",
"converted_args",
"}",
")",
"[",
"'value'",
"]"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.execute_async_script | Asynchronously Executes JavaScript in the current window/frame.
:Args:
- script: The JavaScript to execute.
- \\*args: Any applicable arguments for your JavaScript.
:Usage:
::
script = "var callback = arguments[arguments.length - 1]; " \\
"window.setTimeout(function(){ callback('timeout') }, 3000);"
driver.execute_async_script(script) | py/selenium/webdriver/remote/webdriver.py | def execute_async_script(self, script, *args):
"""
Asynchronously Executes JavaScript in the current window/frame.
:Args:
- script: The JavaScript to execute.
- \\*args: Any applicable arguments for your JavaScript.
:Usage:
::
script = "var callback = arguments[arguments.length - 1]; " \\
"window.setTimeout(function(){ callback('timeout') }, 3000);"
driver.execute_async_script(script)
"""
converted_args = list(args)
if self.w3c:
command = Command.W3C_EXECUTE_SCRIPT_ASYNC
else:
command = Command.EXECUTE_ASYNC_SCRIPT
return self.execute(command, {
'script': script,
'args': converted_args})['value'] | def execute_async_script(self, script, *args):
"""
Asynchronously Executes JavaScript in the current window/frame.
:Args:
- script: The JavaScript to execute.
- \\*args: Any applicable arguments for your JavaScript.
:Usage:
::
script = "var callback = arguments[arguments.length - 1]; " \\
"window.setTimeout(function(){ callback('timeout') }, 3000);"
driver.execute_async_script(script)
"""
converted_args = list(args)
if self.w3c:
command = Command.W3C_EXECUTE_SCRIPT_ASYNC
else:
command = Command.EXECUTE_ASYNC_SCRIPT
return self.execute(command, {
'script': script,
'args': converted_args})['value'] | [
"Asynchronously",
"Executes",
"JavaScript",
"in",
"the",
"current",
"window",
"/",
"frame",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L671-L694 | [
"def",
"execute_async_script",
"(",
"self",
",",
"script",
",",
"*",
"args",
")",
":",
"converted_args",
"=",
"list",
"(",
"args",
")",
"if",
"self",
".",
"w3c",
":",
"command",
"=",
"Command",
".",
"W3C_EXECUTE_SCRIPT_ASYNC",
"else",
":",
"command",
"=",
"Command",
".",
"EXECUTE_ASYNC_SCRIPT",
"return",
"self",
".",
"execute",
"(",
"command",
",",
"{",
"'script'",
":",
"script",
",",
"'args'",
":",
"converted_args",
"}",
")",
"[",
"'value'",
"]"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.quit | Quits the driver and closes every associated window.
:Usage:
::
driver.quit() | py/selenium/webdriver/remote/webdriver.py | def quit(self):
"""
Quits the driver and closes every associated window.
:Usage:
::
driver.quit()
"""
try:
self.execute(Command.QUIT)
finally:
self.stop_client()
self.command_executor.close() | def quit(self):
"""
Quits the driver and closes every associated window.
:Usage:
::
driver.quit()
"""
try:
self.execute(Command.QUIT)
finally:
self.stop_client()
self.command_executor.close() | [
"Quits",
"the",
"driver",
"and",
"closes",
"every",
"associated",
"window",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L731-L744 | [
"def",
"quit",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"execute",
"(",
"Command",
".",
"QUIT",
")",
"finally",
":",
"self",
".",
"stop_client",
"(",
")",
"self",
".",
"command_executor",
".",
"close",
"(",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.current_window_handle | Returns the handle of the current window.
:Usage:
::
driver.current_window_handle | py/selenium/webdriver/remote/webdriver.py | def current_window_handle(self):
"""
Returns the handle of the current window.
:Usage:
::
driver.current_window_handle
"""
if self.w3c:
return self.execute(Command.W3C_GET_CURRENT_WINDOW_HANDLE)['value']
else:
return self.execute(Command.GET_CURRENT_WINDOW_HANDLE)['value'] | def current_window_handle(self):
"""
Returns the handle of the current window.
:Usage:
::
driver.current_window_handle
"""
if self.w3c:
return self.execute(Command.W3C_GET_CURRENT_WINDOW_HANDLE)['value']
else:
return self.execute(Command.GET_CURRENT_WINDOW_HANDLE)['value'] | [
"Returns",
"the",
"handle",
"of",
"the",
"current",
"window",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L747-L759 | [
"def",
"current_window_handle",
"(",
"self",
")",
":",
"if",
"self",
".",
"w3c",
":",
"return",
"self",
".",
"execute",
"(",
"Command",
".",
"W3C_GET_CURRENT_WINDOW_HANDLE",
")",
"[",
"'value'",
"]",
"else",
":",
"return",
"self",
".",
"execute",
"(",
"Command",
".",
"GET_CURRENT_WINDOW_HANDLE",
")",
"[",
"'value'",
"]"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.window_handles | Returns the handles of all windows within the current session.
:Usage:
::
driver.window_handles | py/selenium/webdriver/remote/webdriver.py | def window_handles(self):
"""
Returns the handles of all windows within the current session.
:Usage:
::
driver.window_handles
"""
if self.w3c:
return self.execute(Command.W3C_GET_WINDOW_HANDLES)['value']
else:
return self.execute(Command.GET_WINDOW_HANDLES)['value'] | def window_handles(self):
"""
Returns the handles of all windows within the current session.
:Usage:
::
driver.window_handles
"""
if self.w3c:
return self.execute(Command.W3C_GET_WINDOW_HANDLES)['value']
else:
return self.execute(Command.GET_WINDOW_HANDLES)['value'] | [
"Returns",
"the",
"handles",
"of",
"all",
"windows",
"within",
"the",
"current",
"session",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L762-L774 | [
"def",
"window_handles",
"(",
"self",
")",
":",
"if",
"self",
".",
"w3c",
":",
"return",
"self",
".",
"execute",
"(",
"Command",
".",
"W3C_GET_WINDOW_HANDLES",
")",
"[",
"'value'",
"]",
"else",
":",
"return",
"self",
".",
"execute",
"(",
"Command",
".",
"GET_WINDOW_HANDLES",
")",
"[",
"'value'",
"]"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.maximize_window | Maximizes the current window that webdriver is using | py/selenium/webdriver/remote/webdriver.py | def maximize_window(self):
"""
Maximizes the current window that webdriver is using
"""
params = None
command = Command.W3C_MAXIMIZE_WINDOW
if not self.w3c:
command = Command.MAXIMIZE_WINDOW
params = {'windowHandle': 'current'}
self.execute(command, params) | def maximize_window(self):
"""
Maximizes the current window that webdriver is using
"""
params = None
command = Command.W3C_MAXIMIZE_WINDOW
if not self.w3c:
command = Command.MAXIMIZE_WINDOW
params = {'windowHandle': 'current'}
self.execute(command, params) | [
"Maximizes",
"the",
"current",
"window",
"that",
"webdriver",
"is",
"using"
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L776-L785 | [
"def",
"maximize_window",
"(",
"self",
")",
":",
"params",
"=",
"None",
"command",
"=",
"Command",
".",
"W3C_MAXIMIZE_WINDOW",
"if",
"not",
"self",
".",
"w3c",
":",
"command",
"=",
"Command",
".",
"MAXIMIZE_WINDOW",
"params",
"=",
"{",
"'windowHandle'",
":",
"'current'",
"}",
"self",
".",
"execute",
"(",
"command",
",",
"params",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.get_cookie | Get a single cookie by name. Returns the cookie if found, None if not.
:Usage:
::
driver.get_cookie('my_cookie') | py/selenium/webdriver/remote/webdriver.py | def get_cookie(self, name):
"""
Get a single cookie by name. Returns the cookie if found, None if not.
:Usage:
::
driver.get_cookie('my_cookie')
"""
if self.w3c:
try:
return self.execute(Command.GET_COOKIE, {'name': name})['value']
except NoSuchCookieException:
return None
else:
cookies = self.get_cookies()
for cookie in cookies:
if cookie['name'] == name:
return cookie
return None | def get_cookie(self, name):
"""
Get a single cookie by name. Returns the cookie if found, None if not.
:Usage:
::
driver.get_cookie('my_cookie')
"""
if self.w3c:
try:
return self.execute(Command.GET_COOKIE, {'name': name})['value']
except NoSuchCookieException:
return None
else:
cookies = self.get_cookies()
for cookie in cookies:
if cookie['name'] == name:
return cookie
return None | [
"Get",
"a",
"single",
"cookie",
"by",
"name",
".",
"Returns",
"the",
"cookie",
"if",
"found",
"None",
"if",
"not",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L865-L884 | [
"def",
"get_cookie",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"w3c",
":",
"try",
":",
"return",
"self",
".",
"execute",
"(",
"Command",
".",
"GET_COOKIE",
",",
"{",
"'name'",
":",
"name",
"}",
")",
"[",
"'value'",
"]",
"except",
"NoSuchCookieException",
":",
"return",
"None",
"else",
":",
"cookies",
"=",
"self",
".",
"get_cookies",
"(",
")",
"for",
"cookie",
"in",
"cookies",
":",
"if",
"cookie",
"[",
"'name'",
"]",
"==",
"name",
":",
"return",
"cookie",
"return",
"None"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.implicitly_wait | Sets a sticky timeout to implicitly wait for an element to be found,
or a command to complete. This method only needs to be called one
time per session. To set the timeout for calls to
execute_async_script, see set_script_timeout.
:Args:
- time_to_wait: Amount of time to wait (in seconds)
:Usage:
::
driver.implicitly_wait(30) | py/selenium/webdriver/remote/webdriver.py | def implicitly_wait(self, time_to_wait):
"""
Sets a sticky timeout to implicitly wait for an element to be found,
or a command to complete. This method only needs to be called one
time per session. To set the timeout for calls to
execute_async_script, see set_script_timeout.
:Args:
- time_to_wait: Amount of time to wait (in seconds)
:Usage:
::
driver.implicitly_wait(30)
"""
if self.w3c:
self.execute(Command.SET_TIMEOUTS, {
'implicit': int(float(time_to_wait) * 1000)})
else:
self.execute(Command.IMPLICIT_WAIT, {
'ms': float(time_to_wait) * 1000}) | def implicitly_wait(self, time_to_wait):
"""
Sets a sticky timeout to implicitly wait for an element to be found,
or a command to complete. This method only needs to be called one
time per session. To set the timeout for calls to
execute_async_script, see set_script_timeout.
:Args:
- time_to_wait: Amount of time to wait (in seconds)
:Usage:
::
driver.implicitly_wait(30)
"""
if self.w3c:
self.execute(Command.SET_TIMEOUTS, {
'implicit': int(float(time_to_wait) * 1000)})
else:
self.execute(Command.IMPLICIT_WAIT, {
'ms': float(time_to_wait) * 1000}) | [
"Sets",
"a",
"sticky",
"timeout",
"to",
"implicitly",
"wait",
"for",
"an",
"element",
"to",
"be",
"found",
"or",
"a",
"command",
"to",
"complete",
".",
"This",
"method",
"only",
"needs",
"to",
"be",
"called",
"one",
"time",
"per",
"session",
".",
"To",
"set",
"the",
"timeout",
"for",
"calls",
"to",
"execute_async_script",
"see",
"set_script_timeout",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L925-L945 | [
"def",
"implicitly_wait",
"(",
"self",
",",
"time_to_wait",
")",
":",
"if",
"self",
".",
"w3c",
":",
"self",
".",
"execute",
"(",
"Command",
".",
"SET_TIMEOUTS",
",",
"{",
"'implicit'",
":",
"int",
"(",
"float",
"(",
"time_to_wait",
")",
"*",
"1000",
")",
"}",
")",
"else",
":",
"self",
".",
"execute",
"(",
"Command",
".",
"IMPLICIT_WAIT",
",",
"{",
"'ms'",
":",
"float",
"(",
"time_to_wait",
")",
"*",
"1000",
"}",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.set_script_timeout | Set the amount of time that the script should wait during an
execute_async_script call before throwing an error.
:Args:
- time_to_wait: The amount of time to wait (in seconds)
:Usage:
::
driver.set_script_timeout(30) | py/selenium/webdriver/remote/webdriver.py | def set_script_timeout(self, time_to_wait):
"""
Set the amount of time that the script should wait during an
execute_async_script call before throwing an error.
:Args:
- time_to_wait: The amount of time to wait (in seconds)
:Usage:
::
driver.set_script_timeout(30)
"""
if self.w3c:
self.execute(Command.SET_TIMEOUTS, {
'script': int(float(time_to_wait) * 1000)})
else:
self.execute(Command.SET_SCRIPT_TIMEOUT, {
'ms': float(time_to_wait) * 1000}) | def set_script_timeout(self, time_to_wait):
"""
Set the amount of time that the script should wait during an
execute_async_script call before throwing an error.
:Args:
- time_to_wait: The amount of time to wait (in seconds)
:Usage:
::
driver.set_script_timeout(30)
"""
if self.w3c:
self.execute(Command.SET_TIMEOUTS, {
'script': int(float(time_to_wait) * 1000)})
else:
self.execute(Command.SET_SCRIPT_TIMEOUT, {
'ms': float(time_to_wait) * 1000}) | [
"Set",
"the",
"amount",
"of",
"time",
"that",
"the",
"script",
"should",
"wait",
"during",
"an",
"execute_async_script",
"call",
"before",
"throwing",
"an",
"error",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L947-L965 | [
"def",
"set_script_timeout",
"(",
"self",
",",
"time_to_wait",
")",
":",
"if",
"self",
".",
"w3c",
":",
"self",
".",
"execute",
"(",
"Command",
".",
"SET_TIMEOUTS",
",",
"{",
"'script'",
":",
"int",
"(",
"float",
"(",
"time_to_wait",
")",
"*",
"1000",
")",
"}",
")",
"else",
":",
"self",
".",
"execute",
"(",
"Command",
".",
"SET_SCRIPT_TIMEOUT",
",",
"{",
"'ms'",
":",
"float",
"(",
"time_to_wait",
")",
"*",
"1000",
"}",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.set_page_load_timeout | Set the amount of time to wait for a page load to complete
before throwing an error.
:Args:
- time_to_wait: The amount of time to wait
:Usage:
::
driver.set_page_load_timeout(30) | py/selenium/webdriver/remote/webdriver.py | def set_page_load_timeout(self, time_to_wait):
"""
Set the amount of time to wait for a page load to complete
before throwing an error.
:Args:
- time_to_wait: The amount of time to wait
:Usage:
::
driver.set_page_load_timeout(30)
"""
try:
self.execute(Command.SET_TIMEOUTS, {
'pageLoad': int(float(time_to_wait) * 1000)})
except WebDriverException:
self.execute(Command.SET_TIMEOUTS, {
'ms': float(time_to_wait) * 1000,
'type': 'page load'}) | def set_page_load_timeout(self, time_to_wait):
"""
Set the amount of time to wait for a page load to complete
before throwing an error.
:Args:
- time_to_wait: The amount of time to wait
:Usage:
::
driver.set_page_load_timeout(30)
"""
try:
self.execute(Command.SET_TIMEOUTS, {
'pageLoad': int(float(time_to_wait) * 1000)})
except WebDriverException:
self.execute(Command.SET_TIMEOUTS, {
'ms': float(time_to_wait) * 1000,
'type': 'page load'}) | [
"Set",
"the",
"amount",
"of",
"time",
"to",
"wait",
"for",
"a",
"page",
"load",
"to",
"complete",
"before",
"throwing",
"an",
"error",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L967-L986 | [
"def",
"set_page_load_timeout",
"(",
"self",
",",
"time_to_wait",
")",
":",
"try",
":",
"self",
".",
"execute",
"(",
"Command",
".",
"SET_TIMEOUTS",
",",
"{",
"'pageLoad'",
":",
"int",
"(",
"float",
"(",
"time_to_wait",
")",
"*",
"1000",
")",
"}",
")",
"except",
"WebDriverException",
":",
"self",
".",
"execute",
"(",
"Command",
".",
"SET_TIMEOUTS",
",",
"{",
"'ms'",
":",
"float",
"(",
"time_to_wait",
")",
"*",
"1000",
",",
"'type'",
":",
"'page load'",
"}",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_element | Find an element given a By strategy and locator. Prefer the find_element_by_* methods when
possible.
:Usage:
::
element = driver.find_element(By.ID, 'foo')
:rtype: WebElement | py/selenium/webdriver/remote/webdriver.py | def find_element(self, by=By.ID, value=None):
"""
Find an element given a By strategy and locator. Prefer the find_element_by_* methods when
possible.
:Usage:
::
element = driver.find_element(By.ID, 'foo')
:rtype: WebElement
"""
if self.w3c:
if by == By.ID:
by = By.CSS_SELECTOR
value = '[id="%s"]' % value
elif by == By.TAG_NAME:
by = By.CSS_SELECTOR
elif by == By.CLASS_NAME:
by = By.CSS_SELECTOR
value = ".%s" % value
elif by == By.NAME:
by = By.CSS_SELECTOR
value = '[name="%s"]' % value
return self.execute(Command.FIND_ELEMENT, {
'using': by,
'value': value})['value'] | def find_element(self, by=By.ID, value=None):
"""
Find an element given a By strategy and locator. Prefer the find_element_by_* methods when
possible.
:Usage:
::
element = driver.find_element(By.ID, 'foo')
:rtype: WebElement
"""
if self.w3c:
if by == By.ID:
by = By.CSS_SELECTOR
value = '[id="%s"]' % value
elif by == By.TAG_NAME:
by = By.CSS_SELECTOR
elif by == By.CLASS_NAME:
by = By.CSS_SELECTOR
value = ".%s" % value
elif by == By.NAME:
by = By.CSS_SELECTOR
value = '[name="%s"]' % value
return self.execute(Command.FIND_ELEMENT, {
'using': by,
'value': value})['value'] | [
"Find",
"an",
"element",
"given",
"a",
"By",
"strategy",
"and",
"locator",
".",
"Prefer",
"the",
"find_element_by_",
"*",
"methods",
"when",
"possible",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L988-L1014 | [
"def",
"find_element",
"(",
"self",
",",
"by",
"=",
"By",
".",
"ID",
",",
"value",
"=",
"None",
")",
":",
"if",
"self",
".",
"w3c",
":",
"if",
"by",
"==",
"By",
".",
"ID",
":",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
"value",
"=",
"'[id=\"%s\"]'",
"%",
"value",
"elif",
"by",
"==",
"By",
".",
"TAG_NAME",
":",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
"elif",
"by",
"==",
"By",
".",
"CLASS_NAME",
":",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
"value",
"=",
"\".%s\"",
"%",
"value",
"elif",
"by",
"==",
"By",
".",
"NAME",
":",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
"value",
"=",
"'[name=\"%s\"]'",
"%",
"value",
"return",
"self",
".",
"execute",
"(",
"Command",
".",
"FIND_ELEMENT",
",",
"{",
"'using'",
":",
"by",
",",
"'value'",
":",
"value",
"}",
")",
"[",
"'value'",
"]"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.find_elements | Find elements given a By strategy and locator. Prefer the find_elements_by_* methods when
possible.
:Usage:
::
elements = driver.find_elements(By.CLASS_NAME, 'foo')
:rtype: list of WebElement | py/selenium/webdriver/remote/webdriver.py | def find_elements(self, by=By.ID, value=None):
"""
Find elements given a By strategy and locator. Prefer the find_elements_by_* methods when
possible.
:Usage:
::
elements = driver.find_elements(By.CLASS_NAME, 'foo')
:rtype: list of WebElement
"""
if self.w3c:
if by == By.ID:
by = By.CSS_SELECTOR
value = '[id="%s"]' % value
elif by == By.TAG_NAME:
by = By.CSS_SELECTOR
elif by == By.CLASS_NAME:
by = By.CSS_SELECTOR
value = ".%s" % value
elif by == By.NAME:
by = By.CSS_SELECTOR
value = '[name="%s"]' % value
# Return empty list if driver returns null
# See https://github.com/SeleniumHQ/selenium/issues/4555
return self.execute(Command.FIND_ELEMENTS, {
'using': by,
'value': value})['value'] or [] | def find_elements(self, by=By.ID, value=None):
"""
Find elements given a By strategy and locator. Prefer the find_elements_by_* methods when
possible.
:Usage:
::
elements = driver.find_elements(By.CLASS_NAME, 'foo')
:rtype: list of WebElement
"""
if self.w3c:
if by == By.ID:
by = By.CSS_SELECTOR
value = '[id="%s"]' % value
elif by == By.TAG_NAME:
by = By.CSS_SELECTOR
elif by == By.CLASS_NAME:
by = By.CSS_SELECTOR
value = ".%s" % value
elif by == By.NAME:
by = By.CSS_SELECTOR
value = '[name="%s"]' % value
# Return empty list if driver returns null
# See https://github.com/SeleniumHQ/selenium/issues/4555
return self.execute(Command.FIND_ELEMENTS, {
'using': by,
'value': value})['value'] or [] | [
"Find",
"elements",
"given",
"a",
"By",
"strategy",
"and",
"locator",
".",
"Prefer",
"the",
"find_elements_by_",
"*",
"methods",
"when",
"possible",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L1016-L1045 | [
"def",
"find_elements",
"(",
"self",
",",
"by",
"=",
"By",
".",
"ID",
",",
"value",
"=",
"None",
")",
":",
"if",
"self",
".",
"w3c",
":",
"if",
"by",
"==",
"By",
".",
"ID",
":",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
"value",
"=",
"'[id=\"%s\"]'",
"%",
"value",
"elif",
"by",
"==",
"By",
".",
"TAG_NAME",
":",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
"elif",
"by",
"==",
"By",
".",
"CLASS_NAME",
":",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
"value",
"=",
"\".%s\"",
"%",
"value",
"elif",
"by",
"==",
"By",
".",
"NAME",
":",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
"value",
"=",
"'[name=\"%s\"]'",
"%",
"value",
"# Return empty list if driver returns null",
"# See https://github.com/SeleniumHQ/selenium/issues/4555",
"return",
"self",
".",
"execute",
"(",
"Command",
".",
"FIND_ELEMENTS",
",",
"{",
"'using'",
":",
"by",
",",
"'value'",
":",
"value",
"}",
")",
"[",
"'value'",
"]",
"or",
"[",
"]"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.get_screenshot_as_file | Saves a screenshot of the current window to a PNG image file. Returns
False if there is any IOError, else returns True. Use full paths in
your filename.
:Args:
- filename: The full path you wish to save your screenshot to. This
should end with a `.png` extension.
:Usage:
::
driver.get_screenshot_as_file('/Screenshots/foo.png') | py/selenium/webdriver/remote/webdriver.py | def get_screenshot_as_file(self, filename):
"""
Saves a screenshot of the current window to a PNG image file. Returns
False if there is any IOError, else returns True. Use full paths in
your filename.
:Args:
- filename: The full path you wish to save your screenshot to. This
should end with a `.png` extension.
:Usage:
::
driver.get_screenshot_as_file('/Screenshots/foo.png')
"""
if not filename.lower().endswith('.png'):
warnings.warn("name used for saved screenshot does not match file "
"type. It should end with a `.png` extension", UserWarning)
png = self.get_screenshot_as_png()
try:
with open(filename, 'wb') as f:
f.write(png)
except IOError:
return False
finally:
del png
return True | def get_screenshot_as_file(self, filename):
"""
Saves a screenshot of the current window to a PNG image file. Returns
False if there is any IOError, else returns True. Use full paths in
your filename.
:Args:
- filename: The full path you wish to save your screenshot to. This
should end with a `.png` extension.
:Usage:
::
driver.get_screenshot_as_file('/Screenshots/foo.png')
"""
if not filename.lower().endswith('.png'):
warnings.warn("name used for saved screenshot does not match file "
"type. It should end with a `.png` extension", UserWarning)
png = self.get_screenshot_as_png()
try:
with open(filename, 'wb') as f:
f.write(png)
except IOError:
return False
finally:
del png
return True | [
"Saves",
"a",
"screenshot",
"of",
"the",
"current",
"window",
"to",
"a",
"PNG",
"image",
"file",
".",
"Returns",
"False",
"if",
"there",
"is",
"any",
"IOError",
"else",
"returns",
"True",
".",
"Use",
"full",
"paths",
"in",
"your",
"filename",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L1054-L1080 | [
"def",
"get_screenshot_as_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"filename",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.png'",
")",
":",
"warnings",
".",
"warn",
"(",
"\"name used for saved screenshot does not match file \"",
"\"type. It should end with a `.png` extension\"",
",",
"UserWarning",
")",
"png",
"=",
"self",
".",
"get_screenshot_as_png",
"(",
")",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"png",
")",
"except",
"IOError",
":",
"return",
"False",
"finally",
":",
"del",
"png",
"return",
"True"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.set_window_size | Sets the width and height of the current window. (window.resizeTo)
:Args:
- width: the width in pixels to set the window to
- height: the height in pixels to set the window to
:Usage:
::
driver.set_window_size(800,600) | py/selenium/webdriver/remote/webdriver.py | def set_window_size(self, width, height, windowHandle='current'):
"""
Sets the width and height of the current window. (window.resizeTo)
:Args:
- width: the width in pixels to set the window to
- height: the height in pixels to set the window to
:Usage:
::
driver.set_window_size(800,600)
"""
if self.w3c:
if windowHandle != 'current':
warnings.warn("Only 'current' window is supported for W3C compatibile browsers.")
self.set_window_rect(width=int(width), height=int(height))
else:
self.execute(Command.SET_WINDOW_SIZE, {
'width': int(width),
'height': int(height),
'windowHandle': windowHandle}) | def set_window_size(self, width, height, windowHandle='current'):
"""
Sets the width and height of the current window. (window.resizeTo)
:Args:
- width: the width in pixels to set the window to
- height: the height in pixels to set the window to
:Usage:
::
driver.set_window_size(800,600)
"""
if self.w3c:
if windowHandle != 'current':
warnings.warn("Only 'current' window is supported for W3C compatibile browsers.")
self.set_window_rect(width=int(width), height=int(height))
else:
self.execute(Command.SET_WINDOW_SIZE, {
'width': int(width),
'height': int(height),
'windowHandle': windowHandle}) | [
"Sets",
"the",
"width",
"and",
"height",
"of",
"the",
"current",
"window",
".",
"(",
"window",
".",
"resizeTo",
")"
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L1122-L1143 | [
"def",
"set_window_size",
"(",
"self",
",",
"width",
",",
"height",
",",
"windowHandle",
"=",
"'current'",
")",
":",
"if",
"self",
".",
"w3c",
":",
"if",
"windowHandle",
"!=",
"'current'",
":",
"warnings",
".",
"warn",
"(",
"\"Only 'current' window is supported for W3C compatibile browsers.\"",
")",
"self",
".",
"set_window_rect",
"(",
"width",
"=",
"int",
"(",
"width",
")",
",",
"height",
"=",
"int",
"(",
"height",
")",
")",
"else",
":",
"self",
".",
"execute",
"(",
"Command",
".",
"SET_WINDOW_SIZE",
",",
"{",
"'width'",
":",
"int",
"(",
"width",
")",
",",
"'height'",
":",
"int",
"(",
"height",
")",
",",
"'windowHandle'",
":",
"windowHandle",
"}",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.get_window_size | Gets the width and height of the current window.
:Usage:
::
driver.get_window_size() | py/selenium/webdriver/remote/webdriver.py | def get_window_size(self, windowHandle='current'):
"""
Gets the width and height of the current window.
:Usage:
::
driver.get_window_size()
"""
command = Command.GET_WINDOW_SIZE
if self.w3c:
if windowHandle != 'current':
warnings.warn("Only 'current' window is supported for W3C compatibile browsers.")
size = self.get_window_rect()
else:
size = self.execute(command, {'windowHandle': windowHandle})
if size.get('value', None) is not None:
size = size['value']
return {k: size[k] for k in ('width', 'height')} | def get_window_size(self, windowHandle='current'):
"""
Gets the width and height of the current window.
:Usage:
::
driver.get_window_size()
"""
command = Command.GET_WINDOW_SIZE
if self.w3c:
if windowHandle != 'current':
warnings.warn("Only 'current' window is supported for W3C compatibile browsers.")
size = self.get_window_rect()
else:
size = self.execute(command, {'windowHandle': windowHandle})
if size.get('value', None) is not None:
size = size['value']
return {k: size[k] for k in ('width', 'height')} | [
"Gets",
"the",
"width",
"and",
"height",
"of",
"the",
"current",
"window",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L1145-L1165 | [
"def",
"get_window_size",
"(",
"self",
",",
"windowHandle",
"=",
"'current'",
")",
":",
"command",
"=",
"Command",
".",
"GET_WINDOW_SIZE",
"if",
"self",
".",
"w3c",
":",
"if",
"windowHandle",
"!=",
"'current'",
":",
"warnings",
".",
"warn",
"(",
"\"Only 'current' window is supported for W3C compatibile browsers.\"",
")",
"size",
"=",
"self",
".",
"get_window_rect",
"(",
")",
"else",
":",
"size",
"=",
"self",
".",
"execute",
"(",
"command",
",",
"{",
"'windowHandle'",
":",
"windowHandle",
"}",
")",
"if",
"size",
".",
"get",
"(",
"'value'",
",",
"None",
")",
"is",
"not",
"None",
":",
"size",
"=",
"size",
"[",
"'value'",
"]",
"return",
"{",
"k",
":",
"size",
"[",
"k",
"]",
"for",
"k",
"in",
"(",
"'width'",
",",
"'height'",
")",
"}"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.set_window_position | Sets the x,y position of the current window. (window.moveTo)
:Args:
- x: the x-coordinate in pixels to set the window position
- y: the y-coordinate in pixels to set the window position
:Usage:
::
driver.set_window_position(0,0) | py/selenium/webdriver/remote/webdriver.py | def set_window_position(self, x, y, windowHandle='current'):
"""
Sets the x,y position of the current window. (window.moveTo)
:Args:
- x: the x-coordinate in pixels to set the window position
- y: the y-coordinate in pixels to set the window position
:Usage:
::
driver.set_window_position(0,0)
"""
if self.w3c:
if windowHandle != 'current':
warnings.warn("Only 'current' window is supported for W3C compatibile browsers.")
return self.set_window_rect(x=int(x), y=int(y))
else:
self.execute(Command.SET_WINDOW_POSITION,
{
'x': int(x),
'y': int(y),
'windowHandle': windowHandle
}) | def set_window_position(self, x, y, windowHandle='current'):
"""
Sets the x,y position of the current window. (window.moveTo)
:Args:
- x: the x-coordinate in pixels to set the window position
- y: the y-coordinate in pixels to set the window position
:Usage:
::
driver.set_window_position(0,0)
"""
if self.w3c:
if windowHandle != 'current':
warnings.warn("Only 'current' window is supported for W3C compatibile browsers.")
return self.set_window_rect(x=int(x), y=int(y))
else:
self.execute(Command.SET_WINDOW_POSITION,
{
'x': int(x),
'y': int(y),
'windowHandle': windowHandle
}) | [
"Sets",
"the",
"x",
"y",
"position",
"of",
"the",
"current",
"window",
".",
"(",
"window",
".",
"moveTo",
")"
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L1167-L1190 | [
"def",
"set_window_position",
"(",
"self",
",",
"x",
",",
"y",
",",
"windowHandle",
"=",
"'current'",
")",
":",
"if",
"self",
".",
"w3c",
":",
"if",
"windowHandle",
"!=",
"'current'",
":",
"warnings",
".",
"warn",
"(",
"\"Only 'current' window is supported for W3C compatibile browsers.\"",
")",
"return",
"self",
".",
"set_window_rect",
"(",
"x",
"=",
"int",
"(",
"x",
")",
",",
"y",
"=",
"int",
"(",
"y",
")",
")",
"else",
":",
"self",
".",
"execute",
"(",
"Command",
".",
"SET_WINDOW_POSITION",
",",
"{",
"'x'",
":",
"int",
"(",
"x",
")",
",",
"'y'",
":",
"int",
"(",
"y",
")",
",",
"'windowHandle'",
":",
"windowHandle",
"}",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.get_window_position | Gets the x,y position of the current window.
:Usage:
::
driver.get_window_position() | py/selenium/webdriver/remote/webdriver.py | def get_window_position(self, windowHandle='current'):
"""
Gets the x,y position of the current window.
:Usage:
::
driver.get_window_position()
"""
if self.w3c:
if windowHandle != 'current':
warnings.warn("Only 'current' window is supported for W3C compatibile browsers.")
position = self.get_window_rect()
else:
position = self.execute(Command.GET_WINDOW_POSITION,
{'windowHandle': windowHandle})['value']
return {k: position[k] for k in ('x', 'y')} | def get_window_position(self, windowHandle='current'):
"""
Gets the x,y position of the current window.
:Usage:
::
driver.get_window_position()
"""
if self.w3c:
if windowHandle != 'current':
warnings.warn("Only 'current' window is supported for W3C compatibile browsers.")
position = self.get_window_rect()
else:
position = self.execute(Command.GET_WINDOW_POSITION,
{'windowHandle': windowHandle})['value']
return {k: position[k] for k in ('x', 'y')} | [
"Gets",
"the",
"x",
"y",
"position",
"of",
"the",
"current",
"window",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L1192-L1209 | [
"def",
"get_window_position",
"(",
"self",
",",
"windowHandle",
"=",
"'current'",
")",
":",
"if",
"self",
".",
"w3c",
":",
"if",
"windowHandle",
"!=",
"'current'",
":",
"warnings",
".",
"warn",
"(",
"\"Only 'current' window is supported for W3C compatibile browsers.\"",
")",
"position",
"=",
"self",
".",
"get_window_rect",
"(",
")",
"else",
":",
"position",
"=",
"self",
".",
"execute",
"(",
"Command",
".",
"GET_WINDOW_POSITION",
",",
"{",
"'windowHandle'",
":",
"windowHandle",
"}",
")",
"[",
"'value'",
"]",
"return",
"{",
"k",
":",
"position",
"[",
"k",
"]",
"for",
"k",
"in",
"(",
"'x'",
",",
"'y'",
")",
"}"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.set_window_rect | Sets the x, y coordinates of the window as well as height and width of
the current window. This method is only supported for W3C compatible
browsers; other browsers should use `set_window_position` and
`set_window_size`.
:Usage:
::
driver.set_window_rect(x=10, y=10)
driver.set_window_rect(width=100, height=200)
driver.set_window_rect(x=10, y=10, width=100, height=200) | py/selenium/webdriver/remote/webdriver.py | def set_window_rect(self, x=None, y=None, width=None, height=None):
"""
Sets the x, y coordinates of the window as well as height and width of
the current window. This method is only supported for W3C compatible
browsers; other browsers should use `set_window_position` and
`set_window_size`.
:Usage:
::
driver.set_window_rect(x=10, y=10)
driver.set_window_rect(width=100, height=200)
driver.set_window_rect(x=10, y=10, width=100, height=200)
"""
if not self.w3c:
raise UnknownMethodException("set_window_rect is only supported for W3C compatible browsers")
if (x is None and y is None) and (height is None and width is None):
raise InvalidArgumentException("x and y or height and width need values")
return self.execute(Command.SET_WINDOW_RECT, {"x": x, "y": y,
"width": width,
"height": height})['value'] | def set_window_rect(self, x=None, y=None, width=None, height=None):
"""
Sets the x, y coordinates of the window as well as height and width of
the current window. This method is only supported for W3C compatible
browsers; other browsers should use `set_window_position` and
`set_window_size`.
:Usage:
::
driver.set_window_rect(x=10, y=10)
driver.set_window_rect(width=100, height=200)
driver.set_window_rect(x=10, y=10, width=100, height=200)
"""
if not self.w3c:
raise UnknownMethodException("set_window_rect is only supported for W3C compatible browsers")
if (x is None and y is None) and (height is None and width is None):
raise InvalidArgumentException("x and y or height and width need values")
return self.execute(Command.SET_WINDOW_RECT, {"x": x, "y": y,
"width": width,
"height": height})['value'] | [
"Sets",
"the",
"x",
"y",
"coordinates",
"of",
"the",
"window",
"as",
"well",
"as",
"height",
"and",
"width",
"of",
"the",
"current",
"window",
".",
"This",
"method",
"is",
"only",
"supported",
"for",
"W3C",
"compatible",
"browsers",
";",
"other",
"browsers",
"should",
"use",
"set_window_position",
"and",
"set_window_size",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L1223-L1245 | [
"def",
"set_window_rect",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"w3c",
":",
"raise",
"UnknownMethodException",
"(",
"\"set_window_rect is only supported for W3C compatible browsers\"",
")",
"if",
"(",
"x",
"is",
"None",
"and",
"y",
"is",
"None",
")",
"and",
"(",
"height",
"is",
"None",
"and",
"width",
"is",
"None",
")",
":",
"raise",
"InvalidArgumentException",
"(",
"\"x and y or height and width need values\"",
")",
"return",
"self",
".",
"execute",
"(",
"Command",
".",
"SET_WINDOW_RECT",
",",
"{",
"\"x\"",
":",
"x",
",",
"\"y\"",
":",
"y",
",",
"\"width\"",
":",
"width",
",",
"\"height\"",
":",
"height",
"}",
")",
"[",
"'value'",
"]"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.file_detector | Set the file detector to be used when sending keyboard input.
By default, this is set to a file detector that does nothing.
see FileDetector
see LocalFileDetector
see UselessFileDetector
:Args:
- detector: The detector to use. Must not be None. | py/selenium/webdriver/remote/webdriver.py | def file_detector(self, detector):
"""
Set the file detector to be used when sending keyboard input.
By default, this is set to a file detector that does nothing.
see FileDetector
see LocalFileDetector
see UselessFileDetector
:Args:
- detector: The detector to use. Must not be None.
"""
if detector is None:
raise WebDriverException("You may not set a file detector that is null")
if not isinstance(detector, FileDetector):
raise WebDriverException("Detector has to be instance of FileDetector")
self._file_detector = detector | def file_detector(self, detector):
"""
Set the file detector to be used when sending keyboard input.
By default, this is set to a file detector that does nothing.
see FileDetector
see LocalFileDetector
see UselessFileDetector
:Args:
- detector: The detector to use. Must not be None.
"""
if detector is None:
raise WebDriverException("You may not set a file detector that is null")
if not isinstance(detector, FileDetector):
raise WebDriverException("Detector has to be instance of FileDetector")
self._file_detector = detector | [
"Set",
"the",
"file",
"detector",
"to",
"be",
"used",
"when",
"sending",
"keyboard",
"input",
".",
"By",
"default",
"this",
"is",
"set",
"to",
"a",
"file",
"detector",
"that",
"does",
"nothing",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L1252-L1268 | [
"def",
"file_detector",
"(",
"self",
",",
"detector",
")",
":",
"if",
"detector",
"is",
"None",
":",
"raise",
"WebDriverException",
"(",
"\"You may not set a file detector that is null\"",
")",
"if",
"not",
"isinstance",
"(",
"detector",
",",
"FileDetector",
")",
":",
"raise",
"WebDriverException",
"(",
"\"Detector has to be instance of FileDetector\"",
")",
"self",
".",
"_file_detector",
"=",
"detector"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.orientation | Sets the current orientation of the device
:Args:
- value: orientation to set it to.
:Usage:
::
driver.orientation = 'landscape' | py/selenium/webdriver/remote/webdriver.py | def orientation(self, value):
"""
Sets the current orientation of the device
:Args:
- value: orientation to set it to.
:Usage:
::
driver.orientation = 'landscape'
"""
allowed_values = ['LANDSCAPE', 'PORTRAIT']
if value.upper() in allowed_values:
self.execute(Command.SET_SCREEN_ORIENTATION, {'orientation': value})
else:
raise WebDriverException("You can only set the orientation to 'LANDSCAPE' and 'PORTRAIT'") | def orientation(self, value):
"""
Sets the current orientation of the device
:Args:
- value: orientation to set it to.
:Usage:
::
driver.orientation = 'landscape'
"""
allowed_values = ['LANDSCAPE', 'PORTRAIT']
if value.upper() in allowed_values:
self.execute(Command.SET_SCREEN_ORIENTATION, {'orientation': value})
else:
raise WebDriverException("You can only set the orientation to 'LANDSCAPE' and 'PORTRAIT'") | [
"Sets",
"the",
"current",
"orientation",
"of",
"the",
"device"
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L1283-L1299 | [
"def",
"orientation",
"(",
"self",
",",
"value",
")",
":",
"allowed_values",
"=",
"[",
"'LANDSCAPE'",
",",
"'PORTRAIT'",
"]",
"if",
"value",
".",
"upper",
"(",
")",
"in",
"allowed_values",
":",
"self",
".",
"execute",
"(",
"Command",
".",
"SET_SCREEN_ORIENTATION",
",",
"{",
"'orientation'",
":",
"value",
"}",
")",
"else",
":",
"raise",
"WebDriverException",
"(",
"\"You can only set the orientation to 'LANDSCAPE' and 'PORTRAIT'\"",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | ErrorHandler.check_response | Checks that a JSON response from the WebDriver does not have an error.
:Args:
- response - The JSON response from the WebDriver server as a dictionary
object.
:Raises: If the response contains an error message. | py/selenium/webdriver/remote/errorhandler.py | def check_response(self, response):
"""
Checks that a JSON response from the WebDriver does not have an error.
:Args:
- response - The JSON response from the WebDriver server as a dictionary
object.
:Raises: If the response contains an error message.
"""
status = response.get('status', None)
if status is None or status == ErrorCode.SUCCESS:
return
value = None
message = response.get("message", "")
screen = response.get("screen", "")
stacktrace = None
if isinstance(status, int):
value_json = response.get('value', None)
if value_json and isinstance(value_json, basestring):
import json
try:
value = json.loads(value_json)
if len(value.keys()) == 1:
value = value['value']
status = value.get('error', None)
if status is None:
status = value["status"]
message = value["value"]
if not isinstance(message, basestring):
value = message
message = message.get('message')
else:
message = value.get('message', None)
except ValueError:
pass
if status in ErrorCode.NO_SUCH_ELEMENT:
exception_class = NoSuchElementException
elif status in ErrorCode.NO_SUCH_FRAME:
exception_class = NoSuchFrameException
elif status in ErrorCode.NO_SUCH_WINDOW:
exception_class = NoSuchWindowException
elif status in ErrorCode.STALE_ELEMENT_REFERENCE:
exception_class = StaleElementReferenceException
elif status in ErrorCode.ELEMENT_NOT_VISIBLE:
exception_class = ElementNotVisibleException
elif status in ErrorCode.INVALID_ELEMENT_STATE:
exception_class = InvalidElementStateException
elif status in ErrorCode.INVALID_SELECTOR \
or status in ErrorCode.INVALID_XPATH_SELECTOR \
or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER:
exception_class = InvalidSelectorException
elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE:
exception_class = ElementNotSelectableException
elif status in ErrorCode.ELEMENT_NOT_INTERACTABLE:
exception_class = ElementNotInteractableException
elif status in ErrorCode.INVALID_COOKIE_DOMAIN:
exception_class = InvalidCookieDomainException
elif status in ErrorCode.UNABLE_TO_SET_COOKIE:
exception_class = UnableToSetCookieException
elif status in ErrorCode.TIMEOUT:
exception_class = TimeoutException
elif status in ErrorCode.SCRIPT_TIMEOUT:
exception_class = TimeoutException
elif status in ErrorCode.UNKNOWN_ERROR:
exception_class = WebDriverException
elif status in ErrorCode.UNEXPECTED_ALERT_OPEN:
exception_class = UnexpectedAlertPresentException
elif status in ErrorCode.NO_ALERT_OPEN:
exception_class = NoAlertPresentException
elif status in ErrorCode.IME_NOT_AVAILABLE:
exception_class = ImeNotAvailableException
elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED:
exception_class = ImeActivationFailedException
elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS:
exception_class = MoveTargetOutOfBoundsException
elif status in ErrorCode.JAVASCRIPT_ERROR:
exception_class = JavascriptException
elif status in ErrorCode.SESSION_NOT_CREATED:
exception_class = SessionNotCreatedException
elif status in ErrorCode.INVALID_ARGUMENT:
exception_class = InvalidArgumentException
elif status in ErrorCode.NO_SUCH_COOKIE:
exception_class = NoSuchCookieException
elif status in ErrorCode.UNABLE_TO_CAPTURE_SCREEN:
exception_class = ScreenshotException
elif status in ErrorCode.ELEMENT_CLICK_INTERCEPTED:
exception_class = ElementClickInterceptedException
elif status in ErrorCode.INSECURE_CERTIFICATE:
exception_class = InsecureCertificateException
elif status in ErrorCode.INVALID_COORDINATES:
exception_class = InvalidCoordinatesException
elif status in ErrorCode.INVALID_SESSION_ID:
exception_class = InvalidSessionIdException
elif status in ErrorCode.UNKNOWN_METHOD:
exception_class = UnknownMethodException
else:
exception_class = WebDriverException
if value == '' or value is None:
value = response['value']
if isinstance(value, basestring):
raise exception_class(value)
if message == "" and 'message' in value:
message = value['message']
screen = None
if 'screen' in value:
screen = value['screen']
stacktrace = None
if 'stackTrace' in value and value['stackTrace']:
stacktrace = []
try:
for frame in value['stackTrace']:
line = self._value_or_default(frame, 'lineNumber', '')
file = self._value_or_default(frame, 'fileName', '<anonymous>')
if line:
file = "%s:%s" % (file, line)
meth = self._value_or_default(frame, 'methodName', '<anonymous>')
if 'className' in frame:
meth = "%s.%s" % (frame['className'], meth)
msg = " at %s (%s)"
msg = msg % (meth, file)
stacktrace.append(msg)
except TypeError:
pass
if exception_class == UnexpectedAlertPresentException:
alert_text = None
if 'data' in value:
alert_text = value['data'].get('text')
elif 'alert' in value:
alert_text = value['alert'].get('text')
raise exception_class(message, screen, stacktrace, alert_text)
raise exception_class(message, screen, stacktrace) | def check_response(self, response):
"""
Checks that a JSON response from the WebDriver does not have an error.
:Args:
- response - The JSON response from the WebDriver server as a dictionary
object.
:Raises: If the response contains an error message.
"""
status = response.get('status', None)
if status is None or status == ErrorCode.SUCCESS:
return
value = None
message = response.get("message", "")
screen = response.get("screen", "")
stacktrace = None
if isinstance(status, int):
value_json = response.get('value', None)
if value_json and isinstance(value_json, basestring):
import json
try:
value = json.loads(value_json)
if len(value.keys()) == 1:
value = value['value']
status = value.get('error', None)
if status is None:
status = value["status"]
message = value["value"]
if not isinstance(message, basestring):
value = message
message = message.get('message')
else:
message = value.get('message', None)
except ValueError:
pass
if status in ErrorCode.NO_SUCH_ELEMENT:
exception_class = NoSuchElementException
elif status in ErrorCode.NO_SUCH_FRAME:
exception_class = NoSuchFrameException
elif status in ErrorCode.NO_SUCH_WINDOW:
exception_class = NoSuchWindowException
elif status in ErrorCode.STALE_ELEMENT_REFERENCE:
exception_class = StaleElementReferenceException
elif status in ErrorCode.ELEMENT_NOT_VISIBLE:
exception_class = ElementNotVisibleException
elif status in ErrorCode.INVALID_ELEMENT_STATE:
exception_class = InvalidElementStateException
elif status in ErrorCode.INVALID_SELECTOR \
or status in ErrorCode.INVALID_XPATH_SELECTOR \
or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER:
exception_class = InvalidSelectorException
elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE:
exception_class = ElementNotSelectableException
elif status in ErrorCode.ELEMENT_NOT_INTERACTABLE:
exception_class = ElementNotInteractableException
elif status in ErrorCode.INVALID_COOKIE_DOMAIN:
exception_class = InvalidCookieDomainException
elif status in ErrorCode.UNABLE_TO_SET_COOKIE:
exception_class = UnableToSetCookieException
elif status in ErrorCode.TIMEOUT:
exception_class = TimeoutException
elif status in ErrorCode.SCRIPT_TIMEOUT:
exception_class = TimeoutException
elif status in ErrorCode.UNKNOWN_ERROR:
exception_class = WebDriverException
elif status in ErrorCode.UNEXPECTED_ALERT_OPEN:
exception_class = UnexpectedAlertPresentException
elif status in ErrorCode.NO_ALERT_OPEN:
exception_class = NoAlertPresentException
elif status in ErrorCode.IME_NOT_AVAILABLE:
exception_class = ImeNotAvailableException
elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED:
exception_class = ImeActivationFailedException
elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS:
exception_class = MoveTargetOutOfBoundsException
elif status in ErrorCode.JAVASCRIPT_ERROR:
exception_class = JavascriptException
elif status in ErrorCode.SESSION_NOT_CREATED:
exception_class = SessionNotCreatedException
elif status in ErrorCode.INVALID_ARGUMENT:
exception_class = InvalidArgumentException
elif status in ErrorCode.NO_SUCH_COOKIE:
exception_class = NoSuchCookieException
elif status in ErrorCode.UNABLE_TO_CAPTURE_SCREEN:
exception_class = ScreenshotException
elif status in ErrorCode.ELEMENT_CLICK_INTERCEPTED:
exception_class = ElementClickInterceptedException
elif status in ErrorCode.INSECURE_CERTIFICATE:
exception_class = InsecureCertificateException
elif status in ErrorCode.INVALID_COORDINATES:
exception_class = InvalidCoordinatesException
elif status in ErrorCode.INVALID_SESSION_ID:
exception_class = InvalidSessionIdException
elif status in ErrorCode.UNKNOWN_METHOD:
exception_class = UnknownMethodException
else:
exception_class = WebDriverException
if value == '' or value is None:
value = response['value']
if isinstance(value, basestring):
raise exception_class(value)
if message == "" and 'message' in value:
message = value['message']
screen = None
if 'screen' in value:
screen = value['screen']
stacktrace = None
if 'stackTrace' in value and value['stackTrace']:
stacktrace = []
try:
for frame in value['stackTrace']:
line = self._value_or_default(frame, 'lineNumber', '')
file = self._value_or_default(frame, 'fileName', '<anonymous>')
if line:
file = "%s:%s" % (file, line)
meth = self._value_or_default(frame, 'methodName', '<anonymous>')
if 'className' in frame:
meth = "%s.%s" % (frame['className'], meth)
msg = " at %s (%s)"
msg = msg % (meth, file)
stacktrace.append(msg)
except TypeError:
pass
if exception_class == UnexpectedAlertPresentException:
alert_text = None
if 'data' in value:
alert_text = value['data'].get('text')
elif 'alert' in value:
alert_text = value['alert'].get('text')
raise exception_class(message, screen, stacktrace, alert_text)
raise exception_class(message, screen, stacktrace) | [
"Checks",
"that",
"a",
"JSON",
"response",
"from",
"the",
"WebDriver",
"does",
"not",
"have",
"an",
"error",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/errorhandler.py#L102-L236 | [
"def",
"check_response",
"(",
"self",
",",
"response",
")",
":",
"status",
"=",
"response",
".",
"get",
"(",
"'status'",
",",
"None",
")",
"if",
"status",
"is",
"None",
"or",
"status",
"==",
"ErrorCode",
".",
"SUCCESS",
":",
"return",
"value",
"=",
"None",
"message",
"=",
"response",
".",
"get",
"(",
"\"message\"",
",",
"\"\"",
")",
"screen",
"=",
"response",
".",
"get",
"(",
"\"screen\"",
",",
"\"\"",
")",
"stacktrace",
"=",
"None",
"if",
"isinstance",
"(",
"status",
",",
"int",
")",
":",
"value_json",
"=",
"response",
".",
"get",
"(",
"'value'",
",",
"None",
")",
"if",
"value_json",
"and",
"isinstance",
"(",
"value_json",
",",
"basestring",
")",
":",
"import",
"json",
"try",
":",
"value",
"=",
"json",
".",
"loads",
"(",
"value_json",
")",
"if",
"len",
"(",
"value",
".",
"keys",
"(",
")",
")",
"==",
"1",
":",
"value",
"=",
"value",
"[",
"'value'",
"]",
"status",
"=",
"value",
".",
"get",
"(",
"'error'",
",",
"None",
")",
"if",
"status",
"is",
"None",
":",
"status",
"=",
"value",
"[",
"\"status\"",
"]",
"message",
"=",
"value",
"[",
"\"value\"",
"]",
"if",
"not",
"isinstance",
"(",
"message",
",",
"basestring",
")",
":",
"value",
"=",
"message",
"message",
"=",
"message",
".",
"get",
"(",
"'message'",
")",
"else",
":",
"message",
"=",
"value",
".",
"get",
"(",
"'message'",
",",
"None",
")",
"except",
"ValueError",
":",
"pass",
"if",
"status",
"in",
"ErrorCode",
".",
"NO_SUCH_ELEMENT",
":",
"exception_class",
"=",
"NoSuchElementException",
"elif",
"status",
"in",
"ErrorCode",
".",
"NO_SUCH_FRAME",
":",
"exception_class",
"=",
"NoSuchFrameException",
"elif",
"status",
"in",
"ErrorCode",
".",
"NO_SUCH_WINDOW",
":",
"exception_class",
"=",
"NoSuchWindowException",
"elif",
"status",
"in",
"ErrorCode",
".",
"STALE_ELEMENT_REFERENCE",
":",
"exception_class",
"=",
"StaleElementReferenceException",
"elif",
"status",
"in",
"ErrorCode",
".",
"ELEMENT_NOT_VISIBLE",
":",
"exception_class",
"=",
"ElementNotVisibleException",
"elif",
"status",
"in",
"ErrorCode",
".",
"INVALID_ELEMENT_STATE",
":",
"exception_class",
"=",
"InvalidElementStateException",
"elif",
"status",
"in",
"ErrorCode",
".",
"INVALID_SELECTOR",
"or",
"status",
"in",
"ErrorCode",
".",
"INVALID_XPATH_SELECTOR",
"or",
"status",
"in",
"ErrorCode",
".",
"INVALID_XPATH_SELECTOR_RETURN_TYPER",
":",
"exception_class",
"=",
"InvalidSelectorException",
"elif",
"status",
"in",
"ErrorCode",
".",
"ELEMENT_IS_NOT_SELECTABLE",
":",
"exception_class",
"=",
"ElementNotSelectableException",
"elif",
"status",
"in",
"ErrorCode",
".",
"ELEMENT_NOT_INTERACTABLE",
":",
"exception_class",
"=",
"ElementNotInteractableException",
"elif",
"status",
"in",
"ErrorCode",
".",
"INVALID_COOKIE_DOMAIN",
":",
"exception_class",
"=",
"InvalidCookieDomainException",
"elif",
"status",
"in",
"ErrorCode",
".",
"UNABLE_TO_SET_COOKIE",
":",
"exception_class",
"=",
"UnableToSetCookieException",
"elif",
"status",
"in",
"ErrorCode",
".",
"TIMEOUT",
":",
"exception_class",
"=",
"TimeoutException",
"elif",
"status",
"in",
"ErrorCode",
".",
"SCRIPT_TIMEOUT",
":",
"exception_class",
"=",
"TimeoutException",
"elif",
"status",
"in",
"ErrorCode",
".",
"UNKNOWN_ERROR",
":",
"exception_class",
"=",
"WebDriverException",
"elif",
"status",
"in",
"ErrorCode",
".",
"UNEXPECTED_ALERT_OPEN",
":",
"exception_class",
"=",
"UnexpectedAlertPresentException",
"elif",
"status",
"in",
"ErrorCode",
".",
"NO_ALERT_OPEN",
":",
"exception_class",
"=",
"NoAlertPresentException",
"elif",
"status",
"in",
"ErrorCode",
".",
"IME_NOT_AVAILABLE",
":",
"exception_class",
"=",
"ImeNotAvailableException",
"elif",
"status",
"in",
"ErrorCode",
".",
"IME_ENGINE_ACTIVATION_FAILED",
":",
"exception_class",
"=",
"ImeActivationFailedException",
"elif",
"status",
"in",
"ErrorCode",
".",
"MOVE_TARGET_OUT_OF_BOUNDS",
":",
"exception_class",
"=",
"MoveTargetOutOfBoundsException",
"elif",
"status",
"in",
"ErrorCode",
".",
"JAVASCRIPT_ERROR",
":",
"exception_class",
"=",
"JavascriptException",
"elif",
"status",
"in",
"ErrorCode",
".",
"SESSION_NOT_CREATED",
":",
"exception_class",
"=",
"SessionNotCreatedException",
"elif",
"status",
"in",
"ErrorCode",
".",
"INVALID_ARGUMENT",
":",
"exception_class",
"=",
"InvalidArgumentException",
"elif",
"status",
"in",
"ErrorCode",
".",
"NO_SUCH_COOKIE",
":",
"exception_class",
"=",
"NoSuchCookieException",
"elif",
"status",
"in",
"ErrorCode",
".",
"UNABLE_TO_CAPTURE_SCREEN",
":",
"exception_class",
"=",
"ScreenshotException",
"elif",
"status",
"in",
"ErrorCode",
".",
"ELEMENT_CLICK_INTERCEPTED",
":",
"exception_class",
"=",
"ElementClickInterceptedException",
"elif",
"status",
"in",
"ErrorCode",
".",
"INSECURE_CERTIFICATE",
":",
"exception_class",
"=",
"InsecureCertificateException",
"elif",
"status",
"in",
"ErrorCode",
".",
"INVALID_COORDINATES",
":",
"exception_class",
"=",
"InvalidCoordinatesException",
"elif",
"status",
"in",
"ErrorCode",
".",
"INVALID_SESSION_ID",
":",
"exception_class",
"=",
"InvalidSessionIdException",
"elif",
"status",
"in",
"ErrorCode",
".",
"UNKNOWN_METHOD",
":",
"exception_class",
"=",
"UnknownMethodException",
"else",
":",
"exception_class",
"=",
"WebDriverException",
"if",
"value",
"==",
"''",
"or",
"value",
"is",
"None",
":",
"value",
"=",
"response",
"[",
"'value'",
"]",
"if",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"raise",
"exception_class",
"(",
"value",
")",
"if",
"message",
"==",
"\"\"",
"and",
"'message'",
"in",
"value",
":",
"message",
"=",
"value",
"[",
"'message'",
"]",
"screen",
"=",
"None",
"if",
"'screen'",
"in",
"value",
":",
"screen",
"=",
"value",
"[",
"'screen'",
"]",
"stacktrace",
"=",
"None",
"if",
"'stackTrace'",
"in",
"value",
"and",
"value",
"[",
"'stackTrace'",
"]",
":",
"stacktrace",
"=",
"[",
"]",
"try",
":",
"for",
"frame",
"in",
"value",
"[",
"'stackTrace'",
"]",
":",
"line",
"=",
"self",
".",
"_value_or_default",
"(",
"frame",
",",
"'lineNumber'",
",",
"''",
")",
"file",
"=",
"self",
".",
"_value_or_default",
"(",
"frame",
",",
"'fileName'",
",",
"'<anonymous>'",
")",
"if",
"line",
":",
"file",
"=",
"\"%s:%s\"",
"%",
"(",
"file",
",",
"line",
")",
"meth",
"=",
"self",
".",
"_value_or_default",
"(",
"frame",
",",
"'methodName'",
",",
"'<anonymous>'",
")",
"if",
"'className'",
"in",
"frame",
":",
"meth",
"=",
"\"%s.%s\"",
"%",
"(",
"frame",
"[",
"'className'",
"]",
",",
"meth",
")",
"msg",
"=",
"\" at %s (%s)\"",
"msg",
"=",
"msg",
"%",
"(",
"meth",
",",
"file",
")",
"stacktrace",
".",
"append",
"(",
"msg",
")",
"except",
"TypeError",
":",
"pass",
"if",
"exception_class",
"==",
"UnexpectedAlertPresentException",
":",
"alert_text",
"=",
"None",
"if",
"'data'",
"in",
"value",
":",
"alert_text",
"=",
"value",
"[",
"'data'",
"]",
".",
"get",
"(",
"'text'",
")",
"elif",
"'alert'",
"in",
"value",
":",
"alert_text",
"=",
"value",
"[",
"'alert'",
"]",
".",
"get",
"(",
"'text'",
")",
"raise",
"exception_class",
"(",
"message",
",",
"screen",
",",
"stacktrace",
",",
"alert_text",
")",
"raise",
"exception_class",
"(",
"message",
",",
"screen",
",",
"stacktrace",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriverWait.until | Calls the method provided with the driver as an argument until the \
return value does not evaluate to ``False``.
:param method: callable(WebDriver)
:param message: optional message for :exc:`TimeoutException`
:returns: the result of the last call to `method`
:raises: :exc:`selenium.common.exceptions.TimeoutException` if timeout occurs | py/selenium/webdriver/support/wait.py | def until(self, method, message=''):
"""Calls the method provided with the driver as an argument until the \
return value does not evaluate to ``False``.
:param method: callable(WebDriver)
:param message: optional message for :exc:`TimeoutException`
:returns: the result of the last call to `method`
:raises: :exc:`selenium.common.exceptions.TimeoutException` if timeout occurs
"""
screen = None
stacktrace = None
end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if value:
return value
except self._ignored_exceptions as exc:
screen = getattr(exc, 'screen', None)
stacktrace = getattr(exc, 'stacktrace', None)
time.sleep(self._poll)
if time.time() > end_time:
break
raise TimeoutException(message, screen, stacktrace) | def until(self, method, message=''):
"""Calls the method provided with the driver as an argument until the \
return value does not evaluate to ``False``.
:param method: callable(WebDriver)
:param message: optional message for :exc:`TimeoutException`
:returns: the result of the last call to `method`
:raises: :exc:`selenium.common.exceptions.TimeoutException` if timeout occurs
"""
screen = None
stacktrace = None
end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if value:
return value
except self._ignored_exceptions as exc:
screen = getattr(exc, 'screen', None)
stacktrace = getattr(exc, 'stacktrace', None)
time.sleep(self._poll)
if time.time() > end_time:
break
raise TimeoutException(message, screen, stacktrace) | [
"Calls",
"the",
"method",
"provided",
"with",
"the",
"driver",
"as",
"an",
"argument",
"until",
"the",
"\\",
"return",
"value",
"does",
"not",
"evaluate",
"to",
"False",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/support/wait.py#L62-L86 | [
"def",
"until",
"(",
"self",
",",
"method",
",",
"message",
"=",
"''",
")",
":",
"screen",
"=",
"None",
"stacktrace",
"=",
"None",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"+",
"self",
".",
"_timeout",
"while",
"True",
":",
"try",
":",
"value",
"=",
"method",
"(",
"self",
".",
"_driver",
")",
"if",
"value",
":",
"return",
"value",
"except",
"self",
".",
"_ignored_exceptions",
"as",
"exc",
":",
"screen",
"=",
"getattr",
"(",
"exc",
",",
"'screen'",
",",
"None",
")",
"stacktrace",
"=",
"getattr",
"(",
"exc",
",",
"'stacktrace'",
",",
"None",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"_poll",
")",
"if",
"time",
".",
"time",
"(",
")",
">",
"end_time",
":",
"break",
"raise",
"TimeoutException",
"(",
"message",
",",
"screen",
",",
"stacktrace",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriverWait.until_not | Calls the method provided with the driver as an argument until the \
return value evaluates to ``False``.
:param method: callable(WebDriver)
:param message: optional message for :exc:`TimeoutException`
:returns: the result of the last call to `method`, or
``True`` if `method` has raised one of the ignored exceptions
:raises: :exc:`selenium.common.exceptions.TimeoutException` if timeout occurs | py/selenium/webdriver/support/wait.py | def until_not(self, method, message=''):
"""Calls the method provided with the driver as an argument until the \
return value evaluates to ``False``.
:param method: callable(WebDriver)
:param message: optional message for :exc:`TimeoutException`
:returns: the result of the last call to `method`, or
``True`` if `method` has raised one of the ignored exceptions
:raises: :exc:`selenium.common.exceptions.TimeoutException` if timeout occurs
"""
end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if not value:
return value
except self._ignored_exceptions:
return True
time.sleep(self._poll)
if time.time() > end_time:
break
raise TimeoutException(message) | def until_not(self, method, message=''):
"""Calls the method provided with the driver as an argument until the \
return value evaluates to ``False``.
:param method: callable(WebDriver)
:param message: optional message for :exc:`TimeoutException`
:returns: the result of the last call to `method`, or
``True`` if `method` has raised one of the ignored exceptions
:raises: :exc:`selenium.common.exceptions.TimeoutException` if timeout occurs
"""
end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if not value:
return value
except self._ignored_exceptions:
return True
time.sleep(self._poll)
if time.time() > end_time:
break
raise TimeoutException(message) | [
"Calls",
"the",
"method",
"provided",
"with",
"the",
"driver",
"as",
"an",
"argument",
"until",
"the",
"\\",
"return",
"value",
"evaluates",
"to",
"False",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/support/wait.py#L88-L109 | [
"def",
"until_not",
"(",
"self",
",",
"method",
",",
"message",
"=",
"''",
")",
":",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"+",
"self",
".",
"_timeout",
"while",
"True",
":",
"try",
":",
"value",
"=",
"method",
"(",
"self",
".",
"_driver",
")",
"if",
"not",
"value",
":",
"return",
"value",
"except",
"self",
".",
"_ignored_exceptions",
":",
"return",
"True",
"time",
".",
"sleep",
"(",
"self",
".",
"_poll",
")",
"if",
"time",
".",
"time",
"(",
")",
">",
"end_time",
":",
"break",
"raise",
"TimeoutException",
"(",
"message",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.quit | Quits the driver and close every associated window. | py/selenium/webdriver/firefox/webdriver.py | def quit(self):
"""Quits the driver and close every associated window."""
try:
RemoteWebDriver.quit(self)
except Exception:
# We don't care about the message because something probably has gone wrong
pass
if self.w3c:
self.service.stop()
else:
self.binary.kill()
if self.profile is not None:
try:
shutil.rmtree(self.profile.path)
if self.profile.tempfolder is not None:
shutil.rmtree(self.profile.tempfolder)
except Exception as e:
print(str(e)) | def quit(self):
"""Quits the driver and close every associated window."""
try:
RemoteWebDriver.quit(self)
except Exception:
# We don't care about the message because something probably has gone wrong
pass
if self.w3c:
self.service.stop()
else:
self.binary.kill()
if self.profile is not None:
try:
shutil.rmtree(self.profile.path)
if self.profile.tempfolder is not None:
shutil.rmtree(self.profile.tempfolder)
except Exception as e:
print(str(e)) | [
"Quits",
"the",
"driver",
"and",
"close",
"every",
"associated",
"window",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/webdriver.py#L178-L197 | [
"def",
"quit",
"(",
"self",
")",
":",
"try",
":",
"RemoteWebDriver",
".",
"quit",
"(",
"self",
")",
"except",
"Exception",
":",
"# We don't care about the message because something probably has gone wrong",
"pass",
"if",
"self",
".",
"w3c",
":",
"self",
".",
"service",
".",
"stop",
"(",
")",
"else",
":",
"self",
".",
"binary",
".",
"kill",
"(",
")",
"if",
"self",
".",
"profile",
"is",
"not",
"None",
":",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"profile",
".",
"path",
")",
"if",
"self",
".",
"profile",
".",
"tempfolder",
"is",
"not",
"None",
":",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"profile",
".",
"tempfolder",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"str",
"(",
"e",
")",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.context | Sets the context that Selenium commands are running in using
a `with` statement. The state of the context on the server is
saved before entering the block, and restored upon exiting it.
:param context: Context, may be one of the class properties
`CONTEXT_CHROME` or `CONTEXT_CONTENT`.
Usage example::
with selenium.context(selenium.CONTEXT_CHROME):
# chrome scope
... do stuff ... | py/selenium/webdriver/firefox/webdriver.py | def context(self, context):
"""Sets the context that Selenium commands are running in using
a `with` statement. The state of the context on the server is
saved before entering the block, and restored upon exiting it.
:param context: Context, may be one of the class properties
`CONTEXT_CHROME` or `CONTEXT_CONTENT`.
Usage example::
with selenium.context(selenium.CONTEXT_CHROME):
# chrome scope
... do stuff ...
"""
initial_context = self.execute('GET_CONTEXT').pop('value')
self.set_context(context)
try:
yield
finally:
self.set_context(initial_context) | def context(self, context):
"""Sets the context that Selenium commands are running in using
a `with` statement. The state of the context on the server is
saved before entering the block, and restored upon exiting it.
:param context: Context, may be one of the class properties
`CONTEXT_CHROME` or `CONTEXT_CONTENT`.
Usage example::
with selenium.context(selenium.CONTEXT_CHROME):
# chrome scope
... do stuff ...
"""
initial_context = self.execute('GET_CONTEXT').pop('value')
self.set_context(context)
try:
yield
finally:
self.set_context(initial_context) | [
"Sets",
"the",
"context",
"that",
"Selenium",
"commands",
"are",
"running",
"in",
"using",
"a",
"with",
"statement",
".",
"The",
"state",
"of",
"the",
"context",
"on",
"the",
"server",
"is",
"saved",
"before",
"entering",
"the",
"block",
"and",
"restored",
"upon",
"exiting",
"it",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/webdriver.py#L209-L228 | [
"def",
"context",
"(",
"self",
",",
"context",
")",
":",
"initial_context",
"=",
"self",
".",
"execute",
"(",
"'GET_CONTEXT'",
")",
".",
"pop",
"(",
"'value'",
")",
"self",
".",
"set_context",
"(",
"context",
")",
"try",
":",
"yield",
"finally",
":",
"self",
".",
"set_context",
"(",
"initial_context",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | WebDriver.install_addon | Installs Firefox addon.
Returns identifier of installed addon. This identifier can later
be used to uninstall addon.
:param path: Absolute path to the addon that will be installed.
:Usage:
::
driver.install_addon('/path/to/firebug.xpi') | py/selenium/webdriver/firefox/webdriver.py | def install_addon(self, path, temporary=None):
"""
Installs Firefox addon.
Returns identifier of installed addon. This identifier can later
be used to uninstall addon.
:param path: Absolute path to the addon that will be installed.
:Usage:
::
driver.install_addon('/path/to/firebug.xpi')
"""
payload = {"path": path}
if temporary is not None:
payload["temporary"] = temporary
return self.execute("INSTALL_ADDON", payload)["value"] | def install_addon(self, path, temporary=None):
"""
Installs Firefox addon.
Returns identifier of installed addon. This identifier can later
be used to uninstall addon.
:param path: Absolute path to the addon that will be installed.
:Usage:
::
driver.install_addon('/path/to/firebug.xpi')
"""
payload = {"path": path}
if temporary is not None:
payload["temporary"] = temporary
return self.execute("INSTALL_ADDON", payload)["value"] | [
"Installs",
"Firefox",
"addon",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/webdriver.py#L230-L247 | [
"def",
"install_addon",
"(",
"self",
",",
"path",
",",
"temporary",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"\"path\"",
":",
"path",
"}",
"if",
"temporary",
"is",
"not",
"None",
":",
"payload",
"[",
"\"temporary\"",
"]",
"=",
"temporary",
"return",
"self",
".",
"execute",
"(",
"\"INSTALL_ADDON\"",
",",
"payload",
")",
"[",
"\"value\"",
"]"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | Options.binary | Sets location of the browser binary, either by string or
``FirefoxBinary`` instance. | py/selenium/webdriver/firefox/options.py | def binary(self, new_binary):
"""Sets location of the browser binary, either by string or
``FirefoxBinary`` instance.
"""
if not isinstance(new_binary, FirefoxBinary):
new_binary = FirefoxBinary(new_binary)
self._binary = new_binary | def binary(self, new_binary):
"""Sets location of the browser binary, either by string or
``FirefoxBinary`` instance.
"""
if not isinstance(new_binary, FirefoxBinary):
new_binary = FirefoxBinary(new_binary)
self._binary = new_binary | [
"Sets",
"location",
"of",
"the",
"browser",
"binary",
"either",
"by",
"string",
"or",
"FirefoxBinary",
"instance",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/options.py#L52-L59 | [
"def",
"binary",
"(",
"self",
",",
"new_binary",
")",
":",
"if",
"not",
"isinstance",
"(",
"new_binary",
",",
"FirefoxBinary",
")",
":",
"new_binary",
"=",
"FirefoxBinary",
"(",
"new_binary",
")",
"self",
".",
"_binary",
"=",
"new_binary"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | Options.profile | Sets location of the browser profile to use, either by string
or ``FirefoxProfile``. | py/selenium/webdriver/firefox/options.py | def profile(self, new_profile):
"""Sets location of the browser profile to use, either by string
or ``FirefoxProfile``.
"""
if not isinstance(new_profile, FirefoxProfile):
new_profile = FirefoxProfile(new_profile)
self._profile = new_profile | def profile(self, new_profile):
"""Sets location of the browser profile to use, either by string
or ``FirefoxProfile``.
"""
if not isinstance(new_profile, FirefoxProfile):
new_profile = FirefoxProfile(new_profile)
self._profile = new_profile | [
"Sets",
"location",
"of",
"the",
"browser",
"profile",
"to",
"use",
"either",
"by",
"string",
"or",
"FirefoxProfile",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/options.py#L111-L118 | [
"def",
"profile",
"(",
"self",
",",
"new_profile",
")",
":",
"if",
"not",
"isinstance",
"(",
"new_profile",
",",
"FirefoxProfile",
")",
":",
"new_profile",
"=",
"FirefoxProfile",
"(",
"new_profile",
")",
"self",
".",
"_profile",
"=",
"new_profile"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | Options.headless | Sets the headless argument
Args:
value: boolean value indicating to set the headless option | py/selenium/webdriver/firefox/options.py | def headless(self, value):
"""
Sets the headless argument
Args:
value: boolean value indicating to set the headless option
"""
if value is True:
self._arguments.append('-headless')
elif '-headless' in self._arguments:
self._arguments.remove('-headless') | def headless(self, value):
"""
Sets the headless argument
Args:
value: boolean value indicating to set the headless option
"""
if value is True:
self._arguments.append('-headless')
elif '-headless' in self._arguments:
self._arguments.remove('-headless') | [
"Sets",
"the",
"headless",
"argument"
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/options.py#L128-L138 | [
"def",
"headless",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"True",
":",
"self",
".",
"_arguments",
".",
"append",
"(",
"'-headless'",
")",
"elif",
"'-headless'",
"in",
"self",
".",
"_arguments",
":",
"self",
".",
"_arguments",
".",
"remove",
"(",
"'-headless'",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | Options.to_capabilities | Marshals the Firefox options to a `moz:firefoxOptions`
object. | py/selenium/webdriver/firefox/options.py | def to_capabilities(self):
"""Marshals the Firefox options to a `moz:firefoxOptions`
object.
"""
# This intentionally looks at the internal properties
# so if a binary or profile has _not_ been set,
# it will defer to geckodriver to find the system Firefox
# and generate a fresh profile.
caps = self._caps
opts = {}
if self._binary is not None:
opts["binary"] = self._binary._start_cmd
if len(self._preferences) > 0:
opts["prefs"] = self._preferences
if self._proxy is not None:
self._proxy.add_to_capabilities(opts)
if self._profile is not None:
opts["profile"] = self._profile.encoded
if len(self._arguments) > 0:
opts["args"] = self._arguments
opts.update(self.log.to_capabilities())
if len(opts) > 0:
caps[Options.KEY] = opts
return caps | def to_capabilities(self):
"""Marshals the Firefox options to a `moz:firefoxOptions`
object.
"""
# This intentionally looks at the internal properties
# so if a binary or profile has _not_ been set,
# it will defer to geckodriver to find the system Firefox
# and generate a fresh profile.
caps = self._caps
opts = {}
if self._binary is not None:
opts["binary"] = self._binary._start_cmd
if len(self._preferences) > 0:
opts["prefs"] = self._preferences
if self._proxy is not None:
self._proxy.add_to_capabilities(opts)
if self._profile is not None:
opts["profile"] = self._profile.encoded
if len(self._arguments) > 0:
opts["args"] = self._arguments
opts.update(self.log.to_capabilities())
if len(opts) > 0:
caps[Options.KEY] = opts
return caps | [
"Marshals",
"the",
"Firefox",
"options",
"to",
"a",
"moz",
":",
"firefoxOptions",
"object",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/options.py#L140-L167 | [
"def",
"to_capabilities",
"(",
"self",
")",
":",
"# This intentionally looks at the internal properties",
"# so if a binary or profile has _not_ been set,",
"# it will defer to geckodriver to find the system Firefox",
"# and generate a fresh profile.",
"caps",
"=",
"self",
".",
"_caps",
"opts",
"=",
"{",
"}",
"if",
"self",
".",
"_binary",
"is",
"not",
"None",
":",
"opts",
"[",
"\"binary\"",
"]",
"=",
"self",
".",
"_binary",
".",
"_start_cmd",
"if",
"len",
"(",
"self",
".",
"_preferences",
")",
">",
"0",
":",
"opts",
"[",
"\"prefs\"",
"]",
"=",
"self",
".",
"_preferences",
"if",
"self",
".",
"_proxy",
"is",
"not",
"None",
":",
"self",
".",
"_proxy",
".",
"add_to_capabilities",
"(",
"opts",
")",
"if",
"self",
".",
"_profile",
"is",
"not",
"None",
":",
"opts",
"[",
"\"profile\"",
"]",
"=",
"self",
".",
"_profile",
".",
"encoded",
"if",
"len",
"(",
"self",
".",
"_arguments",
")",
">",
"0",
":",
"opts",
"[",
"\"args\"",
"]",
"=",
"self",
".",
"_arguments",
"opts",
".",
"update",
"(",
"self",
".",
"log",
".",
"to_capabilities",
"(",
")",
")",
"if",
"len",
"(",
"opts",
")",
">",
"0",
":",
"caps",
"[",
"Options",
".",
"KEY",
"]",
"=",
"opts",
"return",
"caps"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | Mobile.set_network_connection | Set the network connection for the remote device.
Example of setting airplane mode::
driver.mobile.set_network_connection(driver.mobile.AIRPLANE_MODE) | py/selenium/webdriver/remote/mobile.py | def set_network_connection(self, network):
"""
Set the network connection for the remote device.
Example of setting airplane mode::
driver.mobile.set_network_connection(driver.mobile.AIRPLANE_MODE)
"""
mode = network.mask if isinstance(network, self.ConnectionType) else network
return self.ConnectionType(self._driver.execute(
Command.SET_NETWORK_CONNECTION, {
'name': 'network_connection',
'parameters': {'type': mode}})['value']) | def set_network_connection(self, network):
"""
Set the network connection for the remote device.
Example of setting airplane mode::
driver.mobile.set_network_connection(driver.mobile.AIRPLANE_MODE)
"""
mode = network.mask if isinstance(network, self.ConnectionType) else network
return self.ConnectionType(self._driver.execute(
Command.SET_NETWORK_CONNECTION, {
'name': 'network_connection',
'parameters': {'type': mode}})['value']) | [
"Set",
"the",
"network",
"connection",
"for",
"the",
"remote",
"device",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/mobile.py#L52-L64 | [
"def",
"set_network_connection",
"(",
"self",
",",
"network",
")",
":",
"mode",
"=",
"network",
".",
"mask",
"if",
"isinstance",
"(",
"network",
",",
"self",
".",
"ConnectionType",
")",
"else",
"network",
"return",
"self",
".",
"ConnectionType",
"(",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"SET_NETWORK_CONNECTION",
",",
"{",
"'name'",
":",
"'network_connection'",
",",
"'parameters'",
":",
"{",
"'type'",
":",
"mode",
"}",
"}",
")",
"[",
"'value'",
"]",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | unzip_to_temp_dir | Unzip zipfile to a temporary directory.
The directory of the unzipped files is returned if success,
otherwise None is returned. | py/selenium/webdriver/remote/utils.py | def unzip_to_temp_dir(zip_file_name):
"""Unzip zipfile to a temporary directory.
The directory of the unzipped files is returned if success,
otherwise None is returned. """
if not zip_file_name or not os.path.exists(zip_file_name):
return None
zf = zipfile.ZipFile(zip_file_name)
if zf.testzip() is not None:
return None
# Unzip the files into a temporary directory
LOGGER.info("Extracting zipped file: %s" % zip_file_name)
tempdir = tempfile.mkdtemp()
try:
# Create directories that don't exist
for zip_name in zf.namelist():
# We have no knowledge on the os where the zipped file was
# created, so we restrict to zip files with paths without
# charactor "\" and "/".
name = (zip_name.replace("\\", os.path.sep).
replace("/", os.path.sep))
dest = os.path.join(tempdir, name)
if (name.endswith(os.path.sep) and not os.path.exists(dest)):
os.mkdir(dest)
LOGGER.debug("Directory %s created." % dest)
# Copy files
for zip_name in zf.namelist():
# We have no knowledge on the os where the zipped file was
# created, so we restrict to zip files with paths without
# charactor "\" and "/".
name = (zip_name.replace("\\", os.path.sep).
replace("/", os.path.sep))
dest = os.path.join(tempdir, name)
if not (name.endswith(os.path.sep)):
LOGGER.debug("Copying file %s......" % dest)
outfile = open(dest, 'wb')
outfile.write(zf.read(zip_name))
outfile.close()
LOGGER.debug("File %s copied." % dest)
LOGGER.info("Unzipped file can be found at %s" % tempdir)
return tempdir
except IOError as err:
LOGGER.error("Error in extracting webdriver.xpi: %s" % err)
return None | def unzip_to_temp_dir(zip_file_name):
"""Unzip zipfile to a temporary directory.
The directory of the unzipped files is returned if success,
otherwise None is returned. """
if not zip_file_name or not os.path.exists(zip_file_name):
return None
zf = zipfile.ZipFile(zip_file_name)
if zf.testzip() is not None:
return None
# Unzip the files into a temporary directory
LOGGER.info("Extracting zipped file: %s" % zip_file_name)
tempdir = tempfile.mkdtemp()
try:
# Create directories that don't exist
for zip_name in zf.namelist():
# We have no knowledge on the os where the zipped file was
# created, so we restrict to zip files with paths without
# charactor "\" and "/".
name = (zip_name.replace("\\", os.path.sep).
replace("/", os.path.sep))
dest = os.path.join(tempdir, name)
if (name.endswith(os.path.sep) and not os.path.exists(dest)):
os.mkdir(dest)
LOGGER.debug("Directory %s created." % dest)
# Copy files
for zip_name in zf.namelist():
# We have no knowledge on the os where the zipped file was
# created, so we restrict to zip files with paths without
# charactor "\" and "/".
name = (zip_name.replace("\\", os.path.sep).
replace("/", os.path.sep))
dest = os.path.join(tempdir, name)
if not (name.endswith(os.path.sep)):
LOGGER.debug("Copying file %s......" % dest)
outfile = open(dest, 'wb')
outfile.write(zf.read(zip_name))
outfile.close()
LOGGER.debug("File %s copied." % dest)
LOGGER.info("Unzipped file can be found at %s" % tempdir)
return tempdir
except IOError as err:
LOGGER.error("Error in extracting webdriver.xpi: %s" % err)
return None | [
"Unzip",
"zipfile",
"to",
"a",
"temporary",
"directory",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/utils.py#L40-L90 | [
"def",
"unzip_to_temp_dir",
"(",
"zip_file_name",
")",
":",
"if",
"not",
"zip_file_name",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"zip_file_name",
")",
":",
"return",
"None",
"zf",
"=",
"zipfile",
".",
"ZipFile",
"(",
"zip_file_name",
")",
"if",
"zf",
".",
"testzip",
"(",
")",
"is",
"not",
"None",
":",
"return",
"None",
"# Unzip the files into a temporary directory",
"LOGGER",
".",
"info",
"(",
"\"Extracting zipped file: %s\"",
"%",
"zip_file_name",
")",
"tempdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"try",
":",
"# Create directories that don't exist",
"for",
"zip_name",
"in",
"zf",
".",
"namelist",
"(",
")",
":",
"# We have no knowledge on the os where the zipped file was",
"# created, so we restrict to zip files with paths without",
"# charactor \"\\\" and \"/\".",
"name",
"=",
"(",
"zip_name",
".",
"replace",
"(",
"\"\\\\\"",
",",
"os",
".",
"path",
".",
"sep",
")",
".",
"replace",
"(",
"\"/\"",
",",
"os",
".",
"path",
".",
"sep",
")",
")",
"dest",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempdir",
",",
"name",
")",
"if",
"(",
"name",
".",
"endswith",
"(",
"os",
".",
"path",
".",
"sep",
")",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dest",
")",
")",
":",
"os",
".",
"mkdir",
"(",
"dest",
")",
"LOGGER",
".",
"debug",
"(",
"\"Directory %s created.\"",
"%",
"dest",
")",
"# Copy files",
"for",
"zip_name",
"in",
"zf",
".",
"namelist",
"(",
")",
":",
"# We have no knowledge on the os where the zipped file was",
"# created, so we restrict to zip files with paths without",
"# charactor \"\\\" and \"/\".",
"name",
"=",
"(",
"zip_name",
".",
"replace",
"(",
"\"\\\\\"",
",",
"os",
".",
"path",
".",
"sep",
")",
".",
"replace",
"(",
"\"/\"",
",",
"os",
".",
"path",
".",
"sep",
")",
")",
"dest",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempdir",
",",
"name",
")",
"if",
"not",
"(",
"name",
".",
"endswith",
"(",
"os",
".",
"path",
".",
"sep",
")",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Copying file %s......\"",
"%",
"dest",
")",
"outfile",
"=",
"open",
"(",
"dest",
",",
"'wb'",
")",
"outfile",
".",
"write",
"(",
"zf",
".",
"read",
"(",
"zip_name",
")",
")",
"outfile",
".",
"close",
"(",
")",
"LOGGER",
".",
"debug",
"(",
"\"File %s copied.\"",
"%",
"dest",
")",
"LOGGER",
".",
"info",
"(",
"\"Unzipped file can be found at %s\"",
"%",
"tempdir",
")",
"return",
"tempdir",
"except",
"IOError",
"as",
"err",
":",
"LOGGER",
".",
"error",
"(",
"\"Error in extracting webdriver.xpi: %s\"",
"%",
"err",
")",
"return",
"None"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | TouchActions.tap | Taps on a given element.
:Args:
- on_element: The element to tap. | py/selenium/webdriver/common/touch_actions.py | def tap(self, on_element):
"""
Taps on a given element.
:Args:
- on_element: The element to tap.
"""
self._actions.append(lambda: self._driver.execute(
Command.SINGLE_TAP, {'element': on_element.id}))
return self | def tap(self, on_element):
"""
Taps on a given element.
:Args:
- on_element: The element to tap.
"""
self._actions.append(lambda: self._driver.execute(
Command.SINGLE_TAP, {'element': on_element.id}))
return self | [
"Taps",
"on",
"a",
"given",
"element",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/touch_actions.py#L49-L58 | [
"def",
"tap",
"(",
"self",
",",
"on_element",
")",
":",
"self",
".",
"_actions",
".",
"append",
"(",
"lambda",
":",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"SINGLE_TAP",
",",
"{",
"'element'",
":",
"on_element",
".",
"id",
"}",
")",
")",
"return",
"self"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | TouchActions.double_tap | Double taps on a given element.
:Args:
- on_element: The element to tap. | py/selenium/webdriver/common/touch_actions.py | def double_tap(self, on_element):
"""
Double taps on a given element.
:Args:
- on_element: The element to tap.
"""
self._actions.append(lambda: self._driver.execute(
Command.DOUBLE_TAP, {'element': on_element.id}))
return self | def double_tap(self, on_element):
"""
Double taps on a given element.
:Args:
- on_element: The element to tap.
"""
self._actions.append(lambda: self._driver.execute(
Command.DOUBLE_TAP, {'element': on_element.id}))
return self | [
"Double",
"taps",
"on",
"a",
"given",
"element",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/touch_actions.py#L60-L69 | [
"def",
"double_tap",
"(",
"self",
",",
"on_element",
")",
":",
"self",
".",
"_actions",
".",
"append",
"(",
"lambda",
":",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"DOUBLE_TAP",
",",
"{",
"'element'",
":",
"on_element",
".",
"id",
"}",
")",
")",
"return",
"self"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | TouchActions.tap_and_hold | Touch down at given coordinates.
:Args:
- xcoord: X Coordinate to touch down.
- ycoord: Y Coordinate to touch down. | py/selenium/webdriver/common/touch_actions.py | def tap_and_hold(self, xcoord, ycoord):
"""
Touch down at given coordinates.
:Args:
- xcoord: X Coordinate to touch down.
- ycoord: Y Coordinate to touch down.
"""
self._actions.append(lambda: self._driver.execute(
Command.TOUCH_DOWN, {
'x': int(xcoord),
'y': int(ycoord)}))
return self | def tap_and_hold(self, xcoord, ycoord):
"""
Touch down at given coordinates.
:Args:
- xcoord: X Coordinate to touch down.
- ycoord: Y Coordinate to touch down.
"""
self._actions.append(lambda: self._driver.execute(
Command.TOUCH_DOWN, {
'x': int(xcoord),
'y': int(ycoord)}))
return self | [
"Touch",
"down",
"at",
"given",
"coordinates",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/touch_actions.py#L71-L83 | [
"def",
"tap_and_hold",
"(",
"self",
",",
"xcoord",
",",
"ycoord",
")",
":",
"self",
".",
"_actions",
".",
"append",
"(",
"lambda",
":",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"TOUCH_DOWN",
",",
"{",
"'x'",
":",
"int",
"(",
"xcoord",
")",
",",
"'y'",
":",
"int",
"(",
"ycoord",
")",
"}",
")",
")",
"return",
"self"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | TouchActions.move | Move held tap to specified location.
:Args:
- xcoord: X Coordinate to move.
- ycoord: Y Coordinate to move. | py/selenium/webdriver/common/touch_actions.py | def move(self, xcoord, ycoord):
"""
Move held tap to specified location.
:Args:
- xcoord: X Coordinate to move.
- ycoord: Y Coordinate to move.
"""
self._actions.append(lambda: self._driver.execute(
Command.TOUCH_MOVE, {
'x': int(xcoord),
'y': int(ycoord)}))
return self | def move(self, xcoord, ycoord):
"""
Move held tap to specified location.
:Args:
- xcoord: X Coordinate to move.
- ycoord: Y Coordinate to move.
"""
self._actions.append(lambda: self._driver.execute(
Command.TOUCH_MOVE, {
'x': int(xcoord),
'y': int(ycoord)}))
return self | [
"Move",
"held",
"tap",
"to",
"specified",
"location",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/touch_actions.py#L85-L97 | [
"def",
"move",
"(",
"self",
",",
"xcoord",
",",
"ycoord",
")",
":",
"self",
".",
"_actions",
".",
"append",
"(",
"lambda",
":",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"TOUCH_MOVE",
",",
"{",
"'x'",
":",
"int",
"(",
"xcoord",
")",
",",
"'y'",
":",
"int",
"(",
"ycoord",
")",
"}",
")",
")",
"return",
"self"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | TouchActions.release | Release previously issued tap 'and hold' command at specified location.
:Args:
- xcoord: X Coordinate to release.
- ycoord: Y Coordinate to release. | py/selenium/webdriver/common/touch_actions.py | def release(self, xcoord, ycoord):
"""
Release previously issued tap 'and hold' command at specified location.
:Args:
- xcoord: X Coordinate to release.
- ycoord: Y Coordinate to release.
"""
self._actions.append(lambda: self._driver.execute(
Command.TOUCH_UP, {
'x': int(xcoord),
'y': int(ycoord)}))
return self | def release(self, xcoord, ycoord):
"""
Release previously issued tap 'and hold' command at specified location.
:Args:
- xcoord: X Coordinate to release.
- ycoord: Y Coordinate to release.
"""
self._actions.append(lambda: self._driver.execute(
Command.TOUCH_UP, {
'x': int(xcoord),
'y': int(ycoord)}))
return self | [
"Release",
"previously",
"issued",
"tap",
"and",
"hold",
"command",
"at",
"specified",
"location",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/touch_actions.py#L99-L111 | [
"def",
"release",
"(",
"self",
",",
"xcoord",
",",
"ycoord",
")",
":",
"self",
".",
"_actions",
".",
"append",
"(",
"lambda",
":",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"TOUCH_UP",
",",
"{",
"'x'",
":",
"int",
"(",
"xcoord",
")",
",",
"'y'",
":",
"int",
"(",
"ycoord",
")",
"}",
")",
")",
"return",
"self"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | TouchActions.scroll | Touch and scroll, moving by xoffset and yoffset.
:Args:
- xoffset: X offset to scroll to.
- yoffset: Y offset to scroll to. | py/selenium/webdriver/common/touch_actions.py | def scroll(self, xoffset, yoffset):
"""
Touch and scroll, moving by xoffset and yoffset.
:Args:
- xoffset: X offset to scroll to.
- yoffset: Y offset to scroll to.
"""
self._actions.append(lambda: self._driver.execute(
Command.TOUCH_SCROLL, {
'xoffset': int(xoffset),
'yoffset': int(yoffset)}))
return self | def scroll(self, xoffset, yoffset):
"""
Touch and scroll, moving by xoffset and yoffset.
:Args:
- xoffset: X offset to scroll to.
- yoffset: Y offset to scroll to.
"""
self._actions.append(lambda: self._driver.execute(
Command.TOUCH_SCROLL, {
'xoffset': int(xoffset),
'yoffset': int(yoffset)}))
return self | [
"Touch",
"and",
"scroll",
"moving",
"by",
"xoffset",
"and",
"yoffset",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/touch_actions.py#L113-L125 | [
"def",
"scroll",
"(",
"self",
",",
"xoffset",
",",
"yoffset",
")",
":",
"self",
".",
"_actions",
".",
"append",
"(",
"lambda",
":",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"TOUCH_SCROLL",
",",
"{",
"'xoffset'",
":",
"int",
"(",
"xoffset",
")",
",",
"'yoffset'",
":",
"int",
"(",
"yoffset",
")",
"}",
")",
")",
"return",
"self"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | TouchActions.scroll_from_element | Touch and scroll starting at on_element, moving by xoffset and yoffset.
:Args:
- on_element: The element where scroll starts.
- xoffset: X offset to scroll to.
- yoffset: Y offset to scroll to. | py/selenium/webdriver/common/touch_actions.py | def scroll_from_element(self, on_element, xoffset, yoffset):
"""
Touch and scroll starting at on_element, moving by xoffset and yoffset.
:Args:
- on_element: The element where scroll starts.
- xoffset: X offset to scroll to.
- yoffset: Y offset to scroll to.
"""
self._actions.append(lambda: self._driver.execute(
Command.TOUCH_SCROLL, {
'element': on_element.id,
'xoffset': int(xoffset),
'yoffset': int(yoffset)}))
return self | def scroll_from_element(self, on_element, xoffset, yoffset):
"""
Touch and scroll starting at on_element, moving by xoffset and yoffset.
:Args:
- on_element: The element where scroll starts.
- xoffset: X offset to scroll to.
- yoffset: Y offset to scroll to.
"""
self._actions.append(lambda: self._driver.execute(
Command.TOUCH_SCROLL, {
'element': on_element.id,
'xoffset': int(xoffset),
'yoffset': int(yoffset)}))
return self | [
"Touch",
"and",
"scroll",
"starting",
"at",
"on_element",
"moving",
"by",
"xoffset",
"and",
"yoffset",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/touch_actions.py#L127-L141 | [
"def",
"scroll_from_element",
"(",
"self",
",",
"on_element",
",",
"xoffset",
",",
"yoffset",
")",
":",
"self",
".",
"_actions",
".",
"append",
"(",
"lambda",
":",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"TOUCH_SCROLL",
",",
"{",
"'element'",
":",
"on_element",
".",
"id",
",",
"'xoffset'",
":",
"int",
"(",
"xoffset",
")",
",",
"'yoffset'",
":",
"int",
"(",
"yoffset",
")",
"}",
")",
")",
"return",
"self"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | TouchActions.long_press | Long press on an element.
:Args:
- on_element: The element to long press. | py/selenium/webdriver/common/touch_actions.py | def long_press(self, on_element):
"""
Long press on an element.
:Args:
- on_element: The element to long press.
"""
self._actions.append(lambda: self._driver.execute(
Command.LONG_PRESS, {'element': on_element.id}))
return self | def long_press(self, on_element):
"""
Long press on an element.
:Args:
- on_element: The element to long press.
"""
self._actions.append(lambda: self._driver.execute(
Command.LONG_PRESS, {'element': on_element.id}))
return self | [
"Long",
"press",
"on",
"an",
"element",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/touch_actions.py#L143-L152 | [
"def",
"long_press",
"(",
"self",
",",
"on_element",
")",
":",
"self",
".",
"_actions",
".",
"append",
"(",
"lambda",
":",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"LONG_PRESS",
",",
"{",
"'element'",
":",
"on_element",
".",
"id",
"}",
")",
")",
"return",
"self"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | TouchActions.flick | Flicks, starting anywhere on the screen.
:Args:
- xspeed: The X speed in pixels per second.
- yspeed: The Y speed in pixels per second. | py/selenium/webdriver/common/touch_actions.py | def flick(self, xspeed, yspeed):
"""
Flicks, starting anywhere on the screen.
:Args:
- xspeed: The X speed in pixels per second.
- yspeed: The Y speed in pixels per second.
"""
self._actions.append(lambda: self._driver.execute(
Command.FLICK, {
'xspeed': int(xspeed),
'yspeed': int(yspeed)}))
return self | def flick(self, xspeed, yspeed):
"""
Flicks, starting anywhere on the screen.
:Args:
- xspeed: The X speed in pixels per second.
- yspeed: The Y speed in pixels per second.
"""
self._actions.append(lambda: self._driver.execute(
Command.FLICK, {
'xspeed': int(xspeed),
'yspeed': int(yspeed)}))
return self | [
"Flicks",
"starting",
"anywhere",
"on",
"the",
"screen",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/touch_actions.py#L154-L166 | [
"def",
"flick",
"(",
"self",
",",
"xspeed",
",",
"yspeed",
")",
":",
"self",
".",
"_actions",
".",
"append",
"(",
"lambda",
":",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"FLICK",
",",
"{",
"'xspeed'",
":",
"int",
"(",
"xspeed",
")",
",",
"'yspeed'",
":",
"int",
"(",
"yspeed",
")",
"}",
")",
")",
"return",
"self"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | TouchActions.flick_element | Flick starting at on_element, and moving by the xoffset and yoffset
with specified speed.
:Args:
- on_element: Flick will start at center of element.
- xoffset: X offset to flick to.
- yoffset: Y offset to flick to.
- speed: Pixels per second to flick. | py/selenium/webdriver/common/touch_actions.py | def flick_element(self, on_element, xoffset, yoffset, speed):
"""
Flick starting at on_element, and moving by the xoffset and yoffset
with specified speed.
:Args:
- on_element: Flick will start at center of element.
- xoffset: X offset to flick to.
- yoffset: Y offset to flick to.
- speed: Pixels per second to flick.
"""
self._actions.append(lambda: self._driver.execute(
Command.FLICK, {
'element': on_element.id,
'xoffset': int(xoffset),
'yoffset': int(yoffset),
'speed': int(speed)}))
return self | def flick_element(self, on_element, xoffset, yoffset, speed):
"""
Flick starting at on_element, and moving by the xoffset and yoffset
with specified speed.
:Args:
- on_element: Flick will start at center of element.
- xoffset: X offset to flick to.
- yoffset: Y offset to flick to.
- speed: Pixels per second to flick.
"""
self._actions.append(lambda: self._driver.execute(
Command.FLICK, {
'element': on_element.id,
'xoffset': int(xoffset),
'yoffset': int(yoffset),
'speed': int(speed)}))
return self | [
"Flick",
"starting",
"at",
"on_element",
"and",
"moving",
"by",
"the",
"xoffset",
"and",
"yoffset",
"with",
"specified",
"speed",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/touch_actions.py#L168-L185 | [
"def",
"flick_element",
"(",
"self",
",",
"on_element",
",",
"xoffset",
",",
"yoffset",
",",
"speed",
")",
":",
"self",
".",
"_actions",
".",
"append",
"(",
"lambda",
":",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"FLICK",
",",
"{",
"'element'",
":",
"on_element",
".",
"id",
",",
"'xoffset'",
":",
"int",
"(",
"xoffset",
")",
",",
"'yoffset'",
":",
"int",
"(",
"yoffset",
")",
",",
"'speed'",
":",
"int",
"(",
"speed",
")",
"}",
")",
")",
"return",
"self"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | Options.to_capabilities | Creates a capabilities with all the options that have been set and
returns a dictionary with everything | py/selenium/webdriver/webkitgtk/options.py | def to_capabilities(self):
"""
Creates a capabilities with all the options that have been set and
returns a dictionary with everything
"""
caps = self._caps
browser_options = {}
if self.binary_location:
browser_options["binary"] = self.binary_location
if self.arguments:
browser_options["args"] = self.arguments
browser_options["useOverlayScrollbars"] = self.overlay_scrollbars_enabled
caps[Options.KEY] = browser_options
return caps | def to_capabilities(self):
"""
Creates a capabilities with all the options that have been set and
returns a dictionary with everything
"""
caps = self._caps
browser_options = {}
if self.binary_location:
browser_options["binary"] = self.binary_location
if self.arguments:
browser_options["args"] = self.arguments
browser_options["useOverlayScrollbars"] = self.overlay_scrollbars_enabled
caps[Options.KEY] = browser_options
return caps | [
"Creates",
"a",
"capabilities",
"with",
"all",
"the",
"options",
"that",
"have",
"been",
"set",
"and",
"returns",
"a",
"dictionary",
"with",
"everything"
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/webkitgtk/options.py#L64-L80 | [
"def",
"to_capabilities",
"(",
"self",
")",
":",
"caps",
"=",
"self",
".",
"_caps",
"browser_options",
"=",
"{",
"}",
"if",
"self",
".",
"binary_location",
":",
"browser_options",
"[",
"\"binary\"",
"]",
"=",
"self",
".",
"binary_location",
"if",
"self",
".",
"arguments",
":",
"browser_options",
"[",
"\"args\"",
"]",
"=",
"self",
".",
"arguments",
"browser_options",
"[",
"\"useOverlayScrollbars\"",
"]",
"=",
"self",
".",
"overlay_scrollbars_enabled",
"caps",
"[",
"Options",
".",
"KEY",
"]",
"=",
"browser_options",
"return",
"caps"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | SwitchTo.active_element | Returns the element with focus, or BODY if nothing has focus.
:Usage:
::
element = driver.switch_to.active_element | py/selenium/webdriver/remote/switch_to.py | def active_element(self):
"""
Returns the element with focus, or BODY if nothing has focus.
:Usage:
::
element = driver.switch_to.active_element
"""
if self._driver.w3c:
return self._driver.execute(Command.W3C_GET_ACTIVE_ELEMENT)['value']
else:
return self._driver.execute(Command.GET_ACTIVE_ELEMENT)['value'] | def active_element(self):
"""
Returns the element with focus, or BODY if nothing has focus.
:Usage:
::
element = driver.switch_to.active_element
"""
if self._driver.w3c:
return self._driver.execute(Command.W3C_GET_ACTIVE_ELEMENT)['value']
else:
return self._driver.execute(Command.GET_ACTIVE_ELEMENT)['value'] | [
"Returns",
"the",
"element",
"with",
"focus",
"or",
"BODY",
"if",
"nothing",
"has",
"focus",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/switch_to.py#L34-L46 | [
"def",
"active_element",
"(",
"self",
")",
":",
"if",
"self",
".",
"_driver",
".",
"w3c",
":",
"return",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"W3C_GET_ACTIVE_ELEMENT",
")",
"[",
"'value'",
"]",
"else",
":",
"return",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"GET_ACTIVE_ELEMENT",
")",
"[",
"'value'",
"]"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | SwitchTo.frame | Switches focus to the specified frame, by index, name, or webelement.
:Args:
- frame_reference: The name of the window to switch to, an integer representing the index,
or a webelement that is an (i)frame to switch to.
:Usage:
::
driver.switch_to.frame('frame_name')
driver.switch_to.frame(1)
driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0]) | py/selenium/webdriver/remote/switch_to.py | def frame(self, frame_reference):
"""
Switches focus to the specified frame, by index, name, or webelement.
:Args:
- frame_reference: The name of the window to switch to, an integer representing the index,
or a webelement that is an (i)frame to switch to.
:Usage:
::
driver.switch_to.frame('frame_name')
driver.switch_to.frame(1)
driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0])
"""
if isinstance(frame_reference, basestring) and self._driver.w3c:
try:
frame_reference = self._driver.find_element(By.ID, frame_reference)
except NoSuchElementException:
try:
frame_reference = self._driver.find_element(By.NAME, frame_reference)
except NoSuchElementException:
raise NoSuchFrameException(frame_reference)
self._driver.execute(Command.SWITCH_TO_FRAME, {'id': frame_reference}) | def frame(self, frame_reference):
"""
Switches focus to the specified frame, by index, name, or webelement.
:Args:
- frame_reference: The name of the window to switch to, an integer representing the index,
or a webelement that is an (i)frame to switch to.
:Usage:
::
driver.switch_to.frame('frame_name')
driver.switch_to.frame(1)
driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0])
"""
if isinstance(frame_reference, basestring) and self._driver.w3c:
try:
frame_reference = self._driver.find_element(By.ID, frame_reference)
except NoSuchElementException:
try:
frame_reference = self._driver.find_element(By.NAME, frame_reference)
except NoSuchElementException:
raise NoSuchFrameException(frame_reference)
self._driver.execute(Command.SWITCH_TO_FRAME, {'id': frame_reference}) | [
"Switches",
"focus",
"to",
"the",
"specified",
"frame",
"by",
"index",
"name",
"or",
"webelement",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/switch_to.py#L73-L97 | [
"def",
"frame",
"(",
"self",
",",
"frame_reference",
")",
":",
"if",
"isinstance",
"(",
"frame_reference",
",",
"basestring",
")",
"and",
"self",
".",
"_driver",
".",
"w3c",
":",
"try",
":",
"frame_reference",
"=",
"self",
".",
"_driver",
".",
"find_element",
"(",
"By",
".",
"ID",
",",
"frame_reference",
")",
"except",
"NoSuchElementException",
":",
"try",
":",
"frame_reference",
"=",
"self",
".",
"_driver",
".",
"find_element",
"(",
"By",
".",
"NAME",
",",
"frame_reference",
")",
"except",
"NoSuchElementException",
":",
"raise",
"NoSuchFrameException",
"(",
"frame_reference",
")",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"SWITCH_TO_FRAME",
",",
"{",
"'id'",
":",
"frame_reference",
"}",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | SwitchTo.new_window | Switches to a new top-level browsing context.
The type hint can be one of "tab" or "window". If not specified the
browser will automatically select it.
:Usage:
::
driver.switch_to.new_window('tab') | py/selenium/webdriver/remote/switch_to.py | def new_window(self, type_hint=None):
"""Switches to a new top-level browsing context.
The type hint can be one of "tab" or "window". If not specified the
browser will automatically select it.
:Usage:
::
driver.switch_to.new_window('tab')
"""
value = self._driver.execute(Command.NEW_WINDOW, {'type': type_hint})['value']
self._w3c_window(value['handle']) | def new_window(self, type_hint=None):
"""Switches to a new top-level browsing context.
The type hint can be one of "tab" or "window". If not specified the
browser will automatically select it.
:Usage:
::
driver.switch_to.new_window('tab')
"""
value = self._driver.execute(Command.NEW_WINDOW, {'type': type_hint})['value']
self._w3c_window(value['handle']) | [
"Switches",
"to",
"a",
"new",
"top",
"-",
"level",
"browsing",
"context",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/switch_to.py#L99-L111 | [
"def",
"new_window",
"(",
"self",
",",
"type_hint",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"NEW_WINDOW",
",",
"{",
"'type'",
":",
"type_hint",
"}",
")",
"[",
"'value'",
"]",
"self",
".",
"_w3c_window",
"(",
"value",
"[",
"'handle'",
"]",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | SwitchTo.window | Switches focus to the specified window.
:Args:
- window_name: The name or window handle of the window to switch to.
:Usage:
::
driver.switch_to.window('main') | py/selenium/webdriver/remote/switch_to.py | def window(self, window_name):
"""
Switches focus to the specified window.
:Args:
- window_name: The name or window handle of the window to switch to.
:Usage:
::
driver.switch_to.window('main')
"""
if self._driver.w3c:
self._w3c_window(window_name)
return
data = {'name': window_name}
self._driver.execute(Command.SWITCH_TO_WINDOW, data) | def window(self, window_name):
"""
Switches focus to the specified window.
:Args:
- window_name: The name or window handle of the window to switch to.
:Usage:
::
driver.switch_to.window('main')
"""
if self._driver.w3c:
self._w3c_window(window_name)
return
data = {'name': window_name}
self._driver.execute(Command.SWITCH_TO_WINDOW, data) | [
"Switches",
"focus",
"to",
"the",
"specified",
"window",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/switch_to.py#L125-L141 | [
"def",
"window",
"(",
"self",
",",
"window_name",
")",
":",
"if",
"self",
".",
"_driver",
".",
"w3c",
":",
"self",
".",
"_w3c_window",
"(",
"window_name",
")",
"return",
"data",
"=",
"{",
"'name'",
":",
"window_name",
"}",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"SWITCH_TO_WINDOW",
",",
"data",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | ActionChains.perform | Performs all stored actions. | py/selenium/webdriver/common/action_chains.py | def perform(self):
"""
Performs all stored actions.
"""
if self._driver.w3c:
self.w3c_actions.perform()
else:
for action in self._actions:
action() | def perform(self):
"""
Performs all stored actions.
"""
if self._driver.w3c:
self.w3c_actions.perform()
else:
for action in self._actions:
action() | [
"Performs",
"all",
"stored",
"actions",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L75-L83 | [
"def",
"perform",
"(",
"self",
")",
":",
"if",
"self",
".",
"_driver",
".",
"w3c",
":",
"self",
".",
"w3c_actions",
".",
"perform",
"(",
")",
"else",
":",
"for",
"action",
"in",
"self",
".",
"_actions",
":",
"action",
"(",
")"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | ActionChains.reset_actions | Clears actions that are already stored locally and on the remote end | py/selenium/webdriver/common/action_chains.py | def reset_actions(self):
"""
Clears actions that are already stored locally and on the remote end
"""
if self._driver.w3c:
self.w3c_actions.clear_actions()
self._actions = [] | def reset_actions(self):
"""
Clears actions that are already stored locally and on the remote end
"""
if self._driver.w3c:
self.w3c_actions.clear_actions()
self._actions = [] | [
"Clears",
"actions",
"that",
"are",
"already",
"stored",
"locally",
"and",
"on",
"the",
"remote",
"end"
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L85-L91 | [
"def",
"reset_actions",
"(",
"self",
")",
":",
"if",
"self",
".",
"_driver",
".",
"w3c",
":",
"self",
".",
"w3c_actions",
".",
"clear_actions",
"(",
")",
"self",
".",
"_actions",
"=",
"[",
"]"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | ActionChains.click_and_hold | Holds down the left mouse button on an element.
:Args:
- on_element: The element to mouse down.
If None, clicks on current mouse position. | py/selenium/webdriver/common/action_chains.py | def click_and_hold(self, on_element=None):
"""
Holds down the left mouse button on an element.
:Args:
- on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element:
self.move_to_element(on_element)
if self._driver.w3c:
self.w3c_actions.pointer_action.click_and_hold()
self.w3c_actions.key_action.pause()
else:
self._actions.append(lambda: self._driver.execute(
Command.MOUSE_DOWN, {}))
return self | def click_and_hold(self, on_element=None):
"""
Holds down the left mouse button on an element.
:Args:
- on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element:
self.move_to_element(on_element)
if self._driver.w3c:
self.w3c_actions.pointer_action.click_and_hold()
self.w3c_actions.key_action.pause()
else:
self._actions.append(lambda: self._driver.execute(
Command.MOUSE_DOWN, {}))
return self | [
"Holds",
"down",
"the",
"left",
"mouse",
"button",
"on",
"an",
"element",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L112-L128 | [
"def",
"click_and_hold",
"(",
"self",
",",
"on_element",
"=",
"None",
")",
":",
"if",
"on_element",
":",
"self",
".",
"move_to_element",
"(",
"on_element",
")",
"if",
"self",
".",
"_driver",
".",
"w3c",
":",
"self",
".",
"w3c_actions",
".",
"pointer_action",
".",
"click_and_hold",
"(",
")",
"self",
".",
"w3c_actions",
".",
"key_action",
".",
"pause",
"(",
")",
"else",
":",
"self",
".",
"_actions",
".",
"append",
"(",
"lambda",
":",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"MOUSE_DOWN",
",",
"{",
"}",
")",
")",
"return",
"self"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | ActionChains.context_click | Performs a context-click (right click) on an element.
:Args:
- on_element: The element to context-click.
If None, clicks on current mouse position. | py/selenium/webdriver/common/action_chains.py | def context_click(self, on_element=None):
"""
Performs a context-click (right click) on an element.
:Args:
- on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element:
self.move_to_element(on_element)
if self._driver.w3c:
self.w3c_actions.pointer_action.context_click()
self.w3c_actions.key_action.pause()
self.w3c_actions.key_action.pause()
else:
self._actions.append(lambda: self._driver.execute(
Command.CLICK, {'button': 2}))
return self | def context_click(self, on_element=None):
"""
Performs a context-click (right click) on an element.
:Args:
- on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element:
self.move_to_element(on_element)
if self._driver.w3c:
self.w3c_actions.pointer_action.context_click()
self.w3c_actions.key_action.pause()
self.w3c_actions.key_action.pause()
else:
self._actions.append(lambda: self._driver.execute(
Command.CLICK, {'button': 2}))
return self | [
"Performs",
"a",
"context",
"-",
"click",
"(",
"right",
"click",
")",
"on",
"an",
"element",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L130-L147 | [
"def",
"context_click",
"(",
"self",
",",
"on_element",
"=",
"None",
")",
":",
"if",
"on_element",
":",
"self",
".",
"move_to_element",
"(",
"on_element",
")",
"if",
"self",
".",
"_driver",
".",
"w3c",
":",
"self",
".",
"w3c_actions",
".",
"pointer_action",
".",
"context_click",
"(",
")",
"self",
".",
"w3c_actions",
".",
"key_action",
".",
"pause",
"(",
")",
"self",
".",
"w3c_actions",
".",
"key_action",
".",
"pause",
"(",
")",
"else",
":",
"self",
".",
"_actions",
".",
"append",
"(",
"lambda",
":",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"CLICK",
",",
"{",
"'button'",
":",
"2",
"}",
")",
")",
"return",
"self"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | ActionChains.double_click | Double-clicks an element.
:Args:
- on_element: The element to double-click.
If None, clicks on current mouse position. | py/selenium/webdriver/common/action_chains.py | def double_click(self, on_element=None):
"""
Double-clicks an element.
:Args:
- on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element:
self.move_to_element(on_element)
if self._driver.w3c:
self.w3c_actions.pointer_action.double_click()
for _ in range(4):
self.w3c_actions.key_action.pause()
else:
self._actions.append(lambda: self._driver.execute(
Command.DOUBLE_CLICK, {}))
return self | def double_click(self, on_element=None):
"""
Double-clicks an element.
:Args:
- on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element:
self.move_to_element(on_element)
if self._driver.w3c:
self.w3c_actions.pointer_action.double_click()
for _ in range(4):
self.w3c_actions.key_action.pause()
else:
self._actions.append(lambda: self._driver.execute(
Command.DOUBLE_CLICK, {}))
return self | [
"Double",
"-",
"clicks",
"an",
"element",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L149-L166 | [
"def",
"double_click",
"(",
"self",
",",
"on_element",
"=",
"None",
")",
":",
"if",
"on_element",
":",
"self",
".",
"move_to_element",
"(",
"on_element",
")",
"if",
"self",
".",
"_driver",
".",
"w3c",
":",
"self",
".",
"w3c_actions",
".",
"pointer_action",
".",
"double_click",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"4",
")",
":",
"self",
".",
"w3c_actions",
".",
"key_action",
".",
"pause",
"(",
")",
"else",
":",
"self",
".",
"_actions",
".",
"append",
"(",
"lambda",
":",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"DOUBLE_CLICK",
",",
"{",
"}",
")",
")",
"return",
"self"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | ActionChains.drag_and_drop | Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
:Args:
- source: The element to mouse down.
- target: The element to mouse up. | py/selenium/webdriver/common/action_chains.py | def drag_and_drop(self, source, target):
"""
Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
:Args:
- source: The element to mouse down.
- target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self | def drag_and_drop(self, source, target):
"""
Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
:Args:
- source: The element to mouse down.
- target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self | [
"Holds",
"down",
"the",
"left",
"mouse",
"button",
"on",
"the",
"source",
"element",
"then",
"moves",
"to",
"the",
"target",
"element",
"and",
"releases",
"the",
"mouse",
"button",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L168-L179 | [
"def",
"drag_and_drop",
"(",
"self",
",",
"source",
",",
"target",
")",
":",
"self",
".",
"click_and_hold",
"(",
"source",
")",
"self",
".",
"release",
"(",
"target",
")",
"return",
"self"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | ActionChains.drag_and_drop_by_offset | Holds down the left mouse button on the source element,
then moves to the target offset and releases the mouse button.
:Args:
- source: The element to mouse down.
- xoffset: X offset to move to.
- yoffset: Y offset to move to. | py/selenium/webdriver/common/action_chains.py | def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""
Holds down the left mouse button on the source element,
then moves to the target offset and releases the mouse button.
:Args:
- source: The element to mouse down.
- xoffset: X offset to move to.
- yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release()
return self | def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""
Holds down the left mouse button on the source element,
then moves to the target offset and releases the mouse button.
:Args:
- source: The element to mouse down.
- xoffset: X offset to move to.
- yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release()
return self | [
"Holds",
"down",
"the",
"left",
"mouse",
"button",
"on",
"the",
"source",
"element",
"then",
"moves",
"to",
"the",
"target",
"offset",
"and",
"releases",
"the",
"mouse",
"button",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L181-L194 | [
"def",
"drag_and_drop_by_offset",
"(",
"self",
",",
"source",
",",
"xoffset",
",",
"yoffset",
")",
":",
"self",
".",
"click_and_hold",
"(",
"source",
")",
"self",
".",
"move_by_offset",
"(",
"xoffset",
",",
"yoffset",
")",
"self",
".",
"release",
"(",
")",
"return",
"self"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
train | ActionChains.key_down | Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
:Args:
- value: The modifier key to send. Values are defined in `Keys` class.
- element: The element to send keys.
If None, sends a key to current focused element.
Example, pressing ctrl+c::
ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform() | py/selenium/webdriver/common/action_chains.py | def key_down(self, value, element=None):
"""
Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
:Args:
- value: The modifier key to send. Values are defined in `Keys` class.
- element: The element to send keys.
If None, sends a key to current focused element.
Example, pressing ctrl+c::
ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
"""
if element:
self.click(element)
if self._driver.w3c:
self.w3c_actions.key_action.key_down(value)
self.w3c_actions.pointer_action.pause()
else:
self._actions.append(lambda: self._driver.execute(
Command.SEND_KEYS_TO_ACTIVE_ELEMENT,
{"value": keys_to_typing(value)}))
return self | def key_down(self, value, element=None):
"""
Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
:Args:
- value: The modifier key to send. Values are defined in `Keys` class.
- element: The element to send keys.
If None, sends a key to current focused element.
Example, pressing ctrl+c::
ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
"""
if element:
self.click(element)
if self._driver.w3c:
self.w3c_actions.key_action.key_down(value)
self.w3c_actions.pointer_action.pause()
else:
self._actions.append(lambda: self._driver.execute(
Command.SEND_KEYS_TO_ACTIVE_ELEMENT,
{"value": keys_to_typing(value)}))
return self | [
"Sends",
"a",
"key",
"press",
"only",
"without",
"releasing",
"it",
".",
"Should",
"only",
"be",
"used",
"with",
"modifier",
"keys",
"(",
"Control",
"Alt",
"and",
"Shift",
")",
"."
] | SeleniumHQ/selenium | python | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L196-L220 | [
"def",
"key_down",
"(",
"self",
",",
"value",
",",
"element",
"=",
"None",
")",
":",
"if",
"element",
":",
"self",
".",
"click",
"(",
"element",
")",
"if",
"self",
".",
"_driver",
".",
"w3c",
":",
"self",
".",
"w3c_actions",
".",
"key_action",
".",
"key_down",
"(",
"value",
")",
"self",
".",
"w3c_actions",
".",
"pointer_action",
".",
"pause",
"(",
")",
"else",
":",
"self",
".",
"_actions",
".",
"append",
"(",
"lambda",
":",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"SEND_KEYS_TO_ACTIVE_ELEMENT",
",",
"{",
"\"value\"",
":",
"keys_to_typing",
"(",
"value",
")",
"}",
")",
")",
"return",
"self"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.