hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
fd99cb1191b861f8da3847b0d4d3c6a8c7f5127a
1,764
swift
Swift
HeatMap/Classes/LoaderView.swift
boof-tech/HeatMap
9bb19445f529df539c923e3d8dba10fe77f651cf
[ "MIT" ]
2
2021-06-09T08:21:53.000Z
2021-06-09T11:04:10.000Z
HeatMap/Classes/LoaderView.swift
boof-tech/HeatMap
9bb19445f529df539c923e3d8dba10fe77f651cf
[ "MIT" ]
null
null
null
HeatMap/Classes/LoaderView.swift
boof-tech/HeatMap
9bb19445f529df539c923e3d8dba10fe77f651cf
[ "MIT" ]
null
null
null
// // LoaderView.swift // HeatMap_Example // // Created by Amir on 6/25/21. // Copyright © 2021 CocoaPods. All rights reserved. // import Foundation import UIKit public final class LoaderFrameworkBundle { public static let main: Bundle = Bundle(for: LoaderFrameworkBundle.self) } public class LoaderView: UIView { @IBOutlet var contentView: UIView! @IBOutlet weak var stackView: UIStackView! @IBOutlet var ObjectsView: [UIView]! private var index = 0 public var baseObjectColor: UIColor = .yellow { didSet { setupUI() } } public var animatedObjectColor: UIColor = .orange { didSet { setupUI() } } public var borderColor: UIColor = .white { didSet { setupUI() } } public var stackItemSpace: CGFloat = 5.0 { didSet { stackView.spacing = stackItemSpace } } public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { commonInit() setupUI() } func commonInit() { LoaderFrameworkBundle.main.loadNibNamed(LoaderView.nameOfClass, owner: self, options: nil) contentView.fixInView(self) } func setupUI() { for item in ObjectsView { item.layer.cornerRadius = item.frame.height / 4 item.backgroundColor = baseObjectColor item.layer.borderWidth = 0.5 item.layer.borderColor = borderColor.cgColor } ObjectsView.first?.backgroundColor = animatedObjectColor } }
22.615385
98
0.586168
74603bd2522c3c535b14fad93f8336647968c648
1,114
html
HTML
manuscript/page-530/body.html
marvindanig/vanity-fair
0c19618738f4b544fac59b7ed4218e32bc2614e0
[ "BlueOak-1.0.0", "MIT" ]
null
null
null
manuscript/page-530/body.html
marvindanig/vanity-fair
0c19618738f4b544fac59b7ed4218e32bc2614e0
[ "BlueOak-1.0.0", "MIT" ]
null
null
null
manuscript/page-530/body.html
marvindanig/vanity-fair
0c19618738f4b544fac59b7ed4218e32bc2614e0
[ "BlueOak-1.0.0", "MIT" ]
null
null
null
<div class="leaf "><div class="inner justify"><p class="no-indent ">his gaping coat pocket; and the tape off, and the string in his mouth, and the favourite letters selected and laid before you; and who does not know the sad eager half-crazy look which he fixes on you with his hopeless eyes?</p><p class=" stretch-last-line ">Changed into a man of this sort, Dobbin found the once florid, jovial, and prosperous John Sedley. His coat, that used to be so glossy and trim, was white at the seams, and the buttons showed the copper. His face had fallen in, and was unshorn; his frill and neckcloth hung limp under his bagging waistcoat. When he used to treat the boys in old days at a coffee-house, he would shout and laugh louder than anybody there, and have all the waiters skipping round him; it was quite painful to see how humble and civil he was to John of the Tapioca, a blear-eyed old attendant in dingy stockings and cracked pumps, whose business it was to serve glasses of wafers, and bumpers of ink in pewter, and slices of paper to the frequenters of this dreary house of entertainment,</p></div> </div>
1,114
1,114
0.771993
0d347d6c34b13c1ae4e8b5911b2766236b045024
27,998
psm1
PowerShell
Microsoft.Graph.PlusPlus.psm1
steviecoaster/MsftGraph
775db8c27141dd01f9ee8a1088df3c765acf4782
[ "MIT" ]
58
2019-03-05T16:02:50.000Z
2022-03-22T15:09:06.000Z
Microsoft.Graph.PlusPlus.psm1
steviecoaster/MsftGraph
775db8c27141dd01f9ee8a1088df3c765acf4782
[ "MIT" ]
7
2019-05-27T12:04:26.000Z
2022-02-01T00:09:32.000Z
Microsoft.Graph.PlusPlus.psm1
steviecoaster/MsftGraph
775db8c27141dd01f9ee8a1088df3c765acf4782
[ "MIT" ]
10
2019-05-10T14:15:18.000Z
2021-12-07T14:39:12.000Z
using namespace System.Management.Automation using namespace Microsoft.Graph.PowerShell.Models using namespace Microsoft.Graph.PowerShell.Authentication $Global:GraphUri = 'https://graph.microsoft.com/v1.0' #Global: instead of Script: for use in cmdline invoke-graphRequest etc. $Script:GUIDRegex = '^\{?[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}\}?$' $Script:WellKnownMailFolderRegex = '^[/\\]?(' + (@( 'archive', 'clutter', 'conflicts', 'conversationhistory', 'deleteditems', 'drafts', 'inbox', 'junkemail', 'localfailures', 'msgfolderroot', 'outbox', 'recoverableitemsdeletions', 'scheduled', 'searchfolders', 'sentitems', 'serverfailures', 'syncissues' ) -join '|' ) + ')[/\\]?$' $Script:DefaultUserProperties = @( 'businessPhones', 'displayName', 'givenName', 'id', 'jobTitle', 'mail', 'mobilePhone', 'officeLocation', 'preferredLanguage', 'surname', 'userPrincipalName', 'assignedLicenses', 'department', 'usageLocation', 'userType' ) $Script:DefaultUsageLocation = 'GB' $Script:SkippedSubmodules = @( ) #region global helper functions, completer, transformer, and validator attributes for parameters **CLASSES NEED TO BE IN PSM1 class UpperCaseTransformAttribute : ArgumentTransformationAttribute { [object] Transform([System.Management.Automation.EngineIntrinsics]$EngineIntrinsics, [object] $InputData) { if ($inputData -is [string]) {return $Inputdata.toUpper()} else {return ($InputData) } } } class ValidateCountryAttribute : ValidateArgumentsAttribute { [void]Validate([object]$Argument, [EngineIntrinsics]$EngineIntrinsics) { if ($Argument -notin [cultureInfo]::GetCultures("SpecificCultures").foreach({ New-Object -TypeName System.Globalization.RegionInfo -ArgumentList $_.name }).TwoLetterIsoRegionName) { Throw [ParameterBindingException]::new("'$Argument' is not an ISO 3166 country Code") } } } class ChannelCompleter : IArgumentCompleter { [string] $GroupID = '' [System.Collections.Generic.IEnumerable[CompletionResult]] CompleteArgument( [string]$CommandName, [string]$ParameterName, [string]$WordToComplete, [Language.CommandAst]$CommandAst, [System.Collections.IDictionary] $FakeBoundParameters ) { $result = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new() #strip quotes from word to complete - replace " or ' with nothing $wordToComplete = $wordToComplete -replace '"|''', '' if (-not $this.GroupID) { $Group = $null if ($FakeBoundParameters['Group']) {$Group = $FakeBoundParameters['Group']} if ($FakeBoundParameters['Team' ]) {$Group = $FakeBoundParameters['Team']} #I do mean = not -eq in the elseif statements. elseif ($key = $Global:PSDefaultParameterValues.Keys.where({"$CommandName`:Team" -like $_})) { $Group = $Global:PSDefaultParameterValues[$key] } elseif ($key = $Global:PSDefaultParameterValues.Keys.where({"$CommandName`:Group" -like $_})) { $Group = $Global:PSDefaultParameterValues[$key] } if ($Group.ID) { $this.Groupid = $Group.id} elseif ($Group -is [string] -and $Group -match $Script:GUIDRegex) { $this.GroupID = $Group} elseif ($Group -is [string]) { $this.GroupID = idfromteam $Group } } if ($this.groupID -and $this.groupID -match $Script:GUIDRegex) { Invoke-GraphRequest "$global:GraphUri/Teams/$($this.groupID)/Channels?$`select=id,displayname" -ValueOnly | ForEach-Object { if ($_.displayname -like "$wordToComplete*") {$_.displayName} } | Sort-Object | ForEach-Object { $result.Add([System.Management.Automation.CompletionResult]::new("'$_'", $_, ([CompletionResultType]::ParameterValue) , $_) ) } } return $result } } class DomainCompleter : IArgumentCompleter { [array]$Domains = @() [System.Collections.Generic.IEnumerable[CompletionResult]] CompleteArgument( [string]$CommandName, [string]$ParameterName, [string]$WordToComplete, [Language.CommandAst]$CommandAst, [System.Collections.IDictionary] $FakeBoundParameters ) { $result = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new() if (-not $this.Domains) {$this.Domains = Invoke-GraphRequest "$Global:GraphUri/domains?`$select=id" -ValueOnly | ForEach-Object id | Sort-Object } $wildcard = ('*' + ($wordToComplete -replace '[''"]','' )+ '*') foreach ($d in $this.domains.where({$_ -like $wildcard})) {$result.Add([System.Management.Automation.CompletionResult]::new($_))} return $result } } class GroupCompleter : IArgumentCompleter { [System.Collections.Generic.IEnumerable[CompletionResult]] CompleteArgument( [string]$CommandName, [string]$ParameterName, [string]$WordToComplete, [Language.CommandAst]$CommandAst, [System.Collections.IDictionary] $FakeBoundParameters ) { $result = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new() #strip quotes from word to complete - replace " or ' with nothing $wordToComplete = $wordToComplete -replace '"|''', '' if ($wordToComplete) {$uri = $Global:GraphUri + ("/Groups/?`$filter=startswith(displayName,'{0}') or startswith(mail,'{0}')" -f $wordToComplete)} else {$uri = "$Global:GraphUri/Groups/?`$Top=20"} Invoke-GraphRequest -Uri $uri -ValueOnly | ForEach-Object displayname | Sort-Object | ForEach-Object { $result.Add([System.Management.Automation.CompletionResult]::new("'$_'", $_, ([CompletionResultType]::ParameterValue) , $_) ) } return $result } } class MailFolderCompleter : IArgumentCompleter { [System.Collections.Generic.IEnumerable[CompletionResult]] CompleteArgument( [string]$CommandName, [string]$ParameterName, [string]$WordToComplete, [Language.CommandAst]$CommandAst, [System.Collections.IDictionary] $FakeBoundParameters ) { $result = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new() #strip quotes from word to complete - replace " or ' with nothing. $wordToComplete = $wordToComplete -replace '"|''', '' #Where interested in what's before the final / or \ $params = @{'Select' = 'displayname'} $path = '' if ($wordToComplete -match '^[/\\]?(\w.*)[/\\].*?$') { $params['Name'] = $Matches[1]; $params['ChildItems'] =$true $path = $Matches[1] + '/' } if ($FakeBoundParameters['User']) { $params['User'] = $FakeBoundParameters['User']} Get-GraphMailFolder @params | ForEach-Object { $p = $path+$_.displayname if ($p -like "$wordToComplete*") { $result.Add([System.Management.Automation.CompletionResult]::new("'$p'", $p, ([CompletionResultType]::ParameterValue) , $p) ) } } return $result } } class OneDriveFolderCompleter : IArgumentCompleter { [System.Collections.Generic.IEnumerable[CompletionResult]] CompleteArgument( [string]$CommandName, [string]$ParameterName, [string]$WordToComplete, [Language.CommandAst]$CommandAst, [System.Collections.IDictionary] $FakeBoundParameters ) { $result = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new() #strip quotes from word to complete - replace " or ' with nothing $wordToComplete = $wordToComplete -replace '"|''', '' If ($wordToComplete -notmatch "/.+/" -or $wordToComplete -eq "/root:?/" ) {$params =@{folderPath = '/'} } elseif ($wordToComplete -Match '^/?root:') {$params =@{folderPath = $wordToComplete -replace '^/?(.*)/.*?$', '/$1:'} } #catch after any leading / and before final /; and sandwich between / and : else {$params =@{folderPath = $wordToComplete -replace '^/?(.*)/.*?$','/root:/$1:'} } #catch after any leading / and before final /; and sandwich between /root/ and : if ($FakeBoundParameters['Drive']) { $params['Drive'] = $FakeBoundParameters['Drive']} #I do mean = no -eq in the next line. elseif ($key = $Global:PSDefaultParameterValues.Keys.where({"$CommandName`:Drive" -like $_})) { $params['Drive'] = $Global:PSDefaultParameterValues[$key] } # #it would be better to order-by at the server, but consumer one drive doesn't support it. Get-GraphDrive @params -subFolders -quiet | Sort-Object -Property name | ForEach-Object { $P = ($_.parentReference.path -replace "/drive/|/drives/.*?/","" ) + "/" + $_.name if ($P -like "*$wordToComplete*") { $result.Add([System.Management.Automation.CompletionResult]::new("'$p'", $p, ([CompletionResultType]::ParameterValue) , $p) ) } } return $result } } class OneDrivePathCompleter : IArgumentCompleter { [System.Collections.Generic.IEnumerable[CompletionResult]] CompleteArgument( [string]$CommandName, [string]$ParameterName, [string]$WordToComplete, [Language.CommandAst]$CommandAst, [System.Collections.IDictionary] $FakeBoundParameters ) { $result = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new() #strip quotes from word to complete - replace " or ' with nothing $wordToComplete = $wordToComplete -replace '"|''', '' If ($wordToComplete -notmatch "/.+/" -or $wordToComplete -eq "/root:?/" ) {$params =@{folderPath = '/'} } elseif ($wordToComplete -Match '^/?root:') {$params =@{folderPath = $wordToComplete -replace '^/?(.*)/.*?$', '/$1:'} } #catch after any leading / and before final /; and sandwich between / and : else {$params =@{folderPath = $wordToComplete -replace '^/?(.*)/.*?$','/root:/$1:'} } #catch after any leading / and before final /; and sandwich between /root/ and : if ($FakeBoundParameters['Drive']) { $params['Drive'] = $FakeBoundParameters['Drive']} #I do mean = no -eq in the next line. elseif ($key = $Global:PSDefaultParameterValues.Keys.where({"$CommandName`:Drive" -like $_})) { $params['Drive'] = $Global:PSDefaultParameterValues[$key] } # #it would be better to order-by at the server, but consumer one drive doesn't support it. Get-GraphDrive -quiet @params | Sort-Object -Property name | ForEach-Object { $P = ($_.parentReference.path -replace "/drive/|/drives/.*?/","" ) + "/" + $_.name if ($P -like "*$wordToComplete*") { $result.Add([System.Management.Automation.CompletionResult]::new("'$p'", $p, ([CompletionResultType]::ParameterValue) , $p) ) } } return $result } } class OneNoteSectionCompleter : IArgumentCompleter { [System.Collections.Generic.IEnumerable[CompletionResult]] CompleteArgument( [string]$CommandName, [string]$ParameterName, [string]$WordToComplete, [Language.CommandAst]$CommandAst, [System.Collections.IDictionary] $FakeBoundParameters ) { $result = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new() #strip quotes from word to complete - replace " or ' with nothing $wordToComplete = $wordToComplete -replace '"|''', '' $values = @() if ($FakeBoundParameters['Notebook'] -and $FakeBoundParameters['Notebook'].Sections ) {$values=$FakeBoundParameters['Notebook'].Sections.DisplayName} #I do mean = no -eq in the next line. elseif ($key = $Global:PSDefaultParameterValues.Keys.where({"$CommandName`:Notebook" -like $_})) { $values = $Global:PSDefaultParameterValues[$key].Sections.DisplayName } foreach ($p in $values) { if ($P -like "$wordToComplete*" -and $p -match '^\w+$') { $result.Add([System.Management.Automation.CompletionResult]::new($p, $p, ([CompletionResultType]::ParameterValue) , $p) ) } elseif ($P -like "$wordToComplete*") { $result.Add([System.Management.Automation.CompletionResult]::new("'$p'", $p, ([CompletionResultType]::ParameterValue) , $p) ) } } return $result } } class SkuCompleter : IArgumentCompleter { [array]$skus = @() [System.Collections.Generic.IEnumerable[CompletionResult]] CompleteArgument( [string]$CommandName, [string]$ParameterName, [string]$WordToComplete, [Language.CommandAst]$CommandAst, [System.Collections.IDictionary] $FakeBoundParameters ) { $result = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new() if (-not $this.skus) {$this.skus = Get-GraphSKU } $wildcard = ("*" + ($wordToComplete -replace "['""]",'' )+ "*") $this.skus.where({$_.skuPartNumber -like $wildcard}).skuPartNumber | Sort-Object | ForEach-Object {$result.Add([System.Management.Automation.CompletionResult]::new($_))} return $result } } class SkuPlanCompleter : IArgumentCompleter { [array]$skus = @() [System.Collections.Generic.IEnumerable[CompletionResult]] CompleteArgument( [string]$CommandName, [string]$ParameterName, [string]$WordToComplete, [Language.CommandAst]$CommandAst, [System.Collections.IDictionary] $FakeBoundParameters ) { $result = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new() if (-not $this.skus) {$this.skus = Get-GraphSKU } $wildcard = ("*" + ($wordToComplete -replace "['""]",'' )+ "*") if ($FakeBoundParameters['SKUID']) { $selectedSkus = $this.skus.where({$_.skuID -in $FakeBoundParameters['SKUID'] -or $_.skuPartNumber -in $FakeBoundParameters['SKUID'] }) } else { $selectedSkus = $this.skus } $selectedSkus.ServicePlans.where({$_.ServicePlanName -like $wildcard}).ServicePlanName | Sort-Object | ForEach-Object {$result.Add([System.Management.Automation.CompletionResult]::new($_))} return $result } } class RoleCompleter : IArgumentCompleter { [System.Collections.Generic.IEnumerable[CompletionResult]] CompleteArgument( [string]$CommandName, [string]$ParameterName, [string]$WordToComplete, [Language.CommandAst]$CommandAst, [System.Collections.IDictionary] $FakeBoundParameters ) { $result = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new() #strip quotes from word to complete - replace " or ' with nothing if (-not $wordToComplete) {$wordToComplete = '*'} else {$wordToComplete = "$wordToComplete*" -replace '"|''', '' } Invoke-GraphRequest -Uri "$Global:GraphUri/directoryroles?`$select=displayname" -ValueOnly | Where-Object displayname -like $wordToComplete | Sort-Object -Property displayname | ForEach-Object { $result.Add([System.Management.Automation.CompletionResult]::new("'$($_.displayname)'", $_.displayname, ([CompletionResultType]::ParameterValue) , $_.displayname) ) } return $result } } class TeamCompleter : IArgumentCompleter { [System.Collections.Generic.IEnumerable[CompletionResult]] CompleteArgument( [string]$CommandName, [string]$ParameterName, [string]$WordToComplete, [Language.CommandAst]$CommandAst, [System.Collections.IDictionary] $FakeBoundParameters ) { $result = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new() #strip quotes from word to complete - replace " or ' with nothing $wordToComplete = $wordToComplete -replace '"|''', '' if ($wordToComplete) {$uri = "$Global:GraphUri/groups?`$select=id,resourceProvisioningOptions,displayname&`$filter=startswith(displayname,'{0}')" -f $wordToComplete} else {$uri = "$Global:GraphUri/groups?`$select=id,resourceProvisioningOptions,displayname"} #had "ResourceProvisioningOptions eq 'team' and " in the filter but it removed some valid teams so this is just completing groups for now Invoke-GraphRequest -Uri $uri -ValueOnly | ForEach-Object {if ("Team" -in $_.resourceProvisioningOptions) {$_.displayname}} | Sort-Object | ForEach-Object { $result.Add([System.Management.Automation.CompletionResult]::new("'$_'", $_, ([CompletionResultType]::ParameterValue) , $_) ) } return $result } } class UPNCompleter : IArgumentCompleter { [System.Collections.Generic.IEnumerable[CompletionResult]] CompleteArgument( [string]$CommandName, [string]$ParameterName, [string]$WordToComplete, [Language.CommandAst]$CommandAst, [System.Collections.IDictionary] $FakeBoundParameters ) { $result = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new() #strip quotes from word to complete - replace " or ' with nothing $wordToComplete = $wordToComplete -replace '"|''', '' if ($wordToComplete) { Invoke-GraphRequest -ValueOnly -headers @{'ConsistencyLevel'='eventual'} -uri "$Global:GraphUri/users?`$filter=startswith(userprincipalname,'$wordToComplete')&top=10&select=userprincipalName" | ForEach-Object userPrincipalName | sort-object | ForEach-Object {$result.Add([System.Management.Automation.CompletionResult]::new("'$_'", $_, ([CompletionResultType]::ParameterValue) , $_) )} } return $result } } function FilterString { param ( [validatescript({ if ($_ -is [string] -and $_ -match '\*.*\*|^\*$') {throw [ParameterBindingException]::new("Wildcard cannot be '*something*' or just '*'")} else {$true} })] [parameter(position=0,mandatory=$true)] [string]$SearchTerm , [parameter(position=1)] $ExtraFields = @(), [switch]$ToLower ) if ($toLower) {$SearchTerm = $SearchTerm.ToLower() } #Replace ' with '' - ensure we don't turn '' into '''' ! $SearchTerm = $SearchTerm -replace "(?<!')'(?!')" ,"''" #validation blocked "* and *something*" so we have no *, * at the start, in the middle, or at the end if ($SearchTerm -notmatch '\*') {$filterStrings = , "displayName eq '$SearchTerm'" } elseif ($SearchTerm -match '^\*(.+)') {$filterStrings = , "endswith(displayName,'$($Matches[1])')" } elseif ($SearchTerm -match '(.+)\*$') {$filterStrings = , "startswith(displayName,'$($Matches[1])')" } elseif ($SearchTerm -match '^(.+)\*(.+)$') {$filterStrings = , ("(startswith(displayName,'$($Matches[1])')" + " and endswith(displayName,'$($Matches[2])'))" )} if ($ToLower) {$filterStrings[0] = $filterStrings[0] -replace 'displayName' , 'toLower(displayName)'} foreach ($f in $ExtraFields) {$filterStrings += $filterStrings[0] -replace 'displayName',$f } $filterStrings -join ' or ' } #endregion #region load the bulk of the module . "$PSScriptRoot\Authentication.ps1" #Submodules which need the class and/or private functions from the SDK module. $ImportCmds = [ordered]@{ 'PersonalContacts' = @() 'Users' = @('Remove-MgUser_Delete','New-MgUserTodoList_CreateExpanded1','New-MgUserTodoListTask_CreateExpanded1', 'Remove-MgUserTodoList_Delete1', 'Remove-MgUserTodoListTask_Delete1', 'Update-MgUserTodoListTask_UpdateExpanded1') #'Get-MgUser_List1' , 'Identity.DirectoryManagement' = @('Get-MgDomain_Get1', 'Get-MgDomain_List1', 'Get-MgDomainNameerenceByRef_List1', 'Get-MgDomainServiceConfigurationRecord_List1' , 'Get-MgDomainVerificationDnsRecord_List1', 'Get-MgOrganization_List1', 'Get-MgSubscribedSku_Get1', 'Get-MgSubscribedSku_List1') 'Users.Functions' = @() 'Users.Actions' = @() 'Identity.SignIns' = @() 'Reports' = @() 'Applications' = @() } foreach ($subModule in $ImportCmds.keys) { $result = $null if (Test-path (Join-Path $PSScriptRoot -ChildPath "Microsoft.Graph.$subModule.private.dll")) { $result = Import-Module -Scope Local (Join-Path $PSScriptRoot -ChildPath "Microsoft.Graph.$subModule.private.dll") -Cmdlet $ImportCmds[$subModule] -PassThru } # I do mean get module and assign it to module and if it works then... not "$module -eq" elseif ($module = Get-Module -ListAvailable "Microsoft.Graph.$submodule" | Sort-Object -Property Version | Select-Object -Last 1) { $result = Import-Module -Scope Local (Join-Path (Split-Path $module.Path) -ChildPath "bin\Microsoft.Graph.$submodule.private.dll") -Cmdlet $ImportCmds[$subModule] -PassThru } else { Write-Verbose "Microsoft.Graph.$subModule.private.dll not found $subModule won't be loaded " $Script:SkippedSubmodules += $subModule } if ($result) { . "$PSScriptRoot\$subModule.ps1" foreach ($cmd in $ImportCmds[$subModule]) { $c = Get-Command $cmd; $c.set_visibility('Private') } } } if ($Script:SkippedSubmodules -contains 'Users') { Write-Verbose "Groups, Notes, OneDrive, Planner, and Sharepoint require the Microsoft.Graph.users module, or Microsoft.Graph.Users.private.dll in the module directory." $Script:SkippedSubmodules += @('Groups', 'Notes', 'OneDrive', 'Planner', 'Sharepoint') } else { #These submodules will work with just the users module. . "$PSScriptRoot\Groups.ps1" . "$PSScriptRoot\Notes.ps1" . "$PSScriptRoot\OneDrive.ps1" . "$PSScriptRoot\Planner.ps1" . "$PSScriptRoot\Sharepoint.ps1" } if ($Script:SkippedSubmodules) { Write-Host -ForegroundColor DarkGray ("Skipped " + ($Script:SkippedSubmodules -join ", ") + " because their Microsoft.Graph module(s) or private.dll file(s) were not found.") } #endregion function Set-GraphOptions { <# .synopsis Sets defaults and the tenant client ID & Client Secret used when logging on without a web dialog #> [cmdletbinding()] param ( #Your Tennant ID $TenantID, #Client ID if not using the SDK default of 14d82eec-204b-4c2f-b7e8-296a70dab67e. Must be known to your tennant $ClientID, #Secret set for the client ID in your $TenantID [Alias('Client_Secret,')] $ClientSecret, #Default Scopes to request $DefaultScopes, #Allows a saved Refresh Token (e.g. from Show-GraphSession) to be added to the session. $RefreshToken, #Changes the dafault properties returned by Get-GraphUser and Get-GraphUserList [validateSet('accountEnabled', 'ageGroup', 'assignedLicenses', 'assignedPlans', 'businessPhones', 'city', 'companyName', 'consentProvidedForMinor', 'country', 'createdDateTime', 'department', 'displayName', 'givenName', 'id', 'imAddresses', 'jobTitle', 'legalAgeGroupClassification', 'mail', 'mailNickname', 'mobilePhone', 'officeLocation', 'onPremisesDomainName', 'onPremisesExtensionAttributes', 'onPremisesImmutableId', 'onPremisesLastSyncDateTime', 'onPremisesProvisioningErrors', 'onPremisesSamAccountName', 'onPremisesSecurityIdentifier', 'onPremisesSyncEnabled', 'onPremisesUserPrincipalName', 'passwordPolicies', 'passwordProfile', 'postalCode', 'preferredDataLocation', 'preferredLanguage', 'provisionedPlans', 'proxyAddresses', 'state', 'streetAddress', 'surname', 'usageLocation', 'userPrincipalName', 'userType')] [string[]]$DefaultUserProperties, #Changes the default two letter (ISO 3166) country code - for new users so they can be assigned licenses. Examples include: 'US', 'JP', and 'GB' [ValidateNotNullOrEmpty()] [string]$DefaultUsageLocation ) if ($TenantID) { if ($TenantID -notmatch $GUIDRegex) {Write-Warning 'TenantID should be a GUID' ; break } else {$Script:TenantID = $TenantID} } if ($ClientID) { if ($Clientid -notmatch $GUIDRegex) {Write-Warning 'ClientID should be a GUID' ; break} else {$Script:ClientID = $ClientID} } if ($ClientSecret) { if ($ClientSecret -is [string]) { $Script:ClientSecret = $ClientSecret } elseif ($ClientSecret -is [securestring]) { $Script:ClientSecret = (new-object pscredential -ArgumentList "NoName", $ClientSecret).GetNetworkCredential().Password } else {Write-Warning 'ClientSecret should be a string or preferably a securestring' ; break} } if ($Script:TenantID) {Write-Verbose "TenantID: '$Script:TenantID' , ClientID: '$Script:ClientID'"} if ($DefaultScopes) {$Script:DefaultGraphScopes = $DefaultScopes} Write-Verbose ('Scopes: ' + ($Script:DefaultGraphScopes -join ', ')) #it would be nice to the use the country validator but this goes wrong when reloading the module and calling something when everything is happening in the PSM1 file. if ($DefaultUsageLocation -and -not [cultureInfo]::GetCultures("SpecificCultures").where({$_.name -match "$DefaultUsageLocation$"})) { Write-Warning 'DefaultUsageLocation should be an ISO 2 letter country code like GB, US or JP' ; break } elseif ($DefaultUsageLocation ) {$Script:DefaultUsageLocation = $DefaultUsageLocation.ToUpper() } if ($DefaultUserProperties) {$Script:DefaultUserProperties = $DefaultUserProperties} if ($RefreshToken) {$Script:RefreshToken = $RefreshToken } } #call a script with calls to Set-GraphOptions if ($env:GraphSettingsPath ) {. $env:GraphSettingsPath} elseif (Test-Path "$PSScriptRoot\Microsoft.Graph.PlusPlus.settings.ps1") {. "$PSScriptRoot\Microsoft.Graph.PlusPlus.settings.ps1"} if ($null -eq [GraphSession]::instance.AuthContext) {Write-Host "Ready for Connect-Graph."} elseif ([GraphSession]::instance.AuthContext.AppName -and -not [GraphSession]::instance.AuthContext.Account) { Write-Host ("Already logged on as the app '$([GraphSession]::instance.AuthContext.AppName)'." )} else {Write-Host ("Already logged on as '$([GraphSession]::instance.AuthContext.Account)'." )}
57.847107
212
0.619294
5fbe0cae09024e91d4ec80fb05d402c216e00520
2,806
h
C
Projet perso/HomologieValue.h
PCottalorda/MT
604c7319731c1d7cb61bc6af761bebbdeb29954f
[ "Zlib", "Apache-2.0" ]
null
null
null
Projet perso/HomologieValue.h
PCottalorda/MT
604c7319731c1d7cb61bc6af761bebbdeb29954f
[ "Zlib", "Apache-2.0" ]
null
null
null
Projet perso/HomologieValue.h
PCottalorda/MT
604c7319731c1d7cb61bc6af761bebbdeb29954f
[ "Zlib", "Apache-2.0" ]
null
null
null
#pragma once /***************************************************************************** * * * Copyright 2016 Paul Cottalorda * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * ******************************************************************************/ #include <vector> #include <iosfwd> class HomologieValue { public: class DimensionException : public std::exception {}; HomologieValue(unsigned int dimension);; HomologieValue(const HomologieValue& other); HomologieValue(HomologieValue&& other); ~HomologieValue(); HomologieValue& operator=(const HomologieValue& other); HomologieValue& operator=(HomologieValue&& other); friend bool operator==(const HomologieValue& lhs, const HomologieValue& rhs); friend bool operator!=(const HomologieValue& lhs, const HomologieValue& rhs); friend bool operator<(const HomologieValue& lhs, const HomologieValue& rhs) { if (lhs.dimension() != rhs.dimension()) { throw DimensionException(); } for (unsigned int i = 0; i < lhs.dimension(); ++i) { if (lhs[i] == rhs[i]) { continue; } else if (lhs[i] < rhs[i]) { return true; } else { return false; } } return false; } int operator[](int i) const; int& operator[](int i); HomologieValue operator-() const; HomologieValue& operator+=(const HomologieValue& rhs); HomologieValue& operator-=(const HomologieValue& rhs); friend HomologieValue operator+(HomologieValue lhs, const HomologieValue& rhs); friend HomologieValue operator-(HomologieValue lhs, const HomologieValue& rhs); unsigned int dimension() const; friend std::ostream& operator<<(std::ostream& os, const HomologieValue& hVal); private: unsigned int dim; std::vector<int> base; };
36.441558
80
0.530649
043125974022b2bac3f1315cc7ca48e793d1f775
352
swift
Swift
Classes/File.swift
pavanidivya48/iOSTesting
2f930d99e21e30aeeef4062bb18d80eaf2f1add2
[ "MIT" ]
null
null
null
Classes/File.swift
pavanidivya48/iOSTesting
2f930d99e21e30aeeef4062bb18d80eaf2f1add2
[ "MIT" ]
null
null
null
Classes/File.swift
pavanidivya48/iOSTesting
2f930d99e21e30aeeef4062bb18d80eaf2f1add2
[ "MIT" ]
null
null
null
// // File.swift // iOSTesting // // Created by Ats on 07/08/19. // import Foundation public class RandomGenerator { private init() { } public static func string() -> String { return UUID().uuidString } public static func integer() -> Int { return Int(arc4random()) // Something to do.. } }
15.304348
53
0.5625
6b951c8d467f4e2f373152953470a33d471adcb4
207
h
C
Example/YYTools/YYViewController.h
baozhoua/YYTools
da1a8aa968e50366aea9dfd75435ea1ef44b513f
[ "MIT" ]
null
null
null
Example/YYTools/YYViewController.h
baozhoua/YYTools
da1a8aa968e50366aea9dfd75435ea1ef44b513f
[ "MIT" ]
null
null
null
Example/YYTools/YYViewController.h
baozhoua/YYTools
da1a8aa968e50366aea9dfd75435ea1ef44b513f
[ "MIT" ]
null
null
null
// // YYViewController.h // YYTools // // Created by baozhoua on 03/12/2020. // Copyright (c) 2020 baozhoua. All rights reserved. // @import UIKit; @interface YYViewController : UIViewController @end
14.785714
53
0.700483
80d4507af38ca4ff3b625b1b8e736cb0c74548ed
12,941
java
Java
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/java/org/rf/ide/core/testdata/model/table/LocalSetting.java
alex729/RED
128bf203cf035892c02805aabd0c915f96006bb0
[ "Apache-2.0" ]
null
null
null
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/java/org/rf/ide/core/testdata/model/table/LocalSetting.java
alex729/RED
128bf203cf035892c02805aabd0c915f96006bb0
[ "Apache-2.0" ]
null
null
null
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/java/org/rf/ide/core/testdata/model/table/LocalSetting.java
alex729/RED
128bf203cf035892c02805aabd0c915f96006bb0
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018 Nokia Solutions and Networks * Licensed under the Apache License, Version 2.0, * see license.txt file for details. */ package org.rf.ide.core.testdata.model.table; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; import org.rf.ide.core.testdata.model.AModelElement; import org.rf.ide.core.testdata.model.ExecutableSetting; import org.rf.ide.core.testdata.model.FilePosition; import org.rf.ide.core.testdata.model.FileRegion; import org.rf.ide.core.testdata.model.ICommentHolder; import org.rf.ide.core.testdata.model.IDocumentationHolder; import org.rf.ide.core.testdata.model.ModelType; import org.rf.ide.core.testdata.text.read.IRobotTokenType; import org.rf.ide.core.testdata.text.read.recognizer.RobotToken; import org.rf.ide.core.testdata.text.read.recognizer.RobotTokenType; import com.google.common.base.Preconditions; public class LocalSetting<T> extends AModelElement<T> implements ICommentHolder, Serializable { private static final long serialVersionUID = 5810286313565051692L; public static final Set<ModelType> TEST_SETTING_TYPES = EnumSet.of(ModelType.TEST_CASE_DOCUMENTATION, ModelType.TEST_CASE_TAGS, ModelType.TEST_CASE_SETUP, ModelType.TEST_CASE_TEARDOWN, ModelType.TEST_CASE_TIMEOUT, ModelType.TEST_CASE_TEMPLATE, ModelType.TEST_CASE_SETTING_UNKNOWN); public static final Set<ModelType> TASK_SETTING_TYPES = EnumSet.of(ModelType.TASK_DOCUMENTATION, ModelType.TASK_TAGS, ModelType.TASK_SETUP, ModelType.TASK_TEARDOWN, ModelType.TASK_TIMEOUT, ModelType.TASK_TEMPLATE, ModelType.TASK_SETTING_UNKNOWN); public static final Set<ModelType> KEYWORD_SETTING_TYPES = EnumSet.of(ModelType.USER_KEYWORD_DOCUMENTATION, ModelType.USER_KEYWORD_TAGS, ModelType.USER_KEYWORD_TEARDOWN, ModelType.USER_KEYWORD_TIMEOUT, ModelType.USER_KEYWORD_ARGUMENTS, ModelType.USER_KEYWORD_RETURN, ModelType.USER_KEYWORD_SETTING_UNKNOWN); private ModelType modelType; private final List<RobotToken> tokens = new ArrayList<>(0); private final List<RobotToken> comments = new ArrayList<>(0); public LocalSetting(final ModelType modelType, final RobotToken declaration) { this.modelType = modelType; this.tokens.add(fixForTheType(Preconditions.checkNotNull(declaration), LocalSettingTokenTypes.getTokenType(modelType, 0))); } @Override public ModelType getModelType() { return modelType; } public void changeModelType(final ModelType type) { // firstly we remove types of tokens tied to old model type removeTypes(0); // then we change the type and properly add token types tied to new model type this.modelType = type; fixTypes(); } private void removeTypes(final int startingIndex) { final List<RobotTokenType> tokenTypes = LocalSettingTokenTypes.getPossibleTokenTypes(modelType); for (int i = startingIndex; i < tokens.size(); i++) { final RobotToken token = tokens.get(i); for (final RobotTokenType type : tokenTypes) { if (token.getTypes().contains(type)) { token.getTypes().removeIf(t -> t == type); } } } } @Override public boolean isPresent() { return !tokens.isEmpty(); } @Override public RobotToken getDeclaration() { return isPresent() ? tokens.get(0) : null; } @Override public FilePosition getBeginPosition() { return getDeclaration().getFilePosition(); } public List<RobotToken> getTokens() { return new ArrayList<>(tokens); } public List<RobotToken> getTokensWithoutDeclaration() { return new ArrayList<>(tokens.subList(1, tokens.size())); } public RobotToken getToken(final IRobotTokenType type) { return tokensOf(type).findFirst().orElse(null); } public Stream<RobotToken> tokensOf(final IRobotTokenType type) { return Stream.concat(tokens.stream(), comments.stream()).filter(token -> token.getTypes().contains(type)); } @Override public List<RobotToken> getElementTokens() { final List<RobotToken> tokens = new ArrayList<>(); if (isPresent()) { tokens.addAll(this.tokens); tokens.addAll(this.comments); } return tokens; } @Override public boolean removeElementToken(final int index) { return super.removeElementFromList(tokens, index); } @Override public void insertValueAt(final String value, final int position) { final RobotToken tokenToInsert = RobotToken.create(value); if (1 <= position && position <= tokens.size()) { removeTypes(position); tokens.add(position, tokenToInsert); fixTypes(); } else if (position > tokens.size()) { final int commentsIndex = position - tokens.size(); fixForTheType(tokenToInsert, commentsIndex == 0 ? RobotTokenType.START_HASH_COMMENT : RobotTokenType.COMMENT_CONTINUE); if (commentsIndex == 0) { comments.get(0).getTypes().remove(RobotTokenType.START_HASH_COMMENT); comments.get(0).getTypes().add(RobotTokenType.COMMENT_CONTINUE); } comments.add(commentsIndex, tokenToInsert); } } public void addToken(final RobotToken token) { this.tokens.add(fixType(token, tokens.size())); } private void fixTypes() { for (int i = 0; i < tokens.size(); i++) { fixType(tokens.get(i), i); } } private RobotToken fixType(final RobotToken token, final int index) { final List<IRobotTokenType> types = token.getTypes(); final IRobotTokenType type = LocalSettingTokenTypes.getTokenType(modelType, index); if (type != null) { types.remove(RobotTokenType.UNKNOWN); } if (!types.contains(type)) { types.add(0, type); } if (types.isEmpty()) { types.add(RobotTokenType.UNKNOWN); } return token; } public void addToken(final String tokenText) { final int index = tokens.size(); tokens.add(RobotToken.create(tokenText, LocalSettingTokenTypes.getTokenType(modelType, index))); } public void setToken(final String tokenText, final int index) { if (tokenText == null && 0 <= index && index < tokens.size()) { tokens.remove(index); } else if (tokenText != null) { for (int i = tokens.size(); i <= index; i++) { tokens.add(RobotToken.create("", LocalSettingTokenTypes.getTokenType(modelType, i))); } tokens.set(index, RobotToken.create(tokenText, LocalSettingTokenTypes.getTokenType(modelType, index))); } } public void setTokens(final List<String> tokenTexts) { while (tokens.size() > 1) { tokens.remove(tokens.size() - 1); } for (int i = 0; i < tokenTexts.size(); i++) { tokens.add(RobotToken.create(tokenTexts.get(i), LocalSettingTokenTypes.getTokenType(modelType, i + 1))); } } @Override public List<RobotToken> getComment() { return Collections.unmodifiableList(comments); } public void addCommentPart(final String commentToken) { addCommentPart(RobotToken.create(commentToken)); } @Override public void addCommentPart(final RobotToken rt) { fixComment(getComment(), rt); comments.add(rt); } @Override public void setComment(final String comment) { setComment(RobotToken.create(comment)); } @Override public void setComment(final RobotToken comment) { comments.clear(); addCommentPart(comment); } @Override public void removeCommentPart(final int index) { comments.remove(index); } @Override public void clearComment() { comments.clear(); } @Override public String toString() { return modelType.name(); } public <C> C adaptTo(final Class<C> clazz) { if (clazz == IDocumentationHolder.class && EnumSet .of(ModelType.TEST_CASE_DOCUMENTATION, ModelType.TASK_DOCUMENTATION, ModelType.USER_KEYWORD_DOCUMENTATION) .contains(modelType)) { return clazz.cast(new DocumentationHolderAdapter()); } else if (clazz == ExecutableSetting.class && EnumSet.of(ModelType.TEST_CASE_SETUP, ModelType.TASK_SETUP).contains(modelType)) { return clazz.cast(new ExecutableAdapter(true)); } else if (clazz == ExecutableSetting.class && EnumSet.of(ModelType.TEST_CASE_TEARDOWN, ModelType.TASK_TEARDOWN, ModelType.USER_KEYWORD_TEARDOWN) .contains(modelType)) { return clazz.cast(new ExecutableAdapter(false)); } return null; } private class ExecutableAdapter implements ExecutableSetting { private final boolean isSetup; public ExecutableAdapter(final boolean isSetup) { this.isSetup = isSetup; } @Override public RobotToken getDeclaration() { return LocalSetting.this.getDeclaration(); } @Override public RobotToken getKeywordName() { final List<RobotToken> tokens = getTokens(); return tokens.size() > 1 ? tokens.get(1) : null; } @Override public List<RobotToken> getArguments() { final List<RobotToken> tokens = getTokens(); final List<RobotToken> arguments = tokens.size() > 2 ? tokens.subList(2, tokens.size()) : new ArrayList<>(); return Collections.unmodifiableList(arguments); } @SuppressWarnings("unchecked") @Override public RobotExecutableRow<T> asExecutableRow() { final RobotExecutableRow<T> execRow = new RobotExecutableRow<>(); execRow.setParent(getParent()); execRow.setAction(getKeywordName().copy()); for (final RobotToken arg : getArguments()) { execRow.addArgument(arg.copy()); } for (final RobotToken c : getComment()) { execRow.addCommentPart(c.copy()); } return execRow; } @Override public boolean isSetup() { return isSetup; } @Override public boolean isTeardown() { return !isSetup; } } private class DocumentationHolderAdapter implements IDocumentationHolder { @Override public List<FileRegion> getContinuousRegions() { return new FileRegion.FileRegionSplitter().splitContinuousRegions(getElementTokens()); } @Override public IDocumentationHolder getCached() { return this; } @Override public FilePosition getBeginPosition() { return getDeclaration().getFilePosition(); } @Override public List<RobotToken> getDocumentationText() { return Collections.unmodifiableList(tokens.subList(1, tokens.size())); } @Override public void addDocumentationText(final RobotToken token) { token.getTypes().clear(); token.getTypes().add(LocalSettingTokenTypes.getTokenType(modelType, 1)); tokens.add(token); } @Override public void clearDocumentation() { while (tokens.size() > 1) { tokens.remove(tokens.size() - 1); } } @Override public boolean equals(final Object obj) { if (obj != null && obj.getClass() == DocumentationHolderAdapter.class) { final LocalSetting<?>.DocumentationHolderAdapter that = (LocalSetting<?>.DocumentationHolderAdapter) obj; return this.getOuterSettingObject().equals(that.getOuterSettingObject()); } return false; } @Override public int hashCode() { return getOuterSettingObject().hashCode(); } private LocalSetting<?> getOuterSettingObject() { return LocalSetting.this; } } }
35.070461
122
0.615254
9c5e36bb116385537662921b01ea3426e41a4da9
2,931
js
JavaScript
Protocol Files/development/jgr/16s/16s.js
SciLifeLab/bravo-protocols
656808582e85d8c14c5dceb5b2ae84f3cf5b0181
[ "Apache-2.0" ]
3
2019-02-01T11:18:29.000Z
2021-02-15T20:08:47.000Z
Protocol Files/development/jgr/16s/16s.js
jgruselius/bravo-protocols
66b762bd5ed9e830d9929f9cc0fd37aa3e986821
[ "Apache-2.0" ]
12
2015-03-04T14:21:48.000Z
2019-04-07T15:04:57.000Z
Protocol Files/development/jgr/16s/16s.js
jgruselius/bravo-protocols
66b762bd5ed9e830d9929f9cc0fd37aa3e986821
[ "Apache-2.0" ]
5
2016-01-26T12:48:14.000Z
2018-07-04T08:58:32.000Z
/* Joel Gruselius, 2016, National Genomics Infrastructure */ var g = GetGlobalObject(); g.runset.clear(); var path = "C:/VWorks Workspace/Protocol Files/development/jgr/16s/"; var form = "16s.VWForm" run("C:/VWorks Workspace/Protocol Files/facility/resources/clear_inventory.bat", true); var columns = parseInt(formColumns, 10); var originalIndexPlate = !!formOriginalIndexPlate; var customVolumes = !!formCustomVolumes; var testMode = !!(typeof formTestMode !== "undefined" && formTestMode); if(testMode) print("Running in test mode: Skipping incubations!"); var protocols = {}; protocols["PCR setup 1"] = { file: "16s_first_pcr.pro", settings: { sampleVolume: 4, reagentVolume: 11, primerVolume: 6, tipColumn: 1, reagentColumn: 1, finalHold: false } }; protocols["PCR setup 2"] = { file: "16s_second_pcr.pro", settings: { sampleVolume: 6, reagentVolume: 10, primerVolume: 4, tipColumn: 1, reagentColumn: 1, finalHold: false, originalIndexPlate: false } }; protocols["PCR cleanup 1"] = { file: "16s_ampure_xp.pro", settings: { sampleVolume: 21, beadVolume: 37.8, bindTime: 300, elutionVolume: 30, beadPlateToUse: 1, altBindPlate: true, splitEluateVolume: 6 } }; protocols["PCR cleanup 2"] = { file: "16s_ampure_xp.pro", settings: { sampleVolume: 20, beadVolume: 36, bindTime: 300, elutionVolume: 20, altBindPlate: true } }; var settings = {}; updateSettings(formProtocol); if(formProtocol === "PCR cleanup 1" && settings.splitEluateVolume > 0) { g.runset.openRunsetFile(path+"16s_ampure_and_transfer.rst", form); } else { g.runset.appendProtocolFileToRunset(path+protocols[formProtocol].file, 1, "", form); } function updateSettings(protocol) { if(protocol in protocols) { settings = protocols[protocol].settings; settings.protocolName = protocol; print(protocol + " preset loaded"); } else { settings = {}; throw "EXCEPTION__UndefinedSetting:"+protocol; } if(customVolumes && formProtocol.indexOf("PCR cleanup") !== -1) { var temp = { "sampleVolume": formCustomSampleVolume, "beadVolume": formCustomBeadVolume, "elutionVolume": formCustomElutionVolume }; for(var p in temp) { var x = validate(temp[p]); if(x > 0) { settings[p] = x; print("Using custom value for " + p + " (" + x + ")") } else { print("Invalid value for " + p + " (" + temp[p] + "); using default") } } } } var runsetIndex = 0; function updateRunset() { updateSettings(runsetOrder[runsetIndex++]); } // Dynamic Pipetting Height 2.0: function dph(vol, endHeight) { var v = parseFloat(vol); var e = parseFloat(endHeight); if(v > 0 && e > 0 && !isNaN(v+e)) { return 0.078 - 9.501E-5*v + (0.734-e)/v; } else { throw "ValueException"; } } /* Checks if n is a valid number (including 0) and return that number else null */ function validate(n) { var x = parseFloat(n); return (!isNaN(x) && isFinite(x)) ? x : null; }
22.546154
87
0.675537
09abd155ecf94ead7978e00ccd0857c8401cc4db
529
swift
Swift
Tests/LeetCodeTests/1576 Replace All ?'s to Avoid Consecutive Repeating Characters/ReplaceAllstoAvoidConsecutiveRepeatingCharactersSpec.swift
szwathub/LeetCode.swift
a15c8dc27cc3a23db61ff3034f5891f13ed4fffe
[ "MIT" ]
null
null
null
Tests/LeetCodeTests/1576 Replace All ?'s to Avoid Consecutive Repeating Characters/ReplaceAllstoAvoidConsecutiveRepeatingCharactersSpec.swift
szwathub/LeetCode.swift
a15c8dc27cc3a23db61ff3034f5891f13ed4fffe
[ "MIT" ]
204
2021-10-30T06:16:59.000Z
2022-03-31T11:57:08.000Z
Tests/LeetCodeTests/1576 Replace All ?'s to Avoid Consecutive Repeating Characters/ReplaceAllstoAvoidConsecutiveRepeatingCharactersSpec.swift
szwathub/LeetCode.swift
a15c8dc27cc3a23db61ff3034f5891f13ed4fffe
[ "MIT" ]
null
null
null
import XCTest @testable import LeetCode final class ReplaceAllstoAvoidConsecutiveRepeatingCharactersSpec: XCTestCase { fileprivate let questions: [((String), String)] = [ (("?zs"), "azs"), (("ubv?w"), "ubvaw"), (("uba?w"), "ubabw") ] func testReplaceAllstoAvoidConsecutiveRepeatingCharacters() { let solution = ReplaceAllstoAvoidConsecutiveRepeatingCharacters() for ((s), answer) in questions { XCTAssertEqual(solution.modifyString(s), answer) } } }
27.842105
78
0.644612
34e9c703a2d8bcd26b33bd52a9ac506279eddd4a
2,449
swift
Swift
CourseList_swift/CourseList_swift/view/TabBarController.swift
huangnan78100/swift_demo
3877e35a41e4c4cab811213ee6e9ead53ff9f686
[ "MIT" ]
1
2019-06-07T15:02:22.000Z
2019-06-07T15:02:22.000Z
CourseList_swift/CourseList_swift/view/TabBarController.swift
huangnan78100/swift_demo
3877e35a41e4c4cab811213ee6e9ead53ff9f686
[ "MIT" ]
null
null
null
CourseList_swift/CourseList_swift/view/TabBarController.swift
huangnan78100/swift_demo
3877e35a41e4c4cab811213ee6e9ead53ff9f686
[ "MIT" ]
null
null
null
// // TabBarController.swift // CourseList_swift // // Created by luban on 2019/6/5. // Copyright © 2019年 hyn. All rights reserved. // import UIKit class TabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() addvc() // Do any additional setup after loading the view. } func addvc(){ let homeVc = HomeViewController() let coursePageVc = CoursePageViewController() let courseVc = CourseNavigaController(rootViewController: coursePageVc) let mineVc = MineViewController() homeVc.tabBarItem = UITabBarItem(title: "首页", image: UIImage(named: "btn_tab_home_normal"), selectedImage: UIImage(named: "btn_tab_home_selected")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)) homeVc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 100)], for: UIControl.State.highlighted) courseVc.tabBarItem = UITabBarItem(title: "课程", image: UIImage(named: "btn_tab_elective_normal"), selectedImage: UIImage(named: "btn_tab_elective_selected")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)) courseVc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 100)], for: UIControl.State.highlighted) mineVc.tabBarItem = UITabBarItem(title: "我的", image: UIImage(named: "btn_tab_mine_normal"), selectedImage: UIImage(named: "btn_tab_mine_selected")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)) mineVc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 100)], for: UIControl.State.highlighted) var arrVcs = [UIViewController]() arrVcs.append(homeVc) arrVcs.append(courseVc) arrVcs.append(mineVc) self.tabBar.barTintColor = UIColor.white self.viewControllers = arrVcs } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
46.207547
222
0.722744
8f75abe354d288c1e97b202e23b297ed19a75650
5,933
lua
Lua
UCDphone/apps/housing/housing_c.lua
itslewiswatson/ucd
91903be2ca58cee80ce206c44d9d077ec069f715
[ "MIT" ]
5
2016-11-07T07:27:51.000Z
2020-02-11T08:34:12.000Z
UCDphone/apps/housing/housing_c.lua
nokizorque/ucd
91903be2ca58cee80ce206c44d9d077ec069f715
[ "MIT" ]
5
2016-12-19T00:40:55.000Z
2016-12-25T11:03:42.000Z
UCDphone/apps/housing/housing_c.lua
nokizorque/ucd
91903be2ca58cee80ce206c44d9d077ec069f715
[ "MIT" ]
6
2016-11-27T02:57:15.000Z
2019-06-21T07:39:01.000Z
Housing = {} Housing.cache = {} Housing.blips = {} Housing.open = false function Housing.create() phone.housing = {label = {}} phone.housing.gridlist = guiCreateGridList(27, 96, 254, 207, false, phone.image["phone_window"]) phone.housing.gridlist:addColumn("House ID", 0.2) phone.housing.gridlist:addColumn("House", 0.5) phone.housing.gridlist:addColumn("Location", 0.2) guiGridListSetSortingEnabled(phone.housing.gridlist, false) phone.housing.button = GuiButton(39, 484, 232, 37, "Toggle Marking", false, phone.image["phone_window"]) phone.housing.label["OwnedHouses"] = GuiLabel(27, 303, 254, 15, "Owned Houses: ", false, phone.image["phone_window"]) phone.housing.label["HouseName"] = GuiLabel(27, 322, 254, 23, "House Name: ", false, phone.image["phone_window"]) phone.housing.label["InteriorID"] = GuiLabel(27, 345, 254, 23, "Interior ID:", false, phone.image["phone_window"]) phone.housing.label["InitialPrice"] = GuiLabel(27, 368, 254, 23, "Initial Price:", false, phone.image["phone_window"]) phone.housing.label["BoughtFor"] = GuiLabel(27, 391, 254, 23, "Bought For:", false, phone.image["phone_window"]) phone.housing.label["CurrentPrice"] = GuiLabel(27, 414, 254, 23, "Current Price:", false, phone.image["phone_window"]) phone.housing.label["Sale"] = GuiLabel(27, 437, 254, 23, "Sale:", false, phone.image["phone_window"]) phone.housing.label["Open"] = GuiLabel(27, 460, 254, 23, "Open:", false, phone.image["phone_window"]) guiLabelSetHorizontalAlign(phone.housing.label["OwnedHouses"], "center", false) guiSetFont(phone.housing.label["OwnedHouses"], "default-bold-small") Housing.all = { phone.housing.gridlist, phone.housing.label["HouseName"], phone.housing.label["InteriorID"], phone.housing.label["InitialPrice"], phone.housing.label["BoughtFor"], phone.housing.label["CurrentPrice"], phone.housing.label["Sale"], phone.housing.label["Open"], phone.housing.label["OwnedHouses"], phone.housing.button } for _, gui in pairs(Housing.all) do gui.visible = false end end Housing.create() function Housing.toggle() for _, gui in pairs(Housing.all) do gui.visible = not gui.visible Housing.open = gui.visible end end function Housing.populate(cache) phone.housing.gridlist:clear() --Housing.destroyAllBlips() local checkBlips = {} -- Use this to retain blips, even when a house sells local houseCount = 0 for houseID, data in pairs(cache) do checkBlips[houseID] = true local zone if (not exports.UCDutil or not exports.UCDutil:getCityZoneFromXYZ(data.Loc.x, data.Loc.y, data.Loc.z)) then zone = "SA" else zone = exports.UCDutil:getCityZoneFromXYZ(data.Loc.x, data.Loc.y, data.Loc.z) end local row = phone.housing.gridlist:addRow(houseID, data.HouseName, zone) guiGridListSetItemData(phone.housing.gridlist, row, 1, houseID) Housing.cache[houseID] = { HouseName = data.HouseName, InteriorID = data.InteriorID, InitialPrice = data.InitialPrice, BoughtFor = data.BoughtFor, CurrentPrice = data.CurrentPrice, Sale = data.Sale, Open = data.Open, x = data.Loc.x, y = data.Loc.y, z = data.Loc.z, } houseCount = houseCount + 1 end phone.housing.label["OwnedHouses"].text = "Owned Houses: "..tostring(houseCount or "0") for houseID in pairs(Housing.blips) do if (not checkBlips[houseID]) then Housing.blips[houseID]:destroy() Housing.blips[houseID] = nil end end end addEvent("UCDphone.housing.populate", true) addEventHandler("UCDphone.housing.populate", root, Housing.populate) function Housing.onHouseGridClick() local row = guiGridListGetSelectedItem(phone.housing.gridlist, 1) if (row and row ~= -1) then local houseID = guiGridListGetItemData(phone.housing.gridlist, row, 1) local houseData = Housing.cache[houseID] if (houseData.Sale == 1) then houseData.Sale = "Yes" else houseData.Sale = "No" end if (houseData.Open == 1) then houseData.Open = "Yes" else houseData.Open = "No" end phone.housing.label["HouseName"].text = "House Name: "..tostring(houseData.HouseName) phone.housing.label["InteriorID"].text = "Interior ID: "..tostring(houseData.InteriorID) phone.housing.label["InitialPrice"].text = "Initial Price: $"..tostring(exports.UCDutil:tocomma(houseData.InitialPrice)) phone.housing.label["BoughtFor"].text = "Bought For: $"..tostring(exports.UCDutil:tocomma(houseData.BoughtFor)) phone.housing.label["CurrentPrice"].text = "Current Price: $"..tostring(exports.UCDutil:tocomma(houseData.CurrentPrice)) phone.housing.label["Sale"].text = "Sale: "..tostring(houseData.Sale) phone.housing.label["Open"].text = "Open: "..tostring(houseData.Open) else phone.housing.label["HouseName"].text = "House Name:" phone.housing.label["InteriorID"].text = "Interior ID:" phone.housing.label["InitialPrice"].text = "Initial Price:" phone.housing.label["BoughtFor"].text = "Bought For:" phone.housing.label["CurrentPrice"].text = "Current Price:" phone.housing.label["Sale"].text = "Sale:" phone.housing.label["Open"].text = "Open:" end end addEventHandler("onClientGUIClick", phone.housing.gridlist, Housing.onHouseGridClick) function Housing.destroyAllBlips() for _, blip in pairs(Housing.blips) do blip:destroy() end Housing.blips = {} end function Housing.onToggleHouseBlip() local row = guiGridListGetSelectedItem(phone.housing.gridlist, 1) if (row and row ~= -1) then local houseID = guiGridListGetItemData(phone.housing.gridlist, row, 1) local houseData = Housing.cache[houseID] local housePos = Vector3(houseData.x, houseData.y, houseData.z) if (Housing.blips[houseID]) then Housing.blips[houseID]:destroy() Housing.blips[houseID] = nil else Housing.blips[houseID] = Blip(housePos, 31, nil, nil, nil, nil, nil, 0, 100000) end else exports.UCDdx:new("You must select a house from the grid list", 255, 0, 0) end end addEventHandler("onClientGUIClick", phone.housing.button, Housing.onToggleHouseBlip, false)
41.48951
131
0.726108
b03d8010efcf6be07d067fddb23362d54978e70d
4,914
html
HTML
index.html
intaset/nbconference
24f0de75dd431b25aaae3412841135504c1c1708
[ "MIT" ]
null
null
null
index.html
intaset/nbconference
24f0de75dd431b25aaae3412841135504c1c1708
[ "MIT" ]
null
null
null
index.html
intaset/nbconference
24f0de75dd431b25aaae3412841135504c1c1708
[ "MIT" ]
null
null
null
--- layout: default title: ICNB'18 - 3rd International Conference on Nanobiotechnology meta: 3rd International Conference on Nanobiotechnology (ICNB 2018). This conference covers different topics such as Nanobiomedicine, Nanobiomechanics, Nanobiosystems, Nanobio Based Devices, Nanobio Imaging, Nanobio Sensors, Nanotechnology and Agriculture, Nanotechnology and Drug Delivery, Self-assembly. --- <div class="unit unit-s-1 unit-m-1-4-1 unit-l-1-4-1"> <div class="unit-spacer content"> <!-- <p class="announcement-text"><strong>Announcement: Due to popular demand, the paper submission deadline has been extended until February 8, 2018</strong></p> --> <p class="body"><strong>The 3<sup>rd</sup> International Conference on Nanobiotechnology (ICNB'18) aims to become the leading annual conference in fields related to nanobiotechnology.</strong> The goal of ICNB'18 is to gather scholars from all over the world to present advances in the relevant fields and to foster an environment conducive to exchanging ideas and information. This conference will also provide an ideal environment to develop new collaborations and meet experts on the fundamentals, applications, and products of the mentioned fields.</p> <p class="body"><b>ICNB</b> is an acronym for <B>I</b>nternational <b>C</b>onference on <b>N</b>anobiotechnology.</p> <br> <h2>Submissions</h2> <p class="body">Submissions in the form of extended abstracts, short papers, and full manuscripts are welcome.</p> <ul> <li>all submitted papers will be <strong>peer-reviewed</strong></li> <li>the congress proceedings will be published under an <strong>ISSN</strong> and <strong>ISBN</strong> number</li> <li>each paper will be assigned a unique <strong>DOI</strong> number by <strong><a class="body-link" href="https://www.crossref.org/" target="_blank">Crossref</a></strong></li> <li>the conference proceedings will be indexed by <strong><a class="body-link" href="https://www.scopus.com/" target="_blank">Scopus</a></strong> and <strong><a class="body-link" href="https://scholar.google.com/" target="_blank">Google Scholar</a></strong></li> <li>the proceedings will be permanently archived in <strong><a class="body-link" href="http://www.portico.org/digital-preservation/" target="_blank">Portico</a></strong> (one of the largest community-supported digital archives in the world) </li> <li>selected papers from the congress will be submitted for possible publication in the <strong><a class="body-link" href="http://ijtan.avestia.com/" target="_blank">International Journal of Theoretical and Applied Nanotechnology (IJTAN)</a></strong>, the <strong><a class="body-link" href="http://ijtan.avestia.com/" target="_blank">Journal of Biomass to Biofuel (JBB)</a></strong>, or the <strong><a class="body-link" href="http://ijtan.avestia.com/" target="_blank">Journal of Biomedical Engineering and Biosciences (JBEB)</a></strong> (publication fees may apply)</li> </ul> <p class="body">To learn more about the previous event in this conference series, please visit: <a href="/past-events/" class="body-link">Past Event</a>.</p> <br> <h2>Paper Topics</h2> <p class="body">ICNB'18 is now accepting papers on the following topics.</p> <ul class="topics"> <li>Bionanocatalysis</li> <li>Gene Delivery Systems</li> <li>Nanobiomedicine</li> <li>Nanobiomechanics</li> <li>Nanobiosystems</li> <li>Nanobio Sensors</li> <li>Nanotechnology and Agriculture</li> <li>Nanotechnology and Drug Delivery</li> </ul> <p class="body">For a complete list of the paper topics, please visit: <a href="/papers" class="body-link">Submissions</a>.</p> <!-- <h2>Keynote Speakers:</h2> <center> <div class="unit unit-s-1-2 unit-m-1-2 unit-l-1-2 keynoteIndex"> <img src="../img/Baulin.jpg" class="flex-img"> <p class="body"><b>Dr. Vladimir A. Baulin,</b><br>Universitat Rovira i Virgili, Spain<br><a href="../keynote#Dr. Baulin" class="body-link">Biography & Abstract</a></p> </div> <br><br> </center> --> <br> <div class="sponsor"> <a href="http://international-aset.com" target="_blank"><img src="../img/int-aset.svg" alt="International Academy of Science, Engineering and Technology (International ASET Inc.) " style="max-width:250px; float:left; padding: 40px 25px 20px 25px;"></a> <a href="http://avestia.com" target="_blank"><img src="../img/avestia.png" alt="Avestia Publishing" style="max-width:150px; float:left; padding: 0px 20px 0px 20px;"></a> <a href="http://where2submit.com" target="_blank"><img src="../img/W2S_logo.png" alt="Where2Submit"style="max-width:230px; float:left; padding: 35px 25px 0px 25px;"></a> <div class="cf"></div> </div> </div> </div>
71.217391
589
0.691901
06fdf9271fb2677223fdc62b85e13d1ec4aba371
342
cpp
C++
codevs/1230.cpp
yyong119/ACM-OnlineJudge
5871993b15231c6615bfa3e7c2b04f0f6a23e9dc
[ "MIT" ]
22
2017-08-12T11:56:19.000Z
2022-03-27T10:04:31.000Z
codevs/1230.cpp
yyong119/ACM-OnlineJudge
5871993b15231c6615bfa3e7c2b04f0f6a23e9dc
[ "MIT" ]
2
2017-12-17T02:52:59.000Z
2018-02-09T02:10:43.000Z
codevs/1230.cpp
yyong119/ACM-OnlineJudge
5871993b15231c6615bfa3e7c2b04f0f6a23e9dc
[ "MIT" ]
4
2017-12-22T15:24:38.000Z
2020-05-18T14:51:16.000Z
#include<stdio.h> #define MAX_N 100000000 char h[MAX_N>>2|1]; int main() { int n ,m ; scanf("%d%d",&n,&m); for(int i=0,temp;i!=n;++i) { scanf("%d",&temp); temp +=MAX_N; h[temp/8]|=(1<<temp%8); } for(int i=0,temp;i!=m;++i) { scanf("%d",&temp); temp +=MAX_N; printf("%s\n",h[temp/8]&(1<<temp%8) ? "YES" : "NO"); } return 0; }
19
54
0.520468
e71c742bebabf0d3fbe7769c50f561282f0c2d29
951
dart
Dart
lib/src/schema/schemas/objects/cupertino_theme_data_schema.dart
cross-team/json_theme
473c75cecbefa884f80c5306ad45fee72a731b30
[ "MIT" ]
13
2020-06-03T07:30:16.000Z
2022-01-25T16:26:53.000Z
lib/src/schema/schemas/objects/cupertino_theme_data_schema.dart
cross-team/json_theme
473c75cecbefa884f80c5306ad45fee72a731b30
[ "MIT" ]
20
2020-08-28T13:44:31.000Z
2022-03-29T09:08:35.000Z
lib/src/schema/schemas/objects/cupertino_theme_data_schema.dart
cross-team/json_theme
473c75cecbefa884f80c5306ad45fee72a731b30
[ "MIT" ]
7
2020-10-20T15:02:11.000Z
2022-02-04T11:38:26.000Z
import 'package:json_theme/json_theme_schemas.dart'; class CupertinoThemeDataSchema { static const id = 'https://peiffer-innovations.github.io/flutter_json_schemas/schemas/json_theme/cupertino_theme_data.json'; static final schema = { r'$schema': 'http://json-schema.org/draft-06/schema#', r'$id': '$id', r'$comment': 'https://api.flutter.dev/flutter/cupertino/CupertinoThemeData-class.html', 'title': 'CupertinoThemeData', 'type': 'object', 'properties': { 'barBackgroundColor': SchemaHelper.objectSchema(ColorSchema.id), 'brightness': SchemaHelper.objectSchema(BrightnessSchema.id), 'primaryColor': SchemaHelper.objectSchema(ColorSchema.id), 'primaryContrastingColor': SchemaHelper.objectSchema(ColorSchema.id), 'scaffoldBackgroundColor': SchemaHelper.objectSchema(ColorSchema.id), 'textTheme': SchemaHelper.objectSchema(CupertinoTextThemeDataSchema.id), }, }; }
39.625
112
0.724501
0c5d8fbcf02bb6ebae7ce6f351135b77a6a5b1fc
344
html
HTML
node_modules/Nonsense/Nonsense.html
Zakir289/kibana
ba3010143ebecc40fe29fce8832d73726adcba32
[ "Apache-2.0" ]
1
2016-01-21T09:54:35.000Z
2016-01-21T09:54:35.000Z
node_modules/Nonsense/Nonsense.html
Zakir289/kibana
ba3010143ebecc40fe29fce8832d73726adcba32
[ "Apache-2.0" ]
null
null
null
node_modules/Nonsense/Nonsense.html
Zakir289/kibana
ba3010143ebecc40fe29fce8832d73726adcba32
[ "Apache-2.0" ]
null
null
null
<!doctype html> <html> <head> <title></title> <script src="Nonsense.js"></script> <script type="text/javascript"> var ns = new Nonsense(), nss = new Nonsense('foo', 'bar', 'baz', 'algebraic!'); console.log(ns.words()); console.log(nss.words()); </script> <style type="text/css"> </style> </head> <body> </body> </html>
20.235294
82
0.593023
5d1eb0412ffa2162406f8518317692493fac39ca
803
kt
Kotlin
kotest-framework/kotest-framework-engine/src/commonMain/kotlin/io/kotest/engine/test/timeouts.kt
dchenbecker/kotest
14fd1091c9b23d49d50759e4b2819771cb35fca7
[ "Apache-2.0" ]
1
2021-08-13T03:38:36.000Z
2021-08-13T03:38:36.000Z
kotest-framework/kotest-framework-engine/src/commonMain/kotlin/io/kotest/engine/test/timeouts.kt
dchenbecker/kotest
14fd1091c9b23d49d50759e4b2819771cb35fca7
[ "Apache-2.0" ]
null
null
null
kotest-framework/kotest-framework-engine/src/commonMain/kotlin/io/kotest/engine/test/timeouts.kt
dchenbecker/kotest
14fd1091c9b23d49d50759e4b2819771cb35fca7
[ "Apache-2.0" ]
null
null
null
package io.kotest.engine.test import io.kotest.core.config.configuration import io.kotest.core.test.TestCase /** * Returns the resolved timeout for a [TestCase] in milliseconds. * * The value cascades from the following settings in order: * - test case config * - spec * - project default */ fun TestCase.resolvedTimeout(): Long = config.timeout?.inWholeMilliseconds ?: spec.timeout ?: spec.timeout() ?: configuration.timeout /** * Returns the resolved timeout for a test invocation taking into account config on the test case, * values specified in the spec itself, and project wide defaults. */ fun TestCase.resolvedInvocationTimeout(): Long = config.invocationTimeout?.inWholeMilliseconds ?: spec.invocationTimeout() ?: spec.invocationTimeout ?: configuration.invocationTimeout
33.458333
102
0.760897
076db8155a64562abe8742c6dd0b423f5ca27fa9
993
ps1
PowerShell
CIS_8/CIS_8.2.2.ps1
mcozzo/ps.CIS_VMW6.7
4d5db9124306528e6e2c6808bbb3606206193d22
[ "MIT" ]
2
2020-11-16T15:11:04.000Z
2021-05-24T19:00:22.000Z
CIS_8/CIS_8.2.2.ps1
mcozzo/ps.CIS_VMW6.7
4d5db9124306528e6e2c6808bbb3606206193d22
[ "MIT" ]
null
null
null
CIS_8/CIS_8.2.2.ps1
mcozzo/ps.CIS_VMW6.7
4d5db9124306528e6e2c6808bbb3606206193d22
[ "MIT" ]
null
null
null
 $Expected = "Expected: Parent IsoPath ConnectionState ------ ------- --------------- <VM> NotConnected, GuestControl, NoStartConnected " ## List the var Settings for all hosts Write-host ( $Expected ) -ForegroundColor Yellow # Check for CD/DVD Drives attached to VMs Get-VM | Get-CDDrive | select Parent,IsoPath,ConnectionState ## List the var Settings for all hosts Write-host ( $Expected ) -ForegroundColor Yellow Write-host "Would you like remediate?" -ForegroundColor Yellow Write-host "Caution remediation not tested!" -ForegroundColor Red $Readhost = Read-Host " ( y / n ) " Switch ($ReadHost) { Y { Write-host "Yes, performing remediation"; $Remediate=$true } N { Write-Host "No, Skipping"; $Remediate=$false } Default {Write-Host "Default, Skipping"; $Remediate=$false } } If($Remediate) { # # Remove all CD/DVD Drives attached to VMs Get-VM | Get-CDDrive | Remove-CDDrive # }
27.583333
72
0.640483
b945e3a7d53a82d4143c63cfdf7c13a3e3fa6b8b
440
lua
Lua
cocos2d/cocos/scripting/lua-bindings/auto/api/TransitionEaseScene.lua
triompha/EarthWarrior3D
d68a347902fa1ca1282df198860f5fb95f326797
[ "MIT" ]
null
null
null
cocos2d/cocos/scripting/lua-bindings/auto/api/TransitionEaseScene.lua
triompha/EarthWarrior3D
d68a347902fa1ca1282df198860f5fb95f326797
[ "MIT" ]
null
null
null
cocos2d/cocos/scripting/lua-bindings/auto/api/TransitionEaseScene.lua
triompha/EarthWarrior3D
d68a347902fa1ca1282df198860f5fb95f326797
[ "MIT" ]
null
null
null
-------------------------------- -- @module TransitionEaseScene -- @parent_module cc -------------------------------- -- returns the Ease action that will be performed on a linear action.<br> -- since v0.8.2 -- @function [parent=#TransitionEaseScene] easeActionWithAction -- @param self -- @param #cc.ActionInterval action -- @return ActionInterval#ActionInterval ret (return value: cc.ActionInterval) return nil
29.333333
79
0.606818
85f908bdbb08ac706d5e569c7f5a20abaabbea9c
1,465
h
C
Pods/Target Support Files/XTComponentUtils/XTComponentUtils-umbrella.h
leblanc-zx/XTModuleBLEMF1Card
69dadcadec25367cb7de25cfc217a3c0a06c0349
[ "MIT" ]
null
null
null
Pods/Target Support Files/XTComponentUtils/XTComponentUtils-umbrella.h
leblanc-zx/XTModuleBLEMF1Card
69dadcadec25367cb7de25cfc217a3c0a06c0349
[ "MIT" ]
null
null
null
Pods/Target Support Files/XTComponentUtils/XTComponentUtils-umbrella.h
leblanc-zx/XTModuleBLEMF1Card
69dadcadec25367cb7de25cfc217a3c0a06c0349
[ "MIT" ]
null
null
null
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif #import "DesEntry.h" #import "bfs.h" #import "bistree.h" #import "bit.h" #import "bitree.h" #import "cbc.h" #import "chtbl.h" #import "clist.h" #import "compress.h" #import "cover.h" #import "dfs.h" #import "directls.h" #import "dlist.h" #import "encrypt.h" #import "events.h" #import "frames.h" #import "geodist.h" #import "geometry.h" #import "graph.h" #import "graphalg.h" #import "hashpjw.h" #import "heap.h" #import "lex.h" #import "list.h" #import "nummeths.h" #import "ohtbl.h" #import "page.h" #import "parcel.h" #import "parcels.h" #import "pqueue.h" #import "queue.h" #import "route.h" #import "search.h" #import "set.h" #import "sort.h" #import "spell.h" #import "stack.h" #import "symbol.h" #import "transfer.h" #import "traverse.h" #import "zxDes.h" #import "NSString+XTEncryption.h" #import "NSString+XTHash.h" #import "XTPriceGroupInfo.h" #import "XTUtils+AES.h" #import "XTUtils+Date.h" #import "XTUtils+DES.h" #import "XTUtils+Float.h" #import "XTUtils+Image.h" #import "XTUtils+MD5.h" #import "XTUtils+NonStandard.h" #import "XTUtils+PriceGroup.h" #import "XTUtils+UIKit.h" #import "XTUtils+Validate.h" #import "XTUtils.h" FOUNDATION_EXPORT double XTComponentUtilsVersionNumber; FOUNDATION_EXPORT const unsigned char XTComponentUtilsVersionString[];
20.347222
70
0.729693
f08586765e5f258c21bc20cfb2909c6a6fa6cf4b
785
lua
Lua
lua/null-ls/builtins/formatting/markdownlint.lua
Geraint/null-ls.nvim
c4b437ca337459dfa80cdbed4c4cf27345fb8cd7
[ "Apache-2.0" ]
1
2022-03-22T10:09:53.000Z
2022-03-22T10:09:53.000Z
lua/null-ls/builtins/formatting/markdownlint.lua
Geraint/null-ls.nvim
c4b437ca337459dfa80cdbed4c4cf27345fb8cd7
[ "Apache-2.0" ]
null
null
null
lua/null-ls/builtins/formatting/markdownlint.lua
Geraint/null-ls.nvim
c4b437ca337459dfa80cdbed4c4cf27345fb8cd7
[ "Apache-2.0" ]
null
null
null
local h = require("null-ls.helpers") local methods = require("null-ls.methods") local FORMATTING = methods.internal.FORMATTING return h.make_builtin({ name = "markdownlint", meta = { url = "https://github.com/igorshubovych/markdownlint-cli", description = "A Node.js style checker and lint tool for Markdown/CommonMark files.", notes = { "Can fix some (but not all!) markdownlint issues. If possible, use [Prettier](https://github.com/prettier/prettier), which can also fix Markdown files.", }, }, method = FORMATTING, filetypes = { "markdown" }, generator_opts = { command = "markdownlint", args = { "--fix", "$FILENAME" }, to_temp_file = true, }, factory = h.formatter_factory, })
32.708333
165
0.626752
d951a7b67c2acc61ae4df06a401b38a16dccb1de
2,079
kt
Kotlin
OnlinePK-Android/lib-basic/src/main/java/com/netease/yunxin/nertc/demo/basic/BaseActivity.kt
Dongshanxu/OnlinePK
e334a9a3c07cd03be26a78b08ca78b38fc097582
[ "MIT" ]
3
2021-04-21T14:44:13.000Z
2021-12-12T14:55:27.000Z
OnlinePK-Android/lib-basic/src/main/java/com/netease/yunxin/nertc/demo/basic/BaseActivity.kt
Dongshanxu/OnlinePK
e334a9a3c07cd03be26a78b08ca78b38fc097582
[ "MIT" ]
1
2021-12-10T09:10:03.000Z
2021-12-10T09:10:03.000Z
OnlinePK-Android/lib-basic/src/main/java/com/netease/yunxin/nertc/demo/basic/BaseActivity.kt
Dongshanxu/OnlinePK
e334a9a3c07cd03be26a78b08ca78b38fc097582
[ "MIT" ]
10
2021-04-14T08:54:36.000Z
2022-03-24T01:55:35.000Z
/* * Copyright (c) 2021 NetEase, Inc. All rights reserved. * Use of this source code is governed by a MIT license that can be found in the LICENSE file */ package com.netease.yunxin.nertc.demo.basic import android.os.Bundle import android.view.View import androidx.annotation.IdRes import androidx.appcompat.app.AppCompatActivity import com.gyf.immersionbar.ImmersionBar import com.netease.yunxin.login.sdk.AuthorManager import com.netease.yunxin.login.sdk.model.EventType import com.netease.yunxin.login.sdk.model.LoginEvent import com.netease.yunxin.login.sdk.model.LoginObserver open class BaseActivity : AppCompatActivity() { private val loginObserver: LoginObserver<LoginEvent> = object : LoginObserver<LoginEvent> { override fun onEvent(event: LoginEvent) { if (event.eventType == EventType.TYPE_LOGOUT && !ignoredLoginEvent()){ finish() } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AuthorManager.registerLoginObserver(loginObserver) val config = provideStatusBarConfig() if (config != null) { val bar = ImmersionBar.with(this) .statusBarDarkFont(config.darkFont) .statusBarColor(config.barColor) if (config.fits) { bar.fitsSystemWindows(true) } if (config.fullScreen) { bar.fullScreen(true) } bar.init() } } override fun onDestroy() { AuthorManager.unregisterLoginObserver(loginObserver) super.onDestroy() } protected open fun provideStatusBarConfig(): StatusBarConfig? { return null } protected open fun ignoredLoginEvent(): Boolean { return false } protected fun paddingStatusBarHeight(view: View?) { StatusBarConfig.paddingStatusBarHeight(this, view) } protected fun paddingStatusBarHeight(@IdRes rootViewId: Int) { paddingStatusBarHeight(findViewById(rootViewId)) } }
31.5
95
0.669553
f3feb6789d6db9f2c1577d0ad2486782791d6fac
476
swift
Swift
Tests/RocketTests/Utils/SpyScriptLauncher.swift
shibapm/Rocket
2d956352672557834543ed64d10cfc808851df0b
[ "MIT" ]
69
2019-04-23T08:26:35.000Z
2022-02-18T01:15:21.000Z
Tests/RocketTests/Utils/SpyScriptLauncher.swift
shibapm/Rocket
2d956352672557834543ed64d10cfc808851df0b
[ "MIT" ]
8
2019-11-20T17:33:31.000Z
2022-01-02T14:43:17.000Z
Tests/RocketTests/Utils/SpyScriptLauncher.swift
shibapm/Rocket
2d956352672557834543ed64d10cfc808851df0b
[ "MIT" ]
10
2019-05-22T03:05:21.000Z
2021-08-09T09:53:11.000Z
import Logger @testable import RocketLib import TestSpy final class SpyScriptLauncher: ScriptLaunching, TestSpy { enum Method: Equatable { case launchScript(content: String, version: String?) } var callstack = CallstackContainer<Method>() var result = "" func launchScript(withContent content: String, version: String?) throws -> String { callstack.record(.launchScript(content: content, version: version)) return result } }
26.444444
87
0.703782
2f1a55102a8a9e4c7e2a23eac3c94de2946284bf
1,746
java
Java
src/java/cd4017be/rs_ctr/gui/ramio/RAMImageFormat.java
scikirbypoke/RedstoneControl
cc7cab2177fbebc274b222455013747dba1d5ef1
[ "MIT" ]
13
2019-04-24T16:03:23.000Z
2021-01-06T20:07:04.000Z
src/java/cd4017be/rs_ctr/gui/ramio/RAMImageFormat.java
scikirbypoke/RedstoneControl
cc7cab2177fbebc274b222455013747dba1d5ef1
[ "MIT" ]
41
2019-04-26T12:42:57.000Z
2021-11-07T20:39:43.000Z
src/java/cd4017be/rs_ctr/gui/ramio/RAMImageFormat.java
scikirbypoke/RedstoneControl
cc7cab2177fbebc274b222455013747dba1d5ef1
[ "MIT" ]
8
2019-04-25T08:52:36.000Z
2021-08-16T00:10:35.000Z
package cd4017be.rs_ctr.gui.ramio; import java.io.*; import java.nio.ByteBuffer; import java.util.ArrayList; import net.minecraft.network.PacketBuffer; /** * @author CD4017BE */ public interface RAMImageFormat { /** * @param filename * @return whether this format should be used to export/import the given file. */ boolean applies(String filename); /** * @param export * @param file * @param w width * @param h height * @param bits memory layout: bits per word * @return info message for export/import */ String infoMessage(boolean export, String file, int w, int h, int bits); /** * @param fos file to export * @param data memory content * @param w width * @param h height * @param bits memory layout: bits per word * @throws IOException */ void exportFile(FileOutputStream fos, ByteBuffer data, int w, int h, int bits) throws IOException; /** * @param fis file to import * @param data target buffer. Must start with the decoded size (in units of 32bit) as short. * @param wh [0] = width, [1] = height * @param bits memory layout: bits per word * @param cap memory capacity (in units of 32bit) * @throws IOException */ void importFile(FileInputStream fis, PacketBuffer data, int[] wh, int bits, int cap) throws IOException; ArrayList<RAMImageFormat> REGISTRY = new ArrayList<>(); static RAMImageFormat get(String filename) { for (RAMImageFormat fmt : REGISTRY) if (fmt.applies(filename)) return fmt; return RAW_BINARY; } RAMImageFormat RAW_BINARY = new RawBinary(); RAMImageFormat INTEL_HEX = new IntelHex(); RAMImageFormat PNG_IMAGE = new PNGImage(); RAMImageFormat BMP_IMAGE = new BMPImage(); }
27.714286
106
0.682703
bc2c787e8e5efe8dbbdda8ae13a8ecb8f34f2c85
4,982
sql
SQL
crud_mysqli.sql
fikriyogi/PHP-MySQLI-CRUD-With-Register-Login
c6a9ee8474880a17105bad54d0c0afe753c88924
[ "Apache-2.0" ]
null
null
null
crud_mysqli.sql
fikriyogi/PHP-MySQLI-CRUD-With-Register-Login
c6a9ee8474880a17105bad54d0c0afe753c88924
[ "Apache-2.0" ]
null
null
null
crud_mysqli.sql
fikriyogi/PHP-MySQLI-CRUD-With-Register-Login
c6a9ee8474880a17105bad54d0c0afe753c88924
[ "Apache-2.0" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 4.2.11 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: 18 Jan 2018 pada 20.29 -- Versi Server: 5.6.21 -- PHP Version: 5.6.3 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `crud_mysqli` -- -- -------------------------------------------------------- -- -- Struktur dari tabel `log` -- CREATE TABLE IF NOT EXISTS `log` ( `id_log` int(11) NOT NULL, `email` varchar(100) NOT NULL, `tgl_log` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `log` -- INSERT INTO `log` (`id_log`, `email`, `tgl_log`) VALUES (1, 'fikriyogi@gmail.com', '2018-01-18 19:06:26'), (2, 'fikriyogi@gmail.com', '2018-01-18 19:06:33'), (3, 'fikriyogi@gmail.com', '2018-01-18 19:08:54'), (4, 'fikriyogi@gmail.com', '2018-01-18 19:10:00'), (5, 'fikriyogi@gmail.com', '2018-01-18 19:11:13'), (6, 'fikriyogi@gmail.com', '2018-01-18 19:13:28'), (7, 'fikriyogi@gmail.com', '2018-01-18 19:16:44'), (8, 'fikriyogi5@gmail.com', '2018-01-18 19:18:50'); -- -------------------------------------------------------- -- -- Struktur dari tabel `mhsasia` -- CREATE TABLE IF NOT EXISTS `mhsasia` ( `id` int(5) NOT NULL, `nama` varchar(35) NOT NULL, `alamat` varchar(35) NOT NULL, `nim` varchar(12) NOT NULL, `email` varchar(34) NOT NULL, `dusun` varchar(50) NOT NULL, `rt` char(3) NOT NULL, `rw` char(3) NOT NULL, `no_telpon` varchar(34) NOT NULL, `photo` varchar(200) NOT NULL, `nik` char(20) NOT NULL ) ENGINE=MyISAM AUTO_INCREMENT=32 DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `mhsasia` -- INSERT INTO `mhsasia` (`id`, `nama`, `alamat`, `nim`, `email`, `dusun`, `rt`, `rw`, `no_telpon`, `photo`, `nik`) VALUES (17, 'Budigunawan', ';lk', 'lk', 'lk', '', '', '', 'lk', '', 'k'), (16, 'Fikri Yogi', 'kl', 'l', 'k;l', '1', '', '', 'k', 'photo/6358466824210098091411538.jpg', '3987243'), (14, 'Ericha', 'k', 'jlk', 'jkl', '', '', '', 'j', 'photo/3HMLaMK.png', '187398123'), (18, 'Khairul Fahri', 'lkl', 'kl', 'kl', '2', '001', '', 'kk', '', ''), (15, 'lkj', 'lkj', 'klj', 'sdn004pulauterap@gmail.com', '', '', '', '', '', '209138'), (19, 'iopp', '098', '', '', '', '', '', '', '', ''), (20, 'dusun', 'lere', '', '', '1', '002', '', '12323', '', 'jkj213123'), (21, 'Sri Darmasari', 'Bengkalis', '23423', 'sdn004pulauterap@gmail.com', '', '', '', '0853', 'photo/bayern-mnchen-tactics-se.png', '13055567567'), (22, 'Fajri', 'ter', '234234343', 'sdn004pulauterap@gmail.com', 'dusun', '001', '002', '0831', '', '140'), (23, '', '', '', '', '', '', '', '', '', ''), (24, '', '', '', '', '', '', '', '', '', ''), (25, 'Nama', '', '', '', '', '', '', '', '', ''), (26, '', '', '', '', '', '', '', '', '', ''), (27, 'Fikri', '', '', '', '', '', '', '', '', ''), (28, 'Fajri', '', '', '', '', '', '', '', '', ''), (29, 'Fajri', 'Lerne', '', '', '', '', '', '', '', ''), (30, 'Fajri', '', '', '', '', '', '', '', '', ''), (31, 'Budi', '', '', '', '', '', '', '', '', ''); -- -------------------------------------------------------- -- -- Struktur dari tabel `users` -- CREATE TABLE IF NOT EXISTS `users` ( `user_id` int(5) NOT NULL, `username` varchar(25) NOT NULL, `email` varchar(35) NOT NULL, `password` varchar(50) NOT NULL, `tgl_daftar` timestamp NULL DEFAULT NULL, `status` enum('1','0') DEFAULT '0' ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `users` -- INSERT INTO `users` (`user_id`, `username`, `email`, `password`, `tgl_daftar`, `status`) VALUES (2, 'dosen', 'fikriyogi@gmail.com', 'b40d317dad65b25c608797a5f4a97e60', '2018-01-18 19:03:52', '0'), (3, 'fikriyogi5', 'fikriyogi5@gmail.com', 'e37c4f1b74f68330bf09be95d03124af', '0000-00-00 00:00:00', '1'); -- -- Indexes for dumped tables -- -- -- Indexes for table `log` -- ALTER TABLE `log` ADD PRIMARY KEY (`id_log`); -- -- Indexes for table `mhsasia` -- ALTER TABLE `mhsasia` ADD PRIMARY KEY (`id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`user_id`), ADD UNIQUE KEY `email` (`email`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `log` -- ALTER TABLE `log` MODIFY `id_log` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=9; -- -- AUTO_INCREMENT for table `mhsasia` -- ALTER TABLE `mhsasia` MODIFY `id` int(5) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=32; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `user_id` int(5) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
31.1375
147
0.57507
2f25890789997ce4fd6843bf2d503fadc3d6fcc2
2,112
php
PHP
examples/async_postcards_from_csv/index.php
lob/lob-php
615d2603d3c3b37b5fef8adb609ddebe4bcb3f30
[ "MIT" ]
55
2015-01-16T13:07:50.000Z
2022-03-10T21:21:57.000Z
examples/async_postcards_from_csv/index.php
freekmurze/lob-php
2c8cd86643b387270b80ad18076ad29aedebf53c
[ "MIT" ]
76
2015-01-10T00:50:54.000Z
2021-12-22T15:38:45.000Z
examples/async_postcards_from_csv/index.php
freekmurze/lob-php
2c8cd86643b387270b80ad18076ad29aedebf53c
[ "MIT" ]
21
2015-01-30T18:17:38.000Z
2021-11-07T10:39:00.000Z
<?php use Amp\Parallel\Worker\DefaultPool; use Amp\Promise; use function Amp\ParallelFunctions\parallelMap; require "vendor/autoload.php"; // Setup Lob client $apiKey = $_ENV["LOB_API_KEY"]; $lob = new \Lob\Lob($apiKey); $concurrency = 10; $pool = new DefaultPool($concurrency); // Create "from" address $from_address = $lob->addresses()->create(array( "name" => "The Big House", "address_line1" => "1201 S Main St", "address_line2" => "", "address_city" => "Ann Arbor", "address_state" => "MI", "address_zip" => "48104", "email" => "goblue@umich.edu", "phone" => "734-647-2583" )); // Load CSV from file $filename = "input.csv"; $file = fopen($filename, "r"); $csv = array(); while (($row = fgetcsv($file)) !== false) { $csv[] = $row; } fclose($file); // Load assets $html_front = file_get_contents("postcard_front.html"); $html_back = file_get_contents("postcard_back.html"); try { $postcards = Promise\wait(parallelMap($csv, function ($row) use ($lob, $html_front, $html_back) { try { $postcard = $lob->postcards()->create(array( "to" => array( "name" => $row[5], "address_line1" => $row[6], "address_line2" => $row[7], "address_city" => $row[8], "address_state" => $row[9], "address_zip" => $row[10], "address_country" => $row[11], ), "from" => $from_address["id"], "front" => $html_front, "back" => $html_back, "size" => "6x11", "merge_variables" => array( "background_image" => $row[1], "background_color" => $row[2], "name" => $row[0], "car" => $row[3], "mileage" => $row[4] ) )); echo $postcard["id"].": ".$postcard["url"]."\n"; return $postcard; } catch (Exception $e) { echo "err: ", $e->getMessage(), "\n"; } }, $pool)); } catch (Amp\MultiReasonException $e) { echo "err: ", $e->getMessage(), "\n"; // Uncomment to debug concurrency bugs // var_dump($e->getReasons()); } echo "\ndone processing file\n"; ?>
25.445783
99
0.547822
805fe4c8b373d3698bfada3a2e1ae5863493ddd7
2,887
java
Java
src/cn/olange/pins/action/MessageInfoAction.java
Linindoo/idea-juejin
d9f1b3ae15ae21c40639700331e7ed515ca41bf8
[ "MIT" ]
5
2020-12-08T13:24:20.000Z
2022-03-25T08:42:22.000Z
src/cn/olange/pins/action/MessageInfoAction.java
zhoriya/idea-juejin
d9f1b3ae15ae21c40639700331e7ed515ca41bf8
[ "MIT" ]
4
2020-12-09T08:48:49.000Z
2022-01-18T10:16:59.000Z
src/cn/olange/pins/action/MessageInfoAction.java
zhoriya/idea-juejin
d9f1b3ae15ae21c40639700331e7ed515ca41bf8
[ "MIT" ]
2
2020-12-08T07:59:15.000Z
2021-03-18T01:54:56.000Z
package cn.olange.pins.action; import cn.olange.pins.model.Config; import cn.olange.pins.service.PinsService; import cn.olange.pins.setting.JuejinPersistentConfig; import cn.olange.pins.view.MessageInfoPanel; import com.google.gson.JsonObject; import com.intellij.icons.AllIcons; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.Disposer; import com.intellij.ui.awt.RelativePoint; import com.intellij.util.ui.UIUtil; import icons.JuejinIcons; import org.jetbrains.annotations.NotNull; import java.awt.*; public class MessageInfoAction extends AnAction { private long lastTime = 0; private JsonObject messageData; public MessageInfoAction() { super(JuejinIcons.Msg_read); } @Override public void update(AnActionEvent e) { Config config = JuejinPersistentConfig.getInstance().getState(); if (config.isLogined() && System.currentTimeMillis() - lastTime > config.getMessageRefreshInterval() * 1000) { refreshMessageInfo(e, config); lastTime = System.currentTimeMillis(); } } @Override public void actionPerformed(@NotNull AnActionEvent e) { Disposable disposable = Disposer.newDisposable(); MessageInfoPanel messageInfoPanel = new MessageInfoPanel(e.getProject(), messageData, disposable); Balloon balloon = JBPopupFactory.getInstance().createBalloonBuilder(messageInfoPanel) .setFillColor(messageInfoPanel.getBackground()) .setAnimationCycle(0) .setDisposable(disposable) .setFadeoutTime(0) .setRequestFocus(true) .createBalloon(); balloon.show(new RelativePoint(e.getInputEvent().getComponent(), new Point(15, 30)), Balloon.Position.below); } private void refreshMessageInfo(AnActionEvent e, Config config) { PinsService pinsService = PinsService.getInstance(e.getProject()); JsonObject messageInfo = pinsService.getMessageInfo(config.getCookieValue()); if (messageInfo != null && !messageInfo.get("data").isJsonNull()) { UIUtil.invokeLaterIfNeeded(() -> { messageData= messageInfo.get("data").getAsJsonObject(); int total = messageData.get("total").getAsInt(); if (total > 0) { e.getPresentation().setIcon(JuejinIcons.Msg_unread); e.getPresentation().setText(String.format("你有%s条未读消息",total)); } else { e.getPresentation().setIcon(JuejinIcons.Msg_read); e.getPresentation().setText("暂无消息"); } }); } } }
40.661972
118
0.674749
b2566ebd1e757e5caf4edf7771fc87370b63f8ff
1,493
tab
SQL
wordLists/wikt/wn-wikt-hak.tab
vatbub/auto-hotkey-noun-replacer
467c34292c1cc6465cb2d4003a91021b763b22d7
[ "Apache-2.0" ]
3
2016-07-11T21:11:08.000Z
2016-10-04T01:27:06.000Z
wordLists/wikt/wn-wikt-hak.tab
vatbub/auto-hotkey-noun-replacer
467c34292c1cc6465cb2d4003a91021b763b22d7
[ "Apache-2.0" ]
55
2016-06-24T00:14:38.000Z
2022-03-01T04:03:47.000Z
wordLists/wikt/wn-wikt-hak.tab
vatbub/auto-hotkey-noun-replacer
467c34292c1cc6465cb2d4003a91021b763b22d7
[ "Apache-2.0" ]
null
null
null
# Wiktionary hak http://wiktionary.org/ CC BY-SA 01382086-a hak:lemma 大 01613294-n hak:lemma ên-tiâu 02374451-n hak:lemma 馬 02374451-n hak:lemma 马 02512053-n hak:lemma 魚 02512053-n hak:lemma 鱼 05462315-n hak:lemma 神經系統 06000644-n hak:lemma sṳ-ho̍k 06149484-n hak:lemma 經濟學 06149484-n hak:lemma 经济学 06434165-n hak:lemma Sṳ-sṳ̂-ki 06444148-n hak:lemma Yî-fut-só-sû 06930804-n hak:lemma 客家話 06930804-n hak:lemma 客家话 06947032-n hak:lemma 英文 06950528-n hak:lemma tet-vùn 06952572-n hak:lemma Hò-làn-ngî 06964901-n hak:lemma Fap-vùn 06966825-n hak:lemma sî-pân-ngà-ngî 06969129-n hak:lemma 梵語 06969129-n hak:lemma 梵语 08730550-n hak:lemma 台灣 08730550-n hak:lemma 臺灣 08730550-n hak:lemma 台湾 08730895-n hak:lemma 臺北 08730895-n hak:lemma 台北 08731148-n hak:lemma 香港 08740875-n hak:lemma Me̍t-sî-kô 08761244-n hak:lemma 丹麥 08761244-n hak:lemma 丹麦 08765890-n hak:lemma Shuì-tién 08780881-n hak:lemma 希臘 08780881-n hak:lemma 希腊 08815046-n hak:lemma 盧旺達 08820121-n hak:lemma 加拿大 08845555-n hak:lemma O-thi-li 08849753-n hak:lemma Pí-li-sṳ̀ 08900535-n hak:lemma 印度 08921850-n hak:lemma 日本 08953324-n hak:lemma 冰島 08953324-n hak:lemma 冰岛 09012297-n hak:lemma Oi-sâ-nì-â 09020961-n hak:lemma 塔吉克斯坦 09207288-n hak:lemma Â-chû 09382990-n hak:lemma 太平洋 09505418-n hak:lemma song-ti 09536058-n hak:lemma Songti 10828990-n hak:lemma 奧古斯都 11623105-n hak:lemma hiông-pak-su 14631502-n hak:lemma 鉍 14638799-n hak:lemma 金 14642417-n hak:lemma thiet 14845743-n hak:lemma 水 14942631-n hak:lemma 黃砂 14942631-n hak:lemma 黄砂
26.192982
48
0.785666
e8ff4205f8efbe6454dce1e931b810fa2782cb7c
5,876
py
Python
zkfarmer/utils.py
artarik/zkfarmer
e1297bd27347ac8a5333b4b10aaae3868f457222
[ "MIT" ]
null
null
null
zkfarmer/utils.py
artarik/zkfarmer
e1297bd27347ac8a5333b4b10aaae3868f457222
[ "MIT" ]
null
null
null
zkfarmer/utils.py
artarik/zkfarmer
e1297bd27347ac8a5333b4b10aaae3868f457222
[ "MIT" ]
null
null
null
import json import operator import logging import re import time from socket import socket, AF_INET, SOCK_DGRAM from functools import reduce logger = logging.getLogger(__name__) def ip(): """Find default IP""" ip = None s = socket(AF_INET, SOCK_DGRAM) try: s.connect(('239.255.0.0', 9)) ip = s.getsockname()[0] except socket.error: raise RuntimeError("Cannot determine host IP") finally: del s return ip def serialize(data): try: if type(data) != dict: raise TypeError('Must be a dict') return json.dumps(data) except Exception as e: logger.warn('Cannot serialize: %s [%s]', data, e) return '{}' def unserialize(serialized): if not serialized: return {} try: data = json.loads(serialized) if type(data) != dict: raise TypeError('Not a dict') return data except Exception as e: logger.warn('Cannot unserialize: %s [%s]', serialized, e) return {} def dict_get_path(the_dict, path): try: return reduce(operator.getitem, [the_dict] + path.split('.')) except: return None def dict_set_path(the_dict, path, value): current = the_dict for component in path.split('.')[:-1]: if component not in current or type(current[component]) != dict: current[component] = {} current = current[component] current[path.split('.')[-1]] = value def dict_filter(the_dict, field_or_fields=None): if field_or_fields is None: return the_dict elif type(field_or_fields) == list: fields = {} for f in field_or_fields: fields[f] = dict_get_path(the_dict, f) return fields elif isinstance(field_or_fields, str): return dict_get_path(the_dict, field_or_fields) else: raise TypeError('Invalid type for field path: %s' % type(field_or_fields)) def get_operator(op): try: return {"==": operator.eq, "=": operator.eq, "!=": operator.ne, ">=": operator.ge, "<=": operator.le, ">": operator.gt, "<": operator.lt}[op] except KeyError: raise ValueError('Unknown operator: %s' % op) def match_predicates(predicates, the_dict): for predicate in predicates: m1, m2 = (dict_get_path(the_dict, predicate['path']), predicate['value']) if m1 is None and m2 is not None: return False try: int(m1) int(m2) m1 = int(m1) m2 = int(m2) except (ValueError, TypeError): pass if not predicate['op'](m1, m2): return False return True def create_filter(filters): if not filters: return lambda a_dict: True predicates = [] for f in filters.replace(' ', '').split(','): predicate = {} match = re.split('(!?[^><!=]+)(?:(>=|<=|!=|=|<|>)(.*))?', f, 2) predicate['path'] = match[1] if match[2]: predicate['op'] = get_operator(match[2]) predicate['value'] = match[3] else: # predicate with not operator/value means "fields exists" if predicate['path'][0] == '!': predicate['path'] = predicate['path'][1:] predicate['op'] = operator.is_ else: predicate['op'] = operator.is_not predicate['value'] = None predicates.append(predicate) return lambda the_dict: match_predicates(predicates, the_dict) class ColorizingStreamHandler(logging.StreamHandler): """Provide a nicer logging output to error output with colors""" def __init__(self): self.colors = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'] self.color_map = dict([(x, self.colors.index(x)) for x in self.colors]) self.level_map = { logging.DEBUG: (None, 'blue', " DBG"), logging.INFO: (None, 'green', "INFO"), logging.WARNING: (None, 'yellow', "WARN"), logging.ERROR: (None, 'red', " ERR"), logging.CRITICAL: ('red', 'white', "CRIT") } self.csi = '\x1b[' self.reset = '\x1b[0m' @property def is_tty(self): isatty = getattr(self.stream, 'isatty', None) return isatty and isatty() def colorize(self, message, record): if record.levelno in self.level_map: params = [] if bg in self.color_map: params.append(str(self.color_map[bg] + 40)) if fg in self.color_map: params.append(str(self.color_map[fg] + 30)) if bold: params.append('1') if params: message = ''.join((self.csi, ';'.join(params), 'm', message, self.reset)) return message def format(self, record): message = logging.StreamHandler.format(self, record) # Build the prefix params = [] levelno = record.levelno if levelno not in self.level_map: levelno = logging.WARNING bg, fg, level = self.level_map[levelno] if bg in self.color_map: params.append(str(self.color_map[bg] + 40)) if fg in self.color_map: params.append(str(self.color_map[fg] + 30)) params.append("1m") level = "[%s]" % level return "\n".join(["%s %s: %s" % ( time.strftime("%Y-%m-%dT%H:%M:%S"), self.is_tty and params and ''.join((self.csi, ';'.join(params), level, self.reset)) or level, line) for line in message.split('\n')])
31.934783
96
0.536079
5b6aeed978cdf2b4c9806a2fae599061a37bf67d
854
cpp
C++
courses/Course_14/Source.cpp
catalinboja/cpp-2021
fbc8147b35bce9d0ea9de7d9b166e1dc3d61d4e7
[ "MIT" ]
null
null
null
courses/Course_14/Source.cpp
catalinboja/cpp-2021
fbc8147b35bce9d0ea9de7d9b166e1dc3d61d4e7
[ "MIT" ]
null
null
null
courses/Course_14/Source.cpp
catalinboja/cpp-2021
fbc8147b35bce9d0ea9de7d9b166e1dc3d61d4e7
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; class Person { protected: string name; int age; public: virtual string GetDescription() = 0; //virtual pure method / abstract method string getName() { return this->name; } }; class Student: public Person { string faculty; public: string GetDescription() { return "Student description"; } }; class Prof: public Person { string courseName; public: string GetDescription() { return "Prof description"; } }; template <typename T> T add(T a, T b) { return a + b; } int main() { //Person person; Person* pointerToPerson = nullptr; Person* persons[2]; persons[0] = new Student(); persons[1] = new Prof(); for (int i = 0; i < 2; i++) { cout << endl << persons[i]->GetDescription(); } int result = add<int>(3, 5); float otherResult = add<float>(3.5, 5.6); }
14.982456
79
0.652225
33b362143b2f19c4ac5cb60fa39b8ed481da039c
609
kt
Kotlin
src/main/kotlin/me/maya/revolt/api/Member.kt
XuaTheGrate/RevoltKt
4d5fd69874320536c18b95b5fe14d2f8c5b253bc
[ "MIT" ]
7
2021-09-01T13:27:54.000Z
2022-01-16T19:45:23.000Z
src/main/kotlin/me/maya/revolt/api/Member.kt
XuaTheGrate/RevoltKt
4d5fd69874320536c18b95b5fe14d2f8c5b253bc
[ "MIT" ]
null
null
null
src/main/kotlin/me/maya/revolt/api/Member.kt
XuaTheGrate/RevoltKt
4d5fd69874320536c18b95b5fe14d2f8c5b253bc
[ "MIT" ]
1
2021-12-10T08:45:17.000Z
2021-12-10T08:45:17.000Z
package me.maya.revolt.api interface Member: IHasID, IUpdateable<Member> { val nickname: String? val user: User val roles: List<Role> val avatar: Image? val server: Server suspend fun edit( nickname: String? = null, // avatar: Image? = null, // TODO ) suspend fun addRole(role: Role) suspend fun addRoles(vararg roles: Role) suspend fun removeRole(role: Role) suspend fun removeRoles(vararg roles: Role) suspend fun updateRoles(roles: List<Role>) suspend fun kick() suspend fun ban(reason: String? = null) suspend fun unban() }
23.423077
47
0.65353
683f6fa405688a2c594759877f76ed1e1ac77aaf
43,042
cpp
C++
vpr/src/ripple/lg/lg_main.cpp
honeychen718/vtrwithap
c5073f89dad7e02a6f898d795be8d624591ff39e
[ "MIT" ]
null
null
null
vpr/src/ripple/lg/lg_main.cpp
honeychen718/vtrwithap
c5073f89dad7e02a6f898d795be8d624591ff39e
[ "MIT" ]
null
null
null
vpr/src/ripple/lg/lg_main.cpp
honeychen718/vtrwithap
c5073f89dad7e02a6f898d795be8d624591ff39e
[ "MIT" ]
null
null
null
#include "pack/clb.h" #include "alg/bipartite.h" #include "lg_main.h" #include "lg_dp_utils.h" #include "gp_setting.h" #include "SetupGrid.h" #include "vtr_math.h" #include "vpr_clb.h" //for debug // #include "DebugNew.h" const t_ext_pin_util FULL_EXTERNAL_PIN_UTIL(1., 1.); void read_cluster_placement_stats_from_clb( int type_index, VPR_CLB *clb, //map<int,map<t_pb_type*,map<t_pb_graph_node*,ripple_primitive_stats>>> &ripple_cluster_placement_stats, t_cluster_placement_stats* cluster_placement_stats_ptr){ int t , m; t_cluster_placement_primitive *cur , *prev; ripple_primitive_stats ripple_primitive_stats; //t_cluster_placement_stats* cluster_placement_stats_ptr; for (size_t i = 0; i < clb->block_types.size(); i++) { //auto &type=clb->block_types[i]; //cluster_placement_stats_ptr=&cluster_placement_stats[type_index]; reset_cluster_placement_stats(cluster_placement_stats_ptr); if(clb->type_index_to_cluster_placement_stats.find(type_index)==clb->type_index_to_cluster_placement_stats.end()){ //initiate type_index_to_cluster_placement_stats[type->index] in clb for (t = 0; t < cluster_placement_stats_ptr->num_pb_types; t++) { if (cluster_placement_stats_ptr->valid_primitives[t]->next_primitive == nullptr) { continue; } cur = cluster_placement_stats_ptr->valid_primitives[t]->next_primitive; while(cur){ ripple_primitive_stats.base_cost=cur->base_cost; ripple_primitive_stats.incremental_cost=cur->incremental_cost; ripple_primitive_stats.valid=cur->valid; clb->type_index_to_cluster_placement_stats[type_index][cur->pb_graph_node->pb_type][cur->pb_graph_node]=ripple_primitive_stats; cur = cur->next_primitive; } } }else{ //write type_index_to_cluster_placement_stats[type->index] to cluster_placement_stats for (t = 0; t < cluster_placement_stats_ptr->num_pb_types; t++) { if (cluster_placement_stats_ptr->valid_primitives[t]->next_primitive == nullptr) { continue; } prev = cluster_placement_stats_ptr->valid_primitives[t]; cur = cluster_placement_stats_ptr->valid_primitives[t]->next_primitive; while(cur){ ripple_primitive_stats=clb->type_index_to_cluster_placement_stats[type_index][cur->pb_graph_node->pb_type][cur->pb_graph_node]; cur->base_cost=ripple_primitive_stats.base_cost; cur->incremental_cost=ripple_primitive_stats.incremental_cost; cur->valid=ripple_primitive_stats.valid; if(cur->valid == false){ cur->valid = 0; prev->next_primitive = cur->next_primitive; cur->next_primitive = cluster_placement_stats_ptr->invalid; cluster_placement_stats_ptr->invalid = cur; cur = prev->next_primitive; }else{ prev = cur; cur = cur->next_primitive; } } } } } } void write_cluster_placement_stats_to_clb(map<int,map<t_pb_type*,map<t_pb_graph_node*,ripple_primitive_stats>>> &ripple_cluster_placement_stats, t_cluster_placement_stats* cluster_placement_stats){ // int i; t_cluster_placement_stats* cluster_placement_stats_ptr; t_cluster_placement_primitive *cur; for(auto &pair:ripple_cluster_placement_stats){ cluster_placement_stats_ptr=&cluster_placement_stats[pair.first]; flush_intermediate_queues(cluster_placement_stats_ptr); //VTR_ASSERT(!cluster_placement_stats_ptr->tried && !cluster_placement_stats_ptr->in_flight); cur=cluster_placement_stats_ptr->invalid; while(cur){ auto &ripple_primitive=pair.second[cur->pb_graph_node->pb_type][cur->pb_graph_node]; ripple_primitive.base_cost=cur->base_cost; ripple_primitive.incremental_cost=cur->incremental_cost; //VTR_ASSERT(!cur->valid); ripple_primitive.valid=cur->valid; cur=cur->next_primitive; } for (i = 0; i < cluster_placement_stats_ptr->num_pb_types; i++) { cur=cluster_placement_stats_ptr->valid_primitives[i]->next_primitive; while(cur){ auto &ripple_primitive=pair.second[cur->pb_graph_node->pb_type][cur->pb_graph_node]; ripple_primitive.base_cost=cur->base_cost; ripple_primitive.incremental_cost=cur->incremental_cost; //VTR_ASSERT(cur->valid); ripple_primitive.valid=cur->valid; cur=cur->next_primitive; } } } } bool vpr_start_new_cluster( VPR_CLB* &clb,t_pack_molecule* molecule,t_packer_opts& packer_opts, std::vector<t_lb_type_rr_node>* &lb_type_rr_graphs, const std::multimap<AtomBlockId, t_pack_molecule*>& atom_molecules, t_pb_graph_node** primitives_list, int max_cluster_size,ClusterBlockId clb_index, ClusteredNetlist* &clb_nlist,t_lb_router_data* &router_data, std::map<t_logical_block_type_ptr, size_t>& num_used_type_instances, const std::map<const t_model*, std::vector<t_logical_block_type_ptr>>& primitive_candidate_block_types, PartitionRegion& temp_cluster_pr, bool balance_block_type_utilization, t_cluster_placement_stats* cluster_placement_stats){ auto& atom_ctx = g_vpr_ctx.atom(); auto& device_ctx = g_vpr_ctx.mutable_device(); auto& floorplanning_ctx = g_vpr_ctx.mutable_floorplanning(); /*Cluster's PartitionRegion is empty initially, meaning it has no floorplanning constraints*/ PartitionRegion empty_pr; floorplanning_ctx.cluster_constraints.push_back(empty_pr); /* Allocate a dummy initial cluster and load a atom block as a seed and check if it is legal */ AtomBlockId root_atom = molecule->atom_block_ids[molecule->root]; const std::string& root_atom_name = atom_ctx.nlist.block_name(root_atom); const t_model* root_model = atom_ctx.nlist.block_model(root_atom); auto itr = primitive_candidate_block_types.find(root_model); VTR_ASSERT(itr != primitive_candidate_block_types.end()); //std::vector<t_logical_block_type_ptr> candidate_types = itr->second; clb->block_types = itr->second; if (balance_block_type_utilization) { //We sort the candidate types in ascending order by their current utilization. //This means that the packer will prefer to use types with lower utilization. //This is a naive approach to try balancing utilization when multiple types can //support the same primitive(s). std::stable_sort(clb->block_types.begin(), clb->block_types.end(), [&](t_logical_block_type_ptr lhs, t_logical_block_type_ptr rhs) { int lhs_num_instances = 0; int rhs_num_instances = 0; // Count number of instances for each type for (auto type : lhs->equivalent_tiles) lhs_num_instances += device_ctx.grid.num_instances(type); for (auto type : rhs->equivalent_tiles) rhs_num_instances += device_ctx.grid.num_instances(type); float lhs_util = vtr::safe_ratio<float>(num_used_type_instances[lhs], lhs_num_instances); float rhs_util = vtr::safe_ratio<float>(num_used_type_instances[rhs], rhs_num_instances); //Lower util first return lhs_util < rhs_util; }); } //t_pb* &pb = pb; //PartitionRegion temp_cluster_pr; bool success=false; t_cluster_placement_stats* cluster_placement_stats_ptr; //ripple_primitives_stats ripple_cur; // cluster_placement_stats_for_ripple ripple_placement_stats; // placement_primitives_for_ripple ripple_placement_primitives; for (size_t i = 0; i < clb->block_types.size(); i++) { auto type =clb->block_types[i]; t_pb* pb = new t_pb; pb->pb_graph_node = type->pb_graph_head; alloc_and_load_pb_stats(pb, packer_opts.feasible_block_array_size); pb->parent_pb = nullptr; router_data=alloc_and_load_router_data(&lb_type_rr_graphs[type->index], type); cluster_placement_stats_ptr=&cluster_placement_stats[type->index]; e_block_pack_status pack_result = BLK_STATUS_UNDEFINED; read_cluster_placement_stats_from_clb(type->index,clb,cluster_placement_stats_ptr); for (int j = 0; j < type->pb_graph_head->pb_type->num_modes && !success; j++) { pb->mode = j; //********************************** // if(clb->type_index_to_cluster_placement_stats.find(type->index)==clb->type_index_to_cluster_placement_stats.end()){ // clb->type_index_to_cluster_placement_stats[type->index]= new t_cluster_placement_stats; // *(clb->type_index_to_cluster_placement_stats[type->index])=cluster_placement_stats[type->index]; // } //reset_cluster_placement_stats(clb->type_index_to_cluster_placement_stats[type->index]); //clb->cluster_placement_stats=alloc_and_load_cluster_placement_stats(); reset_cluster_placement_stats(cluster_placement_stats_ptr); set_mode_cluster_placement_stats(pb->pb_graph_node, j); //********************************************************* pack_result = try_pack_molecule(cluster_placement_stats_ptr, atom_molecules, molecule, primitives_list, pb, database.num_models, max_cluster_size, clb_index, 1,//detailed_routing_stage, set to 1 for now router_data, packer_opts.pack_verbosity, packer_opts.enable_pin_feasibility_filter, packer_opts.feasible_block_array_size, FULL_EXTERNAL_PIN_UTIL, temp_cluster_pr); success = (pack_result == BLK_PASSED); } if (success) { //Once clustering succeeds, add it to the clb netlist if (pb->name != nullptr) { free(pb->name); } pb->name = vtr::strdup(root_atom_name.c_str()); clb_index =clb_nlist->create_block(root_atom_name.c_str(), pb, type); for(auto &pair:clb->type_index_to_cluster_placement_stats){ if(pair.first != type->index){ clb->type_index_to_cluster_placement_stats.erase(pair.first); } } break; } else { //Free failed clustering and try again free_router_data(router_data); free_pb(pb); delete pb; router_data = nullptr; } } if(!success) { printlog(LOG_ERROR, "vpr_start_new_cluster failed!!"); std::abort(); } //Successfully create cluster auto block_type = clb_nlist->block_type(clb_index); num_used_type_instances[block_type]++; /* Expand FPGA size if needed */ // Check used type instances against the possible equivalent physical locations unsigned int num_instances = 0; for (auto equivalent_tile : block_type->equivalent_tiles) { num_instances += device_ctx.grid.num_instances(equivalent_tile); } if (num_used_type_instances[block_type] > num_instances) { //to be un//ed //device_ctx.grid = create_device_grid(device_layout_name, arch->grid_layouts, num_used_type_instances, target_device_utilization); printlog(LOG_INFO, "device to be expanded"); } return success; } bool ExceedClkrgn(Group& group, vector<Site*>& candSites) { if (database.crmap_nx == 0) return false; for (auto site : candSites) { if (group.InClkBox(site)) return false; } cout << group.lgBox.lx() << " " << group.lgBox.ly() << " " << group.lgBox.ux() << " " << group.lgBox.uy() << endl; return true; } /* bool Legalizer::MergeGroupToSite(Site* site, Group& group, bool fixDspRam) { if (site->pack == NULL) { database.place(database.addPack(site->type), site->x, site->y); } auto& type = site->type->name; if (type == SiteType::SLICE) { lgData.invokeCount++; if (lgData.clbMap[site->x][site->y]->AddInsts(group)) { lgData.successCount++; return true; } } else if (type == SiteType::DSP || type == SiteType::BRAM) { if (database.place(group.instances[0], site, 0)) { if (fixDspRam) group.instances[0]->fixed = true; return true; } } else if (type == SiteType::IO) { for (int i = 0; i < (int)site->pack->instances.size(); i++) { if (database.place(group.instances[0], site, i)) return true; } } return false; } */ bool Legalizer::MergeGroupToSite(Site* site, Group& group, bool fixDspRam) { if (site->pack == NULL) { database.place(database.addPack(site->type), site->x, site->y); } auto& type = site->type->name; if (type == SiteType::IO) { lgData.invokeCount++; for (int i = 0; i < database.subtile_capacity[site->type]; i++) { if(lgData.clbMap[site->x][site->y][i].is_full){ continue; } if (lgData.clbMap[site->x][site->y][i].AddInsts(group)) { lgData.successCount++; lgData.clbMap[site->x][site->y][i].is_full=true; return true; } } }else if(type != SiteType::EMPTY){ lgData.invokeCount++; for (int i = 0; i < database.subtile_capacity[site->type]; i++) { if (lgData.clbMap[site->x][site->y][i].AddInsts(group)) { lgData.successCount++; return true; } } } return false; } bool Legalizer::MergeMoleculeToSite(Site* site, t_pack_molecule* molecule, bool fixDspRam,t_packer_opts& packer_opts, std::vector<t_lb_type_rr_node>* lb_type_rr_graphs, //t_pack_molecule* molecule_head, std::multimap<AtomBlockId, t_pack_molecule*>& atom_molecules, t_pb_graph_node** primitives_list, int max_cluster_size,ClusteredNetlist* clb_nlist, std::map<t_logical_block_type_ptr, size_t>& num_used_type_instances, //const std::unordered_set<AtomNetId>& is_clock, //const t_pack_high_fanout_thresholds& high_fanout_thresholds, //std::shared_ptr<SetupTimingInfo>& timing_info, const t_ext_pin_util_targets& ext_pin_util_targets, //vtr::vector<ClusterBlockId, std::vector<t_intra_lb_net>*>& intra_lb_routing, //vtr::vector<ClusterBlockId, std::vector<AtomNetId>>& clb_inter_blk_nets, //t_pb_type* le_pb_type, int& num_clb, const std::map<const t_model*, std::vector<t_logical_block_type_ptr>>& primitive_candidate_block_types, bool balance_block_type_utilization, t_cluster_placement_stats* cluster_placement_stats) { if (site->pack == NULL) { database.place(database.addPack(site->type), site->x, site->y); } // if(site==database.getSite(14,0)){ // cout<<"find site"<<endl; // } // AtomBlockId target_blk_id = AtomBlockId(162); // if(molecule->atom_block_ids[0]==target_blk_id){ // cout<<"find blk"<<endl; // } //**************************** // t_cluster_placement_stats *cluster_placement_stats; // t_pb_graph_node** primitives_list; // t_lb_router_data* router_data = nullptr; // const t_molecule_stats max_molecule_stats = calc_max_molecules_stats(molecule_head); // mark_all_molecules_valid(molecule_head); // int num_molecules = count_molecules(molecule_head); // int cur_cluster_size,cur_pb_depth,max_cluster_size,max_pb_depth; // for (const auto& type : g_vpr_ctx.mutable_device().logical_block_types) { // if (is_empty_type(&type)) // continue; // cur_cluster_size = get_max_primitives_in_pb_type(type.pb_type); // cur_pb_depth = get_max_depth_of_pb_type(type.pb_type); // if (cur_cluster_size > max_cluster_size) { // max_cluster_size = cur_cluster_size; // } // if (cur_pb_depth > max_pb_depth) { // max_pb_depth = cur_pb_depth; // } // } // alloc_and_init_clustering(max_molecule_stats, // &cluster_placement_stats, &primitives_list, molecule_head, // num_molecules); bool success; bool is_cluster_legal= false; enum e_block_pack_status block_pack_status; t_ext_pin_util target_ext_pin_util; t_cluster_placement_stats* cur_cluster_placement_stats_ptr; //PartitionRegion temp_cluster_pr; auto& atom_ctx = g_vpr_ctx.atom(); auto& cluster_ctx = g_vpr_ctx.mutable_clustering(); VPR_CLB* clb=nullptr; if(site->type->name == SiteType::IO){ for(int i = 0;i<database.subtile_capacity[site->type];i++){ if(!lgData.clbMap[site->x][site->y][i].is_full){ clb = &lgData.clbMap[site->x][site->y][i]; site->cur_cluster=i; break; } } if(clb==nullptr){ return false; } }else{ clb = lgData.clbMap[site->x][site->y]; site->cur_cluster=0; } ClusterBlockId clb_index; if(!clb->CLBIsEmpty){ clb_index=(ClusterBlockId)num_clb; success=vpr_start_new_cluster( clb,molecule,packer_opts,lb_type_rr_graphs, atom_molecules, primitives_list,max_cluster_size,clb_index,clb_nlist, clb->router_data,num_used_type_instances,primitive_candidate_block_types, clb->temp_cluster_pr,balance_block_type_utilization, cluster_placement_stats); if(success){ //router_data=nullptr; clb->CLBIsEmpty=true; clb->index=clb_index; num_clb++; } }else{ int type_index; clb_index=clb->index; type_index=cluster_ctx.clb_nlist.block_type(clb_index)->index; cur_cluster_placement_stats_ptr = &cluster_placement_stats[type_index]; target_ext_pin_util = ext_pin_util_targets.get_pin_util(cluster_ctx.clb_nlist.block_type(clb_index)->name); read_cluster_placement_stats_from_clb(type_index,clb,cur_cluster_placement_stats_ptr); block_pack_status = try_pack_molecule(cur_cluster_placement_stats_ptr, atom_molecules, molecule, primitives_list, cluster_ctx.clb_nlist.block_pb(clb_index), database.num_models, max_cluster_size, clb_index, 1,//detailed_routing_stage set to 1 clb->router_data, packer_opts.pack_verbosity, packer_opts.enable_pin_feasibility_filter, packer_opts.feasible_block_array_size, target_ext_pin_util, clb->temp_cluster_pr); success = block_pack_status == BLK_PASSED; } if(success){ write_cluster_placement_stats_to_clb(clb->type_index_to_cluster_placement_stats,cluster_placement_stats); } //if(high_fanout_thresholds != NULL) cout<<1<<endl; //cout<<1<<endl; //auto block_type = clb_nlist->block_type(clb_index); // for(int v=0;v<group.instances.size();v++){ // cout<<group.instances[v]->vpratomblkid.id<<"\t"; // } // cout<<endl; //**************************** auto& type = site->type->name; if (type == SiteType::SLICE) { lgData.invokeCount++; if (success) { lgData.successCount++; } } if(type == SiteType::IO){ if(success){ clb->is_full=true; } } return success; } bool Legalizer::AssignPackToSite(Site* site, Group& group) { if (site->pack == NULL && group.IsTypeMatch(site)) { database.place(database.addPack(site->type), site->x, site->y); for (unsigned i = 0; i < group.instances.size(); i++) { if (group.instances[i] != NULL) { database.place(group.instances[i], site); } else { site->pack->instances[i] = NULL; } } return true; } else return false; } void Legalizer::SortCandSitesByHpwl(vector<Site*>& candSites, const Group& group) { function<double(Site*)> cal_hpwl = [&](Site* site) { double wl = 0; double gx = lgData.groupsX[group.id], gy = lgData.groupsY[group.id]; for (auto net : lgData.group2Nets[group.id]) { if (net->isClk) continue; const auto& b = lgData.netBox[net->id]; if (b.size() == 1) continue; Box<double> tmpBox(b.x.ou(gx), b.y.ou(gy), b.x.ol(gx), b.y.ol(gy)); tmpBox.fupdate(site->cx(), site->cy()); wl += tmpBox.uhp(); } return ((int)(wl * 1000)) / 1000.0; }; ComputeAndSort(candSites, cal_hpwl, less<double>()); // ComputeAndSort(candSites, cal_hpwl, less<double>(), true); // originally, sites are in the order of disp // changing to non-stable sort will 3% tot runtime improvement } void Legalizer::SortCandSitesByPins(vector<Site*>& candSites, const Group& group) { function<int(Site*)> cal_npin = [&](Site* site) { return lgData.nPinPerSite[site->x][site->y]; }; ComputeAndSort(candSites, cal_npin, less<int>()); } void Legalizer::SortCandSitesByAlign(vector<Site*>& candSites, const Group& group) { function<int(Site*)> cal_align = [&](Site* site) { int align = 0; for (auto net : lgData.group2Nets[group.id]) { if (net->isClk) continue; for (auto groupId : lgData.net2Gids[net->id]) { if (groupId == group.id) continue; int gx = lgData.groupsX[groupId]; int gy = lgData.groupsY[groupId]; if (site->x == gx) { align += 1; } if (site->y == gy) { align += 2; if (SWCol(site->x) == SWCol(gx)) align += 1; } } } return align; }; ComputeAndSort(candSites, cal_align, greater<int>()); } void Legalizer::SortGroupsByGroupsize() { function<int(int)> cal_gs = [&](int gid) { int size = 0; for (auto inst : groups[gid].instances) { if (inst == NULL) continue; if (inst->IsFF()) size += 3; else if (inst->IsLUT()) size++; } return size; }; ComputeAndSort(lgData.groupIds, cal_gs, greater<int>()); } void Legalizer::SortGroupsByPins() { function<int(int)> cal_npin = [&](int gid) { return lgData.group2Nets[gid].size(); }; ComputeAndSort(lgData.groupIds, cal_npin, greater<int>()); } void Legalizer::SortGroupsByLGBox() { function<int(int)> cal_boxsz = [&](int gid) { return groups[gid].lgBox.x() * groups[gid].lgBox.y(); }; ComputeAndSort(lgData.groupIds, cal_boxsz, less<int>(), true); } void Legalizer::SortGroupsByOptRgnDist() { function<double(int)> cal_ordist = [&](int gid) { double lx, hx, ly, hy; vector<double> boxX, boxY; for (auto net : lgData.group2Nets[gid]) { if (net->isClk) continue; const auto& b = lgData.netBox[net->id]; if (b.size() == 1) continue; boxX.push_back(b.x.ol(groups[gid].x)); boxX.push_back(b.x.ou(groups[gid].x)); boxY.push_back(b.y.ol(groups[gid].y)); boxY.push_back(b.y.ou(groups[gid].y)); } GetMedianTwo(boxX, lx, hx); GetMedianTwo(boxY, ly, hy); Box<double> optrgn(hx, hy, lx, ly); return optrgn.udist(groups[gid].x, groups[gid].y); }; ComputeAndSort(lgData.groupIds, cal_ordist, greater<int>()); } Legalizer::Legalizer(vector<Group>& _groups) : groups(_groups), lgData(_groups) {} void Legalizer::Init(lgPackMethod packMethod) { mark_all_molecules_valid(database.list_of_pack_molecules); lgData.Init(packMethod); } void Legalizer::GetResult(lgRetrunGroup retGroup,lgGetResultMethod all_or_partial) { lgData.GetDispStatics(); lgData.GetResult(retGroup,all_or_partial);//modified by jia lgData.GetPackStatics(); } bool Legalizer::RunAll(lgSiteOrder siteOrder, lgGroupOrder groupOrder) { const int MAX_WIN = 1000; // SortGroupsByPins(); // SortGroupsByGroupsize(); //better for overlap reduction // SortGroupsByOptRgnDist(); //better for hpwl reduction if (groupOrder == GROUP_LGBOX) { printlog(LOG_INFO, "group order: GROUP_LGBOX"); SortGroupsByLGBox(); } else { printlog(LOG_INFO, "group order: DEFAULT"); } int nChain = 0, chainLen = 0, nSucc = 0; for (const auto gid : lgData.groupIds) { Group& group = groups[gid]; bool isFixed = false; for (auto inst : group.instances) { if (inst != NULL && inst->fixed) { isFixed = true; break; } } if (isFixed) { lgData.placedGroupMap[lgData.groupsX[gid]][lgData.groupsY[gid]].push_back(group.id); continue; } int winWidth = 0; bool isPlaced = false; Site* curSite = NULL; while (!isPlaced) { vector<Site*> candSites; if (siteOrder != SITE_HPWL_SMALL_WIN) { while (candSites.size() < 200) { GetWinElem(candSites, database.sites, {lgData.groupsX[gid], lgData.groupsY[gid]}, winWidth); if (candSites.size() == 0) break; winWidth++; } } else { GetWinElem(candSites, database.sites, {lgData.groupsX[gid], lgData.groupsY[gid]}, winWidth); winWidth++; } if (ExceedClkrgn(group, candSites) || winWidth >= MAX_WIN || candSites.size() == 0) { printlog(LOG_WARN, "no candSites available"); break; } SqueezeCandSites(candSites, group, !group.IsBLE()); if (siteOrder == SITE_HPWL || siteOrder == SITE_HPWL_SMALL_WIN) SortCandSitesByHpwl(candSites, group); else if (siteOrder == SITE_ALIGN) SortCandSitesByAlign(candSites, group); for (unsigned s = 0; !isPlaced && s < candSites.size(); s++) { curSite = candSites[s]; if (MergeGroupToSite(curSite, group, false)) { isPlaced = true; lgData.PartialUpdate(group, curSite); } } } if (!isPlaced) return false; } printlog(LOG_INFO, "chain move: avgLen=%.2f, #fail=%d, #success=%d(%.2f%%)", chainLen * 1.0 / nSucc, nChain - nSucc, nSucc, nSucc * 100.0 / nChain); return true; } bool Legalizer::RunAll( lgSiteOrder siteOrder, lgGroupOrder groupOrder, t_packer_opts& packer_opts,//these two are member of vpr_setup std::vector<t_lb_type_rr_node>* lb_type_rr_graphs,//these two are member of vpr_setup std::multimap<AtomBlockId, t_pack_molecule*>& atom_molecules, t_pb_graph_node** primitives_list, int max_cluster_size,ClusteredNetlist* clb_nlist, std::map<t_logical_block_type_ptr, size_t>& num_used_type_instances, const std::unordered_set<AtomNetId>& is_clock,const t_pack_high_fanout_thresholds& high_fanout_thresholds, std::shared_ptr<SetupTimingInfo>& timing_info, const t_ext_pin_util_targets& ext_pin_util_targets, vtr::vector<ClusterBlockId, std::vector<t_intra_lb_net>*>& intra_lb_routing, vtr::vector<ClusterBlockId, std::vector<AtomNetId>>& clb_inter_blk_nets, t_logical_block_type_ptr& logic_block_type,t_pb_type* le_pb_type, std::vector<int>& le_count,int& num_clb, const std::map<const t_model*, std::vector<t_logical_block_type_ptr>>& primitive_candidate_block_types, bool balance_block_type_utilization, t_cluster_placement_stats* cluster_placement_stats) { const int MAX_WIN = 1000; // SortGroupsByPins(); // SortGroupsByGroupsize(); //better for overlap reduction // SortGroupsByOptRgnDist(); //better for hpwl reduction if (groupOrder == GROUP_LGBOX) { printlog(LOG_INFO, "group order: GROUP_LGBOX"); SortGroupsByLGBox(); } else { printlog(LOG_INFO, "group order: DEFAULT"); } int nChain = 0, chainLen = 0, nSucc = 0; // for(auto grouptemp:groups){ // for (auto instancetemp:grouptemp.instances){ // if(instancetemp->id==260){ // cout<<"findinstance"<<endl; // } // } // } auto& cluster_ctx = g_vpr_ctx.mutable_clustering(); for (const auto gid : lgData.groupIds) { // cout<<gid<<endl; // if(gid==475){ // cout<<"checkbreak"<<endl; // } Group& group = groups[gid]; // for(auto insttemp:group.instances ){ // if (insttemp->id==0){ // cout<<"here"<<endl; // } // } bool isFixed = false; for (auto inst : group.instances) { if (inst != NULL && inst->fixed) { isFixed = true; break; } } if (isFixed) { lgData.placedGroupMap[lgData.groupsX[gid]][lgData.groupsY[gid]].push_back(group.id); continue; } int winWidth = 0; bool isPlaced = false; Site* curSite = NULL; while (!isPlaced) { vector<Site*> candSites; if (siteOrder != SITE_HPWL_SMALL_WIN) { while (candSites.size() < 200) { GetWinElem(candSites, database.sites, {lgData.groupsX[gid], lgData.groupsY[gid]}, winWidth); if (candSites.size() == 0) break; winWidth++; } } else { GetWinElem(candSites, database.sites, {lgData.groupsX[gid], lgData.groupsY[gid]}, winWidth); winWidth++; } if (ExceedClkrgn(group, candSites) || winWidth >= MAX_WIN || candSites.size() == 0) { printlog(LOG_WARN, "no candSites available"); break; } SqueezeCandSites(candSites, group, !group.IsBLE()); if (siteOrder == SITE_HPWL || siteOrder == SITE_HPWL_SMALL_WIN) SortCandSitesByHpwl(candSites, group); else if (siteOrder == SITE_ALIGN) SortCandSitesByAlign(candSites, group); for (unsigned s = 0; !isPlaced && s < candSites.size(); s++) { curSite = candSites[s]; isPlaced=true; if(!MergeMoleculeToSite(curSite, group.vpr_molecule, false,packer_opts, lb_type_rr_graphs,atom_molecules, primitives_list,max_cluster_size,clb_nlist,num_used_type_instances, //is_clock,timing_info, ext_pin_util_targets, //intra_lb_routing, //logic_block_type, num_clb,primitive_candidate_block_types, balance_block_type_utilization,cluster_placement_stats)){ isPlaced=false; } if(isPlaced){ //place succeed!!! auto clb_index=lgData.clbMap[curSite->x][curSite->y][curSite->cur_cluster].index; int high_fanout_threshold = high_fanout_thresholds.get_threshold(cluster_ctx.clb_nlist.block_type(clb_index)->name); update_cluster_stats(group.vpr_molecule, clb_index, is_clock, //Set of clock nets is_clock, //Set of global nets (currently all clocks) packer_opts.global_clocks, packer_opts.alpha, packer_opts.beta, packer_opts.timing_driven, packer_opts.connection_driven, high_fanout_threshold, *timing_info); lgData.PartialUpdate(group, curSite); double disp = abs((int)group.x - (int)lgData.groupsX[group.id]) + abs((int)group.y - (int)lgData.groupsY[group.id]); //jia: no clock region!!!! // if (disp != 0 && database.crmap_nx != 0) { // int len = ChainMove(group, DISP_OPT); // if (len != -1) { // nSucc++; // chainLen += len; // } // nChain++; // } // disp = abs((int)group.x - (int)lgData.groupsX[group.id]) + // abs((int)group.y - (int)lgData.groupsY[group.id]); if (disp >= 2 && database.crmap_nx != 0) { int len = ChainMove(group, MAX_DISP_OPT); if (len != -1) { nSucc++; chainLen += len; } nChain++; } lgData.clbMap[curSite->x][curSite->y][curSite->cur_cluster].AddInsts(group); } } } if (!isPlaced) return false; } /**************************************************************** * after finishing a clb in vpr *****************************************************************/ bool is_cluster_legal; auto& atom_ctx = g_vpr_ctx.atom(); for(int x=0;x<database.sitemap_nx;x++){ for(int y=0;y<database.sitemap_ny;y++){ for(int i=0;i< database.subtile_capacity[database.getSite(x,y)->type] ; i++){ VPR_CLB* clb=&lgData.clbMap[x][y][i]; if(clb!=nullptr && clb->CLBIsEmpty){ intra_lb_routing.push_back(clb->router_data->saved_lb_nets); //VTR_ASSERT((int)intra_lb_routing.size() == num_clb); // if((int)intra_lb_routing.size() != num_clb){ // printlog(LOG_ERROR, "intra_lb_routing.size() != num_clb"); // } clb->router_data->saved_lb_nets = nullptr; //Pick a new seed //istart = get_highest_gain_seed_molecule(&seedindex, atom_molecules, seed_atoms); // if (packer_opts.timing_driven) { // if (num_blocks_hill_added > 0) { // blocks_since_last_analysis += num_blocks_hill_added; // } // } /* store info that will be used later in packing from pb_stats and free the rest */ t_pb_stats* pb_stats = cluster_ctx.clb_nlist.block_pb(clb->index)->pb_stats; for (const AtomNetId mnet_id : pb_stats->marked_nets) { int external_terminals = atom_ctx.nlist.net_pins(mnet_id).size() - pb_stats->num_pins_of_net_in_pb[mnet_id]; /* Check if external terminals of net is within the fanout limit and that there exists external terminals */ if (external_terminals < packer_opts.transitive_fanout_threshold && external_terminals > 0) { clb_inter_blk_nets[clb->index].push_back(mnet_id); } } auto cur_pb = cluster_ctx.clb_nlist.block_pb(clb->index); // update the data structure holding the LE counts update_le_count(cur_pb, logic_block_type, le_pb_type, le_count); //print clustering progress incrementally //print_pack_status(num_clb, num_molecules, num_molecules_processed, mols_since_last_print, device_ctx.grid.width(), device_ctx.grid.height()); free_pb_stats_recursive(cur_pb); } //free_router_data(router_data); //router_data = nullptr;//? necessary? } } } //free_cluster_placement_stats(cluster_placement_stats); printlog(LOG_INFO, "chain move: avgLen=%.2f, #fail=%d, #success=%d(%.2f%%)", chainLen * 1.0 / nSucc, nChain - nSucc, nSucc, nSucc * 100.0 / nChain); return true; } void Legalizer::RunPartial() { for (auto type : {SiteType::DSP, SiteType::BRAM}) BipartiteLeg(type, 10); } void Legalizer::BipartiteLeg(SiteType::Name type, int minNumSites) { assert(minNumSites <= 100); vector<Group*> cells; for (auto& g : groups) { if (g.GetSiteType() == type) { cells.push_back(&g); for (auto inst : g.instances) { database.unplace(inst); } } } database.ClearEmptyPack(); std::unordered_map<Site*, int> siteIds; vector<Site*> sites; vector<vector<pair<int, long>>> allCandSites(cells.size()); // (site, score) TODO: secondary obj disp // add safe sites for (size_t cid = 0; cid < cells.size(); ++cid) { auto& cell = *cells[cid]; int winWidth = 0; bool found = false; for (; !found; ++winWidth) { vector<Site*> candSites; GetWinElem(candSites, database.sites, {lgData.groupsX[cell.id], lgData.groupsY[cell.id]}, winWidth); if (ExceedClkrgn(cell, candSites)) { printlog(LOG_ERROR, "BipartiteLeg: cannot find safe sites"); exit(1); } SqueezeCandSites(candSites, cell, true); SortCandSitesByHpwl(candSites, cell); for (auto site : candSites) { auto it = siteIds.find(site); if (it == siteIds.end()) { int sid = siteIds.size(); siteIds[site] = sid; sites.push_back(site); allCandSites[cid].push_back({sid, -1}); found = true; break; } } } } // add more sites for (size_t cid = 0; cid < cells.size(); ++cid) { auto& cell = *cells[cid]; vector<Site*> candSites; for (int winWidth = 0; (int)candSites.size() < minNumSites; ++winWidth) { GetWinElem(candSites, database.sites, {lgData.groupsX[cell.id], lgData.groupsY[cell.id]}, winWidth); SqueezeCandSites(candSites, cell, true); } for (auto site : candSites) { int sid; auto it = siteIds.find(site); if (it == siteIds.end()) { sid = siteIds.size(); siteIds[site] = sid; sites.push_back(site); } else sid = it->second; allCandSites[cid].push_back({sid, -1}); } } // cal wl for (size_t cid = 0; cid < cells.size(); ++cid) { auto& cell = *cells[cid]; // cell.print(); for (auto& site_wl : allCandSites[cid]) { auto site = sites[site_wl.first]; double wl = 0; for (auto net : lgData.group2Nets[cell.id]) { const auto& b = lgData.netBox[net->id]; Box<double> tmpBox(b.x.ou(lgData.groupsX[cell.id]), b.y.ou(lgData.groupsY[cell.id]), b.x.ol(lgData.groupsX[cell.id]), b.y.ol(lgData.groupsY[cell.id])); tmpBox.fupdate(site->cx(), site->cy()); wl += tmpBox.uhp(); } site_wl.second = wl * 100; // cout << site->x << " " << site->y << " " << wl << endl; } } vector<pair<int, long>> res; long cost = 0; MinCostBipartiteMatching(allCandSites, allCandSites.size(), sites.size(), res, cost); for (size_t cid = 0; cid < cells.size(); ++cid) { if (res[cid].first < 0) printlog(LOG_ERROR, "BipartiteLeg: cannot find ..."); else { auto site = sites[res[cid].first]; MergeGroupToSite(site, *cells[cid]); lgData.PartialUpdate(*cells[cid], site); } } } double Legalizer::GetHpwl() { return lgData.GetHpwl(); }
43.171515
163
0.552158
a9bdc8b01ca4d5c8925c3625ad65e851155ba0c3
1,687
html
HTML
youtube.html
toyjrah/toyjrah.github.io
e6aa5926d3e36810c0aeb3888a210952d40d35c2
[ "MIT" ]
null
null
null
youtube.html
toyjrah/toyjrah.github.io
e6aa5926d3e36810c0aeb3888a210952d40d35c2
[ "MIT" ]
null
null
null
youtube.html
toyjrah/toyjrah.github.io
e6aa5926d3e36810c0aeb3888a210952d40d35c2
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>SOWCoders</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="stylesheet.css"> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> <style> .bs-example{ margin: 20px; } </style> </head> <body> <div class="topnav"> <a href="./index.html">Home</a> <a href="./list.html">List</a> <a class="active" href="#youtube">Youtube</a> <a href="./maps.html">Maps</a> </div> <div class="container h-100"> <div class="row h-100 align-items-center justify-content-center text-center"> <div class="col-lg-10 align-self-end"> <h1 class="text-uppercase text-black font-weight-bold">Welcome to SOWCoders Students!!!</h1> <hr class="divider my-4" /> </div> </div> </div> <div class=youtube> <div id="text" style="text-align:left" > <p><h3>HTML Full Course - Build a Website Tutorial!</h3> </div> <div id = video > <iframe src="https://www.youtube.com/embed/pQN-pnXPaVg" width="666" height="343" float=left frameborder="10" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> </div> </body> </html>
34.428571
215
0.67457
f10500abab2d53e0116d08d6db956884b1fb64bb
292
rb
Ruby
lib/underscore-source.rb
STRd6/underscore-source
7b9d99ddfc34c18bb0364ed502f2610228f7a50a
[ "MIT" ]
1
2015-11-09T01:00:08.000Z
2015-11-09T01:00:08.000Z
lib/underscore-source.rb
STRd6/underscore-source
7b9d99ddfc34c18bb0364ed502f2610228f7a50a
[ "MIT" ]
null
null
null
lib/underscore-source.rb
STRd6/underscore-source
7b9d99ddfc34c18bb0364ed502f2610228f7a50a
[ "MIT" ]
null
null
null
require "underscore-source/version" # Sneaky require for Rails engine environment if defined? ::Rails::Engine require "underscore-source/rails" elsif defined? ::Sprockets require "underscore-source/sprockets" end module Underscore module Source # Your code goes here... end end
19.466667
45
0.760274
86279c2e80cfa5db5165b637aea5a661d3889362
1,173
swift
Swift
Sources/AlamofireXMLRPC/Alamofire+XML.swift
tsukisa/AlamofireXMLRPC
e9f6fee06e46498b5a100e5aff5a5934089981df
[ "MIT" ]
null
null
null
Sources/AlamofireXMLRPC/Alamofire+XML.swift
tsukisa/AlamofireXMLRPC
e9f6fee06e46498b5a100e5aff5a5934089981df
[ "MIT" ]
null
null
null
Sources/AlamofireXMLRPC/Alamofire+XML.swift
tsukisa/AlamofireXMLRPC
e9f6fee06e46498b5a100e5aff5a5934089981df
[ "MIT" ]
null
null
null
// // Alanofire+XML.swift // AlamofireXMLRPC // // Created by Jeremy Marchand on 08/10/2015. // Copyright © 2015 kodlian. All rights reserved. // import Foundation import AEXML import Alamofire extension DataRequest { public func responseXMLDocument(queue: DispatchQueue? = nil, completionHandler: @escaping (AFDataResponse<AEXMLDocument>) -> Void) -> Self { return responseData { (response) in let result: Result<AEXMLDocument, AFError> switch response.result { case .failure(let error): result = .failure(error) case .success(let data): do { let XML = try AEXMLDocument(xml: data) result = .success(XML) } catch let error { result = .failure(AFError.responseValidationFailed(reason: .customValidationFailed(error: error))) } } completionHandler(AFDataResponse(request: response.request, response: response.response, data: response.data, metrics: response.metrics, serializationDuration: response.serializationDuration, result: result)) } } }
34.5
220
0.623188
5deb828132d66c3ea1570f3b2c82b4f618b30c87
451
asm
Assembly
programs/oeis/095/A095097.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/095/A095097.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/095/A095097.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A095097: Fib000 numbers: those n for which the Zeckendorf expansion A014417(n) ends with three zeros. ; 8,13,18,21,26,29,34,39,42,47,52,55,60,63,68,73,76,81,84,89,94,97,102,107,110,115,118,123,128,131,136,141,144,149,152,157,162,165,170,173,178,183,186,191,196,199,204,207,212,217,220,225,228,233,238,241,246 mov $1,$0 sub $0,1 add $1,3 seq $1,130568 ; Generalized Beatty sequence 1+2*floor(n*phi), which contains infinitely many primes. add $0,$1
50.111111
206
0.72949
fbc0e479d9cc12fb126a239abf0ec4d7e6c66b11
2,211
java
Java
dl-dataaccess/src/main/java/eu/dl/dataaccess/dto/Storable.java
govtransparency/dfid2
6822f033560ba9df23f8c3be86bb95b4e3014a9c
[ "MIT" ]
null
null
null
dl-dataaccess/src/main/java/eu/dl/dataaccess/dto/Storable.java
govtransparency/dfid2
6822f033560ba9df23f8c3be86bb95b4e3014a9c
[ "MIT" ]
3
2021-12-10T01:11:21.000Z
2021-12-14T21:17:54.000Z
dl-dataaccess/src/main/java/eu/dl/dataaccess/dto/Storable.java
DatlabDasData/dfid2
2c142224f6b81d715231d0d82f710dd6084fbcae
[ "MIT" ]
1
2019-12-19T14:13:34.000Z
2019-12-19T14:13:34.000Z
package eu.dl.dataaccess.dto; import java.time.LocalDateTime; import java.util.HashMap; /** * Basic storable item. * */ public interface Storable { /** * @return the id */ String getId(); /** * @param id * the id to set */ void setId(String id); /** * @return the created */ LocalDateTime getCreated(); /** * @param created * the created to set */ void setCreated(LocalDateTime created); /** * @return the modified */ LocalDateTime getModified(); /** * @param modified * the modified to set */ void setModified(LocalDateTime modified); /** * @return the createdBy */ String getCreatedBy(); /** * @param createdBy * the createdBy to set */ void setCreatedBy(String createdBy); /** * @return the modifiedBy */ String getModifiedBy(); /** * @param modifiedBy * the modifiedBy to set */ void setModifiedBy(String modifiedBy); /** * @return the createdByVersion */ String getCreatedByVersion(); /** * @param createdByVersion * the createdByVersion to set */ void setCreatedByVersion(String createdByVersion); /** * @return the modifiedByVersion */ String getModifiedByVersion(); /** * @param modifiedByVersion * the modifiedByVersion to set */ void setModifiedByVersion(String modifiedByVersion); /** * @return the metaData */ HashMap<String, Object> getMetaData(); /** * @param metaData * the metaData to set */ void setMetaData(HashMap<String, Object> metaData); /** * @return the persistentId */ String getPersistentId(); /** * @param persistentId the persistentId to set */ void setPersistentId(String persistentId); /** * @return the processing order */ String getProcessingOrder(); /** * @param processingOrder the processing order to set */ void setProcessingOrder(String processingOrder); }
18.579832
57
0.556309
6c0a983b22446bbda54dbaa1f787999f694ec881
1,836
go
Go
go/mgnes/pkg/log/log.go
master-g/childhood
7cd2a6a13f7e862df6d239e78371df6222b30a53
[ "Apache-2.0" ]
1
2019-03-11T17:33:08.000Z
2019-03-11T17:33:08.000Z
go/mgnes/pkg/log/log.go
master-g/childhood
7cd2a6a13f7e862df6d239e78371df6222b30a53
[ "Apache-2.0" ]
null
null
null
go/mgnes/pkg/log/log.go
master-g/childhood
7cd2a6a13f7e862df6d239e78371df6222b30a53
[ "Apache-2.0" ]
null
null
null
// Copyright © 2019 mg // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package log import "fmt" // Logger interface for logging in this module type Logger interface { Log(msg string) } type defaultLogger struct { } // Log default implementation func (l *defaultLogger) Log(msg string) { fmt.Println(msg) } var ( defaultLoggerImpl = &defaultLogger{} logger Logger = defaultLoggerImpl logEnable = false ) // SetLogger set logger instance, if pass in `nil`, a default logger will be use func SetLogger(impl Logger) { if impl == nil { logger = defaultLoggerImpl } else { logger = impl } } // SetLoggingEnable sets log flag func SetLoggingEnable(enable bool) { logEnable = enable } func IsLoggingEnable() bool { return logEnable } func L(msg string) { logger.Log(msg) }
27.818182
80
0.740196
803599dbe4ae1484027f84df68de54babe029606
5,643
java
Java
src/main/java/fictioncraft/wintersteve25/fclib/FCLibMod.java
FictionCraft-Team/FCLib
f4281393743f895456dc7f133c6cc5a2cb97c590
[ "MIT" ]
4
2021-08-10T05:11:53.000Z
2021-08-29T02:58:40.000Z
src/main/java/fictioncraft/wintersteve25/fclib/FCLibMod.java
FictionCraft-Team/FCLib
f4281393743f895456dc7f133c6cc5a2cb97c590
[ "MIT" ]
null
null
null
src/main/java/fictioncraft/wintersteve25/fclib/FCLibMod.java
FictionCraft-Team/FCLib
f4281393743f895456dc7f133c6cc5a2cb97c590
[ "MIT" ]
null
null
null
package fictioncraft.wintersteve25.fclib; import com.mojang.brigadier.CommandDispatcher; import fictioncraft.wintersteve25.fclib.api.events.Hooks; import fictioncraft.wintersteve25.fclib.api.json.ErrorUtils; import fictioncraft.wintersteve25.fclib.api.json.commands.DumpInfoCommand; import fictioncraft.wintersteve25.fclib.api.json.commands.SimpleCommands; import fictioncraft.wintersteve25.fclib.api.json.objects.providers.arg.ArgProviderType; import fictioncraft.wintersteve25.fclib.api.json.objects.providers.arg.template.condition.*; import fictioncraft.wintersteve25.fclib.api.json.objects.providers.arg.template.effects.*; import fictioncraft.wintersteve25.fclib.api.json.objects.providers.obj.ObjProviderType; import fictioncraft.wintersteve25.fclib.api.json.utils.JsonConfigManager; import fictioncraft.wintersteve25.fclib.api.json.utils.JsonUtils; import fictioncraft.wintersteve25.fclib.common.network.FCLibNetworking; import net.minecraft.command.CommandSource; import net.minecraft.command.Commands; import net.minecraft.util.DamageSource; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.RegisterCommandsEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.event.lifecycle.FMLLoadCompleteEvent; import net.minecraftforge.fml.event.server.FMLServerAboutToStartEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.List; //import fictioncraft.wintersteve25.example.EventTest; @Mod("fclib") public class FCLibMod { public static Logger logger = LogManager.getLogger("FCLib"); public static final List<ObjProviderType> OBJ_PROVIDER_TYPES = new ArrayList<>(); public static final List<ArgProviderType> ARG_PROVIDER_TYPES = new ArrayList<>(); public static JsonConfigManager configManager = JsonConfigManager.getInstance(); public static DamageSource GENERIC_DAMAGE = new DamageSource("generic_nobypass"); public FCLibMod() { ModLoadingContext.get().registerConfig(ModConfig.Type.SERVER, FCLibConfig.SERVER_CONFIG); MinecraftForge.EVENT_BUS.addListener(FCLibMod::serverStartup); MinecraftForge.EVENT_BUS.addListener(FCLibMod::playerLogIn); MinecraftForge.EVENT_BUS.addListener(FCLibMod::registerCommands); FMLJavaModLoadingContext.get().getModEventBus().addListener(FCLibMod::commonSetup); MinecraftForge.EVENT_BUS.register(this); } public static void commonSetup(FMLLoadCompleteEvent event) { logger.info("o/ Hi! I hope you are having a wonderful day :)"); FCLibNetworking.registerMessages(); logger.info("Creating directory..."); JsonUtils.createDirectory(); ArgProviderType.registerProvider("E_Commands", "", SimpleCommandArg.class, null); ArgProviderType.registerProvider("E_Effects", "", SimpleEffectArg.class, null); ArgProviderType.registerProvider("E_SwingHand", "", SimpleSwingHandArg.class, null); ArgProviderType.registerProvider("E_Kill", "", SimpleKillArg.class, null); ArgProviderType.registerProvider("E_Transform", "", SimpleTransformArg.class, null); ArgProviderType.registerProvider("E_XP", "", SimpleExperienceArg.class, null); ArgProviderType.registerProvider("E_Hunger", "", SimpleHungerArg.class, null); ArgProviderType.registerProvider("E_Shrink", "", SimpleShrinkArg.class, null); ArgProviderType.registerProvider("E_Particle", "", SimpleParticleArg.class, null); ArgProviderType.registerProvider("E_Summon", "", SimpleSummonArg.class, null); ArgProviderType.registerProvider("E_Sound", "", SimpleSoundArg.class, null); ArgProviderType.registerProvider("E_ItemStack", "", SimpleGiveItemArg.class, null); ArgProviderType.registerProvider("E_Hurt", "", SimpleHurtArg.class, null); ArgProviderType.registerProvider("E_Damage", "", SimpleDamageItemArg.class, null); ArgProviderType.registerProvider("E_Cooldown", "", SimpleCooldownArg.class, null); ArgProviderType.registerProvider("C_ItemStack", "", SimpleItemCondition.class, null); ArgProviderType.registerProvider("C_Cooldown", "", SimpleCooldownCondition.class, null); ArgProviderType.registerProvider("C_XP", "", SimpleExperienceCondition.class, null); ArgProviderType.registerProvider("C_Hunger", "", SimpleHungerCondition.class, null); ArgProviderType.registerProvider("C_Effects", "", SimpleEffectCondition.class, null); } public static void serverStartup(final FMLServerAboutToStartEvent event) { logger.info("Creating Jsons..."); Hooks.onJsonRegister(configManager); if (configManager.jsonConfigMap.isEmpty()) return; JsonUtils.createJson(); JsonUtils.loadJson(); } public static void playerLogIn(PlayerEvent.PlayerLoggedInEvent event) { ErrorUtils.handle(event.getPlayer()); } public static void registerCommands(RegisterCommandsEvent event) { CommandDispatcher<CommandSource> dispatcher = event.getDispatcher(); dispatcher.register(Commands.literal("fclib") .then(DumpInfoCommand.register(dispatcher)) .then(SimpleCommands.registerReloadCommand(dispatcher)) .then(SimpleCommands.registerArgsCommand(dispatcher))); logger.info("Registered Commands!"); } }
53.235849
97
0.766436
c2db9f9ae53174c4aa85c10fb0b7a1e7a1c3a991
3,361
dart
Dart
lib/PreviousWords.dart
danger-ahead/search
b19cbb589197c4a8ea8aa9eddf519f0962ca2486
[ "MIT" ]
4
2021-06-27T07:43:32.000Z
2021-12-13T04:14:35.000Z
lib/PreviousWords.dart
danger-ahead/search
b19cbb589197c4a8ea8aa9eddf519f0962ca2486
[ "MIT" ]
2
2021-07-28T04:06:46.000Z
2021-07-30T09:32:40.000Z
lib/PreviousWords.dart
danger-ahead/search
b19cbb589197c4a8ea8aa9eddf519f0962ca2486
[ "MIT" ]
1
2021-07-30T06:09:54.000Z
2021-07-30T06:09:54.000Z
import 'package:flutter/material.dart'; import 'package:flutter_dictionary/WordsDatabase.dart'; import 'package:flutter_dictionary/results.dart'; import 'package:flutter_dictionary/words.dart'; import 'package:google_fonts/google_fonts.dart'; class PreviousWords extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.lightGreen[100], appBar: AppBar( centerTitle: true, shape: RoundedRectangleBorder( borderRadius: BorderRadius.vertical( bottom: Radius.circular(8), ), ), title: Text( "History", style: GoogleFonts.kosugi(), )), body: FutureBuilder<List<Word>>( future: WordsDatabase.instance.readAllWords(), builder: (BuildContext context, AsyncSnapshot<List<Word>> snapshot) { if (snapshot.hasData) { return ListView.builder( itemCount: snapshot.data!.length, itemBuilder: (BuildContext context, int index) { Word item = snapshot.data![index]; return Card( color: Colors.yellow[50], shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12.0), ), shadowColor: Colors.black, elevation: 2, child: ListTile( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return Results(item.word, item.lang); })); }, title: Text( "\t\t" + item.word, textScaleFactor: 1.2, style: GoogleFonts.overpassMono(), ), subtitle: Text( "\t\tlanguage:\t" + item.lang, style: GoogleFonts.overpassMono(), ), trailing: IconButton( color: Colors.red, icon: Icon(Icons.close), onPressed: () async { await WordsDatabase.instance.delete(item.id); Navigator.of(context).pop(); Navigator.push(context, MaterialPageRoute(builder: (context) { return PreviousWords(); })); }, ), ), ); }, ); } else { return Center(child: CircularProgressIndicator()); } }, ), bottomNavigationBar: BottomAppBar( color: Colors.yellow[50], child: TextButton( child: Text( "DELETE SEARCH HISTORY", style: GoogleFonts.michroma( color: Colors.red, ), ), onPressed: () async { await WordsDatabase.instance.deleteAll(); Navigator.of(context).pop(); Navigator.push(context, MaterialPageRoute(builder: (context) { return PreviousWords(); })); }, ), ), ); } }
34.295918
77
0.468611
83fc5f0b5e40fdbe0520510138cfbcd717f19a96
7,634
java
Java
MapboxAndroidDemo/src/main/java/com/mapbox/mapboxandroiddemo/examples/plugins/GeoJsonPluginActivity.java
LawrenceStent/mapbox-android-demo-master
a5fc5d25432fa091d396c8edba0135276d61a0da
[ "BSD-2-Clause" ]
4
2022-01-14T17:56:11.000Z
2022-02-25T07:10:12.000Z
MapboxAndroidDemo/src/main/java/com/mapbox/mapboxandroiddemo/examples/plugins/GeoJsonPluginActivity.java
selma-belhadj/mapbox-android-demo
62e5c4728da96e44cde9466b8c8664c9301c575d
[ "BSD-2-Clause" ]
null
null
null
MapboxAndroidDemo/src/main/java/com/mapbox/mapboxandroiddemo/examples/plugins/GeoJsonPluginActivity.java
selma-belhadj/mapbox-android-demo
62e5c4728da96e44cde9466b8c8664c9301c575d
[ "BSD-2-Clause" ]
null
null
null
package com.mapbox.mapboxandroiddemo.examples.plugins; import android.Manifest; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import com.afollestad.materialdialogs.folderselector.FileChooserDialog; import com.google.gson.JsonObject; import com.mapbox.mapboxandroiddemo.R; import com.mapbox.mapboxsdk.Mapbox; import com.mapbox.mapboxsdk.annotations.Marker; import com.mapbox.mapboxsdk.maps.MapView; import com.mapbox.mapboxsdk.maps.MapboxMap; import com.mapbox.mapboxsdk.maps.OnMapReadyCallback; import com.mapbox.mapboxsdk.plugins.geojson.GeoJsonPlugin; import com.mapbox.mapboxsdk.plugins.geojson.GeoJsonPluginBuilder; import com.mapbox.mapboxsdk.plugins.geojson.listener.OnLoadingGeoJsonListener; import com.mapbox.mapboxsdk.plugins.geojson.listener.OnMarkerEventListener; import java.io.File; import timber.log.Timber; public class GeoJsonPluginActivity extends AppCompatActivity implements OnMapReadyCallback, OnLoadingGeoJsonListener, OnMarkerEventListener, FileChooserDialog.FileCallback { private CoordinatorLayout coordinatorLayout; private MapView mapView; private MapboxMap mapboxMap; private GeoJsonPlugin geoJsonPlugin; private ProgressBar progressBar; private FloatingActionButton urlFab; private FloatingActionButton assetsFab; private FloatingActionButton pathFab; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Mapbox access token is configured here. This needs to be called either in your application // object or in the same activity which contains the mapview. Mapbox.getInstance(this, getString(R.string.access_token)); // This contains the MapView in XML and needs to be called after the access token is configured. setContentView(R.layout.activity_geojson_plugin); setUpFabButtons(); progressBar = (ProgressBar) findViewById(R.id.geoJSONLoadProgressBar); coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout); mapView = (MapView) findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(this); } @Override public void onMapReady(MapboxMap mapboxMap) { GeoJsonPluginActivity.this.mapboxMap = mapboxMap; geoJsonPlugin = new GeoJsonPluginBuilder() .withContext(this) .withMap(mapboxMap) .withOnLoadingURL(this) .withOnLoadingFileAssets(this) .withOnLoadingFilePath(this) .withMarkerClickListener(this) .build(); } private void setUpFabButtons() { urlFab = (FloatingActionButton) findViewById(R.id.fabURL); assetsFab = (FloatingActionButton) findViewById(R.id.fabAssets); pathFab = (FloatingActionButton) findViewById(R.id.fabPath); onUrlFabClick(); onAssetsFabClick(); onPathFabClick(); } private void onUrlFabClick() { urlFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mapboxMap != null && geoJsonPlugin != null) { mapboxMap.clear(); geoJsonPlugin.setUrl("https://raw.githubusercontent.com/johan/world.geo.json/master/countries/SEN.geo.json"); } } }); } private void onAssetsFabClick() { assetsFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mapboxMap != null && geoJsonPlugin != null) { mapboxMap.clear(); geoJsonPlugin.setAssetsName("boston_police_stations.geojson"); } } }); } private void onPathFabClick() { pathFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (Build.VERSION.SDK_INT >= 23) { if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { Timber.v("Permission is granted"); showFileChooserDialog(); Toast.makeText(GeoJsonPluginActivity.this, R.string.find_file_instruction_toast, Toast.LENGTH_SHORT).show(); } else { Timber.v("Permission is revoked"); ActivityCompat.requestPermissions(GeoJsonPluginActivity.this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } } else { //permission is automatically granted on sdk<23 upon installation Timber.v("Permission is granted"); showFileChooserDialog(); } } }); } /** * Draws GeoJSON file from a specific path. Please add and locate a GeoJSON file in your device to test it. * * @param file selected file from external storage */ private void drawFromPath(File file) { String path = file.getAbsolutePath(); if (mapboxMap != null && geoJsonPlugin != null) { mapboxMap.clear(); geoJsonPlugin.setFilePath(path); } } // Add the mapView lifecycle to the activity's lifecycle methods @Override public void onResume() { super.onResume(); mapView.onResume(); } @Override protected void onStart() { super.onStart(); mapView.onStart(); } @Override protected void onStop() { super.onStop(); mapView.onStop(); } @Override public void onPause() { super.onPause(); mapView.onPause(); } @Override public void onLowMemory() { super.onLowMemory(); mapView.onLowMemory(); } @Override protected void onDestroy() { super.onDestroy(); mapView.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } private void showFileChooserDialog() { new FileChooserDialog.Builder(this) .extensionsFilter(".geojson", ".json", ".js", ".txt") .goUpLabel("Up") .show(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { Timber.v("Permission: " + permissions[0] + "was " + grantResults[0]); showFileChooserDialog(); } } @Override public void onFileSelection(@NonNull FileChooserDialog dialog, @NonNull File file) { drawFromPath(file); } @Override public void onFileChooserDismissed(@NonNull FileChooserDialog dialog) { } @Override public void onPreLoading() { progressBar.setVisibility(View.VISIBLE); } @Override public void onLoaded() { Toast.makeText(this, "GeoJson data loaded", Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.INVISIBLE); } @Override public void onLoadFailed(Exception exception) { progressBar.setVisibility(View.INVISIBLE); Toast.makeText(this, "Error occur during load GeoJson data. see logcat", Toast.LENGTH_LONG).show(); exception.printStackTrace(); } @Override public void onMarkerClickListener(Marker marker, JsonObject properties) { Snackbar.make(coordinatorLayout, properties.get("NAME").getAsString(), Snackbar.LENGTH_SHORT).show(); } }
31.676349
119
0.716662
fb61bb408e0127ae4a03787c784076d58eda78be
933
java
Java
registry-surety/src/test/java/org/gbif/registry/surety/InMemoryEmailSender.java
ManonGros/registry
5894b14cb075b24695c681af2dd5a8091a5e741d
[ "Apache-2.0" ]
null
null
null
registry-surety/src/test/java/org/gbif/registry/surety/InMemoryEmailSender.java
ManonGros/registry
5894b14cb075b24695c681af2dd5a8091a5e741d
[ "Apache-2.0" ]
null
null
null
registry-surety/src/test/java/org/gbif/registry/surety/InMemoryEmailSender.java
ManonGros/registry
5894b14cb075b24695c681af2dd5a8091a5e741d
[ "Apache-2.0" ]
null
null
null
package org.gbif.registry.surety; import org.gbif.registry.surety.email.BaseEmailModel; import org.gbif.registry.surety.email.EmailSender; import java.util.HashMap; import java.util.Map; /** * Simple {@link EmailSender} implementation that keep the {@link BaseEmailModel} into memory. * - For testing only * - 1 {@link BaseEmailModel} is stored per email address * - no automatic cleanup */ public class InMemoryEmailSender implements EmailSender { private final Map<String, BaseEmailModel> emails = new HashMap<>(); @Override public void send(BaseEmailModel baseEmailModel) { emails.put(baseEmailModel.getEmailAddress(), baseEmailModel); } public BaseEmailModel getEmail(String emailAddress) { return emails.get(emailAddress); } /** * Clear all emails in memory */ public void clear() { emails.clear(); } @Override public String toString() { return emails.toString(); } }
22.756098
94
0.724544
cea0f7047cb812ee783c637a2f3351f80b46b4f4
79
swift
Swift
k.swift
ahad11/p
a2c41be0c56d260d3570abdfa2c97e42637e9d46
[ "MIT" ]
null
null
null
k.swift
ahad11/p
a2c41be0c56d260d3570abdfa2c97e42637e9d46
[ "MIT" ]
null
null
null
k.swift
ahad11/p
a2c41be0c56d260d3570abdfa2c97e42637e9d46
[ "MIT" ]
null
null
null
// // k.swift // p // // Created by ahad on 10/25/17. // import Foundation
8.777778
32
0.556962
052aeb993b125ec7f925faf823c3f1d40f644379
2,007
rb
Ruby
lib/foursquare/checkin_proxy.rb
lukasmairl/quimby
cf60a498199b58e37de7a0a30ef3b8971271e0ff
[ "MIT" ]
2
2017-09-07T05:44:03.000Z
2017-09-07T05:44:23.000Z
lib/foursquare/checkin_proxy.rb
lukasmairl/quimby
cf60a498199b58e37de7a0a30ef3b8971271e0ff
[ "MIT" ]
null
null
null
lib/foursquare/checkin_proxy.rb
lukasmairl/quimby
cf60a498199b58e37de7a0a30ef3b8971271e0ff
[ "MIT" ]
null
null
null
module Foursquare class CheckinProxy def initialize(foursquare) @foursquare = foursquare end def find(id) Foursquare::Checkin.new(@foursquare, @foursquare.get("checkins/#{id}")["checkin"]) end def merge_auth_params(params) if @access_token params.merge!(:oauth_token => @access_token) else params.merge!(:client_id => @client_id, :client_secret => @client_secret) end end def reply(checkin_id, options={}) puts "---- hello 3333333 ----" #puts '-------- testing checkin_id -------' #puts checkin_id #puts options.to_yaml #response = Typhoeus::Request.post("https://api.foursquare.com/v2/checkins/#{checkin_id}", options) #Foursquare::Checkin.new(@foursquare, @foursquare.post("checkins/#{checkin_id}", options)) #@foursquare.post("checkins/#{checkin_id}", options)s #puts "------ second ---------" #merge_auth_params(params) #response = Typhoeus::Request.post("https://api.foursquare.com/v2/checkins/#{checkin_id}/reply", :params => params) #puts response.inspect #puts response.inspect #Foursquare.log(response.inspect) #error(response) || response["response"] @foursquare.post("checkins/#{checkin_id}", options) #Foursquare::Checkin.new(@foursquare, @foursquare.post("checkins/#{checkin_id}", options)) end def recent(options={}) @foursquare.get("checkins/recent", options)["recent"].map do |json| Foursquare::Checkin.new(@foursquare, json) end end def all(options={}) @foursquare.get("users/self/checkins", options)["checkins"]["items"].map do |json| Foursquare::Checkin.new(@foursquare, json) end end def create(options={}) if json = @foursquare.post("checkins/add", options) Foursquare::Checkin.new(@foursquare, json["checkin"]) else nil end end alias_method :add, :create end end
31.359375
121
0.619831
bb9ee8e11f64979b2b69a72b795f926ec2aaa33b
85,741
swift
Swift
phoenix-ios/phoenix-ios/views/SendView.swift
EZ0010/phoenix
5cd7e7fd00295a3307e61b9e67d4cd3af7733ebb
[ "Apache-2.0" ]
null
null
null
phoenix-ios/phoenix-ios/views/SendView.swift
EZ0010/phoenix
5cd7e7fd00295a3307e61b9e67d4cd3af7733ebb
[ "Apache-2.0" ]
null
null
null
phoenix-ios/phoenix-ios/views/SendView.swift
EZ0010/phoenix
5cd7e7fd00295a3307e61b9e67d4cd3af7733ebb
[ "Apache-2.0" ]
null
null
null
import SwiftUI import Combine import AVFoundation import PhoenixShared import UIKit import os.log #if DEBUG && true fileprivate var log = Logger( subsystem: Bundle.main.bundleIdentifier!, category: "SendView" ) #else fileprivate var log = Logger(OSLog.disabled) #endif struct MsatRange { let min: Lightning_kmpMilliSatoshi let max: Lightning_kmpMilliSatoshi } struct TipNumbers { let baseMsat: Int64 let tipMsat: Int64 let totalMsat: Int64 let percent: Double } struct TipStrings { let bitcoin_base: FormattedAmount let bitcoin_tip: FormattedAmount let bitcoin_total: FormattedAmount let fiat_base: FormattedAmount let fiat_tip: FormattedAmount let fiat_total: FormattedAmount let percent: String let isEmpty: Bool static func empty(_ currencyPrefs: CurrencyPrefs) -> TipStrings { let zeroBitcoin = Utils.formatBitcoin(msat: 0, bitcoinUnit: currencyPrefs.bitcoinUnit) let exchangeRate = ExchangeRate.BitcoinPriceRate( fiatCurrency: currencyPrefs.fiatCurrency, price: 0.0, source: "", timestampMillis: 0 ) let zeroFiat = Utils.formatFiat(msat: 0, exchangeRate: exchangeRate) return TipStrings( bitcoin_base: zeroBitcoin, bitcoin_tip: zeroBitcoin, bitcoin_total: zeroBitcoin, fiat_base: zeroFiat, fiat_tip: zeroFiat, fiat_total: zeroFiat, percent: "0%", isEmpty: true ) } } enum FlowType { case pay(range: MsatRange) case withdraw(range: MsatRange) } struct SendView: MVIView { @StateObject var mvi: MVIState<Scan.Model, Scan.Intent> @Environment(\.controllerFactory) var factoryEnv var factory: ControllerFactory { return factoryEnv } @State var paymentRequest: String? = nil @StateObject var toast = Toast() @Environment(\.colorScheme) var colorScheme: ColorScheme @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> init(controller: AppScanController? = nil) { if let controller = controller { self._mvi = StateObject(wrappedValue: MVIState(controller)) } else { self._mvi = StateObject(wrappedValue: MVIState { $0.scan(firstModel: Scan.Model_Ready()) }) } } @ViewBuilder var view: some View { ZStack { content toast.view() } .frame(maxWidth: .infinity, maxHeight: .infinity) .onChange(of: mvi.model) { newModel in modelDidChange(newModel) } .onReceive(AppDelegate.get().externalLightningUrlPublisher) { (url: String) in didReceiveExternalLightningUrl(url) } } @ViewBuilder var content: some View { switch mvi.model { case _ as Scan.Model_Ready, _ as Scan.Model_BadRequest, _ as Scan.Model_InvoiceFlow_DangerousRequest, _ as Scan.Model_LnurlServiceFetch: ScanView( mvi: mvi, paymentRequest: $paymentRequest ) case _ as Scan.Model_InvoiceFlow_InvoiceRequest, _ as Scan.Model_LnurlPayFlow_LnurlPayRequest, _ as Scan.Model_LnurlPayFlow_LnurlPayFetch, _ as Scan.Model_LnurlWithdrawFlow_LnurlWithdrawRequest, _ as Scan.Model_LnurlWithdrawFlow_LnurlWithdrawFetch: ValidateView(mvi: mvi) case _ as Scan.Model_InvoiceFlow_Sending, _ as Scan.Model_LnurlPayFlow_Sending: SendingView(mvi: mvi) case _ as Scan.Model_LnurlWithdrawFlow_Receiving: ReceivingView(mvi: mvi) case _ as Scan.Model_LnurlAuthFlow_LoginRequest, _ as Scan.Model_LnurlAuthFlow_LoggingIn, _ as Scan.Model_LnurlAuthFlow_LoginResult: LoginView(mvi: mvi) default: fatalError("Unknown model \(mvi.model)") } } func modelDidChange(_ newModel: Scan.Model) { log.trace("modelDidChange()") if let newModel = newModel as? Scan.Model_BadRequest { showErrorToast(newModel) } else if let model = newModel as? Scan.Model_InvoiceFlow_DangerousRequest { paymentRequest = model.request } else if let model = newModel as? Scan.Model_InvoiceFlow_InvoiceRequest { paymentRequest = model.request } else if newModel is Scan.Model_InvoiceFlow_Sending || newModel is Scan.Model_LnurlPayFlow_Sending { // Pop self from NavigationStack; Back to HomeView presentationMode.wrappedValue.dismiss() } } func showErrorToast(_ model: Scan.Model_BadRequest) -> Void { log.trace("showErrorToast()") let msg: String if let reason = model.reason as? Scan.BadRequestReason_ChainMismatch { let requestChain = reason.requestChain?.name ?? "unknown" msg = NSLocalizedString( "The invoice is for \(requestChain), but you're on \(reason.myChain.name)", comment: "Error message - scanning lightning invoice" ) } else if model.reason is Scan.BadRequestReason_UnsupportedLnUrl { msg = NSLocalizedString( "Phoenix does not support this type of LNURL yet", comment: "Error message - scanning lightning invoice" ) } else if model.reason is Scan.BadRequestReason_IsBitcoinAddress { msg = NSLocalizedString( """ You scanned a bitcoin address. Phoenix currently only supports sending Lightning payments. \ You can use a third-party service to make the offchain->onchain swap. """, comment: "Error message - scanning lightning invoice" ) } else if model.reason is Scan.BadRequestReason_AlreadyPaidInvoice { msg = NSLocalizedString( "You've already paid this invoice. Paying it again could result in stolen funds.", comment: "Error message - scanning lightning invoice" ) } else if let serviceError = model.reason as? Scan.BadRequestReason_ServiceError { let isLightningAddress = serviceError.url.description.contains("/.well-known/lnurlp/") switch serviceError.error { case is LNUrl.Error_RemoteFailure_CouldNotConnect: msg = NSLocalizedString( "Could not connect to service", comment: "Error message - scanning lightning invoice" ) case is LNUrl.Error_RemoteFailure_Unreadable: msg = NSLocalizedString( "Service returned unreadable response", comment: "Error message - scanning lightning invoice" ) default: // is LNUrl.Error_RemoteFailure_Code // is LNUrl.Error_RemoteFailure_Detailed if isLightningAddress { msg = NSLocalizedString( "Service doesn't support Lightning addresses, or doesn't know this user", comment: "Error message - scanning lightning invoice" ) } else { msg = NSLocalizedString( "Service appears to be offline, or they have a down server", comment: "Error message - scanning lightning invoice" ) } } } else { msg = NSLocalizedString( "This doesn't appear to be a Lightning invoice", comment: "Error message - scanning lightning invoice" ) } toast.pop( Text(msg).multilineTextAlignment(.center).anyView, colorScheme: colorScheme.opposite, style: .chrome, duration: 30.0, location: .middle, showCloseButton: true ) } func didReceiveExternalLightningUrl(_ urlStr: String) -> Void { log.trace("didReceiveExternalLightningUrl()") mvi.intent(Scan.Intent_Parse(request: urlStr)) } } struct ScanView: View, ViewName { @ObservedObject var mvi: MVIState<Scan.Model, Scan.Intent> @Binding var paymentRequest: String? @State var displayWarning: Bool = false @State var ignoreScanner: Bool = false @Environment(\.shortSheetState) private var shortSheetState: ShortSheetState @Environment(\.popoverState) var popoverState: PopoverState // Subtle timing bug: // // Steps to reproduce: // - scan payment without amount (and without trampoline support) // - warning popup is displayed // - keep QRcode within camera screen while tapping Confirm button // // What happens: // - the validate screen is not displayed as it should be // // Why: // - the warning popup is displayed // - user taps "confirm" // - we send IntentConfirmEmptyAmount to library // - QrCodeScannerView fires // - we send IntentParse to library // - library sends us ModelValidate // - library sends us ModelRequestWithoutAmount @ViewBuilder var body: some View { ZStack { Color.primaryBackground .edgesIgnoringSafeArea(.all) if AppDelegate.showTestnetBackground { Image("testnet_bg") .resizable(resizingMode: .tile) .edgesIgnoringSafeArea([.horizontal, .bottom]) // not underneath status bar } content if mvi.model is Scan.Model_LnurlServiceFetch { LnurlFetchNotice( title: NSLocalizedString("Fetching Lightning URL", comment: "Progress title"), onCancel: { didCancelLnurlServiceFetch() } ) .ignoresSafeArea(.keyboard) // disable keyboard avoidance on this view } } .frame(maxHeight: .infinity) .navigationBarTitle( NSLocalizedString("Scan a QR code", comment: "Navigation bar title"), displayMode: .inline ) .zIndex(3) // [SendingView, ValidateView, LoginView, ScanView] .transition( .asymmetric( insertion: .identity, removal: .move(edge: .bottom) ) ) .onChange(of: mvi.model) { newModel in modelDidChange(newModel) } .onChange(of: displayWarning) { newValue in if newValue { showWarning() } } } @ViewBuilder var content: some View { VStack { QrCodeScannerView {(request: String) in didScanQRCode(request) } Button { manualInput() } label: { Image(systemName: "square.and.pencil") Text("Manual input") } .font(.title3) .padding(.top, 10) Divider() .padding([.top, .bottom], 10) Button { pasteFromClipboard() } label: { Image(systemName: "arrow.right.doc.on.clipboard") Text("Paste from clipboard") } .font(.title3) .disabled(!UIPasteboard.general.hasStrings) .padding(.bottom, 10) } .ignoresSafeArea(.keyboard) // disable keyboard avoidance on this view } func modelDidChange(_ newModel: Scan.Model) { log.trace("[\(viewName)] modelDidChange()") if ignoreScanner { // Flow: // - User taps "manual input" // - User types in something and taps "OK" // - We send Scan.Intent.Parse() // - We just got back a response from our request // ignoreScanner = false } if let _ = newModel as? Scan.Model_InvoiceFlow_DangerousRequest { displayWarning = true } } func didScanQRCode(_ request: String) { var isFetchingLnurl = false if let _ = mvi.model as? Scan.Model_LnurlServiceFetch { isFetchingLnurl = true } if !ignoreScanner && !isFetchingLnurl { mvi.intent(Scan.Intent_Parse(request: request)) } } func didCancelLnurlServiceFetch() { log.trace("[\(viewName)] didCancelLnurlServiceFetch()") mvi.intent(Scan.Intent_CancelLnurlServiceFetch()) } func manualInput() { log.trace("[\(viewName)] manualInput()") ignoreScanner = true shortSheetState.display(dismissable: true) { ManualInput(mvi: mvi, ignoreScanner: $ignoreScanner) } } func pasteFromClipboard() { log.trace("[\(viewName)] pasteFromClipboard()") if let request = UIPasteboard.general.string { mvi.intent(Scan.Intent_Parse(request: request)) } } func showWarning() { log.trace("[\(viewName)] showWarning()") guard let model = mvi.model as? Scan.Model_InvoiceFlow_DangerousRequest else { return } displayWarning = false ignoreScanner = true popoverState.display(dismissable: false) { DangerousInvoiceAlert( model: model, intent: mvi.intent, ignoreScanner: $ignoreScanner ) } } } struct LnurlFetchNotice: View, ViewName { let title: String let onCancel: () -> Void @ViewBuilder var body: some View { VStack(alignment: HorizontalAlignment.center, spacing: 8) { Text(title) ZStack { Divider() HorizontalActivity(color: .appAccent, diameter: 10, speed: 1.6) } .frame(width: 125, height: 10) Button { didTapCancel() } label: { Text("Cancel") } } .padding() .background(Color(UIColor.systemBackground)) .cornerRadius(16) } func didTapCancel() { log.trace("[\(viewName)] didTapCancel()") onCancel() } } struct ManualInput: View, ViewName { @ObservedObject var mvi: MVIState<Scan.Model, Scan.Intent> @Binding var ignoreScanner: Bool @State var input = "" @Environment(\.shortSheetState) private var shortSheetState: ShortSheetState @ViewBuilder var body: some View { VStack(alignment: HorizontalAlignment.leading, spacing: 0) { Text("Manual Input") .font(.title2) .padding(.bottom) Text( """ Enter a Lightning invoice, LNURL, or Lightning address \ you want to send money to. """ ) .padding(.bottom) HStack(alignment: VerticalAlignment.center, spacing: 0) { TextField("", text: $input) // Clear button (appears when TextField's text is non-empty) Button { input = "" } label: { Image(systemName: "multiply.circle.fill") .foregroundColor(.secondary) } .isHidden(input == "") } .padding(.all, 8) .overlay( RoundedRectangle(cornerRadius: 8) .stroke(Color(UIColor.separator), lineWidth: 1) ) .padding(.bottom) .padding(.bottom) HStack(alignment: VerticalAlignment.center, spacing: 0) { Spacer() Button("Cancel") { didCancel() } .font(.title3) Divider() .frame(maxHeight: 20, alignment: Alignment.center) .padding([.leading, .trailing]) Button("OK") { didConfirm() } .font(.title3) } } // </VStack> .padding() } func didCancel() -> Void { log.trace("[\(viewName)] didCancel()") shortSheetState.close { ignoreScanner = false } } func didConfirm() -> Void { log.trace("[\(viewName)] didConfirm()") let request = input.trimmingCharacters(in: .whitespacesAndNewlines) if request.count > 0 { mvi.intent(Scan.Intent_Parse(request: request)) } shortSheetState.close() } } struct DangerousInvoiceAlert: View, ViewName { let model: Scan.Model_InvoiceFlow_DangerousRequest let intent: (Scan.Intent) -> Void @Binding var ignoreScanner: Bool @Environment(\.popoverState) var popoverState: PopoverState @ViewBuilder var body: some View { VStack(alignment: HorizontalAlignment.leading, spacing: 0) { Text("Warning") .font(.title2) .padding(.bottom) if model.reason is Scan.DangerousRequestReasonIsAmountlessInvoice { content_amountlessInvoice } else if model.reason is Scan.DangerousRequestReasonIsOwnInvoice { content_ownInvoice } else { content_unknown } HStack(alignment: VerticalAlignment.center, spacing: 0) { Spacer() Button("Cancel") { didCancel() } .font(.title3) .padding(.trailing) Button("Continue") { didConfirm() } .font(.title3) .disabled(isUnknownType()) } .padding(.top, 30) } // </VStack> .padding() } @ViewBuilder var content_amountlessInvoice: some View { VStack(alignment: HorizontalAlignment.leading, spacing: 0) { Text(styled: NSLocalizedString( """ The invoice doesn't include an amount. This can be dangerous: \ malicious nodes may be able to steal your payment. To be safe, \ **ask the payee to specify an amount** in the payment request. """, comment: "SendView" )) .padding(.bottom) Text("Are you sure you want to pay this invoice?") } } @ViewBuilder var content_ownInvoice: some View { VStack(alignment: HorizontalAlignment.leading, spacing: 0) { Text("The invoice is for you. You are about to pay yourself.") } } @ViewBuilder var content_unknown: some View { VStack(alignment: HorizontalAlignment.leading, spacing: 0) { Text("Something is amiss with this invoice...") } } func isUnknownType() -> Bool { if model.reason is Scan.DangerousRequestReasonIsAmountlessInvoice { return false } else if model.reason is Scan.DangerousRequestReasonIsOwnInvoice { return false } else { return true } } func didCancel() -> Void { log.trace("[\(viewName)] didCancel()") popoverState.close { ignoreScanner = false } } func didConfirm() -> Void { log.trace("[\(viewName)] didConfirm()") intent(Scan.Intent_InvoiceFlow_ConfirmDangerousRequest( request: model.request, paymentRequest: model.paymentRequest )) popoverState.close() } } struct ValidateView: View, ViewName { @ObservedObject var mvi: MVIState<Scan.Model, Scan.Intent> @State var unit = Currency.bitcoin(.sat) @State var amount: String = "" @State var parsedAmount: Result<Double, TextFieldCurrencyStylerError> = Result.failure(.emptyInput) @State var altAmount: String = "" @State var isInvalidAmount: Bool = false @State var isExpiredInvoice: Bool = false @State var comment: String = "" @State var hasPromptedForComment = false @StateObject var connectionsManager = ObservableConnectionsManager() @Environment(\.colorScheme) var colorScheme @Environment(\.popoverState) var popoverState: PopoverState @Environment(\.shortSheetState) var shortSheetState: ShortSheetState @EnvironmentObject var currencyPrefs: CurrencyPrefs // For the cicular buttons: [metadata, tip, comment] enum MaxButtonWidth: Preference {} let maxButtonWidthReader = GeometryPreferenceReader( key: AppendValue<MaxButtonWidth>.self, value: { [$0.size.width] } ) @State var maxButtonWidth: CGFloat? = nil // For the tipSummary: the max of: [base, tip, total] enum MaxBitcoinWidth: Preference {} let maxBitcoinWidthReader = GeometryPreferenceReader( key: AppendValue<MaxBitcoinWidth>.self, value: { [$0.size.width] } ) @State var maxBitcoinWidth: CGFloat? = nil // For the tipSummary: the max of: [base, tip, total] enum MaxFiatWidth: Preference {} let maxFiatWidthReader = GeometryPreferenceReader( key: AppendValue<MaxFiatWidth>.self, value: { [$0.size.width] } ) @State var maxFiatWidth: CGFloat? = nil var body: some View { ZStack { Color.primaryBackground .ignoresSafeArea(.all, edges: .all) if AppDelegate.showTestnetBackground { Image("testnet_bg") .resizable(resizingMode: .tile) .ignoresSafeArea(.all, edges: .all) .onTapGesture { dismissKeyboardIfVisible() } } else { Color.clear .ignoresSafeArea(.all, edges: .all) .contentShape(Rectangle()) .onTapGesture { dismissKeyboardIfVisible() } } content if mvi.model is Scan.Model_LnurlPayFlow_LnurlPayFetch { LnurlFetchNotice( title: NSLocalizedString("Fetching Invoice", comment: "Progress title"), onCancel: { didCancelLnurlPayFetch() } ) } else if mvi.model is Scan.Model_LnurlWithdrawFlow_LnurlWithdrawFetch { LnurlFetchNotice( title: NSLocalizedString("Forwarding Invoice", comment: "Progress title"), onCancel: { didCancelLnurlWithdrawFetch() } ) } }// </ZStack> .navigationBarTitle( mvi.model is Scan.Model_LnurlWithdrawFlow ? NSLocalizedString("Confirm Withdraw", comment: "Navigation bar title") : NSLocalizedString("Confirm Payment", comment: "Navigation bar title"), displayMode: .inline ) .zIndex(1) // [SendingView, ValidateView, LoginView, ScanView] .transition( .asymmetric( insertion: .identity, removal: .opacity ) ) .onAppear() { onAppear() } .onChange(of: mvi.model) { newModel in modelDidChange(newModel) } .onChange(of: amount) { _ in amountDidChange() } .onChange(of: unit) { _ in unitDidChange() } } @ViewBuilder var content: some View { let isDisconnected = connectionsManager.connections.global != .established VStack { if let host = paymentHost() { VStack(alignment: HorizontalAlignment.center, spacing: 10) { if mvi.model is Scan.Model_LnurlWithdrawFlow { Text("You are redeeming funds from") } else { Text("Payment requested by") } Text(host).bold() } .padding(.bottom) .padding(.bottom) } if mvi.model is Scan.Model_LnurlWithdrawFlow { Text(verbatim: NSLocalizedString("amount to receive", comment: "SendView: lnurl-withdraw flow") .uppercased() ) .padding(.bottom, 4) } HStack(alignment: VerticalAlignment.firstTextBaseline) { TextField(verbatim: "123", text: currencyStyler().amountProxy) .keyboardType(.decimalPad) .disableAutocorrection(true) .fixedSize() .font(.title) .multilineTextAlignment(.trailing) .foregroundColor(isInvalidAmount ? Color.appNegative : Color.primaryForeground) Picker(selection: $unit, label: Text(unit.abbrev).frame(minWidth: 40)) { let options = Currency.displayable(currencyPrefs: currencyPrefs) ForEach(0 ..< options.count) { let option = options[$0] Text(option.abbrev).tag(option) } } .pickerStyle(MenuPickerStyle()) } // </HStack> .padding([.leading, .trailing]) .background( VStack { Spacer() Line().stroke(Color.appAccent, style: StrokeStyle(lineWidth: 2, dash: [3])) .frame(height: 1) } ) Text(altAmount) .font(.caption) .foregroundColor((isInvalidAmount || isExpiredInvoice) ? Color.appNegative : .secondary) .padding(.top, 4) .padding(.bottom) if hasExtendedMetadata() || supportsPriceRange() || supportsComment() { HStack(alignment: VerticalAlignment.center, spacing: 20) { if hasExtendedMetadata() { metadataButton() } if supportsPriceRange() { priceTargetButton() } if supportsComment() { commentButton() } } .assignMaxPreference(for: maxButtonWidthReader.key, to: $maxButtonWidth) .padding(.horizontal) } if let description = requestDescription() { Text(description) .padding() .padding(.bottom) } else { Text("No description") .foregroundColor(.secondary) .padding() .padding(.bottom) } Button { sendPayment() } label: { HStack { if mvi.model is Scan.Model_LnurlWithdrawFlow { Image("ic_receive") .renderingMode(.template) .resizable() .aspectRatio(contentMode: .fit) .foregroundColor(Color.white) .frame(width: 22, height: 22) Text("Redeem") .font(.title2) .foregroundColor(Color.white) } else { Image("ic_send") .renderingMode(.template) .resizable() .aspectRatio(contentMode: .fit) .foregroundColor(Color.white) .frame(width: 22, height: 22) Text("Pay") .font(.title2) .foregroundColor(Color.white) } } .padding(.top, 4) .padding(.bottom, 5) .padding([.leading, .trailing], 24) } .buttonStyle(ScaleButtonStyle( backgroundFill: Color.appAccent, disabledBackgroundFill: Color.gray )) .disabled(isInvalidAmount || isExpiredInvoice || isDisconnected) if !isInvalidAmount && !isExpiredInvoice && isDisconnected { Button { showAppStatusPopover() } label: { HStack { ProgressView() .progressViewStyle(CircularProgressViewStyle()) .padding(.trailing, 1) Text(disconnectedText()) } } .padding(.top, 4) } tipSummary .padding(.top) .padding(.top) } // </VStack> } @ViewBuilder var tipSummary: some View { let tipInfo = tipStrings() // 1,000 sat 0.57 usd // 30 sat +3% 0.01 usd // --------- -------- // 1,030 sat 0.58 usd HStack(alignment: VerticalAlignment.center, spacing: 16) { VStack(alignment: HorizontalAlignment.trailing, spacing: 8) { Text(verbatim: tipInfo.bitcoin_base.string) .read(maxBitcoinWidthReader) Text(verbatim: "+ \(tipInfo.bitcoin_tip.string)") .read(maxBitcoinWidthReader) Divider() .frame(width: tipInfo.isEmpty ? 0 : maxBitcoinWidth ?? 0, height: 1) Text(verbatim: tipInfo.bitcoin_total.string) .read(maxBitcoinWidthReader) } VStack(alignment: HorizontalAlignment.center, spacing: 8) { Text(verbatim: "") Text(verbatim: tipInfo.percent) Divider() .frame(width: 0, height: 1) Text(verbatim: "") } VStack(alignment: HorizontalAlignment.trailing, spacing: 8) { Text(verbatim: tipInfo.fiat_base.string) .read(maxFiatWidthReader) Text(verbatim: "+ \(tipInfo.fiat_tip.string)") .read(maxFiatWidthReader) Divider() .frame(width: tipInfo.isEmpty ? 0 : maxBitcoinWidth ?? 0, height: 1) Text(verbatim: tipInfo.fiat_total.string) .read(maxFiatWidthReader) } } .assignMaxPreference(for: maxBitcoinWidthReader.key, to: $maxBitcoinWidth) .assignMaxPreference(for: maxFiatWidthReader.key, to: $maxFiatWidth) .font(.footnote) .foregroundColor(tipInfo.isEmpty ? Color.clear : Color.secondary) } func currencyStyler() -> TextFieldCurrencyStyler { return TextFieldCurrencyStyler( currency: unit, amount: $amount, parsedAmount: $parsedAmount, hideMsats: false ) } @ViewBuilder func actionButton( text: String, image: Image, width: CGFloat = 20, height: CGFloat = 20, xOffset: CGFloat = 0, yOffset: CGFloat = 0, action: @escaping () -> Void ) -> some View { Button(action: action) { VStack(alignment: HorizontalAlignment.center, spacing: 0) { ZStack { Color.buttonFill .frame(width: 30, height: 30) .cornerRadius(50) .overlay( RoundedRectangle(cornerRadius: 50) .stroke(Color(UIColor.separator), lineWidth: 1) ) image .renderingMode(.template) .resizable() .scaledToFit() .frame(width: width, height: height) .offset(x: xOffset, y: yOffset) } Text(text.lowercased()) .font(.caption) .foregroundColor(Color.secondary) .padding(.top, 2) } // </VStack> } // </Button> .frame(width: maxButtonWidth) .read(maxButtonWidthReader) } @ViewBuilder func metadataButton() -> some View { actionButton( text: NSLocalizedString("info", comment: "button label - try to make it short"), image: Image(systemName: "info.circle"), width: 20, height: 20, xOffset: 0, yOffset: 0 ) { metadataButtonTapped() } } @ViewBuilder func priceTargetButton() -> some View { actionButton( text: priceTargetButtonText(), image: Image(systemName: "target"), width: 20, height: 20, xOffset: 0, yOffset: 0 ) { priceTargetButtonTapped() } } func priceTargetButtonText() -> String { if let _ = lnurlWithdraw() { return NSLocalizedString("range", comment: "button label - try to make it short") } else { return NSLocalizedString("tip", comment: "button label - try to make it short") } } @ViewBuilder func commentButton() -> some View { actionButton( text: NSLocalizedString("comment", comment: "button label - try to make it short"), image: Image(systemName: "pencil.tip"), width: 20, height: 20, xOffset: 0, yOffset: 0 ) { commentButtonTapped() } } func paymentRequest() -> Lightning_kmpPaymentRequest? { if let model = mvi.model as? Scan.Model_InvoiceFlow_InvoiceRequest { return model.paymentRequest } else { return nil } } func lnurlPay() -> LNUrl.Pay? { if let model = mvi.model as? Scan.Model_LnurlPayFlow_LnurlPayRequest { return model.lnurlPay } else if let model = mvi.model as? Scan.Model_LnurlPayFlow_LnurlPayFetch { return model.lnurlPay } else { return nil } } func lnurlWithdraw() -> LNUrl.Withdraw? { if let model = mvi.model as? Scan.Model_LnurlWithdrawFlow_LnurlWithdrawRequest { return model.lnurlWithdraw } else if let model = mvi.model as? Scan.Model_LnurlWithdrawFlow_LnurlWithdrawFetch { return model.lnurlWithdraw } else { return nil } } func paymentHost() -> String? { if let lnurlPay = lnurlPay() { return lnurlPay.lnurl.host } else if let lnurlWithdraw = lnurlWithdraw() { return lnurlWithdraw.lnurl.host } else { return nil } } func requestDescription() -> String? { if let paymentRequest = paymentRequest() { return paymentRequest.desc() } else if let lnurlPay = lnurlPay() { return lnurlPay.metadata.plainText } else if let lnurlWithdraw = lnurlWithdraw() { return lnurlWithdraw.defaultDescription } else { return nil } } func priceRange() -> MsatRange? { if let paymentRequest = paymentRequest() { if let min = paymentRequest.amount { return MsatRange( min: min, max: min.times(m: 2.0) ) } } else if let lnurlPay = lnurlPay() { return MsatRange( min: lnurlPay.minSendable, max: lnurlPay.maxSendable ) } else if let lnurlWithdraw = lnurlWithdraw() { return MsatRange( min: lnurlWithdraw.minWithdrawable, max: lnurlWithdraw.maxWithdrawable ) } return nil } func hasExtendedMetadata() -> Bool { guard let lnurlPay = lnurlPay() else { return false } if lnurlPay.metadata.longDesc != nil { return true } if lnurlPay.metadata.imagePng != nil { return true } if lnurlPay.metadata.imageJpg != nil { return true } return false } func supportsPriceRange() -> Bool { if let tuple = priceRange() { return tuple.max.msat > tuple.min.msat } else { return false } } func supportsComment() -> Bool { guard let lnurlPay = lnurlPay() else { return false } let maxCommentLength = lnurlPay.maxCommentLength?.int64Value ?? 0 return maxCommentLength > 0 } func tipNumbers() -> TipNumbers? { guard let totalAmt = try? parsedAmount.get(), totalAmt > 0 else { return nil } var totalMsat: Int64? = nil switch unit { case .bitcoin(let bitcoinUnit): totalMsat = Utils.toMsat(from: totalAmt, bitcoinUnit: bitcoinUnit) case .fiat(let fiatCurrency): if let exchangeRate = currencyPrefs.fiatExchangeRate(fiatCurrency: fiatCurrency) { totalMsat = Utils.toMsat(fromFiat: totalAmt, exchangeRate: exchangeRate) } } var baseMsat: Int64? = nil if let paymentRequest = paymentRequest() { baseMsat = paymentRequest.amount?.msat } else if let lnurlPay = lnurlPay() { baseMsat = lnurlPay.minSendable.msat } guard let totalMsat = totalMsat, let baseMsat = baseMsat, totalMsat > baseMsat else { return nil } let tipMsat = totalMsat - baseMsat let percent = Double(tipMsat) / Double(baseMsat) return TipNumbers(baseMsat: baseMsat, tipMsat: tipMsat, totalMsat: totalMsat, percent: percent) } func tipStrings() -> TipStrings { guard let nums = tipNumbers() else { return TipStrings.empty(currencyPrefs) } let bitcoin_base = Utils.formatBitcoin(msat: nums.baseMsat, bitcoinUnit: currencyPrefs.bitcoinUnit) let bitcoin_tip = Utils.formatBitcoin(msat: nums.tipMsat, bitcoinUnit: currencyPrefs.bitcoinUnit) let bitcoin_total = Utils.formatBitcoin(msat: nums.totalMsat, bitcoinUnit: currencyPrefs.bitcoinUnit) let fiat_base: FormattedAmount let fiat_tip: FormattedAmount let fiat_total: FormattedAmount if let exchangeRate = currencyPrefs.fiatExchangeRate(fiatCurrency: currencyPrefs.fiatCurrency) { fiat_base = Utils.formatFiat(msat: nums.baseMsat, exchangeRate: exchangeRate) fiat_tip = Utils.formatFiat(msat: nums.tipMsat, exchangeRate: exchangeRate) fiat_total = Utils.formatFiat(msat: nums.totalMsat, exchangeRate: exchangeRate) } else { fiat_base = Utils.unknownFiatAmount(fiatCurrency: currencyPrefs.fiatCurrency) fiat_tip = Utils.unknownFiatAmount(fiatCurrency: currencyPrefs.fiatCurrency) fiat_total = Utils.unknownFiatAmount(fiatCurrency: currencyPrefs.fiatCurrency) } let formatter = NumberFormatter() formatter.numberStyle = .percent let percentStr = formatter.string(from: NSNumber(value: nums.percent)) ?? "?%" return TipStrings( bitcoin_base : bitcoin_base, bitcoin_tip : bitcoin_tip, bitcoin_total : bitcoin_total, fiat_base : fiat_base, fiat_tip : fiat_tip, fiat_total : fiat_total, percent : percentStr, isEmpty : false ) } func balanceMsat() -> Int64? { if let model = mvi.model as? Scan.Model_InvoiceFlow_InvoiceRequest { return model.balanceMsat } else if let model = mvi.model as? Scan.Model_LnurlPayFlow_LnurlPayRequest { return model.balanceMsat } else if let model = mvi.model as? Scan.Model_LnurlPayFlow_LnurlPayFetch { return model.balanceMsat } else if let model = mvi.model as? Scan.Model_LnurlWithdrawFlow_LnurlWithdrawRequest { return model.balanceMsat } else if let model = mvi.model as? Scan.Model_LnurlWithdrawFlow_LnurlWithdrawFetch { return model.balanceMsat } else { return nil } } func disconnectedText() -> String { if connectionsManager.connections.internet != Lightning_kmpConnection.established { return NSLocalizedString("waiting for internet", comment: "button text") } if connectionsManager.connections.peer != Lightning_kmpConnection.established { return NSLocalizedString("connecting to peer", comment: "button text") } if connectionsManager.connections.electrum != Lightning_kmpConnection.established { return NSLocalizedString("connecting to electrum", comment: "button text") } return "" } func onAppear() -> Void { log.trace("[\(viewName)] onAppear()") let bitcoinUnit = currencyPrefs.bitcoinUnit unit = Currency.bitcoin(bitcoinUnit) var amount_msat: Lightning_kmpMilliSatoshi? = nil if let paymentRequest = paymentRequest() { amount_msat = paymentRequest.amount } else if let lnurlPay = lnurlPay() { amount_msat = lnurlPay.minSendable } else if let lnurlWithdraw = lnurlWithdraw() { amount_msat = lnurlWithdraw.maxWithdrawable } if let amount_msat = amount_msat { let formattedAmt = Utils.formatBitcoin(msat: amount_msat, bitcoinUnit: bitcoinUnit, hideMsats: false) parsedAmount = Result.success(formattedAmt.amount) // do this first ! amount = formattedAmt.digits } else { altAmount = NSLocalizedString("Enter an amount", comment: "error message") isInvalidAmount = false // display in gray at very beginning } } func modelDidChange(_ newModel: Scan.Model) -> Void { log.trace("[\(viewName)] modelDidChange()") if let model = newModel as? Scan.Model_LnurlPayFlow_LnurlPayRequest { if let payError = model.error { popoverState.display(dismissable: true) { LnurlFlowErrorNotice(error: LnurlFlowError.pay(error: payError)) } } } else if let model = newModel as? Scan.Model_LnurlWithdrawFlow_LnurlWithdrawRequest { if let withdrawError = model.error { popoverState.display(dismissable: true) { LnurlFlowErrorNotice(error: LnurlFlowError.withdraw(error: withdrawError)) } } } } func dismissKeyboardIfVisible() -> Void { log.trace("[\(viewName)] dismissKeyboardIfVisible()") let keyWindow = UIApplication.shared.connectedScenes .filter({ $0.activationState == .foregroundActive }) .map({ $0 as? UIWindowScene }) .compactMap({ $0 }) .first?.windows .filter({ $0.isKeyWindow }).first keyWindow?.endEditing(true) } func amountDidChange() -> Void { log.trace("[\(viewName)] amountDidChange()") refreshAltAmount() } func unitDidChange() -> Void { log.trace("[\(viewName)] unitDidChange()") // We might want to apply a different formatter let result = TextFieldCurrencyStyler.format(input: amount, currency: unit, hideMsats: false) parsedAmount = result.1 amount = result.0 refreshAltAmount() } func refreshAltAmount() -> Void { log.trace("[\(viewName)] refreshAltAmount()") switch parsedAmount { case .failure(let error): isInvalidAmount = true switch error { case .emptyInput: altAmount = NSLocalizedString("Enter an amount", comment: "error message") case .invalidInput: altAmount = NSLocalizedString("Enter a valid amount", comment: "error message") } case .success(let amt): isInvalidAmount = false var msat: Int64? = nil var alt: FormattedAmount? = nil switch unit { case .bitcoin(let bitcoinUnit): // amt => bitcoinUnit // altAmt => fiatCurrency msat = Utils.toMsat(from: amt, bitcoinUnit: bitcoinUnit) if let exchangeRate = currencyPrefs.fiatExchangeRate() { alt = Utils.formatFiat(msat: msat!, exchangeRate: exchangeRate) } else { // We don't know the exchange rate, so we can't display fiat value. altAmount = "" } case .fiat(let fiatCurrency): // amt => fiatCurrency // altAmt => bitcoinUnit if let exchangeRate = currencyPrefs.fiatExchangeRate(fiatCurrency: fiatCurrency) { msat = Utils.toMsat(fromFiat: amt, exchangeRate: exchangeRate) alt = Utils.formatBitcoin(msat: msat!, bitcoinUnit: currencyPrefs.bitcoinUnit) } else { // We don't know the exchange rate ! // We shouldn't get into this state since Currency.displayable() already filters for this. altAmount = "" } } if let msat = msat { let balanceMsat = balanceMsat() ?? 0 if msat > balanceMsat && !(mvi.model is Scan.Model_LnurlWithdrawFlow) { isInvalidAmount = true altAmount = NSLocalizedString("Amount exceeds your balance", comment: "error message") } else if let alt = alt { altAmount = "≈ \(alt.string)" } } if let paymentRequest = paymentRequest(), let expiryTimestampSeconds = paymentRequest.expiryTimestampSeconds()?.doubleValue, Date(timeIntervalSince1970: expiryTimestampSeconds) <= Date() { isExpiredInvoice = true if !isInvalidAmount { altAmount = NSLocalizedString("Invoice is expired", comment: "error message") } } else { isExpiredInvoice = false } if !isInvalidAmount, let msat = msat, let range = priceRange() { let minMsat = range.min.msat let maxMsat = range.max.msat let isRange = maxMsat > minMsat var bitcoinUnit: BitcoinUnit if case .bitcoin(let unit) = unit { bitcoinUnit = unit } else { bitcoinUnit = currencyPrefs.bitcoinUnit } // Since amounts are specified in bitcoin, there are challenges surrounding fiat conversion. // The min/max amounts in bitcoin may not properly round to fiat amounts. // Which could lead to weird UI issues such as: // - User types in 0.01 USD // - Max amount is 20 sats, which converts to less than 0.01 USD // - Error message says: Amount must be at most 0.01 USD // // So we should instead display error messages using exact BTC amounts. // And render fiat conversions as approximate. if !isRange && msat != minMsat { // amount must be exact isInvalidAmount = true let exactBitcoin = Utils.formatBitcoin(msat: minMsat, bitcoinUnit: bitcoinUnit) if case .fiat(let fiatCurrency) = unit, let exchangeRate = currencyPrefs.fiatExchangeRate(fiatCurrency: fiatCurrency) { let approxFiat = Utils.formatFiat(msat: minMsat, exchangeRate: exchangeRate) altAmount = NSLocalizedString( "Amount must be \(exactBitcoin.string) (≈ \(approxFiat.string))", comment: "error message" ) } else { altAmount = NSLocalizedString( "Amount must be \(exactBitcoin.string)", comment: "error message" ) } } else if msat < minMsat { // amount is too low isInvalidAmount = true let minBitcoin = Utils.formatBitcoin(msat: minMsat, bitcoinUnit: bitcoinUnit) if case .fiat(let fiatCurrency) = unit, let exchangeRate = currencyPrefs.fiatExchangeRate(fiatCurrency: fiatCurrency) { let approxFiat = Utils.formatFiat(msat: minMsat, exchangeRate: exchangeRate) altAmount = NSLocalizedString( "Amount must be at least \(minBitcoin.string) (≈ \(approxFiat.string))", comment: "error message" ) } else { altAmount = NSLocalizedString( "Amount must be at least \(minBitcoin.string)", comment: "error message" ) } } else if msat > maxMsat { // amount is too high isInvalidAmount = true let maxBitcoin = Utils.formatBitcoin(msat: maxMsat, bitcoinUnit: bitcoinUnit) if case .fiat(let fiatCurrency) = unit, let exchangeRate = currencyPrefs.fiatExchangeRate(fiatCurrency: fiatCurrency) { let approxFiat = Utils.formatFiat(msat: maxMsat, exchangeRate: exchangeRate) altAmount = NSLocalizedString( "Amount must be at most \(maxBitcoin.string) (≈ \(approxFiat.string))", comment: "error message" ) } else { altAmount = NSLocalizedString( "Amount must be at most \(maxBitcoin.string)", comment: "error message" ) } } } } // </switch parsedAmount> } func metadataButtonTapped() { log.trace("[\(viewName)] metadataButtonTapped()") guard let lnurlPay = lnurlPay() else { return } dismissKeyboardIfVisible() shortSheetState.display(dismissable: true) { MetadataSheet(lnurlPay: lnurlPay) } } func priceTargetButtonTapped() { log.trace("[\(viewName)] priceTargetButtonTapped()") guard let range = priceRange() else { return } let minMsat = range.min.msat let maxMsat = range.max.msat var msat = minMsat if let amt = try? parsedAmount.get(), amt > 0 { switch unit { case .bitcoin(let bitcoinUnit): msat = Utils.toMsat(from: amt, bitcoinUnit: bitcoinUnit) case .fiat(let fiatCurrency): if let exchangeRate = currencyPrefs.fiatExchangeRate(fiatCurrency: fiatCurrency) { msat = Utils.toMsat(fromFiat: amt, exchangeRate: exchangeRate) } } } let isRange = maxMsat > minMsat if isRange { // A range of valid amounts are possible. // Show the PriceSliderSheet. if msat < minMsat { msat = minMsat } else if msat > maxMsat { msat = maxMsat } var flowType: FlowType? = nil if paymentRequest() != nil || lnurlPay() != nil { flowType = FlowType.pay(range: range) } else if lnurlWithdraw() != nil { flowType = FlowType.withdraw(range: range) } if let flowType = flowType { dismissKeyboardIfVisible() shortSheetState.display(dismissable: true) { PriceSliderSheet( flowType: flowType, msat: msat, valueChanged: priceSliderChanged ) } } } else if msat != minMsat { msat = minMsat // There is only one valid amount. // We set the amount directly via the button tap. priceSliderChanged(minMsat) } } func priceSliderChanged(_ msat: Int64) { log.trace("[\(viewName)] priceSliderChanged()") let preferredBitcoinUnit = currencyPrefs.bitcoinUnit unit = Currency.bitcoin(preferredBitcoinUnit) // The TextFieldCurrencyStyler doesn't seem to fire when we manually set the text value. // So we need to do it manually here, to ensure the `parsedAmount` is properly updated. let amt = Utils.formatBitcoin(msat: msat, bitcoinUnit: preferredBitcoinUnit) let result = TextFieldCurrencyStyler.format(input: amt.digits, currency: unit, hideMsats: false) parsedAmount = result.1 amount = result.0 } func commentButtonTapped() { log.trace("[\(viewName)] commentButtonTapped()") guard let lnurlPay = lnurlPay() else { return } let maxCommentLength = lnurlPay.maxCommentLength?.intValue ?? 140 dismissKeyboardIfVisible() shortSheetState.display(dismissable: true) { CommentSheet( comment: $comment, maxCommentLength: maxCommentLength ) } } func sendPayment() { log.trace("[\(viewName)] sendPayment()") guard let amt = try? parsedAmount.get(), amt > 0 else { isInvalidAmount = true return } var msat: Int64? = nil switch unit { case .bitcoin(let bitcoinUnit): msat = Utils.toMsat(from: amt, bitcoinUnit: bitcoinUnit) case .fiat(let fiatCurrency): if let exchangeRate = currencyPrefs.fiatExchangeRate(fiatCurrency: fiatCurrency) { msat = Utils.toMsat(fromFiat: amt, exchangeRate: exchangeRate) } } let saveTipPercentInPrefs = { if let tip = tipNumbers() { let percent = Int(tip.percent * 100.0) Prefs.shared.addRecentTipPercent(percent) } } if let model = mvi.model as? Scan.Model_InvoiceFlow_InvoiceRequest { if let msat = msat { saveTipPercentInPrefs() mvi.intent(Scan.Intent_InvoiceFlow_SendInvoicePayment( paymentRequest: model.paymentRequest, amount: Lightning_kmpMilliSatoshi(msat: msat) )) } } else if let model = mvi.model as? Scan.Model_LnurlPayFlow_LnurlPayRequest { if supportsComment() && comment.count == 0 && !hasPromptedForComment { let maxCommentLength = model.lnurlPay.maxCommentLength?.intValue ?? 140 shortSheetState.onNextWillDisappear { log.debug("shortSheetState.onNextWillDisappear {}") hasPromptedForComment = true } dismissKeyboardIfVisible() shortSheetState.display(dismissable: true) { CommentSheet( comment: $comment, maxCommentLength: maxCommentLength, sendButtonAction: { sendPayment() } ) } } else if let msat = msat { saveTipPercentInPrefs() mvi.intent(Scan.Intent_LnurlPayFlow_SendLnurlPayment( lnurlPay: model.lnurlPay, amount: Lightning_kmpMilliSatoshi(msat: msat), comment: comment )) } } else if let model = mvi.model as? Scan.Model_LnurlWithdrawFlow_LnurlWithdrawRequest { if let msat = msat { saveTipPercentInPrefs() mvi.intent(Scan.Intent_LnurlWithdrawFlow_SendLnurlWithdraw( lnurlWithdraw: model.lnurlWithdraw, amount: Lightning_kmpMilliSatoshi(msat: msat), description: nil )) } } } func didCancelLnurlPayFetch() { log.trace("[\(viewName)] didCancelLnurlPayFetch()") guard let lnurlPay = lnurlPay() else { return } mvi.intent(Scan.Intent_LnurlPayFlow_CancelLnurlPayment( lnurlPay: lnurlPay )) } func didCancelLnurlWithdrawFetch() { log.trace("[\(viewName)] didCancelLnurlWithdrawFetch()") guard let lnurlWithdraw = lnurlWithdraw() else { return } mvi.intent(Scan.Intent_LnurlWithdrawFlow_CancelLnurlWithdraw( lnurlWithdraw: lnurlWithdraw )) } func showAppStatusPopover() { log.trace("[\(viewName)] showAppStatusPopover()") popoverState.display(dismissable: true) { AppStatusPopover() } } } struct MetadataSheet: View, ViewName { let lnurlPay: LNUrl.Pay @Environment(\.shortSheetState) var shortSheetState: ShortSheetState @ViewBuilder var body: some View { VStack(alignment: HorizontalAlignment.center, spacing: 0) { HStack(alignment: VerticalAlignment.center, spacing: 0) { Text("Metadata") .font(.title3) Spacer() Button { closeButtonTapped() } label: { Image("ic_cross") .resizable() .frame(width: 30, height: 30) } } .padding(.horizontal) .padding(.vertical, 8) .background( Color(UIColor.secondarySystemBackground) .cornerRadius(15, corners: [.topLeft, .topRight]) ) .padding(.bottom, 4) content } } @ViewBuilder var content: some View { ScrollView { VStack(alignment: HorizontalAlignment.leading, spacing: 20) { VStack(alignment: HorizontalAlignment.leading, spacing: 8) { Text("Short Description") .font(Font.system(.body, design: .serif)) .bold() Text(lnurlPay.metadata.plainText) .multilineTextAlignment(.leading) .lineLimit(nil) .padding(.leading) } if let longDesc = lnurlPay.metadata.longDesc { VStack(alignment: HorizontalAlignment.leading, spacing: 8) { Text("Long Description") .font(Font.system(.body, design: .serif)) .bold() Text(longDesc) .multilineTextAlignment(.leading) .lineLimit(nil) .padding(.leading) } } if let imagePng = lnurlPay.metadata.imagePng { VStack(alignment: HorizontalAlignment.leading, spacing: 8) { Text("Image") .font(Font.system(.body, design: .serif)) .bold() if let data = Data(base64Encoded: imagePng), let image = UIImage(data: data) { Image(uiImage: image) .padding(.leading) } else { Text("Malformed PNG image data") .padding(.leading) } } } if let imageJpg = lnurlPay.metadata.imageJpg { VStack(alignment: HorizontalAlignment.leading, spacing: 8) { Text("Image") .font(Font.system(.body, design: .serif)) .bold() if let data = Data(base64Encoded: imageJpg), let image = UIImage(data: data) { Image(uiImage: image) .padding(.leading) } else { Text("Malformed JPG image data") .padding(.leading) } } } } // </VStack> .padding(.horizontal) } // </ScrollView> .frame(maxHeight: 250) .padding(.vertical) } func closeButtonTapped() { log.trace("[\(viewName)] closeButtonTapped()") shortSheetState.close() } } struct PriceSliderSheet: View, ViewName { let flowType: FlowType let valueChanged: (Int64) -> Void init(flowType: FlowType, msat: Int64, valueChanged: @escaping (Int64) -> Void) { self.flowType = flowType self.valueChanged = valueChanged _amountSats = State(initialValue: Utils.convertBitcoin(msat: msat, bitcoinUnit: .sat)) } // The Slider family works with BinaryFloatingPoint. // So we're going to switch to `sats: Double` for simplicity. @State var amountSats: Double var range: MsatRange { switch flowType { case .pay(let range): return range case .withdraw(let range): return range } } var rangeSats: ClosedRange<Double> { let range = range let minSat: Double = Double(range.min.msat) / Utils.Millisatoshis_Per_Satoshi let maxSat: Double = Double(range.max.msat) / Utils.Millisatoshis_Per_Satoshi return minSat...maxSat } enum MaxPercentWidth: Preference {} let maxPercentWidthReader = GeometryPreferenceReader( key: AppendValue<MaxPercentWidth>.self, value: { [$0.size.width] } ) @State var maxPercentWidth: CGFloat? = nil enum MaxAmountWidth: Preference {} let maxAmountWidthReader = GeometryPreferenceReader( key: AppendValue<MaxAmountWidth>.self, value: { [$0.size.width] } ) @State var maxAmountWidth: CGFloat? = nil enum ContentHeight: Preference {} let contentHeightReader = GeometryPreferenceReader( key: AppendValue<ContentHeight>.self, value: { [$0.size.height] } ) @State var contentHeight: CGFloat? = nil @Environment(\.colorScheme) var colorScheme: ColorScheme @Environment(\.shortSheetState) var shortSheetState: ShortSheetState @EnvironmentObject var currencyPrefs: CurrencyPrefs @ViewBuilder var body: some View { ZStack { Text(maxPercentString()) .foregroundColor(.clear) .read(maxPercentWidthReader) VStack(alignment: HorizontalAlignment.center, spacing: 0) { HStack(alignment: VerticalAlignment.center, spacing: 0) { Text("Customize amount") .font(.title3) Spacer() Button { closeButtonTapped() } label: { Image("ic_cross") .resizable() .frame(width: 30, height: 30) } } .padding(.horizontal) .padding(.vertical, 8) .background( Color(UIColor.secondarySystemBackground) .cornerRadius(15, corners: [.topLeft, .topRight]) ) .padding(.bottom, 4) content.padding() footer } } .assignMaxPreference(for: maxPercentWidthReader.key, to: $maxPercentWidth) } @ViewBuilder var content: some View { VStack(alignment: HorizontalAlignment.center, spacing: 20) { GeometryReader { proxy in // We have 3 columns: // // | bitcoin prices | vslider | fiat prices | // // We want: // - column 0 & 2 to be exactly the same width // - column 1 to be perfectly centered let vsliderWidth = CGFloat(50) let columnWidth = (proxy.size.width - vsliderWidth) / CGFloat(2) HStack(alignment: VerticalAlignment.center, spacing: 0) { // Column 0: (left) // - Amounts in Bitcoin VStack(alignment: HorizontalAlignment.trailing, spacing: 40) { HStack(alignment: VerticalAlignment.firstTextBaseline, spacing: 0) { Text("Max: ") .foregroundColor(Color(UIColor.tertiaryLabel)) Text(maxBitcoinAmount().string) .foregroundColor(.secondary) .read(maxAmountWidthReader) } Text(bitcoinAmount().string) HStack(alignment: VerticalAlignment.firstTextBaseline, spacing: 0) { Text("Min: ") .foregroundColor(Color(UIColor.tertiaryLabel)) Text(minBitcoinAmount().string) .foregroundColor(.secondary) .frame(width: maxAmountWidth, alignment: .trailing) } } // </VStack: column 0> .frame(width: columnWidth) .read(contentHeightReader) // Column 1: (center) // - Vertical slider VSlider(value: $amountSats, in: rangeSats) { value in log.debug("VSlider.onEditingChanged") } .frame(width: vsliderWidth, height: contentHeight, alignment: .center) // Column 2: (right) // - Amounts in fiat VStack(alignment: HorizontalAlignment.leading, spacing: 0) { HStack(alignment: VerticalAlignment.center, spacing: 0) { Text(verbatim: "≈ ") .font(.footnote) .foregroundColor(Color(UIColor.tertiaryLabel)) Text(maxFiatAmount().string) .foregroundColor(.secondary) } Spacer() HStack(alignment: VerticalAlignment.center, spacing: 0) { Text(verbatim: "≈ ") .font(.footnote) .foregroundColor(Color(UIColor.tertiaryLabel)) Text(fiatAmount().string) } Spacer() HStack(alignment: VerticalAlignment.center, spacing: 0) { Text(verbatim: "≈ ") .font(.footnote) .foregroundColor(Color(UIColor.tertiaryLabel)) Text(minFiatAmount().string) .foregroundColor(.secondary) } } // </VStack: column 2> .frame(width: columnWidth, height: contentHeight) } // </HStack> } // </GeometryReader> .frame(height: contentHeight) HStack(alignment: VerticalAlignment.center, spacing: 10) { Button { minusButtonTapped() } label: { Image(systemName: "minus.circle") .imageScale(.large) } Text(percentString()) .frame(minWidth: maxPercentWidth, alignment: Alignment.center) Button { plusButtonTapped() } label: { Image(systemName: "plus.circle") .imageScale(.large) } } // </HStack> } // </VStack> .assignMaxPreference(for: maxAmountWidthReader.key, to: $maxAmountWidth) .assignMaxPreference(for: contentHeightReader.key, to: $contentHeight) .onChange(of: amountSats) { valueChanged(Utils.toMsat(from: $0, bitcoinUnit: .sat)) } } @ViewBuilder var footer: some View { let recentPercents = recentPercents() if case .pay(_) = flowType, !recentPercents.isEmpty { HStack(alignment: VerticalAlignment.center, spacing: 0) { ForEach(0 ..< recentPercents.count) { idx in let percent = recentPercents[idx] Button { recentButtonTapped(percent) } label: { Text(verbatim: "\(percent)%") .padding(.vertical, 6) .padding(.horizontal, 12) } .buttonStyle(ScaleButtonStyle( backgroundFill: Color(UIColor.systemGroupedBackground), // secondarySystemBackground borderStroke: Color.appAccent )) if idx+1 < recentPercents.count { Spacer() } } // </ForEach> } // </HStack> .padding(.top, 8) .padding([.leading, .trailing, .bottom]) } } func msat() -> Int64 { return Utils.toMsat(from: amountSats, bitcoinUnit: .sat) } func formatBitcoinAmount(msat: Int64) -> FormattedAmount { return Utils.formatBitcoin(msat: msat, bitcoinUnit: currencyPrefs.bitcoinUnit) } func maxBitcoinAmount() -> FormattedAmount { return formatBitcoinAmount(msat: range.max.msat) } func bitcoinAmount() -> FormattedAmount { return formatBitcoinAmount(msat: msat()) } func minBitcoinAmount() -> FormattedAmount { return formatBitcoinAmount(msat: range.min.msat) } func formatFiatAmount(msat: Int64) -> FormattedAmount { if let exchangeRate = currencyPrefs.fiatExchangeRate(fiatCurrency: currencyPrefs.fiatCurrency) { return Utils.formatFiat(msat: msat, exchangeRate: exchangeRate) } else { return Utils.unknownFiatAmount(fiatCurrency: currencyPrefs.fiatCurrency) } } func maxFiatAmount() -> FormattedAmount { return formatFiatAmount(msat: range.max.msat) } func fiatAmount() -> FormattedAmount { return formatFiatAmount(msat: msat()) } func minFiatAmount() -> FormattedAmount { return formatFiatAmount(msat: range.min.msat) } func formatPercent(_ percent: Double) -> String { let formatter = NumberFormatter() formatter.numberStyle = .percent return formatter.string(from: NSNumber(value: percent)) ?? "?%" } func percentToMsat(_ percent: Double) -> Int64 { switch flowType { case .pay(_): // For outgoing payments: // - min => base amount // - anything above min is treated like a tip return Int64(Double(range.min.msat) * (1.0 + percent)) case .withdraw(_): // For withdraws: // - max => treated like 100% of user's balance // - anything below min is a percent of user's balance return Int64(Double(range.max.msat) * percent) } } func maxPercentDouble() -> Double { switch flowType { case .pay(_): // For outgoing payments: // - min => base amount // - anything above min is treated like a tip let minMsat = range.min.msat let maxMsat = range.max.msat return Double(maxMsat - minMsat) / Double(minMsat) case .withdraw(_): // For withdraws: // - max => treated like 100% of user's balance // - anything below min is a percent of user's balance return 1.0 } } func percentDouble() -> Double { switch flowType { case .pay(_): // For outgoing payments: // - min => base amount // - anything above min is treated like a tip let minMsat = range.min.msat let curMsat = msat() return Double(curMsat - minMsat) / Double(minMsat) case .withdraw(_): // For withdraws: // - max => treated like 100% of user's balance // - anything below min is a percent of user's balance let maxMsat = range.max.msat let curMsat = msat() return Double(curMsat) / Double(maxMsat) } } func minPercentDouble() -> Double { switch flowType { case .pay(_): // For outgoing payments: // - min => base amount // - anything above min is treated like a tip return 0.0 case .withdraw(_): // For withdraws: // - max => treated like 100% of user's balance // - anything below min is a percent of user's balance let maxMsat = range.max.msat let minMsat = range.min.msat return Double(minMsat) / Double(maxMsat) } } func maxPercentString() -> String { return formatPercent(maxPercentDouble()) } func percentString() -> String { return formatPercent(percentDouble()) } func minPercentString() -> String { return formatPercent(minPercentDouble()) } func willUserInterfaceChange(percent: Double) -> Bool { if formatPercent(percent) != percentString() { return true } let newMsat = percentToMsat(percent) if formatBitcoinAmount(msat: newMsat).digits != bitcoinAmount().digits { return true } if formatFiatAmount(msat: newMsat).digits != fiatAmount().digits { return true } return false } func minusButtonTapped() { log.trace("[\(viewName)] minusButtonTapped()") var floorPercent = (percentDouble() * 100.0).rounded(.down) // The previous percent may have been something like "8.7%". // And the new percent may be "8%". // // The question is, if we change the percent to "8%", // does this create any kind of change in the UI. // // If the answer is YES, then it's a valid change. // If the answer is NO, then we should drop another percentage point. if !willUserInterfaceChange(percent: (floorPercent / 100.0)) { floorPercent -= 1.0 } let minPercent = minPercentDouble() * 100.0 if floorPercent < minPercent { floorPercent = minPercent } let newMsat = percentToMsat(floorPercent / 100.0) amountSats = Utils.convertBitcoin(msat: newMsat, bitcoinUnit: .sat) } func plusButtonTapped() { log.trace("[\(viewName)] plusButtonTapped()") var ceilingPercent = (percentDouble() * 100.0).rounded(.up) // The previous percent may have been something like "8.7%". // And the new percent may be "9%". // // The question is, if we change the percent to "9%", // does this create any kind of change in the UI. // // If the answer is YES, then it's a valid change. // If the answer is NO, then we should add another percentage point. if !willUserInterfaceChange(percent: (ceilingPercent / 100.0)) { ceilingPercent += 1.0 } let maxPercent = maxPercentDouble() * 100.0 if ceilingPercent > maxPercent { ceilingPercent = maxPercent } let newMsat = percentToMsat(ceilingPercent / 100.0) amountSats = Utils.convertBitcoin(msat: newMsat, bitcoinUnit: .sat) } func recentPercents() -> [Int] { // Most recent item is at index 0 var recents = Prefs.shared.recentTipPercents // Remove items outside the valid range let minPercent = Int(minPercentDouble() * 100.0) let maxPercent = Int(maxPercentDouble() * 100.0) recents = recents.filter { ($0 >= minPercent) && ($0 <= maxPercent) } // Trim to most recent 3 items let targetCount = 3 recents = Array(recents.prefix(targetCount)) // Add default values (if needed/possible) let defaults = [10, 15, 20].filter { ($0 >= minPercent) && ($0 <= maxPercent) } if recents.isEmpty { recents.append(contentsOf: defaults) } else if recents.count < targetCount { // The default list is [10, 15, 20] // But what if the user's first tip is 5%, what should the new list be ? // // The most helpful results will be those numbers that are // closest to the user's own picks. // // Thus: // - if the user's first pick is 5 : [5, 10, 15] // - if the user's first pick is 12 : [10, 12, 15] // - if the user's first pick is 18 : [15, 18, 20] // - if the user's first pick is 25 : [15, 20, 25] // // We can use a similar logic if recents.count == 2 var extras = defaults repeat { let diffs = extras.map { defaultValue in recents.map { recentValue in return abs(defaultValue - recentValue) }.sum() } if let minDiff = diffs.min(), let minIdx = diffs.firstIndex(of: minDiff) { let defaultValue = extras.remove(at: minIdx) recents.append(defaultValue) } } while recents.count < targetCount && !extras.isEmpty } return recents.sorted() } func recentButtonTapped(_ percent: Int) { log.trace("[\(viewName)] recentButtonTapped()") if case .pay(_) = flowType { // For outgoing payments: // - min => base amount // - anything above min is treated like a tip let newMsat = percentToMsat(Double(percent) / 100.0) amountSats = Utils.convertBitcoin(msat: newMsat, bitcoinUnit: .sat) } } func closeButtonTapped() { log.trace("[\(viewName)] closeButtonTapped()") shortSheetState.close() } } struct CommentSheet: View, ViewName { @State var text: String @Binding var comment: String let maxCommentLength: Int @State var remainingCount: Int let sendButtonAction: (() -> Void)? @Environment(\.shortSheetState) var shortSheetState: ShortSheetState init(comment: Binding<String>, maxCommentLength: Int, sendButtonAction: (() -> Void)? = nil) { self._comment = comment self.maxCommentLength = maxCommentLength self.sendButtonAction = sendButtonAction text = comment.wrappedValue remainingCount = maxCommentLength - comment.wrappedValue.count } @ViewBuilder var body: some View { VStack(alignment: HorizontalAlignment.center, spacing: 0) { HStack(alignment: VerticalAlignment.center, spacing: 0) { Text("Add optional comment") .font(.title3) Spacer() Button { closeButtonTapped() } label: { Image("ic_cross") .resizable() .frame(width: 30, height: 30) } } .padding(.horizontal) .padding(.vertical, 8) .background( Color(UIColor.secondarySystemBackground) .cornerRadius(15, corners: [.topLeft, .topRight]) ) .padding(.bottom, 4) content } } @ViewBuilder var content: some View { VStack(alignment: HorizontalAlignment.leading, spacing: 0) { Text("Your comment will be sent when you pay.") .font(.callout) .foregroundColor(.secondary) .padding(.bottom) TextEditor(text: $text) .frame(maxWidth: .infinity, maxHeight: 75) .padding(.all, 4) .background( RoundedRectangle(cornerRadius: 4) .stroke(Color(UIColor.separator), lineWidth: 1) ) HStack(alignment: VerticalAlignment.firstTextBaseline, spacing: 0) { Text("\(remainingCount) remaining") .foregroundColor(remainingCount >= 0 ? Color.primary : Color.appNegative) Spacer() Button { clearButtonTapped() } label: { Text("Clear") } .disabled(text.count == 0) } .padding(.top, 4) if sendButtonAction != nil { sendButton .padding(.top, 16) } } // </VStack> .padding() .onChange(of: text) { textDidChange($0) } } @ViewBuilder var sendButton: some View { HStack(alignment: VerticalAlignment.center, spacing: 0) { Spacer() Button { sendButtonTapped() } label: { HStack { Image("ic_send") .renderingMode(.template) .resizable() .aspectRatio(contentMode: .fit) .foregroundColor(Color.white) .frame(width: 22, height: 22) Text("Pay") .font(.title2) .foregroundColor(Color.white) } .padding(.top, 4) .padding(.bottom, 5) .padding([.leading, .trailing], 24) } .buttonStyle(ScaleButtonStyle( backgroundFill: Color.appAccent, disabledBackgroundFill: Color.gray )) Spacer() } // </HStack> } func textDidChange(_ newText: String) { log.trace("[\(viewName)] textDidChange()") if newText.count <= maxCommentLength { comment = newText } else { let endIdx = newText.index(newText.startIndex, offsetBy: maxCommentLength) let substr = newText[newText.startIndex ..< endIdx] comment = String(substr) } remainingCount = maxCommentLength - newText.count } func clearButtonTapped() { log.trace("[\(viewName)] clearButtonTapped()") text = "" } func closeButtonTapped() { log.trace("[\(viewName)] closeButtonTapped()") shortSheetState.close() } func sendButtonTapped() { log.trace("[\(viewName)] sendButtonTapped()") shortSheetState.close { sendButtonAction!() } } } enum LnurlFlowError { case pay(error: Scan.LnurlPay_Error) case withdraw(error: Scan.LnurlWithdraw_Error) } struct LnurlFlowErrorNotice: View, ViewName { let error: LnurlFlowError @Environment(\.popoverState) var popoverState: PopoverState @ViewBuilder var body: some View { VStack(alignment: HorizontalAlignment.center, spacing: 0) { HStack(alignment: VerticalAlignment.center, spacing: 0) { Image(systemName: "exclamationmark.triangle") .imageScale(.medium) .padding(.trailing, 6) .foregroundColor(Color.appNegative) Text(title()) .font(.headline) Spacer() Button { closeButtonTapped() } label: { Image("ic_cross") .resizable() .frame(width: 30, height: 30) } } .padding(.horizontal) .padding(.vertical, 8) .background( Color(UIColor.secondarySystemBackground) .cornerRadius(15, corners: [.topLeft, .topRight]) ) .padding(.bottom, 4) content } } @ViewBuilder var content: some View { VStack(alignment: HorizontalAlignment.leading, spacing: 0) { errorMessage() } .padding() } @ViewBuilder func errorMessage() -> some View { switch error { case .pay(let payError): errorMessage(payError) case .withdraw(let withdrawError): errorMessage(withdrawError) } } @ViewBuilder func errorMessage(_ payError: Scan.LnurlPay_Error) -> some View { VStack(alignment: HorizontalAlignment.leading, spacing: 8) { if let remoteError = payError as? Scan.LnurlPay_Error_RemoteError { errorMessage(remoteError.err) } else if let err = payError as? Scan.LnurlPay_Error_BadResponseError { if let details = err.err as? LNUrl.Error_PayInvoice_Malformed { Text("Host: \(details.origin)") .font(.system(.subheadline, design: .monospaced)) Text("Malformed: \(details.context)") .font(.system(.subheadline, design: .monospaced)) } else if let details = err.err as? LNUrl.Error_PayInvoice_InvalidHash { Text("Host: \(details.origin)") .font(.system(.subheadline, design: .monospaced)) Text("Error: invalid hash") .font(.system(.subheadline, design: .monospaced)) } else if let details = err.err as? LNUrl.Error_PayInvoice_InvalidAmount { Text("Host: \(details.origin)") .font(.system(.subheadline, design: .monospaced)) Text("Error: invalid amount") .font(.system(.subheadline, design: .monospaced)) } else { genericErrorMessage() } } else if let err = payError as? Scan.LnurlPay_Error_ChainMismatch { let lChain = err.myChain.name let rChain = err.requestChain?.name ?? "Unknown" Text("You are on bitcoin chain \(lChain), but the invoice is for \(rChain).") } else if let _ = payError as? Scan.LnurlPay_Error_AlreadyPaidInvoice { Text("You have already paid this invoice.") } else { genericErrorMessage() } } } @ViewBuilder func errorMessage(_ withdrawError: Scan.LnurlWithdraw_Error) -> some View { VStack(alignment: HorizontalAlignment.leading, spacing: 8) { if let remoteError = withdrawError as? Scan.LnurlWithdraw_Error_RemoteError { errorMessage(remoteError.err) } else { genericErrorMessage() } } } @ViewBuilder func errorMessage(_ remoteFailure: LNUrl.Error_RemoteFailure) -> some View { if let _ = remoteFailure as? LNUrl.Error_RemoteFailure_CouldNotConnect { Text("Could not connect to host:") Text(remoteFailure.origin) .font(.system(.subheadline, design: .monospaced)) } else if let details = remoteFailure as? LNUrl.Error_RemoteFailure_Code { Text("Host returned status code \(details.code.value):") Text(remoteFailure.origin) .font(.system(.subheadline, design: .monospaced)) } else if let details = remoteFailure as? LNUrl.Error_RemoteFailure_Detailed { Text("Host returned error response.") Text("Host: \(details.origin)") .font(.system(.subheadline, design: .monospaced)) Text("Error: \(details.reason)") .font(.system(.subheadline, design: .monospaced)) } else if let _ = remoteFailure as? LNUrl.Error_RemoteFailure_Unreadable { Text("Host returned unreadable response:", comment: "error details") Text(remoteFailure.origin) .font(.system(.subheadline, design: .monospaced)) } else { genericErrorMessage() } } @ViewBuilder func genericErrorMessage() -> some View { Text("Please try again") } private func title() -> String { switch error { case .pay(let payError): return title(payError) case .withdraw(let withdrawError): return title(withdrawError) } } private func title(_ payError: Scan.LnurlPay_Error) -> String { if let remoteErr = payError as? Scan.LnurlPay_Error_RemoteError { return title(remoteErr.err) } else if let _ = payError as? Scan.LnurlPay_Error_BadResponseError { return NSLocalizedString("Invalid response", comment: "Error title") } else if let _ = payError as? Scan.LnurlPay_Error_ChainMismatch { return NSLocalizedString("Chain mismatch", comment: "Error title") } else if let _ = payError as? Scan.LnurlPay_Error_AlreadyPaidInvoice { return NSLocalizedString("Already paid", comment: "Error title") } else { return NSLocalizedString("Unknown error", comment: "Error title") } } private func title(_ withdrawError: Scan.LnurlWithdraw_Error) -> String { if let remoteErr = withdrawError as? Scan.LnurlWithdraw_Error_RemoteError { return title(remoteErr.err) } else { return NSLocalizedString("Unknown error", comment: "Error title") } } private func title(_ remoteFailure: LNUrl.Error_RemoteFailure) -> String { if remoteFailure is LNUrl.Error_RemoteFailure_CouldNotConnect { return NSLocalizedString("Connection failure", comment: "Error title") } else { return NSLocalizedString("Invalid response", comment: "Error title") } } func closeButtonTapped() { log.trace("[\(viewName)] closeButtonTapped()") popoverState.close() } } struct SendingView: View { @ObservedObject var mvi: MVIState<Scan.Model, Scan.Intent> @ViewBuilder var body: some View { ZStack { Color.primaryBackground .edgesIgnoringSafeArea(.all) if AppDelegate.showTestnetBackground { Image("testnet_bg") .resizable(resizingMode: .tile) .ignoresSafeArea(.all, edges: .all) } VStack { Text("Sending Payment...") .font(.title) .padding() } } .frame(maxHeight: .infinity) .edgesIgnoringSafeArea([.bottom, .leading, .trailing]) // top is nav bar .navigationBarTitle( NSLocalizedString("Sending payment", comment: "Navigation bar title"), displayMode: .inline ) .zIndex(0) // [SendingView, ValidateView, LoginView, ScanView] } } struct ReceivingView: View, ViewName { @ObservedObject var mvi: MVIState<Scan.Model, Scan.Intent> @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> @EnvironmentObject var currencyPrefs: CurrencyPrefs let lastIncomingPaymentPublisher = AppDelegate.get().business.paymentsManager.lastIncomingPaymentPublisher() @ViewBuilder var body: some View { ZStack { Color.primaryBackground .edgesIgnoringSafeArea(.all) if AppDelegate.showTestnetBackground { Image("testnet_bg") .resizable(resizingMode: .tile) .ignoresSafeArea(.all, edges: .all) } content } .frame(maxHeight: .infinity) .edgesIgnoringSafeArea([.bottom, .leading, .trailing]) // top is nav bar .navigationBarTitle( NSLocalizedString("Payment Requested", comment: "Navigation bar title"), displayMode: .inline ) .zIndex(0) // [SendingView, ValidateView, LoginView, ScanView] .onReceive(lastIncomingPaymentPublisher) { lastIncomingPaymentChanged($0) } } @ViewBuilder var content: some View { VStack(alignment: HorizontalAlignment.center, spacing: 0) { let host = paymentRequestHost() ?? "🌐" Text("Payment requested from \(host)") .multilineTextAlignment(.center) .font(.title) let amount = paymentAmount()?.string ?? "" Text("You should soon receive a payment for \(amount)") .multilineTextAlignment(.center) .padding(.vertical, 40) Button { closeButtonTapped() } label: { HStack(alignment: VerticalAlignment.firstTextBaseline) { Image(systemName: "checkmark.circle") .renderingMode(.template) .imageScale(.medium) Text("Close") } .font(.title3) .foregroundColor(Color.white) .padding(.top, 4) .padding(.bottom, 5) .padding([.leading, .trailing], 24) } .buttonStyle(ScaleButtonStyle( backgroundFill: Color.appAccent, disabledBackgroundFill: Color(UIColor.systemGray) )) } .padding() } func paymentRequestHost() -> String? { if let model = mvi.model as? Scan.Model_LnurlWithdrawFlow_Receiving { return model.lnurlWithdraw.lnurl.host } return nil } func paymentAmount() -> FormattedAmount? { if let model = mvi.model as? Scan.Model_LnurlWithdrawFlow_Receiving { return Utils.formatBitcoin(msat: model.amount, bitcoinUnit: currencyPrefs.bitcoinUnit) } return nil } func closeButtonTapped() { log.trace("[\(viewName)] closeButtonTapped()") // Pop self from NavigationStack; Back to HomeView presentationMode.wrappedValue.dismiss() } func lastIncomingPaymentChanged(_ lastIncomingPayment: Lightning_kmpIncomingPayment) { log.trace("[\(viewName)] lastIncomingPaymentChanged()") guard let model = mvi.model as? Scan.Model_LnurlWithdrawFlow_Receiving else { return } log.debug("lastIncomingPayment.paymentHash = \(lastIncomingPayment.paymentHash.toHex())") if lastIncomingPayment.state() == WalletPaymentState.success && lastIncomingPayment.paymentHash.toHex() == model.paymentHash { presentationMode.wrappedValue.dismiss() } } } struct LoginView: View, ViewName { @ObservedObject var mvi: MVIState<Scan.Model, Scan.Intent> enum MaxImageHeight: Preference {} let maxImageHeightReader = GeometryPreferenceReader( key: AppendValue<MaxImageHeight>.self, value: { [$0.size.height] } ) @State var maxImageHeight: CGFloat? = nil let buttonFont: Font = .title3 let buttonImgScale: Image.Scale = .medium @ViewBuilder var body: some View { ZStack { Color.primaryBackground .edgesIgnoringSafeArea(.all) if AppDelegate.showTestnetBackground { Image("testnet_bg") .resizable(resizingMode: .tile) .ignoresSafeArea(.all, edges: .all) } // I want the height of these 2 components to match exactly: // Button("<img> Login") // HStack("<img> Logged In") // // To accomplish this, I need the images to be same height. // But they're not - unless we measure them, and enforce matching heights. Image(systemName: "bolt") .imageScale(buttonImgScale) .font(buttonFont) .foregroundColor(.clear) .read(maxImageHeightReader) Image(systemName: "hand.thumbsup.fill") .imageScale(buttonImgScale) .font(buttonFont) .foregroundColor(.clear) .read(maxImageHeightReader) content } .assignMaxPreference(for: maxImageHeightReader.key, to: $maxImageHeight) .frame(maxHeight: .infinity) .edgesIgnoringSafeArea([.bottom, .leading, .trailing]) // top is nav bar .navigationBarTitle("lnurl-auth", displayMode: .inline) .zIndex(2) // [SendingView, ValidateView, LoginView, ScanView] } @ViewBuilder var content: some View { VStack(alignment: HorizontalAlignment.center, spacing: 30) { Spacer() Text("You can use your wallet to anonymously sign and authorize an action on:") .multilineTextAlignment(.center) Text(domain()) .font(.headline) .multilineTextAlignment(.center) if let model = mvi.model as? Scan.Model_LnurlAuthFlow_LoginResult, model.error == nil { HStack(alignment: VerticalAlignment.firstTextBaseline) { Image(systemName: "hand.thumbsup.fill") .renderingMode(.template) .imageScale(buttonImgScale) .frame(minHeight: maxImageHeight) Text(successTitle()) } .font(buttonFont) .foregroundColor(Color.appPositive) .padding(.top, 4) .padding(.bottom, 5) .padding([.leading, .trailing], 24) } else { Button { loginButtonTapped() } label: { HStack(alignment: VerticalAlignment.firstTextBaseline) { Image(systemName: "bolt") .renderingMode(.template) .imageScale(buttonImgScale) .frame(minHeight: maxImageHeight) Text(buttonTitle()) } .font(buttonFont) .foregroundColor(Color.white) .padding(.top, 4) .padding(.bottom, 5) .padding([.leading, .trailing], 24) } .buttonStyle(ScaleButtonStyle( backgroundFill: Color.appAccent, disabledBackgroundFill: Color(UIColor.systemGray) )) .disabled(mvi.model is Scan.Model_LnurlAuthFlow_LoggingIn) } ZStack { Divider() if mvi.model is Scan.Model_LnurlAuthFlow_LoggingIn { HorizontalActivity(color: .appAccent, diameter: 10, speed: 1.6) } } .frame(width: 100, height: 10) if let errorStr = errorText() { Text(errorStr) .font(.callout) .foregroundColor(.appNegative) .multilineTextAlignment(.center) } else { Text("No personal data will be shared with this service.") .font(.callout) .foregroundColor(.secondary) .multilineTextAlignment(.center) } Spacer() Spacer() } // </VStack> .padding(.horizontal, 20) } var auth: LNUrl.Auth? { if let model = mvi.model as? Scan.Model_LnurlAuthFlow_LoginRequest { return model.auth } else if let model = mvi.model as? Scan.Model_LnurlAuthFlow_LoggingIn { return model.auth } else if let model = mvi.model as? Scan.Model_LnurlAuthFlow_LoginResult { return model.auth } else { return nil } } func domain() -> String { return auth?.url.host ?? "?" } func buttonTitle() -> String { if let action = auth?.action() { switch action { case .register_ : return NSLocalizedString("Register", comment: "lnurl-auth: login button title") case .login : return NSLocalizedString("Login", comment: "lnurl-auth: login button title") case .link : return NSLocalizedString("Link", comment: "lnurl-auth: login button title") case .auth : fallthrough default : break } } return NSLocalizedString("Authenticate", comment: "lnurl-auth: login button title") } func successTitle() -> String { if let action = auth?.action() { switch action { case .register_ : return NSLocalizedString("Registered", comment: "lnurl-auth: success text") case .login : return NSLocalizedString("Logged In", comment: "lnurl-auth: success text") case .link : return NSLocalizedString("Linked", comment: "lnurl-auth: success text") case .auth : fallthrough default : break } } return NSLocalizedString("Authenticated", comment: "lnurl-auth: success text") } func errorText() -> String? { if let model = mvi.model as? Scan.Model_LnurlAuthFlow_LoginResult, let error = model.error { if let error = error as? Scan.LoginErrorServerError { if let details = error.details as? LNUrl.ErrorRemoteFailureCode { let frmt = NSLocalizedString("Server returned HTTP status code %d", comment: "error details") return String(format: frmt, details.code.value) } else if let details = error.details as? LNUrl.ErrorRemoteFailureDetailed { let frmt = NSLocalizedString("Server returned error: %@", comment: "error details") return String(format: frmt, details.reason) } else { return NSLocalizedString("Server returned unreadable response", comment: "error details") } } else if error is Scan.LoginErrorNetworkError { return NSLocalizedString("Network error. Check your internet connection.", comment: "error details") } else { return NSLocalizedString("An unknown error occurred.", comment: "error details") } } return nil } func loginButtonTapped() { log.trace("[\(viewName)] loginButtonTapped()") if let model = mvi.model as? Scan.Model_LnurlAuthFlow_LoginRequest { // There's usually a bit of delay between: // - the successful authentication (when Phoenix receives auth success response from server) // - the webpage updating to reflect the authentication success // // This is probably due to several factors: // Possibly due to client-side polling (webpage asking server for an auth result). // Or perhaps the server pushing the successful auth to the client via websockets. // // But whatever the case, it leads to a bit of confusion for the user. // The wallet says "success", but the website just sits there. // Meanwhile the user is left wondering if the wallet is wrong, or something else is broken. // // For this reason, we're smoothing the user experience with a bit of extra animation in the wallet. // Here's how it works: // - the user taps the button, and we immediately send the HTTP GET to the server for authentication // - the UI starts a pretty animation to show that it's authenticating // - if the server responds too quickly (with succcess), we inject a small delay // - during this small delay, the wallet UI continues the pretty animation // - this gives the website a bit of time to update // // The end result is that the website is usually updating (or updated) by the time // the wallet shows the "authenticated" screen. // This leads to less confusion, and a happier user. // Which hopefully leads to more lnurl-auth adoption. // mvi.intent(Scan.Intent_LnurlAuthFlow_Login( auth: model.auth, minSuccessDelaySeconds: 1.6 )) } } } // MARK: - /* Xcode preview fails class SendView_Previews: PreviewProvider { static var previews: some View { NavigationView { SendView(firstModel: nil).mock( Scan.Model_LnurlWithdrawFlow_Receiving( lnurlWithdraw: Mock.shared.lnurlWithdraw( lnurl: "https://www.foobar.com/lnurl", callback: "https://www.foobar.com/callback", k1: "abc123", defaultDescription: "mock withdraw", minWithdrawable: Lightning_kmpMilliSatoshi(msat: 100_000_000), maxWithdrawable: Lightning_kmpMilliSatoshi(msat: 150_000_000) ), amount: Lightning_kmpMilliSatoshi(msat: 150_000_000), description: nil ) ) } .modifier(GlobalEnvironment()) .previewDevice("iPhone 12 mini") } } */
26.220489
109
0.671651
96ab1f209d95b14b178d585c04368e280533c990
5,216
cpp
C++
Cogs/src/Application.cpp
VasilStamatov/cogs2017
4efe9af48a6233936192f9db3d893bcb6564debb
[ "MIT" ]
null
null
null
Cogs/src/Application.cpp
VasilStamatov/cogs2017
4efe9af48a6233936192f9db3d893bcb6564debb
[ "MIT" ]
null
null
null
Cogs/src/Application.cpp
VasilStamatov/cogs2017
4efe9af48a6233936192f9db3d893bcb6564debb
[ "MIT" ]
null
null
null
#include "../include/Application.h" #include "../include/Input.h" #include "../include/GUI.h" #include "../include/ResourceManager.h" #include "../include/Scene.h" #include "../include/Camera.h" #include "../include/Framebuffer.h" namespace cogs { Application::Application() { } Application::~Application() { } void Application::run(const std::string & _windowName, int _windowWidth, int _windowHeight) { m_running = true; //initialize SDL and OpenGL and create the window m_window.create(_windowName, _windowWidth, _windowHeight, WindowFlag::RESIZABLE); //initialize opengl renderers if needed m_renderer2D.init(); m_particleRenderer.init(); //initialize gui systems cogs::GUI::init("GUI"); cogs::GUI::loadScheme("TaharezLook.scheme"); cogs::GUI::setFont("DejaVuSans-10"); cogs::GUI::setMouseCursor("TaharezLook/MouseArrow"); cogs::GUI::hideMouseCursor(); //m_window.showMouseCursor(false); #if DEBUG_TEST m_debugRenderer.init(m_resourceManager); m_debugRenderer.setDebugMode(m_debugRenderer.DBG_DrawWireframe); m_physics.setDebugDrawer(&m_debugRenderer); #endif //load the first scene m_sceneManager.loadScene(0); //begin game loop loop(); //exit app shutdown(); } void Application::addScene(std::unique_ptr<Scene> _newScene) { m_sceneManager.addScene(std::move(_newScene)); } void Application::loop() { while (m_running) { m_fpsLimiter.beginFrame(); Input::update(); handleEvents(); update(m_fpsLimiter.deltaTime()); if (m_running && !m_window.isMinimized()) { m_window.refreshViewport(); render(); m_window.swapBuffer(); } m_fpsLimiter.endFrame(); static int counter = 0; static float fps = 0.0f; static float dt = 0.0f; fps += m_fpsLimiter.fps(); dt += m_fpsLimiter.deltaTime(); if (counter == 100) { fps /= 100.0f; dt /= 100.0f; m_window.setWindowTitle("FPS: " + std::to_string(fps) + " DT: " + std::to_string(dt)); counter = 0; } else { counter++; } } } void Application::update(float _deltaTime) { m_entityManager.update(_deltaTime); m_entityManager.refresh(); m_physics.stepSimulation(); GUI::update(); m_resourceManager.refresh(); } void Application::handleEvents() { SDL_Event evnt; while (SDL_PollEvent(&evnt)) { GUI::onSDLEvent(evnt); switch (evnt.type) { case SDL_QUIT: { m_running = false; break; } case SDL_MOUSEMOTION: { Input::setMouseCoords(static_cast<float>(evnt.motion.x), static_cast<float>(evnt.motion.y)); Input::setMouseMotion(static_cast<float>(evnt.motion.xrel), static_cast<float>(evnt.motion.yrel)); break; } case SDL_KEYDOWN: { Input::pressKey(evnt.key.keysym.sym); break; } case SDL_KEYUP: { Input::releaseKey(evnt.key.keysym.sym); break; } case SDL_MOUSEBUTTONDOWN: { Input::pressKey(evnt.button.button); break; } case SDL_MOUSEBUTTONUP: { Input::releaseKey(evnt.button.button); break; } case SDL_MOUSEWHEEL: { break; } case SDL_WINDOWEVENT: { m_window.handleEvent(evnt); } } } } void Application::render() { for (cogs::Camera* camera : cogs::Camera::getAllCameras()) { if (!camera->getEntity()->isActive()) { continue; } // set the current camera cogs::Camera::setCurrent(camera); // set the render target cogs::Framebuffer::setActive(camera->getRenderTarget()); // clear the window with the camera's background color m_window.setClearColor(camera->getBackgroundColor()); m_window.clear(true, true); m_renderer2D.begin(); m_renderer3D.begin(); m_particleRenderer.begin(); // call the render function of all entities (submits all entities with sprite and mesh renderers) m_entityManager.render(); m_renderer2D.end(); m_renderer3D.end(); m_particleRenderer.end(); //render opaque objects m_renderer3D.flush(); #if DEBUG_TEST //use the debug renderer to draw the debug physics world m_physics.debugDrawWorld(); m_debugRenderer.end(); m_debugRenderer.render(camera->getViewMatrix(), camera->getProjectionMatrix(), 3.0f); #endif //render the camera's skybox if it has one camera->renderSkybox(); //render transparent objects (sorter or blended) m_renderer2D.flush(); m_particleRenderer.flush(); //set the render target to the default window cogs::Framebuffer::setActive(nullptr); } cogs::GUI::render(); } void Application::shutdown() { m_entityManager.clear(); GUI::destroy(); m_window.close(); } void Application::setDesiredFPS(float _fps) { m_fpsLimiter.setMaxFPS(_fps); } }
23.079646
108
0.606403
2f12a34f18a448b3c3d1e90338dd26829acea4e6
6,595
java
Java
maestro-reports/src/main/java/org/maestro/reports/downloaders/DefaultDownloader.java
zkraus/maestro-java
2c65ea3925e8de85875c94e9518e78f87d915097
[ "Apache-2.0" ]
null
null
null
maestro-reports/src/main/java/org/maestro/reports/downloaders/DefaultDownloader.java
zkraus/maestro-java
2c65ea3925e8de85875c94e9518e78f87d915097
[ "Apache-2.0" ]
null
null
null
maestro-reports/src/main/java/org/maestro/reports/downloaders/DefaultDownloader.java
zkraus/maestro-java
2c65ea3925e8de85875c94e9518e78f87d915097
[ "Apache-2.0" ]
null
null
null
package org.maestro.reports.downloaders; import org.apache.http.HttpStatus; import org.maestro.common.HostTypes; import org.maestro.contrib.utils.Downloader; import org.maestro.contrib.utils.resource.exceptions.ResourceExchangeException; import org.maestro.reports.ReceiverReportResolver; import org.maestro.reports.ReportResolver; import org.maestro.reports.SenderReportResolver; import org.maestro.reports.organizer.DefaultOrganizer; import org.maestro.reports.organizer.Organizer; import org.maestro.reports.organizer.ResultStrings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.List; import java.util.Map; public class DefaultDownloader implements ReportsDownloader { private static final Logger logger = LoggerFactory.getLogger(DefaultDownloader.class); private final Map<String, ReportResolver> resolverMap = new HashMap<>(); private final Organizer organizer; private long lastDownloadedTime; /** * Constructor * @param baseDir the base directory for saving the reports */ public DefaultDownloader(final String baseDir) { this.organizer = new DefaultOrganizer(baseDir); resolverMap.put(HostTypes.SENDER_HOST_TYPE, new SenderReportResolver()); resolverMap.put(HostTypes.RECEIVER_HOST_TYPE, new ReceiverReportResolver()); } /** * Constructor * @param organizer the report organizer to use */ public DefaultDownloader(final Organizer organizer) { this.organizer = organizer; resolverMap.put(HostTypes.SENDER_HOST_TYPE, new SenderReportResolver()); resolverMap.put(HostTypes.RECEIVER_HOST_TYPE, new ReceiverReportResolver()); } public Organizer getOrganizer() { return organizer; } public void addReportResolver(final String hostType, final ReportResolver reportResolver) { resolverMap.put(hostType, reportResolver); } private void downloadReport(final String targetURL, final String hostType) throws ResourceExchangeException { final String destinationDir = organizer.organize(targetURL, hostType); if (logger.isDebugEnabled()) { logger.debug("Downloading the {} report file {} to {}", hostType, targetURL, destinationDir); } else { logger.info("Downloading the {} report file {}", hostType, targetURL); } boolean downloaded = false; int repeat = 10; do { try { Downloader.download(targetURL, destinationDir, true); downloaded = true; } catch (ResourceExchangeException re) { if (re.getCode() == HttpStatus.SC_NOT_FOUND) { logger.warn("Remote resource not found or not available yet. Retrying in 5 seconds"); try { Thread.sleep(5000); repeat--; } catch (InterruptedException e) { e.printStackTrace(); } } else { throw re; } } } while (!downloaded && repeat > 0); } /** * Download files from the peers when a test is successful * @param type the type of the peer (sender, receiver, inspector, etc) * @param host the host to download the files from */ public synchronized void downloadLastSuccessful(final String type, final String host) { ReportResolver reportResolver = resolverMap.get(type); getOrganizer().setResultType(ResultStrings.SUCCESS); List<String> files = reportResolver.getSuccessFiles(host); for (String url : files) { try { downloadReport(url, type); } catch (ResourceExchangeException e) { if (e.getCode() != HttpStatus.SC_NOT_FOUND) { logger.warn("Resource {} not found at {} ", e.getUrl(), host); } else { logger.error("Error: {}", e.getMessage(), e); } } } lastDownloadedTime = System.currentTimeMillis(); } /** * Download files from the peers when a test failed * @param type the type of the peer (sender, receiver, inspector, etc) * @param host the host to download the files from */ public void downloadLastFailed(final String type, final String host) { ReportResolver reportResolver = resolverMap.get(type); getOrganizer().setResultType(ResultStrings.FAILED); List<String> files = reportResolver.getFailedFiles(host); for (String url : files) { try { downloadReport(url, type); } catch (ResourceExchangeException e) { if (e.getCode() == HttpStatus.SC_NOT_FOUND) { logger.warn("Resource {} not found at {} ", e.getUrl(), host); } else { logger.error("Error: {}", e.getMessage(), e); } } } lastDownloadedTime = System.currentTimeMillis(); } private void downloadAny(final ReportResolver reportResolver, final String host, final String testNumber) { List<String> files = reportResolver.getTestFiles(host, testNumber); for (String url : files) { try { downloadReport(url, HostTypes.SENDER_HOST_TYPE); } catch (ResourceExchangeException e) { if (e.getCode() == HttpStatus.SC_NOT_FOUND) { logger.warn("Resource {} not found at {} ", e.getUrl(), host); } else { logger.error("Unable to download files from {}", e.getUrl()); } } } } /** * Download files from the peers * @param host the host to download the files from * @param testNumber the test execution number from the peer or one of the links (last, lastSuccessful, lastFailed) */ public void downloadAny(final String type, final String host, final String testNumber) { ReportResolver reportResolver = resolverMap.get(type); if (reportResolver != null) { downloadAny(reportResolver, host, testNumber); } else { logger.warn("There is no report resolver registered for host type {}", type); } lastDownloadedTime = System.currentTimeMillis(); } @Override public void waitForComplete() { // NO-OP } }
34.89418
119
0.611979
f122e74bd93f56a560031d494f4f3a49fb2da8a9
8,499
dart
Dart
web/main.dart
cavr/DartExample
8631224e5018eefc6c36c6697a9f00a837139fe0
[ "BSD-3-Clause" ]
null
null
null
web/main.dart
cavr/DartExample
8631224e5018eefc6c36c6697a9f00a837139fe0
[ "BSD-3-Clause" ]
null
null
null
web/main.dart
cavr/DartExample
8631224e5018eefc6c36c6697a9f00a837139fe0
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2015, <your name>. All rights reserved. Use of this source code // is governed by a BSD-style license that can be found in the LICENSE file. import 'dart:html'; import 'package:back_office/nav_menu.dart'; import 'package:route_hierarchical/client.dart'; import 'dart:convert'; import 'package:crypto/crypto.dart'; ButtonElement inButton; ButtonElement userButton; ButtonElement prototypeMission; ButtonElement prototypeMail; ButtonElement loadUsers; ButtonElement deleteUsers; ButtonElement clonePrototype; ButtonElement inviteUsers; ButtonElement welcomeAll; ButtonElement company; var token = ""; var authUrl = "http://localhost:8080/auth"; var usersUrl = "http://localhost:8080/admin/user"; var missionUrl = "http://localhost:8080/prototype/mission/"; var mailUrl = "http://localhost:8080/prototype/mail/"; var deleteUsersUrl = "http://localhost:8080/prototype/delete-user/"; var loadUsersUrl = "http://localhost:8080/prototype/users/"; var clonePrototypeUrl = "http://localhost:8080/admin/clone-prototype/"; var inviteUsersUrl = "http://localhost:8080/admin/invite-all"; var welcomeAllUrl = "http://localhost:8080/admin/welcome-all"; var companyUrl = "http://localhost:8080/prototype/company/"; String client; String password; void main() { initNavMenu(); inButton = querySelector('#inButton'); inButton.onClick.listen(login); userButton = querySelector('#userButton'); userButton.onClick.listen(getUsers); prototypeMission = querySelector('#prototypeMission'); prototypeMission.onClick.listen(loadMission); prototypeMail = querySelector('#prototypeMail'); prototypeMail.onClick.listen(loadMailTemplate); loadUsers = querySelector('#loadUsers'); loadUsers.onClick.listen(uploadUsers); deleteUsers = querySelector('#deleteUsers'); deleteUsers.onClick.listen(deleteUsersFromCsv); clonePrototype = querySelector("#clonePrototype"); clonePrototype.onClick.listen(clonePrototypeIntoProgram); inviteUsers = querySelector("#inviteUsers"); inviteUsers.onClick.listen(inviteUsersBack); welcomeAll = querySelector("#welcomeAll"); welcomeAll.onClick.listen(wellComeAllBack); company = querySelector("#companyUpdate"); company.onClick.listen(updateCompanyValues); // Webapps need routing to listen for changes to the URL. var router = new Router(); router.root ..addRoute(name: 'about', path: '/about', enter: showAbout) ..addRoute(name: 'home', defaultRoute: true, path: '/', enter: showHome); router.listen(); } void showAbout(RouteEvent e) { // Extremely simple and non-scalable way to show different views. querySelector('#home').style.display = 'none'; querySelector('#about').style.display = ''; } void showHome(RouteEvent e) { querySelector('#home').style.display = ''; querySelector('#about').style.display = 'none'; } Function login(Event e) { client = querySelector("#name").value; password = querySelector("#pass").value; var data = { 'email': client, 'password': password }; HttpRequest.postFormData(authUrl, data).then((HttpRequest req) { print('Request complete ${req.response}'); Map data = JSON.decode(req.response); print('apiId: ${data["apiId"]}'); print('apiSecret ${data["apiSecret"]}'); token = window.btoa("${data["apiId"]}:${data["apiSecret"]}"); print(token); setUserSession(); }); } void showButtonsForUser(){ querySelector('#userButton').style.display = ''; querySelector("#prototypeMail").style.display=''; querySelector("#prototypeMission").style.display=''; querySelector("#programLoad").style.display=''; querySelector("#loadUsers").style.display = ''; querySelector("#deleteUsers").style.display = ''; querySelector("#clonePrototype").style.display = ''; querySelector("#prototypeId").style.display = ''; querySelector("#inviteUsers").style.display = ''; querySelector("#welcomeAll").style.display = ''; querySelector("#inviteId").style.display = ''; querySelector("#companyUpdate").style.display = ''; querySelector("#companyId").style.display = ''; } void setUserSession(){ querySelector('#home_login').style.display = 'none'; querySelector('#home_welcome').style.display = ''; querySelector('#default_about_info').style.display = 'none'; showButtonsForUser(); } void draw(String name) { querySelector('#resp').text = name; } void showUsers(Map users){ var user; for(user in users) { //querySelector('#resp').text = user; } } void getUsers(Event e) { var basic = "Basic " + token; Map header = {'Authorization': basic}; HttpRequest.request(usersUrl, requestHeaders : header).then((HttpRequest req) { //Map data = JSON.decode(req.response); draw(req.response); }).catchError((error){ print(error); }); } void loadMission(Event e){ var basic = "Basic " + token; Map header = {'Authorization': basic}; draw("Cargando misiones"); HttpRequest.request(missionUrl+querySelector("#programLoad").value, requestHeaders : header).then((HttpRequest req) { //Map data = JSON.decode(req.response); draw(req.response); }).catchError((error){ print(error); }); } void loadMailTemplate(Event e){ var basic = "Basic " + token; Map header = {'Authorization': basic}; draw("Cargando Correos"); HttpRequest.request(mailUrl+querySelector("#programLoad").value, requestHeaders : header).then((HttpRequest req) { //Map data = JSON.decode(req.response); draw(req.response); }).catchError((error){ print(error); }); } void uploadUsers(Event e){ var basic = "Basic " + token; Map header = {'Authorization': basic}; draw("Cargando Usuarios"); HttpRequest.request(loadUsersUrl+querySelector("#programLoad").value, requestHeaders : header).then((HttpRequest req) { //Map data = JSON.decode(req.response); draw(req.response); }).catchError((error){ print(error); }); } void deleteUsersFromCsv(Event e){ var basic = "Basic " + token; Map header = {'Authorization': basic}; draw("Borrando Usuarios"); HttpRequest.request(deleteUsersUrl+querySelector("#programLoad").value, requestHeaders : header).then((HttpRequest req) { //Map data = JSON.decode(req.response); draw(req.response); }).catchError((error){ print(error); }); } void clonePrototypeIntoProgram(Event e){ var basic = "Basic " + token; Map header = {'Authorization': basic}; draw("Clonando Prototipo"); HttpRequest.request(clonePrototypeUrl+querySelector("#prototypeId").value, requestHeaders : header).then((HttpRequest req) { //Map data = JSON.decode(req.response); draw(req.response); }).catchError((error){ print(error); }); } void inviteUsersBack(Event e){ var basic = "Basic " + token; var userList = [querySelector("#inviteId").value]; Map data = { 'userList': userList}; var request = new HttpRequest(); request.onReadyStateChange.listen(( Event e){ draw(request.responseText); }); request.open('POST',inviteUsersUrl); request.setRequestHeader('Authorization', basic); request.setRequestHeader( 'Content-Type', 'application/json'); request.send(JSON.encode(data)); } void wellComeAllBack(Event e){ var basic = "Basic " + token; var userList = [querySelector("#inviteId").value]; Map data = { 'userList': userList}; var request = new HttpRequest(); request.onReadyStateChange.listen(( Event e){ draw(request.responseText); }); request.open('POST',welcomeAllUrl); request.setRequestHeader('Authorization', basic); request.setRequestHeader( 'Content-Type', 'application/json'); request.send(JSON.encode(data)); } void updateCompanyValues(Event e){ var basic = "Basic " + token; Map header = {'Authorization': basic}; draw(companyUrl+querySelector("#companyId").value); HttpRequest.request(companyUrl+querySelector("#companyId").value, requestHeaders : header).then((HttpRequest req) { //Map data = JSON.decode(req.response); draw(req.response); }).catchError((error){ print(error); }); }
26.726415
132
0.662902
861b8c28d2fb90099f4ea2fac6c29ca15719b60e
481
java
Java
components-core/src/test/java/com/adyen/checkout/components/models/TestPaymentMethod.java
developerntuc/adyen-android
a1012e33940b13735174d49d59086a203b2474ae
[ "MIT" ]
114
2017-06-02T06:50:54.000Z
2022-03-15T15:24:01.000Z
components-core/src/test/java/com/adyen/checkout/components/models/TestPaymentMethod.java
developerntuc/adyen-android
a1012e33940b13735174d49d59086a203b2474ae
[ "MIT" ]
366
2017-07-12T01:37:24.000Z
2022-03-31T11:49:46.000Z
components-core/src/test/java/com/adyen/checkout/components/models/TestPaymentMethod.java
developerntuc/adyen-android
a1012e33940b13735174d49d59086a203b2474ae
[ "MIT" ]
83
2017-05-12T16:35:26.000Z
2022-02-24T07:47:57.000Z
/* * Copyright (c) 2019 Adyen N.V. * * This file is open source and available under the MIT license. See the LICENSE file for more info. * * Created by caiof on 29/5/2019. */ package com.adyen.checkout.components.models; import android.os.Parcel; import com.adyen.checkout.components.model.payments.request.PaymentMethodDetails; public class TestPaymentMethod extends PaymentMethodDetails { @Override public void writeToParcel(Parcel dest, int flags) { } }
21.863636
100
0.744283
2f05c10d462c68d0f7eabef02b0e3a87b0bbc430
601
java
Java
src/main/java/com/christophecvb/elitedangerous/events/other/CargoTransferEvent.java
ChristopheCVB/EliteDangerousAPI
d88ce9607a05859f41638e5d5dba9598b053eb5e
[ "MIT" ]
9
2020-10-10T13:53:59.000Z
2022-02-20T19:12:45.000Z
src/main/java/com/christophecvb/elitedangerous/events/other/CargoTransferEvent.java
ChristopheCVB/EliteDangerousAPI
d88ce9607a05859f41638e5d5dba9598b053eb5e
[ "MIT" ]
40
2020-10-10T18:23:48.000Z
2022-03-03T13:10:48.000Z
src/main/java/com/christophecvb/elitedangerous/events/other/CargoTransferEvent.java
ChristopheCVB/EliteDangerousAPI
d88ce9607a05859f41638e5d5dba9598b053eb5e
[ "MIT" ]
2
2020-10-10T14:31:11.000Z
2022-02-21T19:29:53.000Z
package com.christophecvb.elitedangerous.events.other; import com.christophecvb.elitedangerous.events.Event; import com.christophecvb.elitedangerous.models.inventory.Transfer; import java.util.List; public class CargoTransferEvent extends Event { public List<Transfer> transfers; public interface Listener extends Event.Listener { @Override default <T extends Event> void onTriggered(T event) { this.onCargoTransferEventTriggered((CargoTransferEvent) event); } void onCargoTransferEventTriggered(CargoTransferEvent cargoTransferEvent); } }
30.05
82
0.760399
85df51d8683076abaeca010e0a1261f3c0ab6ce2
385
h
C
release/src-rt-6.x.4708/router/samba-3.5.8/source3/lib/netapi/examples/common.h
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
4
2017-05-17T11:27:04.000Z
2020-05-24T07:23:26.000Z
release/src-rt-6.x.4708/router/samba-3.5.8/source3/lib/netapi/examples/common.h
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
1
2018-08-21T03:43:09.000Z
2018-08-21T03:43:09.000Z
release/src-rt-6.x.4708/router/samba-3.5.8/source3/lib/netapi/examples/common.h
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
5
2017-10-11T08:09:11.000Z
2020-10-14T04:10:13.000Z
#include <popt.h> void popt_common_callback(poptContext con, enum poptCallbackReason reason, const struct poptOption *opt, const char *arg, const void *data); extern struct poptOption popt_common_netapi_examples[]; #define POPT_COMMON_LIBNETAPI_EXAMPLES { NULL, 0, POPT_ARG_INCLUDE_TABLE, popt_common_netapi_examples, 0, "Common samba netapi example options:", NULL },
32.083333
153
0.784416
f9f11dd1560ccc038cdbe1fdce6302984c8f5fe5
22,992
go
Go
internal/interactor/interactor_test.go
rafaelespinoza/notexfr
5749f71be4517efd1f19c5ff2a783db5740d2367
[ "MIT" ]
4
2020-05-19T16:39:28.000Z
2022-03-05T20:59:53.000Z
internal/interactor/interactor_test.go
rafaelespinoza/notexfr
5749f71be4517efd1f19c5ff2a783db5740d2367
[ "MIT" ]
1
2020-06-01T06:06:35.000Z
2020-06-01T06:06:36.000Z
internal/interactor/interactor_test.go
rafaelespinoza/notexfr
5749f71be4517efd1f19c5ff2a783db5740d2367
[ "MIT" ]
null
null
null
package interactor_test import ( "context" "encoding/json" "fmt" "os" "regexp" "sort" "testing" "time" "github.com/rafaelespinoza/notexfr/internal/entity" "github.com/rafaelespinoza/notexfr/internal/interactor" "github.com/rafaelespinoza/notexfr/internal/repo/sn" ) const ( _BaseTestOutputDir = "/tmp/notexfr_test/internal/interactor" _FixturesDir = "../../internal/fixtures" _StubNotebooksFile = "edam_notebooks.json" _StubNotesFile = "edam_notes.json" _StubTagsFile = "edam_tags.json" _StubENEXFile = "test_export.enex" _StubENtoSNFile = "evernote-to-sn.txt" ) func TestMain(m *testing.M) { os.MkdirAll(_BaseTestOutputDir, 0755) m.Run() } func TestInterfaceImplementations(t *testing.T) { t.Run("members", func(t *testing.T) { implementations := []interface{}{ new(interactor.FromENToSN), } for i, val := range implementations { var ok bool if _, ok = val.(entity.LinkID); !ok { t.Errorf( "test %d; expected value of type %T to implement entity.LinkID", i, val, ) } } }) } func TestConvert(t *testing.T) { pathToTestDir := _BaseTestOutputDir + "/" + t.Name() if err := os.MkdirAll(pathToTestDir, 0755); err != nil { t.Fatal(err) } type TestReference struct { // Type is a human-readable label for the kind of data referenced. It // should be one of: "Note", "Tag", "Notebook". Type string // Index should be the slice index of a referenced item. Index int } // ExpectedTestValues is a set of expectations for one item in the output. type ExpectedTestValues struct { ContentType string Title string // ExpectNoteText signals that the we expect this item to have some // captured HTML content. This would only be true for Note items in the // test input where the <en-note> element has children. ExpectNoteText bool References []TestReference ParentID *TestReference } // ReferenceIDs is used to collect resource IDs that are either known ahead // of time or are generated after running the code. type ReferenceIDs struct{ Notebooks, Notes, Tags []string } testSNItem := func(t *testing.T, ind int, actual *sn.Item, expectedOutput []ExpectedTestValues) (ok bool) { t.Helper() ok = true if actual.Content.Title != expectedOutput[ind].Title { t.Errorf( "test %d; wrong title; got %q, expected %q", ind, actual.Content.Title, expectedOutput[ind].Title, ) ok = false } if actual.ContentType.String() != expectedOutput[ind].ContentType { t.Errorf( "test %d; wrong content type; got %q, expected %q", ind, actual.ContentType, expectedOutput[ind].ContentType, ) ok = false } if !uuidMatcher.MatchString(actual.UUID) { t.Errorf("test %d; invalid UUID: %q", ind, actual.UUID) ok = false } if actual.CreatedAt.IsZero() { t.Errorf("test %d; CreatedAt should not be zero", ind) ok = false } if actual.UpdatedAt.IsZero() { t.Errorf("test %d; UpdatedAt should not be zero", ind) ok = false } return } testSNNote := func(t *testing.T, ind int, actual *sn.Note, expectedOutput []ExpectedTestValues) (ok bool) { t.Helper() ok = true if expectedOutput[ind].ExpectNoteText && actual.Content.Text == "" { t.Errorf("test %d; expected note content not to be empty", ind) ok = false } val, hasKey := actual.Content.AppData["org.standardnotes.sn"] if !hasKey { t.Errorf( "test %d; expected to have value at key %q", ind, "org.standardnotes.sn", ) ok = false } appData, ok := val.(*interactor.SNItemAppData) if !ok { t.Errorf( "test %d; appData should be a %T", ind, &interactor.SNItemAppData{}, ) ok = false return } if !appData.ClientUpdatedAt.Equal(actual.UpdatedAt) { t.Errorf( "test %d; app data incorrect; got %q, expected %q", ind, appData.ClientUpdatedAt, actual.UpdatedAt, ) ok = false } return } testSNReferences := func(t *testing.T, ind int, tagRefs []sn.Reference, expected []TestReference, knownIDs *ReferenceIDs) (ok bool) { t.Helper() ok = true if len(tagRefs) != len(expected) { t.Errorf( "test %d; wrong number of tag references; got %d, expected %d", ind, len(tagRefs), len(expected), ) ok = false return } for j, tag := range tagRefs { var expectedTagUUID string expTagRef := expected[j] switch tag.ContentType { case sn.ContentTypeTag: expectedTagUUID = knownIDs.Tags[expTagRef.Index] case sn.ContentTypeNotebook: expectedTagUUID = knownIDs.Notebooks[expTagRef.Index] case sn.ContentTypeNote: expectedTagUUID = knownIDs.Notes[expTagRef.Index] default: t.Errorf( "test [%d][%d]; unexpected type %q", ind, j, tag.ContentType, ) ok = false continue } if tag.UUID != expectedTagUUID { t.Errorf( "test [%d][%d]; wrong tag UUID; got %q, expected %q", ind, j, tag.UUID, expectedTagUUID, ) ok = false } } return } t.Run("EDAMToStandardNotes", func(t *testing.T) { out, err := interactor.ConvertEDAMToStandardNotes( context.TODO(), interactor.ConvertParams{ InputFilenames: struct{ Notebooks, Notes, Tags string }{ Notebooks: _FixturesDir + "/" + _StubNotebooksFile, Notes: _FixturesDir + "/" + _StubNotesFile, Tags: _FixturesDir + "/" + _StubTagsFile, }, OutputFilename: pathToTestDir + "/edam_to_standardnotes.json", }, ) if err != nil { t.Fatal(err) } knownIDs := ReferenceIDs{ Notes: []string{ "8c44eeb1-7e50-4edb-95c4-12cf90d1017e", // Batman "7c56e278-c268-4003-b1cd-09853ad92b4a", // Atlanta "0f32f51b-f923-4dd0-b5c3-a7d6e8a8a40f", // Aladdin "9df1e45a-623d-4e1b-b370-2d2365499ed0", // Casino "9901a8a3-39a6-437c-9443-e60ef83e6394", // Baltimore "4a5704f8-0825-4926-8f9e-ca74b3c7da85", // Chicago "04630bf8-0800-408b-97d8-cebba0e8b864", // Despicable Me "c66bca64-4395-4675-ae86-9ef35cc0e5cf", // Enter The Dragon "e0322fce-4633-4d7d-8dff-79664844f03f", // Fargo "a2197031-1570-40e4-bc8f-0cb776057f6b", // Detroit "25480cfd-5785-4741-a6fd-a3e37aa9d43e", // Edmonton "879f5e58-60aa-496b-b764-bee8cfd664f6", // Fargo "1820018f-1d5e-4ae9-92c3-f0d72f45d25c", // Hello World }, Tags: []string{ "ed18a1cf-e1f7-4d51-8d9b-f7201e60f564", // "foo" "f299e07c-b98e-4902-ac69-d0c7927e4870", // "free" "bb170464-72e0-4a22-85e0-b2c4f68272ea", // "bar" "53f1fdb5-4140-4ff4-8590-21e8cc2b4338", // "baker" "17585e5c-58cb-401c-b9db-d6f50c77993c", // "altered" }, Notebooks: []string{ "cdb30948-fd4b-4f0f-88e8-68f0ed9e5a09", // "Cities" "932d7c12-bb87-4b41-895a-5d30fa178688", // "Movies" "6aac8caa-0682-4870-95fb-f384301704bc", // "<Inbox>" "ca62b4e6-5649-4512-ae30-2a8de03f80fe", // "Sample" }, } expectedNotes := []ExpectedTestValues{ {ContentType: "Note", Title: "Batman", ExpectNoteText: true, References: []TestReference{{"Tag", 0}, {"Tag", 3}, {"Notebook", 1}}}, {ContentType: "Note", Title: "Atlanta", ExpectNoteText: true, References: []TestReference{{"Tag", 0}, {"Notebook", 0}}}, {ContentType: "Note", Title: "Aladdin", References: []TestReference{{"Tag", 2}, {"Notebook", 1}}}, {ContentType: "Note", Title: "Casino", References: []TestReference{{"Tag", 2}, {"Notebook", 1}}}, {ContentType: "Note", Title: "Baltimore", References: []TestReference{{"Tag", 2}, {"Notebook", 0}}}, {ContentType: "Note", Title: "Chicago", References: []TestReference{{"Tag", 1}, {"Tag", 3}, {"Notebook", 0}}}, {ContentType: "Note", Title: "Despicable Me", References: []TestReference{{"Tag", 0}, {"Notebook", 1}}}, {ContentType: "Note", Title: "Enter The Dragon", References: []TestReference{{"Tag", 2}, {"Notebook", 1}}}, {ContentType: "Note", Title: "Fargo", References: []TestReference{{"Tag", 0}, {"Notebook", 1}}}, {ContentType: "Note", Title: "Detroit", References: []TestReference{{"Tag", 2}, {"Notebook", 0}}}, {ContentType: "Note", Title: "Edmonton", References: []TestReference{{"Tag", 0}, {"Notebook", 0}}}, {ContentType: "Note", Title: "Fargo", References: []TestReference{{"Tag", 2}, {"Notebook", 0}}}, {ContentType: "Note", Title: "Hello World", ExpectNoteText: true, References: []TestReference{{"Tag", 0}, {"Tag", 3}, {"Notebook", 2}}}, } expectedTags := []ExpectedTestValues{ {ContentType: "Tag", Title: "foo", References: []TestReference{{"Note", 0}, {"Note", 1}, {"Note", 6}, {"Note", 8}, {"Note", 10}, {"Note", 12}}}, {ContentType: "Tag", Title: "free", References: []TestReference{{"Note", 5}}, ParentID: &TestReference{"Tag", 0}}, {ContentType: "Tag", Title: "bar", References: []TestReference{{"Note", 2}, {"Note", 3}, {"Note", 4}, {"Note", 7}, {"Note", 9}, {"Note", 11}}}, {ContentType: "Tag", Title: "baker", References: []TestReference{{"Note", 0}, {"Note", 5}, {"Note", 12}}, ParentID: &TestReference{"Tag", 2}}, {ContentType: "Tag", Title: "altered", References: []TestReference{}}, } expectedNotebooks := []ExpectedTestValues{ {ContentType: "Notebook", Title: "Cities", References: []TestReference{{"Note", 1}, {"Note", 4}, {"Note", 5}, {"Note", 9}, {"Note", 10}, {"Note", 11}}}, {ContentType: "Notebook", Title: "Movies", References: []TestReference{{"Note", 0}, {"Note", 2}, {"Note", 3}, {"Note", 6}, {"Note", 7}, {"Note", 8}}}, {ContentType: "Notebook", Title: "<Inbox>", References: []TestReference{{"Hello World", 12}}}, {ContentType: "Notebook", Title: "Samples", References: []TestReference{}}, } expectedOutput := make([]ExpectedTestValues, 0) expectedOutput = append(expectedOutput, expectedNotes...) expectedOutput = append(expectedOutput, expectedTags...) expectedOutput = append(expectedOutput, expectedNotebooks...) actualItems := out.Items if len(actualItems) != len(expectedOutput) { t.Fatalf( "wrong output length; got %d, expected %d", len(actualItems), len(expectedOutput), ) } for ind, member := range actualItems { switch actual := member.(type) { case *sn.Note: testSNItem(t, ind, &actual.Item, expectedOutput) testSNNote(t, ind, actual, expectedOutput) testSNReferences(t, ind, actual.Content.References, expectedOutput[ind].References, &knownIDs) case *sn.Tag: testSNItem(t, ind, &actual.Item, expectedOutput) testSNReferences(t, ind, actual.Content.References, expectedOutput[ind].References, &knownIDs) default: t.Fatalf("test %d; unexpected type %T", ind, actual) } } numExpectedNotes := len(expectedNotes) numExpectedTags := len(expectedTags) actualTags := actualItems[numExpectedNotes : numExpectedNotes+numExpectedTags] for ind, member := range actualTags { tag, ok := member.(*sn.Tag) if !ok { t.Errorf("test %d; expected a %T", ind, &sn.Tag{}) continue } val, ok := tag.Content.AppData["evernote.com"] if !ok { t.Errorf("test %d; expected appData to have key %q", ind, "evernote") continue } appData, ok := val.(*interactor.SNItemAppData) if !ok { t.Errorf( "test %d; appData should be a %T", ind, &interactor.SNItemAppData{}, ) continue } if expectedTags[ind].ParentID == nil { continue } expected := knownIDs.Tags[expectedTags[ind].ParentID.Index] if appData.ParentID != expected { t.Errorf( "test %d; app data incorrect; got %q, expected %q", ind, appData.ParentID, expected, ) } } // test notebooks separately because there are some workarounds for // StandardNote's lack of Notebooks. actualNotebooks := actualItems[numExpectedNotes+numExpectedTags:] for ind, member := range actualNotebooks { tag, ok := member.(*sn.Tag) if !ok { t.Errorf("test %d; expected a %T", ind, &sn.Tag{}) continue } val, ok := tag.Content.AppData["evernote.com"] if !ok { t.Errorf("test %d; expected appData to have key %q", ind, "evernote") } appData, ok := val.(*interactor.SNItemAppData) if !ok { t.Errorf( "test %d; appData should be a %T", ind, &interactor.SNItemAppData{}, ) continue } if appData.OriginalContentType != "Notebook" { t.Errorf( "test %d; app data incorrect; got %q, expected %q", ind, appData.OriginalContentType, "Notebook", ) } } }) t.Run("ENEXToStandardNotes", func(t *testing.T) { out, err := interactor.ConvertENEXToStandardNotes( context.TODO(), interactor.ConvertParams{ InputFilename: _FixturesDir + "/" + _StubENEXFile, OutputFilename: pathToTestDir + "/enex_to_standardnotes.json", }, ) if err != nil { t.Fatal(err) } // collect generated tag info to use in tests later. knownIDs := ReferenceIDs{ Notes: make([]string, 0), Tags: make([]string, 0), } actualItems := out.Items for ind, member := range actualItems { switch actual := member.(type) { case *sn.Note: knownIDs.Notes = append(knownIDs.Notes, actual.UUID) case *sn.Tag: knownIDs.Tags = append(knownIDs.Tags, actual.UUID) default: t.Fatalf("%d, unexpected type %T", ind, actual) } } baseExpectedNotes := []ExpectedTestValues{ {ContentType: "Note", Title: "Batman", ExpectNoteText: true, References: []TestReference{{"Tag", 0}, {"Tag", 1}}}, {ContentType: "Note", Title: "Atlanta", ExpectNoteText: true, References: []TestReference{{"Tag", 0}}}, {ContentType: "Note", Title: "Hello World", ExpectNoteText: true, References: []TestReference{{"Tag", 0}, {"Tag", 1}}}, {ContentType: "Note", Title: "Chicago", References: []TestReference{{"Tag", 1}, {"Tag", 2}}}, {ContentType: "Note", Title: "Edmonton", References: []TestReference{{"Tag", 0}}}, {ContentType: "Note", Title: "Baltimore", References: []TestReference{{"Tag", 3}}}, {ContentType: "Note", Title: "Fargo", References: []TestReference{{"Tag", 3}}}, {ContentType: "Note", Title: "Despicable Me", References: []TestReference{{"Tag", 0}}}, {ContentType: "Note", Title: "Fargo", References: []TestReference{{"Tag", 0}}}, {ContentType: "Note", Title: "Enter The Dragon", References: []TestReference{{"Tag", 3}}}, {ContentType: "Note", Title: "Detroit", References: []TestReference{{"Tag", 3}}}, {ContentType: "Note", Title: "Casino", References: []TestReference{{"Tag", 3}}}, {ContentType: "Note", Title: "Aladdin", References: []TestReference{{"Tag", 3}}}, } baseExpectedTags := []ExpectedTestValues{ {ContentType: "Tag", Title: "foo", References: []TestReference{{"Note", 0}, {"Note", 1}, {"Note", 2}, {"Note", 4}, {"Note", 7}, {"Note", 8}}}, {ContentType: "Tag", Title: "baker", References: []TestReference{{"Note", 0}, {"Note", 2}, {"Note", 3}}}, {ContentType: "Tag", Title: "free", References: []TestReference{{"Note", 3}}}, {ContentType: "Tag", Title: "bar", References: []TestReference{{"Note", 5}, {"Note", 6}, {"Note", 9}, {"Note", 10}, {"Note", 11}, {"Note", 12}}}, } expectedOutput := make([]ExpectedTestValues, 0) expectedOutput = append(expectedOutput, baseExpectedNotes...) expectedOutput = append(expectedOutput, baseExpectedTags...) if len(actualItems) != len(expectedOutput) { t.Fatalf( "wrong output length; got %d, expected %d", len(actualItems), len(expectedOutput), ) } for ind, member := range actualItems { switch actual := member.(type) { case *sn.Note: testSNItem(t, ind, &actual.Item, expectedOutput) testSNNote(t, ind, actual, expectedOutput) testSNReferences(t, ind, actual.Content.References, expectedOutput[ind].References, &knownIDs) case *sn.Tag: testSNItem(t, ind, &actual.Item, expectedOutput) testSNReferences(t, ind, actual.Content.References, expectedOutput[ind].References, &knownIDs) default: t.Errorf("test %d; unexpected type %T", ind, actual) } } }) } // uuidMatcher helps us make sure we're at least trying to make a UUID. Pattern // lifted from: https://stackoverflow.com/a/13653180. var uuidMatcher = regexp.MustCompile(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$`) func TestBackfill(t *testing.T) { pathToTestDir := _BaseTestOutputDir + "/" + t.Name() if err := os.MkdirAll(pathToTestDir, 0755); err != nil { t.Fatal(err) } // expectedTestValues is a set of expected outputs for one test case. type expectedTestValues struct { SNID string ENID string Title string CreatedAt time.Time UpdatedAt time.Time TagIDs []string } t.Run("BackfillSN", func(t *testing.T) { var ( actualOutput []entity.LinkID err error conv *interactor.FromENToSN note *sn.Note ok bool ) actualOutput, err = interactor.BackfillSN( context.TODO(), &interactor.BackfillParams{ EvernoteFilenames: struct{ Notebooks, Notes, Tags string }{ Notebooks: _FixturesDir + "/" + _StubNotebooksFile, Notes: _FixturesDir + "/" + _StubNotesFile, Tags: _FixturesDir + "/" + _StubTagsFile, }, StandardNotesFilename: _FixturesDir + "/" + _StubENtoSNFile, OutputFilenames: struct{ Notebooks, Notes, Tags string }{ Notes: pathToTestDir + "/all_the_things.json", }, }, ) if err != nil { t.Fatal(err) } sort.Slice(actualOutput, func(i, j int) bool { left, right := mustSNNote(actualOutput[i]), mustSNNote(actualOutput[j]) if left.Content.Title < right.Content.Title { return true } else if left.Content.Title > right.Content.Title { return false } else { return left.UUID < right.UUID } }) knownNotebookIDs := map[string]string{ "Cities": "cdb30948-fd4b-4f0f-88e8-68f0ed9e5a09", "Movies": "932d7c12-bb87-4b41-895a-5d30fa178688", "<Inbox>": "6aac8caa-0682-4870-95fb-f384301704bc", "Samples": "ca62b4e6-5649-4512-ae30-2a8de03f80fe", } knownTagIDs := map[string]string{ "baker": "4cbfa0b5-655c-447c-9961-6a5294b6b041", "bar": "30cf9510-845d-4ea8-b673-51104a3e0bc2", "evernote": "90e045a2-46ea-44ff-808b-648274926c7f", "foo": "845e98ed-4515-473e-836b-ada5b5cb8d01", "free": "e5daa664-db99-4cbf-afe5-2c0f043bac8c", } expectedOutput := []expectedTestValues{ { SNID: "63f6d85b-1ac8-4ccf-8ae7-58007fcd033d", ENID: "0f32f51b-f923-4dd0-b5c3-a7d6e8a8a40f", Title: "Aladdin", TagIDs: []string{ knownTagIDs["bar"], knownNotebookIDs["Movies"], }, }, { SNID: "8154cd4e-dd06-4386-afe4-ec09f847b708", ENID: "7c56e278-c268-4003-b1cd-09853ad92b4a", Title: "Atlanta", TagIDs: []string{ knownTagIDs["foo"], knownNotebookIDs["Cities"], }, }, { SNID: "16245526-2f33-4024-ab55-f6c17a61c053", ENID: "9901a8a3-39a6-437c-9443-e60ef83e6394", Title: "Baltimore", TagIDs: []string{ knownTagIDs["bar"], knownNotebookIDs["Cities"], }, }, { SNID: "8e053669-d1cc-4b69-a7fd-4433fc48feb7", ENID: "8c44eeb1-7e50-4edb-95c4-12cf90d1017e", Title: "Batman", TagIDs: []string{ knownTagIDs["foo"], knownTagIDs["baker"], knownNotebookIDs["Movies"], }, }, { SNID: "0f4fe851-b6ff-455a-8d10-cc2e441f7deb", ENID: "9df1e45a-623d-4e1b-b370-2d2365499ed0", Title: "Casino", TagIDs: []string{ knownTagIDs["bar"], knownNotebookIDs["Movies"], }, }, { SNID: "148dbae4-14b7-420e-8cb0-448d1be90ec6", ENID: "4a5704f8-0825-4926-8f9e-ca74b3c7da85", Title: "Chicago", TagIDs: []string{ knownTagIDs["baker"], knownTagIDs["free"], knownNotebookIDs["Cities"], }, }, { SNID: "27822e0b-7e2e-4ef3-ab8b-164f7932abfb", ENID: "04630bf8-0800-408b-97d8-cebba0e8b864", Title: "Despicable Me", TagIDs: []string{ knownTagIDs["foo"], knownNotebookIDs["Movies"], }, }, { SNID: "59f60f6f-fa97-4eaa-80a3-0006e345d381", ENID: "a2197031-1570-40e4-bc8f-0cb776057f6b", Title: "Detroit", TagIDs: []string{ knownTagIDs["bar"], knownNotebookIDs["Cities"], }, }, { SNID: "7d43e417-d6f2-4a7e-9927-60d914c75a45", ENID: "25480cfd-5785-4741-a6fd-a3e37aa9d43e", Title: "Edmonton", TagIDs: []string{ knownTagIDs["foo"], knownNotebookIDs["Cities"], }, }, { SNID: "581a0e66-2cbf-4976-b5e2-a5c6705ca0af", ENID: "c66bca64-4395-4675-ae86-9ef35cc0e5cf", Title: "Enter The Dragon", TagIDs: []string{ knownTagIDs["bar"], knownNotebookIDs["Movies"], }, }, { SNID: "3d378ee3-774f-49cc-838d-4fec925c593a", ENID: "e0322fce-4633-4d7d-8dff-79664844f03f", Title: "Fargo", TagIDs: []string{ knownTagIDs["foo"], knownNotebookIDs["Movies"], }, }, { SNID: "9c78d572-bf80-4fd5-98ce-5b21624100fe", ENID: "879f5e58-60aa-496b-b764-bee8cfd664f6", Title: "Fargo", TagIDs: []string{ knownTagIDs["bar"], knownNotebookIDs["Cities"], }, }, { SNID: "228e48b8-1f46-4c79-a429-a093ed21656c", ENID: "1820018f-1d5e-4ae9-92c3-f0d72f45d25c", Title: "Hello World", TagIDs: []string{ knownTagIDs["foo"], knownTagIDs["baker"], knownNotebookIDs["<Inbox>"], }, }, } if len(actualOutput) != len(expectedOutput) { t.Errorf( "wrong output length; got %d, expected %d", len(actualOutput), len(expectedOutput), ) } for i, item := range actualOutput { if item.GetID() != expectedOutput[i].SNID { t.Errorf( "test %d; wrong ID; got %q, expected %q", i, item.GetID(), expectedOutput[i].SNID, ) } if conv, ok = item.(*interactor.FromENToSN); !ok { t.Fatalf( "test %d; wrong type; got %T, expected %T", i, item, &interactor.FromENToSN{}, ) } if conv.EvernoteID.GetID() != expectedOutput[i].ENID { t.Errorf( "test %d; wrong ENID; got %q, expected %q", i, conv.EvernoteID.GetID(), expectedOutput[i].ENID, ) } if note, ok = conv.LinkID.(*sn.Note); !ok { t.Fatalf( "test %d; wrong type; got %T, expected %T", i, item, &sn.Tag{}, ) } if note.Content.Title != expectedOutput[i].Title { t.Errorf( "test %d; wrong Title; got %q, expected %q", i, note.Content.Title, expectedOutput[i].Title, ) } if len(note.Content.References) != len(expectedOutput[i].TagIDs) { t.Errorf( "test %d; wrong number of tag IDs; got %d, expected %d", i, len(note.Content.References), len(expectedOutput[i].TagIDs), ) } for j, ref := range note.Content.References { if ref.UUID != expectedOutput[i].TagIDs[j] { t.Errorf( "test [%d][%d] wrong tagID; got %q, expected %q", i, j, ref.UUID, expectedOutput[i].TagIDs[j], ) } } } }) } func mustSNTag(link entity.LinkID) *sn.Tag { item := link.(*interactor.FromENToSN) return item.LinkID.(*sn.Tag) } func mustSNNote(link entity.LinkID) *sn.Note { item := link.(*interactor.FromENToSN) return item.LinkID.(*sn.Note) } func mustPrettyPrintJSON(in interface{}) { out, err := json.MarshalIndent(in, " ", " ") if err != nil { panic(err) } fmt.Printf("%+v\n", string(out)) }
32.752137
155
0.637961
5c8b654ff54cb3c777d8a9cb819822953b10ffd0
964
dart
Dart
lib/provider/user_provider.dart
QEout/lalia
d15937cc09eb90c4df7c3c8d06b244ef4499c44d
[ "MIT" ]
2
2021-06-23T10:20:36.000Z
2022-01-17T12:14:31.000Z
lib/provider/user_provider.dart
QEout/lalia
d15937cc09eb90c4df7c3c8d06b244ef4499c44d
[ "MIT" ]
null
null
null
lib/provider/user_provider.dart
QEout/lalia
d15937cc09eb90c4df7c3c8d06b244ef4499c44d
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:lalia/application.dart'; import 'package:lalia/model/bmobBean/user.dart'; import 'package:lalia/utils/bmob_util.dart'; class UserProvider extends ChangeNotifier { User _user; User get user => _user ?? User(); void setUser(User user) { _user = user; print(user); notifyListeners(); } void init() async { if (_user != null) return; _user = await BmobUtil.queryUser(Application.sp.getString('author')); notifyListeners(); } //切换账号和初始账号 // initUser(String objectId) async { // Persona persona=await Persona.queryPersona(FlutterStars.SpUtil.getString("userId")); // User user = User(); // user = await queryUser(objectId); // user.persona=persona; // if(user.objectId!=FlutterStars.SpUtil.getString('alias')) // JpushUtil.setAlias(FlutterStars.SpUtil.getString('userId')); //// notifyListeners(); // setUser(user); //// return true; // } }
26.054054
90
0.678423
3ead42a47461fedac1745d3c9f53ea9ec8d870f8
213
h
C
include/QtUiTools/qtuitoolsversion.h
nesbox/qt5-static-linux2
16c9bce4e6ceab3675c517f1892144e81e172bcd
[ "Libpng", "Zlib" ]
2
2019-03-07T11:19:06.000Z
2021-07-05T18:15:03.000Z
include/QtUiTools/qtuitoolsversion.h
nesbox/qt5-static-linux2
16c9bce4e6ceab3675c517f1892144e81e172bcd
[ "Libpng", "Zlib" ]
null
null
null
include/QtUiTools/qtuitoolsversion.h
nesbox/qt5-static-linux2
16c9bce4e6ceab3675c517f1892144e81e172bcd
[ "Libpng", "Zlib" ]
2
2019-07-26T09:24:47.000Z
2021-04-07T15:30:36.000Z
/* This file was generated by syncqt. */ #ifndef QT_QTUITOOLS_VERSION_H #define QT_QTUITOOLS_VERSION_H #define QTUITOOLS_VERSION_STR "5.11.0" #define QTUITOOLS_VERSION 0x050B00 #endif // QT_QTUITOOLS_VERSION_H
21.3
40
0.812207
88b900099b46cc5ba24245af32d1e7fc856230d9
2,749
swift
Swift
Sources/PackageEtherCapture/Enumerations/Field.swift
keehun/PackageEtherCapture
0c3014ca0b915b04f5a501e701b777931178f543
[ "MIT" ]
3
2020-11-15T10:03:44.000Z
2021-09-10T16:33:25.000Z
Sources/PackageEtherCapture/Enumerations/Field.swift
keehun/PackageEtherCapture
0c3014ca0b915b04f5a501e701b777931178f543
[ "MIT" ]
null
null
null
Sources/PackageEtherCapture/Enumerations/Field.swift
keehun/PackageEtherCapture
0c3014ca0b915b04f5a501e701b777931178f543
[ "MIT" ]
1
2021-05-24T17:29:57.000Z
2021-05-24T17:29:57.000Z
// // File.swift // // // Created by Darrell Root on 3/12/20. // import Foundation // this is intended for fields with corresponding StartIndex and EndIndex values // for highlighting bytes public enum Field { // Frame Fields case srcmac case dstmac case ethertype case ieeeLength case ieeeDsap case ieeeSsap case ieeeControl case snapOrg case snapType case etherType case padding // ARP Fields case hardwareType case protocolType case hardwareSize case protocolSize case operation case senderEthernet case senderIp case targetEthernet case targetIp // BPDU Fields case protocolId case bpduVersion case type case flags case rootId case rootCost case bridgeId case portId case age case maxAge case helloTime case forwardDelay case v1Length // CDP field //version // ttl // checksum //ICMP4 fields //case type //duplicate above but can reuse case code case checksum case payload // IPv4 fields case sourceIP case destinationIP case version case ihl case dscp case ecn case totalLength case identification //case flags // reuse case fragmentOffset case ttl case ipProtocol case headerChecksum case options //case padding // reuse //IPv6 fields // case version // reuse case trafficClass case flowLabel case payloadLength case nextHeader case hopLimit // case sourceIP // reuse // case destinationIP // reuse // case padding // reuse //TCP fields case sourcePort case destinationPort case sequenceNumber case acknowledgementNumber case dataOffset //case flags case window // case checksum case urgentPointer //case options // case payload //UDP fields //case payload //case sourcePort //case destinationPort case length // case checksum //ICMP4 fields //case type //case code // case checksum // case payload case sequence case identifier case mask case pointer case originate case receive case transmit case address //case payloadLength //ICMP6 fields //case type //case code //case checksum //case payload //case pointer //case identifier //case sequence case target // case flags case destination //IGMP4 fields //case type case maxResponseTime //case checksum //case address //case flags supress flag and querier robustness case queryIntervalCode case numberOfSources case sources //TODO highlight per source }
18.958621
80
0.639142
d2a3568f2d75b0f800c89dff3c6e6ce11508c320
933
php
PHP
src/Authentication/Framework/ServiceLocator/Loader/AuthenticationConfigLoader.php
extendssoftware/extends-framework
65abfa72a60c74a0d5e624225b9a4e716a77f54c
[ "MIT" ]
1
2017-12-30T10:44:23.000Z
2017-12-30T10:44:23.000Z
src/Framework/ServiceLocator/Loader/AuthenticationConfigLoader.php
extendsframework/extends-authentication
3b526cd4ac32d6267422844409a4809dec01d1f0
[ "MIT" ]
2
2022-01-09T13:58:34.000Z
2022-01-09T14:30:56.000Z
src/Authentication/Framework/ServiceLocator/Loader/AuthenticationConfigLoader.php
extendssoftware/extends-framework
65abfa72a60c74a0d5e624225b9a4e716a77f54c
[ "MIT" ]
null
null
null
<?php declare(strict_types=1); namespace ExtendsFramework\Authentication\Framework\ServiceLocator\Loader; use ExtendsFramework\Authentication\AuthenticatorInterface; use ExtendsFramework\Authentication\Framework\ServiceLocator\Factory\AuthenticatorFactory; use ExtendsFramework\ServiceLocator\Config\Loader\LoaderInterface; use ExtendsFramework\ServiceLocator\Resolver\Factory\FactoryResolver; use ExtendsFramework\ServiceLocator\ServiceLocatorInterface; class AuthenticationConfigLoader implements LoaderInterface { /** * @inheritDoc */ public function load(): array { return [ ServiceLocatorInterface::class => [ FactoryResolver::class => [ AuthenticatorInterface::class => AuthenticatorFactory::class, ], ], AuthenticatorInterface::class => [ 'realms' => [], ], ]; } }
30.096774
90
0.681672
65e7b562ad2888a3698381236e8ff22cee2dce9c
815
dart
Dart
example/lib/page/size_any_tab_page.dart
wuweijian1997/any_tab
2f39aa0cb264474a9dfdbfe6530d6a0321f12d8b
[ "MIT" ]
2
2020-11-28T07:19:51.000Z
2020-12-01T01:59:02.000Z
example/lib/page/size_any_tab_page.dart
wuweijian1997/any_tab
2f39aa0cb264474a9dfdbfe6530d6a0321f12d8b
[ "MIT" ]
null
null
null
example/lib/page/size_any_tab_page.dart
wuweijian1997/any_tab
2f39aa0cb264474a9dfdbfe6530d6a0321f12d8b
[ "MIT" ]
null
null
null
import 'package:any_tab/any_tab.dart'; import 'package:example/const/const.dart'; import 'package:example/model/index.dart'; import 'package:flutter/material.dart'; import '../widgets/index.dart'; class SizeAnyTabPage extends StatefulWidget { static const String rName = 'SizeClipperTab'; @override _SizeAnyTabPageState createState() => _SizeAnyTabPageState(); } class _SizeAnyTabPageState extends State<SizeAnyTabPage> { @override Widget build(BuildContext context) { return Scaffold( body: Stack( children: [ AnyTab( anyTabDelegate: SizeAnyTabDelegate( tabs: [ for (AnyTabModel model in pages) AnyTabItem( model: model, ), ], ), ), ], )); } }
23.285714
63
0.608589
42a2e5d46952385f88000caf33c2d25e8cac6cd0
1,817
swift
Swift
Example/MusicPlayerSwift3/SettingCell.swift
josephxwf/StreamingMusicPlayer2-Swift3
bd908de0621540e7b97d4386b69e3c1fb5774cdc
[ "MIT" ]
null
null
null
Example/MusicPlayerSwift3/SettingCell.swift
josephxwf/StreamingMusicPlayer2-Swift3
bd908de0621540e7b97d4386b69e3c1fb5774cdc
[ "MIT" ]
null
null
null
Example/MusicPlayerSwift3/SettingCell.swift
josephxwf/StreamingMusicPlayer2-Swift3
bd908de0621540e7b97d4386b69e3c1fb5774cdc
[ "MIT" ]
null
null
null
// // SettingCell.swift // MusicPlayerSwift3 // // Created by Joseph Fan on 6/18/17. // import UIKit class SettingCell: BaseCell { override var isHighlighted: Bool { didSet { backgroundColor = isHighlighted ? UIColor.darkGray : UIColor.white nameLabel.textColor = isHighlighted ? UIColor.white : UIColor.black iconImageView.tintColor = isHighlighted ? UIColor.white : UIColor.darkGray } } var setting: Setting? { didSet { nameLabel.text = setting?.name if let imageName = setting?.imageName { iconImageView.image = UIImage(named: imageName)?.withRenderingMode(.alwaysTemplate) iconImageView.tintColor = UIColor.darkGray } } } let nameLabel: UILabel = { let label = UILabel() label.text = "Setting" label.font = UIFont.systemFont(ofSize: 16) return label }() let iconImageView: UIImageView = { let imageView = UIImageView() imageView.image = UIImage(named: "settings") imageView.contentMode = .scaleAspectFill return imageView }() override func setupViews() { super.setupViews() addSubview(nameLabel) addSubview(iconImageView) addConstraintsWithFormat("H:|-8-[v0(30)]-8-[v1]|", views: iconImageView, nameLabel) addConstraintsWithFormat("V:|[v0]|", views: nameLabel) addConstraintsWithFormat("V:[v0(30)]", views: iconImageView) addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)) } }
24.890411
165
0.58448
e51598ddae47fa9dad00626c163b9c3e4d6aae2f
893
html
HTML
rimijoker.html
yeetus-maximus/Terminaaal
3ce1a9ed82f0dfc176004e00c891994dbf9f270b
[ "MIT" ]
null
null
null
rimijoker.html
yeetus-maximus/Terminaaal
3ce1a9ed82f0dfc176004e00c891994dbf9f270b
[ "MIT" ]
null
null
null
rimijoker.html
yeetus-maximus/Terminaaal
3ce1a9ed82f0dfc176004e00c891994dbf9f270b
[ "MIT" ]
null
null
null
<span id="a">yeetus-maximus@Terminaaal</span>:<span id="b">~</span ><span id="c">$</span> cd yeetus-maximus/About_Me <span id="a">yeetus-maximus@Terminaaal</span>:<span id="b">~</span ><span id="c">$</span> cat Siow Kai Yang.txt<br /><br /> "<span id="k">Hey there, nice to see you here.</span>" This is yeetus-maximus. <p>Yo wassup I like your cut g</p> <p> I am a web dev/student, you can checkout my projects here. <a href="https://github.com/yeetus-maximus"> Projects</a> </p> <p> I usally waste my time doing projects.<br /><br /><br />Here is my <a href="https://github.com/yeetus-maximus"><i class="fab fa-github"></i>GitHub</a> link. </p> <p>You can visit my LinkedIn, here: <a href="#link">LinkedIn WARNING ! : Nothing In There !</a> <br /></p> You can also contact me through email, feel free to send me an email at "21siow.kai.yang@acsians.acsi.edu.sg.com". <p>Adios!</p>
42.52381
106
0.662934
3b5507c1472a97f637d9074ef8ab6dff568436b8
692
ps1
PowerShell
src/Private/Set-ModVariables.ps1
smarbar/MSTeamsDirectRouting
279e343b5c4b850e9bd9c84f4dfa1b54d5e5d153
[ "MIT" ]
null
null
null
src/Private/Set-ModVariables.ps1
smarbar/MSTeamsDirectRouting
279e343b5c4b850e9bd9c84f4dfa1b54d5e5d153
[ "MIT" ]
null
null
null
src/Private/Set-ModVariables.ps1
smarbar/MSTeamsDirectRouting
279e343b5c4b850e9bd9c84f4dfa1b54d5e5d153
[ "MIT" ]
null
null
null
function Set-ModVariables { do { try { [ValidatePattern('^[A-Z]{3}$')]$prefix = Read-Host "Enter the 3 letter prifix to use for this customer, A to Z only" } catch {} } until ($?) $MSTeamsSettings.prefix = $prefix.ToUpper() do { try { $MSTeamsSettings.onlinepstngateway1 = Read-Host "Enter the primary SBC FQDN" } catch {} } until ($?) $MSTeamsSettings.onlinepstngateway2 = Read-Host "Enter the secondary SBC FQDN" $MSTeamsSettings.pstnusage = $MSTeamsSettings.prefix + "-PSTNUsage" $MSTeamsSettings.onlinevoiceroute = $MSTeamsSettings.prefix + "-Voice-Route" $MSTeamsSettings.onlinevoiceroutingpolicy = $MSTeamsSettings.prefix + "-Route-Policy" }
40.705882
121
0.697977
683cf6fc1a307a59fabf268598a5a63cf1c2c599
191
html
HTML
17-http-server/12-404.html
wangding/nodejs-demo
469fcf9689e789602fe67c26612e99ec8b60079a
[ "MIT" ]
20
2017-09-15T03:01:28.000Z
2021-01-28T12:35:54.000Z
17-http-server/12-404.html
wangding/nodejs-demo
469fcf9689e789602fe67c26612e99ec8b60079a
[ "MIT" ]
1
2019-11-11T01:19:42.000Z
2019-11-11T01:19:42.000Z
17-http-server/12-404.html
wangding/nodejs-demo
469fcf9689e789602fe67c26612e99ec8b60079a
[ "MIT" ]
48
2017-09-26T09:15:34.000Z
2021-01-28T12:36:20.000Z
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Error</title> </head> <body> <h1>Sorry! There is nothing!</h1> <a href="/">back to home page</a> </body> </html>
15.916667
35
0.596859
04c88853b9cbde489702082bb195f41e900425ae
1,123
java
Java
ArrayRotation.java
nikhilss13/JavaPrograms
bd488ad4cf1357dbc47daa706046dfcbd4e68f20
[ "MIT" ]
null
null
null
ArrayRotation.java
nikhilss13/JavaPrograms
bd488ad4cf1357dbc47daa706046dfcbd4e68f20
[ "MIT" ]
null
null
null
ArrayRotation.java
nikhilss13/JavaPrograms
bd488ad4cf1357dbc47daa706046dfcbd4e68f20
[ "MIT" ]
null
null
null
package hackerRank; import java.util.*; public class ArrayRotation { private static Scanner sc; public static void main(String[] args) { int n,k; sc = new Scanner(System.in); System.out.print("Enter the size of array: "); n = sc.nextInt(); int[] a = new int[n]; System.out.print("Enter the "+n+" elements in the list: "); for(int i=0;i<n;i++) a[i] = sc.nextInt(); System.out.print("Enter the number of left shifts to array: "); k = sc.nextInt(); System.out.print("Array before "+k+" shifts: "); display(a); solution(a,k); System.out.println(); System.out.print("Array after "+k+" shifts: "); display(a); } public static void solution(int[] a, int k){ int temp=0, j; for(int i=0;i<k;i++){ temp = a[0]; // j=0; // both codes work i.e. for loop and while loop as well // while(j<a.length-1){ // a[j]=a[j+1]; // j++; // } for(j=0;j<a.length-1;j++) a[j]=a[j+1]; a[j]=temp; } } public static void display(int[] a){ for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); } }
22.019608
70
0.548531
3bcc19a55eb43dfa12395ff31057ecada5d1bdee
10,241
html
HTML
_site/december2015/11.html
alienmoutharchive/alienmoutharchive.github.io
12fdd54e90c9619c9a1e50a6a0043015f74b5c2a
[ "MIT" ]
null
null
null
_site/december2015/11.html
alienmoutharchive/alienmoutharchive.github.io
12fdd54e90c9619c9a1e50a6a0043015f74b5c2a
[ "MIT" ]
null
null
null
_site/december2015/11.html
alienmoutharchive/alienmoutharchive.github.io
12fdd54e90c9619c9a1e50a6a0043015f74b5c2a
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html> <!DOCTYPE html> <head> <link href="../css/lightbox.css" rel="stylesheet"> <script src="../css/lightbox.js"></script> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta property="og:url" content="http://alienmouth.com/december2015/11.html" /> <meta property="og:description" content="Alien Mouth publishes writing and audio/visual art" /> <meta property="og:type" content="article" /> <meta property="og:title" content="Three Stories" /> <meta property="og:image" content="http://alienmouth.com/assets/img/og_image.png" /> <meta property="og:site_name" content="Alien Mouth"> <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:site" content="@alienmouth" /> <meta name="twitter:title" content="Three Stories" /> <meta name="twitter:description" content="Alien Mouth publishes writing and audio/visual art" /> <meta name="twitter:image" content="http://alienmouth.com/assets/img/twitter.png" /> <link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <title>Three Stories</title> <meta name="description" content="p&gt;In the ocean trench of your dream, a version of yourself and I stretch a pun over fire, too consumed with survival to roast it to perfection. Together, ..."> <!-- Google Fonts loaded here depending on setting in _data/options.yml true loads font, blank does not--> <link href='//fonts.googleapis.com/css?family=Lato:400,400italic' rel='stylesheet' type='text/css'> <!-- Load up MathJax script if needed ... specify in /_data/options.yml file--> <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="stylesheet" type="text/css" href="/css/tufte.css"> <!-- <link rel="stylesheet" type="text/css" href="/css/print.css" media="print"> --> <link rel="canonical" href="/december2015/11.html"> <link rel="alternate" type="application/rss+xml" title="Alien Mouth" href="/feed.xml" /> </head> <body class="full-width"> <!--- Header and nav template site-wide --> <header> <a href="/"><img class="amlogo" src="/assets/img/logo.png" alt="CH"></a><br /> <div class="nav_custom"> <a href="/">journal</a> <a href="/reviews/">reviews</a> <a href="/books/">books</a> <a href="/about/">about</a> <a href="/connect/">connect</a> </div> </header> <br /><br /> <article> <br /> <h1><center>Three Stories</center></h1> <p class="subtitle"><center>by Logan Ellis on March 18, 2016</center></p><br /> <hr><br /><br /> <div class="custom_read"> <p>p&gt;In the ocean trench of your dream, a version of yourself and I stretch a pun over fire, too consumed with survival to roast it to perfection. Together, we whisper to keep our arms from floating away. I remember how my voice shattered like glass and sank, how it continues to sink and sink, every piece running an impossible marathon against the others. In the end, no one has prepared you for the malice in the deep. We keep rings around our foreheads to hold it intact. Bloody pools in our bodies like headless horsemen. A phantom kite tied into the hopscotch of our ankles. A new animal whose skin is teeth that do not gnaw but molt and grow again. In the beginning, I tried so hard to learn the art of whistling.&lt;/p&gt;</p> <p><b>dreamwear</b></p> <p>In the church of your dream, a group of people is clustered together near the pulpit, wearing a similar-looking werewolf helmet matted with tears that did not come from their eyes, talking quietly with a scribbled whisper that isn’t coming from their mouths. A version of yourself walks in. “Why are you all wearing werewolf helmets?” You ask. “What, you didn’t bring your werewolf helmet?” They respond in unison. “No, what’s a werewolf helmet?” A boy revolves from the group like a shard of mirror. “The werewolf helmet does something different for everyone. The werewolf helmet hides the craters of light in Megan’s face; the werewolf helmet cools &amp; protects the desert brush in Johnny’s mouth; the werewolf helmet keeps Stanley’s diamond-cut bone structure from being scratched; the werewolf helmet takes Melissa’s head to another world, like an oasis on Mars; for me, the werewolf helmet carries my eyes into a sky in the ocean, it makes me feel calm, held, unafraid. What would the werewolf helmet do for you? If my eyes weren’t deep inside my own werewolf helmet, I would tell you, because no one can see their own face—the mirror never tells the whole truth, just cuts it open and watches it bleed out. Go get a werewolf helmet and never take if off. Come back when we know for certain that you know for certain there’s something you want hidden, and that your werewolf helmet prevents any chance of us seeing it.” The boy revolves back into the group, sealing it shut. You go and exchange all of your jewelry for your own werewolf helmet, but when you come back, the group has shattered across the room, facing different directions. In the multicolored moonglow through the stained-glass window, you can see their heads alive and snapping like a wolf’s, their skin sharp and obsidian. At the center of the circle they had once made, a body lies torn, its insides pure and glass like a petrified chunk of wood. When you put on your werewolf helmet, all you see is a three-dimensional dark, fluid and optimistic, like a lie. From inside, you hear the wolves’ breathing move closer to you until you become the center of their circle, swimming under.</p> <p><b>dreamvault</b></p> <p>A list of items in the underground vault of your dream: • a blind cough • a discouraged closet, forever full • a party of metallic hats, stray jackets, an athlete’s left crutch, my videogame manual from years ago • the alphabet unraveling into something primordial, like o microwaved tongues slouching for the cold • animal meat on the floor, so old o that it’s becoming an invention • the eye sockets of a skeleton o slouching flowers into the back of its throat • the sunlight attempting o to join hands ♣ at the center of • the earth.</p> <p><b>dreamstone</b></p> <p>In the clearing outside the small town of your dream, Viktor Shklovsky argues with stones. He wants them to be more like themselves (for the young artist’s sake) stonier than they ever were or ever will be. He’s opening his hands to read aloud the thousands of words etched into his palms, but he seems to be speaking with more than one voice, projecting inwards, outwards, beyond the forest and all of its forests, like how a kaleidoscope creates ghosts of the same color. He conjures pompoms and begins to cheer the stones on. S-T-O-N-E! Eventually, Shklovsky becomes such a dedicated fan that he curls into a stone himself. Oh, he says, now I am the stoniest of all. Imagine: a talking stone. It’s a spectacle. A couple from the small town discovers it talking to itself and reports to the mayor, who demands a stage be built around stone-Shklovsky and its frightening glory. The town begins charging a fee for anyone who wants to stop by and chat, making a fortune off tourists intrigued by the stone’s intelligence. Now, the town can afford to clean up the public transit and even bring in a Chipotle. Everyone begins to see things as more than just a classification; they see the city of veins in everything. Suddenly, Shklovsky’s speech is reduced to nouns and articles—A box. A chair.—but it’s okay because everyone knows what he means. No one is angry. But, over a span of days, he transforms back into human Viktor Shklovsky, retaining the nature of the stone—holding still, not talking. Despite the change, everyone still sees him as a stone, though tourism does begin to dwindle a bit. The small town reclines back into a state of drowsiness, while Shklovsky stands, even now, as stony as ever, the town’s citizens stopping by now and again to have a picnic in the clearing, or to sit next to him and enjoy a nice reflective silence, staring ahead and mouthing tiny words, Shklovsky, all the while, not saying one. He no longer needs to.</p> <p><b>dreamhunger</b></p> <p>In the badlands of your dream, a man cups a tiny, beached whale in his palm, taking a tiny spoon to its innards, grating along the dark pink meat, snapping the ribs up like seeds that failed to glimmer. “This is mine,” he says to himself, “I found it.”</p> <br /><br /> </div> <hr><br /><br /> </article> <span class="print-footer">Three Stories - March 18, 2016 - </span> <script> (function() { var cx = '012309109243193332464:aa5o5mifvhy'; var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true; gcse.src = 'https://cse.google.com/cse.js?cx=' + cx; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s); })(); </script> <gcse:search></gcse:search> <footer> <br /> </footer> </body> </html>
74.751825
1,956
0.72903
a12d07c35efe19640304037f6bf020b4c51cc947
333
kt
Kotlin
app/src/main/java/com/shivamkumarjha/supaflix/model/xmovies/Episode.kt
ShivamKumarJha/supaflix
f027c8ae631b032b621ef2f33c8370b8919b7043
[ "MIT" ]
10
2021-06-02T11:29:54.000Z
2022-03-08T10:32:30.000Z
app/src/main/java/com/shivamkumarjha/supaflix/model/xmovies/Episode.kt
ShivamKumarJha/supaflix
f027c8ae631b032b621ef2f33c8370b8919b7043
[ "MIT" ]
null
null
null
app/src/main/java/com/shivamkumarjha/supaflix/model/xmovies/Episode.kt
ShivamKumarJha/supaflix
f027c8ae631b032b621ef2f33c8370b8919b7043
[ "MIT" ]
null
null
null
package com.shivamkumarjha.supaflix.model.xmovies import com.google.gson.annotations.SerializedName data class Episode( @SerializedName("episode_hash") val episode_hash: String, @SerializedName("name") val name: String, @SerializedName("name_sort") val name_sort: Int, @SerializedName("title") val title: String? )
30.272727
61
0.75976
eac6d55a45ee7ef0836e9854db6bf3b681e6d3c5
396
asm
Assembly
programs/oeis/300/A300293.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
1
2021-03-15T11:38:20.000Z
2021-03-15T11:38:20.000Z
programs/oeis/300/A300293.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
null
null
null
programs/oeis/300/A300293.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
null
null
null
; A300293: A sequence based on the period 6 sequence A151899. ; 0,0,1,1,1,2,3,3,4,4,4,5,6,6,7,7,7,8,9,9,10,10,10,11,12,12,13,13,13,14,15,15,16,16,16,17,18,18,19,19,19,20,21,21,22,22,22,23,24,24,25,25,25,26,27,27,28,28,28,29,30,30,31,31,31,32,33,33,34,34,34,35,36,36,37,37,37,38,39,39,40,40,40,41,42,42,43,43,43,44 mov $1,$0 sub $0,10 mod $0,6 div $1,2 lpb $0 add $1,1 trn $0,$1 lpe sub $1,1
30.461538
251
0.633838
710aed5d732e0118acea91f9c512e3caae567dc3
356
ts
TypeScript
src/constance.ts
coder-tutu/vscode-akita-snippets-files
0f29f35f45b4a5a0bc21dd33d74bca8276b5fad4
[ "MIT" ]
7
2020-04-30T17:08:28.000Z
2020-11-04T10:47:22.000Z
src/constance.ts
coder-tutu/vscode-akita-snippets-files
0f29f35f45b4a5a0bc21dd33d74bca8276b5fad4
[ "MIT" ]
5
2020-05-04T18:12:48.000Z
2020-05-04T18:12:51.000Z
src/constance.ts
nicolehj/vscode-akita-snippets-files
0f29f35f45b4a5a0bc21dd33d74bca8276b5fad4
[ "MIT" ]
null
null
null
/** * @license * Copyright Nicole Inc. */ export const AKITA_CONFIG = { /** Template suffix */ TEMPLATE_SUFFIX: '.tmpl', /** Configuration key */ CONFIGURATION_KEY: 'akita.menu', /** Template path */ TEMPLATE_PATH: 'templates', }; /** * Akita default configurations */ export const AKITA_DEFAULT = { PREFIX: 'app', STYLE: 'scss', };
16.181818
34
0.632022
04fdb4b95b91dd30f59a570c75df74aec2dc23a2
115
java
Java
src/main/java/net/hycube/join/JoinCallback.java
arturolszak/hycube
e7dc0bc7ff5d7c1d406bfee952398515f3f6b6c8
[ "BSD-2-Clause" ]
3
2018-07-18T14:05:13.000Z
2020-05-18T02:15:36.000Z
src/main/java/net/hycube/join/JoinCallback.java
suhasagg/hycube
e7dc0bc7ff5d7c1d406bfee952398515f3f6b6c8
[ "BSD-2-Clause" ]
4
2016-10-02T14:25:30.000Z
2016-11-27T18:10:58.000Z
src/main/java/net/hycube/join/JoinCallback.java
suhasagg/hycube
e7dc0bc7ff5d7c1d406bfee952398515f3f6b6c8
[ "BSD-2-Clause" ]
1
2022-01-10T16:08:30.000Z
2022-01-10T16:08:30.000Z
package net.hycube.join; public interface JoinCallback { public void joinReturned(Object callbackArg); }
10.454545
46
0.747826
9973f75ee0a0338dbc6715650b6fc44eb4e810b4
225
dart
Dart
lib/services/event_bus/events/updated_in_background_event.dart
cypherstack/Campfire
75566901c89f5a082126964b28a108afb675cd19
[ "MIT" ]
6
2022-03-01T06:34:20.000Z
2022-03-07T16:28:15.000Z
lib/services/event_bus/events/updated_in_background_event.dart
cypherstack/Campfire
75566901c89f5a082126964b28a108afb675cd19
[ "MIT" ]
8
2022-03-01T10:41:38.000Z
2022-03-28T10:43:36.000Z
lib/services/event_bus/events/updated_in_background_event.dart
cypherstack/Campfire
75566901c89f5a082126964b28a108afb675cd19
[ "MIT" ]
2
2022-03-02T09:23:22.000Z
2022-03-27T20:05:11.000Z
import 'package:paymint/utilities/logger.dart'; class UpdatedInBackgroundEvent { String message; UpdatedInBackgroundEvent(this.message) { Logger.print("UpdatedInBackgroundEvent fired with message: $message"); } }
22.5
74
0.773333
701cc9b5207e27afb41fc968de2cf973eacdada2
2,457
go
Go
server.go
cartrujillosa/GoCourse
f6746e94acd4e54905902a83d13875b0cfb9d317
[ "MIT" ]
4
2020-07-01T13:38:30.000Z
2020-09-07T09:13:11.000Z
server.go
cartrujillosa/GoCourse
f6746e94acd4e54905902a83d13875b0cfb9d317
[ "MIT" ]
null
null
null
server.go
cartrujillosa/GoCourse
f6746e94acd4e54905902a83d13875b0cfb9d317
[ "MIT" ]
null
null
null
package main import ( "bufio" "fmt" "io" "log" "net" "strings" "github.com/cartrujillosa/GoCourse/project/users" userslib "github.com/cartrujillosa/GoCourse/project/users" ) func main() { // TODO: shutdown gracefully chat := NewChat(":8888") defer chat.Close() registeredUsers := make(chan userslib.User) defer close(registeredUsers) for { conn, err := chat.Listener().Accept() if err != nil { log.Printf("failed to accept connection: %s", err) continue } go registerUser(chat, &conn, registeredUsers) select { case user := <-registeredUsers: go func() { for { msg, err := user.GetMessage() if err != nil && err.Error() == "EOF" { chat.RemoveUser(user) return } else if err != nil { log.Print(err) return } chat.SendMessage(user, msg) } }() } } } func registerUser(chat Chat, conn *net.Conn, registeredUsers chan userslib.User) { var err error var user users.User for { var response *string if response = ask(conn, "¿cómo te llamas?\n"); response == nil { continue } name := *response if response = ask(conn, "¿dónde vives?\n"); response == nil { continue } location := *response user, err = userslib.NewUser(name, location, conn) if err != nil { log.Println(err) continue } if err := chat.RegisterUser(user); err != nil { log.Println(err) continue } else { break } } user.ReceiveMessage(fmt.Sprintf("Hola %s, bienvenido al chat de GDG Marbella!\n", user.Name())) chat.Broadcast(fmt.Sprintf("Den la bienvenida a %s que viene con fuerza desde %s\n", user.Name(), user.Location())) registeredUsers <- user return } func ask(conn *net.Conn, question string) *string { if _, err := io.WriteString(*conn, question); err != nil { log.Println(err) return nil } input, err := bufio.NewReader(*conn).ReadString('\n') if err != nil { log.Fatal(err) return nil } if strings.HasSuffix(input, "\n") { input = input[:len(input)-len("\n")] } // response := make(chan string) // defer close(response) // go func() { // for { // input, err := bufio.NewReader(*conn).ReadString('\n') // if err != nil { // log.Fatal(err) // return // } // response <- input // } // return // }() // select { // case resp := <-response: // return &resp // case <-time.After(4 * time.Second): // io.WriteString(*conn, "timed out\n") // return nil // } return &input }
19.97561
116
0.612943
a6a940ddbd6f94f961edcd9738250e6221f9f70b
5,167
dart
Dart
bin/drinkapi.dart
jameshp/drinkLogServer
9e671b9fdba1c77fa38f520c35e50b3ff8f0cd25
[ "BSD-3-Clause" ]
null
null
null
bin/drinkapi.dart
jameshp/drinkLogServer
9e671b9fdba1c77fa38f520c35e50b3ff8f0cd25
[ "BSD-3-Clause" ]
null
null
null
bin/drinkapi.dart
jameshp/drinkLogServer
9e671b9fdba1c77fa38f520c35e50b3ff8f0cd25
[ "BSD-3-Clause" ]
null
null
null
library drinkapi; import 'dart:async'; import 'package:rpc/api.dart'; import 'mongodb_api.dart'; import 'package:mongo_dart/mongo_dart.dart'; import 'dart:convert'; ///Defines the [UserResponse] returned on the REST API class UserResponse{ String id; String login; String firstName; String lastName; String email; DateTime lastActivity; List<String> tags; UserResponse(); ///used to create userResponse Objects based on MongoDB data UserResponse.fromJson(Map json) { ObjectId _objectId = json["_id"]; id = _objectId.toHexString(); login = json["login"]; firstName = json["firstName"]; lastName = json["lastName"]; email = json["email"]; lastActivity = json["lastActivity"]; tags = json["tags"]; } } class UserRequest{ @ApiProperty(required:true) String login; String firstName; String lastName; String email; DateTime lastActivity; @ApiProperty(required:false) List<String> tags; //this is automatically called by JSON.encode Map toJson() { return { "login" : login, "firstName": firstName, "lastName": lastName, "email": email, "lastActivity": new DateTime.now(), "tags":tags }; } } class DrinkLogRequest{ String id; DateTime logDate; String user_id; List<Drink> drinks; String comment; DrinkLogRequest(); Map toBson(){ List drinkJson = new List(); drinks.forEach((d)=>drinkJson.add(d.toJson())); //print(drinkJson); Map response = { "_id":new ObjectId.fromHexString(id), "logDate": logDate, "user_id":new ObjectId.fromHexString(user_id), "comment":comment, "drinks": drinkJson //JSON.encode(drinks) //drinks.forEach((d)=>d.toJson()), }; return response; } /* Map toJson(){ return{ "_id":id, "logDate": logDate, "user_id":user_id, "comment":comment, "drinks":[ {"drinktype":"Bier","count":4 }, {"drinktype":"Wein","count":2 }] }; } */ ///used to create DrinkLog Response Objects based on MongoDB data DrinkLogRequest.fromBson(Map json) { ObjectId _objectId = json["_id"]; id = _objectId.toHexString(); logDate = json["logDate"]; ObjectId _userId = json["user_id"]; user_id = _userId.toHexString(); comment = json["comment"]; drinks = new List<Drink>();//json["drinks"]; List drinkList = json["drinks"]; drinkList.forEach((d)=> drinks.add(new Drink.fromBson(d))); //[{"drinktype":"Bier","count":4}]; //drinks = {"drinks":json["drinks"]}; } } class Drink{ //static const List<String> DRINKTYPES = const['Bier','Wein','Sekt','Schnaps']; int count; String drinktype; Drink(); Map toJson(){ return{ "count": count, "drinktype": drinktype }; } Drink.fromBson(Map json) { count = json["count"]; drinktype = json["drinktype"]; } } @ApiClass( name: 'drinks', version:'v1', description:'My DrinkLogger server side API' ) class DrinkApi{ final Dao _Dao; DrinkApi(this._Dao); ///get all users @ApiMethod(method:'GET', path:'users/') Future<List<UserResponse>> getUsers() async{ List<UserResponse> allUsers = await _Dao.getAll(); return allUsers; } @ApiMethod(method:'POST', path:'users/') Future<UserResponse> addUser(UserRequest userReq) async{ //datavalidation logic should come here UserResponse user = await _Dao.addUser(userReq); return user; } @ApiMethod(method:'GET', path:'drinks/{userLogin}') Future<List<DrinkLogRequest>> getDrinksFromUser(String userLogin) async{ //datavalidation logic should come here List<DrinkLogRequest> drinkLog = await _Dao.getDrinksFromUser(userLogin); return drinkLog; } @ApiMethod(method:'POST', path:'drinks/') Future<DrinkLogRequest> addDrink(DrinkLogRequest req) async{ //datavalidation logic should come here DrinkLogRequest drinkLog = await _Dao.addDrink(req); return drinkLog; } } // List<UserResponse> x = new List<UserResponse>(); // if (name == null || name.isEmpty){ // return {'Users':x}; // } // else{ // List<UserResponse> x = new List<UserResponse>(); // List<String> tags = new List<String>(); // tags.add("tag a"); // tags.add("tag b"); // x.add(new UserResponse() // ..id = 1 // ..firstName = "peter" // ..lastName = "hofmann" // ..username = name // ..lastActivity = new DateTime.utc(2015,5,6) // ..tags = tags // ); // x.add(new UserResponse() // ..id = 2 // ..firstName = "peter" // ..lastName = "hofmann" // ..username = name // ..lastActivity = new DateTime.now() // ..tags = tags // ); // return {'Users':x}; // }
23.170404
84
0.570157
02ba03cda8fc0c0d99d3f315f982a5d88c9ccb0f
1,167
lua
Lua
lua/save_spatial_convolution_mm_node.lua
jonathantompson/jtorch
06263b3f45552937c7ac2f3a59e4d59ae92c1ba2
[ "BSD-2-Clause" ]
77
2015-01-27T03:05:26.000Z
2020-11-18T12:34:12.000Z
lua/save_spatial_convolution_mm_node.lua
jonathantompson/jtorch
06263b3f45552937c7ac2f3a59e4d59ae92c1ba2
[ "BSD-2-Clause" ]
6
2015-05-28T00:40:46.000Z
2017-01-04T00:26:08.000Z
lua/save_spatial_convolution_mm_node.lua
jonathantompson/jtorch
06263b3f45552937c7ac2f3a59e4d59ae92c1ba2
[ "BSD-2-Clause" ]
16
2015-02-09T02:23:02.000Z
2020-04-24T17:23:26.000Z
function jtorch._saveSpatialConvolutionMMNode(node, ofile) -- The layout is as follows: -- 1. filter width (int) -- 2. filter height (int) -- 3. filter input features (int) -- 4. filter output features (int) -- 5. padding -- 6. filter weights (float array) -- 7. filter Biases (float) ofile:writeInt(node.kW) ofile:writeInt(node.kH) ofile:writeInt(node.nInputPlane) ofile:writeInt(node.nOutputPlane) if (node.padding) then -- Old version ofile:writeInt(node.padding) ofile:writeInt(node.padding) else ofile:writeInt(node.padW) ofile:writeInt(node.padH) end local fanin = node.nInputPlane assert(node.weight:dim() == 2, 'weight tensor is not 2D!') assert(node.weight:size(2) == (node.nInputPlane * node.kH * node.kW), 'bad weight tensor size!') -- Resize to 4D node.weight:resize(node.nOutputPlane, node.nInputPlane, node.kH, node.kW) jtorch._saveFloatTensorSafe(ofile, node.weight) -- Now Resize back to 2D node.weight:resize(node.nOutputPlane, node.nInputPlane * node.kH * node.kW) assert(node.bias:dim() == 1, 'bias vector is not 1D!') jtorch._saveFloatTensorSafe(ofile, node.bias) end
30.710526
77
0.696658
83e82c66c43410306076c7e36d010b68883ae332
27,560
java
Java
xs2a-server-api/src/main/java/de/adorsys/psd2/model/Transactions.java
ggiorkhelidze/xs2a
f844081ac1c780eb95d5465a9603aa62787dc8b8
[ "Apache-2.0" ]
120
2018-04-19T13:15:59.000Z
2022-03-27T21:50:38.000Z
xs2a-server-api/src/main/java/de/adorsys/psd2/model/Transactions.java
ggiorkhelidze/xs2a
f844081ac1c780eb95d5465a9603aa62787dc8b8
[ "Apache-2.0" ]
72
2018-05-04T14:03:18.000Z
2022-03-10T14:00:22.000Z
xs2a-server-api/src/main/java/de/adorsys/psd2/model/Transactions.java
ggiorkhelidze/xs2a
f844081ac1c780eb95d5465a9603aa62787dc8b8
[ "Apache-2.0" ]
85
2018-05-07T09:56:46.000Z
2022-03-09T10:10:29.000Z
package de.adorsys.psd2.model; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.time.LocalDate; import java.util.Map; import java.util.Objects; /** * Transaction details. */ @ApiModel(description = "Transaction details.") @Validated @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2021-05-27T13:20:30.606211+03:00[Europe/Kiev]") public class Transactions { @JsonProperty("transactionId") private String transactionId = null; @JsonProperty("entryReference") private String entryReference = null; @JsonProperty("endToEndId") private String endToEndId = null; @JsonProperty("batchIndicator") private Boolean batchIndicator = null; @JsonProperty("batchNumberOfTransactions") private Integer batchNumberOfTransactions = null; @JsonProperty("mandateId") private String mandateId = null; @JsonProperty("checkId") private String checkId = null; @JsonProperty("creditorId") private String creditorId = null; @JsonProperty("bookingDate") private LocalDate bookingDate = null; @JsonProperty("valueDate") private LocalDate valueDate = null; @JsonProperty("transactionAmount") private Amount transactionAmount = null; @JsonProperty("currencyExchange") private ReportExchangeRateList currencyExchange = null; @JsonProperty("creditorName") private String creditorName = null; @JsonProperty("creditorAccount") private AccountReference creditorAccount = null; @JsonProperty("creditorAgent") private String creditorAgent = null; @JsonProperty("ultimateCreditor") private String ultimateCreditor = null; @JsonProperty("debtorName") private String debtorName = null; @JsonProperty("debtorAccount") private AccountReference debtorAccount = null; @JsonProperty("debtorAgent") private String debtorAgent = null; @JsonProperty("ultimateDebtor") private String ultimateDebtor = null; @JsonProperty("remittanceInformationUnstructured") private String remittanceInformationUnstructured = null; @JsonProperty("remittanceInformationUnstructuredArray") private RemittanceInformationUnstructuredArray remittanceInformationUnstructuredArray = null; @JsonProperty("remittanceInformationStructured") private String remittanceInformationStructured = null; @JsonProperty("remittanceInformationStructuredArray") private RemittanceInformationStructuredArray remittanceInformationStructuredArray = null; @JsonProperty("entryDetails") private EntryDetails entryDetails = null; @JsonProperty("additionalInformation") private String additionalInformation = null; @JsonProperty("additionalInformationStructured") private AdditionalInformationStructured additionalInformationStructured = null; @JsonProperty("purposeCode") private PurposeCode purposeCode = null; @JsonProperty("bankTransactionCode") private String bankTransactionCode = null; @JsonProperty("proprietaryBankTransactionCode") private String proprietaryBankTransactionCode = null; @JsonProperty("balanceAfterTransaction") private Balance balanceAfterTransaction = null; @JsonProperty("_links") private Map _links = null; public Transactions transactionId(String transactionId) { this.transactionId = transactionId; return this; } /** * Get transactionId * @return transactionId **/ @ApiModelProperty(value = "") @JsonProperty("transactionId") public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public Transactions entryReference(String entryReference) { this.entryReference = entryReference; return this; } /** * Get entryReference * @return entryReference **/ @ApiModelProperty(value = "") @Size(max=35) @JsonProperty("entryReference") public String getEntryReference() { return entryReference; } public void setEntryReference(String entryReference) { this.entryReference = entryReference; } public Transactions endToEndId(String endToEndId) { this.endToEndId = endToEndId; return this; } /** * Unique end to end identity. * @return endToEndId **/ @ApiModelProperty(value = "Unique end to end identity.") @Size(max=35) @JsonProperty("endToEndId") public String getEndToEndId() { return endToEndId; } public void setEndToEndId(String endToEndId) { this.endToEndId = endToEndId; } public Transactions batchIndicator(Boolean batchIndicator) { this.batchIndicator = batchIndicator; return this; } /** * If this indicator equals true, then the related entry is a batch entry. * @return batchIndicator **/ @ApiModelProperty(value = "If this indicator equals true, then the related entry is a batch entry. ") @JsonProperty("batchIndicator") public Boolean isBatchIndicator() { return batchIndicator; } public void setBatchIndicator(Boolean batchIndicator) { this.batchIndicator = batchIndicator; } public Transactions batchNumberOfTransactions(Integer batchNumberOfTransactions) { this.batchNumberOfTransactions = batchNumberOfTransactions; return this; } /** * Shall be used if and only if the batchIndicator is contained and equals true. * @return batchNumberOfTransactions **/ @ApiModelProperty(value = "Shall be used if and only if the batchIndicator is contained and equals true. ") @JsonProperty("batchNumberOfTransactions") public Integer getBatchNumberOfTransactions() { return batchNumberOfTransactions; } public void setBatchNumberOfTransactions(Integer batchNumberOfTransactions) { this.batchNumberOfTransactions = batchNumberOfTransactions; } public Transactions mandateId(String mandateId) { this.mandateId = mandateId; return this; } /** * Identification of Mandates, e.g. a SEPA Mandate ID. * @return mandateId **/ @ApiModelProperty(value = "Identification of Mandates, e.g. a SEPA Mandate ID.") @Size(max=35) @JsonProperty("mandateId") public String getMandateId() { return mandateId; } public void setMandateId(String mandateId) { this.mandateId = mandateId; } public Transactions checkId(String checkId) { this.checkId = checkId; return this; } /** * Identification of a Cheque. * @return checkId **/ @ApiModelProperty(value = "Identification of a Cheque.") @Size(max=35) @JsonProperty("checkId") public String getCheckId() { return checkId; } public void setCheckId(String checkId) { this.checkId = checkId; } public Transactions creditorId(String creditorId) { this.creditorId = creditorId; return this; } /** * Get creditorId * @return creditorId **/ @ApiModelProperty(value = "") @Size(max=35) @JsonProperty("creditorId") public String getCreditorId() { return creditorId; } public void setCreditorId(String creditorId) { this.creditorId = creditorId; } public Transactions bookingDate(LocalDate bookingDate) { this.bookingDate = bookingDate; return this; } /** * Get bookingDate * @return bookingDate **/ @ApiModelProperty(value = "") @Valid @JsonProperty("bookingDate") public LocalDate getBookingDate() { return bookingDate; } public void setBookingDate(LocalDate bookingDate) { this.bookingDate = bookingDate; } public Transactions valueDate(LocalDate valueDate) { this.valueDate = valueDate; return this; } /** * The Date at which assets become available to the account owner in case of a credit, or cease to be available to the account owner in case of a debit entry. **Usage:** If entry status is pending and value date is present, then the value date refers to an expected/requested value date. * @return valueDate **/ @ApiModelProperty(value = "The Date at which assets become available to the account owner in case of a credit, or cease to be available to the account owner in case of a debit entry. **Usage:** If entry status is pending and value date is present, then the value date refers to an expected/requested value date.") @Valid @JsonProperty("valueDate") public LocalDate getValueDate() { return valueDate; } public void setValueDate(LocalDate valueDate) { this.valueDate = valueDate; } public Transactions transactionAmount(Amount transactionAmount) { this.transactionAmount = transactionAmount; return this; } /** * Get transactionAmount * @return transactionAmount **/ @ApiModelProperty(required = true, value = "") @NotNull @Valid @JsonProperty("transactionAmount") public Amount getTransactionAmount() { return transactionAmount; } public void setTransactionAmount(Amount transactionAmount) { this.transactionAmount = transactionAmount; } public Transactions currencyExchange(ReportExchangeRateList currencyExchange) { this.currencyExchange = currencyExchange; return this; } /** * Get currencyExchange * @return currencyExchange **/ @ApiModelProperty(value = "") @Valid @JsonProperty("currencyExchange") public ReportExchangeRateList getCurrencyExchange() { return currencyExchange; } public void setCurrencyExchange(ReportExchangeRateList currencyExchange) { this.currencyExchange = currencyExchange; } public Transactions creditorName(String creditorName) { this.creditorName = creditorName; return this; } /** * Get creditorName * @return creditorName **/ @ApiModelProperty(value = "") @Size(max=70) @JsonProperty("creditorName") public String getCreditorName() { return creditorName; } public void setCreditorName(String creditorName) { this.creditorName = creditorName; } public Transactions creditorAccount(AccountReference creditorAccount) { this.creditorAccount = creditorAccount; return this; } /** * Get creditorAccount * @return creditorAccount **/ @ApiModelProperty(value = "") @Valid @JsonProperty("creditorAccount") public AccountReference getCreditorAccount() { return creditorAccount; } public void setCreditorAccount(AccountReference creditorAccount) { this.creditorAccount = creditorAccount; } public Transactions creditorAgent(String creditorAgent) { this.creditorAgent = creditorAgent; return this; } /** * Get creditorAgent * @return creditorAgent **/ @ApiModelProperty(value = "") @Pattern(regexp="[A-Z]{6,6}[A-Z2-9][A-NP-Z0-9]([A-Z0-9]{3,3}){0,1}") @JsonProperty("creditorAgent") public String getCreditorAgent() { return creditorAgent; } public void setCreditorAgent(String creditorAgent) { this.creditorAgent = creditorAgent; } public Transactions ultimateCreditor(String ultimateCreditor) { this.ultimateCreditor = ultimateCreditor; return this; } /** * Get ultimateCreditor * @return ultimateCreditor **/ @ApiModelProperty(value = "") @Size(max=70) @JsonProperty("ultimateCreditor") public String getUltimateCreditor() { return ultimateCreditor; } public void setUltimateCreditor(String ultimateCreditor) { this.ultimateCreditor = ultimateCreditor; } public Transactions debtorName(String debtorName) { this.debtorName = debtorName; return this; } /** * Get debtorName * @return debtorName **/ @ApiModelProperty(value = "") @Size(max=70) @JsonProperty("debtorName") public String getDebtorName() { return debtorName; } public void setDebtorName(String debtorName) { this.debtorName = debtorName; } public Transactions debtorAccount(AccountReference debtorAccount) { this.debtorAccount = debtorAccount; return this; } /** * Get debtorAccount * @return debtorAccount **/ @ApiModelProperty(value = "") @Valid @JsonProperty("debtorAccount") public AccountReference getDebtorAccount() { return debtorAccount; } public void setDebtorAccount(AccountReference debtorAccount) { this.debtorAccount = debtorAccount; } public Transactions debtorAgent(String debtorAgent) { this.debtorAgent = debtorAgent; return this; } /** * Get debtorAgent * @return debtorAgent **/ @ApiModelProperty(value = "") @Pattern(regexp="[A-Z]{6,6}[A-Z2-9][A-NP-Z0-9]([A-Z0-9]{3,3}){0,1}") @JsonProperty("debtorAgent") public String getDebtorAgent() { return debtorAgent; } public void setDebtorAgent(String debtorAgent) { this.debtorAgent = debtorAgent; } public Transactions ultimateDebtor(String ultimateDebtor) { this.ultimateDebtor = ultimateDebtor; return this; } /** * Get ultimateDebtor * @return ultimateDebtor **/ @ApiModelProperty(value = "") @Size(max=70) @JsonProperty("ultimateDebtor") public String getUltimateDebtor() { return ultimateDebtor; } public void setUltimateDebtor(String ultimateDebtor) { this.ultimateDebtor = ultimateDebtor; } public Transactions remittanceInformationUnstructured(String remittanceInformationUnstructured) { this.remittanceInformationUnstructured = remittanceInformationUnstructured; return this; } /** * Get remittanceInformationUnstructured * @return remittanceInformationUnstructured **/ @ApiModelProperty(value = "") @Size(max=140) @JsonProperty("remittanceInformationUnstructured") public String getRemittanceInformationUnstructured() { return remittanceInformationUnstructured; } public void setRemittanceInformationUnstructured(String remittanceInformationUnstructured) { this.remittanceInformationUnstructured = remittanceInformationUnstructured; } public Transactions remittanceInformationUnstructuredArray(RemittanceInformationUnstructuredArray remittanceInformationUnstructuredArray) { this.remittanceInformationUnstructuredArray = remittanceInformationUnstructuredArray; return this; } /** * Get remittanceInformationUnstructuredArray * @return remittanceInformationUnstructuredArray **/ @ApiModelProperty(value = "") @Valid @JsonProperty("remittanceInformationUnstructuredArray") public RemittanceInformationUnstructuredArray getRemittanceInformationUnstructuredArray() { return remittanceInformationUnstructuredArray; } public void setRemittanceInformationUnstructuredArray(RemittanceInformationUnstructuredArray remittanceInformationUnstructuredArray) { this.remittanceInformationUnstructuredArray = remittanceInformationUnstructuredArray; } public Transactions remittanceInformationStructured(String remittanceInformationStructured) { this.remittanceInformationStructured = remittanceInformationStructured; return this; } /** * Get remittanceInformationStructured * @return remittanceInformationStructured **/ @ApiModelProperty(value = "") @Size(max=140) @JsonProperty("remittanceInformationStructured") public String getRemittanceInformationStructured() { return remittanceInformationStructured; } public void setRemittanceInformationStructured(String remittanceInformationStructured) { this.remittanceInformationStructured = remittanceInformationStructured; } public Transactions remittanceInformationStructuredArray(RemittanceInformationStructuredArray remittanceInformationStructuredArray) { this.remittanceInformationStructuredArray = remittanceInformationStructuredArray; return this; } /** * Get remittanceInformationStructuredArray * @return remittanceInformationStructuredArray **/ @ApiModelProperty(value = "") @Valid @JsonProperty("remittanceInformationStructuredArray") public RemittanceInformationStructuredArray getRemittanceInformationStructuredArray() { return remittanceInformationStructuredArray; } public void setRemittanceInformationStructuredArray(RemittanceInformationStructuredArray remittanceInformationStructuredArray) { this.remittanceInformationStructuredArray = remittanceInformationStructuredArray; } public Transactions entryDetails(EntryDetails entryDetails) { this.entryDetails = entryDetails; return this; } /** * Get entryDetails * @return entryDetails **/ @ApiModelProperty(value = "") @Valid @JsonProperty("entryDetails") public EntryDetails getEntryDetails() { return entryDetails; } public void setEntryDetails(EntryDetails entryDetails) { this.entryDetails = entryDetails; } public Transactions additionalInformation(String additionalInformation) { this.additionalInformation = additionalInformation; return this; } /** * Get additionalInformation * @return additionalInformation **/ @ApiModelProperty(value = "") @Size(max=500) @JsonProperty("additionalInformation") public String getAdditionalInformation() { return additionalInformation; } public void setAdditionalInformation(String additionalInformation) { this.additionalInformation = additionalInformation; } public Transactions additionalInformationStructured(AdditionalInformationStructured additionalInformationStructured) { this.additionalInformationStructured = additionalInformationStructured; return this; } /** * Get additionalInformationStructured * @return additionalInformationStructured **/ @ApiModelProperty(value = "") @Valid @JsonProperty("additionalInformationStructured") public AdditionalInformationStructured getAdditionalInformationStructured() { return additionalInformationStructured; } public void setAdditionalInformationStructured(AdditionalInformationStructured additionalInformationStructured) { this.additionalInformationStructured = additionalInformationStructured; } public Transactions purposeCode(PurposeCode purposeCode) { this.purposeCode = purposeCode; return this; } /** * Get purposeCode * @return purposeCode **/ @ApiModelProperty(value = "") @Valid @JsonProperty("purposeCode") public PurposeCode getPurposeCode() { return purposeCode; } public void setPurposeCode(PurposeCode purposeCode) { this.purposeCode = purposeCode; } public Transactions bankTransactionCode(String bankTransactionCode) { this.bankTransactionCode = bankTransactionCode; return this; } /** * Get bankTransactionCode * @return bankTransactionCode **/ @ApiModelProperty(value = "") @JsonProperty("bankTransactionCode") public String getBankTransactionCode() { return bankTransactionCode; } public void setBankTransactionCode(String bankTransactionCode) { this.bankTransactionCode = bankTransactionCode; } public Transactions proprietaryBankTransactionCode(String proprietaryBankTransactionCode) { this.proprietaryBankTransactionCode = proprietaryBankTransactionCode; return this; } /** * Get proprietaryBankTransactionCode * @return proprietaryBankTransactionCode **/ @ApiModelProperty(value = "") @Size(max=35) @JsonProperty("proprietaryBankTransactionCode") public String getProprietaryBankTransactionCode() { return proprietaryBankTransactionCode; } public void setProprietaryBankTransactionCode(String proprietaryBankTransactionCode) { this.proprietaryBankTransactionCode = proprietaryBankTransactionCode; } public Transactions balanceAfterTransaction(Balance balanceAfterTransaction) { this.balanceAfterTransaction = balanceAfterTransaction; return this; } /** * Get balanceAfterTransaction * @return balanceAfterTransaction **/ @ApiModelProperty(value = "") @Valid @JsonProperty("balanceAfterTransaction") public Balance getBalanceAfterTransaction() { return balanceAfterTransaction; } public void setBalanceAfterTransaction(Balance balanceAfterTransaction) { this.balanceAfterTransaction = balanceAfterTransaction; } public Transactions _links(Map _links) { this._links = _links; return this; } /** * Get _links * @return _links **/ @ApiModelProperty(value = "") @Valid @JsonProperty("_links") public Map getLinks() { return _links; } public void setLinks(Map _links) { this._links = _links; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Transactions transactions = (Transactions) o; return Objects.equals(this.transactionId, transactions.transactionId) && Objects.equals(this.entryReference, transactions.entryReference) && Objects.equals(this.endToEndId, transactions.endToEndId) && Objects.equals(this.batchIndicator, transactions.batchIndicator) && Objects.equals(this.batchNumberOfTransactions, transactions.batchNumberOfTransactions) && Objects.equals(this.mandateId, transactions.mandateId) && Objects.equals(this.checkId, transactions.checkId) && Objects.equals(this.creditorId, transactions.creditorId) && Objects.equals(this.bookingDate, transactions.bookingDate) && Objects.equals(this.valueDate, transactions.valueDate) && Objects.equals(this.transactionAmount, transactions.transactionAmount) && Objects.equals(this.currencyExchange, transactions.currencyExchange) && Objects.equals(this.creditorName, transactions.creditorName) && Objects.equals(this.creditorAccount, transactions.creditorAccount) && Objects.equals(this.creditorAgent, transactions.creditorAgent) && Objects.equals(this.ultimateCreditor, transactions.ultimateCreditor) && Objects.equals(this.debtorName, transactions.debtorName) && Objects.equals(this.debtorAccount, transactions.debtorAccount) && Objects.equals(this.debtorAgent, transactions.debtorAgent) && Objects.equals(this.ultimateDebtor, transactions.ultimateDebtor) && Objects.equals(this.remittanceInformationUnstructured, transactions.remittanceInformationUnstructured) && Objects.equals(this.remittanceInformationUnstructuredArray, transactions.remittanceInformationUnstructuredArray) && Objects.equals(this.remittanceInformationStructured, transactions.remittanceInformationStructured) && Objects.equals(this.remittanceInformationStructuredArray, transactions.remittanceInformationStructuredArray) && Objects.equals(this.entryDetails, transactions.entryDetails) && Objects.equals(this.additionalInformation, transactions.additionalInformation) && Objects.equals(this.additionalInformationStructured, transactions.additionalInformationStructured) && Objects.equals(this.purposeCode, transactions.purposeCode) && Objects.equals(this.bankTransactionCode, transactions.bankTransactionCode) && Objects.equals(this.proprietaryBankTransactionCode, transactions.proprietaryBankTransactionCode) && Objects.equals(this.balanceAfterTransaction, transactions.balanceAfterTransaction) && Objects.equals(this._links, transactions._links); } @Override public int hashCode() { return Objects.hash(transactionId, entryReference, endToEndId, batchIndicator, batchNumberOfTransactions, mandateId, checkId, creditorId, bookingDate, valueDate, transactionAmount, currencyExchange, creditorName, creditorAccount, creditorAgent, ultimateCreditor, debtorName, debtorAccount, debtorAgent, ultimateDebtor, remittanceInformationUnstructured, remittanceInformationUnstructuredArray, remittanceInformationStructured, remittanceInformationStructuredArray, entryDetails, additionalInformation, additionalInformationStructured, purposeCode, bankTransactionCode, proprietaryBankTransactionCode, balanceAfterTransaction, _links); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Transactions {\n"); sb.append(" transactionId: ").append(toIndentedString(transactionId)).append("\n"); sb.append(" entryReference: ").append(toIndentedString(entryReference)).append("\n"); sb.append(" endToEndId: ").append(toIndentedString(endToEndId)).append("\n"); sb.append(" batchIndicator: ").append(toIndentedString(batchIndicator)).append("\n"); sb.append(" batchNumberOfTransactions: ").append(toIndentedString(batchNumberOfTransactions)).append("\n"); sb.append(" mandateId: ").append(toIndentedString(mandateId)).append("\n"); sb.append(" checkId: ").append(toIndentedString(checkId)).append("\n"); sb.append(" creditorId: ").append(toIndentedString(creditorId)).append("\n"); sb.append(" bookingDate: ").append(toIndentedString(bookingDate)).append("\n"); sb.append(" valueDate: ").append(toIndentedString(valueDate)).append("\n"); sb.append(" transactionAmount: ").append(toIndentedString(transactionAmount)).append("\n"); sb.append(" currencyExchange: ").append(toIndentedString(currencyExchange)).append("\n"); sb.append(" creditorName: ").append(toIndentedString(creditorName)).append("\n"); sb.append(" creditorAccount: ").append(toIndentedString(creditorAccount)).append("\n"); sb.append(" creditorAgent: ").append(toIndentedString(creditorAgent)).append("\n"); sb.append(" ultimateCreditor: ").append(toIndentedString(ultimateCreditor)).append("\n"); sb.append(" debtorName: ").append(toIndentedString(debtorName)).append("\n"); sb.append(" debtorAccount: ").append(toIndentedString(debtorAccount)).append("\n"); sb.append(" debtorAgent: ").append(toIndentedString(debtorAgent)).append("\n"); sb.append(" ultimateDebtor: ").append(toIndentedString(ultimateDebtor)).append("\n"); sb.append(" remittanceInformationUnstructured: ").append(toIndentedString(remittanceInformationUnstructured)).append("\n"); sb.append(" remittanceInformationUnstructuredArray: ").append(toIndentedString(remittanceInformationUnstructuredArray)).append("\n"); sb.append(" remittanceInformationStructured: ").append(toIndentedString(remittanceInformationStructured)).append("\n"); sb.append(" remittanceInformationStructuredArray: ").append(toIndentedString(remittanceInformationStructuredArray)).append("\n"); sb.append(" entryDetails: ").append(toIndentedString(entryDetails)).append("\n"); sb.append(" additionalInformation: ").append(toIndentedString(additionalInformation)).append("\n"); sb.append(" additionalInformationStructured: ").append(toIndentedString(additionalInformationStructured)).append("\n"); sb.append(" purposeCode: ").append(toIndentedString(purposeCode)).append("\n"); sb.append(" bankTransactionCode: ").append(toIndentedString(bankTransactionCode)).append("\n"); sb.append(" proprietaryBankTransactionCode: ").append(toIndentedString(proprietaryBankTransactionCode)).append("\n"); sb.append(" balanceAfterTransaction: ").append(toIndentedString(balanceAfterTransaction)).append("\n"); sb.append(" _links: ").append(toIndentedString(_links)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
29.381663
638
0.748839
fbe5159634c4794a85b49742fbc5eda2cd2bc8f3
233
java
Java
app/src/main/java/io/github/xiaolei/transaction/event/AppInitCompletedEvent.java
xiaolei/Transaction
e87d7dbdd46b1cda4007ebd1d45e3b499c241a68
[ "Apache-2.0" ]
null
null
null
app/src/main/java/io/github/xiaolei/transaction/event/AppInitCompletedEvent.java
xiaolei/Transaction
e87d7dbdd46b1cda4007ebd1d45e3b499c241a68
[ "Apache-2.0" ]
null
null
null
app/src/main/java/io/github/xiaolei/transaction/event/AppInitCompletedEvent.java
xiaolei/Transaction
e87d7dbdd46b1cda4007ebd1d45e3b499c241a68
[ "Apache-2.0" ]
null
null
null
package io.github.xiaolei.transaction.event; /** * TODO: add comment */ public class AppInitCompletedEvent { public boolean success; public AppInitCompletedEvent(boolean success) { this.success = success; } }
17.923077
51
0.699571
da121dfc37a1bb151a9c315398967d9590ca5fc7
690
swift
Swift
Code/Bubbles/Bubbles Demo/ViewController.swift
nicolas-miari/Bubbles
5bb3da3822f2cc9b96910e3443c306d172b45ecc
[ "MIT" ]
null
null
null
Code/Bubbles/Bubbles Demo/ViewController.swift
nicolas-miari/Bubbles
5bb3da3822f2cc9b96910e3443c306d172b45ecc
[ "MIT" ]
null
null
null
Code/Bubbles/Bubbles Demo/ViewController.swift
nicolas-miari/Bubbles
5bb3da3822f2cc9b96910e3443c306d172b45ecc
[ "MIT" ]
null
null
null
// // ViewController.swift // Bubbles Demo // // Created by Nicolás Miari on 2019/06/13. // Copyright © 2019 Nicolás Miari. All rights reserved. // import UIKit import Bubbles class ViewController: UIViewController { var counter: Int = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func launchNewBubble(_ sender: Any) { let now = Date() let bubble = Bubble(title: "\(counter) - \(now) - AAAAAAAAAAAAAAAA") do { try bubble.show() counter += 1 } catch { print(error.localizedDescription) } } }
19.166667
76
0.586957
280c9dd6068e52215019aebe2c2e8ec5d4f52e72
104
rb
Ruby
test/test_helper.rb
mustafaturan/hashable
ad95acbe326a9da815f0a2cb964aa029b61828e0
[ "MIT" ]
3
2015-10-05T15:04:27.000Z
2020-02-01T05:09:43.000Z
test/test_helper.rb
mustafaturan/hashable
ad95acbe326a9da815f0a2cb964aa029b61828e0
[ "MIT" ]
null
null
null
test/test_helper.rb
mustafaturan/hashable
ad95acbe326a9da815f0a2cb964aa029b61828e0
[ "MIT" ]
1
2020-09-05T21:09:10.000Z
2020-09-05T21:09:10.000Z
require 'test/unit' require File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib', 'hashable'))
52
84
0.721154
803aec320ed2ce507734adcfbcfacd4cf9ff9d9a
3,678
java
Java
querydsl-mongodb/src/main/java/com/querydsl/mongodb/morphia/MorphiaSerializer.java
coder-hugo/querydsl
2bf234caf78549813a1e0f44d9c30ecc5ef734e3
[ "Apache-2.0" ]
3,579
2015-01-01T18:13:48.000Z
2022-03-31T18:28:45.000Z
querydsl-mongodb/src/main/java/com/querydsl/mongodb/morphia/MorphiaSerializer.java
Camork/querydsl
7ca3d9b24ee7d81af1e90c49223652b874d92102
[ "Apache-2.0" ]
1,828
2015-01-04T10:52:58.000Z
2022-03-31T14:45:10.000Z
querydsl-mongodb/src/main/java/com/querydsl/mongodb/morphia/MorphiaSerializer.java
Camork/querydsl
7ca3d9b24ee7d81af1e90c49223652b874d92102
[ "Apache-2.0" ]
867
2015-01-07T21:46:24.000Z
2022-03-29T12:56:31.000Z
/* * Copyright 2015, The Querydsl Team (http://www.querydsl.com/team) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.querydsl.mongodb.morphia; import java.lang.reflect.AnnotatedElement; import org.mongodb.morphia.Key; import org.mongodb.morphia.Morphia; import org.mongodb.morphia.annotations.Id; import org.mongodb.morphia.annotations.Property; import org.mongodb.morphia.annotations.Reference; import org.mongodb.morphia.mapping.Mapper; import com.mongodb.DBRef; import com.querydsl.core.types.Constant; import com.querydsl.core.types.Path; import com.querydsl.core.types.PathMetadata; import com.querydsl.mongodb.MongodbSerializer; /** * {@code MorphiaSerializer} extends {@link MongodbSerializer} with Morphia specific annotation handling * * @author tiwe * */ public class MorphiaSerializer extends MongodbSerializer { private final Morphia morphia; public MorphiaSerializer(Morphia morphia) { this.morphia = morphia; } @Override public Object visit(Constant<?> expr, Void context) { Object value = super.visit(expr, context); return morphia.getMapper().toMongoObject(null, null, value); } @Override protected String getKeyForPath(Path<?> expr, PathMetadata metadata) { AnnotatedElement annotations = expr.getAnnotatedElement(); if (annotations.isAnnotationPresent(Id.class)) { Path<?> parent = expr.getMetadata().getParent(); if (parent.getAnnotatedElement().isAnnotationPresent(Reference.class)) { return null; // go to parent } else { return "_id"; } } else if (annotations.isAnnotationPresent(Property.class)) { Property property = annotations.getAnnotation(Property.class); if (!property.value().equals(Mapper.IGNORED_FIELDNAME)) { return property.value(); } } else if (annotations.isAnnotationPresent(Reference.class)) { Reference reference = annotations.getAnnotation(Reference.class); if (!reference.value().equals(Mapper.IGNORED_FIELDNAME)) { return reference.value(); } } return super.getKeyForPath(expr, metadata); } @Override protected boolean isReference(Path<?> arg) { return arg.getAnnotatedElement().isAnnotationPresent(Reference.class); } @Override protected boolean isImplicitObjectIdConversion() { // see https://github.com/mongodb/morphia/wiki/FrequentlyAskedQuestions return false; } @Override protected boolean isId(Path<?> arg) { return arg.getAnnotatedElement().isAnnotationPresent(Id.class); } @Override protected DBRef asReference(Object constant) { Key<?> key = morphia.getMapper().getKey(constant); return morphia.getMapper().keyToDBRef(key); } @Override protected DBRef asReferenceKey(Class<?> entity, Object id) { String collection = morphia.getMapper().getCollectionName(entity); Key<?> key = new Key<Object>(entity, collection, id); return morphia.getMapper().keyToDBRef(key); } }
35.365385
104
0.688961
d70223884a61bf1d93bcd0498a64926554eee7f7
1,045
lua
Lua
files_David/ChengPhoto.lua
DavidTeam0/files_David
3e8d151f2ce0548e494a6e6e3c60ee0ac70fc80f
[ "MIT" ]
null
null
null
files_David/ChengPhoto.lua
DavidTeam0/files_David
3e8d151f2ce0548e494a6e6e3c60ee0ac70fc80f
[ "MIT" ]
null
null
null
files_David/ChengPhoto.lua
DavidTeam0/files_David
3e8d151f2ce0548e494a6e6e3c60ee0ac70fc80f
[ "MIT" ]
null
null
null
local function ChengPhoto(msg) local text = msg.content_.text_ if text then tdcli_function({ID = "GetUser",user_id_ = msg.sender_user_id_},function(arg,data) if data.id_ then if data.id_ ~= bot_id then local DavidChengPhoto = database:get(bot_id.."David:Cheng:Photo"..data.id_) if not data.profile_photo_ then if DavidChengPhoto then send(msg.chat_id_, msg.id_, "حذف كل صوره الحلو 😂👌🏻") database:del(bot_id.."David:Cheng:Photo"..data.id_) end end if data.profile_photo_.big_.persistent_id_ then if DavidChengPhoto ~= data.profile_photo_.big_.persistent_id_ then local Text = { "شكو غيرت صورتك يا حلو ", "منور طالع حلو عل صوره جديده", "ها شو غيرت صورتك 🤔😹", "شكو غيرت صورتك شنو قطيت وحده جديده 😹😹🌚", "شو غيرت صورتك شنو تعاركت ويه الحب ؟😹🌞", "شكو غيرت الصوره شسالفه ؟؟ 🤔🌞", } send(msg.chat_id_, msg.id_,Text[math.random(#Text)]) end database:set(bot_id.."David:Cheng:Photo"..data.id_, data.profile_photo_.big_.persistent_id_) end end end end,nil) end end return {David = ChengPhoto}
29.027778
94
0.705263
0bd9725daf811691a344c2d8c30529feed58f6a1
5,041
js
JavaScript
app/index.js
codebusters/generator-reqtangular
a374d4c1388d4994aa3791672cc9224f7cdfc94c
[ "Apache-2.0" ]
1
2015-05-18T11:45:16.000Z
2015-05-18T11:45:16.000Z
app/index.js
codebusters/generator-reqtangular
a374d4c1388d4994aa3791672cc9224f7cdfc94c
[ "Apache-2.0" ]
6
2015-02-12T18:01:30.000Z
2015-03-12T17:10:14.000Z
app/index.js
codebusters/generator-reqtangular
a374d4c1388d4994aa3791672cc9224f7cdfc94c
[ "Apache-2.0" ]
null
null
null
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var yosay = require('yosay'); var chalk = require('chalk'); var context = {}; var config = { askForSEO : false }; var NgRequireGenerator = yeoman.generators.Base.extend({ init: function() { this.pkg = require('../package.json'); this.less = false; this.on('end', function() { this.installDependencies({ bower: true, npm: true, skipInstall: this.options['skip-install'], skipMessage: this.options['skip-install'], callback: function() { console.log(chalk.yellow('┌────────────────────────────────────────────────────────────────┐')); console.log(chalk.yellow('│ ' + chalk.white('Everything is ready!, just run: ') + chalk.blue(' grunt serve')) + chalk.yellow(' │')); console.log(chalk.yellow('│ ' + chalk.white('or build distribution version with: ') + chalk.blue(' grunt dist')) + chalk.yellow(' │')); console.log(chalk.yellow('│ ' + chalk.white('wiki') + chalk.blue(' https://github.com/codebusters/generator-reqtangular/wiki')) + chalk.yellow(' │')); console.log(chalk.yellow('└────────────────────────────────────────────────────────────────┘')); } }); }); }, askFor: function() { var done = this.async(); if (!this.options['skip-welcome-message']) { this.log(yosay('Welcome to the marvelous Reqtangular generator!')); //codeBusters brand. console.log(' ' + chalk.bold.yellow('reqtangular') + ' v' + this.pkg.version + '\t\t' + chalk.bold.white('code') + chalk.bold.red('Busters') + chalk.bold.white(' S.L.') + '\n\n'); } var prompts = [{ type: 'input', name: 'appName', message: 'How would you like to name your application?', default: 'reqtangular' }]; this.prompt(prompts, function(props) { this.appName = props.appName; //Remove all special chars this.appNamePackage = this.appName.replace(/[^\w\s]/gi, ''); //Remove white spaces this.appNamePackage = this.appNamePackage.replace(/\s+/g, ''); this.reqtangularName = this.pkg.name; this.reqtangularVersion = this.pkg.version; done(); }.bind(this)); }, askForSEO: function() { context.indexTitle = ''; context.indexDescription = ''; if (config.askForSEO) { var done = this.async(); this.prompt([{ type: 'confirm', name: 'seo', message: 'Would you like to configure basic SEO data?', default: true }], function(props) { if (props.seo) { var questions = [ { type: "input", name: "indexTitle", message: "Enter index title" }, { type: "input", name: "indexDescription", message: "Enter index description" } ]; this.prompt(questions, function(answers) { context.indexTitle = answers.indexTitle; context.indexDescription = answers.indexDescription; done(); }); } else { done(); } }.bind(this)); } }, app: function() { context.appConfig = { app: 'app', dist: 'dist' }; context.connect = { options: { livereload: '<%= connect.options.livereload %>' } }; context.less = this.less || false; context.appName = this.appName; this.copy('_package.json', 'package.json'); this.copy('_bower.json', 'bower.json'); this.copy('_bowerrc', 'bowerrc'); this.copy('editorconfig', '.editorconfig'); this.copy('jshintrc', '.jshintrc'); this.template('_gruntfile.js', 'Gruntfile.js', context); this.copy('_karma.conf.js', 'karma.conf.js'); this.copy('_karma-e2e.conf.js', 'karma-e2e.conf.js'); }, scaffoldFolders: function() { this.mkdir('app'); // TODO add assert for inner files in test this.directory('_app/_config', 'app/config'); // TODO add assert for inner files in test this.mkdir('app/styles'); // TODO add assert for inner files in test this.directory('_app/_images', 'app/images'); // TODO add assert for inner files in test this.directory('_app/_scripts', 'app/scripts'); this.mkdir('test'); }, appFiles: function() { // TODO for now only copying this.copy('_app/_404.html', 'app/404.html'); this.copy('_app/_favicon.ico', 'app/favicon.ico'); this.copy('_app/htaccess', 'app/.htaccess'); this.copy('_app/_robots.txt', 'app/robots.txt'); this.template('_app/_index.template.html', 'app/index.template.html', context); } , applyDefaultTheme: function() { // TODO add tests this.invoke('reqtangular:theme', { options: { theme: 'codeBusters', 'skip-welcome-message' : true } }); } }); module.exports = NgRequireGenerator;
30.737805
160
0.55247
3618537488909f0e10067cef41f12dde95cfff56
137
lua
Lua
GFM/lua/autorun/gfm_init.lua
ChargedCreeper/GMod-Freedom-Mod
afcdf8876042781b2d6402f711c8399955002005
[ "MIT" ]
null
null
null
GFM/lua/autorun/gfm_init.lua
ChargedCreeper/GMod-Freedom-Mod
afcdf8876042781b2d6402f711c8399955002005
[ "MIT" ]
null
null
null
GFM/lua/autorun/gfm_init.lua
ChargedCreeper/GMod-Freedom-Mod
afcdf8876042781b2d6402f711c8399955002005
[ "MIT" ]
null
null
null
-- TODO: Start GFM function GM:PlayerConnect( name, ip ) PrintMessage( HUD_PRINTTALK, "[GFM] " .. name .. " has joined the game." ) end
27.4
75
0.671533
9c7cec9d40f20b6b1cc2747983b88e1b827088f0
723
js
JavaScript
src/components/LikedPhotos.js
shergillmanav19/Space-Explorer
4ae148ed1a1db06477fb9a4ba5975ccb2b60fcc2
[ "BSD-Source-Code" ]
null
null
null
src/components/LikedPhotos.js
shergillmanav19/Space-Explorer
4ae148ed1a1db06477fb9a4ba5975ccb2b60fcc2
[ "BSD-Source-Code" ]
null
null
null
src/components/LikedPhotos.js
shergillmanav19/Space-Explorer
4ae148ed1a1db06477fb9a4ba5975ccb2b60fcc2
[ "BSD-Source-Code" ]
null
null
null
import { Box, Button } from "@chakra-ui/react"; import React from "react"; import { useLikedPhotos } from "../hooks/useLikedPhotos"; import Photos from "./Photos"; function LikedPhotos() { const { likedPhotos, unlikeAll, like, unlike, contains } = useLikedPhotos(); return ( <div> <Box w="100%" display="flex" justifyContent="center" marginTop="15px"> <Button bg="#BDD5EA" _hover={{ bg: "red.400", color: "white" }} onClick={unlikeAll} > Unlike all </Button> </Box> <Photos photos={likedPhotos} like={like} unlike={unlike} contains={contains} /> </div> ); } export default LikedPhotos;
23.322581
78
0.568465
2a5cef167fe8eea7478db4d25d9418add8aabf9e
126
java
Java
declarative-transaction-propagation/src/main/java/geektime/spring/declarative/transaction/propagation/exception/RollbackException.java
monsterhxw/Spring-Learning-Practice
1a4e549a83339957bab62ac81cd11dec5ae27316
[ "MIT" ]
null
null
null
declarative-transaction-propagation/src/main/java/geektime/spring/declarative/transaction/propagation/exception/RollbackException.java
monsterhxw/Spring-Learning-Practice
1a4e549a83339957bab62ac81cd11dec5ae27316
[ "MIT" ]
null
null
null
declarative-transaction-propagation/src/main/java/geektime/spring/declarative/transaction/propagation/exception/RollbackException.java
monsterhxw/Spring-Learning-Practice
1a4e549a83339957bab62ac81cd11dec5ae27316
[ "MIT" ]
null
null
null
package geektime.spring.declarative.transaction.propagation.exception; public class RollbackException extends Exception { }
21
70
0.849206
fbaebfdb6e46dd98d02ef9529440ccc79e4ab8c7
1,021
java
Java
src/test/java/com/github/qky666/selenidepom/test/java/mtp/pom/constructorpom/ServicesRequiredErrorPage.java
qky666/selenide-pom
0b6716789641747a9bd1d6d337ffd8b923a05285
[ "MIT" ]
null
null
null
src/test/java/com/github/qky666/selenidepom/test/java/mtp/pom/constructorpom/ServicesRequiredErrorPage.java
qky666/selenide-pom
0b6716789641747a9bd1d6d337ffd8b923a05285
[ "MIT" ]
null
null
null
src/test/java/com/github/qky666/selenidepom/test/java/mtp/pom/constructorpom/ServicesRequiredErrorPage.java
qky666/selenide-pom
0b6716789641747a9bd1d6d337ffd8b923a05285
[ "MIT" ]
null
null
null
package com.github.qky666.selenidepom.test.java.mtp.pom.constructorpom; import com.codeborne.selenide.SelenideElement; import com.github.qky666.selenidepom.Required; import com.github.qky666.selenidepom.RequiredError; import java.time.Duration; import static com.codeborne.selenide.Condition.text; import static com.codeborne.selenide.Selenide.$; public class ServicesRequiredErrorPage extends MainFramePage { @Required public final SelenideElement principal = $("div.servicios-principal"); @Required public final SelenideElement title = $("h1.h2"); // badSelector generates an error in shouldLoadRequired @Required public final SelenideElement badSelector = $("bad-selector"); @Required public final SelenideElement otherBadSelector = $("other-bad-selector"); @Override public void shouldLoadRequired(Duration timeout, String pomVersion) throws RequiredError { super.shouldLoadRequired(timeout, pomVersion); title.shouldHave(text("Aseguramiento de la calidad")); } }
40.84
94
0.778648
2f18e3dafd756370c1f306d533793be38425684a
1,982
java
Java
src/test/java/de/kosit/validationtool/impl/xml/RemoteResolvingStrategyTest.java
marvindoering/validator
aef5a50cf8d0ca32d1d3ff80c05e3807e2943e59
[ "Apache-2.0" ]
39
2018-03-28T10:15:31.000Z
2022-03-18T11:18:17.000Z
src/test/java/de/kosit/validationtool/impl/xml/RemoteResolvingStrategyTest.java
marvindoering/validator
aef5a50cf8d0ca32d1d3ff80c05e3807e2943e59
[ "Apache-2.0" ]
77
2018-03-19T07:54:28.000Z
2022-03-03T21:43:21.000Z
src/test/java/de/kosit/validationtool/impl/xml/RemoteResolvingStrategyTest.java
marvindoering/validator
aef5a50cf8d0ca32d1d3ff80c05e3807e2943e59
[ "Apache-2.0" ]
24
2018-03-15T12:01:40.000Z
2022-01-20T09:40:43.000Z
/* * Copyright 2017-2021 Koordinierungsstelle für IT-Standards (KoSIT) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.kosit.validationtool.impl.xml; import static org.assertj.core.api.Assertions.assertThat; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import de.kosit.validationtool.api.ResolvingConfigurationStrategy; import de.kosit.validationtool.impl.Helper.Resolving; /** * Tests {@link RemoteResolvingStrategy}. * * @author Andreas Penski */ public class RemoteResolvingStrategyTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testRemoteSchemaResolving() throws Exception { final ResolvingConfigurationStrategy s = new RemoteResolvingStrategy(); final SchemaFactory schemaFactory = s.createSchemaFactory(); final Schema schema = schemaFactory.newSchema(Resolving.SCHEMA_WITH_REMOTE_REFERENCE.toURL()); assertThat(schema).isNotNull(); } @Test public void testLocalSchemaResolving() throws Exception { final ResolvingConfigurationStrategy s = new StrictLocalResolvingStrategy(); final SchemaFactory schemaFactory = s.createSchemaFactory(); final Schema schema = schemaFactory.newSchema(Resolving.SCHEMA_WITH_REFERENCE.toURL()); assertThat(schema).isNotNull(); } }
34.172414
102
0.755802
d00820a3b3dae862fc0d3211fb101705749797a0
391
dart
Dart
lib/src/services/raw_keyboard_web_ex.dart
flutter-dd/ui_ex
932526f13a6fc1f17c24b64581a03a176a13c9c0
[ "MIT" ]
1
2021-11-18T06:49:07.000Z
2021-11-18T06:49:07.000Z
lib/src/services/raw_keyboard_web_ex.dart
flutter-dd/ui_ex
932526f13a6fc1f17c24b64581a03a176a13c9c0
[ "MIT" ]
null
null
null
lib/src/services/raw_keyboard_web_ex.dart
flutter-dd/ui_ex
932526f13a6fc1f17c24b64581a03a176a13c9c0
[ "MIT" ]
null
null
null
part of ui_ex; /// 服务原始键盘网络 /// RawKeyboardWeb extension ServicesRawKeyboardWebEx<T extends int?> on T { /// RawKeyEventDataWeb RawKeyEventDataWeb rawKeyEventDataWeb({ required String code, required String key, int location = 0, }) => RawKeyEventDataWeb( code: code, key: key, location: location = 0, metaState: this ?? 0, ); }
20.578947
57
0.624041
4227580b096aca5e91503527cdeec37484e7afdf
120
sql
SQL
src/test/resources/sql/select/9b5b0fbe.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
66
2018-06-15T11:34:03.000Z
2022-03-16T09:24:49.000Z
src/test/resources/sql/select/9b5b0fbe.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
13
2019-03-19T11:56:28.000Z
2020-08-05T04:20:50.000Z
src/test/resources/sql/select/9b5b0fbe.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
28
2019-01-05T19:59:02.000Z
2022-03-24T11:55:50.000Z
-- file:box.sql ln:87 expect:true SELECT '' AS four, b.f1 FROM BOX_TBL b WHERE b.f1 >= box '(3.5,3.0,4.5,3.0)'
30
61
0.583333
460f6d6404f5a72e6220089c2673a0563bc12363
1,276
dart
Dart
test/mocks/space_media_mock.dart
Cleber4/app_nasa
7e75eef0bf9641d9d19add6b55e431eef360d676
[ "MIT" ]
null
null
null
test/mocks/space_media_mock.dart
Cleber4/app_nasa
7e75eef0bf9641d9d19add6b55e431eef360d676
[ "MIT" ]
null
null
null
test/mocks/space_media_mock.dart
Cleber4/app_nasa
7e75eef0bf9641d9d19add6b55e431eef360d676
[ "MIT" ]
null
null
null
const spaceMediaMock = """ { "copyright": "Tomas SlovinskySlovakiaPetr HoralekCzech RepublicInstitute of Physics in Opava", "date": "2021-08-09", "explanation": "What's the best way to watch a meteor shower? This question might come up later this week when the annual Perseid Meteor Shower peaks. One thing that is helpful is a dark sky, as demonstrated in the featured composite image of last year's Perseids. Many more faint meteors are visible on the left image, taken through a very dark sky in Slovakia, than on the right image, taken through a moderately dark sky in the Czech Republic. The band of the Milky Way Galaxy bridges the two coordinated images, while the meteor shower radiant in the constellation of Perseus is clearly visible on the left. In sum, many faint meteors are lost through a bright sky. Light pollution is shrinking areas across our Earth with dark skies, although inexpensive ways to combat this might be implemented. Notable Perseids Submissions to APOD: 2018, 2019, 2020", "hdurl": "https://apod.nasa.gov/apod/image/2108/PerseidsLost_SlovinskyHoralek_2048.jpg", "media_type": "image", "service_version": "v1", "title": "Perseus and the Lost Meteors", "url": "https://apod.nasa.gov/apod/image/2108/PerseidsLost_SlovinskyHoralek_1080.jpg" } """;
98.153846
858
0.784483
545d35352a8e398f3621fbc4616e224c5594552a
1,161
go
Go
main.go
bizzaro-jhunt/go-tilesetter
81d5d68c8730a1637ed99168289c20e68f62494d
[ "MIT" ]
1
2020-01-25T14:53:41.000Z
2020-01-25T14:53:41.000Z
main.go
jhunt/go-tilesetter
81d5d68c8730a1637ed99168289c20e68f62494d
[ "MIT" ]
3
2016-10-27T14:42:49.000Z
2016-11-01T18:47:37.000Z
main.go
bizzaro-jhunt/go-tilesetter
81d5d68c8730a1637ed99168289c20e68f62494d
[ "MIT" ]
1
2016-11-01T17:34:09.000Z
2016-11-01T17:34:09.000Z
package main import ( "fmt" "log" "os" "gopkg.in/yaml.v2" "github.com/jhunt/go-tilesetter/tile" "github.com/jhunt/go-tilesetter/web" ) func main() { if len(os.Args) < 3 { fmt.Fprintf(os.Stderr, "USAGE: %s COMMAND [arguments...]\n", os.Args[0]) os.Exit(1) } switch os.Args[1] { case "inspect": inspect() case "api": api() default: fmt.Fprintf(os.Stderr, "Unrecognized sub-command '%s'\n", os.Args[1]) os.Exit(1) } } func inspect() { if len(os.Args) != 3 { fmt.Fprintf(os.Stderr, "USAGE: %s inspect /path/to/tile.pivotal\n", os.Args[0]) os.Exit(1) } fmt.Printf("# %s\n", os.Args[2]) t, err := tile.Unpack(os.Args[2]) if err != nil { log.Fatal(err) } s, err := yaml.Marshal(t) if err != nil { log.Fatal(err) } fmt.Printf("%s", s) return } func api() { if len(os.Args) < 3 || len(os.Args) > 4 { fmt.Fprintf(os.Stderr, "USAGE: %s api /path/to/ui/assets [host:port]\n", os.Args[0]) os.Exit(1) } bind := ":5001" if len(os.Args) == 4 { bind = os.Args[3] } fmt.Printf("starting up tilesetter web ui on %s\n", bind) fmt.Printf("(sourcing assets from %s)\n", os.Args[2]) web.Listen(os.Args[2], bind) }
17.328358
86
0.597761
fbb72690ee73df413138553a5bbf8c09b3f2359d
1,869
java
Java
TelecursoXandao/app/src/main/java/com/xandecompany/telecursoxandao/MainActivity.java
xandelol/telecursoAndroid
44debcda7dbfd7a131d264147715916ec969c90a
[ "MIT" ]
null
null
null
TelecursoXandao/app/src/main/java/com/xandecompany/telecursoxandao/MainActivity.java
xandelol/telecursoAndroid
44debcda7dbfd7a131d264147715916ec969c90a
[ "MIT" ]
null
null
null
TelecursoXandao/app/src/main/java/com/xandecompany/telecursoxandao/MainActivity.java
xandelol/telecursoAndroid
44debcda7dbfd7a131d264147715916ec969c90a
[ "MIT" ]
null
null
null
package com.xandecompany.telecursoxandao; /** * Created by Alexandre on 10.01.2017. */ import android .app . Activity ; import android .os. Bundle ; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android . widget . TextView ; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); ArrayList<Movie> movies = new ArrayList<>(); movies.add(new Movie("Movie 1",5,2016)); movies.add(new Movie("Movie 2",8,2010)); movies.add(new Movie("Movie 3",6,2008)); movies.add(new Movie("Movie 4",9,2004)); movies.add(new Movie("Movie 5",10,2001)); movies.add(new Movie("Movie 6",3,2011)); movies.add(new Movie("Movie 7",2,2009)); movies.add(new Movie("Movie 8",9,2001)); movies.add(new Movie("Movie 9",4,2003)); movies.add(new Movie("Movie 10",8,2002)); //MovieAdapter adapter = new MovieAdapter(this, R.layout.list_view_item_movie, movies); RecyclerView listView = (RecyclerView) findViewById(R.id.movies); Bundle extras = getIntent().getExtras(); String user = extras.getString("user"); String pass = extras.getString("pass"); TextView userTextView = (TextView) findViewById(R.id.user); userTextView.setText(getString(R.string.user_name, user)); listView.setAdapter(new MovieAdapter(movies,this)); RecyclerView.LayoutManager layout = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false); listView.setLayoutManager(layout); } }
35.264151
109
0.687533
28867875cd77f1f71b9d328c33d807054bfdb54e
1,959
dart
Dart
lib/src/ui/common/common_wrong_answer_animation_view.dart
mehulmk/math-metrix
6928cbaf4650826820d1ca7960213fdf5c4ce50c
[ "MIT" ]
1
2020-07-14T00:31:11.000Z
2020-07-14T00:31:11.000Z
lib/src/ui/common/common_wrong_answer_animation_view.dart
gunjanmodi/math-metrix
6928cbaf4650826820d1ca7960213fdf5c4ce50c
[ "MIT" ]
null
null
null
lib/src/ui/common/common_wrong_answer_animation_view.dart
gunjanmodi/math-metrix
6928cbaf4650826820d1ca7960213fdf5c4ce50c
[ "MIT" ]
null
null
null
import 'dart:math'; import 'package:flutter/material.dart'; class SineCurve extends Curve { final double count; SineCurve({this.count = 3}); @override double transformInternal(double t) { var val = sin(count * 2 * pi * t) * 0.5 + 0.5; return val; } } class CommonWrongAnswerAnimationView extends StatefulWidget { final int currentScore; final int oldScore; final Widget child; const CommonWrongAnswerAnimationView({ Key? key, required this.currentScore, required this.oldScore, required this.child, }) : super(key: key); @override State<CommonWrongAnswerAnimationView> createState() => _CommonWrongAnswerAnimationViewState(); } class _CommonWrongAnswerAnimationViewState extends State<CommonWrongAnswerAnimationView> with TickerProviderStateMixin { late AnimationController _controller; late final Animation<double> _opacityAnimationOut; @override void initState() { super.initState(); _controller = AnimationController( duration: const Duration(milliseconds: 500), vsync: this, ); _opacityAnimationOut = Tween( begin: 0.0, end: 1.0, ).animate(CurvedAnimation( parent: _controller, curve: SineCurve(count: 3), )); } @override void didUpdateWidget(CommonWrongAnswerAnimationView oldWidget) { if (oldWidget.currentScore != widget.currentScore) { if (widget.oldScore > widget.currentScore) { _controller.forward(from: 0.0); } } super.didUpdateWidget(oldWidget); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: _opacityAnimationOut, builder: (context, child) { return Transform.translate( offset: Offset(_opacityAnimationOut.value * 4, 0), child: child, ); }, child: widget.child, ); } @override void dispose() { _controller.dispose(); super.dispose(); } }
22.77907
66
0.674324
2a59cb36a780087b0f3126478cb2dca2d150d58f
2,832
java
Java
libraries/gffs-basics/trunk/src/org/morgan/util/io/StreamUtils.java
genesis-2/trunk
9a6b34e8531ef0a1614ee48802b037df6e4fa2d7
[ "Apache-2.0" ]
1
2022-03-16T16:36:00.000Z
2022-03-16T16:36:00.000Z
libraries/gffs-basics/trunk/src/org/morgan/util/io/StreamUtils.java
lancium/GenesisII-public
b8fbdf2881fa125a73ff7d5799bf33e1b5076d6e
[ "Apache-2.0" ]
1
2021-06-04T02:05:42.000Z
2021-06-04T02:05:42.000Z
libraries/gffs-basics/trunk/src/org/morgan/util/io/StreamUtils.java
lancium/GenesisII-Stale-DO-NOT-USE
d0cd1b4502145ef94527459d3d3055800f482250
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2006 University of Virginia * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package org.morgan.util.io; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.Socket; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Mark Morgan (mark@mark-morgan.org) */ public class StreamUtils { static private Log _logger = LogFactory.getLog(StreamUtils.class); static private final int _DEFAULT_BUFFER_SIZE = 1024 * 512; static public void copyStream(Reader reader, Writer writer) throws IOException { char[] data = new char[_DEFAULT_BUFFER_SIZE]; int read; while ((read = reader.read(data)) > 0) { if (writer != null) writer.write(data, 0, read); } writer.flush(); } static public DataTransferStatistics copyStream(InputStream in, OutputStream out, boolean autoflush) throws IOException { DataTransferStatistics stats = DataTransferStatistics.startTransfer(); byte[] data = new byte[_DEFAULT_BUFFER_SIZE]; int read; while ((read = in.read(data)) >= 0) { if (out != null) { out.write(data, 0, read); if (_logger.isTraceEnabled()) _logger.trace("writing " + read + " bytes."); if (autoflush) out.flush(); stats.transfer(read); } } if (out != null) { out.flush(); } return stats.finishTransfer(); } static public DataTransferStatistics copyStream(InputStream in, OutputStream out) throws IOException { return copyStream(in, out, false); } static public void close(Closeable item) { try { if (item != null) item.close(); } catch (Throwable ioe) { } } static public void close(Statement stmt) { try { if (stmt != null) stmt.close(); } catch (Throwable sqe) { } } static public void close(Connection conn) { try { if (conn != null) conn.close(); } catch (Throwable sqe) { } } static public void close(ResultSet rs) { try { if (rs != null) rs.close(); } catch (Throwable sqe) { } } static public void close(Socket socket) { try { if (socket != null) socket.close(); } catch (Throwable cause) { } } }
22.47619
139
0.689619
04b9e2157ad8a9c97a5d9b296ff22c8c5be753be
621
java
Java
abandon/app/src/main/java/com/google/android/libgdx/android/ResolutionStrategy.java
wangrling/media
c378ece82f1f7241605e5568a04d3f771a5ab5d2
[ "MIT" ]
1
2018-12-16T19:43:45.000Z
2018-12-16T19:43:45.000Z
abandon/app/src/main/java/com/google/android/libgdx/android/ResolutionStrategy.java
wangrling/media
c378ece82f1f7241605e5568a04d3f771a5ab5d2
[ "MIT" ]
null
null
null
abandon/app/src/main/java/com/google/android/libgdx/android/ResolutionStrategy.java
wangrling/media
c378ece82f1f7241605e5568a04d3f771a5ab5d2
[ "MIT" ]
null
null
null
package com.google.android.libgdx.android; /** Will manipulate the GLSurfaceView. Gravity is always center. The width and height of the View will be determined by the * classes implementing {@link ResolutionStrategy}. */ public interface ResolutionStrategy { public MeasuredDimension calcMeasures (final int widthMeasureSpec, final int heightMeasureSpec); public static class MeasuredDimension { public final int width; public final int height; public MeasuredDimension (int width, int height) { this.width = width; this.height = height; } } }
27
123
0.700483
a4ddb3632978c9fb519252b04e25a16dab542805
2,389
kt
Kotlin
modules/common_network/src/main/java/kekmech/ru/common_network/connection_tracker/ConnectionTracker.kt
tonykolomeytsev/mpeiapp
28cd15c2cc23b91f88d5bae9f7e16907f9ec0365
[ "MIT" ]
14
2019-08-24T21:41:34.000Z
2022-01-17T08:54:23.000Z
modules/common_network/src/main/java/kekmech/ru/common_network/connection_tracker/ConnectionTracker.kt
tonykolomeytsev/mpeiapp
28cd15c2cc23b91f88d5bae9f7e16907f9ec0365
[ "MIT" ]
125
2019-09-29T21:51:42.000Z
2021-09-25T13:46:36.000Z
modules/common_network/src/main/java/kekmech/ru/common_network/connection_tracker/ConnectionTracker.kt
tonykolomeytsev/mpeiapp
28cd15c2cc23b91f88d5bae9f7e16907f9ec0365
[ "MIT" ]
8
2019-10-10T17:47:32.000Z
2021-09-16T19:34:40.000Z
package kekmech.ru.common_network.connection_tracker import android.annotation.SuppressLint import android.content.Context import android.net.ConnectivityManager import android.net.Network import android.net.NetworkCapabilities.TRANSPORT_CELLULAR import android.net.NetworkCapabilities.TRANSPORT_WIFI import android.net.NetworkRequest import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.subjects.BehaviorSubject import java.util.concurrent.TimeUnit class ConnectionTracker( private val context: Context, ) { private val wifiStateBehavior = BehaviorSubject.create<Boolean>() private val cellularStateBehavior = BehaviorSubject.create<Boolean>() init { startTracking() } fun observeConnectionState(): Observable<Boolean> = Observable .combineLatest(wifiStateBehavior, cellularStateBehavior, ::Pair) .debounce(NETWORK_STATE_DEBOUNCE, TimeUnit.MILLISECONDS) .map { (isWifiEnabled, isCellularEnabled) -> isWifiEnabled or isCellularEnabled } .distinctUntilChanged() private fun startTracking() { wifiStateBehavior.onNext(false) cellularStateBehavior.onNext(false) val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager connectivityManager.observeNetwork(TRANSPORT_WIFI, wifiStateBehavior::onNext) connectivityManager.observeNetwork(TRANSPORT_CELLULAR, cellularStateBehavior::onNext) } @SuppressLint("MissingPermission") private fun ConnectivityManager.observeNetwork( transportType: Int, onConnectionStateChanged: (Boolean) -> Unit, ) { val request = NetworkRequest.Builder() .addTransportType(transportType) .build() val callback = object : ConnectivityManager.NetworkCallback() { override fun onLost(network: Network) { super.onLost(network) onConnectionStateChanged.invoke(false) } override fun onAvailable(network: Network) { super.onAvailable(network) onConnectionStateChanged.invoke(true) } } registerNetworkCallback(request, callback) } private companion object { const val NETWORK_STATE_DEBOUNCE = 300L } }
34.623188
111
0.699037
c4c2ed2447abc7105f868a3037f0c244df997dee
851
kt
Kotlin
src/main/kotlin/net/sileader/argparse/actions/Store.kt
SiLeader/argparse-kt
de6411260a1873efef2df54459d3b02e6fedba14
[ "Apache-2.0" ]
null
null
null
src/main/kotlin/net/sileader/argparse/actions/Store.kt
SiLeader/argparse-kt
de6411260a1873efef2df54459d3b02e6fedba14
[ "Apache-2.0" ]
null
null
null
src/main/kotlin/net/sileader/argparse/actions/Store.kt
SiLeader/argparse-kt
de6411260a1873efef2df54459d3b02e6fedba14
[ "Apache-2.0" ]
null
null
null
package net.sileader.argparse.actions import net.sileader.argparse.Action import net.sileader.argparse.ArgumentsParsingState import net.sileader.argparse.ParameterDescriptor import net.sileader.argparse.errors.ParseException class Store : Action { override fun doAction(descriptor: ParameterDescriptor, state: ArgumentsParsingState) { if(!descriptor.isFlagOrKeyword && state.existsArgument(descriptor.canonicalName)) { throw ParseException("unrecognized arguments: ${state.current}") } if(descriptor.isFlagOrKeyword) { state.advance() if(state.isFinished) { throw ParseException("not enough arguments passed") } } state.appendArgument(descriptor.canonicalName, state.current); state.advance() } override val valueCount = 1 }
35.458333
91
0.701528
e377969838b4e558a9cda447c98af077999e746e
1,809
dart
Dart
lib/home_page_widgets/search_bar_widget.dart
hauntarl/flight-list
741e772289cfec7c07e8c7c3d348b7382e650aa7
[ "MIT" ]
null
null
null
lib/home_page_widgets/search_bar_widget.dart
hauntarl/flight-list
741e772289cfec7c07e8c7c3d348b7382e650aa7
[ "MIT" ]
null
null
null
lib/home_page_widgets/search_bar_widget.dart
hauntarl/flight-list
741e772289cfec7c07e8c7c3d348b7382e650aa7
[ "MIT" ]
null
null
null
import 'package:flight_list_ui/utils/flight_colors.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../models/location.dart'; import '../utils/flight_styles.dart'; import '../pages/flight_list.dart'; class SearchBarWidget extends StatefulWidget { @override _SearchBarWidgetState createState() => _SearchBarWidgetState(); } class _SearchBarWidgetState extends State<SearchBarWidget> { final _textEditingController = TextEditingController(text: locations[1]); @override Widget build(BuildContext context) { return Stack( alignment: Alignment.centerRight, children: <Widget>[ Material( elevation: 15, shadowColor: FlightColors.shadow, borderRadius: BorderRadius.circular(30), child: TextField( controller: _textEditingController, style: FlightStyles.searchBarText, decoration: InputDecoration( contentPadding: EdgeInsets.symmetric( vertical: 15, horizontal: 30, ), border: InputBorder.none, ), ), ), GestureDetector( onTap: () { FocusScope.of(context).requestFocus(FocusNode()); Navigator.push( context, CupertinoPageRoute( builder: (_) => FlightList(), ), ); }, child: Material( elevation: 15, borderRadius: BorderRadius.circular(30), child: Padding( padding: EdgeInsets.all(12), child: Icon( Icons.search, color: FlightColors.accentColor, ), ), ), ), ], ); } }
28.265625
75
0.561636
fd4356cf5370468d8a13942e3d433324418c47df
1,163
swift
Swift
VirojFernando-COBSCComp171P-023/controllers/PasswordResetViewController.swift
Trish-V/NIBM-Connect
ab4d0dd9da9cf4605755d68daca2586c58cceda0
[ "MIT" ]
null
null
null
VirojFernando-COBSCComp171P-023/controllers/PasswordResetViewController.swift
Trish-V/NIBM-Connect
ab4d0dd9da9cf4605755d68daca2586c58cceda0
[ "MIT" ]
null
null
null
VirojFernando-COBSCComp171P-023/controllers/PasswordResetViewController.swift
Trish-V/NIBM-Connect
ab4d0dd9da9cf4605755d68daca2586c58cceda0
[ "MIT" ]
null
null
null
// // PasswordResetViewController.swift // VirojFernando-COBSCComp171P-023 // // Created by Viroj Fernando on 5/26/19. // Copyright © 2019 Heaven'sCode. All rights reserved. // import UIKit import Firebase import FirebaseAuth class PasswordResetViewController: UIViewController { @IBOutlet weak var username: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } func sendPasswordReset(withEmail email: String, _ callback: ((Error?) -> ())? = nil){ Auth.auth().sendPasswordReset(withEmail: email) { error in callback?(error) } } @IBAction func resetButton(_ sender: Any) { self.sendPasswordReset(withEmail: username.text! ) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
25.282609
106
0.656062
b6b56dcf5a0bb7bfe283c40344d8fb08794f2693
1,623
lua
Lua
tools/heartbeat.lua
leonardoguetta/cryptofu
0f194d74db2ec668e38e0cfda4879f9348920221
[ "MIT" ]
1
2017-10-03T22:49:01.000Z
2017-10-03T22:49:01.000Z
tools/heartbeat.lua
leonardoguetta/cryptofu
0f194d74db2ec668e38e0cfda4879f9348920221
[ "MIT" ]
null
null
null
tools/heartbeat.lua
leonardoguetta/cryptofu
0f194d74db2ec668e38e0cfda4879f9348920221
[ "MIT" ]
null
null
null
local heartbeat = {} local tick_charswitch = { [' '] = '.', ['.'] = ' ' } local pulse_state = { dead = 1, live = 2, } local function clear_pulseline (self) local clear_width = self.pulse_width local start = ('\b'):rep (clear_width) self.pulse_writer (start) self.pulse_writer ((' '):rep (clear_width)) self.pulse_writer (start) end local function print_pulseline (self) self.pulse_writer (self.pulse_linestr) self.pulse_writer (('\b'):rep (self.pulse_width - 1)) end function heartbeat:tick () if self.pulse == pulse_state.dead then print_pulseline (self) self.pulse = pulse_state.live end self.pulse_writer (self.tick_char) self.cursor_sp = self.cursor_sp - 1 if self.cursor_sp == 0 then self.cursor_sp = self.pulse_width - 2 self.pulse_writer (('\b'):rep (self.cursor_sp)) self.tick_char = tick_charswitch[self.tick_char] end end function heartbeat:clear () if self.pulse == pulse_state.live then clear_pulseline (self) self.tick_char = '.' self.cursor_sp = self.pulse_width - 2 self.pulse = pulse_state.dead end end local heartbeat_mt = { __index = heartbeat } function heartbeat.newpulse (width, writer) assert (type(width) == "number" and width > 2) local self = { pulse_width = width, pulse_writer = writer or io.write, pulse = pulse_state.dead, tick_char = '.', } self.cursor_sp = self.pulse_width - 2 self.pulse_linestr = ("[%s]"):format ((' '):rep (self.cursor_sp)) return setmetatable (self, heartbeat_mt) end return heartbeat
22.859155
68
0.648799
8b32be8880d62399878c48478fbece82a6ac8440
143
asm
Assembly
engine/phone/scripts/bike_shop.asm
Dev727/ancientplatinum
8b212a1728cc32a95743e1538b9eaa0827d013a7
[ "blessing" ]
28
2019-11-08T07:19:00.000Z
2021-12-20T10:17:54.000Z
engine/phone/scripts/bike_shop.asm
Dev727/ancientplatinum
8b212a1728cc32a95743e1538b9eaa0827d013a7
[ "blessing" ]
13
2020-01-11T17:00:40.000Z
2021-09-14T01:27:38.000Z
engine/phone/scripts/bike_shop.asm
Dev727/ancientplatinum
8b212a1728cc32a95743e1538b9eaa0827d013a7
[ "blessing" ]
22
2020-05-28T17:31:38.000Z
2022-03-07T20:49:35.000Z
BikeShopPhoneCallerScript: farwritetext UnknownText_0x174000 clearflag ENGINE_BIKE_SHOP_CALL_ENABLED specialphonecall SPECIALCALL_NONE end
23.833333
40
0.909091
0a0d0f72aa886c04f0ab9493ac53a4adf52d8461
4,655
asm
Assembly
Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48.log_21829_2588.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48.log_21829_2588.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48.log_21829_2588.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r8 push %r9 push %rax push %rbp push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_D_ht+0x101ef, %rbx nop sub $64328, %r8 movl $0x61626364, (%rbx) nop nop xor %rbp, %rbp lea addresses_D_ht+0x1112f, %r10 add $33879, %rax mov $0x6162636465666768, %r9 movq %r9, (%r10) sub $20471, %rdx lea addresses_normal_ht+0x1a23f, %rsi lea addresses_UC_ht+0x99ef, %rdi xor %r10, %r10 mov $5, %rcx rep movsq nop nop nop xor $59404, %r10 pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rbp pop %rax pop %r9 pop %r8 pop %r10 ret .global s_faulty_load s_faulty_load: push %r12 push %r14 push %r9 push %rbp push %rcx push %rdi // Faulty Load lea addresses_normal+0x8def, %rdi clflush (%rdi) nop nop nop and %r9, %r9 mov (%rdi), %ecx lea oracles, %r9 and $0xff, %rcx shlq $12, %rcx mov (%r9,%rcx,1), %rcx pop %rdi pop %rcx pop %rbp pop %r9 pop %r14 pop %r12 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 9, 'size': 4, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 6, 'size': 8, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 9, 'same': False}} {'34': 21829} 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 */
52.897727
2,999
0.662513
d129b3165432b86a5126958074921d4137787063
6,255
lua
Lua
src/unicode/unicode.lua
mullikine/rosie
2d91fdea1e9f77e9d92b26de938b0b31b7adc6f2
[ "MIT" ]
null
null
null
src/unicode/unicode.lua
mullikine/rosie
2d91fdea1e9f77e9d92b26de938b0b31b7adc6f2
[ "MIT" ]
null
null
null
src/unicode/unicode.lua
mullikine/rosie
2d91fdea1e9f77e9d92b26de938b0b31b7adc6f2
[ "MIT" ]
null
null
null
-- -*- Mode: Lua; -*- -- -- unicode.lua -- -- © Copyright Jamie A. Jennings 2018. -- LICENSE: MIT License (https://opensource.org/licenses/mit-license.html) -- AUTHOR: Jamie A. Jennings local rosie = require("rosie") import = rosie.import local list = import("list") local violation = import("violation") local engine = rosie.engine.new() local ok, pkgname, errs = engine:loadfile("ucd.rpl") if not ok then error(table.concat(list.map(violation.tostring, errs), "\n")) end ucd = dofile("ucd.lua") enumerated = dofile("enumerated.lua") util = dofile("util.lua") UNICODE_VERSION = "10.0.0" UCD_DIR = assert(rosie.env.ROSIE_HOME) .. "/src/unicode/UCD-" .. UNICODE_VERSION .. "/" ReadmeFile = "ReadMe.txt" UnicodeDataFile = "UnicodeData.txt" PropertyFiles = { {"Block", "Blocks.txt"}, {"Script", "Scripts.txt"}, {"Category", "extracted/DerivedGeneralCategory.txt"}, {"Property", "PropList.txt"}, {"Property", "extracted/DerivedBinaryProperties.txt"}, {"LineBreak", "extracted/DerivedLineBreak.txt"}, {"NumericType", "extracted/DerivedNumericType.txt"}, {"GraphemeBreak", "auxiliary/GraphemeBreakProperty.txt"}, {"SentenceBreak", "auxiliary/SentenceBreakProperty.txt"}, {"WordBreak", "auxiliary/WordBreakProperty.txt"}, } character_db = nil as_peg = false property_db = {} source_property_db = {} function populate_property_db() for _, entry in ipairs(PropertyFiles) do local property_name = entry[1] local filename = entry[2] local new_source, new = enumerated.processPropertyFile(engine, filename, property_name, as_peg) if not property_db[property_name] then property_db[property_name] = new source_property_db[property_name] = new_source else -- A property by the same name exists, but we can merge them if the value sets -- for each are unique local existing = property_db[property_name] for value, pattern in pairs(new) do if existing[value] then error("Value collision for " .. property_name .. ": " .. value) else existing[value] = pattern end end end end end header_top = [[ -- DO NOT EDIT. THIS FILE WAS GENERATED FROM THE Unicode Character Database. -- About the Unicode Character Database: -- ]] header_rest = [[ -- -- This file © Copyright IBM, 2018. -- LICENSE: MIT License (https://opensource.org/licenses/mit-license.html) ]] function construct_header() local nl, err = io.lines(UCD_DIR .. "/" .. ReadmeFile) if not nl then error(err); end local line = nl() header = header_top while line do if line:sub(1,1)=="#" then header = header .. "-- " .. line .. "\n" end line = nl() end header = header .. header_rest end -- ----------------------------------------------------------------------------- -- ASCII character classes from the Posix locale (also called C locale) -- ----------------------------------------------------------------------------- ascii_patterns = {} function ranges_from_locale_peg(peg) local ranges = {} local start = nil local last_ascii = 0x7F for c = 0x0, last_ascii do if peg:match(string.char(c)) then if not start then start = c; end else if start then -- from start to c-1 is a valid range of ascii chars for this peg table.insert(ranges, {start, c - 1}) start = nil end end end if start then table.insert(ranges, {start, last_ascii}); end return ranges end function rpl_from_locale_peg(name, peg) local ranges = ranges_from_locale_peg(peg) local rpl_for_name = util.compile_all_ranges({[name] = ranges}, false) return rpl_for_name[name] end function read_ascii() locale = lpeg.locale() for name, peg in pairs(locale) do ascii_patterns[name] = rpl_from_locale_peg(name, peg) end local engine = rosie.engine.new() for name, source in pairs(ascii_patterns) do print("Compiling", name, source:sub(1,40).."...") local rplx, errs = engine:compile(source) if not rplx then error(table.concat(list.map(violation.tostring, errs), "\n")) end local in_range_errors = 0 local peg_out_range_errors = 0 local rpl_out_range_errors = 0 for c = 0x0, 0x7F do local pok = locale[name]:match(string.char(c)) local rok = rplx:match(string.char(c)) if (pok and not rok) or (rok and not pok) then print(string.format("%s failed at char \\x%02x", name, c)) in_range_errors = in_range_errors + 1 end end -- for 0x0 - 0x7F for c = 0x80, 0xff do if locale[name]:match(string.char(c)) then print(string.format("peg matches non-ascii character \\x%02x", c)) peg_out_range_errors = peg_out_range_errors + 1 end if rplx:match(string.char(c)) then print(string.format("rpl matches non-ascii character \\x%02x", c)) rpl_out_range_errors = rpl_out_range_errors + 1 end end -- for 0x80 - 0xFF if in_range_errors == 0 then print("In range ascii values tested OK") end if (peg_out_range_errors == 0) and (rpl_out_range_errors == 0) then print("Out of range values tested OK") else print("ERRORS with bytes outside of ascii range") end end -- for each compiled rpl pattern end -- ----------------------------------------------------------------------------- -- Top level: read(); write() -- ----------------------------------------------------------------------------- function read() construct_header() character_db = ucd.processUnicodeData(engine, UnicodeDataFile) populate_property_db() os.setlocale("C") read_ascii() source_property_db.Ascii = ascii_patterns end function write(optional_directory) optional_directory = optional_directory or "/tmp" for propname, patterns in pairs(source_property_db) do local filename = (optional_directory .. "/" .. propname .. ".rpl") print("Writing " .. filename) local f, err = io.open(filename, 'w') if not f then error(err); end f:write(header, "\n") f:write("package ", propname, "\n\n") for patname, patsource in pairs(patterns) do f:write(patname, " = ", patsource, "\n") end f:close() end end
30.812808
101
0.626379
02ec1170a8e06a14e505b5d44dd2cfacefe58e74
705
sql
SQL
scriptDB/CreaDB207DWESProyectoTema4-Desarollo.sql
AlbertoFRSauces/proyectoTema4
31535ba65b11e046ff7595d9740d7c52e29aebea
[ "MIT" ]
null
null
null
scriptDB/CreaDB207DWESProyectoTema4-Desarollo.sql
AlbertoFRSauces/proyectoTema4
31535ba65b11e046ff7595d9740d7c52e29aebea
[ "MIT" ]
null
null
null
scriptDB/CreaDB207DWESProyectoTema4-Desarollo.sql
AlbertoFRSauces/proyectoTema4
31535ba65b11e046ff7595d9740d7c52e29aebea
[ "MIT" ]
null
null
null
/** * Author: Alberto Fernandez Ramirez * Created: 3 nov. 2021 * Script creación de base de datos y usuario */ -- Crear base de datos Departamentos CREATE DATABASE IF NOT EXISTS DB207DWESProyectoTema4; -- CREAR Tabla Departamento dentro de la base de datos DAW207DBDepartamentos CREATE TABLE IF NOT EXISTS DB207DWESProyectoTema4.Departamento( CodDepartamento varchar(3) PRIMARY KEY, DescDepartamento varchar(255) NOT NULL, FechaBaja date NULL, VolumenNegocio float NULL )engine=innodb; -- Crear usuario CREATE USER 'User207DWESProyectoTema4'@'%' IDENTIFIED BY 'P@ssw0rd'; -- Dar permisos al usuario GRANT ALL PRIVILEGES ON DB207DWESProyectoTema4.* to 'User207DWESProyectoTema4'@'%';
35.25
83
0.774468
a14fb5aeecf0735824960109eda29df242d49909
31,466
dart
Dart
lib/src/decoder/thumb/converter.dart
matanlurey/armv4t.dart
06235938d16cb1f2b09d26f564b985854e4155c0
[ "MIT" ]
8
2020-06-21T22:05:00.000Z
2021-10-06T19:59:20.000Z
lib/src/decoder/thumb/converter.dart
matanlurey/armv4t.dart
06235938d16cb1f2b09d26f564b985854e4155c0
[ "MIT" ]
82
2020-06-21T22:02:00.000Z
2020-08-04T01:48:42.000Z
lib/src/decoder/thumb/converter.dart
matanlurey/armv4t.dart
06235938d16cb1f2b09d26f564b985854e4155c0
[ "MIT" ]
1
2020-06-22T15:16:02.000Z
2020-06-22T15:16:02.000Z
/// Decoding elements specific to `THUMB`. /// /// {@category THUMB} library armv4t.decoder.thumb.converter; import 'dart:convert'; import 'package:armv4t/src/common/binary.dart'; import 'package:armv4t/src/common/union.dart'; import 'package:armv4t/src/decoder/arm/condition.dart'; import 'package:armv4t/src/decoder/arm/instruction.dart'; import 'package:armv4t/src/decoder/common.dart'; import 'package:binary/binary.dart'; import 'package:meta/meta.dart'; import 'format.dart'; /// Implements `THUMB`-instruction parsing by converting into equivalent `ARM`. /// /// This approach sacrifies making mapping/debugging easier by instead just /// converting 16-bit `THUMB` instructions it to the equivalent 32-bit `ARM`. @immutable @sealed abstract class ThumbToArmDecoder implements Converter<Uint16, ArmInstruction> { const factory ThumbToArmDecoder({ ThumbFormatDecoder formatDecoder, }) = _ThumbToArmDecoder; } extension on Uint3 { /// Converts [Uint3] into a [RegisterAny]. RegisterAny toLoRegister() => RegisterAny(Uint4(value)); /// Converts [Uint3] into a [RegisterAny], with `0` treated as `8`. RegisterAny toHiRegister() => RegisterAny(Uint4(value + 8)); /// Converts [Uint3] into a [RegisterNotPC]. RegisterNotPC toLoRegisterNonPC() => RegisterNotPC(Uint4(value)); /// Converts [Uint3] into a [RegisterNotPC], with `0` treated as `8`. RegisterNotPC toHiRegisterNonPC() => RegisterNotPC(Uint4(value + 8)); } class _ThumbToArmDecoder extends Converter<Uint16, ArmInstruction> implements /**/ ThumbToArmDecoder, /**/ ThumbFormatVisitor<ArmInstruction, void> { static const _always = Condition.al; @alwaysThrows // ignore: prefer_void_to_null static Null _nullOpCode() { throw StateError('Cannot have a "null" opCode'); } final ThumbFormatDecoder _formatDecoder; const _ThumbToArmDecoder({ ThumbFormatDecoder formatDecoder, }) : _formatDecoder = formatDecoder ?? const ThumbFormatDecoder(); @override ArmInstruction convert(Uint16 input) { return _formatDecoder.convert(input).accept(this); } @override ArmInstruction visitAddOffsetToStackPointer( AddOffsetToStackPointerThumbFormat format, [ void _, ]) { // THUMB: ADD Rd, <PC|SP>, #Imm // ARM: ADD Rd, <R13|R15>, #Imm return ADDArmInstruction( condition: _always, setConditionCodes: false, operand1: RegisterAny.pc, destination: RegisterAny.pc, operand2: Or3.right( ShiftedImmediate(Uint4.zero, Immediate(Uint8(format.word.value))), ), ); } @override ArmInstruction visitAddOrSubtract( AddOrSubtractThumbFormat format, [ void _, ]) { final operand1 = format.sourceRegister.toLoRegister(); final destination = format.destinationRegister.toLoRegister(); if (format.immediateOperandBit) { final operand2 = ShiftedImmediate( Uint4.zero, Immediate(Uint8(format.baseRegisterOrImmediate.value)), ); if (format.opCode$SUB) { // THUMB: SUB Rd, Rs, #Offset3 // ARM: SUBS Rd, Rs, #Offset3 return SUBArmInstruction( condition: _always, setConditionCodes: true, operand1: operand1, destination: destination, operand2: Or3.right(operand2), ); } else { // THUMB: ADD Rd, Rs, #Offset3 // ARM: ADDS Rd, Rs, #Offset3 return ADDArmInstruction( condition: _always, setConditionCodes: true, operand1: operand1, destination: destination, operand2: Or3.right(operand2), ); } } else { final operand2 = format.baseRegisterOrImmediate.toLoRegister(); if (format.opCode$SUB) { // THUMB: SUB Rd, Rs, Rn // ARM: SUBS Rd, Rs, Rn return SUBArmInstruction( condition: _always, setConditionCodes: true, operand1: operand1, destination: destination, operand2: Or3.left( ShiftedRegister( operand2, ShiftType.LSL, Immediate(Uint5.zero), ), ), ); } else { // THUMB: ADD Rd, Rs, Rn // ARM: ADDS Rd, Rs, Rn return ADDArmInstruction( condition: _always, setConditionCodes: true, operand1: operand1, destination: destination, operand2: Or3.left( ShiftedRegister( operand2, ShiftType.LSL, Immediate(Uint5.zero), ), ), ); } } } @override ArmInstruction visitAluOperation( AluOperationThumbFormat format, [ void _, ]) { ShiftedRegister<Immediate<Uint5>, RegisterAny> left() { return ShiftedRegister( format.source.toLoRegister(), ShiftType.LSL, Immediate(Uint5.zero), ); } ShiftedRegister<RegisterNotPC, RegisterAny> middle(ShiftType shiftType) { return ShiftedRegister( format.destination.toLoRegister(), shiftType, format.source.toLoRegisterNonPC(), ); } final destination = format.destination.toLoRegister(); switch (format.opCode.value) { // THUMB: AND Rd, Rs // ARM: ANDS Rd, Rd, Rs case 0x0: return ANDArmInstruction( condition: _always, setConditionCodes: true, destination: destination, operand1: destination, operand2: Or3.left(left()), ); // THUMB: EOR Rd, Rs // ARM: EORS Rd, Rd, Rs case 0x1: return EORArmInstruction( condition: _always, setConditionCodes: true, destination: destination, operand1: destination, operand2: Or3.left(left()), ); // THUMB: LSL Rd, Rs // ARM: MOVS Rd, Rd, LSL Rs case 0x2: return MOVArmInstruction( condition: _always, setConditionCodes: true, destination: Register.filledWith0s, operand1: destination, operand2: Or3.middle(middle(ShiftType.LSL)), ); // THUMB: LSR Rd, Rs // ARM: MOVS Rd, Rd, LSR Rs case 0x3: return MOVArmInstruction( condition: _always, setConditionCodes: true, destination: Register.filledWith0s, operand1: destination, operand2: Or3.middle(middle(ShiftType.LSR)), ); // THUMB: ASR Rd, Rs // ARM: MOVS Rd, Rd, ASR Rs case 0x4: return MOVArmInstruction( condition: _always, setConditionCodes: true, destination: Register.filledWith0s, operand1: destination, operand2: Or3.middle(middle(ShiftType.ASR)), ); // THUMB: ADC Rd, Rs // ARM: ADCS Rd, Rd, Rs case 0x5: return ADCArmInstruction( condition: _always, setConditionCodes: true, destination: destination, operand1: destination, operand2: Or3.left(left()), ); // THUMB: SBC Rd, Rs // ARM: SBCS Rd, Rd, Rs case 0x6: return SBCArmInstruction( condition: _always, setConditionCodes: true, destination: destination, operand1: destination, operand2: Or3.left(left()), ); // THUMB: ROR Rd, Rs // ARM: MOVS Rd, Rd, ROR Rs case 0x7: return MOVArmInstruction( condition: _always, setConditionCodes: true, destination: Register.filledWith0s, operand1: destination, operand2: Or3.middle(middle(ShiftType.ROR)), ); // THUMB: TST Rd, Rs // ARM: TST Rd, Rs case 0x8: return TSTArmInstruction( condition: _always, destination: Register.filledWith0s, operand1: destination, operand2: Or3.left(left()), ); // THUMB: NEG Rd, Rs // ARM: RSBS Rd, Rd, #0 case 0x9: return RSBArmInstruction( condition: _always, setConditionCodes: true, destination: destination, operand1: destination, operand2: Or3.right( ShiftedImmediate( Uint4.zero, Immediate(Uint8.zero), ), ), ); // THUMB: CMP Rd, Rs // ARM: CMP Rd, Rs case 0xa: return CMPArmInstruction( condition: _always, destination: Register.filledWith0s, operand1: destination, operand2: Or3.left(left()), ); // THUMB: CMN Rd, Rs // ARM: CMN Rd, Rs case 0xb: return CMNArmInstruction( condition: _always, destination: Register.filledWith0s, operand1: destination, operand2: Or3.left(left()), ); // THUMB: ORR Rd, Rs // ARM: ORRS Rd, Rd, Rs case 0xc: return ORRArmInstruction( condition: _always, setConditionCodes: true, destination: destination, operand1: destination, operand2: Or3.left(left()), ); // THUMB: MUL Rd, Rs // ARM: MULS Rd, Rs, Rd case 0xd: return MULArmInstruction( condition: _always, setConditionCodes: true, destination: format.destination.toLoRegisterNonPC(), operand1: format.source.toLoRegisterNonPC(), operand2: format.destination.toLoRegisterNonPC(), ); // THUMB: BIC Rd, Rs // ARM: BICS Rd, Rd, Rs case 0xe: return BICArmInstruction( condition: _always, setConditionCodes: true, destination: destination, operand1: destination, operand2: Or3.left(left()), ); // THUMB: MVN Rd, Rs // ARM: MVNS Rd, Rs case 0xf: return MVNArmInstruction( condition: _always, setConditionCodes: true, destination: Register.filledWith0s, operand1: destination, operand2: Or3.middle(middle(ShiftType.ASR)), ); default: return _nullOpCode(); } } @override ArmInstruction visitConditionalBranch( ConditionalBranchThumbFormat format, [ void _, ]) { return BArmInstruction( condition: Condition.parse(format.condition.value), offset: Int24(format.offset.value.toSigned(8)), ); } @override ArmInstruction visitHiRegisterOperationsOrBranchExchange( HiRegisterOperationsOrBranchExchangeThumbFormat format, [ void _, ]) { @alwaysThrows // ignore: prefer_void_to_null Null _unsupportedHH() { throw FormatException('Unsupported HH: ${format.hCodes.value}'); } RegisterAny destinationLo() => format.destination.toLoRegister(); RegisterAny destinationHi() => format.destination.toHiRegister(); switch (format.opCode.value) { case 0x0: switch (format.hCodes.value) { // THUMB: ADD Rd, Hs // ARM: ADD Rd, Rd, Hs case 0x1: // 01 return ADDArmInstruction( condition: _always, setConditionCodes: false, operand1: destinationLo(), destination: destinationLo(), operand2: Or3.left( ShiftedRegister( format.source.toHiRegister(), ShiftType.LSL, Immediate(Uint5.zero), ), ), ); // THUMB: ADD Hd, Rs // ARM: ADD Hd, Hd, Rs case 0x2: // 10 return ADDArmInstruction( condition: _always, setConditionCodes: false, operand1: destinationHi(), destination: destinationHi(), operand2: Or3.left( ShiftedRegister( format.source.toLoRegister(), ShiftType.LSL, Immediate(Uint5.zero), ), ), ); // THUMB: ADD Hd, Hs // ARM: ADD Hd, Hd, Hs case 0x3: // 11 return ADDArmInstruction( condition: _always, setConditionCodes: false, operand1: destinationHi(), destination: destinationHi(), operand2: Or3.left( ShiftedRegister( format.source.toHiRegister(), ShiftType.LSL, Immediate(Uint5.zero), ), ), ); } return _unsupportedHH(); case 0x1: switch (format.hCodes.value) { // THUMB: CMP Rd, Hs // ARM: CMP Rd, Hs case 0x1: // 01 return CMPArmInstruction( condition: _always, operand1: destinationLo(), destination: Register.filledWith0s, operand2: Or3.left(ShiftedRegister( format.source.toHiRegister(), ShiftType.LSL, Immediate(Uint5.zero), )), ); // THUMB: CMP Hd, Rs // ARM: CMP Hd, Rs case 0x2: // 10 return CMPArmInstruction( condition: _always, operand1: destinationHi(), destination: Register.filledWith0s, operand2: Or3.left(ShiftedRegister( format.source.toLoRegister(), ShiftType.LSL, Immediate(Uint5.zero), )), ); // THUMB: CMP Hd, Hs // ARM: CMP Hd, Hs case 0x3: // 11 return CMPArmInstruction( condition: _always, operand1: destinationHi(), destination: Register.filledWith0s, operand2: Or3.left(ShiftedRegister( format.source.toHiRegister(), ShiftType.LSL, Immediate(Uint5.zero), )), ); } return _unsupportedHH(); case 0x2: switch (format.hCodes.value) { // THUMB: MOV Rd, Hs // ARM: MOV Rd, Hs case 0x1: // 00 return MOVArmInstruction( condition: _always, setConditionCodes: false, operand1: Register.filledWith0s, destination: format.destination.toLoRegister(), operand2: Or3.left( ShiftedRegister( format.source.toHiRegister(), ShiftType.LSL, Immediate(Uint5.zero), ), ), ); // THUMB: MOV Hd, Rs // ARM: MOV Hd, Rs case 0x2: // 01 return MOVArmInstruction( condition: _always, setConditionCodes: false, operand1: Register.filledWith0s, destination: format.destination.toHiRegister(), operand2: Or3.left( ShiftedRegister( format.source.toLoRegister(), ShiftType.LSL, Immediate(Uint5.zero), ), ), ); // THUMB: MOV Hd, Hs // ARM: MOV Hd, Hs case 0x3: return MOVArmInstruction( condition: _always, setConditionCodes: false, operand1: Register.filledWith0s, destination: format.destination.toHiRegister(), operand2: Or3.left( ShiftedRegister( format.source.toHiRegister(), ShiftType.LSL, Immediate(Uint5.zero), ), ), ); } return _unsupportedHH(); case 0x3: switch (format.hCodes.value) { // THUMB: BX Rs // ARM: BX Rs case 0x0: // 00 return BXArmInstruction( condition: _always, operand: format.source.toLoRegisterNonPC(), ); // THUMB: BX Hs // ARM: BX Hs case 0x1: // 01 return BXArmInstruction( condition: _always, operand: format.source.toHiRegisterNonPC(), ); } return _unsupportedHH(); default: return _nullOpCode(); } } @override ArmInstruction visitLoadAddress( LoadAddressThumbFormat format, [ void _, ]) { // THUMB: ADD Rd, <PC|SP>, #Imm // ARM: ADD Rd, <R13|R15>, #Imm final register = format.stackPointerBit ? RegisterAny.sp : RegisterAny.pc; return ADDArmInstruction( condition: _always, setConditionCodes: false, operand1: register, destination: format.destination.toLoRegister(), operand2: Or3.right(ShiftedImmediate(Uint4.zero, Immediate(format.word))), ); } @override ArmInstruction visitLoadOrStoreHalfword( LoadOrStoreHalfwordThumbFormat format, [ void _, ]) { // Addresses are pre-indeed using a 6-bit immediate value. // // Note: [format.offset.value] is a full 6-bit address but must be half-word // aligned (i.e. with bit 0 set to 0) since the assembler places #Imm >> 1 // in the Offset5 field. final offset = Immediate(Uint8(format.offset.value << 1)); if (format.loadBit) { // ARM: LDRH Rd, [Rb, #Imm] // THUMB: LDRH Rd, [Rb, #Imm] return LDRHArmInstruction( condition: _always, addOffsetBeforeTransfer: true, addOffsetToBase: true, writeAddressIntoBase: false, base: format.baseRegister.toLoRegister(), destination: format.sourceOrDestinationRegister.toLoRegister(), offset: Or2.right(offset), ); } else { // ARM: STRH Rd, [Rb, #Imm] // THUMB: STRH Rd, [Rb, #Imm] return STRHArmInstruction( condition: _always, addOffsetBeforeTransfer: true, addOffsetToBase: true, writeAddressIntoBase: false, base: format.baseRegister.toLoRegister(), source: format.sourceOrDestinationRegister.toLoRegister(), offset: Or2.right(offset), ); } } @override ArmInstruction visitLoadOrStoreSignExtendedByteOrHalfword( LoadOrStoreSignExtendedByteOrHalfword format, [ void _, ]) { if (format.sBit) { if (format.hBit) { // ARM: LDRSH Rd, [Rb, Ro] // THUMB: LDRSH Rd, [Rb, Ro] // 1 1 return LDRSHArmInstruction( condition: _always, addOffsetBeforeTransfer: true, addOffsetToBase: true, writeAddressIntoBase: false, base: format.baseRegister.toLoRegister(), destination: format.sourceOrdestinationRegister.toLoRegister(), offset: Or2.left(format.offsetRegister.toLoRegisterNonPC()), ); } else { // ARM: LDRSB Rd, [Rb, Ro] // THUMB: LDRSB Rd, [Rb, Ro] // 1 0 return LDRSBArmInstruction( condition: _always, addOffsetBeforeTransfer: true, addOffsetToBase: true, writeAddressIntoBase: false, base: format.baseRegister.toLoRegister(), destination: format.sourceOrdestinationRegister.toLoRegister(), offset: Or2.left(format.offsetRegister.toLoRegisterNonPC()), ); } } else { if (format.hBit) { // ARM: LDRH Rd, [Rb, Ro] // THUMB: LDRH Rd, [Rb, Ro] // 0 1 return LDRHArmInstruction( condition: _always, addOffsetBeforeTransfer: true, addOffsetToBase: true, writeAddressIntoBase: false, base: format.baseRegister.toLoRegister(), destination: format.sourceOrdestinationRegister.toLoRegister(), offset: Or2.left(format.offsetRegister.toLoRegisterNonPC()), ); } else { // ARM: STRH Rd, [Rb, Ro] // THUMB: STRH Rd, [Rb, Ro] // 0 0 return STRHArmInstruction( condition: _always, addOffsetBeforeTransfer: true, addOffsetToBase: true, writeAddressIntoBase: false, base: format.baseRegister.toLoRegister(), source: format.sourceOrdestinationRegister.toLoRegister(), offset: Or2.left(format.offsetRegister.toLoRegisterNonPC()), ); } } } @override ArmInstruction visitLoadOrStoreWithImmediateOffset( LoadOrStoreWithImmediateOffsetThumbFormat format, [ void _, ]) { // For word access (B = 0), the value specified by [format.offset] is a full // 7-bit address, but must be word-aligned (i.e. with bits 1:0 set to 0), // since the assembler places #Imm >> 2 in the Offset5 field. var value = format.offset.value; if (!format.byteBit) { value = value << 2; } final offset = Immediate(Uint12(value)); if (format.loadBit) { // THUMB: LDR{B} Rd, [Rb, #Imm] // ARM: LDR{B} Rd, [Rb, #Imm] return LDRArmInstruction( condition: _always, addOffsetBeforeTransfer: true, addOffsetToBase: true, writeAddressIntoBaseOrForceNonPrivilegedAccess: false, transferByte: format.byteBit, base: format.base.toLoRegister(), destination: format.destination.toLoRegister(), offset: Or2.left(offset), ); } else { // THUMB: STR{B} Rd, [Rb, #Imm] // ARM: STR{B} Rd, [Rb, #Imm] return STRArmInstruction( condition: _always, addOffsetBeforeTransfer: true, addOffsetToBase: true, writeAddressIntoBaseOrForceNonPrivilegedAccess: false, transferByte: format.byteBit, base: format.base.toLoRegister(), source: format.destination.toLoRegister(), offset: Or2.left(offset), ); } } @override ArmInstruction visitLoadOrStoreWithRegisterOffset( LoadOrStoreWithRegisterOffsetThumbFormat format, [ void _, ]) { if (format.loadBit) { // THUMB: LDR{B} Rd, [Rb, Ro] // ARM: LDR{B} Rd, [Rb, Ro] return LDRArmInstruction( condition: _always, addOffsetBeforeTransfer: true, addOffsetToBase: true, writeAddressIntoBaseOrForceNonPrivilegedAccess: false, transferByte: format.byteBit, base: format.base.toLoRegister(), destination: format.destination.toLoRegister(), offset: Or2.right(ShiftedRegister( format.offset.toLoRegisterNonPC(), ShiftType.LSL, Immediate(Uint4.zero), )), ); } else { // THUMB: STR{B} Rd, [Rb, Ro] // ARM: STR{B} Rd, [Rb, Ro] return STRArmInstruction( condition: _always, addOffsetBeforeTransfer: true, addOffsetToBase: true, writeAddressIntoBaseOrForceNonPrivilegedAccess: false, transferByte: format.byteBit, base: format.base.toLoRegister(), source: format.destination.toLoRegister(), offset: Or2.right(ShiftedRegister( format.offset.toLoRegisterNonPC(), ShiftType.LSL, Immediate(Uint4.zero), )), ); } } @override ArmInstruction visitLongBranchWithLink( LongBranchWithLinkThumbFormat format, [ void _, ]) { return BLArmInstruction( condition: _always, offset: Int24(format.offset.value.toSigned(11)), thumbLongBranch: format.hBit, ); } @override ArmInstruction visitMoveOrCompareOrAddOrSubtractImmediate( MoveOrCompareOrAddOrSubtractImmediateThumbFormat format, [ void _, ]) { final destination = format.destination.toLoRegister(); final operand2 = ShiftedImmediate(Uint4.zero, Immediate(format.offset)); switch (format.opCode.value) { // THUMB: MOV Rd, #Offset8 // ARM: MOVS Rd, #Offset8 case 0x0: return MOVArmInstruction( condition: _always, setConditionCodes: true, operand1: Register.filledWith0s, destination: destination, operand2: Or3.right(operand2), ); // THUMB: CMP Rd, #Offset8 // ARM: CMPS Rd, #Offset8 case 0x1: return CMPArmInstruction( condition: _always, operand1: destination, destination: Register.filledWith0s, operand2: Or3.right(operand2), ); // THUMB: ADD Rd, #Offset8 // ARM: ADDS Rd, #Offset8 case 0x2: return ADDArmInstruction( condition: _always, setConditionCodes: true, operand1: destination, destination: destination, operand2: Or3.right(operand2), ); // THUMB: SUB Rd, #Offset8 // ARM: SUBS Rd, #Offset8 case 0x3: return SUBArmInstruction( condition: _always, setConditionCodes: true, operand1: destination, destination: destination, operand2: Or3.right(operand2), ); default: return _nullOpCode(); } } @override ArmInstruction visitMoveShiftedRegister( MoveShiftedRegisterThumbFormat format, [ void _, ]) { final shiftRegister = format.sourceRegister.toLoRegister(); final shiftImmediate = Immediate(format.immediate); final destination = format.destinationRegister.toLoRegister(); switch (format.opCode.value) { // THUMB: LSL Rd, Rs, #Offset5 // ARM: MOVS Rd, Rs, LSL #Offset5 case 0x0: return MOVArmInstruction( condition: _always, setConditionCodes: true, operand1: Register.filledWith0s, destination: destination, operand2: Or3.left( ShiftedRegister( shiftRegister, ShiftType.LSL, shiftImmediate, ), ), ); // THUMB: LSR Rd, Rs, #Offset5 // ARM: MOVS Rd, Rs, LSr #Offset5 case 0x1: return MOVArmInstruction( condition: _always, setConditionCodes: true, operand1: Register.filledWith0s, destination: destination, operand2: Or3.left( ShiftedRegister( shiftRegister, ShiftType.LSR, shiftImmediate, ), ), ); // THUMB: ASR Rd, Rs, #Offset5 // ARM: MOVS Rd, Rs, ASR #Offset5 case 0x2: return MOVArmInstruction( condition: _always, setConditionCodes: true, operand1: Register.filledWith0s, destination: destination, operand2: Or3.left( ShiftedRegister( shiftRegister, ShiftType.ASR, shiftImmediate, ), ), ); default: throw FormatException('Unexpected opCode: ${format.opCode.value}'); } } @override ArmInstruction visitMultipleLoadOrStore( MultipleLoadOrStoreThumbFormat format, [ void _, ]) { if (format.loadBit) { // THUMB: LDMIA Rb!, { Rlist } // ARM: LDMIA Rb!, { Rlist } return LDMArmInstruction( condition: _always, addOffsetBeforeTransfer: false, addOffsetToBase: true, writeAddressIntoBase: true, loadPsr: false, base: RegisterAny.sp, registerList: RegisterList.parse(format.registerList.value), ); } else { // THUMB: STMIA Rb!, { Rlist } // ARM: STMIA Rb!, { Rlist } return STMArmInstruction( condition: _always, addOffsetBeforeTransfer: false, addOffsetToBase: true, writeAddressIntoBase: true, forceNonPrivilegedAccess: false, base: RegisterAny.sp, registerList: RegisterList.parse(format.registerList.value), ); } } @override ArmInstruction visitPCRelativeLoad( PCRelativeLoadThumbFormat format, [ void _, ]) { return LDRArmInstruction( condition: _always, addOffsetBeforeTransfer: false, addOffsetToBase: true, writeAddressIntoBaseOrForceNonPrivilegedAccess: false, transferByte: false, base: format.destination.toLoRegister(), destination: RegisterAny.pc, offset: Or2.left(Immediate(Uint12(format.word.value))), ); } @override ArmInstruction visitPushOrPopRegisters( PushOrPopRegistersThumbFormat format, [ void _, ]) { var registerList = format.registerList; if (format.pcOrLrBit) { // Store LR/Load PC if (format.loadBit) { // Load PC registerList = registerList.setBit(15); } else { // Store LR registerList = registerList.setBit(14); } } if (format.loadBit) { // THUMB: POP { Rlist } // ARM: LDMIA R13!, { Rlist } // -or- // THUMB: POP { Rlist, PC } // ARM: LDMIA R13!, { Rlist, R15 } return LDMArmInstruction( condition: _always, addOffsetBeforeTransfer: false, addOffsetToBase: true, writeAddressIntoBase: true, loadPsr: false, base: RegisterAny.sp, registerList: RegisterList.parse(registerList.value), ); } else { // THUMB: PUSH { Rlist } // ARM: STMDB R13!, { Rlist } // -or- // THUMB: PUSH { Rlist, LR } // ARM: STMDB R13!, { Rlist, R14 } return STMArmInstruction( condition: _always, addOffsetBeforeTransfer: true, addOffsetToBase: false, writeAddressIntoBase: true, forceNonPrivilegedAccess: false, base: RegisterAny.sp, registerList: RegisterList.parse(registerList.value), ); } } @override ArmInstruction visitSPRelativeLoadOrStore( SPRelativeLoadOrStoreThumbFormat format, [ void _, ]) { // For word access (B = 0), the value specified by [format.offset] is a full // 7-bit address, but must be word-aligned (i.e. with bits 1:0 set to 0), // since the assembler places #Imm >> 2 in the Offset5 field. final offset = Immediate(Uint12(format.word.value << 2)); if (format.loadBit) { // THUMB: LDR Rd, [SP, #Imm] // ARM: LDR Rd, [R13 #Imm] return LDRArmInstruction( condition: _always, addOffsetBeforeTransfer: true, addOffsetToBase: true, writeAddressIntoBaseOrForceNonPrivilegedAccess: false, transferByte: false, base: RegisterAny.sp, destination: format.destination.toLoRegister(), offset: Or2.left(offset), ); } else { // THUMB: STR Rd, [SP, #Imm] // ARM: STR Rd, [R13 #Imm] return STRArmInstruction( condition: _always, addOffsetBeforeTransfer: true, addOffsetToBase: true, writeAddressIntoBaseOrForceNonPrivilegedAccess: false, transferByte: false, base: RegisterAny.sp, source: format.destination.toLoRegister(), offset: Or2.left(offset), ); } } @override ArmInstruction visitSoftwareInterrupt( SoftwareInterruptThumbFormat format, [ void _, ]) { return SWIArmInstruction( condition: _always, comment: Comment(Uint24(format.value.value)), ); } @override ArmInstruction visitUnconditionalBranch( UnconditionalBranchThumbFormat format, [ void _, ]) { return BArmInstruction( condition: _always, offset: Int24(format.offset.value.toSigned(11)), ); } }
30.549515
80
0.573635