text:
import json

from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.abstract_client import AbstractClient
from tencentcloud.dasb.v20191018 import models

class DasbClient(AbstractClient):
    _apiVersion = '2019-10-18'
    _endpoint = 'dasb.tencentcloudapi.com'
    _service = 'dasb'

    def AddDeviceGroupMembers(self, request):
        """添加资产组成员

        :param request: Request instance for AddDeviceGroupMembers.
        :type request: :class:`tencentcloud.dasb.v20191018.models.AddDeviceGroupMembersRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.AddDeviceGroupMembersResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("AddDeviceGroupMembers", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.AddDeviceGroupMembersResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def AddUserGroupMembers(self, request):
        """添加用户组成员

        :param request: Request instance for AddUserGroupMembers.
        :type request: :class:`tencentcloud.dasb.v20191018.models.AddUserGroupMembersRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.AddUserGroupMembersResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("AddUserGroupMembers", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.AddUserGroupMembersResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def BindDeviceResource(self, request):
        """修改资产绑定的堡垒机服务

        :param request: Request instance for BindDeviceResource.
        :type request: :class:`tencentcloud.dasb.v20191018.models.BindDeviceResourceRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.BindDeviceResourceResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("BindDeviceResource", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.BindDeviceResourceResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def CreateAcl(self, request):
        """新建访问权限

        :param request: Request instance for CreateAcl.
        :type request: :class:`tencentcloud.dasb.v20191018.models.CreateAclRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.CreateAclResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("CreateAcl", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.CreateAclResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def CreateDeviceGroup(self, request):
        """新建资产组

        :param request: Request instance for CreateDeviceGroup.
        :type request: :class:`tencentcloud.dasb.v20191018.models.CreateDeviceGroupRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.CreateDeviceGroupResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("CreateDeviceGroup", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.CreateDeviceGroupResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def CreateUser(self, request):
        """新建用户

        :param request: Request instance for CreateUser.
        :type request: :class:`tencentcloud.dasb.v20191018.models.CreateUserRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.CreateUserResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("CreateUser", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.CreateUserResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def CreateUserGroup(self, request):
        """新建用户组

        :param request: Request instance for CreateUserGroup.
        :type request: :class:`tencentcloud.dasb.v20191018.models.CreateUserGroupRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.CreateUserGroupResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("CreateUserGroup", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.CreateUserGroupResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def DeleteAcls(self, request):
        """删除访问权限

        :param request: Request instance for DeleteAcls.
        :type request: :class:`tencentcloud.dasb.v20191018.models.DeleteAclsRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.DeleteAclsResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("DeleteAcls", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.DeleteAclsResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def DeleteDeviceGroupMembers(self, request):
        """删除资产组成员

        :param request: Request instance for DeleteDeviceGroupMembers.
        :type request: :class:`tencentcloud.dasb.v20191018.models.DeleteDeviceGroupMembersRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.DeleteDeviceGroupMembersResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("DeleteDeviceGroupMembers", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.DeleteDeviceGroupMembersResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def DeleteDeviceGroups(self, request):
        """删除资产组

        :param request: Request instance for DeleteDeviceGroups.
        :type request: :class:`tencentcloud.dasb.v20191018.models.DeleteDeviceGroupsRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.DeleteDeviceGroupsResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("DeleteDeviceGroups", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.DeleteDeviceGroupsResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def DeleteUserGroupMembers(self, request):
        """删除用户组成员

        :param request: Request instance for DeleteUserGroupMembers.
        :type request: :class:`tencentcloud.dasb.v20191018.models.DeleteUserGroupMembersRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.DeleteUserGroupMembersResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("DeleteUserGroupMembers", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.DeleteUserGroupMembersResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def DeleteUserGroups(self, request):
        """删除用户组

        :param request: Request instance for DeleteUserGroups.
        :type request: :class:`tencentcloud.dasb.v20191018.models.DeleteUserGroupsRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.DeleteUserGroupsResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("DeleteUserGroups", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.DeleteUserGroupsResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def DeleteUsers(self, request):
        """删除用户

        :param request: Request instance for DeleteUsers.
        :type request: :class:`tencentcloud.dasb.v20191018.models.DeleteUsersRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.DeleteUsersResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("DeleteUsers", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.DeleteUsersResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def DescribeAcls(self, request):
        """查询访问权限列表

        :param request: Request instance for DescribeAcls.
        :type request: :class:`tencentcloud.dasb.v20191018.models.DescribeAclsRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.DescribeAclsResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("DescribeAcls", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.DescribeAclsResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def DescribeDasbImageIds(self, request):
        """获取镜像列表

        :param request: Request instance for DescribeDasbImageIds.
        :type request: :class:`tencentcloud.dasb.v20191018.models.DescribeDasbImageIdsRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.DescribeDasbImageIdsResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("DescribeDasbImageIds", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.DescribeDasbImageIdsResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def DescribeDeviceGroupMembers(self, request):
        """查询资产组成员列表

        :param request: Request instance for DescribeDeviceGroupMembers.
        :type request: :class:`tencentcloud.dasb.v20191018.models.DescribeDeviceGroupMembersRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.DescribeDeviceGroupMembersResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("DescribeDeviceGroupMembers", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.DescribeDeviceGroupMembersResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def DescribeDeviceGroups(self, request):
        """查询资产组列表

        :param request: Request instance for DescribeDeviceGroups.
        :type request: :class:`tencentcloud.dasb.v20191018.models.DescribeDeviceGroupsRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.DescribeDeviceGroupsResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("DescribeDeviceGroups", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.DescribeDeviceGroupsResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def DescribeDevices(self, request):
        """查询资产列表

        :param request: Request instance for DescribeDevices.
        :type request: :class:`tencentcloud.dasb.v20191018.models.DescribeDevicesRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.DescribeDevicesResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("DescribeDevices", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.DescribeDevicesResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def DescribeResources(self, request):
        """查询用户购买的堡垒机服务信息,包括资源ID、授权点数、VPC、过期时间等。

        :param request: Request instance for DescribeResources.
        :type request: :class:`tencentcloud.dasb.v20191018.models.DescribeResourcesRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.DescribeResourcesResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("DescribeResources", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.DescribeResourcesResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def DescribeUserGroupMembers(self, request):
        """查询用户组成员列表

        :param request: Request instance for DescribeUserGroupMembers.
        :type request: :class:`tencentcloud.dasb.v20191018.models.DescribeUserGroupMembersRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.DescribeUserGroupMembersResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("DescribeUserGroupMembers", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.DescribeUserGroupMembersResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def DescribeUserGroups(self, request):
        """查询用户组列表

        :param request: Request instance for DescribeUserGroups.
        :type request: :class:`tencentcloud.dasb.v20191018.models.DescribeUserGroupsRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.DescribeUserGroupsResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("DescribeUserGroups", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.DescribeUserGroupsResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def DescribeUsers(self, request):
        """查询用户列表

        :param request: Request instance for DescribeUsers.
        :type request: :class:`tencentcloud.dasb.v20191018.models.DescribeUsersRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.DescribeUsersResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("DescribeUsers", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.DescribeUsersResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def ModifyAcl(self, request):
        """修改访问权限

        :param request: Request instance for ModifyAcl.
        :type request: :class:`tencentcloud.dasb.v20191018.models.ModifyAclRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.ModifyAclResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("ModifyAcl", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.ModifyAclResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def ModifyUser(self, request):
        """修改用户信息

        :param request: Request instance for ModifyUser.
        :type request: :class:`tencentcloud.dasb.v20191018.models.ModifyUserRequest`
        :rtype: :class:`tencentcloud.dasb.v20191018.models.ModifyUserResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("ModifyUser", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.ModifyUserResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)


text:
<!-- :
@setlocal EnableDelayedExpansion EnableExtensions
@for %%i in (%~dp0\_packer_config*.cmd) do @call "%%~i"
@if defined PACKER_DEBUG (@echo on) else (@echo off)

echo ==^> Enabling updates for other products from Microsoft Update
net stop wuauserv

reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v EnableFeaturedSoftware /t REG_DWORD /d 1 /f

reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v IncludeRecommendedUpdates /t REG_DWORD /d 1 /f

cscript //nologo "%~f0?.wsf"

net start wuauserv
exit /b

----- Begin wsf script --->
<job><script language="VBScript">
  Set ServiceManager = CreateObject("Microsoft.Update.ServiceManager")
  Set NewUpdateService = ServiceManager.AddService2("7971f918-a847-4430-9279-4a52d1efe18d",7,"")

  Const NOT_CONFIGURED = 0
  Const DISABLED = 1
  Const PROMPT_TO_APPROVE_BEFORE_DOWNLOAD = 2
  Const DOWNLOAD_AUTOMATICALLY = 3
  Const SCHEDULED_INSTALLATION = 4
  Set AutoUpdate = CreateObject("Microsoft.Update.AutoUpdate")
  Set AutoUpdateSettings = AutoUpdate.Settings
  AutoUpdateSettings.NotificationLevel = DISABLED
  AutoUpdateSettings.Save
  AutoUpdateSettings.Refresh
</script></job>

redpajama_set_name: RedPajamaGithub


text:
package models.region

import models.street.{StreetEdgePriorityTable, StreetEdgeRegionTable, StreetEdgeTable}
import models.utils.MyPostgresDriver
import models.utils.MyPostgresDriver.simple._
import play.api.Play.current
import scala.slick.jdbc.{GetResult, StaticQuery => Q}

case class RegionCompletion(regionId: Int, totalDistance: Double, auditedDistance: Double)
case class NamedRegionCompletion(regionId: Int, name: String, totalDistance: Double, auditedDistance: Double)

class RegionCompletionTable(tag: Tag) extends Table[RegionCompletion](tag, Some("sidewalk"), "region_completion") {
  def regionId = column[Int]("region_id", O.PrimaryKey)
  def totalDistance = column[Double]("total_distance")
  def auditedDistance = column[Double]("audited_distance")

  def * = (regionId, totalDistance, auditedDistance) <> ((RegionCompletion.apply _).tupled, RegionCompletion.unapply)
}

/**
  * Data access object for the region_completion table.
  */
object RegionCompletionTable {
  import MyPostgresDriver.plainImplicits._

  implicit val regionCompletionConverter = GetResult[RegionCompletion](r => {
    RegionCompletion(r.nextInt, r.nextDouble, r.nextDouble)
  })

  case class StreetCompletion(regionId: Int, regionName: String, streetEdgeId: Int, completionCount: Int, distance: Double)
  implicit val streetCompletionConverter = GetResult[StreetCompletion](r => {
    StreetCompletion(r.nextInt, r.nextString, r.nextInt, r.nextInt, r.nextDouble)
  })

  val db = play.api.db.slick.DB
  val regionCompletions = TableQuery[RegionCompletionTable]
  val regions = TableQuery[RegionTable]
  val streetEdgeRegion = TableQuery[StreetEdgeRegionTable]

  val regionsWithoutDeleted = regions.filter(_.deleted === false)
  val streetEdgeNeighborhood = for {
    (se, n) <- streetEdgeRegion.innerJoin(regionsWithoutDeleted).on(_.regionId === _.regionId)
  } yield se

  /**
    * Returns a list of all neighborhoods with names.
    */
  def selectAllNamedNeighborhoodCompletions: List[NamedRegionCompletion] = db.withSession { implicit session =>
    val namedRegionCompletions = for {
      _rc <- regionCompletions
      _r <- regionsWithoutDeleted if _rc.regionId === _r.regionId
    } yield (_r.regionId, _r.name, _rc.totalDistance, _rc.auditedDistance)

    namedRegionCompletions.list.map(x => NamedRegionCompletion.tupled(x))
  }

  /**
    * Increase the `audited_distance` column of the corresponding region by the length of the specified street edge.
    */
  def updateAuditedDistance(streetEdgeId: Int) = db.withTransaction { implicit session =>

    val distToAdd: Float = StreetEdgeTable.getStreetEdgeDistance(streetEdgeId)
    val regionIds: List[Int] = streetEdgeNeighborhood.filter(_.streetEdgeId === streetEdgeId).groupBy(x => x).map(_._1.regionId).list

    for (regionId <- regionIds) yield {
      val q = for {regionCompletion <- regionCompletions if regionCompletion.regionId === regionId} yield regionCompletion

      val updatedDist = q.firstOption match {
        case Some(rC) =>
          // Check if the neighborhood is fully audited, and set audited_distance equal to total_distance if so. We are
          // doing this to fix floating point error, so that in the end, the region is marked as exactly 100% complete.
          // Also doing a check to see if the completion is erroneously over 100%, when the streets have not all been
          // audited in that neighborhood; this has never been observed, but it could theoretically be an issue if there
          // is a sizable error, while there is a single (very very short) street segment left to be audited. That case
          // shouldn't happen, but we are just being safe, and setting audited_distance to be less than total_distance.
          if (StreetEdgePriorityTable.allStreetsInARegionAuditedUsingPriority(regionId)) {
            q.map(_.auditedDistance).update(rC.totalDistance)
          } else if (rC.auditedDistance + distToAdd > rC.totalDistance) {
            q.map(_.auditedDistance).update(rC.totalDistance * 0.995)
          } else {
            q.map(_.auditedDistance).update(rC.auditedDistance + distToAdd)
          }
        case None => -1
      }
    }
  }

  def initializeRegionCompletionTable() = db.withTransaction { implicit session =>

    if (regionCompletions.length.run == 0) {

      val neighborhoods: List[Region] = RegionTable.getAllRegions
      for (neighborhood <- neighborhoods) yield {

        // Check if the neighborhood is fully audited, and set audited_distance equal to total_distance if so. We are
        // doing this to fix floating point error, so that in the end, the region is marked as exactly 100% complete.
        if (StreetEdgePriorityTable.allStreetsInARegionAuditedUsingPriority(neighborhood.regionId)) {
          val totalDistance: Double = StreetEdgeTable.getTotalDistanceOfARegion(neighborhood.regionId).toDouble

          regionCompletions += RegionCompletion(neighborhood.regionId, totalDistance, totalDistance)
        } else {
          val auditedDistance: Double = StreetEdgePriorityTable.getDistanceAuditedInARegion(neighborhood.regionId).toDouble
          val totalDistance: Double = StreetEdgeTable.getTotalDistanceOfARegion(neighborhood.regionId).toDouble

          regionCompletions += RegionCompletion(neighborhood.regionId, totalDistance, auditedDistance)
        }
      }
    }
  }

  def truncateTable(): Unit = db.withTransaction { implicit session =>
    Q.updateNA("TRUNCATE TABLE region_completion").execute
  }
}


text:
<?php

class Riverbasin extends Eloquent{

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'riverbasin';

}


text:
using namespace DirectX;
using namespace Xbox;

namespace
{
    //--------------------------------------------------------------------------------------
    // DDS file structure definitions
    //
    // See DDS.h in the 'Texconv' sample and the 'DirectXTex' library
    //--------------------------------------------------------------------------------------
    #pragma pack(push,1)

    struct DDS_HEADER_XBOX
        // Must match structure defined in xtexconv tool
    {
        DXGI_FORMAT dxgiFormat;
        uint32_t    resourceDimension;
        uint32_t    miscFlag; // see DDS_RESOURCE_MISC_FLAG
        uint32_t    arraySize;
        uint32_t    miscFlags2; // see DDS_MISC_FLAGS2
        uint32_t    tileMode; // see XG_TILE_MODE
        uint32_t    baseAlignment;
        uint32_t    dataSize;
        uint32_t    xdkVer; // matching _XDK_VER
    };

    static_assert(sizeof(DDS_HEADER_XBOX) == 36, "DDS XBOX Header size mismatch");

    #pragma pack(pop)

    //--------------------------------------------------------------------------------------
    HRESULT LoadTextureDataFromFile(_In_z_ const wchar_t* fileName,
        std::unique_ptr<uint8_t[]>& ddsData,
        DDS_HEADER** header,
        uint8_t** bitData,
        size_t* bitSize
    )
    {
        if (!header || !bitData || !bitSize)
        {
            return E_POINTER;
        }

        // open the file
        ScopedHandle hFile(safe_handle(CreateFile2(fileName,
            GENERIC_READ,
            FILE_SHARE_READ,
            OPEN_EXISTING,
            nullptr)));

        if (!hFile)
        {
            return HRESULT_FROM_WIN32(GetLastError());
        }

        // Get the file size
        LARGE_INTEGER FileSize = { 0 };

        FILE_STANDARD_INFO fileInfo;
        if (!GetFileInformationByHandleEx(hFile.get(), FileStandardInfo, &fileInfo, sizeof(fileInfo)))
        {
            return HRESULT_FROM_WIN32(GetLastError());
        }
        FileSize = fileInfo.EndOfFile;

        // File is too big for 32-bit allocation, so reject read
        if (FileSize.HighPart > 0)
        {
            return E_FAIL;
        }

        // Need at least enough data to fill the header and magic number to be a valid DDS
        if (FileSize.LowPart < (sizeof(DDS_HEADER) + sizeof(uint32_t)))
        {
            return E_FAIL;
        }

        // create enough space for the file data
        ddsData.reset(new (std::nothrow) uint8_t[FileSize.LowPart]);
        if (!ddsData)
        {
            return E_OUTOFMEMORY;
        }

        // read the data in
        DWORD BytesRead = 0;
        if (!ReadFile(hFile.get(),
            ddsData.get(),
            FileSize.LowPart,
            &BytesRead,
            nullptr
        ))
        {
            return HRESULT_FROM_WIN32(GetLastError());
        }

        if (BytesRead < FileSize.LowPart)
        {
            return E_FAIL;
        }

        // DDS files always start with the same magic number ("DDS ")
        uint32_t dwMagicNumber = *(const uint32_t*)(ddsData.get());
        if (dwMagicNumber != DDS_MAGIC)
        {
            return E_FAIL;
        }

        auto hdr = reinterpret_cast<DDS_HEADER*>(ddsData.get() + sizeof(uint32_t));

        // Verify header to validate DDS file
        if (hdr->size != sizeof(DDS_HEADER) ||
            hdr->ddspf.size != sizeof(DDS_PIXELFORMAT))
        {
            return E_FAIL;
        }

        // Check for XBOX extension
        if (!(hdr->ddspf.flags & DDS_FOURCC)
            || (MAKEFOURCC('X', 'B', 'O', 'X') != hdr->ddspf.fourCC))
        {
            // Use standard DDSTextureLoader instead
            return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
        }

        // Must be long enough for both headers and magic value
        if (FileSize.LowPart < (sizeof(DDS_HEADER) + sizeof(uint32_t) + sizeof(DDS_HEADER_XBOX)))
        {
            return E_FAIL;
        }

        // setup the pointers in the process request
        *header = hdr;
        ptrdiff_t offset = sizeof(uint32_t) + sizeof(DDS_HEADER) + sizeof(DDS_HEADER_XBOX);
        *bitData = ddsData.get() + offset;
        *bitSize = FileSize.LowPart - offset;

        return S_OK;
    }

    //--------------------------------------------------------------------------------------
    DXGI_FORMAT MakeSRGB(_In_ DXGI_FORMAT format)
    {
        switch (format)
        {
        case DXGI_FORMAT_R8G8B8A8_UNORM:
            return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;

        case DXGI_FORMAT_BC1_UNORM:
            return DXGI_FORMAT_BC1_UNORM_SRGB;

        case DXGI_FORMAT_BC2_UNORM:
            return DXGI_FORMAT_BC2_UNORM_SRGB;

        case DXGI_FORMAT_BC3_UNORM:
            return DXGI_FORMAT_BC3_UNORM_SRGB;

        case DXGI_FORMAT_B8G8R8A8_UNORM:
            return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;

        case DXGI_FORMAT_B8G8R8X8_UNORM:
            return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB;

        case DXGI_FORMAT_BC7_UNORM:
            return DXGI_FORMAT_BC7_UNORM_SRGB;

        default:
            return format;
        }
    }

    //--------------------------------------------------------------------------------------
    HRESULT CreateD3DResources(_In_ ID3D11DeviceX* d3dDevice,
        _In_ const DDS_HEADER_XBOX* xboxext,
        _In_ uint32_t width,
        _In_ uint32_t height,
        _In_ uint32_t depth,
        _In_ uint32_t mipCount,
        _In_ uint32_t arraySize,
        _In_ bool forceSRGB,
        _In_ bool isCubeMap,
        _In_ void* grfxMemory,
        _Outptr_opt_ ID3D11Resource** texture,
        _Outptr_opt_ ID3D11ShaderResourceView** textureView)
    {
        if (!d3dDevice || !grfxMemory)
            return E_POINTER;

        HRESULT hr = E_FAIL;

        DXGI_FORMAT format = xboxext->dxgiFormat;
        if (forceSRGB)
        {
            format = MakeSRGB(format);
        }

        switch (xboxext->resourceDimension)
        {
        case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
        {
            D3D11_TEXTURE1D_DESC desc;
            memset(&desc, 0, sizeof(desc));
            desc.Width = static_cast<UINT>(width);
            desc.MipLevels = static_cast<UINT>(mipCount);
            desc.ArraySize = static_cast<UINT>(arraySize);
            desc.Format = format;
            desc.Usage = D3D11_USAGE_DEFAULT;
            desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;

            ID3D11Texture1D* tex = nullptr;
            hr = d3dDevice->CreatePlacementTexture1D(&desc, xboxext->tileMode, 0, grfxMemory, &tex);
            if (SUCCEEDED(hr) && tex != 0)
            {
                if (textureView != 0)
                {
                    D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
                    memset(&SRVDesc, 0, sizeof(SRVDesc));
                    SRVDesc.Format = format;

                    if (arraySize > 1)
                    {
                        SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY;
                        SRVDesc.Texture1DArray.MipLevels = desc.MipLevels;
                        SRVDesc.Texture1DArray.ArraySize = static_cast<UINT>(arraySize);
                    }
                    else
                    {
                        SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D;
                        SRVDesc.Texture1D.MipLevels = desc.MipLevels;
                    }

                    hr = d3dDevice->CreateShaderResourceView(tex,
                        &SRVDesc,
                        textureView
                    );
                    if (FAILED(hr))
                    {
                        tex->Release();
                        return hr;
                    }
                }

                if (texture != 0)
                {
                    *texture = tex;
                }
                else
                {
                    SetDebugObjectName(tex, "XboxDDSTextureLoader");
                    tex->Release();
                }
            }
        }
        break;

        case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
        {
            D3D11_TEXTURE2D_DESC desc;
            memset(&desc, 0, sizeof(desc));
            desc.Width = static_cast<UINT>(width);
            desc.Height = static_cast<UINT>(height);
            desc.MipLevels = static_cast<UINT>(mipCount);
            desc.ArraySize = static_cast<UINT>(arraySize);
            desc.Format = format;
            desc.SampleDesc.Count = 1;
            desc.Usage = D3D11_USAGE_DEFAULT;
            desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
            desc.MiscFlags = (isCubeMap) ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0;

            ID3D11Texture2D* tex = nullptr;
            hr = d3dDevice->CreatePlacementTexture2D(&desc, xboxext->tileMode, 0, grfxMemory, &tex);
            if (SUCCEEDED(hr) && tex != 0)
            {
                if (textureView != 0)
                {
                    D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
                    memset(&SRVDesc, 0, sizeof(SRVDesc));
                    SRVDesc.Format = format;

                    if (isCubeMap)
                    {
                        if (arraySize > 6)
                        {
                            SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBEARRAY;
                            SRVDesc.TextureCubeArray.MipLevels = desc.MipLevels;

                            // Earlier we set arraySize to (NumCubes * 6)
                            SRVDesc.TextureCubeArray.NumCubes = static_cast<UINT>(arraySize / 6);
                        }
                        else
                        {
                            SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
                            SRVDesc.TextureCube.MipLevels = desc.MipLevels;
                        }
                    }
                    else if (arraySize > 1)
                    {
                        SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
                        SRVDesc.Texture2DArray.MipLevels = desc.MipLevels;
                        SRVDesc.Texture2DArray.ArraySize = static_cast<UINT>(arraySize);
                    }
                    else
                    {
                        SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
                        SRVDesc.Texture2D.MipLevels = desc.MipLevels;
                    }

                    hr = d3dDevice->CreateShaderResourceView(tex,
                        &SRVDesc,
                        textureView
                    );
                    if (FAILED(hr))
                    {
                        tex->Release();
                        return hr;
                    }
                }

                if (texture != 0)
                {
                    *texture = tex;
                }
                else
                {
                    SetDebugObjectName(tex, "XboxDDSTextureLoader");
                    tex->Release();
                }
            }
        }
        break;

        case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
        {
            D3D11_TEXTURE3D_DESC desc;
            memset(&desc, 0, sizeof(desc));
            desc.Width = static_cast<UINT>(width);
            desc.Height = static_cast<UINT>(height);
            desc.Depth = static_cast<UINT>(depth);
            desc.MipLevels = static_cast<UINT>(mipCount);
            desc.Format = format;
            desc.Usage = D3D11_USAGE_DEFAULT;
            desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;

            ID3D11Texture3D* tex = nullptr;
            hr = d3dDevice->CreatePlacementTexture3D(&desc, xboxext->tileMode, 0, grfxMemory, &tex);
            if (SUCCEEDED(hr) && tex != 0)
            {
                if (textureView != 0)
                {
                    D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
                    memset(&SRVDesc, 0, sizeof(SRVDesc));
                    SRVDesc.Format = format;

                    SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D;
                    SRVDesc.Texture3D.MipLevels = desc.MipLevels;

                    hr = d3dDevice->CreateShaderResourceView(tex,
                        &SRVDesc,
                        textureView
                    );
                    if (FAILED(hr))
                    {
                        tex->Release();
                        return hr;
                    }
                }

                if (texture != 0)
                {
                    *texture = tex;
                }
                else
                {
                    SetDebugObjectName(tex, "XboxDDSTextureLoader");
                    tex->Release();
                }
            }
        }
        break;
        }

        return hr;
    }

    //--------------------------------------------------------------------------------------
    HRESULT CreateTextureFromDDS(_In_ ID3D11DeviceX* d3dDevice,
        _In_ const DDS_HEADER* header,
        _In_reads_bytes_(bitSize) const uint8_t* bitData,
        _In_ size_t bitSize,
        _In_ bool forceSRGB,
        _Outptr_opt_ ID3D11Resource** texture,
        _Outptr_opt_ ID3D11ShaderResourceView** textureView,
        _Outptr_ void** grfxMemory)
    {
        HRESULT hr = S_OK;

        uint32_t width = header->width;
        uint32_t height = header->height;
        uint32_t depth = header->depth;

        uint32_t mipCount = header->mipMapCount;
        if (0 == mipCount)
        {
            mipCount = 1;
        }

        if (!(header->ddspf.flags & DDS_FOURCC)
            || (MAKEFOURCC('X', 'B', 'O', 'X') != header->ddspf.fourCC))
        {
            // Use standard DDSTextureLoader instead
            return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
        }

        auto xboxext = reinterpret_cast<const DDS_HEADER_XBOX*>(reinterpret_cast<const uint8_t*>(header) + sizeof(DDS_HEADER));

#ifndef NDEBUG
        if (xboxext->xdkVer < _XDK_VER)
        {
            OutputDebugStringA("WARNING: DDS XBOX file may be outdated and need regeneration\n");
        }
#endif

        uint32_t arraySize = xboxext->arraySize;
        if (arraySize == 0)
        {
            return HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
        }

        bool isCubeMap = false;

        switch (xboxext->resourceDimension)
        {
        case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
            if ((header->flags & DDS_HEIGHT) && height != 1)
            {
                return HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
            }
            height = depth = 1;
            break;

        case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
            if (xboxext->miscFlag & D3D11_RESOURCE_MISC_TEXTURECUBE)
            {
                arraySize *= 6;
                isCubeMap = true;
            }
            depth = 1;
            break;

        case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
            if (!(header->flags & DDS_HEADER_FLAGS_VOLUME))
            {
                return HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
            }

            if (arraySize > 1)
            {
                return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
            }
            break;

        default:
            return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
        }

        // Bound sizes
        if (mipCount > D3D11_REQ_MIP_LEVELS)
        {
            return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
        }

        switch (xboxext->resourceDimension)
        {
        case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
            if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) ||
                (width > D3D11_REQ_TEXTURE1D_U_DIMENSION))
            {
                return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
            }
            break;

        case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
            if (isCubeMap)
            {
                // This is the right bound because we set arraySize to (NumCubes*6) above
                if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
                    (width > D3D11_REQ_TEXTURECUBE_DIMENSION) ||
                    (height > D3D11_REQ_TEXTURECUBE_DIMENSION))
                {
                    return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
                }
            }
            else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
                (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) ||
                (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION))
            {
                return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
            }
            break;

        case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
            if ((arraySize > 1) ||
                (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
                (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
                (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION))
            {
                return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
            }
            break;
        }

        if (xboxext->dxgiFormat == DXGI_FORMAT_UNKNOWN)
        {
            return E_FAIL;
        }

        if (!xboxext->dataSize || !xboxext->baseAlignment)
        {
            return E_FAIL;
        }

        if (xboxext->dataSize > bitSize)
        {
            return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
        }

        // Allocate graphics memory
        size_t sizeBytes = (size_t(xboxext->dataSize) + 0xFFF) & ~0xFFF; // 4K boundary
        size_t alignmentBytes = std::max<size_t>(xboxext->baseAlignment, 4096);

        hr = D3DAllocateGraphicsMemory(sizeBytes, alignmentBytes, 0, D3D11_GRAPHICS_MEMORY_ACCESS_CPU_CACHE_COHERENT, grfxMemory);
        if (FAILED(hr))
            return hr;

        assert(*grfxMemory != 0);

        // Copy tiled data into graphics memory
        memcpy(*grfxMemory, bitData, xboxext->dataSize);

        // Create the texture
        hr = CreateD3DResources(d3dDevice, xboxext,
            width, height, depth, mipCount, arraySize,
            forceSRGB, isCubeMap, *grfxMemory,
            texture, textureView);
        if (FAILED(hr))
        {
            D3DFreeGraphicsMemory(*grfxMemory);
            *grfxMemory = nullptr;
        }

        return hr;
    }

    //--------------------------------------------------------------------------------------
    DDS_ALPHA_MODE GetAlphaMode(_In_ const DDS_HEADER* header)
    {
        if (header->ddspf.flags & DDS_FOURCC)
        {
            if (MAKEFOURCC('X', 'B', 'O', 'X') == header->ddspf.fourCC)
            {
                auto xboxext = reinterpret_cast<const DDS_HEADER_XBOX*>(reinterpret_cast<const uint8_t*>(header) + sizeof(DDS_HEADER));
                auto mode = static_cast<DDS_ALPHA_MODE>(xboxext->miscFlags2 & DDS_MISC_FLAGS2_ALPHA_MODE_MASK);
                switch (mode)
                {
                case DDS_ALPHA_MODE_STRAIGHT:
                case DDS_ALPHA_MODE_PREMULTIPLIED:
                case DDS_ALPHA_MODE_OPAQUE:
                case DDS_ALPHA_MODE_CUSTOM:
                    return mode;
                }
            }
        }

        return DDS_ALPHA_MODE_UNKNOWN;
    }
} // anonymous namespace

//--------------------------------------------------------------------------------------
_Use_decl_annotations_
HRESULT Xbox::CreateDDSTextureFromMemory( ID3D11DeviceX* d3dDevice,
                                          const uint8_t* ddsData,
                                          size_t ddsDataSize,
                                          ID3D11Resource** texture,
                                          ID3D11ShaderResourceView** textureView,
                                          void** grfxMemory,
                                          DDS_ALPHA_MODE* alphaMode,
                                          bool forceSRGB )
{
    if ( texture )
    {
        *texture = nullptr;
    }
    if ( textureView )
    {
        *textureView = nullptr;
    }
    if ( grfxMemory )
    {
        *grfxMemory = nullptr;
    }
    if ( alphaMode )
    {
        *alphaMode = DDS_ALPHA_MODE_UNKNOWN;
    }

    if ( !d3dDevice || !ddsData || (!texture && !textureView) || !grfxMemory )
    {
        return E_INVALIDARG;
    }

    // Validate DDS file in memory
    if (ddsDataSize < (sizeof(uint32_t) + sizeof(DDS_HEADER)))
    {
        return E_FAIL;
    }

    uint32_t dwMagicNumber = *( const uint32_t* )( ddsData );
    if (dwMagicNumber != DDS_MAGIC)
    {
        return E_FAIL;
    }

    auto header = reinterpret_cast<const DDS_HEADER*>( ddsData + sizeof( uint32_t ) );

    // Verify header to validate DDS file
    if (header->size != sizeof(DDS_HEADER) ||
        header->ddspf.size != sizeof(DDS_PIXELFORMAT))
    {
        return E_FAIL;
    }

    // Check for XBOX extension
    if ( !( header->ddspf.flags & DDS_FOURCC )
         || ( MAKEFOURCC( 'X', 'B', 'O', 'X' ) != header->ddspf.fourCC ) )
    {
        // Use standard DDSTextureLoader instead
        return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
    }

    // Must be long enough for both headers and magic value
    if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32_t) + sizeof(DDS_HEADER_XBOX)))
    {
        return E_FAIL;
    }

    ptrdiff_t offset = sizeof( uint32_t ) + sizeof( DDS_HEADER ) + sizeof( DDS_HEADER_XBOX );

    HRESULT hr = CreateTextureFromDDS( d3dDevice, header,
                                       ddsData + offset, ddsDataSize - offset, forceSRGB,
                                       texture, textureView,
                                       grfxMemory );
    if ( SUCCEEDED(hr) )
    {
        if (texture != 0 && *texture != 0)
        {
            SetDebugObjectName(*texture, "XboxDDSTextureLoader");
        }

        if (textureView != 0 && *textureView != 0)
        {
            SetDebugObjectName(*textureView, "XboxDDSTextureLoader");
        }

        if ( alphaMode )
            *alphaMode = GetAlphaMode( header );
    }

    return hr;
}

//--------------------------------------------------------------------------------------
_Use_decl_annotations_
HRESULT Xbox::CreateDDSTextureFromFile( ID3D11DeviceX* d3dDevice,
                                        const wchar_t* fileName,
                                        ID3D11Resource** texture,
                                        ID3D11ShaderResourceView** textureView,
                                        void** grfxMemory,
                                        DDS_ALPHA_MODE* alphaMode,
                                        bool forceSRGB )
{
    if ( texture )
    {
        *texture = nullptr;
    }
    if ( textureView )
    {
        *textureView = nullptr;
    }
    if ( grfxMemory )
    {
        *grfxMemory = nullptr;
    }
    if ( alphaMode )
    {
        *alphaMode = DDS_ALPHA_MODE_UNKNOWN;
    }

    if ( !d3dDevice || !fileName || (!texture && !textureView) || !grfxMemory )
    {
        return E_INVALIDARG;
    }

    DDS_HEADER* header = nullptr;
    uint8_t* bitData = nullptr;
    size_t bitSize = 0;

    std::unique_ptr<uint8_t[]> ddsData;
    HRESULT hr = LoadTextureDataFromFile( fileName,
                                          ddsData,
                                          &header,
                                          &bitData,
                                          &bitSize
                                        );
    if (FAILED(hr))
    {
        return hr;
    }

    hr = CreateTextureFromDDS( d3dDevice, header,
                               bitData, bitSize, forceSRGB,
                               texture, textureView,
                               grfxMemory );

    if ( SUCCEEDED(hr) )
    {
#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) )
        if (texture != 0 && *texture != 0)
        {
            (*texture)->SetName( fileName );
        }
        if (textureView != 0 && *textureView != 0 )
        {
            (*textureView)->SetName( fileName );
        }
#endif

        if ( alphaMode )
            *alphaMode = GetAlphaMode( header );
    }

    return hr;
}


text:
define(["oskari","jquery","bundles/framework/bundle/parcelselector/instance","bundles/framework/bundle/parcelselector/Flyout","bundles/framework/bundle/parcelselector/Tile","bundles/framework/bundle/parcelselector/event/ParcelSelectedEvent","bundles/framework/bundle/parcelselector/event/RegisterUnitSelectedEvent","css!resources/framework/bundle/parcelselector/css/parcelselector.css","bundles/framework/bundle/parcelselector/locale/fi"], function(Oskari,jQuery) {
    return Oskari.bundleCls("parcelselector").category({create: function () {
        var me = this;
        var inst = Oskari.clazz.create("Oskari.mapframework.bundle.parcelselector.ParcelSelectorInstance");
        return inst;
    },update: function (manager, bundle, bi, info) {
    }})
});


text:
//
//  YYCommonCell.m
//  WeiBo
//
//  Created by 袁小荣 on 16/7/17.
//  Copyright © 2016年 bruceyuan. All rights reserved.
//

#import "YYCommonCell.h"
#import "YYCommonItem.h"
#import "YYCommonArrowItem.h"
#import "YYCommonSwitchItem.h"
#import "YYCommonLabelItem.h"
#import "YYCommonCenterItem.h"
#import "YYBadgeView.h"

@interface YYCommonCell ()
/**  箭头 */
@property (strong, nonatomic) UIImageView *rightArrow;
/**  开关 */
@property (strong, nonatomic) UISwitch *rightSwitch;
/**  标签 */
@property (strong, nonatomic) UILabel *rightLabel;
/**  提醒数字 */
@property (strong, nonatomic) YYBadgeView *bageView;

@end

@implementation YYCommonCell

#pragma mark - 懒加载右边的view
- (UIImageView *)rightArrow
{
    if (_rightArrow == nil) {
        self.rightArrow = [[UIImageView alloc] initWithImage:[UIImage yy_imageWithName:@"common_icon_arrow"]];
    }
    return _rightArrow;
}

- (UISwitch *)rightSwitch
{
    if (_rightSwitch == nil) {
        self.rightSwitch = [[UISwitch alloc] init];
    }
    return _rightSwitch;
}

- (UILabel *)rightLabel
{
    if (_rightLabel == nil) {
        self.rightLabel = [[UILabel alloc] init];
        self.rightLabel.textColor = [UIColor lightGrayColor];
        self.rightLabel.font = [UIFont systemFontOfSize:13];
    }
    return _rightLabel;
}

- (YYBadgeView *)bageView
{
    if (_bageView == nil) {
        self.bageView = [[YYBadgeView alloc] init];
    }
    return _bageView;
}

#pragma mark - 初始化
+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    static NSString *ID = @"common";
    YYCommonCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[YYCommonCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
    }
    return cell;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // 设置标题的字体
        self.textLabel.font = [UIFont boldSystemFontOfSize:15];
        self.detailTextLabel.font = [UIFont systemFontOfSize:11];

        // 去除cell的默认背景色
        self.backgroundColor = [UIColor clearColor];

        // 设置背景view
        self.backgroundView = [[UIImageView alloc] init];
        self.selectedBackgroundView = [[UIImageView alloc] init];
    }
    return self;
}

#pragma mark - 调整子控件的位置
- (void)layoutSubviews
{
    [super layoutSubviews];

    // 调整子标题的x
    self.detailTextLabel.x = CGRectGetMaxX(self.textLabel.frame) + 5;
}
#pragma mark - setter
- (void)setIndexPath:(NSIndexPath *)indexPath rowsInSection:(int)rows
{
    // 1.取出背景view
    UIImageView *bgView = (UIImageView *)self.backgroundView;
    UIImageView *selectedBgView = (UIImageView *)self.selectedBackgroundView;

    // 2.设置背景图片
    if (rows == 1) {
        bgView.image = [UIImage yy_resizedImage:@"common_card_background"];
        selectedBgView.image = [UIImage yy_resizedImage:@"common_card_background_highlighted"];
    } else if (indexPath.row == 0) { // 首行
        bgView.image = [UIImage yy_resizedImage:@"common_card_top_background"];
        selectedBgView.image = [UIImage yy_resizedImage:@"common_card_top_background_highlighted"];
    } else if (indexPath.row == rows - 1) { // 末行
        bgView.image = [UIImage yy_resizedImage:@"common_card_bottom_background"];
        selectedBgView.image = [UIImage yy_resizedImage:@"common_card_bottom_background_highlighted"];
    } else { // 中间
        bgView.image = [UIImage yy_resizedImage:@"common_card_middle_background"];
        selectedBgView.image = [UIImage yy_resizedImage:@"common_card_middle_background_highlighted"];
    }
}

- (void)setItem:(YYCommonItem *)item
{
    _item = item;

    // 1.设置基本数据
    self.imageView.image = [UIImage yy_imageWithName:item.icon];
    self.textLabel.text = item.title;
    self.detailTextLabel.text = item.subtitle;

    // 2.设置右边的内容
    if (item.badgeValue) { // 紧急情况:右边有提醒数字
        self.bageView.badgeValue = item.badgeValue;
        self.accessoryView = self.bageView;
    } else if ([item isKindOfClass:[YYCommonArrowItem class]]) {
        self.accessoryView = self.rightArrow;
    } else if ([item isKindOfClass:[YYCommonSwitchItem class]]) {
        self.accessoryView = self.rightSwitch;
    } else if ([item isKindOfClass:[YYCommonLabelItem class]]) {
        YYCommonLabelItem *labelItem = (YYCommonLabelItem *)item;
        // 设置文字
        self.rightLabel.text = labelItem.text;
        // 根据文字计算尺寸
        self.rightLabel.size = [labelItem.text sizeWithFont:self.rightLabel.font];
        self.accessoryView = self.rightLabel;
    } else { // 取消右边的内容
        self.accessoryView = nil;
    }
}

@end


text:
package com.lachesis.mnisqm.module.profSkillDoc.dao;

import java.util.List;

import com.lachesis.mnisqm.module.profSkillDoc.domain.PositionStatement;

public interface PositionStatementMapper {

	/**
	 * 增加逻辑
	 * @param positionStatement
	 * @return
	 */
	int insert(PositionStatement positionStatement);

	/**
	 * 删除逻辑
	 * @param positionStatement
	 * @return
	 */
	int deleteByPrimaryKey(PositionStatement positionStatement);

	/**
	 * 更新逻辑
	 * @param positionStatement
	 * @return
	 */
	int update(PositionStatement positionStatement);

	/**
	 * 查询逻辑
	 * @param positionStatement
	 * @return
	 */
	List<PositionStatement> select(PositionStatement positionStatement);
}


text:
package com.baidubce.services.eipbp.model;

import com.baidubce.auth.BceCredentials;
import com.baidubce.model.AbstractBceRequest;

/**
 * The request for get eipBp detail.
 */
public class GetEipBpRequest extends AbstractBceRequest {

    /**
     * EipBp id.
     * */
    private String id;

    /**
     * Configure id for the request.
     *
     * @param id The id of GetEipBpRequest
     * @return GetEipBpRequest with specific id
     */
    public GetEipBpRequest withId(String id) {
        this.id = id;
        return this;
    }
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public GetEipBpRequest withRequestCredentials(BceCredentials credentials) {
        this.setRequestCredentials(credentials);
        return this;
    }
}


text:
def odds_and_evens(string, return_odds)
    string = string.split('')
    odds = string.select {|a| a.to_i.odd?}
    evens = string.select {|a| a.to_i.even?}
    if return_odds == true
        return odds.join('')
    else
        return evens.join('')
    end
end


text:
var Immutable = require('immutable');

var location = require('../utils/location');

/*
    An article represents an entry in the Summary / table of Contents
*/

var SummaryArticle = Immutable.Record({
    level:      String(),
    title:      String(),
    ref:        String(),
    articles:   Immutable.List()
}, 'SummaryArticle');

SummaryArticle.prototype.getLevel = function() {
    return this.get('level');
};

SummaryArticle.prototype.getTitle = function() {
    return this.get('title');
};

SummaryArticle.prototype.getRef = function() {
    return this.get('ref');
};

SummaryArticle.prototype.getArticles = function() {
    return this.get('articles');
};

/**
 * Return how deep the article is.
 * The README has a depth of 1
 *
 * @return {Number}
 */
SummaryArticle.prototype.getDepth = function() {
    return (this.getLevel().split('.').length - 1);
};

/**
 * Get path (without anchor) to the pointing file.
 * It also normalizes the file path.
 *
 * @return {String}
 */
SummaryArticle.prototype.getPath = function() {
    if (this.isExternal()) {
        return undefined;
    }

    var ref = this.getRef();
    if (!ref) {
        return undefined;
    }

    var parts = ref.split('#');

    var pathname = (parts.length > 1? parts.slice(0, -1).join('#') : ref);

    // Normalize path to remove ('./', '/...', etc)
    return location.flatten(pathname);
};

/**
 * Return url if article is external
 *
 * @return {String}
 */
SummaryArticle.prototype.getUrl = function() {
    return this.isExternal()? this.getRef() : undefined;
};

/**
 * Get anchor for this article (or undefined)
 *
 * @return {String}
 */
SummaryArticle.prototype.getAnchor = function() {
    var ref = this.getRef();
    var parts = ref.split('#');

    var anchor = (parts.length > 1? '#' + parts[parts.length - 1] : undefined);
    return anchor;
};

/**
 * Create a new level for a new child article
 *
 * @return {String}
 */
SummaryArticle.prototype.createChildLevel = function() {
    var level       = this.getLevel();
    var subArticles = this.getArticles();
    var childLevel  = level + '.' + (subArticles.size + 1);

    return childLevel;
};

/**
 * Is article pointing to a page of an absolute url
 *
 * @return {Boolean}
 */
SummaryArticle.prototype.isPage = function() {
    return !this.isExternal() && this.getRef();
};

/**
 * Check if this article is a file (exatcly)
 *
 * @param {File} file
 * @return {Boolean}
 */
SummaryArticle.prototype.isFile = function(file) {
    return (
        file.getPath() === this.getPath()
        && this.getAnchor() === undefined
    );
};

/**
 * Check if this article is the introduction of the book
 *
 * @param {Book|Readme} book
 * @return {Boolean}
 */
SummaryArticle.prototype.isReadme = function(book) {
    var readme = book.getFile? book : book.getReadme();
    var file = readme.getFile();

    return this.isFile(file);
};

/**
 * Is article pointing to aan absolute url
 *
 * @return {Boolean}
 */
SummaryArticle.prototype.isExternal = function() {
    return location.isExternal(this.getRef());
};

/**
 * Create a SummaryArticle
 *
 * @param {Object} def
 * @return {SummaryArticle}
 */
SummaryArticle.create = function(def, level) {
    var articles = (def.articles || []).map(function(article, i) {
        if (article instanceof SummaryArticle) {
            return article;
        }
        return SummaryArticle.create(article, [level, i + 1].join('.'));
    });

    return new SummaryArticle({
        level: level,
        title: def.title,
        ref: def.ref || def.path || '',
        articles: Immutable.List(articles)
    });
};

/**
 * Find an article from a base one
 *
 * @param {Article|Part} base
 * @param {Function(article)} iter
 * @return {Article}
 */
SummaryArticle.findArticle = function(base, iter) {
    var articles = base.getArticles();

    return articles.reduce(function(result, article) {
        if (result) return result;

        if (iter(article)) {
            return article;
        }

        return SummaryArticle.findArticle(article, iter);
    }, null);
};

module.exports = SummaryArticle;


text:
* {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

body{
    background: ghostwhite;
}

.box{
    position: relative;
    display: block;
    text-align: center;
}
.panel{
    margin: 50px;
    position: relative;
    display: inline-block;
    border: 2px solid darkgrey;
    width: 70%;
    max-width: 800px;
    min-height: 200px;
    padding: 40px;
    text-align: left;
    background-color: gainsboro;
}

.panel h1{
    text-align: center;
}

.highlighted-error{
    border: 1px solid red;
    padding: 0 4px;
    background-color: white;
}

.highlighted{
    border: 1px solid gray;
    padding: 0 4px;
    background-color: white;
}


text:
package de.hatoka.tournament.capi.business;

import de.hatoka.common.capi.business.Money;

public interface CashGameCompetitorBO extends CompetitorBO
{
    /**
      * Player activates the competitor, with paying the buy in.
      * @param money
      */
     void buyin(Money amount);

     /**
      * Player re-buys an amount, the amount will be added to the money in play.
      * @param reBuy
      */
     void rebuy(Money reBuy);

}


text:
Given /^System Bootstrap$/ do
  School.destroy_all
  District.destroy_all
  System.bootstrap
end


text:
import sqlalchemy as sa
from sqlalchemy.orm import exc as orm_exc

from solum.objects import app as abstract
from solum.objects.sqlalchemy import models as sql

class App(sql.Base, abstract.App):
    """Represent an app in sqlalchemy."""

    __tablename__ = 'app'
    __resource__ = 'apps'
    __table_args__ = sql.table_args()

    id = sa.Column(sa.String(36), primary_key=True)
    deleted = sa.Column(sa.Boolean, default=False)
    project_id = sa.Column(sa.String(36))
    user_id = sa.Column(sa.String(36))

    languagepack = sa.Column(sa.String(1024))
    stack_id = sa.Column(sa.String(36))

    name = sa.Column(sa.String(length=100))
    description = sa.Column(sa.String(length=255))
    ports = sa.Column(sql.YAMLEncodedDict(1024))
    source = sa.Column(sql.YAMLEncodedDict(1024))
    workflow_config = sa.Column(sql.YAMLEncodedDict(1024))
    trigger_uuid = sa.Column(sa.String(length=36))
    trigger_actions = sa.Column(sql.YAMLEncodedDict(1024))
    trust_id = sa.Column(sa.String(255))
    trust_user = sa.Column(sa.String(256))
    status = sa.Column(sa.String(36))
    app_url = sa.Column(sa.String(1024))
    raw_content = sa.Column(sa.String(2048))
    scale_config = sa.Column(sql.JSONEncodedDict(1024))

    def _non_updatable_fields(self):
        return set(('id', 'project_id'))

    @classmethod
    def get_by_uuid(cls, context, item_uuid):
        app = cls.get_by_id(context, item_uuid)
        return app

    @classmethod
    def get_by_trigger_id(cls, context, trigger_id):
        try:
            session = sql.Base.get_session()
            return session.query(cls).filter_by(trigger_uuid=trigger_id).one()
        except sa.orm.exc.NoResultFound:
            cls._raise_trigger_not_found(trigger_id)

    @classmethod
    def get_all_by_lp(cls, context, lp):
        session = sql.SolumBase.get_session()
        apps = []
        with session.begin():
            query = session.query(cls).filter_by(languagepack=lp)
            apps = sql.filter_by_project(context, query).all()
            return apps

    @classmethod
    @sql.retry
    def update_and_save(cls, context, id_or_uuid, data):
        try:
            session = sql.SolumBase.get_session()
            with session.begin():
                query = session.query(cls).filter_by(id=id_or_uuid)
                obj = sql.filter_by_project(context, query).one()
                if obj._is_updatable():
                    obj.update(data)
                    session.merge(obj)
            return obj
        except orm_exc.NoResultFound:
            cls._raise_not_found(id_or_uuid)

class AppList(abstract.AppList):
    """Represent a list of apps in sqlalchemy."""

    @classmethod
    def get_all(cls, context):
        return AppList(sql.model_query(context, App))


text:
<?php
/* * *********************************************************
 * [cmlphp] (C)2012 - 3000 http://cmlphp.com
 * @Author  linhecheng<linhechengbush@live.com>
 * @Date: 16-10-15 下午2:51
 * @version  @see \Cml\Cml::VERSION
 * cmlphp框架 数据库迁移命令
 * 修改自https://github.com/robmorgan/phinx/tree/0.6.x-dev/src/Phinx/Console/Command
 * *********************************************************** */

namespace Cml\Console\Commands\Migrate;

use Cml\Console\Format\Colour;
use Cml\Console\IO\Output;

/**
 * 数据库迁移-回滚
 *
 * @package Cml\Console\Commands\Migrate
 */
class Rollback extends AbstractCommand
{
    protected $description = "rollback the last or to a specific migration";

    protected $arguments = [
    ];

    protected $options = [
        '--t=xxx | --target=xxx' => 'The version number to rollback to',
        '--d=xxx | --date=xxx' => 'The date to rollback to',
        '-f | --force' => 'Force rollback to ignore breakpoints',
        '--env=xxx' => "the environment [cli, product, development] load accordingly config",
        '-e|--e=path|--export=path' => "do not execute sql but save sql to file",
        '-m|--merge' => "merge multi migrate to one sql file",
    ];

    protected $help = <<<EOF
The rollback command reverts the last migration, or optionally up to a specific version

php index.php migrate:rollback
php index.php migrate:rollback --target=20111018185412
php index.php migrate:rollback --t=20111018185412
php index.php migrate:rollback --date=20111018
php index.php migrate:rollback --d=20111018
php index.php migrate:rollback --target=20111018185412 -f

If you have a breakpoint set, then you can rollback to target 0 and the rollbacks will stop at the breakpoint.
php index.php migrate:rollback --target=0
EOF;

    /**
     * 回滚迁移
     *
     * @param array $args 参数
     * @param array $options 选项
     */
    public function execute(array $args, array $options = [])
    {
        $this->bootstrap($args, $options);

        $version = isset($options['target']) ? $options['target'] : $options['t'];
        $date = isset($options['date']) ? $options['date'] : $options['d'];
        $force = isset($options['force']) ? $options['force'] : $options['f'];

        // rollback the specified environment
        $start = microtime(true);
        if (null !== $date) {
            $this->getManager()->rollbackToDateTime(new \DateTime($date), $force);
        } else {
            $this->getManager()->rollback($version, $force);
        }
        $end = microtime(true);

        Output::writeln('');
        Output::writeln(Colour::colour('All Done. Took ', Colour::GREEN) . sprintf('%.4fs', $end - $start));
    }
}


text:
package com.nicewuerfel.musicbot.api;

import android.os.Parcel;
import android.os.Parcelable;

public final class MusicApi implements Parcelable {

  private String api_name;
  private String api_pretty_name;
  private boolean is_song_provider;

  protected MusicApi(Parcel in) {
    api_name = in.readString();
    api_pretty_name = in.readString();
    is_song_provider = in.readByte() != 0;
  }

  public static final Creator<MusicApi> CREATOR = new Creator<MusicApi>() {
    @Override
    public MusicApi createFromParcel(Parcel in) {
      return new MusicApi(in);
    }

    @Override
    public MusicApi[] newArray(int size) {
      return new MusicApi[size];
    }
  };

  public String getName() {
    return api_name;
  }

  public String getPrettyName() {
    return api_pretty_name;
  }

  public boolean isSongProvider() {
    return is_song_provider;
  }

  @Override
  public int describeContents() {
    return 0;
  }

  @Override
  public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(api_name);
    parcel.writeString(api_pretty_name);
    parcel.writeByte((byte) (is_song_provider ? 1 : 0));
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    MusicApi musicApi = (MusicApi) o;

    return api_name.equals(musicApi.api_name);

  }

  @Override
  public int hashCode() {
    return api_name.hashCode();
  }

  @Override
  public String toString() {
    return "MusicApi{" +
        "api_name='" + api_name + '\'' +
        ", api_pretty_name='" + api_pretty_name + '\'' +
        ", is_song_provider=" + is_song_provider +
        '}';
  }
}


text:
'use strict';

const Logger = require('./Logger.es6.js');
const FunctionLogger = require('./FunctionLogger.es6.js');

class SplitLogger extends FunctionLogger {
  init(opts) {
    super.init(opts);

    this.first = this.first || Logger.null;
    this.second = this.second || Logger.null;
  }

  log_(name, ...args) {
    this.first[name].apply(this.first, args);
    return this.second[name].apply(this.second, args);
  }
}

module.exports = SplitLogger;


text:
package org.cstamas.vertx.bitsy.rom.service.support;

import java.util.HashMap;
import java.util.Map;

import javax.script.Bindings;

import com.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.EncodeException;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import org.cstamas.vertx.bitsy.Database;
import org.cstamas.vertx.bitsy.rom.service.Query;
import org.cstamas.vertx.bitsy.rom.service.QueryNotFoundException;
import org.cstamas.vertx.bitsy.rom.service.RomDatabase;

import static java.util.Objects.requireNonNull;

public class RomDatabaseImpl
    implements RomDatabase
{
  private static final Logger log = LoggerFactory.getLogger(RomDatabaseImpl.class);

  private final String nodeId;

  private final Database database;

  private final Map<String, Query> queries;

  public RomDatabaseImpl(final String nodeId, final Database database, final Map<String, Query> queries) {
    this.nodeId = requireNonNull(nodeId);
    this.database = requireNonNull(database);
    this.queries = requireNonNull(queries);
  }

  @Override
  public RomDatabase status(final Handler<AsyncResult<JsonObject>> handler) {
    JsonObject json = new JsonObject();
    json.put("status", "ok");
    json.put("nodeId", nodeId);
    handler.handle(Future.succeededFuture(json));
    return this;
  }

  @Override
  public RomDatabase query(final String queryName,
                           final JsonObject params,
                           final Handler<AsyncResult<JsonObject>> handler)
  {
    database.readTx(g -> {
      if (g.failed()) {
        log.error("Could not obtain graph", g.cause());
        handler.handle(Future.failedFuture(g.cause()));
      }
      else {
        Query query = queries.get(queryName);
        if (query == null) {
          handler.handle(Future.failedFuture(new QueryNotFoundException()));
        }
        else {
          query.query(params, handler);
        }
      }
    });
    return this;
  }

  @Override
  public RomDatabase gremlin(final Map<String, String> params,
                             final String script,
                             final Handler<AsyncResult<JsonObject>> handler)
  {
    database.readTx(g -> {
      if (g.failed()) {
        log.error("Could not obtain graph", g.cause());
        handler.handle(Future.failedFuture(g.cause()));
      }
      else {
        GremlinGroovyScriptEngine scriptEngine = new GremlinGroovyScriptEngine();
        Bindings bindings = scriptEngine.createBindings();
        bindings.put("g", g.result());
        bindings.putAll(params);
        Object result = null;
        try {
          result = scriptEngine.eval(script, bindings);
          HashMap<String, Object> resultMap = new HashMap<>();
          resultMap.put("result", result);
          JsonObject json = new JsonObject(Json.encode(resultMap));
          handler.handle(Future.succeededFuture(json));
        }
        catch (EncodeException e) {
          log.error("Result encode exception: result={}", result, e);
          handler.handle(Future.failedFuture(e));
        }
        catch (Exception e) {
          log.error("Script execution error: params={}, script={}", params, script, e);
          handler.handle(Future.failedFuture(e));
        }
      }
    });
    return this;
  }
}


text:
package com.business.domain;

import javax.persistence.*;

/**
 * Created by billb on 2015-05-04.
 */
@Entity
@Table(name = "purchaseitem")
public class QueryPurItem {

    @Id
    @GeneratedValue
    private long id;

    @ManyToOne
    @JoinColumn(name = "sheetid")
    private QueryPur queryPur;

    private int goodsid;
    @Column(name = "goodsname")
    private String name;
    private double price;
    private double cost;
    private double qty;
    private double valqty;
    private double retqty;

    public int getGoodsid() {
        return goodsid;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    public double getCost() {
        return cost;
    }

    public double getQty() {
        return qty;
    }

    public double getValqty() {
        return valqty;
    }

    public double getRetqty() {
        return retqty;
    }

    public long getId() {
        return id;
    }

    public QueryPur getSheet() {
        return queryPur;
    }
}


text:
package tmp;

import java.util.Random;
import java.util.stream.LongStream;

/**
 * <a href="http://stackoverflow.com/questions/36538557/how-do-i-convert-a-long-of-thousands-of-elements-to
 * -substreams-of-100-element"> so problem </a>.
 *
 * Created by kmhaswade on 4/10/16.
 */
public class ChunksOf100 {
    private static final Random r = new Random();
    public static void main(String[] args) {
        final long limit = 30_000;
        LongStream.rangeClosed(1, limit)
                .filter(l -> myPredicate(l));
//                .collect()
    }

    private static boolean myPredicate(long l) {
        return r.nextBoolean();
    }
}


text:
      {{ structure.label }}
      {{ structure.canvasIndex + 1 }}


text:
"use strict";

var hopscotch = require('hopscotch'),
    App = require('../app'),
    router = require('../router').router,
    views = require('./views'),
    tours = require('./tours'),
    modelingModels = require('../modeling/models.js');

var CompareController = {
    compare: function(projectId) {
        if (App.currentProject) {
            setupProject();
            showCompareWindow();
        } else if (projectId) {
            App.currentProject = new modelingModels.ProjectModel({
                id: projectId
            });

            App.currentProject
                .fetch()
                .done(function() {
                    setupProject();
                    showCompareWindow();
                });
        }
        // else -- this case is caught by the backend and raises a 404

    },

    compareCleanUp: function() {
        App.user.off('change:guest', saveAfterLogin);
        App.currentProject.off('change:id', updateUrl);

        if (!App.map.get('areaOfInterest')) {
            App.map.set('areaOfInterest', App.currentProject.get('area_of_interest'));
        }

        App.rootView.footerRegion.empty();

        hopscotch.endTour();
    }
};

function setupProject() {
    App.user.on('change:guest', saveAfterLogin);
    App.currentProject.on('change:id', updateUrl);
}

function saveAfterLogin(user, guest) {
    if (!guest && App.currentProject.isNew()) {
        var user_id = user.get('id');
        App.currentProject.set('user_id', user_id);
        App.currentProject.get('scenarios').each(function(scenario) {
            scenario.set('user_id', user_id);
        });

        App.currentProject.saveProjectAndScenarios();
    }
}

function updateUrl() {
    // Use replace: true, so that the back button will work as expected.
    router.navigate(App.currentProject.getCompareUrl(), { replace: true });
}

function showCompareWindow() {
    var compareWindow = new views.CompareWindow({
            model: App.currentProject
        });
    App.rootView.footerRegion.show(compareWindow);
    tours.compareTour.showTourIfNecessary();
}

module.exports = {
    CompareController: CompareController
};


text:
local autosave = require("autosave")
local lspconfig = require("lspconfig")

autosave.setup(
    {
        enabled = true,
    }
)

lspconfig.pylsp.setup {}

vim.schedule(function()
    vim.env.FZF_DEFAULT_COMMAND = 'fd --hidden --exclude={.git,.idea,.vscode,.sass-cache,node_modules,build} --type f'
end)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace WiringPiNet.Wrapper
{
    public class SPI
    {
        [DllImport("libwiringPi.so", EntryPoint = "wiringPiSPIGetFd")]
        public static extern int WiringPiSPIGetFd(SPIChannels channel);

        [DllImport("libwiringPi.so", EntryPoint = "wiringPiSPIDataRW")]
        public static extern int WiringPiSPIDataRW(SPIChannels channel, byte[] data, int len);

        [DllImport("libwiringPi.so", EntryPoint = "wiringPiSPISetup")]
        public static extern int WiringPiSPISetup(SPIChannels channel, int speed);

        [DllImport("libwiringPi.so", EntryPoint = "wiringPiSPISetupMode")]
        public static extern int wiringPiSPISetupMode(SPIChannels channel, int speed, int mode);
    }
}