body stringlengths 26 98.2k | body_hash int64 -9,222,864,604,528,158,000 9,221,803,474B | docstring stringlengths 1 16.8k | path stringlengths 5 230 | name stringlengths 1 96 | repository_name stringlengths 7 89 | lang stringclasses 1
value | body_without_docstring stringlengths 20 98.2k |
|---|---|---|---|---|---|---|---|
def __init__(self, F, poly):
'Define the Extension Field and the representative polynomial\n '
self.F = F
self.poly = poly
self.siz = len(poly.coef)
self.deg = self.siz | 7,119,987,552,794,296,000 | Define the Extension Field and the representative polynomial | mathTools/field.py | __init__ | ecuvelier/PPAT | python | def __init__(self, F, poly):
'\n '
self.F = F
self.poly = poly
self.siz = len(poly.coef)
self.deg = self.siz |
def iszero(self):
'Return True if it is a zero polynomial (each coefficient is zero)\n This does not return True if the polynomial is the polynomial that generates the extension field\n '
cond = True
for i in self.coef:
pcond = i.iszero()
cond = (pcond * cond)
return con... | 3,512,125,350,708,358,700 | Return True if it is a zero polynomial (each coefficient is zero)
This does not return True if the polynomial is the polynomial that generates the extension field | mathTools/field.py | iszero | ecuvelier/PPAT | python | def iszero(self):
'Return True if it is a zero polynomial (each coefficient is zero)\n This does not return True if the polynomial is the polynomial that generates the extension field\n '
cond = True
for i in self.coef:
pcond = i.iszero()
cond = (pcond * cond)
return con... |
def truedeg(self):
'Return the position of the first non zero coefficient and the actual degree of the polynomial\n '
if self.iszero():
return (0, 0)
n = 0
while (self.coef[n] == self.F.zero()):
n = (n + 1)
return (n, (self.deg - n)) | -7,869,618,672,398,647,000 | Return the position of the first non zero coefficient and the actual degree of the polynomial | mathTools/field.py | truedeg | ecuvelier/PPAT | python | def truedeg(self):
'\n '
if self.iszero():
return (0, 0)
n = 0
while (self.coef[n] == self.F.zero()):
n = (n + 1)
return (n, (self.deg - n)) |
def mdot(*args):
'chained matrix product: mdot(A,B,C,..) = A*B*C*...\n No attempt is made to optimize the contraction order.'
r = args[0]
for a in args[1:]:
r = dot(r, a)
return r | 8,142,903,852,845,072,000 | chained matrix product: mdot(A,B,C,..) = A*B*C*...
No attempt is made to optimize the contraction order. | pyscf/tools/Molpro2Pyscf/wmme.py | mdot | JFurness1/pyscf | python | def mdot(*args):
'chained matrix product: mdot(A,B,C,..) = A*B*C*...\n No attempt is made to optimize the contraction order.'
r = args[0]
for a in args[1:]:
r = dot(r, a)
return r |
def _InvokeBfint(Atoms, Bases, BasisLibs, BaseArgs, Outputs, Inputs=None):
'Outputs: an array of tuples (cmdline-arguments,filename-base).\n We will generate arguments for each of them and try to read the\n corresponding files as numpy arrays and return them in order.'
from tempfile import mkdtemp
from ... | 7,459,019,133,808,410,000 | Outputs: an array of tuples (cmdline-arguments,filename-base).
We will generate arguments for each of them and try to read the
corresponding files as numpy arrays and return them in order. | pyscf/tools/Molpro2Pyscf/wmme.py | _InvokeBfint | JFurness1/pyscf | python | def _InvokeBfint(Atoms, Bases, BasisLibs, BaseArgs, Outputs, Inputs=None):
'Outputs: an array of tuples (cmdline-arguments,filename-base).\n We will generate arguments for each of them and try to read the\n corresponding files as numpy arrays and return them in order.'
from tempfile import mkdtemp
from ... |
def __init__(self, Positions, Elements, Orientations=None, Name=None):
'Positions: 3 x nAtom matrix. Given in atomic units (ABohr).\n Elements: element name (e.g., H) for each of the positions.\n Orientations: If given, a [3,3,N] array encoding the standard\n orientation of the given atoms (for repli... | -7,393,387,328,684,770,000 | Positions: 3 x nAtom matrix. Given in atomic units (ABohr).
Elements: element name (e.g., H) for each of the positions.
Orientations: If given, a [3,3,N] array encoding the standard
orientation of the given atoms (for replicating potentials!). For
each atom there is a orthogonal 3x3 matrix denoting the ex,ey,ez
directi... | pyscf/tools/Molpro2Pyscf/wmme.py | __init__ | JFurness1/pyscf | python | def __init__(self, Positions, Elements, Orientations=None, Name=None):
'Positions: 3 x nAtom matrix. Given in atomic units (ABohr).\n Elements: element name (e.g., H) for each of the positions.\n Orientations: If given, a [3,3,N] array encoding the standard\n orientation of the given atoms (for repli... |
def nElecNeutral(self):
'return number of electrons present in the total system if neutral.'
return sum([ElementNumbers[o] for o in self.Elements]) | 4,413,039,619,599,940,000 | return number of electrons present in the total system if neutral. | pyscf/tools/Molpro2Pyscf/wmme.py | nElecNeutral | JFurness1/pyscf | python | def nElecNeutral(self):
return sum([ElementNumbers[o] for o in self.Elements]) |
def MakeBaseIntegrals(self, Smh=True, MakeS=False):
'Invoke bfint to calculate CoreEnergy (scalar), CoreH (nOrb x nOrb),\n Int2e_Frs (nFit x nOrb x nOrb), and overlap matrix (nOrb x nOrb)'
Args = []
if Smh:
Args.append('--orb-trafo=Smh')
Outputs = []
Outputs.append(('--save-coreh', 'INT... | 1,153,435,770,864,813,000 | Invoke bfint to calculate CoreEnergy (scalar), CoreH (nOrb x nOrb),
Int2e_Frs (nFit x nOrb x nOrb), and overlap matrix (nOrb x nOrb) | pyscf/tools/Molpro2Pyscf/wmme.py | MakeBaseIntegrals | JFurness1/pyscf | python | def MakeBaseIntegrals(self, Smh=True, MakeS=False):
'Invoke bfint to calculate CoreEnergy (scalar), CoreH (nOrb x nOrb),\n Int2e_Frs (nFit x nOrb x nOrb), and overlap matrix (nOrb x nOrb)'
Args = []
if Smh:
Args.append('--orb-trafo=Smh')
Outputs = []
Outputs.append(('--save-coreh', 'INT... |
def MakeOverlaps2(self, OrbBasis2):
'calculate overlap between current basis and a second basis, as\n described in OrbBasis2. Returns <1|2> and <2|2> matrices.'
Args = []
MoreBases = {'--basis-orb-2': OrbBasis2}
Outputs = []
Outputs.append(('--save-overlap-2', 'OVERLAP_2'))
Outputs.append((... | -8,342,458,476,742,344,000 | calculate overlap between current basis and a second basis, as
described in OrbBasis2. Returns <1|2> and <2|2> matrices. | pyscf/tools/Molpro2Pyscf/wmme.py | MakeOverlaps2 | JFurness1/pyscf | python | def MakeOverlaps2(self, OrbBasis2):
'calculate overlap between current basis and a second basis, as\n described in OrbBasis2. Returns <1|2> and <2|2> matrices.'
Args = []
MoreBases = {'--basis-orb-2': OrbBasis2}
Outputs = []
Outputs.append(('--save-overlap-2', 'OVERLAP_2'))
Outputs.append((... |
def MakeOverlap(self, OrbBasis2=None):
'calculate overlap within main orbital basis, and, optionally, between main\n orbital basis and a second basis, as described in OrbBasis2.\n Returns <1|1>, <1|2>, and <2|2> matrices.'
Args = []
Outputs = []
Outputs.append(('--save-overlap', 'OVERLAP_1'))
... | -2,965,824,893,769,018,400 | calculate overlap within main orbital basis, and, optionally, between main
orbital basis and a second basis, as described in OrbBasis2.
Returns <1|1>, <1|2>, and <2|2> matrices. | pyscf/tools/Molpro2Pyscf/wmme.py | MakeOverlap | JFurness1/pyscf | python | def MakeOverlap(self, OrbBasis2=None):
'calculate overlap within main orbital basis, and, optionally, between main\n orbital basis and a second basis, as described in OrbBasis2.\n Returns <1|1>, <1|2>, and <2|2> matrices.'
Args = []
Outputs = []
Outputs.append(('--save-overlap', 'OVERLAP_1'))
... |
def MakeNuclearAttractionIntegrals(self, Smh=True):
'calculate nuclear attraction integrals in main basis, for each individual atomic core.\n Returns nAo x nAo x nAtoms array.'
Args = []
if Smh:
Args.append('--orb-trafo=Smh')
Outputs = []
Outputs.append(('--save-vnucN', 'VNUC_N'))
V... | -7,974,952,442,303,949,000 | calculate nuclear attraction integrals in main basis, for each individual atomic core.
Returns nAo x nAo x nAtoms array. | pyscf/tools/Molpro2Pyscf/wmme.py | MakeNuclearAttractionIntegrals | JFurness1/pyscf | python | def MakeNuclearAttractionIntegrals(self, Smh=True):
'calculate nuclear attraction integrals in main basis, for each individual atomic core.\n Returns nAo x nAo x nAtoms array.'
Args = []
if Smh:
Args.append('--orb-trafo=Smh')
Outputs = []
Outputs.append(('--save-vnucN', 'VNUC_N'))
V... |
def MakeNuclearSqDistanceIntegrals(self, Smh=True):
'calculate <mu|(r-rA)^2|nu> integrals in main basis, for each individual atomic core.\n Returns nAo x nAo x nAtoms array.'
Args = []
if Smh:
Args.append('--orb-trafo=Smh')
Outputs = []
Outputs.append(('--save-rsqN', 'RSQ_N'))
RsqN ... | 441,603,403,193,922,800 | calculate <mu|(r-rA)^2|nu> integrals in main basis, for each individual atomic core.
Returns nAo x nAo x nAtoms array. | pyscf/tools/Molpro2Pyscf/wmme.py | MakeNuclearSqDistanceIntegrals | JFurness1/pyscf | python | def MakeNuclearSqDistanceIntegrals(self, Smh=True):
'calculate <mu|(r-rA)^2|nu> integrals in main basis, for each individual atomic core.\n Returns nAo x nAo x nAtoms array.'
Args = []
if Smh:
Args.append('--orb-trafo=Smh')
Outputs = []
Outputs.append(('--save-rsqN', 'RSQ_N'))
RsqN ... |
def MakeKineticIntegrals(self, Smh=True):
'calculate <mu|-1/2 Laplace|nu> integrals in main basis, for each individual atomic core.\n Returns nAo x nAo x nAtoms array.'
Args = []
if Smh:
Args.append('--orb-trafo=Smh')
Outputs = []
Outputs.append(('--save-kinetic', 'EKIN'))
Op = self... | -8,121,335,166,548,213,000 | calculate <mu|-1/2 Laplace|nu> integrals in main basis, for each individual atomic core.
Returns nAo x nAo x nAtoms array. | pyscf/tools/Molpro2Pyscf/wmme.py | MakeKineticIntegrals | JFurness1/pyscf | python | def MakeKineticIntegrals(self, Smh=True):
'calculate <mu|-1/2 Laplace|nu> integrals in main basis, for each individual atomic core.\n Returns nAo x nAo x nAtoms array.'
Args = []
if Smh:
Args.append('--orb-trafo=Smh')
Outputs = []
Outputs.append(('--save-kinetic', 'EKIN'))
Op = self... |
def MakeDipoleIntegrals(self, Smh=True):
'calculate dipole operator matrices <\\mu|w|\\nu> (w=x,y,z) in\n main basis, for each direction. Returns nAo x nAo x 3 array.'
Args = []
if Smh:
Args.append('--orb-trafo=Smh')
Outputs = []
Outputs.append(('--save-dipole', 'DIPN'))
DipN = self... | 3,350,475,485,117,086,700 | calculate dipole operator matrices <\mu|w|\nu> (w=x,y,z) in
main basis, for each direction. Returns nAo x nAo x 3 array. | pyscf/tools/Molpro2Pyscf/wmme.py | MakeDipoleIntegrals | JFurness1/pyscf | python | def MakeDipoleIntegrals(self, Smh=True):
'calculate dipole operator matrices <\\mu|w|\\nu> (w=x,y,z) in\n main basis, for each direction. Returns nAo x nAo x 3 array.'
Args = []
if Smh:
Args.append('--orb-trafo=Smh')
Outputs = []
Outputs.append(('--save-dipole', 'DIPN'))
DipN = self... |
def MakeOrbitalsOnGrid(self, Orbitals, Grid, DerivativeOrder=0):
'calculate values of molecular orbitals on a grid of 3d points in space.\n Input:\n - Orbitals: nAo x nOrb matrix, where nAo must be compatible with\n self.OrbBasis. The AO dimension must be contravariant AO (i.e., not SMH).\n ... | -8,708,707,247,343,573,000 | calculate values of molecular orbitals on a grid of 3d points in space.
Input:
- Orbitals: nAo x nOrb matrix, where nAo must be compatible with
self.OrbBasis. The AO dimension must be contravariant AO (i.e., not SMH).
- Grid: 3 x nGrid array giving the coordinates of the grid points.
- DerivativeOrder: 0:... | pyscf/tools/Molpro2Pyscf/wmme.py | MakeOrbitalsOnGrid | JFurness1/pyscf | python | def MakeOrbitalsOnGrid(self, Orbitals, Grid, DerivativeOrder=0):
'calculate values of molecular orbitals on a grid of 3d points in space.\n Input:\n - Orbitals: nAo x nOrb matrix, where nAo must be compatible with\n self.OrbBasis. The AO dimension must be contravariant AO (i.e., not SMH).\n ... |
def MakeRaw2eIntegrals(self, Smh=True, Kernel2e='coulomb'):
'compute Int2e_Frs (nFit x nOrb x nOrb) and fitting metric Int2e_FG (nFit x nFit),\n where the fitting metric is *not* absorbed into the 2e integrals.'
Args = []
if Smh:
Args.append('--orb-trafo=Smh')
Args.append(("--kernel2e='%s'"... | 2,896,667,907,041,322,000 | compute Int2e_Frs (nFit x nOrb x nOrb) and fitting metric Int2e_FG (nFit x nFit),
where the fitting metric is *not* absorbed into the 2e integrals. | pyscf/tools/Molpro2Pyscf/wmme.py | MakeRaw2eIntegrals | JFurness1/pyscf | python | def MakeRaw2eIntegrals(self, Smh=True, Kernel2e='coulomb'):
'compute Int2e_Frs (nFit x nOrb x nOrb) and fitting metric Int2e_FG (nFit x nFit),\n where the fitting metric is *not* absorbed into the 2e integrals.'
Args = []
if Smh:
Args.append('--orb-trafo=Smh')
Args.append(("--kernel2e='%s'"... |
def service_cidr():
" Return the charm's service-cidr config "
db = unitdata.kv()
frozen_cidr = db.get('kubernetes-master.service-cidr')
return (frozen_cidr or hookenv.config('service-cidr')) | 2,082,332,788,383,550,500 | Return the charm's service-cidr config | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | service_cidr | BaiHuoYu/nbp | python | def service_cidr():
" "
db = unitdata.kv()
frozen_cidr = db.get('kubernetes-master.service-cidr')
return (frozen_cidr or hookenv.config('service-cidr')) |
def freeze_service_cidr():
' Freeze the service CIDR. Once the apiserver has started, we can no\n longer safely change this value. '
db = unitdata.kv()
db.set('kubernetes-master.service-cidr', service_cidr()) | -8,319,294,074,560,905,000 | Freeze the service CIDR. Once the apiserver has started, we can no
longer safely change this value. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | freeze_service_cidr | BaiHuoYu/nbp | python | def freeze_service_cidr():
' Freeze the service CIDR. Once the apiserver has started, we can no\n longer safely change this value. '
db = unitdata.kv()
db.set('kubernetes-master.service-cidr', service_cidr()) |
@hook('upgrade-charm')
def reset_states_for_delivery():
'An upgrade charm event was triggered by Juju, react to that here.'
migrate_from_pre_snaps()
install_snaps()
set_state('reconfigure.authentication.setup')
remove_state('authentication.setup') | -2,834,097,775,026,214,400 | An upgrade charm event was triggered by Juju, react to that here. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | reset_states_for_delivery | BaiHuoYu/nbp | python | @hook('upgrade-charm')
def reset_states_for_delivery():
migrate_from_pre_snaps()
install_snaps()
set_state('reconfigure.authentication.setup')
remove_state('authentication.setup') |
@when('config.changed.client_password', 'leadership.is_leader')
def password_changed():
'Handle password change via the charms config.'
password = hookenv.config('client_password')
if ((password == '') and is_state('client.password.initialised')):
return
elif (password == ''):
password =... | -6,696,244,841,314,084,000 | Handle password change via the charms config. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | password_changed | BaiHuoYu/nbp | python | @when('config.changed.client_password', 'leadership.is_leader')
def password_changed():
password = hookenv.config('client_password')
if ((password == ) and is_state('client.password.initialised')):
return
elif (password == ):
password = token_generator()
setup_basic_auth(password, '... |
@when('cni.connected')
@when_not('cni.configured')
def configure_cni(cni):
" Set master configuration on the CNI relation. This lets the CNI\n subordinate know that we're the master so it can respond accordingly. "
cni.set_config(is_master=True, kubeconfig_path='') | 8,362,492,290,030,831,000 | Set master configuration on the CNI relation. This lets the CNI
subordinate know that we're the master so it can respond accordingly. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | configure_cni | BaiHuoYu/nbp | python | @when('cni.connected')
@when_not('cni.configured')
def configure_cni(cni):
" Set master configuration on the CNI relation. This lets the CNI\n subordinate know that we're the master so it can respond accordingly. "
cni.set_config(is_master=True, kubeconfig_path=) |
@when('leadership.is_leader')
@when_not('authentication.setup')
def setup_leader_authentication():
'Setup basic authentication and token access for the cluster.'
api_opts = FlagManager('kube-apiserver')
controller_opts = FlagManager('kube-controller-manager')
service_key = '/root/cdk/serviceaccount.key'... | 7,515,041,697,489,415,000 | Setup basic authentication and token access for the cluster. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | setup_leader_authentication | BaiHuoYu/nbp | python | @when('leadership.is_leader')
@when_not('authentication.setup')
def setup_leader_authentication():
api_opts = FlagManager('kube-apiserver')
controller_opts = FlagManager('kube-controller-manager')
service_key = '/root/cdk/serviceaccount.key'
basic_auth = '/root/cdk/basic_auth.csv'
known_tokens ... |
def get_keys_from_leader(keys, overwrite_local=False):
'\n Gets the broadcasted keys from the leader and stores them in\n the corresponding files.\n\n Args:\n keys: list of keys. Keys are actually files on the FS.\n\n Returns: True if all key were fetched, False if not.\n\n '
os.makedirs('... | 5,011,326,847,538,366,000 | Gets the broadcasted keys from the leader and stores them in
the corresponding files.
Args:
keys: list of keys. Keys are actually files on the FS.
Returns: True if all key were fetched, False if not. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | get_keys_from_leader | BaiHuoYu/nbp | python | def get_keys_from_leader(keys, overwrite_local=False):
'\n Gets the broadcasted keys from the leader and stores them in\n the corresponding files.\n\n Args:\n keys: list of keys. Keys are actually files on the FS.\n\n Returns: True if all key were fetched, False if not.\n\n '
os.makedirs('... |
@when('kubernetes-master.snaps.installed')
def set_app_version():
' Declare the application version to juju '
version = check_output(['kube-apiserver', '--version'])
hookenv.application_version_set(version.split(b' v')[(- 1)].rstrip()) | -7,837,022,965,875,794,000 | Declare the application version to juju | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | set_app_version | BaiHuoYu/nbp | python | @when('kubernetes-master.snaps.installed')
def set_app_version():
' '
version = check_output(['kube-apiserver', '--version'])
hookenv.application_version_set(version.split(b' v')[(- 1)].rstrip()) |
@when('cdk-addons.configured', 'kube-api-endpoint.available', 'kube-control.connected')
def idle_status(kube_api, kube_control):
' Signal at the end of the run that we are running. '
if (not all_kube_system_pods_running()):
hookenv.status_set('waiting', 'Waiting for kube-system pods to start')
elif ... | -87,910,655,510,297,980 | Signal at the end of the run that we are running. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | idle_status | BaiHuoYu/nbp | python | @when('cdk-addons.configured', 'kube-api-endpoint.available', 'kube-control.connected')
def idle_status(kube_api, kube_control):
' '
if (not all_kube_system_pods_running()):
hookenv.status_set('waiting', 'Waiting for kube-system pods to start')
elif (hookenv.config('service-cidr') != service_cidr()... |
def master_services_down():
'Ensure master services are up and running.\n\n Return: list of failing services'
services = ['kube-apiserver', 'kube-controller-manager', 'kube-scheduler']
failing_services = []
for service in services:
daemon = 'snap.{}.daemon'.format(service)
if (not hos... | 5,637,071,088,973,993,000 | Ensure master services are up and running.
Return: list of failing services | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | master_services_down | BaiHuoYu/nbp | python | def master_services_down():
'Ensure master services are up and running.\n\n Return: list of failing services'
services = ['kube-apiserver', 'kube-controller-manager', 'kube-scheduler']
failing_services = []
for service in services:
daemon = 'snap.{}.daemon'.format(service)
if (not hos... |
@when('etcd.available', 'tls_client.server.certificate.saved', 'authentication.setup')
@when_not('kubernetes-master.components.started')
def start_master(etcd):
'Run the Kubernetes master components.'
hookenv.status_set('maintenance', 'Configuring the Kubernetes master services.')
freeze_service_cidr()
... | 704,572,935,404,919,700 | Run the Kubernetes master components. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | start_master | BaiHuoYu/nbp | python | @when('etcd.available', 'tls_client.server.certificate.saved', 'authentication.setup')
@when_not('kubernetes-master.components.started')
def start_master(etcd):
hookenv.status_set('maintenance', 'Configuring the Kubernetes master services.')
freeze_service_cidr()
if (not etcd.get_connection_string()):
... |
@when('etcd.available')
def etcd_data_change(etcd):
' Etcd scale events block master reconfiguration due to the\n kubernetes-master.components.started state. We need a way to\n handle these events consistenly only when the number of etcd\n units has actually changed '
connection_string = et... | 138,625,547,488,238,990 | Etcd scale events block master reconfiguration due to the
kubernetes-master.components.started state. We need a way to
handle these events consistenly only when the number of etcd
units has actually changed | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | etcd_data_change | BaiHuoYu/nbp | python | @when('etcd.available')
def etcd_data_change(etcd):
' Etcd scale events block master reconfiguration due to the\n kubernetes-master.components.started state. We need a way to\n handle these events consistenly only when the number of etcd\n units has actually changed '
connection_string = et... |
@when('kube-control.connected')
@when('cdk-addons.configured')
def send_cluster_dns_detail(kube_control):
' Send cluster DNS info '
dns_ip = get_dns_ip()
kube_control.set_dns(53, hookenv.config('dns_domain'), dns_ip) | -5,709,654,663,551,629,000 | Send cluster DNS info | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | send_cluster_dns_detail | BaiHuoYu/nbp | python | @when('kube-control.connected')
@when('cdk-addons.configured')
def send_cluster_dns_detail(kube_control):
' '
dns_ip = get_dns_ip()
kube_control.set_dns(53, hookenv.config('dns_domain'), dns_ip) |
@when('kube-control.auth.requested')
@when('authentication.setup')
@when('leadership.is_leader')
def send_tokens(kube_control):
'Send the tokens to the workers.'
kubelet_token = get_token('kubelet')
proxy_token = get_token('kube_proxy')
admin_token = get_token('admin')
requests = kube_control.auth_u... | -4,402,742,211,720,884,700 | Send the tokens to the workers. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | send_tokens | BaiHuoYu/nbp | python | @when('kube-control.auth.requested')
@when('authentication.setup')
@when('leadership.is_leader')
def send_tokens(kube_control):
kubelet_token = get_token('kubelet')
proxy_token = get_token('kube_proxy')
admin_token = get_token('admin')
requests = kube_control.auth_user()
for request in requests... |
@when_not('kube-control.connected')
def missing_kube_control():
"Inform the operator master is waiting for a relation to workers.\n\n If deploying via bundle this won't happen, but if operator is upgrading a\n a charm in a deployment that pre-dates the kube-control relation, it'll be\n missing.\n\n "
... | 1,777,728,462,669,904,100 | Inform the operator master is waiting for a relation to workers.
If deploying via bundle this won't happen, but if operator is upgrading a
a charm in a deployment that pre-dates the kube-control relation, it'll be
missing. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | missing_kube_control | BaiHuoYu/nbp | python | @when_not('kube-control.connected')
def missing_kube_control():
"Inform the operator master is waiting for a relation to workers.\n\n If deploying via bundle this won't happen, but if operator is upgrading a\n a charm in a deployment that pre-dates the kube-control relation, it'll be\n missing.\n\n "
... |
@when('kube-api-endpoint.available')
def push_service_data(kube_api):
' Send configuration to the load balancer, and close access to the\n public interface '
kube_api.configure(port=6443) | 5,358,579,529,708,485,000 | Send configuration to the load balancer, and close access to the
public interface | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | push_service_data | BaiHuoYu/nbp | python | @when('kube-api-endpoint.available')
def push_service_data(kube_api):
' Send configuration to the load balancer, and close access to the\n public interface '
kube_api.configure(port=6443) |
@when('certificates.available')
def send_data(tls):
'Send the data that is required to create a server certificate for\n this server.'
common_name = hookenv.unit_public_ip()
kubernetes_service_ip = get_kubernetes_service_ip()
domain = hookenv.config('dns_domain')
sans = [hookenv.unit_public_ip(),... | 4,849,997,581,079,090,000 | Send the data that is required to create a server certificate for
this server. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | send_data | BaiHuoYu/nbp | python | @when('certificates.available')
def send_data(tls):
'Send the data that is required to create a server certificate for\n this server.'
common_name = hookenv.unit_public_ip()
kubernetes_service_ip = get_kubernetes_service_ip()
domain = hookenv.config('dns_domain')
sans = [hookenv.unit_public_ip(),... |
@when('kubernetes-master.components.started')
def configure_cdk_addons():
' Configure CDK addons '
remove_state('cdk-addons.configured')
dbEnabled = str(hookenv.config('enable-dashboard-addons')).lower()
args = [('arch=' + arch()), ('dns-ip=' + get_dns_ip()), ('dns-domain=' + hookenv.config('dns_domain'... | -2,867,987,770,483,336,000 | Configure CDK addons | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | configure_cdk_addons | BaiHuoYu/nbp | python | @when('kubernetes-master.components.started')
def configure_cdk_addons():
' '
remove_state('cdk-addons.configured')
dbEnabled = str(hookenv.config('enable-dashboard-addons')).lower()
args = [('arch=' + arch()), ('dns-ip=' + get_dns_ip()), ('dns-domain=' + hookenv.config('dns_domain')), ('enable-dashboa... |
@retry(times=3, delay_secs=20)
def addons_ready():
'\n Test if the add ons got installed\n\n Returns: True is the addons got applied\n\n '
try:
check_call(['cdk-addons.apply'])
return True
except CalledProcessError:
hookenv.log('Addons are not ready yet.')
return Fal... | -7,442,323,682,676,021,000 | Test if the add ons got installed
Returns: True is the addons got applied | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | addons_ready | BaiHuoYu/nbp | python | @retry(times=3, delay_secs=20)
def addons_ready():
'\n Test if the add ons got installed\n\n Returns: True is the addons got applied\n\n '
try:
check_call(['cdk-addons.apply'])
return True
except CalledProcessError:
hookenv.log('Addons are not ready yet.')
return Fal... |
@when('certificates.ca.available', 'certificates.client.cert.available', 'authentication.setup')
@when_not('loadbalancer.available')
def create_self_config(ca, client):
'Create a kubernetes configuration for the master unit.'
server = 'https://{0}:{1}'.format(hookenv.unit_get('public-address'), 6443)
build_... | 6,422,452,282,395,083,000 | Create a kubernetes configuration for the master unit. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | create_self_config | BaiHuoYu/nbp | python | @when('certificates.ca.available', 'certificates.client.cert.available', 'authentication.setup')
@when_not('loadbalancer.available')
def create_self_config(ca, client):
server = 'https://{0}:{1}'.format(hookenv.unit_get('public-address'), 6443)
build_kubeconfig(server) |
@when('ceph-storage.available')
def ceph_state_control(ceph_admin):
' Determine if we should remove the state that controls the re-render\n and execution of the ceph-relation-changed event because there\n are changes in the relationship data, and we should re-render any\n configs, keys, and/or service pre-... | 4,012,998,128,674,763,300 | Determine if we should remove the state that controls the re-render
and execution of the ceph-relation-changed event because there
are changes in the relationship data, and we should re-render any
configs, keys, and/or service pre-reqs | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | ceph_state_control | BaiHuoYu/nbp | python | @when('ceph-storage.available')
def ceph_state_control(ceph_admin):
' Determine if we should remove the state that controls the re-render\n and execution of the ceph-relation-changed event because there\n are changes in the relationship data, and we should re-render any\n configs, keys, and/or service pre-... |
@when('ceph-storage.available')
@when_not('ceph-storage.configured')
def ceph_storage(ceph_admin):
'Ceph on kubernetes will require a few things - namely a ceph\n configuration, and the ceph secret key file used for authentication.\n This method will install the client package, and render the requisit files\n... | -2,433,001,908,601,862,700 | Ceph on kubernetes will require a few things - namely a ceph
configuration, and the ceph secret key file used for authentication.
This method will install the client package, and render the requisit files
in order to consume the ceph-storage relation. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | ceph_storage | BaiHuoYu/nbp | python | @when('ceph-storage.available')
@when_not('ceph-storage.configured')
def ceph_storage(ceph_admin):
'Ceph on kubernetes will require a few things - namely a ceph\n configuration, and the ceph secret key file used for authentication.\n This method will install the client package, and render the requisit files\n... |
def is_privileged():
'Return boolean indicating whether or not to set allow-privileged=true.\n\n '
privileged = hookenv.config('allow-privileged')
if (privileged == 'auto'):
return is_state('kubernetes-master.gpu.enabled')
else:
return (privileged == 'true') | -780,240,340,701,585,900 | Return boolean indicating whether or not to set allow-privileged=true. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | is_privileged | BaiHuoYu/nbp | python | def is_privileged():
'\n\n '
privileged = hookenv.config('allow-privileged')
if (privileged == 'auto'):
return is_state('kubernetes-master.gpu.enabled')
else:
return (privileged == 'true') |
@when('config.changed.allow-privileged')
@when('kubernetes-master.components.started')
def on_config_allow_privileged_change():
"React to changed 'allow-privileged' config value.\n\n "
remove_state('kubernetes-master.components.started')
remove_state('config.changed.allow-privileged') | 4,813,052,077,131,673,000 | React to changed 'allow-privileged' config value. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | on_config_allow_privileged_change | BaiHuoYu/nbp | python | @when('config.changed.allow-privileged')
@when('kubernetes-master.components.started')
def on_config_allow_privileged_change():
"\n\n "
remove_state('kubernetes-master.components.started')
remove_state('config.changed.allow-privileged') |
@when('kube-control.gpu.available')
@when('kubernetes-master.components.started')
@when_not('kubernetes-master.gpu.enabled')
def on_gpu_available(kube_control):
'The remote side (kubernetes-worker) is gpu-enabled.\n\n We need to run in privileged mode.\n\n '
config = hookenv.config()
if (config['allow... | 4,215,349,961,622,603,300 | The remote side (kubernetes-worker) is gpu-enabled.
We need to run in privileged mode. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | on_gpu_available | BaiHuoYu/nbp | python | @when('kube-control.gpu.available')
@when('kubernetes-master.components.started')
@when_not('kubernetes-master.gpu.enabled')
def on_gpu_available(kube_control):
'The remote side (kubernetes-worker) is gpu-enabled.\n\n We need to run in privileged mode.\n\n '
config = hookenv.config()
if (config['allow... |
@when('kubernetes-master.gpu.enabled')
@when_not('kubernetes-master.privileged')
def disable_gpu_mode():
'We were in gpu mode, but the operator has set allow-privileged="false",\n so we can\'t run in gpu mode anymore.\n\n '
remove_state('kubernetes-master.gpu.enabled') | 7,250,460,879,740,247,000 | We were in gpu mode, but the operator has set allow-privileged="false",
so we can't run in gpu mode anymore. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | disable_gpu_mode | BaiHuoYu/nbp | python | @when('kubernetes-master.gpu.enabled')
@when_not('kubernetes-master.privileged')
def disable_gpu_mode():
'We were in gpu mode, but the operator has set allow-privileged="false",\n so we can\'t run in gpu mode anymore.\n\n '
remove_state('kubernetes-master.gpu.enabled') |
@hook('stop')
def shutdown():
' Stop the kubernetes master services\n\n '
service_stop('snap.kube-apiserver.daemon')
service_stop('snap.kube-controller-manager.daemon')
service_stop('snap.kube-scheduler.daemon') | -1,049,840,848,278,248,600 | Stop the kubernetes master services | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | shutdown | BaiHuoYu/nbp | python | @hook('stop')
def shutdown():
' \n\n '
service_stop('snap.kube-apiserver.daemon')
service_stop('snap.kube-controller-manager.daemon')
service_stop('snap.kube-scheduler.daemon') |
def arch():
'Return the package architecture as a string. Raise an exception if the\n architecture is not supported by kubernetes.'
architecture = check_output(['dpkg', '--print-architecture']).rstrip()
architecture = architecture.decode('utf-8')
return architecture | 7,777,717,789,895,950,000 | Return the package architecture as a string. Raise an exception if the
architecture is not supported by kubernetes. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | arch | BaiHuoYu/nbp | python | def arch():
'Return the package architecture as a string. Raise an exception if the\n architecture is not supported by kubernetes.'
architecture = check_output(['dpkg', '--print-architecture']).rstrip()
architecture = architecture.decode('utf-8')
return architecture |
def build_kubeconfig(server):
'Gather the relevant data for Kubernetes configuration objects and create\n a config object with that information.'
layer_options = layer.options('tls-client')
ca = layer_options.get('ca_certificate_path')
ca_exists = (ca and os.path.isfile(ca))
client_pass = get_pas... | -2,934,579,074,449,449,000 | Gather the relevant data for Kubernetes configuration objects and create
a config object with that information. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | build_kubeconfig | BaiHuoYu/nbp | python | def build_kubeconfig(server):
'Gather the relevant data for Kubernetes configuration objects and create\n a config object with that information.'
layer_options = layer.options('tls-client')
ca = layer_options.get('ca_certificate_path')
ca_exists = (ca and os.path.isfile(ca))
client_pass = get_pas... |
def create_kubeconfig(kubeconfig, server, ca, key=None, certificate=None, user='ubuntu', context='juju-context', cluster='juju-cluster', password=None, token=None):
'Create a configuration for Kubernetes based on path using the supplied\n arguments for values of the Kubernetes server, CA, key, certificate, user\... | -2,665,510,102,998,262,000 | Create a configuration for Kubernetes based on path using the supplied
arguments for values of the Kubernetes server, CA, key, certificate, user
context and cluster. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | create_kubeconfig | BaiHuoYu/nbp | python | def create_kubeconfig(kubeconfig, server, ca, key=None, certificate=None, user='ubuntu', context='juju-context', cluster='juju-cluster', password=None, token=None):
'Create a configuration for Kubernetes based on path using the supplied\n arguments for values of the Kubernetes server, CA, key, certificate, user\... |
def get_dns_ip():
'Get an IP address for the DNS server on the provided cidr.'
interface = ipaddress.IPv4Interface(service_cidr())
ip = (interface.network.network_address + 10)
return ip.exploded | 5,212,188,719,946,503,000 | Get an IP address for the DNS server on the provided cidr. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | get_dns_ip | BaiHuoYu/nbp | python | def get_dns_ip():
interface = ipaddress.IPv4Interface(service_cidr())
ip = (interface.network.network_address + 10)
return ip.exploded |
def get_kubernetes_service_ip():
'Get the IP address for the kubernetes service based on the cidr.'
interface = ipaddress.IPv4Interface(service_cidr())
ip = (interface.network.network_address + 1)
return ip.exploded | 4,044,658,461,190,373,000 | Get the IP address for the kubernetes service based on the cidr. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | get_kubernetes_service_ip | BaiHuoYu/nbp | python | def get_kubernetes_service_ip():
interface = ipaddress.IPv4Interface(service_cidr())
ip = (interface.network.network_address + 1)
return ip.exploded |
def handle_etcd_relation(reldata):
' Save the client credentials and set appropriate daemon flags when\n etcd declares itself as available'
connection_string = reldata.get_connection_string()
etcd_dir = '/root/cdk/etcd'
ca = os.path.join(etcd_dir, 'client-ca.pem')
key = os.path.join(etcd_dir, 'cl... | -8,894,728,876,959,341,000 | Save the client credentials and set appropriate daemon flags when
etcd declares itself as available | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | handle_etcd_relation | BaiHuoYu/nbp | python | def handle_etcd_relation(reldata):
' Save the client credentials and set appropriate daemon flags when\n etcd declares itself as available'
connection_string = reldata.get_connection_string()
etcd_dir = '/root/cdk/etcd'
ca = os.path.join(etcd_dir, 'client-ca.pem')
key = os.path.join(etcd_dir, 'cl... |
def configure_master_services():
' Add remaining flags for the master services and configure snaps to use\n them '
api_opts = FlagManager('kube-apiserver')
controller_opts = FlagManager('kube-controller-manager')
scheduler_opts = FlagManager('kube-scheduler')
scheduler_opts.add('v', '2')
laye... | 1,320,986,970,023,214,800 | Add remaining flags for the master services and configure snaps to use
them | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | configure_master_services | BaiHuoYu/nbp | python | def configure_master_services():
' Add remaining flags for the master services and configure snaps to use\n them '
api_opts = FlagManager('kube-apiserver')
controller_opts = FlagManager('kube-controller-manager')
scheduler_opts = FlagManager('kube-scheduler')
scheduler_opts.add('v', '2')
laye... |
def setup_basic_auth(password=None, username='admin', uid='admin'):
'Create the htacces file and the tokens.'
root_cdk = '/root/cdk'
if (not os.path.isdir(root_cdk)):
os.makedirs(root_cdk)
htaccess = os.path.join(root_cdk, 'basic_auth.csv')
if (not password):
password = token_generat... | 3,896,753,039,689,212,000 | Create the htacces file and the tokens. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | setup_basic_auth | BaiHuoYu/nbp | python | def setup_basic_auth(password=None, username='admin', uid='admin'):
root_cdk = '/root/cdk'
if (not os.path.isdir(root_cdk)):
os.makedirs(root_cdk)
htaccess = os.path.join(root_cdk, 'basic_auth.csv')
if (not password):
password = token_generator()
with open(htaccess, 'w') as stre... |
def setup_tokens(token, username, user):
'Create a token file for kubernetes authentication.'
root_cdk = '/root/cdk'
if (not os.path.isdir(root_cdk)):
os.makedirs(root_cdk)
known_tokens = os.path.join(root_cdk, 'known_tokens.csv')
if (not token):
token = token_generator()
with op... | -5,288,888,162,399,618,000 | Create a token file for kubernetes authentication. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | setup_tokens | BaiHuoYu/nbp | python | def setup_tokens(token, username, user):
root_cdk = '/root/cdk'
if (not os.path.isdir(root_cdk)):
os.makedirs(root_cdk)
known_tokens = os.path.join(root_cdk, 'known_tokens.csv')
if (not token):
token = token_generator()
with open(known_tokens, 'a') as stream:
stream.writ... |
def get_password(csv_fname, user):
'Get the password of user within the csv file provided.'
root_cdk = '/root/cdk'
tokens_fname = os.path.join(root_cdk, csv_fname)
if (not os.path.isfile(tokens_fname)):
return None
with open(tokens_fname, 'r') as stream:
for line in stream:
... | 1,101,407,316,263,802,400 | Get the password of user within the csv file provided. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | get_password | BaiHuoYu/nbp | python | def get_password(csv_fname, user):
root_cdk = '/root/cdk'
tokens_fname = os.path.join(root_cdk, csv_fname)
if (not os.path.isfile(tokens_fname)):
return None
with open(tokens_fname, 'r') as stream:
for line in stream:
record = line.split(',')
if (record[1] ==... |
def get_token(username):
'Grab a token from the static file if present. '
return get_password('known_tokens.csv', username) | 2,882,756,315,456,273,400 | Grab a token from the static file if present. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | get_token | BaiHuoYu/nbp | python | def get_token(username):
' '
return get_password('known_tokens.csv', username) |
def set_token(password, save_salt):
' Store a token so it can be recalled later by token_generator.\n\n param: password - the password to be stored\n param: save_salt - the key to store the value of the token.'
db = unitdata.kv()
db.set(save_salt, password)
return db.get(save_salt) | 7,914,817,382,534,536,000 | Store a token so it can be recalled later by token_generator.
param: password - the password to be stored
param: save_salt - the key to store the value of the token. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | set_token | BaiHuoYu/nbp | python | def set_token(password, save_salt):
' Store a token so it can be recalled later by token_generator.\n\n param: password - the password to be stored\n param: save_salt - the key to store the value of the token.'
db = unitdata.kv()
db.set(save_salt, password)
return db.get(save_salt) |
def token_generator(length=32):
' Generate a random token for use in passwords and account tokens.\n\n param: length - the length of the token to generate'
alpha = (string.ascii_letters + string.digits)
token = ''.join((random.SystemRandom().choice(alpha) for _ in range(length)))
return token | 4,775,048,515,420,518,000 | Generate a random token for use in passwords and account tokens.
param: length - the length of the token to generate | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | token_generator | BaiHuoYu/nbp | python | def token_generator(length=32):
' Generate a random token for use in passwords and account tokens.\n\n param: length - the length of the token to generate'
alpha = (string.ascii_letters + string.digits)
token = .join((random.SystemRandom().choice(alpha) for _ in range(length)))
return token |
@retry(times=3, delay_secs=10)
def all_kube_system_pods_running():
' Check pod status in the kube-system namespace. Returns True if all\n pods are running, False otherwise. '
cmd = ['kubectl', 'get', 'po', '-n', 'kube-system', '-o', 'json']
try:
output = check_output(cmd).decode('utf-8')
exce... | -5,931,451,774,860,304,000 | Check pod status in the kube-system namespace. Returns True if all
pods are running, False otherwise. | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | all_kube_system_pods_running | BaiHuoYu/nbp | python | @retry(times=3, delay_secs=10)
def all_kube_system_pods_running():
' Check pod status in the kube-system namespace. Returns True if all\n pods are running, False otherwise. '
cmd = ['kubectl', 'get', 'po', '-n', 'kube-system', '-o', 'json']
try:
output = check_output(cmd).decode('utf-8')
exce... |
@maybe_login_required
def get(self):
'\n ---\n description: Get a list of commits.\n responses:\n "200": "CommitList"\n "401": "401"\n tags:\n - Commits\n '
commits = Commit.all(order_by=Commit.timestamp.desc(), limit=500)
return self.seriali... | 2,398,455,464,862,368,000 | ---
description: Get a list of commits.
responses:
"200": "CommitList"
"401": "401"
tags:
- Commits | conbench/api/commits.py | get | Christian8491/conbench | python | @maybe_login_required
def get(self):
'\n ---\n description: Get a list of commits.\n responses:\n "200": "CommitList"\n "401": "401"\n tags:\n - Commits\n '
commits = Commit.all(order_by=Commit.timestamp.desc(), limit=500)
return self.seriali... |
@maybe_login_required
def get(self, commit_id):
'\n ---\n description: Get a commit.\n responses:\n "200": "CommitEntity"\n "401": "401"\n "404": "404"\n parameters:\n - name: commit_id\n in: path\n schema:\n ... | -4,298,231,717,111,611,400 | ---
description: Get a commit.
responses:
"200": "CommitEntity"
"401": "401"
"404": "404"
parameters:
- name: commit_id
in: path
schema:
type: string
tags:
- Commits | conbench/api/commits.py | get | Christian8491/conbench | python | @maybe_login_required
def get(self, commit_id):
'\n ---\n description: Get a commit.\n responses:\n "200": "CommitEntity"\n "401": "401"\n "404": "404"\n parameters:\n - name: commit_id\n in: path\n schema:\n ... |
def __init__(self, basedir=None, **kwargs):
' Constructor '
self.basedir = basedir | 4,008,232,155,774,888,000 | Constructor | lookup_plugins/oo_option.py | __init__ | Acidburn0zzz/openshift-ansible | python | def __init__(self, basedir=None, **kwargs):
' '
self.basedir = basedir |
def run(self, terms, variables, **kwargs):
' Main execution path '
ret = []
for term in terms:
option_name = term.split()[0]
cli_key = ('cli_' + option_name)
if (('vars' in variables) and (cli_key in variables['vars'])):
ret.append(variables['vars'][cli_key])
elif... | -6,311,369,496,282,909,000 | Main execution path | lookup_plugins/oo_option.py | run | Acidburn0zzz/openshift-ansible | python | def run(self, terms, variables, **kwargs):
' '
ret = []
for term in terms:
option_name = term.split()[0]
cli_key = ('cli_' + option_name)
if (('vars' in variables) and (cli_key in variables['vars'])):
ret.append(variables['vars'][cli_key])
elif (option_name in os... |
def download_file(url, data_path='.', filename=None, size=None, chunk_size=4096, verbose=True):
'Uses stream=True and a reasonable chunk size to be able to download large (GB) files over https'
if (filename is None):
filename = dropbox_basename(url)
file_path = os.path.join(data_path, filename)
... | 2,216,735,184,912,804,000 | Uses stream=True and a reasonable chunk size to be able to download large (GB) files over https | nlpia/book/examples/ch09.py | download_file | brusic/nlpia | python | def download_file(url, data_path='.', filename=None, size=None, chunk_size=4096, verbose=True):
if (filename is None):
filename = dropbox_basename(url)
file_path = os.path.join(data_path, filename)
if url.endswith('?dl=0'):
url = (url[:(- 1)] + '1')
if verbose:
tqdm_prog = t... |
def pre_process_data(filepath):
'\n This is dependent on your training data source but we will try to generalize it as best as possible.\n '
positive_path = os.path.join(filepath, 'pos')
negative_path = os.path.join(filepath, 'neg')
pos_label = 1
neg_label = 0
dataset = []
for filename... | -6,618,729,490,272,597,000 | This is dependent on your training data source but we will try to generalize it as best as possible. | nlpia/book/examples/ch09.py | pre_process_data | brusic/nlpia | python | def pre_process_data(filepath):
'\n \n '
positive_path = os.path.join(filepath, 'pos')
negative_path = os.path.join(filepath, 'neg')
pos_label = 1
neg_label = 0
dataset = []
for filename in glob.glob(os.path.join(positive_path, '*.txt')):
with open(filename, 'r') as f:
... |
def collect_expected(dataset):
' Peel of the target values from the dataset '
expected = []
for sample in dataset:
expected.append(sample[0])
return expected | -2,978,209,738,048,376,000 | Peel of the target values from the dataset | nlpia/book/examples/ch09.py | collect_expected | brusic/nlpia | python | def collect_expected(dataset):
' '
expected = []
for sample in dataset:
expected.append(sample[0])
return expected |
def pad_trunc(data, maxlen):
' For a given dataset pad with zero vectors or truncate to maxlen '
new_data = []
zero_vector = []
for _ in range(len(data[0][0])):
zero_vector.append(0.0)
for sample in data:
if (len(sample) > maxlen):
temp = sample[:maxlen]
elif (len... | -2,545,233,103,941,332,500 | For a given dataset pad with zero vectors or truncate to maxlen | nlpia/book/examples/ch09.py | pad_trunc | brusic/nlpia | python | def pad_trunc(data, maxlen):
' '
new_data = []
zero_vector = []
for _ in range(len(data[0][0])):
zero_vector.append(0.0)
for sample in data:
if (len(sample) > maxlen):
temp = sample[:maxlen]
elif (len(sample) < maxlen):
temp = sample
addit... |
def clean_data(data):
' Shift to lower case, replace unknowns with UNK, and listify '
new_data = []
VALID = 'abcdefghijklmnopqrstuvwxyz123456789"\'?!.,:; '
for sample in data:
new_sample = []
for char in sample[1].lower():
if (char in VALID):
new_sample.append... | -5,663,162,335,939,279,000 | Shift to lower case, replace unknowns with UNK, and listify | nlpia/book/examples/ch09.py | clean_data | brusic/nlpia | python | def clean_data(data):
' '
new_data = []
VALID = 'abcdefghijklmnopqrstuvwxyz123456789"\'?!.,:; '
for sample in data:
new_sample = []
for char in sample[1].lower():
if (char in VALID):
new_sample.append(char)
else:
new_sample.append(... |
def char_pad_trunc(data, maxlen):
' We truncate to maxlen or add in PAD tokens '
new_dataset = []
for sample in data:
if (len(sample) > maxlen):
new_data = sample[:maxlen]
elif (len(sample) < maxlen):
pads = (maxlen - len(sample))
new_data = (sample + (['P... | -6,277,311,333,360,395,000 | We truncate to maxlen or add in PAD tokens | nlpia/book/examples/ch09.py | char_pad_trunc | brusic/nlpia | python | def char_pad_trunc(data, maxlen):
' '
new_dataset = []
for sample in data:
if (len(sample) > maxlen):
new_data = sample[:maxlen]
elif (len(sample) < maxlen):
pads = (maxlen - len(sample))
new_data = (sample + (['PAD'] * pads))
else:
ne... |
def create_dicts(data):
' Modified from Keras LSTM example'
chars = set()
for sample in data:
chars.update(set(sample))
char_indices = dict(((c, i) for (i, c) in enumerate(chars)))
indices_char = dict(((i, c) for (i, c) in enumerate(chars)))
return (char_indices, indices_char) | 89,649,798,061,459,300 | Modified from Keras LSTM example | nlpia/book/examples/ch09.py | create_dicts | brusic/nlpia | python | def create_dicts(data):
' '
chars = set()
for sample in data:
chars.update(set(sample))
char_indices = dict(((c, i) for (i, c) in enumerate(chars)))
indices_char = dict(((i, c) for (i, c) in enumerate(chars)))
return (char_indices, indices_char) |
def onehot_encode(dataset, char_indices, maxlen):
' \n One hot encode the tokens\n \n Args:\n dataset list of lists of tokens\n char_indices dictionary of {key=character, value=index to use encoding vector}\n maxlen int Length of each sample\n Return:\n np array of shape ... | 1,302,900,060,204,858,600 | One hot encode the tokens
Args:
dataset list of lists of tokens
char_indices dictionary of {key=character, value=index to use encoding vector}
maxlen int Length of each sample
Return:
np array of shape (samples, tokens, encoding length) | nlpia/book/examples/ch09.py | onehot_encode | brusic/nlpia | python | def onehot_encode(dataset, char_indices, maxlen):
' \n One hot encode the tokens\n \n Args:\n dataset list of lists of tokens\n char_indices dictionary of {key=character, value=index to use encoding vector}\n maxlen int Length of each sample\n Return:\n np array of shape ... |
def encode(iterator, method='xml', encoding=None, out=None):
'Encode serializer output into a string.\n \n :param iterator: the iterator returned from serializing a stream (basically\n any iterator that yields unicode objects)\n :param method: the serialization method; determines how ch... | 4,164,344,655,488,987,000 | Encode serializer output into a string.
:param iterator: the iterator returned from serializing a stream (basically
any iterator that yields unicode objects)
:param method: the serialization method; determines how characters not
representable in the specified encoding are treated
:param... | Packages/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/output.py | encode | 262877348/Data | python | def encode(iterator, method='xml', encoding=None, out=None):
'Encode serializer output into a string.\n \n :param iterator: the iterator returned from serializing a stream (basically\n any iterator that yields unicode objects)\n :param method: the serialization method; determines how ch... |
def get_serializer(method='xml', **kwargs):
'Return a serializer object for the given method.\n \n :param method: the serialization method; can be either "xml", "xhtml",\n "html", "text", or a custom serializer class\n\n Any additional keyword arguments are passed to the serializer, and t... | 1,971,087,575,448,008,400 | Return a serializer object for the given method.
:param method: the serialization method; can be either "xml", "xhtml",
"html", "text", or a custom serializer class
Any additional keyword arguments are passed to the serializer, and thus
depend on the `method` parameter value.
:see: `XMLSerializer`, `X... | Packages/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/output.py | get_serializer | 262877348/Data | python | def get_serializer(method='xml', **kwargs):
'Return a serializer object for the given method.\n \n :param method: the serialization method; can be either "xml", "xhtml",\n "html", "text", or a custom serializer class\n\n Any additional keyword arguments are passed to the serializer, and t... |
def _prepare_cache(use_cache=True):
'Prepare a private token serialization cache.\n\n :param use_cache: boolean indicating whether a real cache should\n be used or not. If not, the returned functions\n are no-ops.\n\n :return: emit and get functions, for storing and r... | 5,364,588,915,978,782,000 | Prepare a private token serialization cache.
:param use_cache: boolean indicating whether a real cache should
be used or not. If not, the returned functions
are no-ops.
:return: emit and get functions, for storing and retrieving
serialized values from the cache. | Packages/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/output.py | _prepare_cache | 262877348/Data | python | def _prepare_cache(use_cache=True):
'Prepare a private token serialization cache.\n\n :param use_cache: boolean indicating whether a real cache should\n be used or not. If not, the returned functions\n are no-ops.\n\n :return: emit and get functions, for storing and r... |
@classmethod
def get(cls, name):
'Return the ``(name, pubid, sysid)`` tuple of the ``DOCTYPE``\n declaration for the specified name.\n \n The following names are recognized in this version:\n * "html" or "html-strict" for the HTML 4.01 strict DTD\n * "html-transitional" for the ... | 2,591,025,277,008,289,000 | Return the ``(name, pubid, sysid)`` tuple of the ``DOCTYPE``
declaration for the specified name.
The following names are recognized in this version:
* "html" or "html-strict" for the HTML 4.01 strict DTD
* "html-transitional" for the HTML 4.01 transitional DTD
* "html-frameset" for the HTML 4.01 frameset DTD
* "ht... | Packages/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/output.py | get | 262877348/Data | python | @classmethod
def get(cls, name):
'Return the ``(name, pubid, sysid)`` tuple of the ``DOCTYPE``\n declaration for the specified name.\n \n The following names are recognized in this version:\n * "html" or "html-strict" for the HTML 4.01 strict DTD\n * "html-transitional" for the ... |
def __init__(self, doctype=None, strip_whitespace=True, namespace_prefixes=None, cache=True):
'Initialize the XML serializer.\n \n :param doctype: a ``(name, pubid, sysid)`` tuple that represents the\n DOCTYPE declaration that should be included at the top\n ... | -4,096,005,298,788,750,000 | Initialize the XML serializer.
:param doctype: a ``(name, pubid, sysid)`` tuple that represents the
DOCTYPE declaration that should be included at the top
of the generated output, or the name of a DOCTYPE as
defined in `DocType.get`
:param strip_whitespace: whether extra... | Packages/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/output.py | __init__ | 262877348/Data | python | def __init__(self, doctype=None, strip_whitespace=True, namespace_prefixes=None, cache=True):
'Initialize the XML serializer.\n \n :param doctype: a ``(name, pubid, sysid)`` tuple that represents the\n DOCTYPE declaration that should be included at the top\n ... |
def __init__(self, doctype=None, strip_whitespace=True, cache=True):
'Initialize the HTML serializer.\n \n :param doctype: a ``(name, pubid, sysid)`` tuple that represents the\n DOCTYPE declaration that should be included at the top\n of the generated outp... | 8,366,487,007,270,063,000 | Initialize the HTML serializer.
:param doctype: a ``(name, pubid, sysid)`` tuple that represents the
DOCTYPE declaration that should be included at the top
of the generated output
:param strip_whitespace: whether extraneous whitespace should be
stripped from the... | Packages/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/output.py | __init__ | 262877348/Data | python | def __init__(self, doctype=None, strip_whitespace=True, cache=True):
'Initialize the HTML serializer.\n \n :param doctype: a ``(name, pubid, sysid)`` tuple that represents the\n DOCTYPE declaration that should be included at the top\n of the generated outp... |
def __init__(self, strip_markup=False):
'Create the serializer.\n \n :param strip_markup: whether markup (tags and encoded characters) found\n in the text should be removed\n '
self.strip_markup = strip_markup | 4,920,285,809,569,111,000 | Create the serializer.
:param strip_markup: whether markup (tags and encoded characters) found
in the text should be removed | Packages/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/output.py | __init__ | 262877348/Data | python | def __init__(self, strip_markup=False):
'Create the serializer.\n \n :param strip_markup: whether markup (tags and encoded characters) found\n in the text should be removed\n '
self.strip_markup = strip_markup |
def __init__(self, preserve=None, noescape=None):
'Initialize the filter.\n \n :param preserve: a set or sequence of tag names for which white-space\n should be preserved\n :param noescape: a set or sequence of tag names for which text content\n s... | -8,983,873,959,590,232,000 | Initialize the filter.
:param preserve: a set or sequence of tag names for which white-space
should be preserved
:param noescape: a set or sequence of tag names for which text content
should not be escaped
The `noescape` set is expected to refer to elements that cannot contain
furthe... | Packages/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/output.py | __init__ | 262877348/Data | python | def __init__(self, preserve=None, noescape=None):
'Initialize the filter.\n \n :param preserve: a set or sequence of tag names for which white-space\n should be preserved\n :param noescape: a set or sequence of tag names for which text content\n s... |
def __init__(self, doctype):
'Initialize the filter.\n\n :param doctype: DOCTYPE as a string or DocType object.\n '
if isinstance(doctype, basestring):
doctype = DocType.get(doctype)
self.doctype_event = (DOCTYPE, doctype, (None, (- 1), (- 1))) | -3,173,367,274,843,465,000 | Initialize the filter.
:param doctype: DOCTYPE as a string or DocType object. | Packages/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/output.py | __init__ | 262877348/Data | python | def __init__(self, doctype):
'Initialize the filter.\n\n :param doctype: DOCTYPE as a string or DocType object.\n '
if isinstance(doctype, basestring):
doctype = DocType.get(doctype)
self.doctype_event = (DOCTYPE, doctype, (None, (- 1), (- 1))) |
def correlation_columns(dataset: pd.DataFrame, target_column: str, k: float=0.5):
'\n Columns that are correlated to the target point\n\n Parameters\n ----------\n\n dataset: pd.DataFrame\n The pandas dataframe\n \n target_column: str\n The target column to calculate correlation agai... | 1,533,437,794,607,541,500 | Columns that are correlated to the target point
Parameters
----------
dataset: pd.DataFrame
The pandas dataframe
target_column: str
The target column to calculate correlation against
k: float
The correlation cuttoff point; defaults to -0.5 and 0.5.
The values passed in represents the negative and po... | credit-card-fraud/src/features/build_features.py | correlation_columns | samie-hash/data-science-repo | python | def correlation_columns(dataset: pd.DataFrame, target_column: str, k: float=0.5):
'\n Columns that are correlated to the target point\n\n Parameters\n ----------\n\n dataset: pd.DataFrame\n The pandas dataframe\n \n target_column: str\n The target column to calculate correlation agai... |
def cummin(self: FrameLike, skipna: bool=True) -> FrameLike:
"\n Return cumulative minimum over a DataFrame or Series axis.\n\n Returns a DataFrame or Series of the same size containing the cumulative minimum.\n\n .. note:: the current implementation of cummin uses Spark's Window without\n ... | -2,685,636,878,631,528,400 | Return cumulative minimum over a DataFrame or Series axis.
Returns a DataFrame or Series of the same size containing the cumulative minimum.
.. note:: the current implementation of cummin uses Spark's Window without
specifying partition specification. This leads to move all data into
single partition in singl... | python/pyspark/pandas/generic.py | cummin | XpressAI/spark | python | def cummin(self: FrameLike, skipna: bool=True) -> FrameLike:
"\n Return cumulative minimum over a DataFrame or Series axis.\n\n Returns a DataFrame or Series of the same size containing the cumulative minimum.\n\n .. note:: the current implementation of cummin uses Spark's Window without\n ... |
def cummax(self: FrameLike, skipna: bool=True) -> FrameLike:
"\n Return cumulative maximum over a DataFrame or Series axis.\n\n Returns a DataFrame or Series of the same size containing the cumulative maximum.\n\n .. note:: the current implementation of cummax uses Spark's Window without\n ... | -3,348,748,663,714,688,000 | Return cumulative maximum over a DataFrame or Series axis.
Returns a DataFrame or Series of the same size containing the cumulative maximum.
.. note:: the current implementation of cummax uses Spark's Window without
specifying partition specification. This leads to move all data into
single partition in singl... | python/pyspark/pandas/generic.py | cummax | XpressAI/spark | python | def cummax(self: FrameLike, skipna: bool=True) -> FrameLike:
"\n Return cumulative maximum over a DataFrame or Series axis.\n\n Returns a DataFrame or Series of the same size containing the cumulative maximum.\n\n .. note:: the current implementation of cummax uses Spark's Window without\n ... |
def cumsum(self: FrameLike, skipna: bool=True) -> FrameLike:
"\n Return cumulative sum over a DataFrame or Series axis.\n\n Returns a DataFrame or Series of the same size containing the cumulative sum.\n\n .. note:: the current implementation of cumsum uses Spark's Window without\n s... | -8,141,575,604,497,648,000 | Return cumulative sum over a DataFrame or Series axis.
Returns a DataFrame or Series of the same size containing the cumulative sum.
.. note:: the current implementation of cumsum uses Spark's Window without
specifying partition specification. This leads to move all data into
single partition in single machin... | python/pyspark/pandas/generic.py | cumsum | XpressAI/spark | python | def cumsum(self: FrameLike, skipna: bool=True) -> FrameLike:
"\n Return cumulative sum over a DataFrame or Series axis.\n\n Returns a DataFrame or Series of the same size containing the cumulative sum.\n\n .. note:: the current implementation of cumsum uses Spark's Window without\n s... |
def cumprod(self: FrameLike, skipna: bool=True) -> FrameLike:
"\n Return cumulative product over a DataFrame or Series axis.\n\n Returns a DataFrame or Series of the same size containing the cumulative product.\n\n .. note:: the current implementation of cumprod uses Spark's Window without\n ... | 1,569,474,608,944,173,600 | Return cumulative product over a DataFrame or Series axis.
Returns a DataFrame or Series of the same size containing the cumulative product.
.. note:: the current implementation of cumprod uses Spark's Window without
specifying partition specification. This leads to move all data into
single partition in sing... | python/pyspark/pandas/generic.py | cumprod | XpressAI/spark | python | def cumprod(self: FrameLike, skipna: bool=True) -> FrameLike:
"\n Return cumulative product over a DataFrame or Series axis.\n\n Returns a DataFrame or Series of the same size containing the cumulative product.\n\n .. note:: the current implementation of cumprod uses Spark's Window without\n ... |
def get_dtype_counts(self) -> pd.Series:
"\n Return counts of unique dtypes in this object.\n\n .. deprecated:: 0.14.0\n\n Returns\n -------\n dtype : pd.Series\n Series with the count of columns with each dtype.\n\n See Also\n --------\n dtypes : R... | 9,206,764,287,967,669,000 | Return counts of unique dtypes in this object.
.. deprecated:: 0.14.0
Returns
-------
dtype : pd.Series
Series with the count of columns with each dtype.
See Also
--------
dtypes : Return the dtypes in this object.
Examples
--------
>>> a = [['a', 1, 1], ['b', 2, 2], ['c', 3, 3]]
>>> df = ps.DataFrame(a, column... | python/pyspark/pandas/generic.py | get_dtype_counts | XpressAI/spark | python | def get_dtype_counts(self) -> pd.Series:
"\n Return counts of unique dtypes in this object.\n\n .. deprecated:: 0.14.0\n\n Returns\n -------\n dtype : pd.Series\n Series with the count of columns with each dtype.\n\n See Also\n --------\n dtypes : R... |
def pipe(self, func: Callable[(..., Any)], *args: Any, **kwargs: Any) -> Any:
'\n Apply func(self, \\*args, \\*\\*kwargs).\n\n Parameters\n ----------\n func : function\n function to apply to the DataFrame.\n ``args``, and ``kwargs`` are passed into ``func``.\n ... | -5,945,533,546,538,242,000 | Apply func(self, \*args, \*\*kwargs).
Parameters
----------
func : function
function to apply to the DataFrame.
``args``, and ``kwargs`` are passed into ``func``.
Alternatively a ``(callable, data_keyword)`` tuple where
``data_keyword`` is a string indicating the keyword of
``callable`` that expect... | python/pyspark/pandas/generic.py | pipe | XpressAI/spark | python | def pipe(self, func: Callable[(..., Any)], *args: Any, **kwargs: Any) -> Any:
'\n Apply func(self, \\*args, \\*\\*kwargs).\n\n Parameters\n ----------\n func : function\n function to apply to the DataFrame.\n ``args``, and ``kwargs`` are passed into ``func``.\n ... |
def to_numpy(self) -> np.ndarray:
'\n A NumPy ndarray representing the values in this DataFrame or Series.\n\n .. note:: This method should only be used if the resulting NumPy ndarray is expected\n to be small, as all the data is loaded into the driver\'s memory.\n\n Returns\n ... | 3,172,926,021,327,149,600 | A NumPy ndarray representing the values in this DataFrame or Series.
.. note:: This method should only be used if the resulting NumPy ndarray is expected
to be small, as all the data is loaded into the driver's memory.
Returns
-------
numpy.ndarray
Examples
--------
>>> ps.DataFrame({"A": [1, 2], "B": [3, 4]}).t... | python/pyspark/pandas/generic.py | to_numpy | XpressAI/spark | python | def to_numpy(self) -> np.ndarray:
'\n A NumPy ndarray representing the values in this DataFrame or Series.\n\n .. note:: This method should only be used if the resulting NumPy ndarray is expected\n to be small, as all the data is loaded into the driver\'s memory.\n\n Returns\n ... |
@property
def values(self) -> np.ndarray:
"\n Return a Numpy representation of the DataFrame or the Series.\n\n .. warning:: We recommend using `DataFrame.to_numpy()` or `Series.to_numpy()` instead.\n\n .. note:: This method should only be used if the resulting NumPy ndarray is expected\n ... | -1,081,172,129,595,538,400 | Return a Numpy representation of the DataFrame or the Series.
.. warning:: We recommend using `DataFrame.to_numpy()` or `Series.to_numpy()` instead.
.. note:: This method should only be used if the resulting NumPy ndarray is expected
to be small, as all the data is loaded into the driver's memory.
Returns
------... | python/pyspark/pandas/generic.py | values | XpressAI/spark | python | @property
def values(self) -> np.ndarray:
"\n Return a Numpy representation of the DataFrame or the Series.\n\n .. warning:: We recommend using `DataFrame.to_numpy()` or `Series.to_numpy()` instead.\n\n .. note:: This method should only be used if the resulting NumPy ndarray is expected\n ... |
def to_csv(self, path: Optional[str]=None, sep: str=',', na_rep: str='', columns: Optional[List[Union[(Any, Tuple)]]]=None, header: bool=True, quotechar: str='"', date_format: Optional[str]=None, escapechar: Optional[str]=None, num_files: Optional[int]=None, mode: str='overwrite', partition_cols: Optional[Union[(str, L... | 4,511,092,456,395,762,000 | Write object to a comma-separated values (csv) file.
.. note:: pandas-on-Spark `to_csv` writes files to a path or URI. Unlike pandas',
pandas-on-Spark respects HDFS's property such as 'fs.default.name'.
.. note:: pandas-on-Spark writes CSV files into the directory, `path`, and writes
multiple `part-...` files... | python/pyspark/pandas/generic.py | to_csv | XpressAI/spark | python | def to_csv(self, path: Optional[str]=None, sep: str=',', na_rep: str=, columns: Optional[List[Union[(Any, Tuple)]]]=None, header: bool=True, quotechar: str='"', date_format: Optional[str]=None, escapechar: Optional[str]=None, num_files: Optional[int]=None, mode: str='overwrite', partition_cols: Optional[Union[(str, Lis... |
def to_json(self, path: Optional[str]=None, compression: str='uncompressed', num_files: Optional[int]=None, mode: str='overwrite', orient: str='records', lines: bool=True, partition_cols: Optional[Union[(str, List[str])]]=None, index_col: Optional[Union[(str, List[str])]]=None, **options: Any) -> Optional[str]:
'\n... | 4,444,707,189,741,475,000 | Convert the object to a JSON string.
.. note:: pandas-on-Spark `to_json` writes files to a path or URI. Unlike pandas',
pandas-on-Spark respects HDFS's property such as 'fs.default.name'.
.. note:: pandas-on-Spark writes JSON files into the directory, `path`, and writes
multiple `part-...` files in the direct... | python/pyspark/pandas/generic.py | to_json | XpressAI/spark | python | def to_json(self, path: Optional[str]=None, compression: str='uncompressed', num_files: Optional[int]=None, mode: str='overwrite', orient: str='records', lines: bool=True, partition_cols: Optional[Union[(str, List[str])]]=None, index_col: Optional[Union[(str, List[str])]]=None, **options: Any) -> Optional[str]:
'\n... |
def to_excel(self, excel_writer: Union[(str, pd.ExcelWriter)], sheet_name: str='Sheet1', na_rep: str='', float_format: Optional[str]=None, columns: Optional[Union[(str, List[str])]]=None, header: bool=True, index: bool=True, index_label: Optional[Union[(str, List[str])]]=None, startrow: int=0, startcol: int=0, engine: ... | 1,914,719,261,915,198,700 | Write object to an Excel sheet.
.. note:: This method should only be used if the resulting DataFrame is expected
to be small, as all the data is loaded into the driver's memory.
To write a single object to an Excel .xlsx file it is only necessary to
specify a target file name. To write to multiple sheets it... | python/pyspark/pandas/generic.py | to_excel | XpressAI/spark | python | def to_excel(self, excel_writer: Union[(str, pd.ExcelWriter)], sheet_name: str='Sheet1', na_rep: str=, float_format: Optional[str]=None, columns: Optional[Union[(str, List[str])]]=None, header: bool=True, index: bool=True, index_label: Optional[Union[(str, List[str])]]=None, startrow: int=0, startcol: int=0, engine: Op... |
def mean(self, axis: Optional[Axis]=None, numeric_only: bool=None) -> Union[(Scalar, 'Series')]:
"\n Return the mean of the values.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : bool, default Non... | -7,254,371,689,763,669,000 | Return the mean of the values.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
numeric_only : bool, default None
Include only float, int, boolean columns. False is not supported. This parameter
is mainly for pandas compatibility.
Returns
-------
mean : scalar ... | python/pyspark/pandas/generic.py | mean | XpressAI/spark | python | def mean(self, axis: Optional[Axis]=None, numeric_only: bool=None) -> Union[(Scalar, 'Series')]:
"\n Return the mean of the values.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : bool, default Non... |
def sum(self, axis: Optional[Axis]=None, numeric_only: bool=None, min_count: int=0) -> Union[(Scalar, 'Series')]:
"\n Return the sum of the values.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : b... | 4,394,613,206,444,410,000 | Return the sum of the values.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
numeric_only : bool, default None
Include only float, int, boolean columns. False is not supported. This parameter
is mainly for pandas compatibility.
min_count : int, default 0
T... | python/pyspark/pandas/generic.py | sum | XpressAI/spark | python | def sum(self, axis: Optional[Axis]=None, numeric_only: bool=None, min_count: int=0) -> Union[(Scalar, 'Series')]:
"\n Return the sum of the values.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : b... |
def product(self, axis: Optional[Axis]=None, numeric_only: bool=None, min_count: int=0) -> Union[(Scalar, 'Series')]:
'\n Return the product of the values.\n\n .. note:: unlike pandas\', pandas-on-Spark\'s emulates product by ``exp(sum(log(...)))``\n trick. Therefore, it only works for posi... | 4,500,819,481,037,292,500 | Return the product of the values.
.. note:: unlike pandas', pandas-on-Spark's emulates product by ``exp(sum(log(...)))``
trick. Therefore, it only works for positive numbers.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
numeric_only : bool, default None
Inc... | python/pyspark/pandas/generic.py | product | XpressAI/spark | python | def product(self, axis: Optional[Axis]=None, numeric_only: bool=None, min_count: int=0) -> Union[(Scalar, 'Series')]:
'\n Return the product of the values.\n\n .. note:: unlike pandas\', pandas-on-Spark\'s emulates product by ``exp(sum(log(...)))``\n trick. Therefore, it only works for posi... |
def skew(self, axis: Optional[Axis]=None, numeric_only: bool=None) -> Union[(Scalar, 'Series')]:
"\n Return unbiased skew normalized by N-1.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : bool, de... | 7,805,550,396,065,647,000 | Return unbiased skew normalized by N-1.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
numeric_only : bool, default None
Include only float, int, boolean columns. False is not supported. This parameter
is mainly for pandas compatibility.
Returns
-------
skew ... | python/pyspark/pandas/generic.py | skew | XpressAI/spark | python | def skew(self, axis: Optional[Axis]=None, numeric_only: bool=None) -> Union[(Scalar, 'Series')]:
"\n Return unbiased skew normalized by N-1.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : bool, de... |
def kurtosis(self, axis: Optional[Axis]=None, numeric_only: bool=None) -> Union[(Scalar, 'Series')]:
"\n Return unbiased kurtosis using Fisher’s definition of kurtosis (kurtosis of normal == 0.0).\n Normalized by N-1.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n... | -2,364,789,027,313,932,300 | Return unbiased kurtosis using Fisher’s definition of kurtosis (kurtosis of normal == 0.0).
Normalized by N-1.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
numeric_only : bool, default None
Include only float, int, boolean columns. False is not supported. This p... | python/pyspark/pandas/generic.py | kurtosis | XpressAI/spark | python | def kurtosis(self, axis: Optional[Axis]=None, numeric_only: bool=None) -> Union[(Scalar, 'Series')]:
"\n Return unbiased kurtosis using Fisher’s definition of kurtosis (kurtosis of normal == 0.0).\n Normalized by N-1.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n... |
def min(self, axis: Optional[Axis]=None, numeric_only: bool=None) -> Union[(Scalar, 'Series')]:
"\n Return the minimum of the values.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : bool, default N... | 398,092,958,807,587,700 | Return the minimum of the values.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
numeric_only : bool, default None
If True, include only float, int, boolean columns. This parameter is mainly for
pandas compatibility. False is supported; however, the columns sh... | python/pyspark/pandas/generic.py | min | XpressAI/spark | python | def min(self, axis: Optional[Axis]=None, numeric_only: bool=None) -> Union[(Scalar, 'Series')]:
"\n Return the minimum of the values.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : bool, default N... |
def max(self, axis: Optional[Axis]=None, numeric_only: bool=None) -> Union[(Scalar, 'Series')]:
"\n Return the maximum of the values.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : bool, default N... | -8,641,553,948,083,875,000 | Return the maximum of the values.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
numeric_only : bool, default None
If True, include only float, int, boolean columns. This parameter is mainly for
pandas compatibility. False is supported; however, the columns sh... | python/pyspark/pandas/generic.py | max | XpressAI/spark | python | def max(self, axis: Optional[Axis]=None, numeric_only: bool=None) -> Union[(Scalar, 'Series')]:
"\n Return the maximum of the values.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : bool, default N... |
def count(self, axis: Optional[Axis]=None, numeric_only: bool=False) -> Union[(Scalar, 'Series')]:
'\n Count non-NA cells for each column.\n\n The values `None`, `NaN` are considered NA.\n\n Parameters\n ----------\n axis : {0 or ‘index’, 1 or ‘columns’}, default 0\n If... | 7,315,654,646,070,643,000 | Count non-NA cells for each column.
The values `None`, `NaN` are considered NA.
Parameters
----------
axis : {0 or ‘index’, 1 or ‘columns’}, default 0
If 0 or ‘index’ counts are generated for each column. If 1 or ‘columns’ counts are
generated for each row.
numeric_only : bool, default False
If True, incl... | python/pyspark/pandas/generic.py | count | XpressAI/spark | python | def count(self, axis: Optional[Axis]=None, numeric_only: bool=False) -> Union[(Scalar, 'Series')]:
'\n Count non-NA cells for each column.\n\n The values `None`, `NaN` are considered NA.\n\n Parameters\n ----------\n axis : {0 or ‘index’, 1 or ‘columns’}, default 0\n If... |
def std(self, axis: Optional[Axis]=None, ddof: int=1, numeric_only: bool=None) -> Union[(Scalar, 'Series')]:
"\n Return sample standard deviation.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n ddof : int, defau... | 8,972,190,425,281,151,000 | Return sample standard deviation.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
numeric_only : bool, default None
Incl... | python/pyspark/pandas/generic.py | std | XpressAI/spark | python | def std(self, axis: Optional[Axis]=None, ddof: int=1, numeric_only: bool=None) -> Union[(Scalar, 'Series')]:
"\n Return sample standard deviation.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n ddof : int, defau... |
def var(self, axis: Optional[Axis]=None, ddof: int=1, numeric_only: bool=None) -> Union[(Scalar, 'Series')]:
"\n Return unbiased variance.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n ddof : int, default 1\n ... | -3,360,667,890,068,724,000 | Return unbiased variance.
Parameters
----------
axis : {index (0), columns (1)}
Axis for the function to be applied on.
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
numeric_only : bool, default None
Include only... | python/pyspark/pandas/generic.py | var | XpressAI/spark | python | def var(self, axis: Optional[Axis]=None, ddof: int=1, numeric_only: bool=None) -> Union[(Scalar, 'Series')]:
"\n Return unbiased variance.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n ddof : int, default 1\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.