问:
php split a file into $key=>$value pairs with duplicate keys
I've been trying to wrap my head around this and I'm just brain frozen.

I have a file with multiple lines, each line is delimited by "=" into separate pieces of data:

```<code>// Example file. Syntax: <key>=<Value>
key1=value1
key1=value2
key1=value3
key2=value1
key2=value2
key3=value1
key3=value2
key3=value3
key3=value4
</code>```

I need to explode this file into separate lines, and throw them all in an array such that key1 holds an array of value1, 2, 3, key2 has its values, key3 has its values, so on and so forth. Kind of like this:

```<code>Array
(
    [key1] => Array
        (
        [0] => value1
        [1] => value2
        [2] => value3
        )
    [key2] => Array
        (
        [0] => value1
        [1] => value2
        )
    [key3] => Array
        (
        [0] => value1
        [1] => value2
        [2] => value3
        [3] => value4
        )
)
</code>```

So far I have the following code:

```<code>$loadFile = file('file.txt');
$returnArray = array();
foreach ($loadFile as $line) {
  $startWith = substr(trim($line), 0, 2);
    if (empty($line) || $startWith == '//') {
          continue;
  }
  list($key, $value) = explode('=', $line);
  $returnArray[$key] = $value;
}
return $returnArray;
</code>```

However all I'm getting back is:

```<code>Array ( [key1] => value3 [key2] => value2 [key3] => value4 )
</code>```

I've also tried

```<code>$loadFile = file('file.txt');
$returnArray = array();
foreach ($loadFile as $line) {
  $startWith = substr(trim($line), 0, 2);
    if (empty($line) || $startWith == '//') {
          continue;
  }
  $exp = explode('=', $line);
  $returnArray[$exp[0]] = $exp[1];
}
return $returnArray;
</code>```

Which also gives me the same result. I've also tried an array_merge which just shoved everything into an array with a numeric value as the key.

答:
For fun, just turn them into array syntax for an ini file and parse it:

```<code>$result = parse_ini_string(str_replace('=', '[]=', file_get_contents('file.txt')));
</code>```

More fun, turn them into a query string and parse it:

```<code>parse_str(str_replace('=', '[]=', implode('&', file('file.txt'))), $result);
</code>```

Both yield:

```<code>Array
(
    [key1] => Array
        (
            [0] => value1
            [1] => value2
            [2] => value3
        )

    [key2] => Array
        (
            [0] => value1
            [1] => value2
        )

    [key3] => Array
        (
            [0] => value1
            [1] => value2
            [2] => value3
            [3] => value4
        )
)
</code>```

Body:
I've been trying to wrap my head around this and I'm just brain frozen.

I have a file with multiple lines, each line is delimited by "=" into separate pieces of data:

// Example file. Syntax: <key>=<Value>
key1=value1
key1=value2
key1=value3
key2=value1
key2=value2
key3=value1
key3=value2
key3=value3
key3=value4

I need to explode this file into separate lines, and throw them all in an array such that key1 holds an array of value1, 2, 3, key2 has its values, key3 has its values, so on and so forth. Kind of like this:

Array
(
    [key1] => Array
        (
        [0] => value1
        [1] => value2
        [2] => value3
        )
    [key2] => Array
        (
        [0] => value1
        [1] => value2
        )
    [key3] => Array
        (
        [0] => value1
        [1] => value2
        [2] => value3
        [3] => value4
        )
)

So far I have the following code:

$loadFile = file('file.txt');
$returnArray = array();
foreach ($loadFile as $line) {
  $startWith = substr(trim($line), 0, 2);
    if (empty($line) || $startWith == '//') {
          continue;
  }
  list($key, $value) = explode('=', $line);
  $returnArray[$key] = $value;
}
return $returnArray;

However all I'm getting back is:

Array ( [key1] => value3 [key2] => value2 [key3] => value4 )

I've also tried

$loadFile = file('file.txt');
$returnArray = array();
foreach ($loadFile as $line) {
  $startWith = substr(trim($line), 0, 2);
    if (empty($line) || $startWith == '//') {
          continue;
  }
  $exp = explode('=', $line);
  $returnArray[$exp[0]] = $exp[1];
}
return $returnArray;

Which also gives me the same result. I've also tried an array_merge which just shoved everything into an array with a numeric value as the key.

Body:
For fun, just turn them into array syntax for an ini file and parse it:

$result = parse_ini_string(str_replace('=', '[]=', file_get_contents('file.txt')));

More fun, turn them into a query string and parse it:

parse_str(str_replace('=', '[]=', implode('&', file('file.txt'))), $result);

Both yield:

Array
(
    [key1] => Array
        (
            [0] => value1
            [1] => value2
            [2] => value3
        )

    [key2] => Array
        (
            [0] => value1
            [1] => value2
        )

    [key3] => Array
        (
            [0] => value1
            [1] => value2
            [2] => value3
            [3] => value4
        )
)


来源: stackexchange

问:
how to update or remove the nested object inside ngrx entities?
how to update or remove nested object inside ngrx entities for example I want to delete the first element which has the 19 id from (charter.entities.scopes.data) as it shown in the bellow stored json object inside my ngrx store

```<code> charter: {
      ids: [
        1
      ],
      entities: {
        '1': {
          id: 1,
          projectName: 'Some Project',
          projectCode: '899',
          projectUniqueCode: '674a9596-50ee',
          projectStatus: 'construction',
          budgetCode: 'CC34',
          projectTypeOne: 'Goods',
          projectTypeTwo: 'New',
          donorName: 'Elza Hills',
          scopes: {
            data: [
              {
                id: 19,
                module: 'Miss Cassandra Cartwright I',
                description: 'In tempore quia asperiores aut ea cum optio minima nemo est et aspernatur est repudiandae voluptas ipsum.',
                time: '2018-01-23 15:37:36'
              },

              {
                id: 43,
                module: 'Leanne Douglas',
                description: 'Occaecati facere eligendi esse esse nostrum in et vitae assumenda molestias omnis quis sit qui aut omnis est.',
                time: '2018-01-23 15:37:36'
              },
            ]
          },
          assumptions: {
            data: [
              {
                id: 29,
                assumption: 'Doloremque quo nihil minima ad optio perspiciatis asperiores debitis mollitia at debitis porro quia nam accusantium illo consequatur labore cum.',
                comments: 'Inventore ut pariatur id laboriosam recusandae soluta quo sunt impedit aut velit.'
              },
              {
                id: 164,
                assumption: 'Dolores quam aut possimus sint fugiat natus quos quaerat saepe facilis harum molestiae.',
                comments: 'Cumque quis magni illo dolore quas nam officiis dolores enim soluta doloribus in sed eum ut sunt.'
              },
            ]
          },
</code>```

The Reducer

```<code>export interface State extends EntityState<ProjectsCharter> {
  isLoading: boolean;
  isLoaded: boolean;
  selectedProjectsId: any;
}

export const adapter: EntityAdapter<ProjectsCharter> = createEntityAdapter({
  selectId: (state: ProjectsCharter) => state.id,
  sortComparer: false
});

export const initialState = adapter.getInitialState({
  isLoading: false,
  isLoaded: false,
  selectedProjectsId: null
});

export function reducer(state = initialState, action: CharterActions) {
  switch (action.type) {
    case CharterActionTypes.loadCharterSuccess:
      return {
        ...adapter.addOne(action.payload['data'], state),
        isLoading: false,
        isLoaded: true
      };
    case CharterActionTypes.updateScopeOnParent:
      const scopeEntity = { ...state.entities[action.payload.param] };
      scopeEntity.scopes.data = scopeEntity.scopes.data.map(item => {
        if (item.id === action.payload.id) {
          item.module = action.payload.module;
        }
        return item;
      });

      return {
        ...adapter.updateOne(scopeEntity, state)
      };
    default:
      return {
        ...state
      };
  }
}
</code>```

I can update and modify the nestad object with this reducer but the problem is 1- it's a little bit complex and also show me in terminal in compile time error TS2339: Property 'map' does not exist on type 'Scope'. also Argument of type '{ id: string; projectName: string; projectStatus: string; projectCode: string; projectUniqueCode:...' is not assignable to parameter of type 'Update<ProjectsCharter>'.

答:
Let me preface this by saying the ideal solution is to normalize your entities with something like normalizr.  That said, here is a solution that works for me:

Make a deep clone of the state object

Use the Javascript delete method on the cloned object

Pass this new object as the new state

So let's assume your state looks something like this:

{
  entities: {
   '1': {
     prop1: 'val1',
     nested: {
      '1': {
        prop1: 'val1'
      },
      '2': {
        prop2: 'val2'
      }
    }
  }
}
```

<p>If your goal is to delete <code>entities[1].nested[1]</code>, just use the following code (note that I am using the lodash library):</p>

<pre class="lang-js prettyprint-override"><code>import * as _ from 'lodash'

on(Actions.sampleDeleteAction, (state) => {
  const clonedState = _.cloneDeep(state);

  delete clonedState.entities[1].nested[1];

  return { ...clonedState };
}
</code>```

Obviously, you would want to add props to your action that contain the necessary index values you are using to delete rather than explicitly using indexes as in the example entities[1].nested[1].

ContentLicense: CC BY-SA 3.0

Body:
how to update or remove nested object inside ngrx entities for example I want to delete the first element which has the 19 id from (charter.entities.scopes.data) as it shown in the bellow stored json object inside my ngrx store

 charter: {
      ids: [
        1
      ],
      entities: {
        '1': {
          id: 1,
          projectName: 'Some Project',
          projectCode: '899',
          projectUniqueCode: '674a9596-50ee',
          projectStatus: 'construction',
          budgetCode: 'CC34',
          projectTypeOne: 'Goods',
          projectTypeTwo: 'New',
          donorName: 'Elza Hills',
          scopes: {
            data: [
              {
                id: 19,
                module: 'Miss Cassandra Cartwright I',
                description: 'In tempore quia asperiores aut ea cum optio minima nemo est et aspernatur est repudiandae voluptas ipsum.',
                time: '2018-01-23 15:37:36'
              },

              {
                id: 43,
                module: 'Leanne Douglas',
                description: 'Occaecati facere eligendi esse esse nostrum in et vitae assumenda molestias omnis quis sit qui aut omnis est.',
                time: '2018-01-23 15:37:36'
              },
            ]
          },
          assumptions: {
            data: [
              {
                id: 29,
                assumption: 'Doloremque quo nihil minima ad optio perspiciatis asperiores debitis mollitia at debitis porro quia nam accusantium illo consequatur labore cum.',
                comments: 'Inventore ut pariatur id laboriosam recusandae soluta quo sunt impedit aut velit.'
              },
              {
                id: 164,
                assumption: 'Dolores quam aut possimus sint fugiat natus quos quaerat saepe facilis harum molestiae.',
                comments: 'Cumque quis magni illo dolore quas nam officiis dolores enim soluta doloribus in sed eum ut sunt.'
              },
            ]
          },

The Reducer

export interface State extends EntityState<ProjectsCharter> {
  isLoading: boolean;
  isLoaded: boolean;
  selectedProjectsId: any;
}

export const adapter: EntityAdapter<ProjectsCharter> = createEntityAdapter({
  selectId: (state: ProjectsCharter) => state.id,
  sortComparer: false
});

export const initialState = adapter.getInitialState({
  isLoading: false,
  isLoaded: false,
  selectedProjectsId: null
});

export function reducer(state = initialState, action: CharterActions) {
  switch (action.type) {
    case CharterActionTypes.loadCharterSuccess:
      return {
        ...adapter.addOne(action.payload['data'], state),
        isLoading: false,
        isLoaded: true
      };
    case CharterActionTypes.updateScopeOnParent:
      const scopeEntity = { ...state.entities[action.payload.param] };
      scopeEntity.scopes.data = scopeEntity.scopes.data.map(item => {
        if (item.id === action.payload.id) {
          item.module = action.payload.module;
        }
        return item;
      });

      return {
        ...adapter.updateOne(scopeEntity, state)
      };
    default:
      return {
        ...state
      };
  }
}

I can update and modify the nestad object with this reducer but the problem is 1- it's a little bit complex and also show me in terminal in compile time error TS2339: Property 'map' does not exist on type 'Scope'. also Argument of type '{ id: string; projectName: string; projectStatus: string; projectCode: string; projectUniqueCode:...' is not assignable to parameter of type 'Update<ProjectsCharter>'.

Body:
Let me preface this by saying the ideal solution is to normalize your entities with something like normalizr.  That said, here is a solution that works for me:

Make a deep clone of the state object

Use the Javascript delete method on the cloned object

Pass this new object as the new state

So let's assume your state looks something like this:

{
  entities: {
   '1': {
     prop1: 'val1',
     nested: {
      '1': {
        prop1: 'val1'
      },
      '2': {
        prop2: 'val2'
      }
    }
  }
}

If your goal is to delete entities[1].nested[1], just use the following code (note that I am using the lodash library):

import * as _ from 'lodash'

on(Actions.sampleDeleteAction, (state) => {
  const clonedState = _.cloneDeep(state);

  delete clonedState.entities[1].nested[1];

  return { ...clonedState };
}

Obviously, you would want to add props to your action that contain the necessary index values you are using to delete rather than explicitly using indexes as in the example entities[1].nested[1].

ContentLicense: CC BY-SA 4.0


问:
SourceCodeScanner not calling visitMethodCall
I'm playing with lint rules.

All my ResourceXmlDetector run without problems and pass all the tests. But Detector(), SourceCodeScanner are failing because they return 0 warnings/errors, and the reason is visitMethodCall not being called thus context.report wont either.

My code is similar to android lint-checks, for instance CipherGetInstanceDetector, but I can't find my mistake.

```<code>@Suppress("UnstableApiUsage")
class MySourceDetector : Detector(), SourceCodeScanner {

    override fun getApplicableMethodNames() = listOf("...")

    override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
        if (context.evaluator.isMemberInClass(method, "...")) {
            ...
            reportUsage(context, node)
        }
    }

    private fun reportUsage(context: JavaContext, node: UCallExpression) {
        context.report(
            issue = ISSUE,
            scope = node,
            location = context.getCallLocation(
                call = node,
                includeReceiver = true,
                includeArguments = true
            ),
            message = ISSUE.getExplanation(TextFormat.RAW)
        )
    }

    companion object {
        @JvmField
        val ISSUE = Issue.create(...Scope.JAVA_FILE_SCOPE)
    }
}
</code>```

The only methods stopping in break points are Issue.create and getApplicableMethodNames(). What's missing?

答:
I didn't think this was important but my test rule was:

```<code> TestLintTask.lint()
            .files(TestFiles.kotlin("Test.kt", input).indented())
            .issues(ISSUE)
            .run()
            .expectWarningCount(1)
            .expect(output)
</code>```

And replacing kotlin("Test.kt", input) with kotlin(input) made it work...

Body:
I'm playing with lint rules.

All my ResourceXmlDetector run without problems and pass all the tests. But Detector(), SourceCodeScanner are failing because they return 0 warnings/errors, and the reason is visitMethodCall not being called thus context.report wont either.

My code is similar to android lint-checks, for instance CipherGetInstanceDetector, but I can't find my mistake.

@Suppress("UnstableApiUsage")
class MySourceDetector : Detector(), SourceCodeScanner {

    override fun getApplicableMethodNames() = listOf("...")

    override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
        if (context.evaluator.isMemberInClass(method, "...")) {
            ...
            reportUsage(context, node)
        }
    }

    private fun reportUsage(context: JavaContext, node: UCallExpression) {
        context.report(
            issue = ISSUE,
            scope = node,
            location = context.getCallLocation(
                call = node,
                includeReceiver = true,
                includeArguments = true
            ),
            message = ISSUE.getExplanation(TextFormat.RAW)
        )
    }

    companion object {
        @JvmField
        val ISSUE = Issue.create(...Scope.JAVA_FILE_SCOPE)
    }
}

The only methods stopping in break points are Issue.create and getApplicableMethodNames(). What's missing?

Body:
I didn't think this was important but my test rule was:

 TestLintTask.lint()
            .files(TestFiles.kotlin("Test.kt", input).indented())
            .issues(ISSUE)
            .run()
            .expectWarningCount(1)
            .expect(output)

And replacing kotlin("Test.kt", input) with kotlin(input) made it work...


问:
Deleting an extension which has no means to be uninstalled
I have an extension installed in VS 2010  but there is no option to uninstall it from extension manager or add/remove programs (if it was in an msi, can't remember). Add-in manager gives me the option to disable the extension, but it still comes up when I restart VS2010 (always running in Administrator mode btw). I also looked in my Local folder under VisualStudio/Extensions.

I've checked the registry for entries for this extension, but can't find anything, either. What can I do (except reinstall VS2010)?

Thanks

答: It has uninstall option in installer. Download it again (using your link) and click uninstall.


问:
powershell - class / function declaration issues
I'm new to powershell so I am not sure why I am getting the following error:

missing closing '}' in statement block or type definition

But everything looks consistent from my java knowledge.

I have a class { method1{} method2{} } type of structure happening as follows:

case use

```<code>class DoSomething1
{

    <#
         .SYNOPSIS whatever
         .PARAMETER somevalue1
         .PARAMETER somevalue2
         ... etc
    #>

    function DoSomething1
    {
        [cmdletbinding()]
        param
        (
            [parameter(Mandatory = $true, HelpMessage = "help yourself")]
             $somevalue3
        )
     # will add code to constructor later
    }
}
</code>```

I'm unsure what the problem is with it, because when I write my method as:

alternative

```<code>class DoSomething1
{
   DoSomething1()
   {
      # whatever
   }
}
</code>```

I'm not sure if there's an advantage of one versus the other, or if I'm m using the keyword function out of context, but I wanted to apply the concept of cmdletbindings and get-help information further on by using <# .SYNOPSIS details #> in front of the function command.

Does anyone know what i am doing incorrectly?

答:
As mentioned in the comments, PowerShell is not quite like Java or C#, and classes are sort of "second-class citizens" with respect to PowerShell language features.

Instead, in PowerShell we can implement cmdlet-like behavior with something called advanced functions - like the one you already have:

```<code>function DoSomething1
{
    [cmdletbinding()]
    param
    (
        [parameter(Mandatory = $true, HelpMessage = "help yourself")]
         $somevalue3
    )

    # do something with $somevalue3
}
</code>```

PowerShell scripts are evaluated line by line, so if you put one of these function definitions in a script, any subsequent call to DoSomething1 will invoke that function.

Depending in the size and scope of what you're trying to automate, you might find yourself with a large number of small self-contained functions like this. To better organize your code in larger projects, you can split function definitions into individual files, and then use the . invocation operator to execute them, which will make the function(s) "persist" in the current scope:

Get-Something.ps1:

function Get-Something
{
  [CmdletBinding()]
  param(<# ... #>)
  # ...
}
```

<p><code>Export-Somewhere.ps1</code>:</p>

<pre class="lang-bsh prettyprint-override"><code>function Export-Somewhere
{
  [CmdletBinding()]
  param(<# ... #>)
  # ...
}
</code>```

script.ps1:

# Import functions from other the script files
. .\Get-Something.ps1
. .\Export-Somewhere.ps1

# Now we can use the functions in here
Get-Something |Export-Somewhere
```

For more broadly reusable tools, you might want to consider organizing your functions into modules

Body:
I'm new to powershell so I am not sure why I am getting the following error:

missing closing '}' in statement block or type definition

But everything looks consistent from my java knowledge.

I have a class { method1{} method2{} } type of structure happening as follows:

case use

class DoSomething1
{

    <#
         .SYNOPSIS whatever
         .PARAMETER somevalue1
         .PARAMETER somevalue2
         ... etc
    #>

    function DoSomething1
    {
        [cmdletbinding()]
        param
        (
            [parameter(Mandatory = $true, HelpMessage = "help yourself")]
             $somevalue3
        )
     # will add code to constructor later
    }
}

I'm unsure what the problem is with it, because when I write my method as:

alternative

class DoSomething1
{
   DoSomething1()
   {
      # whatever
   }
}

I'm not sure if there's an advantage of one versus the other, or if I'm m using the keyword function out of context, but I wanted to apply the concept of cmdletbindings and get-help information further on by using <# .SYNOPSIS details #> in front of the function command.

Does anyone know what i am doing incorrectly?

Body:
As mentioned in the comments, PowerShell is not quite like Java or C#, and classes are sort of "second-class citizens" with respect to PowerShell language features.

Instead, in PowerShell we can implement cmdlet-like behavior with something called advanced functions - like the one you already have:

function DoSomething1
{
    [cmdletbinding()]
    param
    (
        [parameter(Mandatory = $true, HelpMessage = "help yourself")]
         $somevalue3
    )

    # do something with $somevalue3
}

PowerShell scripts are evaluated line by line, so if you put one of these function definitions in a script, any subsequent call to DoSomething1 will invoke that function.

Depending in the size and scope of what you're trying to automate, you might find yourself with a large number of small self-contained functions like this. To better organize your code in larger projects, you can split function definitions into individual files, and then use the . invocation operator to execute them, which will make the function(s) "persist" in the current scope:

Get-Something.ps1:

function Get-Something
{
  [CmdletBinding()]
  param(<# ... #>)
  # ...
}

Export-Somewhere.ps1:

function Export-Somewhere
{
  [CmdletBinding()]
  param(<# ... #>)
  # ...
}

script.ps1:

# Import functions from other the script files
. .\Get-Something.ps1
. .\Export-Somewhere.ps1

# Now we can use the functions in here
Get-Something |Export-Somewhere

For more broadly reusable tools, you might want to consider organizing your functions into modules


问:
PHP-FPM processes causing high CPU usage on VPS
A few months ago we moved our e-commerce website to a VPS, after struggling with poor performance from shared hosting platforms. To handle an increase in traffic (avg. 300-500 daily visitors), we tweaked our PHP-FPM settings and increased the Max Children from 5 (default) to 50. Currently, PHP-FPM "pool" processes are requiring high CPU usage (30-40%). Any tips to make those "pool" processes use less CPU? Thanks!

VPS Specs:

2 CPUs

Intel(R) Xeon(R) CPU E5-2630 v4 @ 2.20GHz

4GB RAM

WHM: Centos 7.8 v86.0.18

Ecommerce platform: OpenCart 3.0.2.0

答:
FPM has nothing to do with the CPU usage, it's your code.

That said, don't just arbitrarily change the number of worker processes without a sound basis to do so, eg: actual resource statistics.

With 300-500 daily users you're really unlikely to have 50 concurrent requests unless you're doing something strange.

The place I'm currently working at peaks at about 600 concurrent users and a grand maximum of 15-20 connections actually simultaneously doing anything. [Note: Much larger/broader backing infrastructure]

Do you really expect each CPU core to handle 25 simultaneous requests?

Can you reasonably fit 50 requests' worth of RAM into that 4GB?

Are you fine with those 50 idle PHP processes each consuming 10-15MB RAM apiece?

All that said, we can't tell you what in your code is using up resources, and it's not possible for you to post enough information for us to make more than a vague guess. You need to put things in place to measure where that resource usage is happening, profile your code to find out why, and tune your infrastructure configuration to accommodate your specific application requirements.

There's no one "magic" config that works for everyone.


问:
How to see if the list contains consecutive numbers
I want to test if a list contains consecutive integers and no repetition of numbers.
For example, if I have

```<code>l = [1, 3, 5, 2, 4, 6]
</code>```

It should return True.

How should I check if the list contains up to n consecutive numbers without modifying the original list?
I thought about copying the list and removing each number that appears in the original list and if the list is empty then it will return True.

Is there a better way to do this?

答:
list must be sorted!

```<code>lst = [9,10,11,12,13,14,15,16]

final = True if len( [ True for x in lst[:-1] for y in lst[1:] if x + 1 == y ] ) == len(lst[1:]) else False
</code>```

i don't know how efficient this is but it should do the trick.

Body:
I want to test if a list contains consecutive integers and no repetition of numbers.
For example, if I have

l = [1, 3, 5, 2, 4, 6]

It should return True.

How should I check if the list contains up to n consecutive numbers without modifying the original list?
I thought about copying the list and removing each number that appears in the original list and if the list is empty then it will return True.

Is there a better way to do this?

Body:
list must be sorted!

lst = [9,10,11,12,13,14,15,16]

final = True if len( [ True for x in lst[:-1] for y in lst[1:] if x + 1 == y ] ) == len(lst[1:]) else False

i don't know how efficient this is but it should do the trick.


问:
Value undefined after a function
I have one class with one fuction in it, and another class that will import the first class and use that function. After the function operates i need one value, but i am not getting any value afte the function.

First class:

```<code>export class MoveEff {

    checkEffect(effectFaceOff1,moveEff1,moveEff2){
        if ( effectFaceOff1=== 'grassgrass') {

            moveEff1 = 10;
            console.log(moveEff1);

        }
    }
}
</code>```

Second class :

```<code>
import { Component, OnInit } from '@angular/core';
import {GenIService} from "../Pokemons/gen-i.service";
import {MovesService} from "../Moves/moves.service";
import {MoveDataClass} from "../MoveDATA/move-data-class";
import {MoveEff} from "../MoveDATA/move-eff";

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage implements OnInit {

  effectFaceOff1;
  moveEff1;
  moveEff2;

constructor(private moveeff: MoveEff) {}

 this.moveeff.checkEffect(this.effectFaceOff1,this.moveEff1,this.moveEff2);

 console.log(this.moveEff1,this.moveEff2);

</code>```

On the last console.log i should be seeing the 10 value of moveEff1, but it appears undefined.

Why? and how can i solve it?

答:
i don't know where you are getting  effectFaceOff1, moveEff1 and moveEff2 from, but if they are @Input, their values cannot be retrieved in the constructor.

In that case, you should move your code to the ngOnInit:

```<code>ngOnInit() {
  this.moveeff.checkEffect(this.effectFaceOff1,this.moveEff1,this.moveEff2);
  console.log(this.moveEff1,this.moveEff2);
}
</code>```

Last but not least, MoveEff should be made an Injectable in order to provide it to your class:

```<code>@Injectable({ providedIn: 'root' })
export class MoveEff {
  checkEffect(effectFaceOff1,moveEff1,moveEff2){
    if ( effectFaceOff1 === 'grassgrass') {
        moveEff1 = 10;
        console.log(moveEff1);
    }
  }
}
</code>```

Title: Value undefined after a function

Body:
I have one class with one fuction in it, and another class that will import the first class and use that function. After the function operates i need one value, but i am not getting any value afte the function.

First class:

export class MoveEff {

    checkEffect(effectFaceOff1,moveEff1,moveEff2){
        if ( effectFaceOff1=== 'grassgrass') {

            moveEff1 = 10;
            console.log(moveEff1);

        }
    }
}

Second class :

import { Component, OnInit } from '@angular/core';
import {GenIService} from "../Pokemons/gen-i.service";
import {MovesService} from "../Moves/moves.service";
import {MoveDataClass} from "../MoveDATA/move-data-class";
import {MoveEff} from "../MoveDATA/move-eff";

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage implements OnInit {

  effectFaceOff1;
  moveEff1;
  moveEff2;

constructor(private moveeff: MoveEff) {}

 this.moveeff.checkEffect(this.effectFaceOff1,this.moveEff1,this.moveEff2);

 console.log(this.moveEff1,this.moveEff2);

On the last console.log i should be seeing the 10 value of moveEff1, but it appears undefined.

Why? and how can i solve it?

Body:
i don't know where you are getting  effectFaceOff1, moveEff1 and moveEff2 from, but if they are @Input, their values cannot be retrieved in the constructor.

In that case, you should move your code to the ngOnInit:

ngOnInit() {
  this.moveeff.checkEffect(this.effectFaceOff1,this.moveEff1,this.moveEff2);
  console.log(this.moveEff1,this.moveEff2);
}

Last but not least, MoveEff should be made an Injectable in order to provide it to your class:

@Injectable({ providedIn: 'root' })
export class MoveEff {
  checkEffect(effectFaceOff1,moveEff1,moveEff2){
    if ( effectFaceOff1 === 'grassgrass') {
        moveEff1 = 10;
        console.log(moveEff1);
    }
  }
}


问:
How to display values of an array as colored lattice points?
I am creating a python program that simulates the folding of proteins. My protein is 19 elements (amino acids) long, with each element specified by a number between 1 and 20. I used randint() to create the protein and created an array of zeros.

The protein is initially unfolded and centered horizontally in a 21 by 21 array. So the nonzero values of the array are on the 10th row. I imported matplotlib and used matshow() to display this arrangement:

.

What I like about this figure is that it is apparent that the protein is made up of different amino acids/elements, as shown by color of each square. I would like to keep this feature. However, instead of squares I would like each element to show up as a colored dot connected to its neighbor by a link, or on a grid:

 .

I have provided my code below. To summarize my questions:

1) How do I display the elements in an array as circles or as lattice points with links connecting the dots?

2) How do I do the above while keeping the colors the same for each element?

3) How do I specify that the zero-values (currently purple) should be white? I don't have a preference for the other colors, I would like a white background.

```<code>import numpy as np
import matplotlib.pyplot as plt
import random
from matplotlib.colors import ListedColormap

###create grid
rows = 21
columns = 21
x = np.zeros(rows) #create arrays for the x- and y-positions
y = np.zeros(columns)
middle = (rows-1)/2

grid = np.zeros((rows,columns)) #grid = [row][columns] = value = grid[j][i]

###create protein:
n = 20
protein = []
while len(protein) < n:
     a = random.randint(1, 20)
     protein = np.append(protein, a)

###specify initial condition with protein unfolded along y=0
j = int(middle)
i = 1
while i < rows-1:
    grid[j][i] = protein[i]
    i = i+1
print(grid)
plt.matshow(grid)
</code>```

答:
Colored dots can be drawn with plt.scatter(). Straight line segments with plt.plot().

To represent the folding, an array of 0s, 1s and -1s can represent the folding going straight, turning right or turning left.

To draw the plot, create x and y positions while applying the folding directions. These positions serve to draw the line segments (plt.plot) and as well as the colored dots (plt.scatter). To have 20 different colors, the 'tab20' colormap could be used.

Here is some example code to get you started.

```<code>import numpy as np
from matplotlib import pyplot as plt

n = 20
protein = np.random.randint(1, 20, n) # n numbers between 1 and 19
folds = np.zeros(n, dtype=np.int) # default there are no turns
folds[9] = -1 # turn left after protein 9
folds[11] = 1 # turn right after protein 11
folds[15] = -1 # turn left after protein 15

dir = (1, 0)
pos = (0, 0)
x = np.zeros_like(protein)
y = np.zeros_like(protein)
for i, (p, f) in enumerate(zip(protein, folds)):
    x[i], y[i] = pos
    if f == 1:  # turn right
        dir = (dir[1], -dir[0])
    elif f == -1:  # turn left
        dir = (-dir[1], dir[0])
    pos = (pos[0] + dir[0], pos[1] + dir[1])
plt.plot(x, y, 'k-', zorder=0)  # straight lines
# large dots colored via the 'tab20' colormap, set zorder=3 to draw the dots on top of the lines
plt.scatter(x, y, c=protein, cmap='tab20', s=200, zorder=3)

plt.axis('off') # don't show the axes
plt.margins(0.1) # enough margin so that the large scatter dots don't touch the borders
plt.gca().set_aspect('equal') # equal distances in x and y direction
plt.show()
</code>```

To draw something similar to example 'd':

n = 15
protein = np.random.randint(1, 20, n)
folds = [1, -1, 1, -1, 0, 0, 0, 1, -1, 0, 0, 1, -1, -1, 0]
```

<p><img src="https://i.stack.imgur.com/1jow4.png" alt="similar to example d"></p>

<p>PS: With the following adaptions, gridlines are shown:</p>

<pre class="lang-py prettyprint-override"><code>from matplotlib.ticker import MultipleLocator, NullFormatter

plt.axis('on')
ax = plt.gca()
ax.xaxis.set_major_locator(MultipleLocator(1))
ax.xaxis.set_major_formatter(NullFormatter())
ax.yaxis.set_major_locator(MultipleLocator(1))
ax.yaxis.set_major_formatter(NullFormatter())
ax.tick_params(axis='both', length=0)
plt.grid(True, ls=':')
</code>```

Body:
I am creating a python program that simulates the folding of proteins. My protein is 19 elements (amino acids) long, with each element specified by a number between 1 and 20. I used randint() to create the protein and created an array of zeros.

The protein is initially unfolded and centered horizontally in a 21 by 21 array. So the nonzero values of the array are on the 10th row. I imported matplotlib and used matshow() to display this arrangement:

.

What I like about this figure is that it is apparent that the protein is made up of different amino acids/elements, as shown by color of each square. I would like to keep this feature. However, instead of squares I would like each element to show up as a colored dot connected to its neighbor by a link, or on a grid:

 .

I have provided my code below. To summarize my questions:

1) How do I display the elements in an array as circles or as lattice points with links connecting the dots?

2) How do I do the above while keeping the colors the same for each element?

3) How do I specify that the zero-values (currently purple) should be white? I don't have a preference for the other colors, I would like a white background.

import numpy as np
import matplotlib.pyplot as plt
import random
from matplotlib.colors import ListedColormap

###create grid
rows = 21
columns = 21
x = np.zeros(rows) #create arrays for the x- and y-positions
y = np.zeros(columns)
middle = (rows-1)/2

grid = np.zeros((rows,columns)) #grid = [row][columns] = value = grid[j][i]

###create protein:
n = 20
protein = []
while len(protein) < n:
     a = random.randint(1, 20)
     protein = np.append(protein, a)

###specify initial condition with protein unfolded along y=0
j = int(middle)
i = 1
while i < rows-1:
    grid[j][i] = protein[i]
    i = i+1
print(grid)
plt.matshow(grid)

Body:
Colored dots can be drawn with plt.scatter(). Straight line segments with plt.plot().

To represent the folding, an array of 0s, 1s and -1s can represent the folding going straight, turning right or turning left.

To draw the plot, create x and y positions while applying the folding directions. These positions serve to draw the line segments (plt.plot) and as well as the colored dots (plt.scatter). To have 20 different colors, the 'tab20' colormap could be used.

Here is some example code to get you started.

import numpy as np
from matplotlib import pyplot as plt

n = 20
protein = np.random.randint(1, 20, n) # n numbers between 1 and 19
folds = np.zeros(n, dtype=np.int) # default there are no turns
folds[9] = -1 # turn left after protein 9
folds[11] = 1 # turn right after protein 11
folds[15] = -1 # turn left after protein 15

dir = (1, 0)
pos = (0, 0)
x = np.zeros_like(protein)
y = np.zeros_like(protein)
for i, (p, f) in enumerate(zip(protein, folds)):
    x[i], y[i] = pos
    if f == 1:  # turn right
        dir = (dir[1], -dir[0])
    elif f == -1:  # turn left
        dir = (-dir[1], dir[0])
    pos = (pos[0] + dir[0], pos[1] + dir[1])
plt.plot(x, y, 'k-', zorder=0)  # straight lines
# large dots colored via the 'tab20' colormap, set zorder=3 to draw the dots on top of the lines
plt.scatter(x, y, c=protein, cmap='tab20', s=200, zorder=3)

plt.axis('off') # don't show the axes
plt.margins(0.1) # enough margin so that the large scatter dots don't touch the borders
plt.gca().set_aspect('equal') # equal distances in x and y direction
plt.show()

To draw something similar to example 'd':

n = 15
protein = np.random.randint(1, 20, n)
folds = [1, -1, 1, -1, 0, 0, 0, 1, -1, 0, 0, 1, -1, -1, 0]

PS: With the following adaptions, gridlines are shown:

from matplotlib.ticker import MultipleLocator, NullFormatter

plt.axis('on')
ax = plt.gca()
ax.xaxis.set_major_locator(MultipleLocator(1))
ax.xaxis.set_major_formatter(NullFormatter())
ax.yaxis.set_major_locator(MultipleLocator(1))
ax.yaxis.set_major_formatter(NullFormatter())
ax.tick_params(axis='both', length=0)
plt.grid(True, ls=':')


问:
How to add dummy values to a table in SQL
Probably not the most descriptive title but sometimes it's hard to put stupid SQL problems(the kind that make you want to put booze in your coffee to get through the day) into english. I basically have the following two tables:

TABLE1

```<code>studentid   firstname   lastname    counter cmid    score   lessond
328000            Jacob           GG             5  189 90  103950
328111            Jacob           GG            6   189 80  103951
3283333           Tyler           GR            5   189 70  103950
3244444            William    FL               5    189 70  103950
3280000            Sean           DA           5    189 80  103950
3283333            Sean           DA             6  189 90  103951
</code>```

TABLE 2

```<code>Lesson2ClassroomAssignmentId    Counter
103956                      1
103947                           2
103948                          3
103949                          4
103950                          5
103951                          6
</code>```

The first table is basically a list of students and their scores for certain lessons(numbered 1-6 and denoted by counter). The second table is a list of all possible lessons(numbered 1-6 and denoted by counter).

What I need to do is get a table that has a row for each student and each lesson, regardless of whether or not the student has a row in table 1 for that lesson or not.

Ive tried doing something like selecting * from table 1 and UNIONING it with the results of the 2nd table LEFT OUTER JOINED with the first table where counter <> counter but havent been able to get the results I desired.

If anyone has any suggestions(dont need the full answer, just pointed in the right direction) I'd owe ya one!! Alternatively, feel free to make fun of me if this post is unintelligable as it barely makes sense to me and I'm the one who has been staring at it for the past 6 hours ;)

Ciao Ciao,

Tim

DESIRED OUTPUT:

The Desired output would be:

TABLE FINAL

```<code> studentid     firstname   lastname    counter cmid    score   lessond
    3280000         Jacob       GG      1 NULL, NULL, NULL
    3280000         Jacob       GG 2 NULL, NULL, NULL
    3280000         Jacob       GG 3 NULL, NULL, NULL
    3280000         Jacob       GG 4 NULL, NULL, NULL
    3280000         Jacob       GG 5 189, 90, 103950
    3280000         Jacob       GG 6 189, 80, 103951
    3283333         Tyler       GR 1, NULL, NULL, NULL
    3283333         Tyler       GR 2, NULL, NULL, NULL
    3283333         Tyler       GR 3, NULL, NULL, NULL
    3283333         Tyler       GR 4, NULL, NULL, NULL
    3283333         Tyler       GR 5, 189, 70, 103950
    3283333         Tyler       GR 6, NULL, NULL, NULL
</code>```

So basically taking any row with actual lesson data for a student from table one and supplementing it with dummy rows with no score data for each lesson(from table 2) that the student didnt have a score for.

答:
If you find your time to be valuable just purchase one of the commercial products designed to provide this type of functionality.

I'm very happy with EMS Data Generator for SQL Server which is priced under $100...

EMS Data Generator for SQL Server is
  an impressive tool for generating test
  data to SQL Server database tables
  with the possibility to save and edit
  scripts. The utility can help you to
  simulate the database production
  environment and allows you to populate
  several SQL Server database tables
  with test data simultaneously, define
  tables and fields for generating data,
  set value ranges, generate SQL Server
  char fields by mask, define lists of
  values manually or select them from
  SQL queries, set generation parameters
  for each field type and has many other
  features to generate SQL Server test
  data in a simple and direct way. Data
  Generator for SQL Server also provides
  a console application, which allows
  you to generate SQL Server test data
  in one-touch by using generation
  templates.

Body:
Probably not the most descriptive title but sometimes it's hard to put stupid SQL problems(the kind that make you want to put booze in your coffee to get through the day) into english. I basically have the following two tables:

TABLE1

studentid   firstname   lastname    counter cmid    score   lessond
328000            Jacob           GG             5  189 90  103950
328111            Jacob           GG            6   189 80  103951
3283333           Tyler           GR            5   189 70  103950
3244444            William    FL               5    189 70  103950
3280000            Sean           DA           5    189 80  103950
3283333            Sean           DA             6  189 90  103951

TABLE 2

Lesson2ClassroomAssignmentId    Counter
103956                      1
103947                           2
103948                          3
103949                          4
103950                          5
103951                          6

The first table is basically a list of students and their scores for certain lessons(numbered 1-6 and denoted by counter). The second table is a list of all possible lessons(numbered 1-6 and denoted by counter).

What I need to do is get a table that has a row for each student and each lesson, regardless of whether or not the student has a row in table 1 for that lesson or not.

Ive tried doing something like selecting * from table 1 and UNIONING it with the results of the 2nd table LEFT OUTER JOINED with the first table where counter <> counter but havent been able to get the results I desired.

If anyone has any suggestions(dont need the full answer, just pointed in the right direction) I'd owe ya one!! Alternatively, feel free to make fun of me if this post is unintelligable as it barely makes sense to me and I'm the one who has been staring at it for the past 6 hours ;)

Ciao Ciao,

Tim

DESIRED OUTPUT:

The Desired output would be:

TABLE FINAL

 studentid     firstname   lastname    counter cmid    score   lessond
    3280000         Jacob       GG      1 NULL, NULL, NULL
    3280000         Jacob       GG 2 NULL, NULL, NULL
    3280000         Jacob       GG 3 NULL, NULL, NULL
    3280000         Jacob       GG 4 NULL, NULL, NULL
    3280000         Jacob       GG 5 189, 90, 103950
    3280000         Jacob       GG 6 189, 80, 103951
    3283333         Tyler       GR 1, NULL, NULL, NULL
    3283333         Tyler       GR 2, NULL, NULL, NULL
    3283333         Tyler       GR 3, NULL, NULL, NULL
    3283333         Tyler       GR 4, NULL, NULL, NULL
    3283333         Tyler       GR 5, 189, 70, 103950
    3283333         Tyler       GR 6, NULL, NULL, NULL

So basically taking any row with actual lesson data for a student from table one and supplementing it with dummy rows with no score data for each lesson(from table 2) that the student didnt have a score for.


问:
MST in directed graph
there are prim and Kruskal algorithms to find mst in polynomial time
I wonder, Are there any algorithms to find MST in a directed acyclic graph in linear time?</p>

答:
The equivalent of an MST in a directed graph is called an optimum branching or minimum-cost arborescence and there are several good algorithms for finding one. The most famous is probably the Chu-Edmonds-Liu algorithm, which can be implemented in time O(mn) in a straightforward way and time O(m + n log n) using more clever data structures.

Hope this helps!

Title: MST in directed graph


问:
“Microsoft.VisualBasic.FileIO does not exist”. How to include this library in my project?
So I am trying to parse a .csv file with columns that may include their own comma characters.

Answers here and here say that the best way to easily handle this without writing my own line-by-line parser would be to use the Microsoft.VisualBasic.FileIO library.

Unfortunately, when i try to include this in my project I get the common error:

```<code>'File.IO' does not exist in the namespace "Microsoft.VisualBasic" (are you missing an assembly reference?)
</code>```

Fixes for this issue here and here all say that I need to use the Reference Manager to add Microsoft.VisualBasic to my project, but my reference manager does not have the Assemblies, with Framework and Extensions subgroups tabs that the official help documents say to use to add the package to my project. I have attached a screenshot of my Reference Manager window here. The Projects tab just shows a list of all the projects in my solution and the Shared Projects tab is blank.

I have also checked to see if I should include a NuGet package instead, but that did not solve the problem at all.

答:
I ended up using the CSVHelper library which installs fine with NuGet and handled the comma-contained columns perfectly and even could be configured to ignore blank lines and headers.

I do not know why VisualBasic.FileIO could not be added to my project, why the best solutions from 6+ years ago said to use this library, or why my Reference Manager window is different from what official help says it should be, but I solved my root problem so here's hoping I don't actually need to use the Reference Manager in the future for anything.

Body:
So I am trying to parse a .csv file with columns that may include their own comma characters.

Answers here and here say that the best way to easily handle this without writing my own line-by-line parser would be to use the Microsoft.VisualBasic.FileIO library.

Unfortunately, when i try to include this in my project I get the common error:

'File.IO' does not exist in the namespace "Microsoft.VisualBasic" (are you missing an assembly reference?)

Fixes for this issue here and here all say that I need to use the Reference Manager to add Microsoft.VisualBasic to my project, but my reference manager does not have the Assemblies, with Framework and Extensions subgroups tabs that the official help documents say to use to add the package to my project. I have attached a screenshot of my Reference Manager window here. The Projects tab just shows a list of all the projects in my solution and the Shared Projects tab is blank.

I have also checked to see if I should include a NuGet package instead, but that did not solve the problem at all.


问:
How to install the beta version of @nuxtjs/auth?
When I run npm view @nuxtjs/auth dist-tags, I get { latest: '4.9.1' }, the development version is not listed. How are we supposed to install it ?

```<code>$ npm install @nuxtjs/auth@beta
npm ERR! code ETARGET
npm ERR! notarget No matching version found for @nuxtjs/auth@beta.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/me/.npm/_logs/2020-05-28T23_02_05_605Z-debug.log
</code>```

答:
The beta version is in another package:</p>

```<code>npm i @nuxtjs/auth-next
</code>```

Body:
When I run npm view @nuxtjs/auth dist-tags, I get { latest: '4.9.1' }, the development version is not listed. How are we supposed to install it ?

$ npm install @nuxtjs/auth@beta
npm ERR! code ETARGET
npm ERR! notarget No matching version found for @nuxtjs/auth@beta.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/me/.npm/_logs/2020-05-28T23_02_05_605Z-debug.log

Body:
The beta version is in another package:

npm i @nuxtjs/auth-next


问:
ASP.NET gridview control rowCreated function after button click
I am wondering how can I control the execution order of server-side functions(asp.net and C#) for a post_back request?

For example:
I have two buttons on my webpage, and click on any of them will trigger a post_back request. The post back will update a gridview in an AJAXUpdatePanel. I found that if I click button1, the functions execution order is:
button1_onclick();
gridview1_rowCreated();

However, if I click button 2, the order is:
gridview1_rowCreated();
button2_onClick();

Is there anyway to make the order consistent? Any comment is truly appreciated.

答:
Try to Bind the grid on PreRender Event of the Page or Do the Task on the Button Clicked event and make sure you have first time binding done using an</p>

```<code>if(!IsPostBack)
{
 Code Binding Grid.
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Try to Bind the grid on PreRender Event of the Page or Do the Task on the Button Clicked event and make sure you have first time binding done using an

if(!IsPostBack)
{
 Code Binding Grid.
}


问:
Vuforia edit default script
I'm trying to use Vuforia to make an aplication that matches images for corresponding to a same group.
For example if the camera show a the image of a zebra stored and the image of a dog stored it should set a text saying correct, but if the camera catches the image of the zebra and the image of a car it should set a text saying error.
I have completed the camera camera recognition but i don't know to handle the code to avoid the default behavior.
I suppose i have to modify these part of the C# script

```<code>protected virtual void OnTrackingFound()
    {
        if (mTrackableBehaviour)
        {

            Debug.Log("Trackable " + mTrackableBehaviour.TrackableName);

            var rendererComponents = mTrackableBehaviour.GetComponentsInChildren<Renderer>(true);
            var colliderComponents = mTrackableBehaviour.GetComponentsInChildren<Collider>(true);
            var canvasComponents = mTrackableBehaviour.GetComponentsInChildren<Canvas>(true);

            // Enable rendering:
            foreach (var component in rendererComponents)
                component.enabled = true;

            // Enable colliders:
            foreach (var component in colliderComponents)
                component.enabled = true;

            // Enable canvas':
            foreach (var component in canvasComponents)
                component.enabled = true;
        }
    }

    protected virtual void OnTrackingLost()
    {
        if (mTrackableBehaviour)
        {
            var rendererComponents = mTrackableBehaviour.GetComponentsInChildren<Renderer>(true);
            var colliderComponents = mTrackableBehaviour.GetComponentsInChildren<Collider>(true);
            var canvasComponents = mTrackableBehaviour.GetComponentsInChildren<Canvas>(true);

            // Disable rendering:
            foreach (var component in rendererComponents)
                component.enabled = false;

            // Disable colliders:
            foreach (var component in colliderComponents)
                component.enabled = false;

            // Disable canvas':
            foreach (var component in canvasComponents)
                component.enabled = false;
        }
    }
</code>```

But i don't know how to do it, so if someone can help me giving ideas o the solution it will be apreciated.

Thank you very much.

答:
A simpler way is to create a new script attached to every marker you want to compare. For example:

```<code>public class MyMarker : MonoBehaviour
{
  public string markerName; //Can be edited in the inspector
}
</code>```

Then you need to know that when Vuforia founds or losts a Marker, the GameObject is enabled or disabled.

You can have specific behaviour when found (enabled) or lost (disable) with the methods OnEnable() and OnDisable().

```<code>public class MyMarker : MonoBehaviour
{
  public string markerName; //Can be edited in the inspector

  void OnEnable()
  {
    //The object is active
  }

  void OnDisable()
  {
    //The object is inactive
  }
}
</code>```

Also, you can know if a game object is active with myGameObject.activeInHierarchy.

With this you now which markers are active.

Title: Vuforia edit default script

Body:
I'm trying to use Vuforia to make an aplication that matches images for corresponding to a same group.
For example if the camera show a the image of a zebra stored and the image of a dog stored it should set a text saying correct, but if the camera catches the image of the zebra and the image of a car it should set a text saying error.
I have completed the camera camera recognition but i don't know to handle the code to avoid the default behavior.
I suppose i have to modify these part of the C# script

protected virtual void OnTrackingFound()
    {
        if (mTrackableBehaviour)
        {

            Debug.Log("Trackable " + mTrackableBehaviour.TrackableName);

            var rendererComponents = mTrackableBehaviour.GetComponentsInChildren<Renderer>(true);
            var colliderComponents = mTrackableBehaviour.GetComponentsInChildren<Collider>(true);
            var canvasComponents = mTrackableBehaviour.GetComponentsInChildren<Canvas>(true);

            // Enable rendering:
            foreach (var component in rendererComponents)
                component.enabled = true;

            // Enable colliders:
            foreach (var component in colliderComponents)
                component.enabled = true;

            // Enable canvas':
            foreach (var component in canvasComponents)
                component.enabled = true;
        }
    }

    protected virtual void OnTrackingLost()
    {
        if (mTrackableBehaviour)
        {
            var rendererComponents = mTrackableBehaviour.GetComponentsInChildren<Renderer>(true);
            var colliderComponents = mTrackableBehaviour.GetComponentsInChildren<Collider>(true);
            var canvasComponents = mTrackableBehaviour.GetComponentsInChildren<Canvas>(true);

            // Disable rendering:
            foreach (var component in rendererComponents)
                component.enabled = false;

            // Disable colliders:
            foreach (var component in colliderComponents)
                component.enabled = false;

            // Disable canvas':
            foreach (var component in canvasComponents)
                component.enabled = false;
        }
    }

But i don't know how to do it, so if someone can help me giving ideas o the solution it will be apreciated.

Thank you very much.

Body:
A simpler way is to create a new script attached to every marker you want to compare. For example:

public class MyMarker : MonoBehaviour
{
  public string markerName; //Can be edited in the inspector
}

Then you need to know that when Vuforia founds or losts a Marker, the GameObject is enabled or disabled.

You can have specific behaviour when found (enabled) or lost (disable) with the methods OnEnable() and OnDisable().

public class MyMarker : MonoBehaviour
{
  public string markerName; //Can be edited in the inspector

  void OnEnable()
  {
    //The object is active
  }

  void OnDisable()
  {
    //The object is inactive
  }
}

Also, you can know if a game object is active with myGameObject.activeInHierarchy.

With this you now which markers are active.


问:
Delete last 3 characters if they are equal to something
(without affecting the char level formatting in the cell)

I've already posted a similar question, but I unfortunately I realized I couldn't use any of the solutions because all of them removed all the formatting in the cells :(

I have a code that replaces various text strings. It looks like this (+ some more IFs):

```<code>Sub Fix()
  Dim X As Long, Cell As Range
  For Each Cell In Selection
    For X = Len(Cell.Text) To 1 Step -1
      If Cell.Characters(X, 3).Text = ", ," Then Cell.Characters(X, 3).Text = ","
      If Cell.Characters(X, 3).Text = ", (" Then Cell.Characters(X, 3).Text = " ("
      If Cell.Characters(X, 3).Text = ", [" Then Cell.Characters(X, 3).Text = " ["
      If Cell.Characters(X, 3).Text = ", -" Then Cell.Characters(X, 3).Text = " -"
      If Cell.Characters(1, 3).Text = "abc" Then Cell.Characters(1, 3).Text = ""
    Next
  Next
End Sub
</code>```

The last line of my code deletes abc if this is contained at the beginning of the selected cell(s).

I am looking to find out how to delete abc when this is contained at the end of the selected cell(s).

But it's really important for me to preserve all the original formatting in the cells (text size, colors, bold/italic/underline letters etc).

Please bear in mind that I am a complete beginner and I don't know anything about programming. I've copied the code above from the internet and just changed the values.

Thank you in advance for your help.

答:
Replace Characters (Preserve Formatting)

```<code>Option Explicit

Sub FixIt()

    Const NoC As Long = 3
    Const Special As String = "abc"
    Dim Source As Variant: Source = Array(", ,", ", (", ", [", ", -")
    Dim Target As Variant: Target = Array(",", " (", " [", " -")

    Dim Cell As Range
    Dim UB As Long: UB = UBound(Source)
    Dim i As Long, x As Long
    Dim Current As String

    For Each Cell In Selection
        Current = Cell.Characters(Len(Cell.Text) - NoC + 1, NoC).Text
        If Current = Special Then _
           Cell.Characters(Len(Cell.Text) - NoC + 1, NoC).Delete
        For x = Len(Cell.Text) - NoC + 1 To 1 Step -1
            GoSub replaceCurrent
        Next
    Next

    Exit Sub

replaceCurrent:
    Current = Cell.Characters(x, NoC).Text
    For i = 0 To UB
        If Current = Source(i) Then Current = Target(i): Exit For
    Next
    If i <= UB Then Cell.Characters(x, NoC).Text = Current
    Return

End Sub
</code>```

Body:
(without affecting the char level formatting in the cell)

I've already posted a similar question, but I unfortunately I realized I couldn't use any of the solutions because all of them removed all the formatting in the cells :(

I have a code that replaces various text strings. It looks like this (+ some more IFs):

Sub Fix()
  Dim X As Long, Cell As Range
  For Each Cell In Selection
    For X = Len(Cell.Text) To 1 Step -1
      If Cell.Characters(X, 3).Text = ", ," Then Cell.Characters(X, 3).Text = ","
      If Cell.Characters(X, 3).Text = ", (" Then Cell.Characters(X, 3).Text = " ("
      If Cell.Characters(X, 3).Text = ", [" Then Cell.Characters(X, 3).Text = " ["
      If Cell.Characters(X, 3).Text = ", -" Then Cell.Characters(X, 3).Text = " -"
      If Cell.Characters(1, 3).Text = "abc" Then Cell.Characters(1, 3).Text = ""
    Next
  Next
End Sub

The last line of my code deletes abc if this is contained at the beginning of the selected cell(s).

I am looking to find out how to delete abc when this is contained at the end of the selected cell(s).

But it's really important for me to preserve all the original formatting in the cells (text size, colors, bold/italic/underline letters etc).

Please bear in mind that I am a complete beginner and I don't know anything about programming. I've copied the code above from the internet and just changed the values.

Thank you in advance for your help.

Body:
Replace Characters (Preserve Formatting)

Option Explicit

Sub FixIt()

    Const NoC As Long = 3
    Const Special As String = "abc"
    Dim Source As Variant: Source = Array(", ,", ", (", ", [", ", -")
    Dim Target As Variant: Target = Array(",", " (", " [", " -")

    Dim Cell As Range
    Dim UB As Long: UB = UBound(Source)
    Dim i As Long, x As Long
    Dim Current As String

    For Each Cell In Selection
        Current = Cell.Characters(Len(Cell.Text) - NoC + 1, NoC).Text
        If Current = Special Then _
           Cell.Characters(Len(Cell.Text) - NoC + 1, NoC).Delete
        For x = Len(Cell.Text) - NoC + 1 To 1 Step -1
            GoSub replaceCurrent
        Next
    Next

    Exit Sub

replaceCurrent:
    Current = Cell.Characters(x, NoC).Text
    For i = 0 To UB
        If Current = Source(i) Then Current = Target(i): Exit For
    Next
    If i <= UB Then Cell.Characters(x, NoC).Text = Current
    Return

End Sub


问:
Variogram manual calculation
I have a question about variograms please.
In fact, I only have points with their Z(pi) values and the distances between them. (For example a point p1(z(p1),d(p1,p2), d(p1,p3),.., d(p1,pn)))
I want to estimate the variogram for those having a specific k distance between them.

答:
I actually understood how to get that:

Forming multiple pairs {z(si),z(sj)} that have the same separation
vectors h = si −sj and estimate correlation from them.

Calculating the Estimated value for each pair : (Z(Si) - Z(Si + h))

Calculating The probability of each pair : P(Z(S=Si)- Z(S=Si + h))

The the semi variance will be just : 1/2 var[(Z(si)- Z(si + h))]

Title: Variogram manual calculation


问:
STL + typedefs vs. OOP, best practices?
I "grew up" learning to set up data structures using OOP. But now as I learn more about C++, STL, and Boost, I find that many of my data structure needs can be met by combining STL classes into more complex composites like: </p>

```<code>typedef std::map<std::string, std::map<std::string, int> > CSVData;
</code>```

<p>Obviously there are limits to this when I need to mix data types, but generally I find myself avoiding OOP when I can in favor of these STL composites for their simplicity. Is this a common progression? Are there best-practice rules-of-thumb for when it's better to define your own class? Are there common pitfalls to this? </p>

答:
It is always best to program against an interface, rather than a concrete implementation.

As @adrian-mccarthy mentioned, C++ is a multi-paradigm language, and there are several different ways to program against an interface.

One way is to use OOP.

Another way, is to write templates.

Instead of using the typedef directly, templatize your client code to work with any container implementing the same concepts. (The Boost Static Assertions and Boost Concept Checking facilities may be helpful in locking down precisely which concepts your algorithm depends on.)

The decision to templatize is, of course, implies certain non-trivial changes to your code organization (moving method implementations into headers).  It is up to you to decide if it is appropriate.

Title: STL + typedefs vs. OOP, best practices?

Body:
I "grew up" learning to set up data structures using OOP. But now as I learn more about C++, STL, and Boost, I find that many of my data structure needs can be met by combining STL classes into more complex composites like:

typedef std::map<std::string, std::map<std::string, int> > CSVData;

Obviously there are limits to this when I need to mix data types, but generally I find myself avoiding OOP when I can in favor of these STL composites for their simplicity. Is this a common progression? Are there best-practice rules-of-thumb for when it's better to define your own class? Are there common pitfalls to this?


问:
VB.Net in Visual Studio 2015 - "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
everyone.  I hope all are well during this pandemic.

I have a maintenance program in which I have been using the following feature successfully for years until we recently changed from Windows 7 to Windows 10.

Among other things, my program displays PDF documents that were scanned into Xerox Docushare.  The documents are associated with a reference Id from a bar code.  There could be one or dozens of scan instances for a single coversheet (barcode).

I have a user defined control (ucDocushare_DocumentSetByRefID.vb), which has a ListView (lvwDocuments) and a TabControl (tcDocumentScanInstances).  The functionality is that the ListView displays the coversheets that represent the scan sets.  When a user clicks an item in the ListView, the TabControl is displayed with a tab for each individual scan instance related to the selected coversheet.

Every now and then, for no apparent reason, when I click a coversheet item in the ListView, the program directly terminates.  When debugging in Visual Studio 2015, following message is displayed.  It is not related to the size of the document or to the number of scan instances.  I have brought up very large documents with many pages successfully.  I also have had many scan instances successfully appear.

System.AccessViolationException was unhandled
Message: An unhandled exception of type 'System.AccessViolationException' occurred in System.Windows.Forms.dll

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Also, a Break Mode tab appears with the following:

The application is in break mode

Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code).

The error occurs immediately when stepping from the End Sub line of this:

```<code>Private Sub tcDocumentScanInstances_DrawItem(sender As Object, e As DrawItemEventArgs) _
    Handles tcDocumentScanInstances.DrawItem
</code>```

This DrawItem sub does a little font managing for the tab labels but primarily determines which icon is displayed on those labels.

This is the full code for that sub:

```<code>'Color code document tab labels and display appropriate icons.
 Private Sub tcDocumentScanInstances_DrawItem(sender As Object, e As DrawItemEventArgs) _
    Handles tcDocumentScanInstances.DrawItem

Try

    Dim intTabIndex As Integer = 0

    '  Identify which TabPage is currently selected
    Dim SelectedTab As TabPage = tcDocumentScanInstances.TabPages(e.Index)

    '  Get the area of the header of this TabPage.  This is the actual label for the tab page.
    Dim HeaderRect As Rectangle = tcDocumentScanInstances.GetTabRect(e.Index)

    '  Create a Brush to paint the Text
    Dim sbBlackBrush As New SolidBrush(Color.Black)
    Dim sbRedBrush As New SolidBrush(Color.Red)

    '  Set the Alignment of the Text
    Dim sf As New StringFormat()
    sf.Alignment = StringAlignment.Center
    sf.LineAlignment = StringAlignment.Center

    '  Paint the Text using the appropriate Bold setting
    Dim intIconPositionX As Integer = HeaderRect.Left + 4
    Dim intIconPositionY As Integer = HeaderRect.Top + 7

    Dim dicImages As New Dictionary(Of String, Image)()
    dicImages("Tab" & e.Index) = Nothing  ' Set the value of the "variable"

    tcDocumentScanInstances.Padding = New System.Drawing.Point(15, 15)
    'tcDocumentScanInstances.TabPages(0).Width = 500

    If Convert.ToBoolean(e.State And DrawItemState.Selected) Then

        Dim BoldFont As New Font(tcDocumentScanInstances.Font.Name, tcDocumentScanInstances.Font.Size, FontStyle.Bold)

        e.Graphics.FillRectangle(New SolidBrush(SystemColors.ButtonFace), e.Bounds)

        If tcDocumentScanInstances.TabPages(e.Index).Tag Is Nothing Then
            tcDocumentScanInstances.TabPages(e.Index).Tag = ""
        End If

        Select Case tcDocumentScanInstances.TabPages(e.Index).Tag.ToString
            Case "Delete", "Delete Client Letter", "Excessive Documentation"
                dicImages("Tab" & e.Index) = ilTabIconsForDocumentScanInstances.Images(IconsForDocumentScanInstances.DeleteDocument)
                e.Graphics.DrawString(SelectedTab.Text, BoldFont, sbRedBrush, HeaderRect, sf)
                sbRedBrush.Dispose()
            Case "No Documentation"
                dicImages("Tab" & e.Index) = ilTabIconsForDocumentScanInstances.Images(IconsForDocumentScanInstances.NoDocumentExists)
                e.Graphics.DrawString(SelectedTab.Text, BoldFont, sbBlackBrush, HeaderRect, sf)
                sbBlackBrush.Dispose()
            Case Else
                dicImages("Tab" & e.Index) = ilTabIconsForDocumentScanInstances.Images(IconsForDocumentScanInstances.DocumentExists)
                e.Graphics.DrawString(SelectedTab.Text, BoldFont, sbBlackBrush, HeaderRect, sf)
                sbBlackBrush.Dispose()
        End Select

        e.Graphics.DrawImage(dicImages("Tab" & e.Index), intIconPositionX, intIconPositionY)

    Else

        e.Graphics.FillRectangle(New SolidBrush(Color.FromArgb(128, 167, 240)), e.Bounds)
        If tcDocumentScanInstances.TabPages(e.Index).Tag Is Nothing Then
            tcDocumentScanInstances.TabPages(e.Index).Tag = ""
        End If

        Select Case tcDocumentScanInstances.TabPages(e.Index).Tag.ToString
            Case "Delete", "Delete Client Letter", "Excessive Documentation"
                dicImages("Tab" & e.Index) = ilTabIconsForDocumentScanInstances.Images(IconsForDocumentScanInstances.DeleteDocument)
                e.Graphics.DrawString(SelectedTab.Text, e.Font, sbRedBrush, HeaderRect, sf)
                sbRedBrush.Dispose()
            Case "No Documentation", "Missing Documentation"
                dicImages("Tab" & e.Index) = ilTabIconsForDocumentScanInstances.Images(IconsForDocumentScanInstances.NoDocumentExists)
                e.Graphics.DrawString(SelectedTab.Text, e.Font, sbBlackBrush, HeaderRect, sf)
                sbBlackBrush.Dispose()
            Case Else
                dicImages("Tab" & e.Index) = ilTabIconsForDocumentScanInstances.Images(IconsForDocumentScanInstances.DocumentExists)
                e.Graphics.DrawString(SelectedTab.Text, e.Font, sbBlackBrush, HeaderRect, sf)
                sbBlackBrush.Dispose()
        End Select

        e.Graphics.DrawImage(dicImages("Tab" & e.Index), intIconPositionX, intIconPositionY)

    End If

    If tcDocumentScanInstances.SelectedTab.Tag Is Nothing Then
        tcDocumentScanInstances.SelectedTab.Tag = ""
    End If

    If frmCaseMaintenance.tcDocumentationByRefID.TabPages( _
        frmCaseMaintenance.tcDocumentationByRefID.SelectedIndex).Tag.ToString.Length >= "Delete".Length Then

        If frmCaseMaintenance.tcDocumentationByRefID.TabPages( _
            frmCaseMaintenance.tcDocumentationByRefID.SelectedIndex).Tag.ToString.Substring(0, "Delete".Length) <> "Delete" Then
            'The coversheet and all associated documents, together, are not marked for deletion.

            Select Case tcDocumentScanInstances.SelectedTab.Tag.ToString.Trim
                Case "Delete", "Delete Client Letter"
                    btnMarkCurrentDocumentForDeletion.Enabled = False
                    btnUnmarkCurrentDocumentForDeletion.Enabled = True
                Case "No Documentation", "Missing Documentation"
                    'A tab displaying a message that there is no documentation can not be deleted.
                    btnMarkCurrentDocumentForDeletion.Enabled = False
                    btnUnmarkCurrentDocumentForDeletion.Enabled = False
                Case Else
                    btnMarkCurrentDocumentForDeletion.Enabled = True
                    btnUnmarkCurrentDocumentForDeletion.Enabled = False
            End Select

        Else 'the coversheet and all associated documents, together, are marked for deletion.

            btnMarkCurrentDocumentForDeletion.Enabled = False
            btnUnmarkCurrentDocumentForDeletion.Enabled = False

        End If

    Else 'the coversheet and all associated documents, together, are marked for deletion.

            Select Case tcDocumentScanInstances.SelectedTab.Tag.ToString.Trim
                Case "Delete", "Delete Client Letter"
                    btnMarkCurrentDocumentForDeletion.Enabled = False
                    btnUnmarkCurrentDocumentForDeletion.Enabled = True
                Case "No Documentation", "Missing Documentation"
                    'A tab displaying a message that there is no documentation can not be deleted.
                    btnMarkCurrentDocumentForDeletion.Enabled = False
                    btnUnmarkCurrentDocumentForDeletion.Enabled = False
                Case Else
                    btnMarkCurrentDocumentForDeletion.Enabled = True
                    btnUnmarkCurrentDocumentForDeletion.Enabled = False
            End Select

    End If

Catch ex As Exception

    If Err.Description = "A generic error occurred in GDI+." Then
        'This error probably was tripped by this line:  e.Graphics.FillRectangle(New SolidBrush(SystemColors.ButtonFace), e.Bounds)
        'tabDocumentScanInstance_DrawItem() will execute again without that line causing a problem, so we do nothing here.
    Else
            MessageBox.Show( _
                 "Class Name:  " & Me.Name & vbCrLf & _
                 "Sub Name:  tcDocumentScanInstances_DrawItem()" & vbCrLf & _
                 "Error Number:  " & Err.Number & vbCrLf & _
                 "Message:  " & Err.Description, _
                 gstrExecutableName & " - Error", _
                 MessageBoxButtons.OK, MessageBoxIcon.Error)
    End If

End Try

End Sub
</code>```

PRODUCTS IN USE

Microsoft Visual Studio Professional 2015
Version 14.0.25431.01 Update 3

Microsoft .NET Framework
Version 4.8.03752

ATTEMPTED SOLUTIONS

rebooted computer

deleted executable and generated a new one

executed “netsh winsock reset” in the Command Prompt and rebooted; also executed “netsh winsock reset catalog” in the Command Prompt and rebooted

changed the "Platform target" from "Any CPU" to "x86".

[Project Name] Properties ->”Compile” tab -> “Compile Options” -> “Target CPU”

Rebuild/Build project.
(I changed it back to “Any CPU” when “x86” failed to correct the problem.)

It was suggested that the following be unchecked in Visual Studio.  It already was.

```<code>   Tools menu ->Options -> Debugging -> General -> Uncheck this option "Suppress JIT optimization on module load"
</code>```

replaced System.Windows.Forms.dll located here with another copy of the file (same date/time and file size):  C:\Windows\Microsoft.NET\Framework\v2.0.50727

I appreciate input.

答:
May I suggest you open your project as an Administration :

Right click VS2015-> Run as Administrator and Open your project.

Debug your code. I think your problem is not in code but accessing resources. It says here :

You can do nearly everything in the Visual Studio IDE as a normal
  user, but, you need administrator permissions to complete the
  following tasks:

Toolbox ||    Adding classic COM controls to the Toolbox. || Using the
  Toolbox

As you mentioned

'I have a user defined control (ucDocushare_DocumentSetByRefID.vb)'

Body:
everyone.  I hope all are well during this pandemic.

I have a maintenance program in which I have been using the following feature successfully for years until we recently changed from Windows 7 to Windows 10.

Among other things, my program displays PDF documents that were scanned into Xerox Docushare.  The documents are associated with a reference Id from a bar code.  There could be one or dozens of scan instances for a single coversheet (barcode).

I have a user defined control (ucDocushare_DocumentSetByRefID.vb), which has a ListView (lvwDocuments) and a TabControl (tcDocumentScanInstances).  The functionality is that the ListView displays the coversheets that represent the scan sets.  When a user clicks an item in the ListView, the TabControl is displayed with a tab for each individual scan instance related to the selected coversheet.

Every now and then, for no apparent reason, when I click a coversheet item in the ListView, the program directly terminates.  When debugging in Visual Studio 2015, following message is displayed.  It is not related to the size of the document or to the number of scan instances.  I have brought up very large documents with many pages successfully.  I also have had many scan instances successfully appear.

System.AccessViolationException was unhandled
Message: An unhandled exception of type 'System.AccessViolationException' occurred in System.Windows.Forms.dll

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Also, a Break Mode tab appears with the following:

The application is in break mode

Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code).

The error occurs immediately when stepping from the End Sub line of this:

Private Sub tcDocumentScanInstances_DrawItem(sender As Object, e As DrawItemEventArgs) _
    Handles tcDocumentScanInstances.DrawItem

This DrawItem sub does a little font managing for the tab labels but primarily determines which icon is displayed on those labels.

This is the full code for that sub:

'Color code document tab labels and display appropriate icons.
 Private Sub tcDocumentScanInstances_DrawItem(sender As Object, e As DrawItemEventArgs) _
    Handles tcDocumentScanInstances.DrawItem

Try

    Dim intTabIndex As Integer = 0

    '  Identify which TabPage is currently selected
    Dim SelectedTab As TabPage = tcDocumentScanInstances.TabPages(e.Index)

    '  Get the area of the header of this TabPage.  This is the actual label for the tab page.
    Dim HeaderRect As Rectangle = tcDocumentScanInstances.GetTabRect(e.Index)

    '  Create a Brush to paint the Text
    Dim sbBlackBrush As New SolidBrush(Color.Black)
    Dim sbRedBrush As New SolidBrush(Color.Red)

    '  Set the Alignment of the Text
    Dim sf As New StringFormat()
    sf.Alignment = StringAlignment.Center
    sf.LineAlignment = StringAlignment.Center

    '  Paint the Text using the appropriate Bold setting
    Dim intIconPositionX As Integer = HeaderRect.Left + 4
    Dim intIconPositionY As Integer = HeaderRect.Top + 7

    Dim dicImages As New Dictionary(Of String, Image)()
    dicImages("Tab" & e.Index) = Nothing  ' Set the value of the "variable"

    tcDocumentScanInstances.Padding = New System.Drawing.Point(15, 15)
    'tcDocumentScanInstances.TabPages(0).Width = 500

    If Convert.ToBoolean(e.State And DrawItemState.Selected) Then

        Dim BoldFont As New Font(tcDocumentScanInstances.Font.Name, tcDocumentScanInstances.Font.Size, FontStyle.Bold)

        e.Graphics.FillRectangle(New SolidBrush(SystemColors.ButtonFace), e.Bounds)

        If tcDocumentScanInstances.TabPages(e.Index).Tag Is Nothing Then
            tcDocumentScanInstances.TabPages(e.Index).Tag = ""
        End If

        Select Case tcDocumentScanInstances.TabPages(e.Index).Tag.ToString
            Case "Delete", "Delete Client Letter", "Excessive Documentation"
                dicImages("Tab" & e.Index) = ilTabIconsForDocumentScanInstances.Images(IconsForDocumentScanInstances.DeleteDocument)
                e.Graphics.DrawString(SelectedTab.Text, BoldFont, sbRedBrush, HeaderRect, sf)
                sbRedBrush.Dispose()
            Case "No Documentation"
                dicImages("Tab" & e.Index) = ilTabIconsForDocumentScanInstances.Images(IconsForDocumentScanInstances.NoDocumentExists)
                e.Graphics.DrawString(SelectedTab.Text, BoldFont, sbBlackBrush, HeaderRect, sf)
                sbBlackBrush.Dispose()
            Case Else
                dicImages("Tab" & e.Index) = ilTabIconsForDocumentScanInstances.Images(IconsForDocumentScanInstances.DocumentExists)
                e.Graphics.DrawString(SelectedTab.Text, BoldFont, sbBlackBrush, HeaderRect, sf)
                sbBlackBrush.Dispose()
        End Select

        e.Graphics.DrawImage(dicImages("Tab" & e.Index), intIconPositionX, intIconPositionY)

    Else

        e.Graphics.FillRectangle(New SolidBrush(Color.FromArgb(128, 167, 240)), e.Bounds)
        If tcDocumentScanInstances.TabPages(e.Index).Tag Is Nothing Then
            tcDocumentScanInstances.TabPages(e.Index).Tag = ""
        End If

        Select Case tcDocumentScanInstances.TabPages(e.Index).Tag.ToString
            Case "Delete", "Delete Client Letter", "Excessive Documentation"
                dicImages("Tab" & e.Index) = ilTabIconsForDocumentScanInstances.Images(IconsForDocumentScanInstances.DeleteDocument)
                e.Graphics.DrawString(SelectedTab.Text, e.Font, sbRedBrush, HeaderRect, sf)
                sbRedBrush.Dispose()
            Case "No Documentation", "Missing Documentation"
                dicImages("Tab" & e.Index) = ilTabIconsForDocumentScanInstances.Images(IconsForDocumentScanInstances.NoDocumentExists)
                e.Graphics.DrawString(SelectedTab.Text, e.Font, sbBlackBrush, HeaderRect, sf)
                sbBlackBrush.Dispose()
            Case Else
                dicImages("Tab" & e.Index) = ilTabIconsForDocumentScanInstances.Images(IconsForDocumentScanInstances.DocumentExists)
                e.Graphics.DrawString(SelectedTab.Text, e.Font, sbBlackBrush, HeaderRect, sf)
                sbBlackBrush.Dispose()
        End Select

        e.Graphics.DrawImage(dicImages("Tab" & e.Index), intIconPositionX, intIconPositionY)

    End If

    If tcDocumentScanInstances.SelectedTab.Tag Is Nothing Then
        tcDocumentScanInstances.SelectedTab.Tag = ""
    End If

    If frmCaseMaintenance.tcDocumentationByRefID.TabPages( _
        frmCaseMaintenance.tcDocumentationByRefID.SelectedIndex).Tag.ToString.Length >= "Delete".Length Then

        If frmCaseMaintenance.tcDocumentationByRefID.TabPages( _
            frmCaseMaintenance.tcDocumentationByRefID.SelectedIndex).Tag.ToString.Substring(0, "Delete".Length) <> "Delete" Then
            'The coversheet and all associated documents, together, are not marked for deletion.

            Select Case tcDocumentScanInstances.SelectedTab.Tag.ToString.Trim
                Case "Delete", "Delete Client Letter"
                    btnMarkCurrentDocumentForDeletion.Enabled = False
                    btnUnmarkCurrentDocumentForDeletion.Enabled = True
                Case "No Documentation", "Missing Documentation"
                    'A tab displaying a message that there is no documentation can not be deleted.
                    btnMarkCurrentDocumentForDeletion.Enabled = False
                    btnUnmarkCurrentDocumentForDeletion.Enabled = False
                Case Else
                    btnMarkCurrentDocumentForDeletion.Enabled = True
                    btnUnmarkCurrentDocumentForDeletion.Enabled = False
            End Select

        Else 'the coversheet and all associated documents, together, are marked for deletion.

            btnMarkCurrentDocumentForDeletion.Enabled = False
            btnUnmarkCurrentDocumentForDeletion.Enabled = False

        End If

    Else 'the coversheet and all associated documents, together, are marked for deletion.

            Select Case tcDocumentScanInstances.SelectedTab.Tag.ToString.Trim
                Case "Delete", "Delete Client Letter"
                    btnMarkCurrentDocumentForDeletion.Enabled = False
                    btnUnmarkCurrentDocumentForDeletion.Enabled = True
                Case "No Documentation", "Missing Documentation"
                    'A tab displaying a message that there is no documentation can not be deleted.
                    btnMarkCurrentDocumentForDeletion.Enabled = False
                    btnUnmarkCurrentDocumentForDeletion.Enabled = False
                Case Else
                    btnMarkCurrentDocumentForDeletion.Enabled = True
                    btnUnmarkCurrentDocumentForDeletion.Enabled = False
            End Select

    End If

Catch ex As Exception

    If Err.Description = "A generic error occurred in GDI+." Then
        'This error probably was tripped by this line:  e.Graphics.FillRectangle(New SolidBrush(SystemColors.ButtonFace), e.Bounds)
        'tabDocumentScanInstance_DrawItem() will execute again without that line causing a problem, so we do nothing here.
    Else
            MessageBox.Show( _
                 "Class Name:  " & Me.Name & vbCrLf & _
                 "Sub Name:  tcDocumentScanInstances_DrawItem()" & vbCrLf & _
                 "Error Number:  " & Err.Number & vbCrLf & _
                 "Message:  " & Err.Description, _
                 gstrExecutableName & " - Error", _
                 MessageBoxButtons.OK, MessageBoxIcon.Error)
    End If

End Try

End Sub

PRODUCTS IN USE

Microsoft Visual Studio Professional 2015
Version 14.0.25431.01 Update 3

Microsoft .NET Framework
Version 4.8.03752

ATTEMPTED SOLUTIONS

rebooted computer

deleted executable and generated a new one

executed “netsh winsock reset” in the Command Prompt and rebooted; also executed “netsh winsock reset catalog” in the Command Prompt and rebooted

changed the "Platform target" from "Any CPU" to "x86".

[Project Name] Properties ->”Compile” tab -> “Compile Options” -> “Target CPU”

Rebuild/Build project.
(I changed it back to “Any CPU” when “x86” failed to correct the problem.)

It was suggested that the following be unchecked in Visual Studio.  It already was.

   Tools menu ->Options -> Debugging -> General -> Uncheck this option "Suppress JIT optimization on module load"

replaced System.Windows.Forms.dll located here with another copy of the file (same date/time and file size):  C:\Windows\Microsoft.NET\Framework\v2.0.50727

I appreciate input.


问:
AccessibilityService setServiceInfo method's changes don't seem to take effect outside onServiceConnected
Quoting the docs for setServiceInfo
"You can call this method any time but the info will be picked up after the system has bound to this service and when this method is called thereafter."

Accessibility has been enabled for my app and I have set the serviceInfo inside the onServiceConnected method and I am receiving events for those apps and all is well.

Now ,the problem is I'm trying to modify the package list by calling setServiceInfo outside the onServiceConnected method, but the changes are not taking effect( i.e i'm still receiving events from the packages in the package list specified earlier which are absent in the modified package list).

```<code>@Override
protected void onServiceConnected() {
    AccessibilityServiceInfo accessibilityServiceInfo = new AccessibilityServiceInfo();
    accessibilityServiceInfo.packageNames = new String[]{"packageA","packageB"};
    accessibilityServiceInfo.eventTypes = AccessibilityEvent.TYPE_VIEW_CLICKED | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
            | AccessibilityEvent.TYPE_VIEW_SCROLLED | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
            | AccessibilityEvent.TYPE_VIEW_FOCUSED | AccessibilityEvent.TYPE_VIEW_SELECTED
            | AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
    accessibilityServiceInfo.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
    accessibilityServiceInfo.notificationTimeout = 100;
    accessibilityServiceInfo.flags = (AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS | accessibilityServiceInfo.flags);
    setServiceInfo(accessibilityServiceInfo);
}

@Override
public void onAccessibilityEvent(final AccessibilityEvent event) {
    AccessibilityServiceInfo serviceInfo = getServiceInfo();
    serviceInfo.packageNames = new String[]{"packageA"};
    setServiceInfo(serviceInfo);
}
</code>```

accessibility_service_config.xml

```<code><accessibility-service
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:canRetrieveWindowContent="true"
    android:description="@string/accessibility_service_description"
/>
</code>```

So, the question is how do I add/remove packages inside the Accessibility Service depending on the Accessibility events I receive later?

答:
Encountered the same issue recently. After looking into source code (SDK 8.1), it seems the API description gives the wrong expectation that set packageNames to some app list then set it null would make the service receive all events again.

The reason is in two methods below. In #1 when you it calls setServiceInfo(info) where the info.mPackageNames is null, here it just skips it and never set service.mPackageNames to null. In #2, when mPackageNames already includes the apps you added before. So later mPackageNames.isEmpty() will always be false.

http://androidxref.com/8.1.0_r33/xref/frameworks/base/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java#mPackageNames

1

line 2786 - 2788

```<code>if (packageNames != null) {
      mPackageNames.addAll(Arrays.asList(packageNames));
}
</code>```

2

```<code>1428 Set<String> packageNames = service.mPackageNames;
1429        String packageName = (event.getPackageName() != null)
1430                ? event.getPackageName().toString() : null;
1431
1432        return (packageNames.isEmpty() || packageNames.contains(packageName));
</code>```

Body:
Quoting the docs for setServiceInfo
"You can call this method any time but the info will be picked up after the system has bound to this service and when this method is called thereafter."

Accessibility has been enabled for my app and I have set the serviceInfo inside the onServiceConnected method and I am receiving events for those apps and all is well.

Now ,the problem is I'm trying to modify the package list by calling setServiceInfo outside the onServiceConnected method, but the changes are not taking effect( i.e i'm still receiving events from the packages in the package list specified earlier which are absent in the modified package list).

@Override
protected void onServiceConnected() {
    AccessibilityServiceInfo accessibilityServiceInfo = new AccessibilityServiceInfo();
    accessibilityServiceInfo.packageNames = new String[]{"packageA","packageB"};
    accessibilityServiceInfo.eventTypes = AccessibilityEvent.TYPE_VIEW_CLICKED | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
            | AccessibilityEvent.TYPE_VIEW_SCROLLED | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
            | AccessibilityEvent.TYPE_VIEW_FOCUSED | AccessibilityEvent.TYPE_VIEW_SELECTED
            | AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
    accessibilityServiceInfo.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
    accessibilityServiceInfo.notificationTimeout = 100;
    accessibilityServiceInfo.flags = (AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS | accessibilityServiceInfo.flags);
    setServiceInfo(accessibilityServiceInfo);
}

@Override
public void onAccessibilityEvent(final AccessibilityEvent event) {
    AccessibilityServiceInfo serviceInfo = getServiceInfo();
    serviceInfo.packageNames = new String[]{"packageA"};
    setServiceInfo(serviceInfo);
}

accessibility_service_config.xml

<accessibility-service
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:canRetrieveWindowContent="true"
    android:description="@string/accessibility_service_description"
/>

So, the question is how do I add/remove packages inside the Accessibility Service depending on the Accessibility events I receive later?

Body:
Encountered the same issue recently. After looking into source code (SDK 8.1), it seems the API description gives the wrong expectation that set packageNames to some app list then set it null would make the service receive all events again.

The reason is in two methods below. In #1 when you it calls setServiceInfo(info) where the info.mPackageNames is null, here it just skips it and never set service.mPackageNames to null. In #2, when mPackageNames already includes the apps you added before. So later mPackageNames.isEmpty() will always be false.

http://androidxref.com/8.1.0_r33/xref/frameworks/base/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java#mPackageNames

1

line 2786 - 2788

if (packageNames != null) {
      mPackageNames.addAll(Arrays.asList(packageNames));
}

2

1428 Set<String> packageNames = service.mPackageNames;
1429        String packageName = (event.getPackageName() != null)
1430                ? event.getPackageName().toString() : null;
1431
1432        return (packageNames.isEmpty() || packageNames.contains(packageName));


问:
AWS CDK - StepFunction - Modify input before passing to the next step
I have a 3 step state machine for a step function.

InputStep -> ExecuteSparkJob -> OutputLambda

ExecuteSparkJob is a glue task. Since it cannot pass its output to the step function, it writes it output to an S3 bucket. OutputLambda reads it from there and passes it on to the step function.

The idea of InputStep is simply to define a common S3 URI that the following steps can use.

Below is the code I have for the Input Step.

const op1 = Data.stringAt("$.op1");
const op2 = Data.stringAt("$.op2");

const inputTask = new Pass(this, "Input Step", {
    result: Result.fromString(this.getURI(op1, op2)),
    resultPath: "$.s3path"
});

getURI(op1: string, op2: string): string {
    return op1.concat("/").concat(op2).concat("/").concat("response");
}
```
<p>However, the string manipulation that I am doing in <code>getURI</code> is not working. The values in <code>inputTask.result</code> are not being substituted by the value in <code>Path</code>.</p>
<p>This is the input and output to the <code>Input Step</code></p>
<pre class="lang-json prettyprint-override"><code>{
  "op1": "test1",
  "op2": "test2"
}
</code>```

Output

{
  "op1": "test1",
  "op2": "test2"
  "responsePath": "$.op1/$.op2/response"
}
```

Is it possible to do some string manipulations using parameters in the Path in Step Function definition? If yes, what am I missing?

Thanks for your help.

答:
You can use one or more EvaluateExpression Tasks - it's still a bit clunky.

You can find examples here.

API doc here.

Body:
I have a 3 step state machine for a step function.

InputStep -> ExecuteSparkJob -> OutputLambda

ExecuteSparkJob is a glue task. Since it cannot pass its output to the step function, it writes it output to an S3 bucket. OutputLambda reads it from there and passes it on to the step function.

The idea of InputStep is simply to define a common S3 URI that the following steps can use.

Below is the code I have for the Input Step.

const op1 = Data.stringAt("$.op1");
const op2 = Data.stringAt("$.op2");

const inputTask = new Pass(this, "Input Step", {
    result: Result.fromString(this.getURI(op1, op2)),
    resultPath: "$.s3path"
});

getURI(op1: string, op2: string): string {
    return op1.concat("/").concat(op2).concat("/").concat("response");
}

However, the string manipulation that I am doing in getURI is not working. The values in inputTask.result are not being substituted by the value in Path.

This is the input and output to the Input Step

{
  "op1": "test1",
  "op2": "test2"
}

Output

{
  "op1": "test1",
  "op2": "test2"
  "responsePath": "$.op1/$.op2/response"
}

Is it possible to do some string manipulations using parameters in the Path in Step Function definition? If yes, what am I missing?

Thanks for your help.


问:
Displaying the last two digits of the current year in Java
How can I display only the last two digits of the current year without using any substring algorithms or any third party libraries?

I have tried the below method and it gave a four-digit year. I want to know whether there are any date formatting options available to get the current year in two-digit format.

```<code>Calendar.getInstance().get(Calendar.YEAR);
</code>```

答:
String.format() also has Date/Time Conversions.

To get the last two digits of the current year,

```<code>String.format("%ty", Year.now());
</code>```

This works with a number of the java.time classes, including Year, YearMonth, LocalDate, LocalDateTime, and ZonedDateTime.

Body:
How can I display only the last two digits of the current year without using any substring algorithms or any third party libraries?

I have tried the below method and it gave a four-digit year. I want to know whether there are any date formatting options available to get the current year in two-digit format.

Calendar.getInstance().get(Calendar.YEAR);

Body:
String.format() also has Date/Time Conversions.

To get the last two digits of the current year,

String.format("%ty", Year.now());

This works with a number of the java.time classes, including Year, YearMonth, LocalDate, LocalDateTime, and ZonedDateTime.


问:
Is the maintenance window burning error budget
Is the maintenance window burning error budget?

Example:
Let's say I have a 1h error budget left. I stop the service for planned maintenance for 30 minutes. Is the error budget still 1h or is it 30 minutes?

The maintenance window is happening when there is no traffic to the application, for example, 3-5 am for online retailer that is available in one country.

答:
it is 30 minutes

“The development team can ‘spend’ this error budget in any way they like. If the product is currently running flawlessly, with few or no errors, they can launch whatever they want, whenever they want. Conversely, if they have met or exceeded the error budget and are operating at or below the defined SLA, all launches are frozen until they reduce the number of errors to a level that allows the launch to proceed.”

from
https://www.atlassian.com/br/incident-management/devops/sre