uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
3b2cf29774e839fce64e7ae6
train
class
class ModifyAssistantCidrResponse(AbstractModel): """ModifyAssistantCidr返回参数结构体 """ def __init__(self): """ :param AssistantCidrSet: 辅助CIDR数组。 注意:此字段可能返回 null,表示取不到有效值。 :type AssistantCidrSet: list of AssistantCidr :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId...
class ModifyAssistantCidrResponse(AbstractModel):
"""ModifyAssistantCidr返回参数结构体 """ def __init__(self): """ :param AssistantCidrSet: 辅助CIDR数组。 注意:此字段可能返回 null,表示取不到有效值。 :type AssistantCidrSet: list of AssistantCidr :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ ...
Blocks = None def _deserialize(self, params): self.VpcId = params.get("VpcId") self.NewCidrBlocks = params.get("NewCidrBlocks") self.OldCidrBlocks = params.get("OldCidrBlocks") class ModifyAssistantCidrResponse(AbstractModel):
64
64
207
9
55
dyllllll/tencentcloud-sdk-python
tencentcloud/vpc/v20170312/models.py
Python
ModifyAssistantCidrResponse
ModifyAssistantCidrResponse
10,657
10,681
10,657
10,657
07e0efdab83dd062d6bcba395d5103ce8ab249f4
bigcode/the-stack
train
efea3e7944efa2c414f771fe
train
class
class ReplaceSecurityGroupPolicyRequest(AbstractModel): """ReplaceSecurityGroupPolicy请求参数结构体 """ def __init__(self): """ :param SecurityGroupId: 安全组实例ID,例如sg-33ocnj9n,可通过DescribeSecurityGroups获取。 :type SecurityGroupId: str :param SecurityGroupPolicySet: 安全组规则集合对象。 :...
class ReplaceSecurityGroupPolicyRequest(AbstractModel):
"""ReplaceSecurityGroupPolicy请求参数结构体 """ def __init__(self): """ :param SecurityGroupId: 安全组实例ID,例如sg-33ocnj9n,可通过DescribeSecurityGroups获取。 :type SecurityGroupId: str :param SecurityGroupPolicySet: 安全组规则集合对象。 :type SecurityGroupPolicySet: :class:`tencentcloud.vpc.v2...
返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None def _deserialize(self, params): self.RequestId = params.get("RequestId") class ReplaceSecurityGroupPolicyRequest...
90
90
300
9
81
dyllllll/tencentcloud-sdk-python
tencentcloud/vpc/v20170312/models.py
Python
ReplaceSecurityGroupPolicyRequest
ReplaceSecurityGroupPolicyRequest
13,126
13,152
13,126
13,126
88bacc9e26fba64e044821cc89fa979da85df27b
bigcode/the-stack
train
69befdba0fd1557f88b6e9d9
train
class
class SetCcnRegionBandwidthLimitsRequest(AbstractModel): """SetCcnRegionBandwidthLimits请求参数结构体 """ def __init__(self): """ :param CcnId: CCN实例ID。形如:ccn-f49l6u0z。 :type CcnId: str :param CcnRegionBandwidthLimits: 云联网(CCN)各地域出带宽上限。 :type CcnRegionBandwidthLimits: list...
class SetCcnRegionBandwidthLimitsRequest(AbstractModel):
"""SetCcnRegionBandwidthLimits请求参数结构体 """ def __init__(self): """ :param CcnId: CCN实例ID。形如:ccn-f49l6u0z。 :type CcnId: str :param CcnRegionBandwidthLimits: 云联网(CCN)各地域出带宽上限。 :type CcnRegionBandwidthLimits: list of CcnRegionBandwidthLimit """ self.CcnI...
Id: str """ self.ServiceId = None self.ServiceGroupId = None def _deserialize(self, params): self.ServiceId = params.get("ServiceId") self.ServiceGroupId = params.get("ServiceGroupId") class SetCcnRegionBandwidthLimitsRequest(AbstractModel):
64
64
212
11
53
dyllllll/tencentcloud-sdk-python
tencentcloud/vpc/v20170312/models.py
Python
SetCcnRegionBandwidthLimitsRequest
SetCcnRegionBandwidthLimitsRequest
14,098
14,121
14,098
14,098
b24937196d7a42b9547118213b9a5317be05c164
bigcode/the-stack
train
cb661a70fdb90aee256cf831
train
class
class UnassignPrivateIpAddressesRequest(AbstractModel): """UnassignPrivateIpAddresses请求参数结构体 """ def __init__(self): """ :param NetworkInterfaceId: 弹性网卡实例ID,例如:eni-m6dyj72l。 :type NetworkInterfaceId: str :param PrivateIpAddresses: 指定的内网IP信息,单次最多指定10个。 :type PrivateI...
class UnassignPrivateIpAddressesRequest(AbstractModel):
"""UnassignPrivateIpAddresses请求参数结构体 """ def __init__(self): """ :param NetworkInterfaceId: 弹性网卡实例ID,例如:eni-m6dyj72l。 :type NetworkInterfaceId: str :param PrivateIpAddresses: 指定的内网IP信息,单次最多指定10个。 :type PrivateIpAddresses: list of PrivateIpAddressSpecification ...
,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None def _deserialize(self, params): self.RequestId = params.get("RequestId") class UnassignPrivateIpAddressesRequest(AbstractModel):
64
64
194
10
54
dyllllll/tencentcloud-sdk-python
tencentcloud/vpc/v20170312/models.py
Python
UnassignPrivateIpAddressesRequest
UnassignPrivateIpAddressesRequest
14,458
14,481
14,458
14,458
d89f72bee7691d68cd02da020908be086ba1d1ad
bigcode/the-stack
train
f8fe851ebf41cf81a7d3df83
train
class
class VpnGatewayQuota(AbstractModel): """VPN网关配额对象 """ def __init__(self): """ :param Bandwidth: 带宽配额 :type Bandwidth: int :param Cname: 配额中文名称 :type Cname: str :param Name: 配额英文名称 :type Name: str """ self.Bandwidth = None sel...
class VpnGatewayQuota(AbstractModel):
"""VPN网关配额对象 """ def __init__(self): """ :param Bandwidth: 带宽配额 :type Bandwidth: int :param Cname: 配额中文名称 :type Cname: str :param Name: 配额英文名称 :type Name: str """ self.Bandwidth = None self.Cname = None self.Name = Non...
item in params.get("VpnGatewayQuotaSet"): obj = VpnGatewayQuota() obj._deserialize(item) self.VpnGatewayQuotaSet.append(obj) self.Version = params.get("Version") self.NetworkInstanceId = params.get("NetworkInstanceId") class VpnGatewayQuota(AbstractModel)...
64
64
146
8
56
dyllllll/tencentcloud-sdk-python
tencentcloud/vpc/v20170312/models.py
Python
VpnGatewayQuota
VpnGatewayQuota
14,828
14,850
14,828
14,828
fdbf7f508b22c8daaaffb995e1b8df74a878f365
bigcode/the-stack
train
de75e6c35ce5d31384da02ff
train
class
class CreateNatGatewayResponse(AbstractModel): """CreateNatGateway返回参数结构体 """ def __init__(self): """ :param NatGatewaySet: NAT网关对象数组。 :type NatGatewaySet: list of NatGateway :param TotalCount: 符合条件的 NAT网关对象数量。 :type TotalCount: int :param RequestId: 唯一请求 ID...
class CreateNatGatewayResponse(AbstractModel):
"""CreateNatGateway返回参数结构体 """ def __init__(self): """ :param NatGatewaySet: NAT网关对象数组。 :type NatGatewaySet: list of NatGateway :param TotalCount: 符合条件的 NAT网关对象数量。 :type TotalCount: int :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :ty...
params.get("Zone") if params.get("Tags") is not None: self.Tags = [] for item in params.get("Tags"): obj = Tag() obj._deserialize(item) self.Tags.append(obj) self.SubnetId = params.get("SubnetId") class CreateNatGatewayResponse(Abs...
67
67
225
8
59
dyllllll/tencentcloud-sdk-python
tencentcloud/vpc/v20170312/models.py
Python
CreateNatGatewayResponse
CreateNatGatewayResponse
2,824
2,851
2,824
2,824
980d1fa599975ac333576f7e33ed16ff6608bfde
bigcode/the-stack
train
e18793a67f1b36b3feb0e7c3
train
class
class DescribeBandwidthPackagesRequest(AbstractModel): """DescribeBandwidthPackages请求参数结构体 """ def __init__(self): """ :param BandwidthPackageIds: 带宽包唯一ID列表 :type BandwidthPackageIds: list of str :param Filters: 每次请求的`Filters`的上限为10。参数不支持同时指定`BandwidthPackageIds`和`Filters`。...
class DescribeBandwidthPackagesRequest(AbstractModel):
"""DescribeBandwidthPackages请求参数结构体 """ def __init__(self): """ :param BandwidthPackageIds: 带宽包唯一ID列表 :type BandwidthPackageIds: list of str :param Filters: 每次请求的`Filters`的上限为10。参数不支持同时指定`BandwidthPackageIds`和`Filters`。详细的过滤条件如下: <li> bandwidth-package_id - String - 是否必填:否 ...
详细信息列表。 :type ResourceSet: list of Resource :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.TotalCount = None self.ResourceSet = None self.RequestId = None def _deserialize(self, params): self.TotalCount = p...
158
158
528
8
150
dyllllll/tencentcloud-sdk-python
tencentcloud/vpc/v20170312/models.py
Python
DescribeBandwidthPackagesRequest
DescribeBandwidthPackagesRequest
5,408
5,446
5,408
5,408
6f4b415da19a3b7fd9c964c92e768d7557bfd7a1
bigcode/the-stack
train
54b7ee9418935f5906e9e10b
train
class
class DescribeNatGatewayDestinationIpPortTranslationNatRulesRequest(AbstractModel): """DescribeNatGatewayDestinationIpPortTranslationNatRules请求参数结构体 """ def __init__(self): """ :param NatGatewayIds: NAT网关ID。 :type NatGatewayIds: list of str :param Filters: 过滤条件: 参数不支持同时指定Na...
class DescribeNatGatewayDestinationIpPortTranslationNatRulesRequest(AbstractModel):
"""DescribeNatGatewayDestinationIpPortTranslationNatRules请求参数结构体 """ def __init__(self): """ :param NatGatewayIds: NAT网关ID。 :type NatGatewayIds: list of str :param Filters: 过滤条件: 参数不支持同时指定NatGatewayIds和Filters。 <li> nat-gateway-id,NAT网关的ID,如`nat-0yi4hekt`</li> <li> vpc-id,私...
""" self.AddressInfo = None self.Total = None self.RequestId = None def _deserialize(self, params): if params.get("AddressInfo") is not None: self.AddressInfo = [] for item in params.get("AddressInfo"): obj = IpGeolocationInfo() ...
114
114
382
14
100
dyllllll/tencentcloud-sdk-python
tencentcloud/vpc/v20170312/models.py
Python
DescribeNatGatewayDestinationIpPortTranslationNatRulesRequest
DescribeNatGatewayDestinationIpPortTranslationNatRulesRequest
6,848
6,887
6,848
6,848
bb312afb4645cd7bf2252be469ce06610c8deb7c
bigcode/the-stack
train
caf8529f3fbe076718b15cc8
train
class
class DescribeAddressTemplateGroupsRequest(AbstractModel): """DescribeAddressTemplateGroups请求参数结构体 """ def __init__(self): """ :param Filters: 过滤条件。 <li>address-template-group-name - String - (过滤条件)IP地址模板集合名称。</li> <li>address-template-group-id - String - (过滤条件)IP地址模板实集合例ID,例如:ipmg-mdunqeb...
class DescribeAddressTemplateGroupsRequest(AbstractModel):
"""DescribeAddressTemplateGroups请求参数结构体 """ def __init__(self): """ :param Filters: 过滤条件。 <li>address-template-group-name - String - (过滤条件)IP地址模板集合名称。</li> <li>address-template-group-id - String - (过滤条件)IP地址模板实集合例ID,例如:ipmg-mdunqeb6。</li> :type Filters: list of Filter :para...
params): if params.get("QuotaSet") is not None: self.QuotaSet = [] for item in params.get("QuotaSet"): obj = Quota() obj._deserialize(item) self.QuotaSet.append(obj) self.RequestId = params.get("RequestId") class DescribeAddressTem...
71
71
237
9
62
dyllllll/tencentcloud-sdk-python
tencentcloud/vpc/v20170312/models.py
Python
DescribeAddressTemplateGroupsRequest
DescribeAddressTemplateGroupsRequest
5,005
5,034
5,005
5,005
1a16495c5f3db6bf24ea326519421023595e6a2e
bigcode/the-stack
train
3c7e453fe28fb16a03280903
train
class
class DisableRoutesResponse(AbstractModel): """DisableRoutes返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None def _deserialize(self, params): self.RequestId =...
class DisableRoutesResponse(AbstractModel):
"""DisableRoutes返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None def _deserialize(self, params): self.RequestId = params.get("RequestId")
Ids = None self.RouteItemIds = None def _deserialize(self, params): self.RouteTableId = params.get("RouteTableId") self.RouteIds = params.get("RouteIds") self.RouteItemIds = params.get("RouteItemIds") class DisableRoutesResponse(AbstractModel):
64
64
92
7
57
dyllllll/tencentcloud-sdk-python
tencentcloud/vpc/v20170312/models.py
Python
DisableRoutesResponse
DisableRoutesResponse
8,911
8,925
8,911
8,911
a720b2cddfcc4f9d77c115271d38c69c300dbf17
bigcode/the-stack
train
625514b609890574b854e4cc
train
class
class User(AbstractUser): # First Name and Last Name Do Not Cover Name Patterns # Around the Globe. name = models.CharField( _("Name of User"), blank=True, max_length=255 ) bio = models.TextField("Bio", blank=True) def get_absolute_url(self): return reverse( "users:...
class User(AbstractUser): # First Name and Last Name Do Not Cover Name Patterns # Around the Globe.
name = models.CharField( _("Name of User"), blank=True, max_length=255 ) bio = models.TextField("Bio", blank=True) def get_absolute_url(self): return reverse( "users:detail", kwargs={"username": self.username} )
from django.contrib.auth.models import AbstractUser from django.db import models from django.urls import reverse from django.utils.translation import gettext_lazy as _ class User(AbstractUser): # First Name and Last Name Do Not Cover Name Patterns # Around the Globe.
54
64
85
24
30
tonper19/awod_everycheese
everycheese/everycheese/users/models.py
Python
User
User
7
19
7
10
3be8302d615a11f3fce8c8deeeca9d17c0bd8871
bigcode/the-stack
train
b2cb49b38970ba79237e7761
train
function
@app.route('/') def v_index(): if request.cookies != None: rsp=make_response(redirect('/newbies')) rsp.set_cookie('user','tongkun') return rsp else: #如果是新用户,如何处理? # rsp=make_response(redirect('/')) # rsp.set_cookie('user','tongkun') # user=request.cookies['user'] return 'user is news ,you are ?!'
@app.route('/') def v_index():
if request.cookies != None: rsp=make_response(redirect('/newbies')) rsp.set_cookie('user','tongkun') return rsp else: #如果是新用户,如何处理? # rsp=make_response(redirect('/')) # rsp.set_cookie('user','tongkun') # user=request.cookies['user'] return 'user is news ,you are ?!'
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask,redirect,request,make_response app=Flask(__name__) @app.route('/') def v_index():
39
64
99
7
32
louiskun/flaskGIT
redirecttk1.py
Python
v_index
v_index
6
17
6
7
94cedef91a22a6af5d6964dcdb2af0b14dfea41d
bigcode/the-stack
train
00e74451f442debe442cd802
train
function
@app.route('/newbies') def v_newbies(): user=request.cookies['user'] return 'this page is for newbies only!you are %s' % user
@app.route('/newbies') def v_newbies():
user=request.cookies['user'] return 'this page is for newbies only!you are %s' % user
是新用户,如何处理? # rsp=make_response(redirect('/')) # rsp.set_cookie('user','tongkun') # user=request.cookies['user'] return 'user is news ,you are ?!' @app.route('/newbies') def v_newbies():
63
64
34
11
52
louiskun/flaskGIT
redirecttk1.py
Python
v_newbies
v_newbies
19
22
19
20
ac709311f43341c875304feb5cba722298b0e2f8
bigcode/the-stack
train
ae5399fce17365b862087b4e
train
class
class SerialController: def __init__(self) -> None: """コンストラクタ""" logging.info("init") self.interval: typing.Optional[SetInterval] = None self.serial: typing.Optional[Serial] = None self.ports: list[str] = [] self.startTime: typing.Optional[int] = None self.i...
class SerialController:
def __init__(self) -> None: """コンストラクタ""" logging.info("init") self.interval: typing.Optional[SetInterval] = None self.serial: typing.Optional[Serial] = None self.ports: list[str] = [] self.startTime: typing.Optional[int] = None self.isConnected = False ...
import logging import math import typing import PySimpleGUI as sg import numpy as np import pandas as pd import scipy.stats import serial import serial.tools.list_ports from serial import Serial, SerialException from src.model.Model import Model from src.util import Global from src.util.SetInterval import SetInterval...
73
256
1,600
4
68
gekkyo/dendai_ict
src/controller/SerialController.py
Python
SerialController
SerialController
18
237
18
18
2e4900ebf90f1031fff0264139cc021cefcc543d
bigcode/the-stack
train
a98c7f7bcf0bfd798d17a5f3
train
class
class HerokuConfig(ProductionConfig): SSL_DISABLE = bool(os.environ.get('SSL_DISABLE')) @classmethod def init_app(cls, app): ProductionConfig.init_app(app) # handle proxy server headers from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) ...
class HerokuConfig(ProductionConfig):
SSL_DISABLE = bool(os.environ.get('SSL_DISABLE')) @classmethod def init_app(cls, app): ProductionConfig.init_app(app) # handle proxy server headers from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) # log to stderr import log...
_SENDER, toaddrs=[cls.FLASKY_ADMIN], subject=cls.FLASKY_MAIL_SUBJECT_PREFIX + ' Application Error', credentials=credentials, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) class HerokuConfig(ProductionConfig):
64
64
110
8
56
techkang/c_project
config.py
Python
HerokuConfig
HerokuConfig
72
88
72
72
3a2d67bfe85a80d0e9568e6eda1c5e38585deb12
bigcode/the-stack
train
be7437780052e6532b178a7a
train
class
class ProductionConfig(Config): SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'data.sqlite') @classmethod def init_app(cls, app): Config.init_app(app) # email errors to the administrators import logging from loggi...
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'data.sqlite') @classmethod def init_app(cls, app): Config.init_app(app) # email errors to the administrators import logging from logging.handlers import SMTPHandler ...
os.path.join(basedir, 'data-dev.sqlite') class TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'data-test.sqlite') class ProductionConfig(Config):
64
65
218
5
59
techkang/c_project
config.py
Python
ProductionConfig
ProductionConfig
44
69
44
44
4598b1125eb83238870409c706f89fe9e3ede859
bigcode/the-stack
train
e9d814ddd274c9d7deccff43
train
class
class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')
class DevelopmentConfig(Config):
DEBUG = True SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')
ASKY_FOLLOWERS_PER_PAGE = 50 FLASKY_COMMENTS_PER_PAGE = 30 FLASKY_SLOW_DB_QUERY_TIME=0.5 WTF_CSRF_ENABLED = False @staticmethod def init_app(app): pass class DevelopmentConfig(Config):
64
64
46
5
58
techkang/c_project
config.py
Python
DevelopmentConfig
DevelopmentConfig
31
34
31
31
25c1724da1d246ae19d8cde2c4e9bbabaaa8aa42
bigcode/the-stack
train
be9e3f2044ded2d762d83cba
train
class
class TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'data-test.sqlite')
class TestingConfig(Config):
TESTING = True SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'data-test.sqlite')
@staticmethod def init_app(app): pass class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite') class TestingConfig(Config):
64
64
47
5
59
techkang/c_project
config.py
Python
TestingConfig
TestingConfig
37
40
37
37
d6ffa7cdb8f12630f25a4e8f6f6dff34e5aee011
bigcode/the-stack
train
6417eb98cb0948d29f109f39
train
class
class UnixConfig(ProductionConfig): @classmethod def init_app(cls, app): ProductionConfig.init_app(app) # log to syslog import logging from logging.handlers import SysLogHandler syslog_handler = SysLogHandler() syslog_handler.setLevel(logging.WARNING) app...
class UnixConfig(ProductionConfig): @classmethod
def init_app(cls, app): ProductionConfig.init_app(app) # log to syslog import logging from logging.handlers import SysLogHandler syslog_handler = SysLogHandler() syslog_handler.setLevel(logging.WARNING) app.logger.addHandler(syslog_handler)
app.wsgi_app = ProxyFix(app.wsgi_app) # log to stderr import logging from logging import StreamHandler file_handler = StreamHandler() file_handler.setLevel(logging.WARNING) app.logger.addHandler(file_handler) class UnixConfig(ProductionConfig): @classmethod
64
64
73
11
53
techkang/c_project
config.py
Python
UnixConfig
UnixConfig
91
101
91
92
784fcba92e3ecffb6f41d2966b8b5f7b7fc97b13
bigcode/the-stack
train
f8dd10c2c2ad271a21f319ec
train
class
class Config: SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string' SSL_DISABLE = False SQLALCHEMY_COMMIT_ON_TEARDOWN = True SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_RECORD_QUERIES = True MAIL_SERVER = 'smtp.sina.cn' MAIL_PORT = 587 MAIL_USE_TLS = True MAIL_USE...
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string' SSL_DISABLE = False SQLALCHEMY_COMMIT_ON_TEARDOWN = True SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_RECORD_QUERIES = True MAIL_SERVER = 'smtp.sina.cn' MAIL_PORT = 587 MAIL_USE_TLS = True MAIL_USERNAME = os.env...
# -*- coding:utf-8 -*- import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config:
25
69
230
3
22
techkang/c_project
config.py
Python
Config
Config
6
28
6
6
1cb2d0f4bc525883295619b3a2a1ff418fed7599
bigcode/the-stack
train
8370fd90d3b2263774e09a9f
train
class
class ImageList(object): """ Structure that holds a list of images (of possibly varying sizes) as a single tensor. This works by padding the images to the same size, and storing in a field the original sizes of each image Attributes: image_sizes (list[tuple[int, int]]): each tuple is (h...
class ImageList(object):
""" Structure that holds a list of images (of possibly varying sizes) as a single tensor. This works by padding the images to the same size, and storing in a field the original sizes of each image Attributes: image_sizes (list[tuple[int, int]]): each tuple is (h, w) """ def __i...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. from __future__ import division from typing import Any, List, Sequence, Tuple, Union import torch from torch.nn import functional as F class ImageList(object):
53
256
923
5
47
miranthajayatilake/detectron2
detectron2/structures/image_list.py
Python
ImageList
ImageList
8
96
8
8
547e59b53b12cc2cb7257146f19fbe0543f51ae5
bigcode/the-stack
train
4395f0406de929a9f84d6a11
train
function
def parse_df(df): total_time = df['client_start_time_dt'].max() - df['client_start_time_dt'].min() # Number of minutes to ignore in the beginning ignore_mins = total_time.total_seconds() / 60 / 4 # print(f"Ignoring {ignore_mins:4.2f} minutes") ss_df = df.loc[df['client_start_time_dt'] > (df['client...
def parse_df(df):
total_time = df['client_start_time_dt'].max() - df['client_start_time_dt'].min() # Number of minutes to ignore in the beginning ignore_mins = total_time.total_seconds() / 60 / 4 # print(f"Ignoring {ignore_mins:4.2f} minutes") ss_df = df.loc[df['client_start_time_dt'] > (df['client_start_time_dt'].m...
for epoch_col in epoch_millis_cols_list: df[epoch_col] = df[epoch_col] / 1000 df['client_elapsed_time'] = df['client_elapsed_time'] * 1000 epoch_cols_list = ['client_start_time', 'client_end_time', 'end_time', 'start_time'] for epoch_col in epoch_cols_list: times = df[epoch_col].apply(lam...
129
129
432
5
123
pacslab/serverless-performance-modeling
pacsltk/pacsltk/exp_parser.py
Python
parse_df
parse_df
32
63
32
32
e5526cca899d811017eca2efd7bcc3b4120ddcd8
bigcode/the-stack
train
b022730d348ee19764f07c47
train
function
def parse_instance_info(df, idle_mins_before_kill): import pandas as pd u_instances = df['inst_id'].unique() all_instance_info = [] for instance_id in (u_instances): sub_df = df[df['inst_id'] == instance_id].copy() instance_start = sub_df['client_start_time'].min() instance_start...
def parse_instance_info(df, idle_mins_before_kill):
import pandas as pd u_instances = df['inst_id'].unique() all_instance_info = [] for instance_id in (u_instances): sub_df = df[df['inst_id'] == instance_id].copy() instance_start = sub_df['client_start_time'].min() instance_start_dt = sub_df['client_start_time_dt'].min() i...
['client_elapsed_time'].mean() cold_prob = df['is_cold'].mean() ss_cold_prob = ss_df['is_cold'].mean() list_of_vars = ['df', 'ss_df', 'total_time', 'ignore_mins', 'total_invocations', 'mean_reqs_per_min', 'mean_reqs_per_sec', 'mean_resp_time_client', 'mean_resp_time_aws', 'cold_count...
142
142
474
13
129
pacslab/serverless-performance-modeling
pacsltk/pacsltk/exp_parser.py
Python
parse_instance_info
parse_instance_info
65
99
65
65
35c8ac2df266d01759a02a148ddb6bbda799e7b8
bigcode/the-stack
train
9802288f0cac00cd9ceca5b9
train
function
def parse_counting_info(df, ss_df, df_inst, step_seconds): import pandas as pd time_idx = pd.date_range(start=ss_df['client_start_time_dt'].min(), end=ss_df['client_start_time_dt'].max(), freq='{}S'.format(step_seconds)) df_counts = pd.DataFrame(data = {'count': 0}, index=time_idx) def func_instance_co...
def parse_counting_info(df, ss_df, df_inst, step_seconds):
import pandas as pd time_idx = pd.date_range(start=ss_df['client_start_time_dt'].min(), end=ss_df['client_start_time_dt'].max(), freq='{}S'.format(step_seconds)) df_counts = pd.DataFrame(data = {'count': 0}, index=time_idx) def func_instance_count(x): val = ((df_inst.loc[:,'instance_start_dt'] ...
', 'running_time_mins', 'idle_time_mins', 'idle_time_mins_ext'] all_instance_info.append(get_local_vars_as_dict(list_of_vars, locals())) df_inst = pd.DataFrame(data=all_instance_info) instance_end_times = list(df_inst['instance_end'].values) # add the is_las...
158
158
529
16
142
pacslab/serverless-performance-modeling
pacsltk/pacsltk/exp_parser.py
Python
parse_counting_info
parse_counting_info
102
149
102
102
981fdb17af8544b7f4188b5119e004c428c3fd0c
bigcode/the-stack
train
2a9a1962570ae6b9b71fe8a7
train
function
def preprocess_df(df): import pandas as pd epoch_millis_cols_list = ['end_time', 'start_time'] for epoch_col in epoch_millis_cols_list: df[epoch_col] = df[epoch_col] / 1000 df['client_elapsed_time'] = df['client_elapsed_time'] * 1000 epoch_cols_list = ['client_start_time', 'client_end_time...
def preprocess_df(df):
import pandas as pd epoch_millis_cols_list = ['end_time', 'start_time'] for epoch_col in epoch_millis_cols_list: df[epoch_col] = df[epoch_col] / 1000 df['client_elapsed_time'] = df['client_elapsed_time'] * 1000 epoch_cols_list = ['client_start_time', 'client_end_time', 'end_time', 'start_t...
np from datetime import datetime from datetime import timedelta # Import util functions from pacsltk.pacs_util import * def read_csv_file(csv_file): import pandas as pd return pd.read_csv(csv_file, index_col=0, parse_dates=True).dropna() def preprocess_df(df):
64
64
151
5
59
pacslab/serverless-performance-modeling
pacsltk/pacsltk/exp_parser.py
Python
preprocess_df
preprocess_df
15
29
15
15
ea90c676aefa0640eee2a9cd539c59c43a6c3082
bigcode/the-stack
train
7edab3e463603e25530b7693
train
function
def read_csv_file(csv_file): import pandas as pd return pd.read_csv(csv_file, index_col=0, parse_dates=True).dropna()
def read_csv_file(csv_file):
import pandas as pd return pd.read_csv(csv_file, index_col=0, parse_dates=True).dropna()
import os import numpy as np from datetime import datetime from datetime import timedelta # Import util functions from pacsltk.pacs_util import * def read_csv_file(csv_file):
39
64
33
7
32
pacslab/serverless-performance-modeling
pacsltk/pacsltk/exp_parser.py
Python
read_csv_file
read_csv_file
11
13
11
11
5352a6614d29e95d891cbfab1d30af66e0cbe771
bigcode/the-stack
train
510dba182bb7e0979d9f3cc4
train
class
class DataopsMatrixManipulation(test.OntaskTestCase): table_name = 'TEST_TABLE' pk = '999' csv1 = """key,text1,text2,double1,double2,bool1,bool2,date1,date2 1.0,"d1_t1_1",,111.0,,True,,1/1/18 01:00:00, 2.0,"d2_t1_2",,112.0,,False,,1/1/18 02:00:00, 3.0,"",d1_t2_3,...
class DataopsMatrixManipulation(test.OntaskTestCase):
table_name = 'TEST_TABLE' pk = '999' csv1 = """key,text1,text2,double1,double2,bool1,bool2,date1,date2 1.0,"d1_t1_1",,111.0,,True,,1/1/18 01:00:00, 2.0,"d2_t1_2",,112.0,,False,,1/1/18 02:00:00, 3.0,"",d1_t2_3,,123.0,,False,,1/2/18 03:00:00 4.0,,d1_t2...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import StringIO import numpy as np import test from dataops import pandas_db from dataops.ops import perform_dataframe_upload_merge class DataopsMatrixManipulation(test.OntaskTestCase):
61
256
979
13
47
Lukahm/ontask
src/dataops/tests/test_logic.py
Python
DataopsMatrixManipulation
DataopsMatrixManipulation
13
103
13
14
37c5ac31d12b8ce2c57cbf0640f96bea21da71ec
bigcode/the-stack
train
1e1568d0a5918ef6bdbd3757
train
class
class FaucetExperimentalAPI(object): """An experimental API for communicating with Faucet. Contains methods for interacting with a running Faucet controller from within a RyuApp. This app should be run together with Faucet in the same ryu-manager process. """ def __init__(self, *args, **kwargs...
class FaucetExperimentalAPI(object):
"""An experimental API for communicating with Faucet. Contains methods for interacting with a running Faucet controller from within a RyuApp. This app should be run together with Faucet in the same ryu-manager process. """ def __init__(self, *args, **kwargs): self.faucet = None de...
Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distribu...
121
121
404
6
115
tousix/faucet
faucet/faucet_experimental_api.py
Python
FaucetExperimentalAPI
FaucetExperimentalAPI
25
80
25
25
0cb3206917815563c7f8d553272a78642dfad1dd
bigcode/the-stack
train
e5381f5b3a71186e070e4bf5
train
class
class Ui_login(object): def setupUi(self, login): if not login.objectName(): login.setObjectName(u"login") login.resize(550, 375) login.setMaximumSize(QSize(550, 375)) self.gridLayout = QGridLayout(login) self.gridLayout.setSpacing(0) self.gridLayout.setOb...
class Ui_login(object):
def setupUi(self, login): if not login.objectName(): login.setObjectName(u"login") login.resize(550, 375) login.setMaximumSize(QSize(550, 375)) self.gridLayout = QGridLayout(login) self.gridLayout.setSpacing(0) self.gridLayout.setObjectName(u"gridLayout") ...
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'login.ui' ## ## Created by: Qt User Interface Compiler version 6.1.1 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! #####################...
106
256
915
5
100
ShibinChristin/FS-mini-project
ui/login.py
Python
Ui_login
Ui_login
16
90
16
16
0ce38bae58859c1a625d35a880f78761f5bf9a35
bigcode/the-stack
train
8c5d06da8c58ec2d53ec42ee
train
function
def lookup(name): for qtype in 'A','AAA','CNAME','MX','NS': answer = dns.resolver.query(name, qtype,raise_on_no_answer = False) if answer.rrset is not None: print(answer.rrset)
def lookup(name):
for qtype in 'A','AAA','CNAME','MX','NS': answer = dns.resolver.query(name, qtype,raise_on_no_answer = False) if answer.rrset is not None: print(answer.rrset)
import argparse,dns.resolver def lookup(name):
11
64
57
4
6
mass9/Python
Network/(4) Socket Names and DNS/dns_basic.py
Python
lookup
lookup
3
7
3
3
e451ccbb081188883267985dd4f73769545b60ff
bigcode/the-stack
train
3fdc586aa3ed838f52244b07
train
function
def TreponemaBryantii( directed: bool = False, preprocess: bool = True, load_nodes: bool = True, verbose: int = 2, cache: bool = True, cache_path: str = "graphs/string", version: str = "links.v11.5", **additional_graph_kwargs: Dict ) -> Graph: """Return new instance of the Treponema ...
def TreponemaBryantii( directed: bool = False, preprocess: bool = True, load_nodes: bool = True, verbose: int = 2, cache: bool = True, cache_path: str = "graphs/string", version: str = "links.v11.5", **additional_graph_kwargs: Dict ) -> Graph:
"""Return new instance of the Treponema bryantii graph. The graph is automatically retrieved from the STRING repository. Parameters ------------------- directed: bool = False Wether to load the graph as directed or undirected. By default false. preprocess: bool = True ...
and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others}, journal={Nucleic acids research}, volume={47}, number={D1}, pages={D607--D613}, year={2019}, publisher={Oxford University Press} } ``` """ from typing import Dict from ..automatic_graph_retrieval impor...
186
186
623
79
106
AnacletoLAB/ensmallen_graph
bindings/python/ensmallen/datasets/string/treponemabryantii.py
Python
TreponemaBryantii
TreponemaBryantii
30
107
30
39
d022bd959bbf82cc53035c224a4b76b89acf6c36
bigcode/the-stack
train
7d1999ffc6e0bc7722bdb8ef
train
class
class i18nBot(object): """I18n bot.""" def __init__(self, script, *args, **kwargs): """Constructor.""" modules = script.split('.') self.scriptname = modules[0] self.script = __import__('scripts.' + self.scriptname) for m in modules: self.script = getattr(sel...
class i18nBot(object):
"""I18n bot.""" def __init__(self, script, *args, **kwargs): """Constructor.""" modules = script.split('.') self.scriptname = modules[0] self.script = __import__('scripts.' + self.scriptname) for m in modules: self.script = getattr(self.script, m) sel...
This may be mixed with preleading positonal argumens: >>> bot = i18nBot('<scriptname>', '<msg dict1>', the_other_msg='<msg dict2>') If you have the messages as instance constants you may call the bot as follows: >>> bot = i18nBot('<scriptname>.<class instance>', '<msg dict1>', '<msg dict2>') It's also possible to ma...
229
229
766
7
221
Annie201/pywikibot-core
scripts/maintenance/make_i18n_dict.py
Python
i18nBot
i18nBot
46
135
46
47
cc3f46fa980a4f19d6729269b9b8e92654ce462f
bigcode/the-stack
train
ce5f369fb0f90cd21ad5a6e6
train
function
def create_app(): from apps.controller import note_module app.register_blueprint(note_module) set_up_swagger(app) return app
def create_app():
from apps.controller import note_module app.register_blueprint(note_module) set_up_swagger(app) return app
import SQLAlchemy from flask_cors import CORS, cross_origin from swagger_init import set_up_swagger app = Flask(__name__) CORS(app) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///my_note_space.sqlite3' db = SQLAlchemy(app) def create_app():
64
64
31
4
60
kc495/frameworks_and_languages_module
server_Implementation/note_app/factory.py
Python
create_app
create_app
14
19
14
15
c43062f5bb743144d7a7187b5adee26d8590cab0
bigcode/the-stack
train
f6384b3797f695adb98540b2
train
class
class TestEnergyPointRule(unittest.TestCase): pass
class TestEnergyPointRule(unittest.TestCase):
pass
# -*- coding: utf-8 -*- # Copyright (c) 2022, Diksha Ahire and Contributors # See license.txt from __future__ import unicode_literals # import frappe import unittest class TestEnergyPointRule(unittest.TestCase):
53
64
11
9
43
DeeMysterio/Social-Wall
social_wall/social_wall/doctype/energy_point_rule/test_energy_point_rule.py
Python
TestEnergyPointRule
TestEnergyPointRule
9
10
9
9
d6e63348e925f84437fbb9065652825c6c504ba6
bigcode/the-stack
train
35880957d5cca2fe5c79a81b
train
function
def cosine_dic_parts(dic1,dic2): numerator = 0 dena = 0 for key1,val1 in dic1.items(): numerator += val1*dic2.get(key1,0.0) dena += val1*val1 denb = 0 for val2 in dic2.values(): denb += val2*val2 return numerator, dena, denb
def cosine_dic_parts(dic1,dic2):
numerator = 0 dena = 0 for key1,val1 in dic1.items(): numerator += val1*dic2.get(key1,0.0) dena += val1*val1 denb = 0 for val2 in dic2.values(): denb += val2*val2 return numerator, dena, denb
.sqrt((dena1+dena2)*(denb1+denb2)) if numerator1 != 0 or numerator2 != 0 else 0.0 #cosine distance measure #https://en.wikipedia.org/wiki/Cosine_similarity def cosine_dic_parts(dic1,dic2):
64
64
96
10
53
aigents/pygents
pygents/cluster.py
Python
cosine_dic_parts
cosine_dic_parts
55
64
55
55
7dfba77989b38c849c3e40066a15740fb030aa59
bigcode/the-stack
train
0477e7fa6f136d7bfd358096
train
function
def overlap_dic2(dica1,dicb1,dica2,dicb2): numerator1, dena1, denb1 = overlap_dic_parts(dica1,dicb1) numerator2, dena2, denb2 = overlap_dic_parts(dica2,dicb2) return (numerator1+numerator2)/math.sqrt((dena1+dena2)*(denb1+denb2)) if numerator1 != 0 or numerator2 != 0 else 0.0
def overlap_dic2(dica1,dicb1,dica2,dicb2):
numerator1, dena1, denb1 = overlap_dic_parts(dica1,dicb1) numerator2, dena2, denb2 = overlap_dic_parts(dica2,dicb2) return (numerator1+numerator2)/math.sqrt((dena1+dena2)*(denb1+denb2)) if numerator1 != 0 or numerator2 != 0 else 0.0
.012884201800751829" assert str(overlap_dic(x1,x6)) == "0.018077538151554683" assert str(overlap_dic(x1,x7)) == "0.0" def overlap_dic2(dica1,dicb1,dica2,dicb2):
64
64
113
19
45
aigents/pygents
pygents/cluster.py
Python
overlap_dic2
overlap_dic2
47
50
47
47
6c65bf1e1f7c0e853439c1df7b4d48054fd59760
bigcode/the-stack
train
90d3198f466c25bc1d4399e3
train
function
def do_cluster_threshold(model,dic4tree=None,simfunc2=cosine_dic2,thresholds=[0.95,0.9,0.85,0.8,0.75,0.7,0.65,0.6,0.55,0.5,0.45,0.4],debug = False): copy = model_to_dict(model) if debug: print('start count',len(copy)) for threshold in thresholds: if debug: print('threshold',thres...
def do_cluster_threshold(model,dic4tree=None,simfunc2=cosine_dic2,thresholds=[0.95,0.9,0.85,0.8,0.75,0.7,0.65,0.6,0.55,0.5,0.45,0.4],debug = False):
copy = model_to_dict(model) if debug: print('start count',len(copy)) for threshold in thresholds: if debug: print('threshold',threshold) while True: simlst = compute_similiarities_from_dict(copy,simfunc2=simfunc2) simlst.sort(key=lambda tup: tup[2]...
]][0]), dict_merge(copy[top[0]][1],copy[top[1]][1]) ) del copy[top[0]] del copy[top[1]] n += 1 if debug: print(len(copy)) def do_cluster_threshold(model,dic4tree=None,simfunc2=cosine_dic2,thresholds=[0.95,0.9,0.85,0.8,0.75,0.7,0.65,0.6,0.55,0.5,0.45,0.4],debug = False):
124
124
414
75
49
aigents/pygents
pygents/cluster.py
Python
do_cluster_threshold
do_cluster_threshold
186
221
186
186
0f500431603155c3c68713339f738e899c829103
bigcode/the-stack
train
771c953b2c157867ec6e46f0
train
function
def overlap_dic(dic1,dic2): numerator, dena, denb = overlap_dic_parts(dic1,dic2) return numerator/math.sqrt(dena*denb) if numerator != 0 else 0.0
def overlap_dic(dic1,dic2):
numerator, dena, denb = overlap_dic_parts(dic1,dic2) return numerator/math.sqrt(dena*denb) if numerator != 0 else 0.0
1,dic2.get(key1,0.0)) dena += max(val1,val1) denb = 0 for val2 in dic2.values(): denb += val2 return numerator, dena, denb def overlap_dic(dic1,dic2):
64
64
50
9
54
aigents/pygents
pygents/cluster.py
Python
overlap_dic
overlap_dic
27
29
27
27
a4486e0b3d41d3bc8bc42c92cf0962630cacfadd
bigcode/the-stack
train
ab68ee5210d8bbef56004c8f
train
function
def compute_similiarities_from_dict(dic,simfunc2=cosine_dic2,debug=False): lst = [] done = set() for a in dic: a1 = dic[a][0] a2 = dic[a][1] for b in dic: if a != b and not (b,a) in done: b1 = dic[b][0] b2 = dic[b][1...
def compute_similiarities_from_dict(dic,simfunc2=cosine_dic2,debug=False):
lst = [] done = set() for a in dic: a1 = dic[a][0] a2 = dic[a][1] for b in dic: if a != b and not (b,a) in done: b1 = dic[b][0] b2 = dic[b][1] s = simfunc2(a1,b1,a2,b2) done.ad...
2,b2) done.add((a,b)) lst.append( (a,b,s) if a <= b else (b,a,s) ) if debug: print(a) return lst def compute_similiarities_from_dict(dic,simfunc2=cosine_dic2,debug=False):
64
64
146
21
42
aigents/pygents
pygents/cluster.py
Python
compute_similiarities_from_dict
compute_similiarities_from_dict
122
137
122
122
9b45f12fcdd2ae5406a40fdb12f2e227dc3d3552
bigcode/the-stack
train
e367e14b073e222adaaa366d
train
function
def model_to_dict(model,arity=1,debug=False): copy = {} for a in model[0]: if len(a) == arity: copy[a] = (model[1][a] if a in model[1] else {}, model[2][a] if a in model[2] else {}) return copy
def model_to_dict(model,arity=1,debug=False):
copy = {} for a in model[0]: if len(a) == arity: copy[a] = (model[1][a] if a in model[1] else {}, model[2][a] if a in model[2] else {}) return copy
simfunc2(a1,b1,a2,b2) done.add((a,b)) lst.append( (a,b,s) if a <= b else (b,a,s) ) if debug: print(a) return lst def model_to_dict(model,arity=1,debug=False):
64
64
74
13
50
aigents/pygents
pygents/cluster.py
Python
model_to_dict
model_to_dict
139
144
139
139
b1b179f66bb0ae3ec395c0fa584498f97adf5b81
bigcode/the-stack
train
7823998f66e3962108adf2be
train
function
def do_cluster(model,dic4tree=None,simfunc2=cosine_dic2,debug = False): copy = model_to_dict(model) if debug: print(len(copy)) n = 0 while True: simlst = compute_similiarities_from_dict(copy,simfunc2=simfunc2) simlst.sort(key=lambda tup: tup[2], reverse=False) # sort to end so we...
def do_cluster(model,dic4tree=None,simfunc2=cosine_dic2,debug = False):
copy = model_to_dict(model) if debug: print(len(copy)) n = 0 while True: simlst = compute_similiarities_from_dict(copy,simfunc2=simfunc2) simlst.sort(key=lambda tup: tup[2], reverse=False) # sort to end so we can be removing from the end length = len(simlst) if le...
0.2, 'b': 0.2, 'c': 0.2}" def join_letters(a,b): return "".join(sorted(list(a)+list(b))) assert str(join_letters("1.2","zba")) == ".12abz" def do_cluster(model,dic4tree=None,simfunc2=cosine_dic2,debug = False):
80
81
272
23
57
aigents/pygents
pygents/cluster.py
Python
do_cluster
do_cluster
160
183
160
160
2caa07a7adfe52a377d2979dd375f7e6baae0c66
bigcode/the-stack
train
b37876586d9b45c0974b3d6d
train
function
def compute_similiarities(model,arity=1,simfunc2=cosine_dic2,debug=False): lst = [] done = set() for a in model[0]: if len(a) == arity: a1 = model[1][a] a2 = model[2][a] for b in model[0]: if a != b and len(b) == arity and not (b,a) in done: ...
def compute_similiarities(model,arity=1,simfunc2=cosine_dic2,debug=False):
lst = [] done = set() for a in model[0]: if len(a) == arity: a1 = model[1][a] a2 = model[2][a] for b in model[0]: if a != b and len(b) == arity and not (b,a) in done: b1 = model[1][b] b2 = model[2][b] ...
osine_dic2(x0,x1,x0,x1)) == "1.0" assert str(cosine_dic2(x1,x7,x1,x7)) == "0.0" def compute_similiarities(model,arity=1,simfunc2=cosine_dic2,debug=False):
64
64
172
23
41
aigents/pygents
pygents/cluster.py
Python
compute_similiarities
compute_similiarities
103
119
103
103
fa09278ea1b0a9853cbdd562c25dbf0595e1f744
bigcode/the-stack
train
9437da697d88a9e56b5ec1a1
train
function
def overlap_dic_parts(dic1,dic2): numerator = 0 dena = 0 for key1,val1 in dic1.items(): numerator += min(val1,dic2.get(key1,0.0)) dena += max(val1,val1) denb = 0 for val2 in dic2.values(): denb += val2 return numerator, dena, denb
def overlap_dic_parts(dic1,dic2):
numerator = 0 dena = 0 for key1,val1 in dic1.items(): numerator += min(val1,dic2.get(key1,0.0)) dena += max(val1,val1) denb = 0 for val2 in dic2.values(): denb += val2 return numerator, dena, denb
.com/aigents/aigents-java/blob/master/src/main/java/net/webstructor/data/Miner.java#L157 #public double crossOverlap(Linker that, Linker other) #overlap measure #https://en.wikipedia.org/wiki/Jaccard_index def overlap_dic_parts(dic1,dic2):
64
64
94
10
53
aigents/pygents
pygents/cluster.py
Python
overlap_dic_parts
overlap_dic_parts
16
25
16
16
e8ddc6db9b1f415a3e3c65c3e0249c4e5560d971
bigcode/the-stack
train
dbdb47268d4904d4c1f8df88
train
function
def invert_model(model,maxn=2): index = {} forward = {} backward = {} for ngram in model[1]: if len(ngram) <= maxn: model1ngram = model[1][ngram] for e in model1ngram: dictcount(index,e) countcount(backward,e,ngram,model1ngram[e]) for ...
def invert_model(model,maxn=2):
index = {} forward = {} backward = {} for ngram in model[1]: if len(ngram) <= maxn: model1ngram = model[1][ngram] for e in model1ngram: dictcount(index,e) countcount(backward,e,ngram,model1ngram[e]) for ngram in model[2]: if le...
]] del copy[top[1]] merged_set.add(top[0]) merged_set.add(top[1]) merged_count += 1 if merged_count == 0: break if debug: print('end count',len(copy)) def invert_model(model,maxn=2):
64
64
171
9
55
aigents/pygents
pygents/cluster.py
Python
invert_model
invert_model
224
241
224
224
581963d1eece6f0c14da4b1bf73bc813a75c1b52
bigcode/the-stack
train
9dcc07e43d65045f19b5b451
train
function
def dict_merge(a,b): c = dcp(a) for key in b: if key in c: c[key] = c[key] + b[key] else: c[key] = b[key] return c
def dict_merge(a,b):
c = dcp(a) for key in b: if key in c: c[key] = c[key] + b[key] else: c[key] = b[key] return c
{} for a in model[0]: if len(a) == arity: copy[a] = (model[1][a] if a in model[1] else {}, model[2][a] if a in model[2] else {}) return copy def dict_merge(a,b):
64
64
52
6
57
aigents/pygents
pygents/cluster.py
Python
dict_merge
dict_merge
146
153
146
146
5e20221d16f851f3a324ef0012429ac243fcc228
bigcode/the-stack
train
defc6ab83536a2125b03ac6c
train
function
def cosine_dic2(dica1,dicb1,dica2,dicb2): numerator1, dena1, denb1 = cosine_dic_parts(dica1,dicb1) numerator2, dena2, denb2 = cosine_dic_parts(dica2,dicb2) return (numerator1+numerator2)/math.sqrt((dena1+dena2)*(denb1+denb2)) if numerator1 != 0 or numerator2 != 0 else 0.0
def cosine_dic2(dica1,dicb1,dica2,dicb2):
numerator1, dena1, denb1 = cosine_dic_parts(dica1,dicb1) numerator2, dena2, denb2 = cosine_dic_parts(dica2,dicb2) return (numerator1+numerator2)/math.sqrt((dena1+dena2)*(denb1+denb2)) if numerator1 != 0 or numerator2 != 0 else 0.0
" assert str(cosine_dic(x1,x7)) == "0.0" # computes cosine distance based on 2 dicts corresponding to # two vectors in complementary two segments of bi-segment vector space def cosine_dic2(dica1,dicb1,dica2,dicb2):
64
64
113
19
44
aigents/pygents
pygents/cluster.py
Python
cosine_dic2
cosine_dic2
88
91
88
88
c6ab95c8c2415d1d7c7db8df62881d0208009965
bigcode/the-stack
train
788398203934502bcb3c6956
train
function
def cosine_dic(dic1,dic2): numerator, dena, denb = cosine_dic_parts(dic1,dic2) return numerator/math.sqrt(dena*denb) if numerator != 0 else 0.0
def cosine_dic(dic1,dic2):
numerator, dena, denb = cosine_dic_parts(dic1,dic2) return numerator/math.sqrt(dena*denb) if numerator != 0 else 0.0
2.get(key1,0.0) dena += val1*val1 denb = 0 for val2 in dic2.values(): denb += val2*val2 return numerator, dena, denb def cosine_dic(dic1,dic2):
64
64
50
9
54
aigents/pygents
pygents/cluster.py
Python
cosine_dic
cosine_dic
66
68
66
66
306a700b4a6bd94e36c5e601c4baf3df66b53b13
bigcode/the-stack
train
5df946b7a238d684de90c7df
train
function
def join_letters(a,b): return "".join(sorted(list(a)+list(b)))
def join_letters(a,b):
return "".join(sorted(list(a)+list(b)))
assert str(dict_merge({'a':0.2,'b':0.1},{'c':0.2,'b':0.1})) == "{'a': 0.2, 'b': 0.2, 'c': 0.2}" def join_letters(a,b):
62
64
17
6
56
aigents/pygents
pygents/cluster.py
Python
join_letters
join_letters
156
157
156
156
315c54bd6aeaa77c932fdd152bb27753190ffe77
bigcode/the-stack
train
547858df846068fe1f3dd64b
train
function
def run_scorer(gold_tsv, system_tsv): """Run the scorer. Args: gold_tsv: Gold annotations to score against. system_tsv: System output to score. Returns: A string, the scorecard. """ gold_annotations = read_annotations(gold_tsv, is_gold=True) assert gold_annotations, 'No gold annotations read!'...
def run_scorer(gold_tsv, system_tsv):
"""Run the scorer. Args: gold_tsv: Gold annotations to score against. system_tsv: System output to score. Returns: A string, the scorecard. """ gold_annotations = read_annotations(gold_tsv, is_gold=True) assert gold_annotations, 'No gold annotations read!' system_annotations = read_annotati...
f}'.format( bias_terms[Gender.FEMININE] / bias_terms[Gender.MASCULINE]) scorecard.append('Bias (F/M): {}\n'.format(bias)) return '\n'.join(scorecard) def run_scorer(gold_tsv, system_tsv):
64
64
129
14
50
vid-koci/gap-coreference
gap_scorer.py
Python
run_scorer
run_scorer
227
244
227
227
82b7347923b3436e72adb9b69d2a1e8740a9e753
bigcode/the-stack
train
d0cd8026f2f4a3792e15a6fd
train
function
def read_annotations(filename, is_gold): """Reads coreference annotations for the examples in the given file. Args: filename: Path to .tsv file to read. is_gold: Whether or not we are reading the gold annotations. Returns: A dict mapping example ID strings to their Annotation representation. If ...
def read_annotations(filename, is_gold):
"""Reads coreference annotations for the examples in the given file. Args: filename: Path to .tsv file to read. is_gold: Whether or not we are reading the gold annotations. Returns: A dict mapping example ID strings to their Annotation representation. If reading gold, 'Pronoun' field is used to ...
.0 * numerator / denominator if denominator else 0.0 def f1(self): """Calculates F1 based on the observed scores. Returns: float, the F1 score. """ recall = self.recall() precision = self.precision() numerator = 2 * precision * recall denominator = precision + recall return nu...
97
97
326
8
88
vid-koci/gap-coreference
gap_scorer.py
Python
read_annotations
read_annotations
102
145
102
102
354a10561c7f89f57faee81f7975f71cc62360ec
bigcode/the-stack
train
57c899bdc14d6cc2c780eb00
train
function
def make_scorecard(scores): """Returns a human-readable scorecard of the given scores. Args: scores: dict from gender to its Scores object. None is used to denote no specific gender, i.e. overall scores. Returns: A string, the scorecard. """ scorecard = [] display_names = [(None, 'Overall')...
def make_scorecard(scores):
"""Returns a human-readable scorecard of the given scores. Args: scores: dict from gender to its Scores object. None is used to denote no specific gender, i.e. overall scores. Returns: A string, the scorecard. """ scorecard = [] display_names = [(None, 'Overall'), (Gender.MASCULINE, 'Mascul...
', example_id) scores[gender].false_negatives += 1 elif gold and system: scores[gender].true_positives += 1 elif not gold and system: scores[gender].false_positives += 1 elif not gold and not system: scores[gender].true_negatives += 1 elif gold and...
104
104
348
6
97
vid-koci/gap-coreference
gap_scorer.py
Python
make_scorecard
make_scorecard
188
224
188
188
48b3679801a65449bd38f9ecb8f008ee95890c70
bigcode/the-stack
train
96401a8cbe9981cc1d83cf3f
train
class
class Scores(object): """Container class for storing scores, and generating evaluation metrics. Attributes: true_positives: Tally of true positives seen. false_positives: Tally of false positives seen. true_negatives: Tally of true negatives seen. false_negatives: Tally of false negatives seen. "...
class Scores(object):
"""Container class for storing scores, and generating evaluation metrics. Attributes: true_positives: Tally of true positives seen. false_positives: Tally of false positives seen. true_negatives: Tally of true negatives seen. false_negatives: Tally of false negatives seen. """ def __init__(sel...
for this example. None indicates that no annotation was found for the given example. name_b_coref(None): bool reflecting whether Name B was recorded as coreferential with the target pronoun for this example. None indicates that no annotation was found for the given example. """ def __init__(...
98
98
329
4
93
vid-koci/gap-coreference
gap_scorer.py
Python
Scores
Scores
52
99
52
52
15a05ccdac3a0abe9a56654eed2b2ad03cf708e6
bigcode/the-stack
train
d4fd7140317dc072b2ceb139
train
function
def calculate_scores(gold_annotations, system_annotations): """Score the system annotations against gold. Args: gold_annotations: dict from example ID to its gold Annotation. system_annotations: dict from example ID to its system Annotation. Returns: A dict from gender to a Scores object for that ge...
def calculate_scores(gold_annotations, system_annotations):
"""Score the system annotations against gold. Args: gold_annotations: dict from example ID to its gold Annotation. system_annotations: dict from example ID to its system Annotation. Returns: A dict from gender to a Scores object for that gender. None is used to denote no specific gender, i.e. ...
[example_id].name_a_coref = is_true(row['A-coref']) annotations[example_id].name_b_coref = is_true(row['B-coref']) if is_gold: gender = PRONOUNS.get(row['Pronoun'].lower(), Gender.UNKNOWN) assert gender != Gender.UNKNOWN, row annotations[example_id].gender = gender return annotatio...
92
92
308
10
81
vid-koci/gap-coreference
gap_scorer.py
Python
calculate_scores
calculate_scores
148
185
148
148
9eb050591974802becbfa6d1a87455718464b532
bigcode/the-stack
train
359fc3b9bf5f7776a7aae79f
train
class
class Annotation(object): """Container class for storing annotations of an example. Attributes: gender(None): The gender of the annotation. None indicates that gender was not determined for the given example. name_a_coref(None): bool reflecting whether Name A was recorded as coreferential with ...
class Annotation(object):
"""Container class for storing annotations of an example. Attributes: gender(None): The gender of the annotation. None indicates that gender was not determined for the given example. name_a_coref(None): bool reflecting whether Name A was recorded as coreferential with the target pronoun for thi...
the GAP challenge. """ from __future__ import division from __future__ import print_function import argparse from collections import defaultdict import csv from constants import Gender from constants import GOLD_FIELDNAMES from constants import PRONOUNS from constants import SYSTEM_FIELDNAMES class Annotation(object...
64
64
161
4
59
vid-koci/gap-coreference
gap_scorer.py
Python
Annotation
Annotation
32
49
32
32
b2119e4c169a7b40b3784271b0014d05f1d6d589
bigcode/the-stack
train
d321abec346b918cf353b81b
train
function
def main(args): """Score system output against gold and display the scorecard. Args: args: argparse namespace containing gold_tsv and system_tsv. """ scorecard = run_scorer(args.gold_tsv, args.system_tsv) print(scorecard)
def main(args):
"""Score system output against gold and display the scorecard. Args: args: argparse namespace containing gold_tsv and system_tsv. """ scorecard = run_scorer(args.gold_tsv, args.system_tsv) print(scorecard)
_gold=True) assert gold_annotations, 'No gold annotations read!' system_annotations = read_annotations(system_tsv, is_gold=False) assert system_annotations, 'No system annotations read!' scores = calculate_scores(gold_annotations, system_annotations) return make_scorecard(scores) def main(args):
64
64
59
4
60
vid-koci/gap-coreference
gap_scorer.py
Python
main
main
247
254
247
247
9c5fe7a4d3dcd11f1b49f74bec44fb77a2acd44e
bigcode/the-stack
train
cc3639987db7559976a9ca91
train
class
class Text(proto.Message): r"""A widget that displays textual content. Attributes: content (str): The text content to be displayed. format_ (google.monitoring.dashboard_v1.types.Text.Format): How the text content is formatted. """ class Format(proto.Enum): ...
class Text(proto.Message):
r"""A widget that displays textual content. Attributes: content (str): The text content to be displayed. format_ (google.monitoring.dashboard_v1.types.Text.Format): How the text content is formatted. """ class Format(proto.Enum): r"""The format type of th...
either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import proto # type: ignore __protobuf__ = proto.module( package='google.monitoring.dashboard.v1', manifest={ 'Text', }, ) class Text(proto.Message):
64
64
135
5
59
googleapis/googleapis-gen
google/monitoring/dashboard/v1/monitoring-dashboard-v1-py/google/monitoring/dashboard_v1/types/text.py
Python
Text
Text
27
50
27
27
19ef01003577e6881f90c21e4aeaee6cbd26f310
bigcode/the-stack
train
3659dae33258ef7dd362e234
train
function
def rename_columns(data_summary: dict, columns: list, new_names: list) -> dict: ''' Function will return the data_summary dict with the names of the columns in the dataframe changed ''' df: pd.DataFrame = data_summary['Dataset'].copy() for x, i in enumerate(columns): df.rename(columns={...
def rename_columns(data_summary: dict, columns: list, new_names: list) -> dict:
''' Function will return the data_summary dict with the names of the columns in the dataframe changed ''' df: pd.DataFrame = data_summary['Dataset'].copy() for x, i in enumerate(columns): df.rename(columns={i: new_names[x]}, inplace=True) data_summary['Dataset'] = df return da...
''' Function will return the dataset with all inf and nan values removed. ''' df: pd.DataFrame = data_summary['Dataset'].copy() df = clean_data(df, []) return df def rename_columns(data_summary: dict, columns: list, new_names: list) -> dict:
64
64
94
20
43
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
rename_columns
rename_columns
535
546
535
535
4ceb1c9abed41935e701fb63ec3349f43199d87f
bigcode/the-stack
train
3f0babab4ab78cb085a19d15
train
function
def rename_values_in_column(data_summary: dict, replace: list) -> pd.DataFrame: ''' Function will return a dataframe with the names of the columns changed replace: [('column', {'old_name': 'new_name', ...}), ...] ''' length: int = len(replace) df: pd.DataFrame = data_summary['Dataset']...
def rename_values_in_column(data_summary: dict, replace: list) -> pd.DataFrame:
''' Function will return a dataframe with the names of the columns changed replace: [('column', {'old_name': 'new_name', ...}), ...] ''' length: int = len(replace) df: pd.DataFrame = data_summary['Dataset'].copy() for i in range(length): df[replace[i][0]].replace(replace[i]...
= data_summary['Dataset'].copy() for x, i in enumerate(columns): df.rename(columns={i: new_names[x]}, inplace=True) data_summary['Dataset'] = df return data_summary def rename_values_in_column(data_summary: dict, replace: list) -> pd.DataFrame:
64
64
107
19
44
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
rename_values_in_column
rename_values_in_column
550
563
550
550
4fd790bd4b35f7234a67a0525e4d8548034585a2
bigcode/the-stack
train
c7b859dc3c09b921b8b509d0
train
function
@delegates(Learner.__init__) def residual_tabular_learner(dls, layers=None, emb_szs=None, config=None, n_out=None, y_range=None, cardinality=None, ps=None, **kwargs): "Get a `Learner` using `dls`, with `metrics`, including a `TabularModel` created using the remaining params." if config is None: config = tabular...
@delegates(Learner.__init__) def residual_tabular_learner(dls, layers=None, emb_szs=None, config=None, n_out=None, y_range=None, cardinality=None, ps=None, **kwargs):
"Get a `Learner` using `dls`, with `metrics`, including a `TabularModel` created using the remaining params." if config is None: config = tabular_config() if layers is None: layers = [200,100] to = dls.train_ds emb_szs = get_emb_sz(dls.train_ds, {} if emb_szs is None else emb_szs) if n_out is No...
x = torch.cat([x, x_cont], 1) if self.n_emb != 0 else x_cont return self.layers(x) @delegates(Learner.__init__) def residual_tabular_learner(dls, layers=None, emb_szs=None, config=None, n_out=None, y_range=None, cardinality=None, ps=None, **kwargs):
79
79
264
48
31
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
residual_tabular_learner
residual_tabular_learner
1,018
1,029
1,018
1,019
a56ffba44e737e69f16f06fa3c55b125d2cf0c04
bigcode/the-stack
train
ef17e57f418f1e9a1481b17f
train
function
def features_with_bad_values(df: pd.DataFrame, datasetName: str) -> pd.DataFrame: ''' Function will scan the dataframe for features with Inf, NaN, or Zero values. Returns a new dataframe describing the distribution of these values in the original dataframe ''' # Inf and NaN values can take ...
def features_with_bad_values(df: pd.DataFrame, datasetName: str) -> pd.DataFrame:
''' Function will scan the dataframe for features with Inf, NaN, or Zero values. Returns a new dataframe describing the distribution of these values in the original dataframe ''' # Inf and NaN values can take different forms so we screen for every one of them invalid_values: list = [ np...
tTo Dataset Cache: {pickleDump}\n') # check if data already exists within cache if os.path.exists(pickleDump): df = pd.read_pickle(pickleDump) # if not, load data and clean it before caching it else: df = pd.read_csv(filePath, low_memory=True) df.to_pickle(pickleDump) ...
105
105
353
21
83
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
features_with_bad_values
features_with_bad_values
166
203
166
166
6bbe8394f73a01d562b3f63fc1b4334e46ba4c96
bigcode/the-stack
train
e6d4a8eac4046cc43e37256b
train
function
def transform_and_split_data(df: pd.DataFrame, target_label: str, split=0, name='', categorical : list = ['Protocol'], scale:bool = False, leave_out: list = []) -> Model_data: ''' Transform and split the data into a train and test set returns the 10-tuple with the following indicies: results...
def transform_and_split_data(df: pd.DataFrame, target_label: str, split=0, name='', categorical : list = ['Protocol'], scale:bool = False, leave_out: list = []) -> Model_data:
''' Transform and split the data into a train and test set returns the 10-tuple with the following indicies: results: tuple = (name, model, classes, X_train, y_train, X_test, y_test, to, dls, model_type) ''' # First we split the features into the dependent variable and # contin...
_type_ attribute to our model so yellowbrick knows how to make the visualizations if len(classes) == 2: model.target_type_ = 'binary' elif len(classes) > 2: model.target_type_ = 'multiclass' else: print('Must be more than one class to perform classification') raise ValueErr...
201
201
671
45
155
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
transform_and_split_data
transform_and_split_data
1,182
1,253
1,182
1,182
c12aba0a52aeeaab6d058c1217352cb5b08d84ad
bigcode/the-stack
train
cab12ac7fa6b1440c8a8772c
train
class
class PCA_tabular(Transform): ''' Class will implement a PCA feature extraction method for tabular data On setup, we train a pca on the training data, then extract n_comps from the entire dataset the components are then added to the dataframe as new columns ''' def __init__(self...
class PCA_tabular(Transform):
''' Class will implement a PCA feature extraction method for tabular data On setup, we train a pca on the training data, then extract n_comps from the entire dataset the components are then added to the dataframe as new columns ''' def __init__(self, n_comps=3, add_col=True): ...
X): self._calls.append(('predict_proba', X)) return self.get_new_preds(X)[0].numpy() def predict(self, X): self._calls.append(('predict', X)) return self.get_new_preds(X)[1].numpy() # fastai classes class PCA_tabular(Transform):
68
68
229
7
60
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
PCA_tabular
PCA_tabular
323
347
323
323
68d2567f3a87dafa25eeb436de65e51b571c4f86
bigcode/the-stack
train
1029eec649c4f2550036b22e
train
function
def check_infs(data_summary: dict) -> pd.DataFrame: ''' Function will return a dataframe of features with a value of Inf. ''' vals: pd.DataFrame = data_summary['Feature_stats'] inf_df = vals[vals['Value'] == 'Inf'].T return inf_df[inf_df[0] != 0]
def check_infs(data_summary: dict) -> pd.DataFrame:
''' Function will return a dataframe of features with a value of Inf. ''' vals: pd.DataFrame = data_summary['Feature_stats'] inf_df = vals[vals['Value'] == 'Inf'].T return inf_df[inf_df[0] != 0]
data_summary: dict = { 'File': f'{label}', 'Dataset': df, 'Feature_stats': features_with_bad_values(df, f'{label}'), } return data_summary def check_infs(data_summary: dict) -> pd.DataFrame:
64
64
76
14
49
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
check_infs
check_infs
458
467
458
458
12ea049ec80419834af004f9bf6d3ce14cfa4cde
bigcode/the-stack
train
b14165ee00f9b7cb3b52b94c
train
function
def run_residual_deep_nn_experiment( df: pd.DataFrame, file_name: str, target_label: str, shape: tuple, split=0.2, categorical: list = ['Protocol'], procs = [FillMissing, Categorify, Normalize], leave_out: list = [], epochs: int = 10, batch_size: int = 64, metrics: list...
def run_residual_deep_nn_experiment( df: pd.DataFrame, file_name: str, target_label: str, shape: tuple, split=0.2, categorical: list = ['Protocol'], procs = [FillMissing, Categorify, Normalize], leave_out: list = [], epochs: int = 10, batch_size: int = 64, metrics: list...
''' Function trains a residual deep neural network model on the given data. Based on ResNet from Deep Residual Learning for Image Recognition by He et al. (2016) as well as the ResNext network proposed by Xie et al. (2017) but adapted to tabular data (https://arx...
= 'multiclass' else: print('Must be more than one class to perform classification') raise ValueError('Wrong number of classes') wrapped_model._target_labels = target_label model_data: Model_data = Model_data(file_name, wrapped_model, classes, X_train, y_train, X_test, y_test, to, ...
256
256
1,514
172
83
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
run_residual_deep_nn_experiment
run_residual_deep_nn_experiment
1,559
1,722
1,559
1,578
18acb50030209e57b5acfdd83ee96eb52a274f0e
bigcode/the-stack
train
affa5e3b03e23e6564cc4568
train
function
def get_file_path(directory: str): ''' Closure that will return a function. Function will return the filepath to the directory given to the closure ''' def func(file: str) -> str: return os.path.join(directory, file) return func
def get_file_path(directory: str):
''' Closure that will return a function. Function will return the filepath to the directory given to the closure ''' def func(file: str) -> str: return os.path.join(directory, file) return func
tsklearn:\t{sklearn.__version__} \ttorch:\t\t{torch.__version__} \tyellowbrick:\t{yb.__version__} \timblearn:\t{imblearn.__version__} ''' ) def get_file_path(directory: str):
64
64
58
8
56
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
get_file_path
get_file_path
126
135
126
126
163a4a2e939d3d67fb160a75c289e6482f4ef21e
bigcode/the-stack
train
08b4d98460b4e39fab7effad
train
function
def package_data_for_inspection(df: pd.DataFrame) -> dict: ''' Function will return a dictionary containing dataframe passed in as well as that dataframe's feature stats. ''' # print the data composition print(f''' Dataset statistics: Shape:\t\t\t\t{df.shape} Samples:\t\t\t{...
def package_data_for_inspection(df: pd.DataFrame) -> dict:
''' Function will return a dictionary containing dataframe passed in as well as that dataframe's feature stats. ''' # print the data composition print(f''' Dataset statistics: Shape:\t\t\t\t{df.shape} Samples:\t\t\t{df.shape[0]} Features:\t\t\t{df.shape[1]} ''')...
dict = { 'File': file_set[job_id], 'Dataset': df, 'Feature_stats': features_with_bad_values(df, file_set[job_id]), } return data_summary def package_data_for_inspection(df: pd.DataFrame) -> dict:
64
64
147
15
48
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
package_data_for_inspection
package_data_for_inspection
409
430
409
409
b6724ad3b483da7727c9e3be1900067d32add043
bigcode/the-stack
train
2daf39853dfcda9f155c7697
train
function
def package_data_for_inspection_with_label(df: pd.DataFrame, label: str) -> dict: ''' Function will return a dictionary containing dataframe passed in as well as that dataframe's feature stats. ''' # print the data composition print(f''' Shape:\t\t\t\t{df.shape} Samples:\t\t\t{d...
def package_data_for_inspection_with_label(df: pd.DataFrame, label: str) -> dict:
''' Function will return a dictionary containing dataframe passed in as well as that dataframe's feature stats. ''' # print the data composition print(f''' Shape:\t\t\t\t{df.shape} Samples:\t\t\t{df.shape[0]} Features:\t\t\t{df.shape[1]} ''') # return the ...
data_summary: dict = { 'File': '', 'Dataset': df, 'Feature_stats': features_with_bad_values(df, ''), } return data_summary def package_data_for_inspection_with_label(df: pd.DataFrame, label: str) -> dict:
64
64
154
21
42
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
package_data_for_inspection_with_label
package_data_for_inspection_with_label
434
454
434
434
3b27a11b80ede7e07f70332a24f71136fa1d9067
bigcode/the-stack
train
122ded0c62df930afea11e8c
train
function
def reduce_feature_to_values(df: pd.DataFrame, column: str, value: list) -> pd.DataFrame: ''' Function takes a dataframe, a column name, and a list of values and returns a dataframe with all rows that do not have the values in the column removed ''' new_df = pd.DataFrame() for v in value...
def reduce_feature_to_values(df: pd.DataFrame, column: str, value: list) -> pd.DataFrame:
''' Function takes a dataframe, a column name, and a list of values and returns a dataframe with all rows that do not have the values in the column removed ''' new_df = pd.DataFrame() for v in value: new_df = new_df.append(df[df[column] == v].copy()) return new_df
keeping them ''' new_df = pd.DataFrame() for v in value: new_df = new_df.append(df[df[column] == v].copy()) return new_df def reduce_feature_to_values(df: pd.DataFrame, column: str, value: list) -> pd.DataFrame:
64
64
98
24
39
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
reduce_feature_to_values
reduce_feature_to_values
612
621
612
612
a65640e2e6358e5a0f2815c811e3a6cc71f53626
bigcode/the-stack
train
664cb43904c0552b8e2ed2c7
train
function
def prune_dataset(data_summary: dict, prune: list) -> pd.DataFrame: ''' Function will return the dataset with all the columns in the prune list removed. ''' df: pd.DataFrame = data_summary['Dataset'].copy() df = clean_data(df, prune) return df
def prune_dataset(data_summary: dict, prune: list) -> pd.DataFrame:
''' Function will return the dataset with all the columns in the prune list removed. ''' df: pd.DataFrame = data_summary['Dataset'].copy() df = clean_data(df, prune) return df
= len(replace) df1: pd.DataFrame = df.copy() for i in range(length): df1[replace[i][0]].replace(replace[i][1], inplace=True) return df1 def prune_dataset(data_summary: dict, prune: list) -> pd.DataFrame:
64
64
64
17
46
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
prune_dataset
prune_dataset
584
592
584
584
153e937d5a6f932b17bd7b1737633ef6be984642
bigcode/the-stack
train
4de983c3530dc439034b423f
train
function
def plot_persistence_diagrams(diagrams: list, shape: tuple = (1, 4), titles: list or None = None, homology_dimensions: list or None = None, colors: list or None = None): ''' Function plots a set of persistence diagrams ''' cols = shape[1] fig = make_subplots(rows=shape[0], cols=cols, column_ti...
def plot_persistence_diagrams(diagrams: list, shape: tuple = (1, 4), titles: list or None = None, homology_dimensions: list or None = None, colors: list or None = None):
''' Function plots a set of persistence diagrams ''' cols = shape[1] fig = make_subplots(rows=shape[0], cols=cols, column_titles=titles) if homology_dimensions is None: homology_dimensions = np.unique(diagrams[0][:, 2]) if colors is None: colors = get_n_color_list(len...
specs[i, j] = {'type': 'scene'} fig = make_subplots(rows=shape[0], cols=shape[1], specs=specs.tolist(), column_titles=titles) for i, cloud in enumerate(clouds): row = (i // cols) + 1 col = (i % cols) + 1 fig.add_trace(go.Scatter3d( # x=cloud[0, :], ...
256
256
886
47
208
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
plot_persistence_diagrams
plot_persistence_diagrams
2,409
2,513
2,409
2,409
64688d67d3f065995ab50da5539d6e4ae7f05ec8
bigcode/the-stack
train
50a6b01092433d38f89777ce
train
function
def remove_infs_and_nans(data_summary: dict) -> pd.DataFrame: ''' Function will return the dataset with all inf and nan values removed. ''' df: pd.DataFrame = data_summary['Dataset'].copy() df = clean_data(df, []) return df
def remove_infs_and_nans(data_summary: dict) -> pd.DataFrame:
''' Function will return the dataset with all inf and nan values removed. ''' df: pd.DataFrame = data_summary['Dataset'].copy() df = clean_data(df, []) return df
[0] zero_df = vals[vals['Value'] == 'Zero'].T zero_df_bottom = zero_df[2:] return zero_df_bottom[zero_df_bottom[2] > threshold*size] def remove_infs_and_nans(data_summary: dict) -> pd.DataFrame:
63
64
61
17
46
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
remove_infs_and_nans
remove_infs_and_nans
523
531
523
523
5a1d2f8e0d81e8ae082501aaf678e509b807bbca
bigcode/the-stack
train
3017636581ea2f91092f116e
train
class
class DFLogger(Callback): ''' Class defines a callback that is passed to the fastai learner that will save the recorded metrics for each epoch to a dataframe ''' order=60 def __init__(self, fname='history.csv', append=False): self.fname,self.append = pathlib.Path(fname),appen...
class DFLogger(Callback):
''' Class defines a callback that is passed to the fastai learner that will save the recorded metrics for each epoch to a dataframe ''' order=60 def __init__(self, fname='history.csv', append=False): self.fname,self.append = pathlib.Path(fname),append self.df = pd.Dat...
''' Function asserts the dataset has none of the columns present in the prune list ''' original_size: int = data_summary_original['Dataset'].shape[1] pruned_size: int = data_summary_pruned['Dataset'].shape[1] prune_list_size: int = len(prune) assert original_size - prune_list_size == pru...
96
96
323
6
89
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
DFLogger
DFLogger
684
720
684
684
77e26a268b983c5903b9fdf73be69f2efc3b0a72
bigcode/the-stack
train
801010879e90fd2e80836cde
train
class
class CardinalResidualBlock(Module): ''' A residule block that creates a skip connection around a set of n branches where the number of branches is determined by the number of input modules in the branches list parameter. The output of the branches is summed together along w...
class CardinalResidualBlock(Module):
''' A residule block that creates a skip connection around a set of n branches where the number of branches is determined by the number of input modules in the branches list parameter. The output of the branches is summed together along with the input Output size of ...
= module self.layer = layer def forward(self, inputs): fx = self.module(inputs) if(inputs.shape != fx.shape): print('mismatch at layer:', self.layer ,inputs.shape, fx.shape) assert False return fx + inputs class CardinalResidualBlock(Module):
64
64
197
6
57
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
CardinalResidualBlock
CardinalResidualBlock
908
930
908
908
7f312e024013ce978c4d548ed1d494b1183de31f
bigcode/the-stack
train
cb37cd0e4e23683cbcb92b7d
train
function
def run_cross_validated_deep_nn_experiment( df: pd.DataFrame, name: str, target_label: str, shape: tuple, k_folds: int = 10, categorical = ['Protocol'], dropout_rate: float = 0.01, callbacks: list = [ShowGraphCallback], metrics: list or None= None, procs: list = [FillMissing,...
def run_cross_validated_deep_nn_experiment( df: pd.DataFrame, name: str, target_label: str, shape: tuple, k_folds: int = 10, categorical = ['Protocol'], dropout_rate: float = 0.01, callbacks: list = [ShowGraphCallback], metrics: list or None= None, procs: list = [FillMissing,...
''' Function will fit a deep neural network to the given dataset using cross-validation ''' metrics_ = metrics lr_choice = { 'valley': 0, 'slide': 1, 'steep': 2, 'minimum': 3, }[lr_choice] if(experiment_type is None): experiment_type = f'Deep_NN_{...
_ = 'single' model_data: Model_data = Model_data(name, model, classes, X_train, y_train, X_test, y_test, to, dls, 'Transformed_and_Split_data') # Now that the classifier has been created and trained, we pass out our training values # for analysis and further experimentation return model_data ...
256
256
1,153
140
115
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
run_cross_validated_deep_nn_experiment
run_cross_validated_deep_nn_experiment
1,262
1,399
1,262
1,277
81e9900e16834a831d325b54206ba7e0fa5ed495
bigcode/the-stack
train
bfa6fd6c18b38ecfe6e104c6
train
class
class BottleneckResidualBlock(Module): ''' A residule block that creates a skip connection around a set of n branches where the number of branches is determined by the number of input modules in the branches list parameter. the residual connection is put through a linear...
class BottleneckResidualBlock(Module):
''' A residule block that creates a skip connection around a set of n branches where the number of branches is determined by the number of input modules in the branches list parameter. the residual connection is put through a linear batchnormed layer if the i...
1): for i in range(len(self.branches) - 1): fx += self.branches[i + 1](inputs) return fx + inputs # currently need to create a bottlenecking block that can be used to reduce the number of inputs # being passed by the residual connection class BottleneckResidualBlock(Module):
72
72
240
7
64
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
BottleneckResidualBlock
BottleneckResidualBlock
935
963
935
935
d81a289b1d323344f386bf140ea64728869350d1
bigcode/the-stack
train
a6348bc7d60111e3d76f1894
train
function
def show_clusters_by_label_2D(model_data: Model_data, x_col: str, y_col: str, target_label: str = 'label', samples=25000, title='Clusters by Label', ) -> dict: ''' Takes a model_data tuple and displays the indicated columns of the X_train data as a scatter plot. ''' X = model_data.X_trai...
def show_clusters_by_label_2D(model_data: Model_data, x_col: str, y_col: str, target_label: str = 'label', samples=25000, title='Clusters by Label', ) -> dict:
''' Takes a model_data tuple and displays the indicated columns of the X_train data as a scatter plot. ''' X = model_data.X_train.copy() X[target_label] = model_data.y_train.copy() classes = model_data.classes num_labels = len(X.groupby(target_label).size()) labe...
): temp_fig.layout.title = individual_titles[i * stack_shape[0] + j] horizantal_stack.append(temp_fig) vertical_stack.append(widgets.HBox(horizantal_stack)) horizantal_stack = [] fig = widgets.VBox(vertical_stack) return fig """ def show_clusters_by...
107
108
361
47
60
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
show_clusters_by_label_2D
show_clusters_by_label_2D
2,172
2,221
2,172
2,172
c5f14f793d9f58ac1398a8ab57ca5f5acfaafcab
bigcode/the-stack
train
d7f62e59400cea10ad60d2d3
train
function
def visualize_pr_curve(model_data: tuple, ax=None, cmap='Blues') -> yb.classifier: ''' Takes a 10-tuple from the run_experiments function and creates a Precision-Recall Curve model_data: tuple = (name, model, classes, X_train, y_train, X_test, y_test, to, dls, model_type) ''' visu...
def visualize_pr_curve(model_data: tuple, ax=None, cmap='Blues') -> yb.classifier:
''' Takes a 10-tuple from the run_experiments function and creates a Precision-Recall Curve model_data: tuple = (name, model, classes, X_train, y_train, X_test, y_test, to, dls, model_type) ''' visualizer = yb.classifier.PrecisionRecallCurve(model_data[1], title=model_data[0], ax=...
1], classes=model_data[2], title=model_data[0], ax=ax, cmap=cmap) visualizer.score(model_data[5], model_data[6]) return visualizer def visualize_pr_curve(model_data: tuple, ax=None, cmap='Blues') -> yb.classifier:
64
64
134
23
40
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
visualize_pr_curve
visualize_pr_curve
2,069
2,080
2,069
2,069
c5d6793d9f3cf53e721dc1e4dbaad6f45e1eea18
bigcode/the-stack
train
605263c88f3e40965696b5a8
train
function
def test_pruned_size(data_summary_original: dict, data_summary_pruned: dict, prune: list) -> bool: ''' Function asserts the dataset has none of the columns present in the prune list ''' original_size: int = data_summary_original['Dataset'].shape[1] pruned_size: int = data_summary_pruned['Datas...
def test_pruned_size(data_summary_original: dict, data_summary_pruned: dict, prune: list) -> bool:
''' Function asserts the dataset has none of the columns present in the prune list ''' original_size: int = data_summary_original['Dataset'].shape[1] pruned_size: int = data_summary_pruned['Dataset'].shape[1] prune_list_size: int = len(prune) assert original_size - prune_list_size == ...
in prune: if col in data_summary['Dataset'].columns: pruned = False assert pruned, 'Dataset has columns present in prune list' return pruned def test_pruned_size(data_summary_original: dict, data_summary_pruned: dict, prune: list) -> bool:
64
64
116
25
38
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
test_pruned_size
test_pruned_size
671
682
671
671
e38e742a1c138d2c32e5bb0b28d0675d7c1bce72
bigcode/the-stack
train
b1989b874457aa9d6e7ad37f
train
function
def check_zeros_over_threshold(data_summary: dict, threshold: int) -> pd.DataFrame: ''' Function will return a dataframe of features with a value of 0. ''' vals: pd.DataFrame = data_summary['Feature_stats'] zero_df = vals[vals['Value'] == 'Zero'].T zero_df_bottom = zero_df[2:] return z...
def check_zeros_over_threshold(data_summary: dict, threshold: int) -> pd.DataFrame:
''' Function will return a dataframe of features with a value of 0. ''' vals: pd.DataFrame = data_summary['Feature_stats'] zero_df = vals[vals['Value'] == 'Zero'].T zero_df_bottom = zero_df[2:] return zero_df_bottom[zero_df_bottom[2] > threshold]
vals: pd.DataFrame = data_summary['Feature_stats'] zero_df = vals[vals['Value'] == 'Zero'].T return zero_df[zero_df[2] != 0] def check_zeros_over_threshold(data_summary: dict, threshold: int) -> pd.DataFrame:
63
64
93
20
43
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
check_zeros_over_threshold
check_zeros_over_threshold
495
504
495
495
2596c7788dec1e04890d563b01c034402eb97cab
bigcode/the-stack
train
9df8bde05d877a8466e18863
train
function
def visualize_side_by_side( model_datum: list, results: dict, title: str = "Confusion Matrices", model_descriptions: list or None = None, plotting_function: callable = visualize_confusion_matrix, shape: tuple = (2,5), size: tuple = (20,10), x_label: str = 'Predicted', y_label: str = ...
def visualize_side_by_side( model_datum: list, results: dict, title: str = "Confusion Matrices", model_descriptions: list or None = None, plotting_function: callable = visualize_confusion_matrix, shape: tuple = (2,5), size: tuple = (20,10), x_label: str = 'Predicted', y_label: str = ...
''' Function will take the plotting function and execute it on each Model_data tuple passed in through the model_datum list The plots will be oriented in a subplot grid with the number of rows and columns specified by the shape tuple average accuracy will be calculated and displayed ...
fig = go.Figure({'data': traces, 'layout': layout}) # a, b = fig.data # fig.data = b, a figs.append(fig) return figs def visualize_side_by_side( model_datum: list, results: dict, title: str = "Confusion Matrices", model_descriptions: list or None = None, plotting_functi...
136
136
456
94
41
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
visualize_side_by_side
visualize_side_by_side
2,293
2,347
2,293
2,303
a85d86e042f927f4a375f23020a3df916acf78d4
bigcode/the-stack
train
5f324df7afc0754946124b81
train
function
def get_n_color_list(n: int, opacity=.8, luminosity=.5, saturation=.5) -> list: ''' Function creates a list of n distinct colors, formatted for use in a plotly graph ''' colors = [] for i in range(n): color = colorsys.hls_to_rgb( i / n, luminosity, ...
def get_n_color_list(n: int, opacity=.8, luminosity=.5, saturation=.5) -> list:
''' Function creates a list of n distinct colors, formatted for use in a plotly graph ''' colors = [] for i in range(n): color = colorsys.hls_to_rgb( i / n, luminosity, saturation, ) colors.append(f'rgba({color[0]...
'turbid', 'turbo', 'twilight', 'viridis', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd' ] def get_n_color_list(n: int, opacity=.8, luminosity=.5, saturation=.5) -> list:
64
64
125
25
39
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
get_n_color_list
get_n_color_list
259
275
259
259
b229df4534fefa3ecba38f0c009a6fd32b87a741
bigcode/the-stack
train
fc8e11024d7c5efc0208f4c7
train
function
def decode_classes_and_create_Xy_df(model_data: Model_data, target_label: str): """ Function takes a Model_data namedtuple and returns a dataframe with the X and decoded y data """ X = model_data.X_train y = model_data.y_train classes = model_data.classes Xy_df = pd.DataFrame(X) y_s...
def decode_classes_and_create_Xy_df(model_data: Model_data, target_label: str):
""" Function takes a Model_data namedtuple and returns a dataframe with the X and decoded y data """ X = model_data.X_train y = model_data.y_train classes = model_data.classes Xy_df = pd.DataFrame(X) y_s: list = [] for x in y: y_s.append(classes[x]) Xy_df[target_labe...
= target_label model_data: Model_data = Model_data(file_name, wrapped_model, classes, X_train, y_train, X_test, y_test, to, dls, name) return model_data def decode_classes_and_create_Xy_df(model_data: Model_data, target_label: str):
64
64
113
19
44
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
decode_classes_and_create_Xy_df
decode_classes_and_create_Xy_df
1,891
1,905
1,891
1,891
ad792aaf83b73e186d68224a502094644aa5c3f2
bigcode/the-stack
train
547240022ae33c332980e885
train
function
def extract_validation_set(df: pd.DataFrame, target_label: str, categorical : list = ['Protocol'], leave_out: list = []): ''' Run binary classification using a shallow learning model returns the 10-tuple Model_data ''' dep_var: str = target_label categorical_features: list = [] unto...
def extract_validation_set(df: pd.DataFrame, target_label: str, categorical : list = ['Protocol'], leave_out: list = []):
''' Run binary classification using a shallow learning model returns the 10-tuple Model_data ''' dep_var: str = target_label categorical_features: list = [] untouched_features : list = [] for x in categorical: if x in df.columns: categorical_features.append...
ls) assert n_out, "`n_out` is not defined, and could not be inferred from data, set `dls.c` or pass `n_out`" if y_range is None and 'y_range' in config: y_range = config.pop('y_range') model = ResidualTabularModel(emb_szs, len(dls.cont_names), n_out, layers, y_range=y_range, cardinality=cardinality, ps=ps, ...
144
144
481
29
115
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
extract_validation_set
extract_validation_set
1,032
1,084
1,032
1,032
9c7802abf6a93bb39a0a63d3369206c2bece68b5
bigcode/the-stack
train
4be90b319b672cdadc6abf96
train
function
def confusion_matrix_from_dataset(model_data: tuple, df: pd.DataFrame, ax=None, cmap='Blues') -> yb.classifier: ''' Takes a 10-tuple from the run_experiments function and uses the model to classify the data passed in as the dataframe. Produces a confusion matrix (currently only confi...
def confusion_matrix_from_dataset(model_data: tuple, df: pd.DataFrame, ax=None, cmap='Blues') -> yb.classifier:
''' Takes a 10-tuple from the run_experiments function and uses the model to classify the data passed in as the dataframe. Produces a confusion matrix (currently only confirmed to work with fastai models) model_data: tuple = (name, model, classes, X_train, y_train, X_test, y...
= yb.target.ClassBalance(labels=model_data[0], ax=ax, cmap=cmap) visualizer.fit(model_data[4], model_data[6]) return visualizer def confusion_matrix_from_dataset(model_data: tuple, df: pd.DataFrame, ax=None, cmap='Blues') -> yb.classifier:
69
69
231
30
38
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
confusion_matrix_from_dataset
confusion_matrix_from_dataset
2,115
2,132
2,115
2,115
b10444e3ee82511069439b5851bb390c30087c55
bigcode/the-stack
train
e25b5cc293ac3d399a7a5742
train
function
def load_data(filePath): ''' Loads the Dataset from the given filepath and caches it for quick access in the future Function will only work when filepath is a .csv file ''' p = pathlib.Path(filePath) filePathClean: str = str(p.parts[-1]) pickleDump: str = f'./cache/{filePathClean}.p...
def load_data(filePath):
''' Loads the Dataset from the given filepath and caches it for quick access in the future Function will only work when filepath is a .csv file ''' p = pathlib.Path(filePath) filePathClean: str = str(p.parts[-1]) pickleDump: str = f'./cache/{filePathClean}.pickle' print(f'Loadi...
def get_file_path(directory: str): ''' Closure that will return a function. Function will return the filepath to the directory given to the closure ''' def func(file: str) -> str: return os.path.join(directory, file) return func def load_data(filePath):
64
64
178
6
57
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
load_data
load_data
139
162
139
139
2c118f9579a8d4b90f2d3bfcfb6b59068b7f9cc6
bigcode/the-stack
train
67420ebd7a6842fd642a8ba5
train
function
def plot_point_clouds(clouds: list, shape: tuple = (1, 4), titles: list or None = None, homology_dimensions: list or None = None, color='magma'): specs = np.zeros(shape).astype(object) cols = shape[1] for i in range(specs.shape[0]): for j in range(specs.shape[1]): specs[i, j] = {'type...
def plot_point_clouds(clouds: list, shape: tuple = (1, 4), titles: list or None = None, homology_dimensions: list or None = None, color='magma'):
specs = np.zeros(shape).astype(object) cols = shape[1] for i in range(specs.shape[0]): for j in range(specs.shape[1]): specs[i, j] = {'type': 'scene'} fig = make_subplots(rows=shape[0], cols=shape[1], specs=specs.tolist(), column_titles=titles) for i, cloud in enumerate(cloud...
, color='g') ax.set_xticks(range(len(feature_importances))) ax.set_xticklabels(dl.x_names, rotation=90) ax.set_title(title) return (fig, ax) def plot_point_clouds(clouds: list, shape: tuple = (1, 4), titles: list or None = None, homology_dimensions: list or None = None, color='magma'):
87
87
293
45
42
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
plot_point_clouds
plot_point_clouds
2,370
2,406
2,370
2,372
f04f2972323e87301b1fb45c9ae4c0e1bfa1939e
bigcode/the-stack
train
2abf6e7ddb302d6067049b0f
train
function
def extract_correlations(correlations: pd.DataFrame, feature: str, leave_out: list = ['Traffic Type', 'Application Type']) -> list: ''' Function takes a correlation dataframe and extracts a list of features correlated with the input feature. Anything in leave_out is not included in the list. ...
def extract_correlations(correlations: pd.DataFrame, feature: str, leave_out: list = ['Traffic Type', 'Application Type']) -> list:
''' Function takes a correlation dataframe and extracts a list of features correlated with the input feature. Anything in leave_out is not included in the list. ''' correlation_order: list = list(correlations.sort_values(by=feature, ascending=False).index) for x in leave_out: ...
''' encoded_data = model_data.X_train.copy() encoded_data[target_label] = model_data.y_train return encoded_data.corr() def extract_correlations(correlations: pd.DataFrame, feature: str, leave_out: list = ['Traffic Type', 'Application Type']) -> list:
64
64
113
32
32
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
extract_correlations
extract_correlations
2,026
2,038
2,026
2,026
16050d9071dfd1ae60c490cb824944aa8f0c6f44
bigcode/the-stack
train
6910eac4bd0d9fb8603dced7
train
function
def examine_dataset(job_id: int) -> dict: ''' Function will return a dictionary containing dataframe of the job_id passed in as well as that dataframe's feature stats, data composition, and file name. This dictionary is expected as the input for all of the other helper functions ''' ...
def examine_dataset(job_id: int) -> dict:
''' Function will return a dictionary containing dataframe of the job_id passed in as well as that dataframe's feature stats, data composition, and file name. This dictionary is expected as the input for all of the other helper functions ''' job_id = job_id - 1 # adjusts for index...
, to, **kwargs): to.conts = (to.conts-self.mins) / (self.maxs - self.mins) return to def decodes(self, to, **kwargs): to.conts = (to.conts) * (to.maxs - to.mins) + to.mins return to def examine_dataset(job_id: int) -> dict:
84
84
280
11
72
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
examine_dataset
examine_dataset
373
405
373
373
8d4c22832b40845588343f2f2bed60afc78bc857
bigcode/the-stack
train
739ce9b641f551706f4f82f6
train
function
def rename_values_in_column_df(df: pd.DataFrame, replace: list) -> pd.DataFrame: ''' Function will return a dataframe with the names of the columns changed replace: [('column', {'old_name': 'new_name', ...}), ...] ''' length: int = len(replace) df1: pd.DataFrame = df.copy() for i i...
def rename_values_in_column_df(df: pd.DataFrame, replace: list) -> pd.DataFrame:
''' Function will return a dataframe with the names of the columns changed replace: [('column', {'old_name': 'new_name', ...}), ...] ''' length: int = len(replace) df1: pd.DataFrame = df.copy() for i in range(length): df1[replace[i][0]].replace(replace[i][1], inplace=True) ...
df: pd.DataFrame = data_summary['Dataset'].copy() for i in range(length): df[replace[i][0]].replace(replace[i][1], inplace=True) return df def rename_values_in_column_df(df: pd.DataFrame, replace: list) -> pd.DataFrame:
64
64
108
21
42
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
rename_values_in_column_df
rename_values_in_column_df
567
580
567
567
49fc9fa6826139ed36f06597189df39c79879933
bigcode/the-stack
train
f681914c281e2ba12fbccc27
train
function
@delegates(Learner.__init__) def residual_tabular_learner(dls, layers=None, emb_szs=None, config=None, n_out=None, y_range=None, **kwargs): "Get a `Learner` using `dls`, with `metrics`, including a `TabularModel` created using the remaining params." if config is None: config = tabular_config() if layers is ...
@delegates(Learner.__init__) def residual_tabular_learner(dls, layers=None, emb_szs=None, config=None, n_out=None, y_range=None, **kwargs):
"Get a `Learner` using `dls`, with `metrics`, including a `TabularModel` created using the remaining params." if config is None: config = tabular_config() if layers is None: layers = [200,100] to = dls.train_ds emb_szs = get_emb_sz(dls.train_ds, {} if emb_szs is None else emb_szs) if n_out is No...
_cont) x = torch.cat([x, x_cont], 1) if self.n_emb != 0 else x_cont return self.layers(x) @delegates(Learner.__init__) def residual_tabular_learner(dls, layers=None, emb_szs=None, config=None, n_out=None, y_range=None, **kwargs):
74
74
247
41
33
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
residual_tabular_learner
residual_tabular_learner
872
883
872
873
8e65b26ae7c142a5d6399f25ed9bf43b81e16005
bigcode/the-stack
train
e4463a6dd675251be02c0d1a
train
function
def plot_point_clouds_and_persistence_diagram(point_clouds: list, persistence_diagrams: list, rows: int, columns: int, homology_dimensions: list or None = None, color='magma', column_titles: list or None = None): cols = columns ri1 = {'type': 'scene'} ri2 = {'type': 'xy'} specs = np.zeros((2,4)).ast...
def plot_point_clouds_and_persistence_diagram(point_clouds: list, persistence_diagrams: list, rows: int, columns: int, homology_dimensions: list or None = None, color='magma', column_titles: list or None = None):
cols = columns ri1 = {'type': 'scene'} ri2 = {'type': 'xy'} specs = np.zeros((2,4)).astype(object) for i in range(specs.shape[0]): for j in range(specs.shape[1]): if(i == 0): specs[i, j] = ri1 else: specs[i, j] = ri2 if homology...
markers", showlegend = (i==0), ), row=row, col=col ) if(row == (len(diagrams)//cols)): fig.update_xaxes(title_text="Feature Birth", row=row, col=col) if(col == 1): fig.update_yaxes(title...
256
256
1,140
55
200
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
plot_point_clouds_and_persistence_diagram
plot_point_clouds_and_persistence_diagram
2,516
2,656
2,516
2,519
c795382521e57e264d3600e3a1a4ee0fea829f0d
bigcode/the-stack
train
4643b886680dab7cca963bcf
train
function
def visualize_roc(model_data: tuple, ax=None, cmap='Blues') -> yb.classifier: ''' Takes a 10-tuple from the run_experiments function and creates a Receiver Operating Characteristic (ROC) Curve model_data: tuple = (name, model, classes, X_train, y_train, X_test, y_test, to, dls, model_type)...
def visualize_roc(model_data: tuple, ax=None, cmap='Blues') -> yb.classifier:
''' Takes a 10-tuple from the run_experiments function and creates a Receiver Operating Characteristic (ROC) Curve model_data: tuple = (name, model, classes, X_train, y_train, X_test, y_test, to, dls, model_type) ''' visualizer = yb.classifier.ROCAUC(model_data[1], classes=model_d...
[2], title=model_data[0], ax=ax, cmap=cmap, is_fitted=True) visualizer.score(model_data[5], model_data[6]) return visualizer def visualize_roc(model_data: tuple, ax=None, cmap='Blues') -> yb.classifier:
64
64
143
23
40
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
visualize_roc
visualize_roc
2,054
2,065
2,054
2,054
b721a0a428056c24a671783d91ff740267545560
bigcode/the-stack
train
44d776843d1c51f28a912080
train
function
def check_nans(data_summary: dict) -> pd.DataFrame: ''' Function will return a dataframe of features with a value of NaN. ''' vals: pd.DataFrame = data_summary['Feature_stats'] nan_df = vals[vals['Value'] == 'NaN'].T return nan_df[nan_df[1] != 0]
def check_nans(data_summary: dict) -> pd.DataFrame:
''' Function will return a dataframe of features with a value of NaN. ''' vals: pd.DataFrame = data_summary['Feature_stats'] nan_df = vals[vals['Value'] == 'NaN'].T return nan_df[nan_df[1] != 0]
of Inf. ''' vals: pd.DataFrame = data_summary['Feature_stats'] inf_df = vals[vals['Value'] == 'Inf'].T return inf_df[inf_df[0] != 0] def check_nans(data_summary: dict) -> pd.DataFrame:
63
64
77
14
49
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
check_nans
check_nans
471
479
471
471
3a872c43252e173e4551b7cf4d31c97ab93a3e81
bigcode/the-stack
train
0cee715cfef095039d8db6b9
train
function
def test_pruned(data_summary: dict, prune: list) -> bool: ''' Function asserts the dataset has none of the columns present in the prune list ''' pruned: bool = True for col in prune: if col in data_summary['Dataset'].columns: pruned = False assert pruned, 'Dataset has...
def test_pruned(data_summary: dict, prune: list) -> bool:
''' Function asserts the dataset has none of the columns present in the prune list ''' pruned: bool = True for col in prune: if col in data_summary['Dataset'].columns: pruned = False assert pruned, 'Dataset has columns present in prune list' return pruned
_df = vals[vals['Value'] == 'NaN'].T assert nan_df[nan_df[1] != 0].shape[0] == 2, 'Dataset has NaN values' return True def test_pruned(data_summary: dict, prune: list) -> bool:
64
64
86
16
47
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
test_pruned
test_pruned
654
667
654
654
50219c66367894cc628e924f79d9e84ff9aa531b
bigcode/the-stack
train
40f11fb1c08e02cabb53abfe
train
function
def calculate_correlations(model_data: Model_data, target_label: str): ''' Function merges together the encoded and standardized model data and labels to calculate pearson correlation ''' encoded_data = model_data.X_train.copy() encoded_data[target_label] = model_data.y_train return encode...
def calculate_correlations(model_data: Model_data, target_label: str):
''' Function merges together the encoded and standardized model data and labels to calculate pearson correlation ''' encoded_data = model_data.X_train.copy() encoded_data[target_label] = model_data.y_train return encoded_data.corr()
clouds = np.array(clouds) clouds_y = np.array(clouds_y) clouds_y_decoded = np.array(clouds_y_decoded) return clouds, clouds_y, classes, clouds_y_decoded def calculate_correlations(model_data: Model_data, target_label: str):
64
64
66
15
48
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
calculate_correlations
calculate_correlations
2,015
2,023
2,015
2,015
0bb780558dd5a870186e7752fdd2664b4af0fdb9
bigcode/the-stack
train
fb2903063a0ca063cd984e33
train
function
def visualize_confusion_matrix(model_data: tuple, ax=None, cmap='Blues') -> yb.classifier: ''' Takes a 10-tuple from the run_experiments function and creates a confusion matrix model_data: tuple = (name, model, classes, X_train, y_train, X_test, y_test, to, dls, model_type) ''' visualizer ...
def visualize_confusion_matrix(model_data: tuple, ax=None, cmap='Blues') -> yb.classifier:
''' Takes a 10-tuple from the run_experiments function and creates a confusion matrix model_data: tuple = (name, model, classes, X_train, y_train, X_test, y_test, to, dls, model_type) ''' visualizer = yb.classifier.ConfusionMatrix(model_data[1], classes=model_data[2], title=model_data[0], ...
list(correlations.sort_values(by=feature, ascending=False).index) for x in leave_out: if x in correlation_order: correlation_order.remove(x) return correlation_order def visualize_confusion_matrix(model_data: tuple, ax=None, cmap='Blues') -> yb.classifier:
64
64
142
24
39
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
visualize_confusion_matrix
visualize_confusion_matrix
2,041
2,051
2,041
2,041
51c0f51bad50883d327e57c03aed4b6eb8f3b443
bigcode/the-stack
train
80d6419b74094f15e5b8b485
train
class
class ResidualBlock(Module): ''' A simple residule block that creates a skip connection around any input module Output size of the input module must match the module's input size ''' def __init__(self, module, layer): self.module = module self.layer = layer def forward(s...
class ResidualBlock(Module):
''' A simple residule block that creates a skip connection around any input module Output size of the input module must match the module's input size ''' def __init__(self, module, layer): self.module = module self.layer = layer def forward(self, inputs): fx = se...
(dls, model, **kwargs) Model_data = namedtuple( 'model_data', ['name', 'model', 'classes', 'X_train', 'y_train', 'X_test', 'y_test', 'to', 'dls', 'model_type'] ) class ResidualBlock(Module):
64
64
113
6
58
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
ResidualBlock
ResidualBlock
891
905
891
891
6a8c39a7e437eb2cc8f86396acd943858442f7d4
bigcode/the-stack
train
338073afe24d058214c4b900
train
function
def run_knn_experiment(df: pd.DataFrame, name: str, target_label: str, split=0.2, categorical : list = ['Protocol'], leave_out: list = []) -> Model_data: ''' Run binary classification using K-Nearest Neighbors returns the 10-tuple Model_data ''' # First we split the features into the depend...
def run_knn_experiment(df: pd.DataFrame, name: str, target_label: str, split=0.2, categorical : list = ['Protocol'], leave_out: list = []) -> Model_data:
''' Run binary classification using K-Nearest Neighbors returns the 10-tuple Model_data ''' # First we split the features into the dependent variable and # continous and categorical features dep_var: str = target_label print(df.shape) categorical_features: list = [] ...
continuous_features , ) # We use fastai to quickly extract the names of the classes as they are mapped to the encodings dls = to.dataloaders(bs=64) #model = utils.tabular_learner(dls) #classes : list = list(model.dls.vocab) # We extract the training and test datasets from the dataframe X...
240
240
803
44
195
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
run_knn_experiment
run_knn_experiment
1,088
1,177
1,088
1,088
1fb97d9293df2f6668d52a27aef386ff9f694c39
bigcode/the-stack
train
93db7be055a926487a5d0be2
train
function
def faceted_clusters_by_label_2D(model_data: Model_data, x_col: str, y_col: str, target_label: str = 'label', samples=25000, title='Clusters by Label', ) -> dict: ''' Takes a model_data tuple and returns a list of figures that each contain a highlighted value in the label with the other values s...
def faceted_clusters_by_label_2D(model_data: Model_data, x_col: str, y_col: str, target_label: str = 'label', samples=25000, title='Clusters by Label', ) -> dict:
''' Takes a model_data tuple and returns a list of figures that each contain a highlighted value in the label with the other values serving as a grey background in a scatter plot that demonstrates the distribution ''' X = model_data.X_train.copy() X[target_label] = mode...
= dict( title = title, xaxis = dict( title = x_col, ticklen = 5 , zeroline = False, ), yaxis = dict( title = y_col, ticklen = 5 , zeroline = False, ) ) fig: dict = {'data': traces, 'la...
145
145
486
48
96
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
faceted_clusters_by_label_2D
faceted_clusters_by_label_2D
2,224
2,290
2,224
2,224
1555f3238a8ef8d1521e84802389e7e672fd6987
bigcode/the-stack
train
a61ae927a4c79cf896272780
train
function
def run_deep_nn_experiment( df: pd.DataFrame, file_name: str, target_label: str, shape: tuple, split=0.2, categorical: list = ['Protocol'], procs = [FillMissing, Categorify, Normalize], leave_out: list = [], epochs: int = 10, batch_size: int = 64, metrics: list or None ...
def run_deep_nn_experiment( df: pd.DataFrame, file_name: str, target_label: str, shape: tuple, split=0.2, categorical: list = ['Protocol'], procs = [FillMissing, Categorify, Normalize], leave_out: list = [], epochs: int = 10, batch_size: int = 64, metrics: list or None ...
''' Function trains a deep neural network model on the given data. Parameters: df: pandas dataframe containing the data file_name: name of the file the dataset came from target_label: the label to predict shape: the shape of the neural network, the ...
('Must be more than one class to perform classification') raise ValueError('Wrong number of classes') model_data: Model_data = Model_data(fold_name, wrapped_model, classes, X_train, y_train, X_test, y_test, to, dls, experiment_type) model_data_list[i] = model_data model_datum...
256
256
1,412
160
95
Karson-Fye/CMUDarknet
experiments/data_generation/VAE/utilities.py
Python
run_deep_nn_experiment
run_deep_nn_experiment
1,401
1,557
1,401
1,419
642d84b74f492714106c125c632e605282d95fe5
bigcode/the-stack
train