问:
SoundPool doesn't play sounds
When I try to start a sound in my application it doesn't play. I have seen that the method does get called however soundPool just doesn't want to play the sound. The app starts as intended, however, it just doesn't want to play the queued sound. Is it something I am doing wrong? is the music file I am trying to play just too large? (35.4MB)

Any input is appreciated!

StartActivity (relevant bit)

```<code>public class StartActivity extends AppCompatActivity {
    private Button startButton;

    //Sounds
    private SoundManager soundManager;
    private int ambient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start_activity);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        startButton = (Button) findViewById(R.id.startButton);

        //Setting Up sounds
        soundManager = new SoundManager(this);
        ambient = soundManager.getSoundID(R.raw.music_ambient);

        soundManager.playLoop(ambient);
        Application.setSoundManager(soundManager);

</code>```

Application

```<code>
public class Application {
    public static SoundManager soundManager;

    public static SoundManager getSoundManager() {
        return soundManager;
    }

    public static void setSoundManager(SoundManager soundManagerIns) {
        soundManager = soundManagerIns;
    }
}

</code>```

SoundManager class

```<code>
import android.content.Context;
import android.media.SoundPool;
import android.util.Log;

public class SoundManager {

    private Context context;
    private SoundPool soundPool;
    private boolean isPlaying = false;

    SoundManager(Context context) {
        this.context = context;

        SoundPool.Builder builder = new SoundPool.Builder();
        builder.setMaxStreams(10);
        soundPool = builder.build();
    }

    int getSoundID(int resourcesID) {
        return (soundPool.load(context, resourcesID, 1));
    }

    void play(int soundId) {
        soundPool.play(soundId, 1, 1, 1, 0, 1);
    }

    void playLoop(int soundId){
        if(!isPlaying) {
            Log.d("LEADER", "called this");
            soundPool.play(soundId, 1, 1, 1, -1, 1);
            isPlaying = true;
        }
    }

    void stop(int soundId){
        isPlaying = false;
        soundPool.stop(soundId);
    }
}

</code>```

答:
is the music file I am trying to play just too large? (35.4MB)

That might be the case. I have seen several StackOverflow answers (including recent ones) that claim that the uncompressed in-memory limit per sound is 1 MB for SoundPool, though I haven't been able to check that in the official documentation. If it is indeed the case, you might be able to see this error in your log as described by https://stackoverflow.com/a/18548242/9543944 :

If your clip is too big in memory, sound pool will fall silent, and you'll find following error: "AudioFlinger could not create track. status: -12"

You should be able to see the log from inside Android Studio, and you can then filter for errors to more quickly search for the above error.

If this is indeed the case, MediaPlayer might be a good alternative: https://developer.android.com/guide/topics/media/mediaplayer .

Title: SoundPool doesn't play sounds

Body:
When I try to start a sound in my application it doesn't play. I have seen that the method does get called however soundPool just doesn't want to play the sound. The app starts as intended, however, it just doesn't want to play the queued sound. Is it something I am doing wrong? is the music file I am trying to play just too large? (35.4MB)

Any input is appreciated!

StartActivity (relevant bit)

public class StartActivity extends AppCompatActivity {
    private Button startButton;

    //Sounds
    private SoundManager soundManager;
    private int ambient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start_activity);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        startButton = (Button) findViewById(R.id.startButton);

        //Setting Up sounds
        soundManager = new SoundManager(this);
        ambient = soundManager.getSoundID(R.raw.music_ambient);

        soundManager.playLoop(ambient);
        Application.setSoundManager(soundManager);

Application

public class Application {
    public static SoundManager soundManager;

    public static SoundManager getSoundManager() {
        return soundManager;
    }

    public static void setSoundManager(SoundManager soundManagerIns) {
        soundManager = soundManagerIns;
    }
}

SoundManager class

import android.content.Context;
import android.media.SoundPool;
import android.util.Log;

public class SoundManager {

    private Context context;
    private SoundPool soundPool;
    private boolean isPlaying = false;

    SoundManager(Context context) {
        this.context = context;

        SoundPool.Builder builder = new SoundPool.Builder();
        builder.setMaxStreams(10);
        soundPool = builder.build();
    }

    int getSoundID(int resourcesID) {
        return (soundPool.load(context, resourcesID, 1));
    }

    void play(int soundId) {
        soundPool.play(soundId, 1, 1, 1, 0, 1);
    }

    void playLoop(int soundId){
        if(!isPlaying) {
            Log.d("LEADER", "called this");
            soundPool.play(soundId, 1, 1, 1, -1, 1);
            isPlaying = true;
        }
    }

    void stop(int soundId){
        isPlaying = false;
        soundPool.stop(soundId);
    }
}


来源: stackexchange

问:
API Gateway GET fails with "Missing Authentication Token" (but POST works)
I have a working Lambda + API Gateway "hello world" combination, as follows -

lambda.py

```<code>import boto3, json, logging

logger=logging.getLogger()
logger.setLevel(logging.INFO)

logging.getLogger('botocore').setLevel(logging.WARNING)

def api_gateway(fn):
    def wrapped(event, context):
        body=json.loads(event["body"])
        resp=fn(body, context)
        return {"statusCode": 200,
                "headers": {"Content-Type": "application/json",
                            "Access-Control-Allow-Origin": "*"},
                "body": json.dumps(resp)}
    return wrapped

@api_gateway
def handler(event, context):
    logging.info("event: %s" % event)
    return {"hello": "world"}
</code>```

api_gateway.yaml

```<code>---
AWSTemplateFormatVersion: '2010-09-09'
Parameters:
  FunctionName:
    Type: String
  StageName:
    Type: String
  FunctionArn:
    Type: String
  HttpMethod:
    Type: String
    Default: POST
Outputs:
  GatewayURL:
    Value: !Sub "https://${ApiGateway}.execute-api.${AWS::Region}.amazonaws.com/${StageName}"
Resources:
  ApiGateway:
    Properties:
      Name: !Sub "${FunctionName}-${StageName}"
    Type: AWS::ApiGateway::RestApi
  ApiGatewayMethod:
    Properties:
      AuthorizationType: NONE
      HttpMethod: !Ref HttpMethod
      Integration:
        IntegrationHttpMethod: POST
        Type: AWS_PROXY
        Uri: !Sub
          - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
          - lambdaArn: !Ref FunctionArn
      ResourceId: !GetAtt ApiGateway.RootResourceId
      RestApiId: !Ref ApiGateway
    Type: AWS::ApiGateway::Method
  ApiGatewayDeployment:
    Properties:
      RestApiId: !Ref ApiGateway
      StageName: !Ref StageName
    DependsOn:
      - ApiGatewayMethod
    Type: AWS::ApiGateway::Deployment
  ApiGatewayPermission:
    Properties:
      Action: lambda:InvokeFunction
      FunctionName: !Ref FunctionArn
      Principal: apigateway.amazonaws.com
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ApiGateway}/*/${HttpMethod}/"
    Type: AWS::Lambda::Permission
</code>```

This works fine for a POST request -

```<code>curl -X POST  -H "Content-Type: application/json" https://XXXXXXXXX.execute-api.eu-west-1.amazonaws.com/dev -d "{\"foo\": \"bar\"}"
{"hello": "world"}
</code>```

but I need a GET :/

I was hoping this would be a simple change, just change the gateway HttpMethod parameter to GET - which deploys fine, but when I try to ping it -

```<code>curl -X GET https://XXXXXXXX.execute-api.eu-west-1.amazonaws.com/dev
{"message":"Missing Authentication Token"}
</code>```

There are no errors shown in the Lambda logs so this looks like some kind of failure at the API Gateway level :(

Any ideas at to what to tweak in the API Gateway config to make a GET request work ?

答:
Turns out you need to define an extra API Gateway resource to make this work -

```<code>Resources:
  ApiGatewayStage:
    Type: AWS::ApiGateway::Stage
    Properties:
      RestApiId: !Ref ApiGateway
      DeploymentId: !Ref ApiGatewayDeployment
      StageName: !Ref StageName
</code>```

With this, you should be able to make both GET and POST requests to work.

Without this, it seems that API Gateway will create some kind of "default" stage, one which will only support POST requests.

ContentLicense: CC BY-SA 4.0

Body:
I have a working Lambda + API Gateway "hello world" combination, as follows -

lambda.py

import boto3, json, logging

logger=logging.getLogger()
logger.setLevel(logging.INFO)

logging.getLogger('botocore').setLevel(logging.WARNING)

def api_gateway(fn):
    def wrapped(event, context):
        body=json.loads(event["body"])
        resp=fn(body, context)
        return {"statusCode": 200,
                "headers": {"Content-Type": "application/json",
                            "Access-Control-Allow-Origin": "*"},
                "body": json.dumps(resp)}
    return wrapped

@api_gateway
def handler(event, context):
    logging.info("event: %s" % event)
    return {"hello": "world"}

api_gateway.yaml

---
AWSTemplateFormatVersion: '2010-09-09'
Parameters:
  FunctionName:
    Type: String
  StageName:
    Type: String
  FunctionArn:
    Type: String
  HttpMethod:
    Type: String
    Default: POST
Outputs:
  GatewayURL:
    Value: !Sub "https://${ApiGateway}.execute-api.${AWS::Region}.amazonaws.com/${StageName}"
Resources:
  ApiGateway:
    Properties:
      Name: !Sub "${FunctionName}-${StageName}"
    Type: AWS::ApiGateway::RestApi
  ApiGatewayMethod:
    Properties:
      AuthorizationType: NONE
      HttpMethod: !Ref HttpMethod
      Integration:
        IntegrationHttpMethod: POST
        Type: AWS_PROXY
        Uri: !Sub
          - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
          - lambdaArn: !Ref FunctionArn
      ResourceId: !GetAtt ApiGateway.RootResourceId
      RestApiId: !Ref ApiGateway
    Type: AWS::ApiGateway::Method
  ApiGatewayDeployment:
    Properties:
      RestApiId: !Ref ApiGateway
      StageName: !Ref StageName
    DependsOn:
      - ApiGatewayMethod
    Type: AWS::ApiGateway::Deployment
  ApiGatewayPermission:
    Properties:
      Action: lambda:InvokeFunction
      FunctionName: !Ref FunctionArn
      Principal: apigateway.amazonaws.com
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ApiGateway}/*/${HttpMethod}/"
    Type: AWS::Lambda::Permission

This works fine for a POST request -

curl -X POST  -H "Content-Type: application/json" https://XXXXXXXXX.execute-api.eu-west-1.amazonaws.com/dev -d "{\"foo\": \"bar\"}"
{"hello": "world"}

but I need a GET :/

I was hoping this would be a simple change, just change the gateway HttpMethod parameter to GET - which deploys fine, but when I try to ping it -

curl -X GET https://XXXXXXXX.execute-api.eu-west-1.amazonaws.com/dev
{"message":"Missing Authentication Token"}

There are no errors shown in the Lambda logs so this looks like some kind of failure at the API Gateway level :(

Any ideas at to what to tweak in the API Gateway config to make a GET request work ?

Body:
Turns out you need to define an extra API Gateway resource to make this work -

Resources:
  ApiGatewayStage:
    Type: AWS::ApiGateway::Stage
    Properties:
      RestApiId: !Ref ApiGateway
      DeploymentId: !Ref ApiGatewayDeployment
      StageName: !Ref StageName

With this, you should be able to make both GET and POST requests to work.

Without this, it seems that API Gateway will create some kind of "default" stage, one which will only support POST requests.


问:
how to invoke javac from windows git shell/gnu makefile
I was working home office with my linux box,
was sure to write portable code.
Used shell and gnumake and compiled java through

```<code>javac -Xlint:deprecation -Xlint:unchecked --module-path libs/nrjavaserial-4.0.1.jar:libs/jep-3.9.0.jar:libs/commons-beanutils-1.9.4.jar:libs/commons-collections-3.2.2.jar:libs/commons-logging-1.2.jar:src/  src/main/de/name/product/Product.java -d target/classes/
</code>```

All ok.
Now in office with windows 10 but still gnumake, does not work.
Also from git bash, no.

I would be content as a first step to get it run in gitshell.
I use javac 11.0.7 and 2.26.0.windows.1.

The errors (i cannot show in full because related to customer)
show that no jar has been accepted:

```<code> error: cannot find symbol
       NRSerialPort serial = getSingleSerialPort(baudRate);
        ^
  symbol:   class NRSerialPort
  location: class xxx
</code>```

shows that libs/nrjavaserial-4.0.1.jar is not accepted athough present
and

```<code> error: cannot find symbol
        } catch(JepException e) {
                ^
  symbol:   class JepException
  location: class XXX
</code>```

shows that libs/jep-3.9.0.jar is not accepted.
Note that on linux all works fine on an ordinary bash shell.

Maybe separators wrong for windows?
I always thought, separators are transparent on git bash?
or only / but not :?
I tried several combinations, without success.

I suspect all quite easy... right?

答:
You've guessed right, you need to use different separators on Windows.

See https://docs.oracle.com/en/java/javase/13/docs/specs/man/javac.html

In the following lists of options, an argument of path represents a
  search path, composed of a list of file system locations separated by
  the platform path separator character, (semicolon ; on Windows, or
  colon : on other systems.) Depending on the option, the file system
  locations may be directories, JAR files or JMOD files.

If you want portability, ease-of-use and maintainability, use something like ant, maven or gradle.

Body:
I was working home office with my linux box,
was sure to write portable code.
Used shell and gnumake and compiled java through

javac -Xlint:deprecation -Xlint:unchecked --module-path libs/nrjavaserial-4.0.1.jar:libs/jep-3.9.0.jar:libs/commons-beanutils-1.9.4.jar:libs/commons-collections-3.2.2.jar:libs/commons-logging-1.2.jar:src/  src/main/de/name/product/Product.java -d target/classes/

All ok.
Now in office with windows 10 but still gnumake, does not work.
Also from git bash, no.

I would be content as a first step to get it run in gitshell.
I use javac 11.0.7 and 2.26.0.windows.1.

The errors (i cannot show in full because related to customer)
show that no jar has been accepted:

 error: cannot find symbol
       NRSerialPort serial = getSingleSerialPort(baudRate);
        ^
  symbol:   class NRSerialPort
  location: class xxx

shows that libs/nrjavaserial-4.0.1.jar is not accepted athough present
and

 error: cannot find symbol
        } catch(JepException e) {
                ^
  symbol:   class JepException
  location: class XXX

shows that libs/jep-3.9.0.jar is not accepted.
Note that on linux all works fine on an ordinary bash shell.

Maybe separators wrong for windows?
I always thought, separators are transparent on git bash?
or only / but not :?
I tried several combinations, without success.

I suspect all quite easy... right?


问:
Python Mocks: How to spy on instance methods that are created in runtime?
I'm trying to spy on a class object and see if class instance method is called with right parameters.

I can't use Mock(wraps=obj_instance) because the flow I trigger creates its own object instance.

I tried to use Mock(spec=obj_class) as seen in below, but it doesnt work.

Any ideas on how to spy on instance methods without creating the instance beforehand?

from mock import Mock
import unittest

class CreditAPI:
    def __init__(self, *args, **kwargs):
        self.user = kwargs['user']

    def add_credit(self, amount):
        print("adding amount %s to user %s" % (amount, self.user))

def consume_credit():
    credit_api = CreditAPI(user="Ali")
    credit_api.add_credit(50)

class ConsumeCreditTestCase(unittest.TestCase):
    def test_consume_credit(self):
        m_credit_api = Mock(spec=CreditAPI)
        consume_credit()
        m_credit_api.__init__.assert_called_with(user="Ali")  # doesnt work
        m_credit_api.add_credit.assert_called_with(50)  # doesnt work

if __name__ == '__main__':
    unittest.main()
```

答:
With @jonrsharpe's help I managed to get it working by using spec like this:

class ConsumeCreditTestCase(unittest.TestCase):
    def test_consume_credit(self):
        with patch('__main__.CreditAPI', spec=CreditAPI) as m_credit_api:
           consume_credit()
           m_credit_api.assert_called_with(user="Ali")
           m_credit_api().add_credit.assert_called_with(50)

```


问:
Jasmine test on angular sidenav with routing
I have a component with routing like this :

```<code><div>
  <div class="d-flex px-2 py-3">
    <a
      class="navbar-brand p-0"
      aria-label="AdAsia"
      [routerLink]="[routes.pages.dashboard.children.home.link]"
    >
      <app-logo [logoType]="logoType"></app-logo>
    </a>
  </div>

  <nav class="nav flex-column mb-4 flex-column">
    <p
      class="nav-item w-100 rounded-sm mb-2"
      #home="routerLinkActive"
      [routerLinkActive]="['active']"
    >
      <a
        class="nav-link text-m text-truncate p-1"
        [routerLink]="[routes.pages.dashboard.children.home.link]"
      >
        <svg-icon [hidden]="!home.isActive" src="assets/svg/dooh-dashboard-dark.svg"></svg-icon>
        <svg-icon [hidden]="home.isActive" src="assets/svg/dooh-dashboard-light.svg"></svg-icon>
        {{ 'PAGES.DASHBOARD.NAME' | translate }}
      </a>
    </p>
    <p
      class="nav-item w-100 rounded-sm mb-2"
      #report="routerLinkActive"
      [routerLinkActive]="['active']"
    >
      <a
        class="nav-link text-m text-truncate p-1"
        [routerLink]="[routes.pages.dashboard.children.reports.link]"
      >
        <svg-icon [hidden]="!report.isActive" src="assets/svg/report-dark.svg"></svg-icon>
        <svg-icon [hidden]="report.isActive" src="assets/svg/report-light.svg"></svg-icon>
        {{ 'PAGES.REPORTS.NAME' | translate }}
      </a>
    </p>
  </nav>
</div>
</code>```

I try to test it with the following :

```<code>import { ComponentFixture, TestBed } from '@angular/core/testing'
import { NO_ERRORS_SCHEMA } from '@angular/core'
import { TranslateModule } from '@ngx-translate/core'

import { LogoTypeEnum } from '@app/types'
import { SidenavComponent } from './sidenav.component'

describe('SidenavComponent', () => {
  let component: SidenavComponent
  let fixture: ComponentFixture<SidenavComponent>

  beforeEach(() => {
    TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [SidenavComponent],
      imports: [TranslateModule.forRoot()],
    })
    fixture = TestBed.createComponent(SidenavComponent)
    component = fixture.componentInstance
  })

  it('can load instance', () => {
    expect(component).toBeTruthy()
  })

  it('logoType has default value', () => {
    expect(component.logoType).toEqual(LogoTypeEnum.DARK)
  })
})
</code>```

But I had a routerActiveLink do not exist error.

So I create following another answer a stub like this

```<code>import { Directive, Input, HostListener } from '@angular/core'

@Directive({
  /* tslint:disable-next-line */
  selector: '[routerLink]',
})
export class RouterLinkStubDirective {
  /* tslint:disable-next-line */
  @Input('routerLink') linkParams: any
  navigatedTo: any = null

  @HostListener('click')
  onClick() {
    this.navigatedTo = this.linkParams
  }
}
</code>```

and updated the jasmine test

```<code>@Component({
  template: ``,
})
export class HomeComponent {}

@Component({
  template: ``,
})
export class EditComponent {}

const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
  },
  {
    path: 'edit',
    component: EditComponent,
  },
]

describe('SidenavComponent', () => {
  let component: SidenavComponent
  let fixture: ComponentFixture<SidenavComponent>
  let router: Router

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      imports: [RouterTestingModule.withRoutes(routes), TranslateModule.forRoot()],
      declarations: [SidenavComponent, RouterLinkStubDirective, HomeComponent, EditComponent],
    }).compileComponents()
  }))

  beforeEach(() => {
    fixture = TestBed.createComponent(SidenavComponent)
    component = fixture.componentInstance
    router = TestBed.get(Router)
    fixture.detectChanges()
  })

  it('can be instantiated', () => {
    expect(component).not.toBeNull()
  })
})

</code>```

but now I get can't find property pages of undefined

but I have no idea where this is coming from.

How do I fix this ?

答:
The best way is to mock it properly, try to use ng-mocks for example.

Also you need to provide routes to the tested component via providers:

providers: [{
  provide: NAME_WHAT_YOU_IMPORT,
  useValue: {
    pages: {
      dashboard: {
        children: {
          home: {
            link: 'test-link',
          },
        },
      },
    },
  },
}],
```

Body:
I have a component with routing like this :

      <app-logo [logoType]="logoType"></app-logo>

        <svg-icon [hidden]="!home.isActive" src="assets/svg/dooh-dashboard-dark.svg"></svg-icon>
        <svg-icon [hidden]="home.isActive" src="assets/svg/dooh-dashboard-light.svg"></svg-icon>
        {{ 'PAGES.DASHBOARD.NAME' | translate }}

        <svg-icon [hidden]="!report.isActive" src="assets/svg/report-dark.svg"></svg-icon>
        <svg-icon [hidden]="report.isActive" src="assets/svg/report-light.svg"></svg-icon>
        {{ 'PAGES.REPORTS.NAME' | translate }}

I try to test it with the following :

import { ComponentFixture, TestBed } from '@angular/core/testing'
import { NO_ERRORS_SCHEMA } from '@angular/core'
import { TranslateModule } from '@ngx-translate/core'

import { LogoTypeEnum } from '@app/types'
import { SidenavComponent } from './sidenav.component'

describe('SidenavComponent', () => {
  let component: SidenavComponent
  let fixture: ComponentFixture<SidenavComponent>

  beforeEach(() => {
    TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [SidenavComponent],
      imports: [TranslateModule.forRoot()],
    })
    fixture = TestBed.createComponent(SidenavComponent)
    component = fixture.componentInstance
  })

  it('can load instance', () => {
    expect(component).toBeTruthy()
  })

  it('logoType has default value', () => {
    expect(component.logoType).toEqual(LogoTypeEnum.DARK)
  })
})

But I had a routerActiveLink do not exist error.

So I create following another answer a stub like this

import { Directive, Input, HostListener } from '@angular/core'

@Directive({
  /* tslint:disable-next-line */
  selector: '[routerLink]',
})
export class RouterLinkStubDirective {
  /* tslint:disable-next-line */
  @Input('routerLink') linkParams: any
  navigatedTo: any = null

  @HostListener('click')
  onClick() {
    this.navigatedTo = this.linkParams
  }
}

and updated the jasmine test

@Component({
  template: ``,
})
export class HomeComponent {}

@Component({
  template: ``,
})
export class EditComponent {}

const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
  },
  {
    path: 'edit',
    component: EditComponent,
  },
]

describe('SidenavComponent', () => {
  let component: SidenavComponent
  let fixture: ComponentFixture<SidenavComponent>
  let router: Router

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      imports: [RouterTestingModule.withRoutes(routes), TranslateModule.forRoot()],
      declarations: [SidenavComponent, RouterLinkStubDirective, HomeComponent, EditComponent],
    }).compileComponents()
  }))

  beforeEach(() => {
    fixture = TestBed.createComponent(SidenavComponent)
    component = fixture.componentInstance
    router = TestBed.get(Router)
    fixture.detectChanges()
  })

  it('can be instantiated', () => {
    expect(component).not.toBeNull()
  })
})

but now I get can't find property pages of undefined

but I have no idea where this is coming from.

How do I fix this ?


问:
Querying JSON API with node.js
How should querying a JSON API be done best in node.js? Is there a module that will simplify this?

I am trying to get the City location from http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452

I would use jQuery to query the API in client-side because it vastly simplifies things. Is there something similar for node.js?

答: The request module makes http-request very easy. Just place a GET request to your URL and JSON.parse() the response. You might want to use encodeURIComponent() for your query parameters.

ContentLicense: CC BY-SA 3.0

Title: Querying JSON API with node.js


问:
Trying to zip and automatically delete files with "find" and "zip -m" on Linux
there are over 300000 files in the /test folder with a long name (over 30 character )and same header like this "TEST_*" i want to zip all the files into a .zip package and remove them from the /test file.
so i used the command show as below:

```<code>find ./test -name "TEST_\*" -mtime +1 | zip -m /home/TESTbac.zip -@;
</code>```

but the files in the /test folder still exist after i run the shell script

what i want to ask is why the files still exist after running the script ?
and how can i fix this problem ?

答:
```<code>zip -rm files.zip *.xml
</code>```

This works perfectly

Body:
there are over 300000 files in the /test folder with a long name (over 30 character )and same header like this "TEST_*" i want to zip all the files into a .zip package and remove them from the /test file.
so i used the command show as below:

find ./test -name "TEST_\*" -mtime +1 | zip -m /home/TESTbac.zip -@;

but the files in the /test folder still exist after i run the shell script

what i want to ask is why the files still exist after running the script ?
and how can i fix this problem ?

Body:
zip -rm files.zip *.xml

This works perfectly


问:
Can two or more coroutines await for the same Deferred in Twisted?
I am trying to use a deferred to signal the end of a task to multiple coroutines that may be waiting for it. I want the same behavior of events in threading.Event. The coroutines waits but only one gets the result of the fired deferred. Code example:

```<code>from twisted.internet import defer, task, reactor

async def test(d):
    print("Awaiting")
    print(f"Await finished: {await d}")

d = defer.Deferred()
defer.ensureDeferred(test(d))
defer.ensureDeferred(test(d))
task.deferLater(reactor, 1, d.callback, 'Deferred Fired')

reactor.run()
</code>```

Outputs:

```<code>Awaiting
Awaiting
Await finished: Deferred Fired
Await finished: None
</code>```

I was expecting:

```<code>Awaiting
Awaiting
Await finished: Deferred Fired
Await finished: Deferred Fired
</code>```

But it works fine when one coroutine awaits two or more times:

```<code>async def test(d):
    print("Awaiting")
    print(f"Await finished: {await d}")
    print(f"Await finished: {await d}")

d = defer.Deferred()
defer.ensureDeferred(test(d))
task.deferLater(reactor, 1, d.callback, 'Deferred Fired')
</code>```

答:
You're trying to use deferreds as a method to synchronize, but that's not really its intended purpose, at least not on their own. I assume you want to use Deferred like you use Event.wait()? This is the paradigm I've usually seen:

from dataclasses import dataclass, field
from typing import List

from twisted.internet import defer, reactor

@dataclass
class Thing:

    deferred_list: List[defer.Deferred] = field(default_factory=list)

    def notifyFinished(self) -> defer.Deferred:
        deferred = defer.Deferred()
        self.deferred_list.append(deferred)
        return deferred

    def finish(self):
        for index, deferred in enumerate(self.deferred_list):
            deferred.callback(index + 1)
        self.deferred_list = []

async def doSomethingElse(d):
    print("[!] awaiting...")
    print(f"[x] done waiting: {await d}")

def main():
    thing = Thing()
    for _ in range(5):
        d = thing.notifyFinished()
        defer.ensureDeferred(doSomethingElse(d))
    reactor.callLater(5, thing.finish)
    reactor.run()

main()
```

Here we have a function that returns a deferred/future (ie. notifyFinished), keep track of those deferred, and once a job is complete, calls a function that signals the end of the job (ie. finish). Deferred are intended to only fire once (Future might too, but don't quote me on that), so using this method ensures that individual Deferred objects are returned and fire at the same time.

Body:
I am trying to use a deferred to signal the end of a task to multiple coroutines that may be waiting for it. I want the same behavior of events in threading.Event. The coroutines waits but only one gets the result of the fired deferred. Code example:

from twisted.internet import defer, task, reactor

async def test(d):
    print("Awaiting")
    print(f"Await finished: {await d}")

d = defer.Deferred()
defer.ensureDeferred(test(d))
defer.ensureDeferred(test(d))
task.deferLater(reactor, 1, d.callback, 'Deferred Fired')

reactor.run()

Outputs:

Awaiting
Awaiting
Await finished: Deferred Fired
Await finished: None

I was expecting:

Awaiting
Awaiting
Await finished: Deferred Fired
Await finished: Deferred Fired

But it works fine when one coroutine awaits two or more times:

async def test(d):
    print("Awaiting")
    print(f"Await finished: {await d}")
    print(f"Await finished: {await d}")

d = defer.Deferred()
defer.ensureDeferred(test(d))
task.deferLater(reactor, 1, d.callback, 'Deferred Fired')

Body:
You're trying to use deferreds as a method to synchronize, but that's not really its intended purpose, at least not on their own. I assume you want to use Deferred like you use Event.wait()? This is the paradigm I've usually seen:

from dataclasses import dataclass, field
from typing import List

from twisted.internet import defer, reactor

@dataclass
class Thing:

    deferred_list: List[defer.Deferred] = field(default_factory=list)

    def notifyFinished(self) -> defer.Deferred:
        deferred = defer.Deferred()
        self.deferred_list.append(deferred)
        return deferred

    def finish(self):
        for index, deferred in enumerate(self.deferred_list):
            deferred.callback(index + 1)
        self.deferred_list = []

async def doSomethingElse(d):
    print("[!] awaiting...")
    print(f"[x] done waiting: {await d}")

def main():
    thing = Thing()
    for _ in range(5):
        d = thing.notifyFinished()
        defer.ensureDeferred(doSomethingElse(d))
    reactor.callLater(5, thing.finish)
    reactor.run()

main()

Here we have a function that returns a deferred/future (ie. notifyFinished), keep track of those deferred, and once a job is complete, calls a function that signals the end of the job (ie. finish). Deferred are intended to only fire once (Future might too, but don't quote me on that), so using this method ensures that individual Deferred objects are returned and fire at the same time.


问:
Navigation menu can not show list when responsive smaller

As you can see here, in max-width: 960px; my navigation menu is showing but after that when I set responsive to 840px, it can not show, although I already click to the hamburger icon

I do not know why?
You can see my code here
index.html

```<code><header class="header-container">

  <div class="header-content">
    <!-- nav bar -->
    <div class="nav-bar">
      <div class="header-logo">
        <a href="#">
          <img id="image-logo-header" class="bottom img-logo" src="images/logo.png">
        </a>
      </div>

      <div class="menu-section">
        <nav role="navigation">
          <ul class="nav-content" id="menu">
            <li class="menu-item"><a class="active" href="#">Home</a></li>
            <li class="menu-item"><a href="#">Blog</a></li>
            <li class="menu-item"><a href="#">About</a></li>
            <li class="menu-item"><a href="#">Contact</a></li>
            <li class="menu-item"><a href="#">Login</a></li>
            <li class="menu-item"><a href="#">Sign up</a></li>
            <li class="menu-item"><a href="#" class="hamburger-icon" onclick="myFunction()"><img src="images/hamburger.png" alt="hamburger icon"></a></li>
          </ul>
        </nav>
      </div>
    </div>

    <h1 class="header-title">SHARE YOUR HOLIDDAY DREAM</h1>

    <div class="header-video">
      <img class="video-img" src="images/video-img.png">
    </div>
  </div>
</header>
</code>```

style.css

```<code> /* -------header------- */
 .header-container {
      background-image:  linear-gradient(
      0deg,
      rgba(35, 39, 49, -0.18),
      rgba(35, 39, 49, 1.82)
 ), url("images/bg-image.jpeg");
  background-repeat: no-repeat;
   background-size: cover;
   box-sizing: border-box;
   position: relative;
   height: 743px;
   width: 100%;
 }

 /* nav bar */
 .nav-bar{
     margin-left: 7%;
     margin-right: 7%;
     height: 140px;
  }

  .nav-content li a.hamburger-icon  {
      display: none;
   }

   .header-logo{
      float: left;
   }

   .menu-section{
      float: right;
    }

   .nav-content{
       list-style-type: none;
       margin-top: 10%;
    }

   .menu-item{
       display: block;
       float: left;
       margin-left: 30px;

    }

   .menu-item a.active{
        color: #00B9F7
    }

   .nav-content li a{
       text-decoration: none;
       color: #fff;
       font-size: 18px;
    }

   .nav-content li a:hover {
       color: #00B9F7;
    }

   .header-title{
       color: #fff;
       font-size: 52px;
       line-height: 63px;
       text-align: center;
        margin: auto;
        width: 35%;

     }

    .header-video {
        margin: auto;
        width: fit-content;
        margin-top: 10%;
      }
</code>```

responsive.css

```<code>@media (max-width:960px) {
    .header-title {
        font-size: 32px;
    }

   .partner-name, .user-comment, .search-question {
        font-size: 18px;
    }

   .partner-description{
        font-size: 12px;
    }

   .activity_item:nth-child(5), .activity_item:nth-child(6) {
        height: 258px;
    }

   .search-input {
        padding-right: 59%;
   }

   .nav-content li a{
        display: none;
   }

  .nav-content li a.hamburger-icon  {
       display: block;
   }

  .menu-item{
      float: right;
   }

  }

 @media (max-width:960px) {
     .nav-content.responsive {position: relative;}
     .nav-content.responsive .hamburger-icon {
         position: absolute;
         right: 0;
         top: 0;
      }
     .nav-content.responsive a {
         float: none;
         display: block;
      }
     .nav-content{
         background-color: #000;
         padding: 0%;
         width: 160px;
         text-align: center;
     }

    .menu-item{
        float: none;
        margin-left: 0%;
        line-height: 35px;
    }

    .menu-item:hover{
        background-color: #00B9F7;
    }

   .nav-content li a:hover {
        color: #fff;
    }

   .hamburger-icon{
        float: right;
    }

   }
</code>```

javascript.js

```<code><script>
function myFunction() {
  var x = document.getElementById("menu");
  if (x.className === "nav-content") {
    x.className += " responsive";
  } else {
    x.className = "nav-content";
  }
}
</script>
</code>```

Can you guys help me please, I do not understand why? in 840px my navigation menu not show for me? I need your help

答:
From your given code, I made it to code snippet and run it. It is working fine.

function myFunction() {
  var x = document.getElementById("menu");
  if (x.className === "nav-content") {
    x.className += " responsive";
  } else {
    x.className = "nav-content";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* style.css */

/* -------header------- */

.header-container {
  background-image: linear-gradient( 0deg, rgba(35, 39, 49, -0.18), rgba(35, 39, 49, 1.82)), url("images/bg-image.jpeg");
  background-repeat: no-repeat;
  background-size: cover;
  box-sizing: border-box;
  position: relative;
  height: 743px;
  width: 100%;
}

/* nav bar */

.nav-bar {
  margin-left: 7%;
  margin-right: 7%;
  height: 140px;
}

.nav-content li a.hamburger-icon {
  display: none;
}

.header-logo {
  float: left;
}

.menu-section {
  float: right;
}

.nav-content {
  list-style-type: none;
  margin-top: 10%;
}

.menu-item {
  display: block;
  float: left;
  margin-left: 30px;
}

.menu-item a.active {
  color: #00B9F7
}

.nav-content li a {
  text-decoration: none;
  color: #fff;
  font-size: 18px;
}

.nav-content li a:hover {
  color: #00B9F7;
}

.header-title {
  color: #fff;
  font-size: 52px;
  line-height: 63px;
  text-align: center;
  margin: auto;
  width: 35%;
}

.header-video {
  margin: auto;
  width: fit-content;
  margin-top: 10%;
}

/* responsive.css */

@media (max-width:960px) {
  .header-title {
    font-size: 32px;
  }
  .partner-name,
  .user-comment,
  .search-question {
    font-size: 18px;
  }
  .partner-description {
    font-size: 12px;
  }
  .activity_item:nth-child(5),
  .activity_item:nth-child(6) {
    height: 258px;
  }
  .search-input {
    padding-right: 59%;
  }
  .nav-content li a {
    display: none;
  }
  .nav-content li a.hamburger-icon {
    display: block;
  }
  .menu-item {
    float: right;
  }
}

@media (max-width:960px) {
  .nav-content.responsive {
    position: relative;
  }
  .nav-content.responsive .hamburger-icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .nav-content.responsive a {
    float: none;
    display: block;
  }
  .nav-content {
    background-color: #000;
    padding: 0%;
    width: 160px;
    text-align: center;
  }
  .menu-item {
    float: none;
    margin-left: 0%;
    line-height: 35px;
  }
  .menu-item:hover {
    background-color: #00B9F7;
  }
  .nav-content li a:hover {
    color: #fff;
  }
  .hamburger-icon {
    float: right;
  }
}</code>```

Home

Blog

About

Contact

Login

Sign up

SHARE YOUR HOLIDDAY DREAM

```

Body:
As you can see here, in max-width: 960px; my navigation menu is showing but after that when I set responsive to 840px, it can not show, although I already click to the hamburger icon

I do not know why?
You can see my code here
index.html

Home

Blog

About

Contact

Login

Sign up

SHARE YOUR HOLIDDAY DREAM

style.css

 /* -------header------- */
 .header-container {
      background-image:  linear-gradient(
      0deg,
      rgba(35, 39, 49, -0.18),
      rgba(35, 39, 49, 1.82)
 ), url("images/bg-image.jpeg");
  background-repeat: no-repeat;
   background-size: cover;
   box-sizing: border-box;
   position: relative;
   height: 743px;
   width: 100%;
 }

 /* nav bar */
 .nav-bar{
     margin-left: 7%;
     margin-right: 7%;
     height: 140px;
  }

  .nav-content li a.hamburger-icon  {
      display: none;
   }

   .header-logo{
      float: left;
   }

   .menu-section{
      float: right;
    }

   .nav-content{
       list-style-type: none;
       margin-top: 10%;
    }

   .menu-item{
       display: block;
       float: left;
       margin-left: 30px;

    }

   .menu-item a.active{
        color: #00B9F7
    }

   .nav-content li a{
       text-decoration: none;
       color: #fff;
       font-size: 18px;
    }

   .nav-content li a:hover {
       color: #00B9F7;
    }

   .header-title{
       color: #fff;
       font-size: 52px;
       line-height: 63px;
       text-align: center;
        margin: auto;
        width: 35%;

     }

    .header-video {
        margin: auto;
        width: fit-content;
        margin-top: 10%;
      }

responsive.css

@media (max-width:960px) {
    .header-title {
        font-size: 32px;
    }

   .partner-name, .user-comment, .search-question {
        font-size: 18px;
    }

   .partner-description{
        font-size: 12px;
    }

   .activity_item:nth-child(5), .activity_item:nth-child(6) {
        height: 258px;
    }

   .search-input {
        padding-right: 59%;
   }

   .nav-content li a{
        display: none;
   }

  .nav-content li a.hamburger-icon  {
       display: block;
   }

  .menu-item{
      float: right;
   }

  }

 @media (max-width:960px) {
     .nav-content.responsive {position: relative;}
     .nav-content.responsive .hamburger-icon {
         position: absolute;
         right: 0;
         top: 0;
      }
     .nav-content.responsive a {
         float: none;
         display: block;
      }
     .nav-content{
         background-color: #000;
         padding: 0%;
         width: 160px;
         text-align: center;
     }

    .menu-item{
        float: none;
        margin-left: 0%;
        line-height: 35px;
    }

    .menu-item:hover{
        background-color: #00B9F7;
    }

   .nav-content li a:hover {
        color: #fff;
    }

   .hamburger-icon{
        float: right;
    }

   }

javascript.js

Can you guys help me please, I do not understand why? in 840px my navigation menu not show for me? I need your help

Body:
From your given code, I made it to code snippet and run it. It is working fine.

function myFunction() {
  var x = document.getElementById("menu");
  if (x.className === "nav-content") {
    x.className += " responsive";
  } else {
    x.className = "nav-content";
  }
}

/* style.css */

/* -------header------- */

.header-container {
  background-image: linear-gradient( 0deg, rgba(35, 39, 49, -0.18), rgba(35, 39, 49, 1.82)), url("images/bg-image.jpeg");
  background-repeat: no-repeat;
  background-size: cover;
  box-sizing: border-box;
  position: relative;
  height: 743px;
  width: 100%;
}

/* nav bar */

.nav-bar {
  margin-left: 7%;
  margin-right: 7%;
  height: 140px;
}

.nav-content li a.hamburger-icon {
  display: none;
}

.header-logo {
  float: left;
}

.menu-section {
  float: right;
}

.nav-content {
  list-style-type: none;
  margin-top: 10%;
}

.menu-item {
  display: block;
  float: left;
  margin-left: 30px;
}

.menu-item a.active {
  color: #00B9F7
}

.nav-content li a {
  text-decoration: none;
  color: #fff;
  font-size: 18px;
}

.nav-content li a:hover {
  color: #00B9F7;
}

.header-title {
  color: #fff;
  font-size: 52px;
  line-height: 63px;
  text-align: center;
  margin: auto;
  width: 35%;
}

.header-video {
  margin: auto;
  width: fit-content;
  margin-top: 10%;
}

/* responsive.css */

@media (max-width:960px) {
  .header-title {
    font-size: 32px;
  }
  .partner-name,
  .user-comment,
  .search-question {
    font-size: 18px;
  }
  .partner-description {
    font-size: 12px;
  }
  .activity_item:nth-child(5),
  .activity_item:nth-child(6) {
    height: 258px;
  }
  .search-input {
    padding-right: 59%;
  }
  .nav-content li a {
    display: none;
  }
  .nav-content li a.hamburger-icon {
    display: block;
  }
  .menu-item {
    float: right;
  }
}

@media (max-width:960px) {
  .nav-content.responsive {
    position: relative;
  }
  .nav-content.responsive .hamburger-icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .nav-content.responsive a {
    float: none;
    display: block;
  }
  .nav-content {
    background-color: #000;
    padding: 0%;
    width: 160px;
    text-align: center;
  }
  .menu-item {
    float: none;
    margin-left: 0%;
    line-height: 35px;
  }
  .menu-item:hover {
    background-color: #00B9F7;
  }
  .nav-content li a:hover {
    color: #fff;
  }
  .hamburger-icon {
    float: right;
  }
}

<header class="header-container">

  <div class="header-content">
    <!-- nav bar -->
    <div class="nav-bar">
      <div class="header-logo">
        <a href="#">
          <img id="image-logo-header" class="bottom img-logo" src="images/logo.png">
        </a>
      </div>

      <div class="menu-section">
        <nav role="navigation">
          <ul class="nav-content" id="menu">
            <li class="menu-item"><a class="active" href="#">Home</a></li>
            <li class="menu-item"><a href="#">Blog</a></li>
            <li class="menu-item"><a href="#">About</a></li>
            <li class="menu-item"><a href="#">Contact</a></li>
            <li class="menu-item"><a href="#">Login</a></li>
            <li class="menu-item"><a href="#">Sign up</a></li>
            <li class="menu-item">
              <a href="#" class="hamburger-icon" onclick="myFunction()"><img src="images/hamburger.png" alt="hamburger icon"></a>
            </li>
          </ul>
        </nav>
      </div>
    </div>

    <h1 class="header-title">SHARE YOUR HOLIDDAY DREAM</h1>

    <div class="header-video">
      <img class="video-img" src="images/video-img.png">
    </div>
  </div>
</header>


答:
Following is a sample query for you to check and use the same logic for your update process using CTE-

DEMO HERE

Important Note: Update is a risky process and you should try with your test data first.

```<code>WITH CTE
AS
(
    SELECT *,
    (
        SELECT COUNT(*)
        FROM #Temp B
        WHERE B.FkLocationId = A.FkLocationId
        AND SortValue = 0
    ) Zero_Count,
    -- The above Zero count is a simple count of rows with 0
    -- for a specific FkLocationId. This is for adding to other
    -- rows where there are already value in column SortValue. The logic
    -- is simple, the number of row with 0 in column SortValue,
    -- should be add to existing value where there is value not equal 0.
    ROW_NUMBER() OVER (PARTITION BY FkLocationId ORDER BY SortValue ASC, FkProductId DESC) RN
    -- ROW_NUMBER is simply creating the Number you should replace 0 by.
    -- As you are looking for 1 to start for the MAX FkProductId with 0,
    -- I applied DESC order on that column
    FROM #Temp A
)

UPDATE A
SET A.SortValue =
CASE
    WHEN A.SortValue = 0 THEN B.RN
    -- RN is created in such way, so that you can directly
    -- Replace your value in column SortValue by RN if SortValue = 0
    ELSE A.SortValue + B.Zero_Count
    -- IF SortValue contains already value > 0,
    -- You need to just increment the value with Number
    -- of rows is there with value 0. I have calculated that value
    -- by a sub query in the CTE you can check.
END
FROM  #Temp A
INNER JOIN CTE B ON A.FkLocationId = B.FkLocationId
AND A.FkProductId = B.FkProductId

SELECT * FROM #Temp
</code>```

Just use your "table_name" where I have used #temp

Title: How to increment column by one group wise

Body:
I have a table called productLocation, and its data structure as follows,  SQLFiddle

+--------------+-------------+-----------+
| FkLocationId | FkProductId | SortValue |
+--------------+-------------+-----------+
| 1            | 100         | 0         |
+--------------+-------------+-----------+
| 1            | 101         | 0         |
+--------------+-------------+-----------+
| 1            | 102         | 0         |
+--------------+-------------+-----------+
| 1            | 103         | 2         |
+--------------+-------------+-----------+
| 1            | 104         | 1         |
+--------------+-------------+-----------+
| 1            | 105         | 3         |
+--------------+-------------+-----------+
| 2            | 100         | 0         |
+--------------+-------------+-----------+
| 2            | 101         | 0         |
+--------------+-------------+-----------+
| 2            | 102         | 0         |
+--------------+-------------+-----------+
| 2            | 103         | 1         |
+--------------+-------------+-----------+
| 2            | 104         | 3         |
+--------------+-------------+-----------+
| 2            | 105         | 2         |
+--------------+-------------+-----------+
| 3            | 100         | 0         |
+--------------+-------------+-----------+
| 3            | 101         | 0         |
+--------------+-------------+-----------+
| 3            | 102         | 0         |
+--------------+-------------+-----------+
| 3            | 103         | 1         |
+--------------+-------------+-----------+
| 3            | 104         | 2         |
+--------------+-------------+-----------+

For each location have its own sorting order for products. But some of the products have 0 as the SortValue
Now I need to write a query to update SortValue as,

If I consider one location, FkLocationId  = 1

+--------------+-------------+-----------+
| FkLocationId | FkProductId | SortValue |
+--------------+-------------+-----------+
| 1            | 100         | 0         |
+--------------+-------------+-----------+
| 1            | 101         | 0         |
+--------------+-------------+-----------+
| 1            | 102         | 0         |
+--------------+-------------+-----------+
| 1            | 103         | 2         |
+--------------+-------------+-----------+
| 1            | 104         | 1         |
+--------------+-------------+-----------+
| 1            | 105         | 3         |
+--------------+-------------+-----------+

In the above data table, you can see, FkProductId  = 100,101,102 have 0 as the SortValue. I need to update its sortValue as order by FkProductId descending order. I need to update its like

+--------------+-------------+-----------+
| FkLocationId | FkProductId | SortValue |
+--------------+-------------+-----------+
| 1            | 100         | 3         |
+--------------+-------------+-----------+
| 1            | 101         | 2         |
+--------------+-------------+-----------+
| 1            | 102         | 1         |
+--------------+-------------+-----------+

And also update the previous SortValue by one by one.

Then the complete output should be,

+--------------+-------------+-----------+
| FkLocationId | FkProductId | SortValue |
+--------------+-------------+-----------+
| 1            | 100         | 3         |
+--------------+-------------+-----------+
| 1            | 101         | 2         |
+--------------+-------------+-----------+
| 1            | 102         | 1         |
+--------------+-------------+-----------+
| 1            | 103         | 5         |
+--------------+-------------+-----------+
| 1            | 104         | 4         |
+--------------+-------------+-----------+
| 1            | 105         | 6         |
+--------------+-------------+-----------+

Is this possible to do? I'm really confused about this, please help me to solve this. Thank you

Updated:

Suppose I have another table as product. And its data structure as follows,

+-----------+-----------+
| ProdcutId | SortValue |
+-----------+-----------+
| 100       | 0         |
+-----------+-----------+
| 101       | 0         |
+-----------+-----------+
| 107       | 0         |
+-----------+-----------+
| 108       | 1         |
+-----------+-----------+
| 109       | 2         |
+-----------+-----------+
| 110       | 6         |
+-----------+-----------+
| 111       | 5         |
+-----------+-----------+
| 112       | 4         |
+-----------+-----------+
| 113       | 3         |
+-----------+-----------+

I also need to do same thing for this table as well, How can I do it

Expected Output:

+-----------+-----------+
| ProdcutId | SortValue |
+-----------+-----------+
| 100       | 3         |
+-----------+-----------+
| 101       | 2         |
+-----------+-----------+
| 107       | 1         |
+-----------+-----------+
| 108       | 4         |
+-----------+-----------+
| 109       | 5         |
+-----------+-----------+
| 110       | 9         |
+-----------+-----------+
| 111       | 8         |
+-----------+-----------+
| 112       | 7         |
+-----------+-----------+
| 113       | 6         |
+-----------+-----------+

Body:
Following is a sample query for you to check and use the same logic for your update process using CTE-

DEMO HERE

Important Note: Update is a risky process and you should try with your test data first.

WITH CTE
AS
(
    SELECT *,
    (
        SELECT COUNT(*)
        FROM #Temp B
        WHERE B.FkLocationId = A.FkLocationId
        AND SortValue = 0
    ) Zero_Count,
    -- The above Zero count is a simple count of rows with 0
    -- for a specific FkLocationId. This is for adding to other
    -- rows where there are already value in column SortValue. The logic
    -- is simple, the number of row with 0 in column SortValue,
    -- should be add to existing value where there is value not equal 0.
    ROW_NUMBER() OVER (PARTITION BY FkLocationId ORDER BY SortValue ASC, FkProductId DESC) RN
    -- ROW_NUMBER is simply creating the Number you should replace 0 by.
    -- As you are looking for 1 to start for the MAX FkProductId with 0,
    -- I applied DESC order on that column
    FROM #Temp A
)

UPDATE A
SET A.SortValue =
CASE
    WHEN A.SortValue = 0 THEN B.RN
    -- RN is created in such way, so that you can directly
    -- Replace your value in column SortValue by RN if SortValue = 0
    ELSE A.SortValue + B.Zero_Count
    -- IF SortValue contains already value > 0,
    -- You need to just increment the value with Number
    -- of rows is there with value 0. I have calculated that value
    -- by a sub query in the CTE you can check.
END
FROM  #Temp A
INNER JOIN CTE B ON A.FkLocationId = B.FkLocationId
AND A.FkProductId = B.FkProductId

SELECT * FROM #Temp

Just use your "table_name" where I have used #temp


问:
"Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
I have my User struct declared like this. How can we decode an array using JSONdecoder?

I get an error of typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

```<code>This is my json data:

// http://localhost:1337/user/5eca2fa01583786f1c0ee1bc

[
  {
    "id": "5eca2fa01583786f1c0ee1bc",
    "fullName": "Raj Shrestha",
    "emailAddress": "raj@yahoo.com",
    "following": [

    ],
    "followers": [
      {
        "id": "5eca2f451583786f1c0ee1ba",
        "fullName": "Udin Rajkarnikar",
        "emailAddress": "udin@gmail.com"
      }
    ],
    "isFollowing": true
  },
  [
    {
      "createdAt": 1590581837003,
      "updatedAt": 1590581837003,
      "id": "5ece5a4d6e2e801e95365d50",
      "text": "I love waterfalls",
      "imageUrl": "https://nepgram-bucket.s3.amazonaws.com/a121f7-6854-4fe9-bc8e-defce029d",
      "user": {
        "id": "5eca2fa01583786f1c0ee1bc",
        "fullName": "Raj Shrestha",
        "emailAddress": "raj@yahoo.com"
      }
    },
    {
      "createdAt": 1590334928984,
      "updatedAt": 1590334928984,
      "id": "5eca95d08538288438c63779",
      "text": "Creating post from iphone",
      "imageUrl": "https://nepgram-bucket.s3.amazonaws.com/2badfb0e-de49-4b6c-ae1-0c6",
      "user": {
        "id": "5eca2fa01583786f1c0ee1bc",
        "fullName": "Raj Shrestha",
        "emailAddress": "raj@yahoo.com"
      }
    },
    {
      "createdAt": 1590308888243,
      "updatedAt": 1590308888243,
      "id": "5eca30181583786f1c0ee1bf",
      "text": "asdasd",
      "imageUrl": "https://nepgram-bucket.s3.ap-south-1.amazonaws.com/83b7e688b-4d37-a368-3b8b4526bd58.png",
      "user": {
        "id": "5eca2fa01583786f1c0ee1bc",
        "fullName": "Raj Shrestha",
        "emailAddress": "raj@yahoo.com"
      }
    }
  ]
]

struct User: Decodable {
    let id : String
    let fullName: String
    let emailAddress: String
    var isFollowing: Bool?
    var followers, following: [User]?
    var post: [Post]?
}

struct Post: Decodable {
    let id: String
    let createdAt: Int
    let text: String
    let user: User
    let imageUrl: String
}

let user = try JSONDecoder().decode([User].self, from: data)

print(user)

</code>```

答:
This is how you can do it</p>

```<code>import Foundation

struct UserUnion: Codable {
    let fluffyUser:FluffyUser
    let purpleUserArray:[PurpleUser]
}

// MARK: - PurpleUser
struct PurpleUser: Codable {
    let createdAt, updatedAt: Int
    let id, text: String
    let imageURL: String
    let user: UserElement
}

// MARK: - UserElement
struct UserElement: Codable {
    let id, fullName, emailAddress: String
}

// MARK: - FluffyUser
struct FluffyUser: Codable {
    let id, fullName, emailAddress: String
    let following: [UserElement]?
    let followers: [UserElement]
    let isFollowing: Bool
}

let userUnion = try JSONDecoder().decode([UserUnion].self, from: data)

print(userUnion)
</code>```

Body:
I have my User struct declared like this. How can we decode an array using JSONdecoder?

I get an error of typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

This is my json data:

// http://localhost:1337/user/5eca2fa01583786f1c0ee1bc

[
  {
    "id": "5eca2fa01583786f1c0ee1bc",
    "fullName": "Raj Shrestha",
    "emailAddress": "raj@yahoo.com",
    "following": [

    ],
    "followers": [
      {
        "id": "5eca2f451583786f1c0ee1ba",
        "fullName": "Udin Rajkarnikar",
        "emailAddress": "udin@gmail.com"
      }
    ],
    "isFollowing": true
  },
  [
    {
      "createdAt": 1590581837003,
      "updatedAt": 1590581837003,
      "id": "5ece5a4d6e2e801e95365d50",
      "text": "I love waterfalls",
      "imageUrl": "https://nepgram-bucket.s3.amazonaws.com/a121f7-6854-4fe9-bc8e-defce029d",
      "user": {
        "id": "5eca2fa01583786f1c0ee1bc",
        "fullName": "Raj Shrestha",
        "emailAddress": "raj@yahoo.com"
      }
    },
    {
      "createdAt": 1590334928984,
      "updatedAt": 1590334928984,
      "id": "5eca95d08538288438c63779",
      "text": "Creating post from iphone",
      "imageUrl": "https://nepgram-bucket.s3.amazonaws.com/2badfb0e-de49-4b6c-ae1-0c6",
      "user": {
        "id": "5eca2fa01583786f1c0ee1bc",
        "fullName": "Raj Shrestha",
        "emailAddress": "raj@yahoo.com"
      }
    },
    {
      "createdAt": 1590308888243,
      "updatedAt": 1590308888243,
      "id": "5eca30181583786f1c0ee1bf",
      "text": "asdasd",
      "imageUrl": "https://nepgram-bucket.s3.ap-south-1.amazonaws.com/83b7e688b-4d37-a368-3b8b4526bd58.png",
      "user": {
        "id": "5eca2fa01583786f1c0ee1bc",
        "fullName": "Raj Shrestha",
        "emailAddress": "raj@yahoo.com"
      }
    }
  ]
]

struct User: Decodable {
    let id : String
    let fullName: String
    let emailAddress: String
    var isFollowing: Bool?
    var followers, following: [User]?
    var post: [Post]?
}

struct Post: Decodable {
    let id: String
    let createdAt: Int
    let text: String
    let user: User
    let imageUrl: String
}

let user = try JSONDecoder().decode([User].self, from: data)

print(user)

Body:
This is how you can do it

import Foundation

struct UserUnion: Codable {
    let fluffyUser:FluffyUser
    let purpleUserArray:[PurpleUser]
}

// MARK: - PurpleUser
struct PurpleUser: Codable {
    let createdAt, updatedAt: Int
    let id, text: String
    let imageURL: String
    let user: UserElement
}

// MARK: - UserElement
struct UserElement: Codable {
    let id, fullName, emailAddress: String
}

// MARK: - FluffyUser
struct FluffyUser: Codable {
    let id, fullName, emailAddress: String
    let following: [UserElement]?
    let followers: [UserElement]
    let isFollowing: Bool
}

let userUnion = try JSONDecoder().decode([UserUnion].self, from: data)

print(userUnion)


问:
Where should I put these strange files in the file structure for Flask app?
So I downloaded a template for a website, with the aim to use it in my Flask app. I know the basic file structure of Flask app is this:

```<code>-app
 app.py
 -static
  -images
    -image files
  -style
    -css files
 -templates
  -html files
</code>```

But when I opened the folder of the template code, I found all these strange files and I couldn't decide where to put them.

The original files:

So I put the css, fonts, images, js folders into the static folder and left the rest of the files in the templates folder along with index.html (ignore index - Copy.html, that is a copy I made of the original index.html file), updated the paths of css and js files inside the HTML document and executed app.py.

The file ran but most of the text of index.html was not loading and only one image was being displayed. I checked the logs in the command line terminal and discovered that most of the css was not even getting called.

What am I doing wrong? How should I arrange these files?

答:
In your html file you should connect styles in this way:</p>

```<code><link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/style.css') }}">
</code>```

Body:
So I downloaded a template for a website, with the aim to use it in my Flask app. I know the basic file structure of Flask app is this:

-app
 app.py
 -static
  -images
    -image files
  -style
    -css files
 -templates
  -html files

But when I opened the folder of the template code, I found all these strange files and I couldn't decide where to put them.

The original files:

So I put the css, fonts, images, js folders into the static folder and left the rest of the files in the templates folder along with index.html (ignore index - Copy.html, that is a copy I made of the original index.html file), updated the paths of css and js files inside the HTML document and executed app.py.

The file ran but most of the text of index.html was not loading and only one image was being displayed. I checked the logs in the command line terminal and discovered that most of the css was not even getting called.

What am I doing wrong? How should I arrange these files?

Body:
In your html file you should connect styles in this way:

<link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/style.css') }}">


问:
How to simplify many if else statements
I want to simplify this code and want to make it smarter, there are about 80 singleS and multipleS's. I considered State design pattern usage but it seems that it wont be simpler. Can anybody help me with the below lines:</p>

```<code>void spy::run(string num, SingleS single, MultipleS multipleS)
{
if(num == "1")
{singleS.runS1}
else if(num == "2")
{singleS.runS2}
else if(num == "3")
{singleS.runS3}
else if(num == "4")
{singleS.runS4}
else if(num == "5")
{singleS.runS5}
else if(num == "6")
{singleS.runS6}
else if(num == "7")
{singleS.runS7}
else if(num == "8")
{singleS.runS8}
else if(num == "9")
{singleS.runS9}
else if(num == "10")
{multipleS.runS10}
else if(num == "11")
{multipleS.runS11}
else if(num == "12")
{multipleS.runS12}
else if(num == "13")
{multipleS.runS13}
}
}

</code>```

答:
You can use std::map or std::unordered_map like that

```<code>std::unordered_map<std::string, std::function<void(void)>> functionsMap = {
   {"1", std::bind(&SingleS::runS1, &singleS)},
   {"12", std::bind(&MultipleS::runS12, &multipleS)},
...
};

auto it = functionsMap.find(num);
if (it != functionsMap.end())
    it->second();
...
</code>```

Links: http://www.cplusplus.com/reference/functional/bind/, http://www.cplusplus.com/reference/functional/function/function/, http://www.cplusplus.com/reference/unordered_map/unordered_map/

Title: How to simplify many if else statements

Body:
I want to simplify this code and want to make it smarter, there are about 80 singleS and multipleS's. I considered State design pattern usage but it seems that it wont be simpler. Can anybody help me with the below lines:

void spy::run(string num, SingleS single, MultipleS multipleS)
{
if(num == "1")
{singleS.runS1}
else if(num == "2")
{singleS.runS2}
else if(num == "3")
{singleS.runS3}
else if(num == "4")
{singleS.runS4}
else if(num == "5")
{singleS.runS5}
else if(num == "6")
{singleS.runS6}
else if(num == "7")
{singleS.runS7}
else if(num == "8")
{singleS.runS8}
else if(num == "9")
{singleS.runS9}
else if(num == "10")
{multipleS.runS10}
else if(num == "11")
{multipleS.runS11}
else if(num == "12")
{multipleS.runS12}
else if(num == "13")
{multipleS.runS13}
}
}

Body:
You can use std::map or std::unordered_map like that

std::unordered_map<std::string, std::function<void(void)>> functionsMap = {
   {"1", std::bind(&SingleS::runS1, &singleS)},
   {"12", std::bind(&MultipleS::runS12, &multipleS)},
...
};

auto it = functionsMap.find(num);
if (it != functionsMap.end())
    it->second();
...

Links: http://www.cplusplus.com/reference/functional/bind/, http://www.cplusplus.com/reference/functional/function/function/, http://www.cplusplus.com/reference/unordered_map/unordered_map/


问:
HTML5 - Select multi required-checkbox
I've writen some code here: http://jsfiddle.net/anhtran/kXsj9/8/

Users have to select at least 1 option on the group. But it makes me must click all of them to submit the form. How to do this issue without javascript?

Thanks for any help :)

答:
You can't do this without javascript.
What you can do is select a default option and set it as selected.
But it can't assure you that a checkbox is selected when the form is submitted.</p>

Title: HTML5 - Select multi required-checkbox


问:
(TFS) Test Result meaning of field "Tested Build"
I am working with Azure DevOps Server (TFS) Test Management tool but there is a field concerning Test Results that I can find anywhere in docs for explanation.

The field is named Tested Build, I've attached an image highlighting it.
If one can give maximum details about it, it would be great.
Thanks

答: Tested Build is the build number when this test run is produced from a pipeline. For example, if you use Visual Studio Test task to run tests in a pipeline, you'll see the Tested Build shows the build number.


问:
pandas DataFrame: aggregate values within blocks of repeating IDs
Given a DataFrame with an ID column and corresponding values column, how can I aggregate (let's say sum) the values within blocks of repeating IDs?

Example DF:

```<code>import numpy as np
import pandas as pd

df = pd.DataFrame(
    {'id': ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'a', 'a', 'b', 'a', 'b', 'b', 'b'],
     'v': np.ones(15)}
    )
</code>```

Note that there's only two unique IDs, so a simple groupby('id') won't work. Also, the IDs don't alternate/repeat in a regular manner. What I came up with was to recreate the index, to represent the blocks of changed IDs:

```<code># where id changes:
m = [True] + list(df['id'].values[:-1] != df['id'].values[1:])

# generate a new index from m:
idx, i = [], -1
for b in m:
    if b:
        i += 1
    idx.append(i)

# set as index:
df = df.set_index(np.array(idx))

# now I can use groupby:
df.groupby(df.index)['v'].sum()
# 0    5.0
# 1    3.0
# 2    2.0
# 3    1.0
# 4    1.0
# 5    3.0
</code>```

This re-creation of the index feels sort-of not how you'd do this in pandas. What did I miss? Is there a better way to do this?

答:
Here is necessary create helper Series with compare shifted values for not equal by ne with cumulative sums and pass to groupby, for id column is possible pass together in list, remove first level of MultiIndex by first reset_index(level=0, drop=True) and then convert index to column id:

```<code>print (df['id'].ne(df['id'].shift()).cumsum())
0     1
1     1
2     1
3     1
4     1
5     2
6     2
7     2
8     3
9     3
10    4
11    5
12    6
13    6
14    6
Name: id, dtype: int32

df1 = (df.groupby([df['id'].ne(df['id'].shift()).cumsum(), 'id'])['v'].sum()
          .reset_index(level=0, drop=True)
          .reset_index())
print (df1)
  id    v
0  a  5.0
1  b  3.0
2  a  2.0
3  b  1.0
4  a  1.0
5  b  3.0
</code>```

Another idea is useGroupBy.agg with dictioanry and aggregate id column by GroupBy.first:

```<code>df1 = (df.groupby(df['id'].ne(df['id'].shift()).cumsum(), as_index=False)
         .agg({'id':'first', 'v':'sum'}))
</code>```

Body:
Given a DataFrame with an ID column and corresponding values column, how can I aggregate (let's say sum) the values within blocks of repeating IDs?

Example DF:

import numpy as np
import pandas as pd

df = pd.DataFrame(
    {'id': ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'a', 'a', 'b', 'a', 'b', 'b', 'b'],
     'v': np.ones(15)}
    )

Note that there's only two unique IDs, so a simple groupby('id') won't work. Also, the IDs don't alternate/repeat in a regular manner. What I came up with was to recreate the index, to represent the blocks of changed IDs:

# where id changes:
m = [True] + list(df['id'].values[:-1] != df['id'].values[1:])

# generate a new index from m:
idx, i = [], -1
for b in m:
    if b:
        i += 1
    idx.append(i)

# set as index:
df = df.set_index(np.array(idx))

# now I can use groupby:
df.groupby(df.index)['v'].sum()
# 0    5.0
# 1    3.0
# 2    2.0
# 3    1.0
# 4    1.0
# 5    3.0

This re-creation of the index feels sort-of not how you'd do this in pandas. What did I miss? Is there a better way to do this?

Body:
Here is necessary create helper Series with compare shifted values for not equal by ne with cumulative sums and pass to groupby, for id column is possible pass together in list, remove first level of MultiIndex by first reset_index(level=0, drop=True) and then convert index to column id:

print (df['id'].ne(df['id'].shift()).cumsum())
0     1
1     1
2     1
3     1
4     1
5     2
6     2
7     2
8     3
9     3
10    4
11    5
12    6
13    6
14    6
Name: id, dtype: int32

df1 = (df.groupby([df['id'].ne(df['id'].shift()).cumsum(), 'id'])['v'].sum()
          .reset_index(level=0, drop=True)
          .reset_index())
print (df1)
  id    v
0  a  5.0
1  b  3.0
2  a  2.0
3  b  1.0
4  a  1.0
5  b  3.0

Another idea is useGroupBy.agg with dictioanry and aggregate id column by GroupBy.first:

df1 = (df.groupby(df['id'].ne(df['id'].shift()).cumsum(), as_index=False)
         .agg({'id':'first', 'v':'sum'}))


问:
How to create Zip and upload files to it on google storage?
Using NodeJs v12, We have multiple files creating dynamically for every minute, these files should be uploaded to cloud storage as zip, and this zip files should be updated with new files which are created on my system.

I have referred some docs, it says there is no directory concept in GCS, then how can we archive it?, We have observed that gzip added for files/object.

using @google-cloud/storage latest.

Current code:

```<code>storage.bucket(bucketName).upload(destinationStorage, {
     gzip: true,
     destination: userId+"/"+filename,
     metadata: {
         cacheControl: 'no-cache'
     },
}).then( async(result) =>{
     console.log("Uploaded");
})
</code>```

答:
In GCS, you can only create, read and delete object. It's not a file system. You can't move (even if you have the option, it's only a create elsewhere and delete the origin) and you can't update the content (you can create a new version if you activate the versioning, but you can't change an existing content)

So, now you understand that you can't update an existing zip to add a file in it. You have to upload it again, with the whole content.

About ZIP and GZIP. It's 2 different things that you don't have to mix up. GZIP compresses only 1 file, ZIP compress files AND can create a package with 1 or several files/folders in it.

So you can't add several files into GZIP, only in ZIP. And ZIP isn't native to GCS, you have to handle the ZIP compression/file management on your side before sending the blob to GCS.

Anyway, I have the feeling that I have cleared up some misunderstood parts but not solved your issues. Don't hesitate to comment if you want more help!

Body:
Using NodeJs v12, We have multiple files creating dynamically for every minute, these files should be uploaded to cloud storage as zip, and this zip files should be updated with new files which are created on my system.

I have referred some docs, it says there is no directory concept in GCS, then how can we archive it?, We have observed that gzip added for files/object.

using @google-cloud/storage latest.

Current code:

storage.bucket(bucketName).upload(destinationStorage, {
     gzip: true,
     destination: userId+"/"+filename,
     metadata: {
         cacheControl: 'no-cache'
     },
}).then( async(result) =>{
     console.log("Uploaded");
})


问:
can any one tell me the name of alert view that should do the works of **C# show dialog**
can any one tell me the name of alert view that should do the works of   C# show dialog .
other actions will not work without dismissing it(EVEN DELEGATES ALSO).

答:
Modal dialogs in Windows (in any language) and in iOS are fundamentally different.

On Windows, a modal dialog (and in particular the ShowDialog method) behaves like a function call that will only return when the dialog is closed. Your app will naturally wait until the your has made his decision.

On iOS, presentModalViewController (or [UIAlertView show]) almost immediately return. You can registered a delegate that will be notified when the dialog is closed. But if your app is supposed to wait only the user has chosen something in the dialog, then you have to implement the waiting yourself.


问:
XCode Error: The maximum number of apps for free development profiles has been reached
Get this error when trying to install the app on a device to test. I have no apps that I'v developed on the device, so the error does not make sense.

Have tried the solutions mentioned in other similar Stackoverflow posts:

unpair and pair the device again

delete profiles from Window >
Devices (I had only one profile)

XCode version: 11.5

Phone iOS version: 13.5

Error Details:

```<code>The maximum number of apps for free development profiles has been reached.
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402620383
User Info: {
    DVTRadarComponentKey = 487925;
    MobileDeviceErrorCode = "(0xE8008021)";
    "com.apple.dtdevicekit.stacktrace" = (
0   DTDeviceKitBase                     0x000000011bc5081a DTDKCreateNSErrorFromAMDErrorCode + 233
1   DTDeviceKitBase                     0x000000011bc91f70 __90-[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:]_block_invoke + 155
2   DVTFoundation                       0x00000001029e9145 DVTInvokeWithStrongOwnership + 73
3   DTDeviceKitBase                     0x000000011bc91ca8 -[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:] + 1654
4   IDEiOSSupportCore                   0x000000011bb08e91 __118-[DVTiOSDevice(DVTiPhoneApplicationInstallation) processAppInstallSet:appUninstallSet:installOptions:completionBlock:]_block_invoke.352 + 4165
5   DVTFoundation                       0x0000000102b1c7e4 __DVT_CALLING_CLIENT_BLOCK__ + 7
6   DVTFoundation                       0x0000000102b1e426 __DVTDispatchAsync_block_invoke + 1194
7   libdispatch.dylib                   0x00007fff726606c4 _dispatch_call_block_and_release + 12
8   libdispatch.dylib                   0x00007fff72661658 _dispatch_client_callout + 8
9   libdispatch.dylib                   0x00007fff72666c44 _dispatch_lane_serial_drain + 597
10  libdispatch.dylib                   0x00007fff726675d6 _dispatch_lane_invoke + 363
11  libdispatch.dylib                   0x00007fff72670c09 _dispatch_workloop_worker_thread + 596
12  libsystem_pthread.dylib             0x00007fff728bba3d _pthread_wqthread + 290
13  libsystem_pthread.dylib             0x00007fff728bab77 start_wqthread + 15
);
}
</code>```

答:
What did not work:

deleting the provisioning profiles that are installed on the device (from the device manager in Xcode)

cleared out any apps that I had installed on the device

cleared out sufficient space from the phone

What did work:

In my case I think the problem arose because I recently joined the developer programme.

So it was like 3 days ago everything was working fine. But after I made payments and my membership was under review, I started getting this error. Even after approval of membership I was getting the same error.

So I just thought that I would revoke my older dev certificate and create a new one with the "new" account.

And that worked.
So, I suspect in my scenario the privilege changes was the issue.

Body:
Get this error when trying to install the app on a device to test. I have no apps that I'v developed on the device, so the error does not make sense.

Have tried the solutions mentioned in other similar Stackoverflow posts:

unpair and pair the device again

delete profiles from Window >
Devices (I had only one profile)

XCode version: 11.5

Phone iOS version: 13.5

Error Details:

The maximum number of apps for free development profiles has been reached.
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402620383
User Info: {
    DVTRadarComponentKey = 487925;
    MobileDeviceErrorCode = "(0xE8008021)";
    "com.apple.dtdevicekit.stacktrace" = (
0   DTDeviceKitBase                     0x000000011bc5081a DTDKCreateNSErrorFromAMDErrorCode + 233
1   DTDeviceKitBase                     0x000000011bc91f70 __90-[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:]_block_invoke + 155
2   DVTFoundation                       0x00000001029e9145 DVTInvokeWithStrongOwnership + 73
3   DTDeviceKitBase                     0x000000011bc91ca8 -[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:] + 1654
4   IDEiOSSupportCore                   0x000000011bb08e91 __118-[DVTiOSDevice(DVTiPhoneApplicationInstallation) processAppInstallSet:appUninstallSet:installOptions:completionBlock:]_block_invoke.352 + 4165
5   DVTFoundation                       0x0000000102b1c7e4 __DVT_CALLING_CLIENT_BLOCK__ + 7
6   DVTFoundation                       0x0000000102b1e426 __DVTDispatchAsync_block_invoke + 1194
7   libdispatch.dylib                   0x00007fff726606c4 _dispatch_call_block_and_release + 12
8   libdispatch.dylib                   0x00007fff72661658 _dispatch_client_callout + 8
9   libdispatch.dylib                   0x00007fff72666c44 _dispatch_lane_serial_drain + 597
10  libdispatch.dylib                   0x00007fff726675d6 _dispatch_lane_invoke + 363
11  libdispatch.dylib                   0x00007fff72670c09 _dispatch_workloop_worker_thread + 596
12  libsystem_pthread.dylib             0x00007fff728bba3d _pthread_wqthread + 290
13  libsystem_pthread.dylib             0x00007fff728bab77 start_wqthread + 15
);
}


问:
Can anybody explain syntax
```<code>  const lastTick = this.xAxis[0].ticks[this.xAxis[0].tickPositions.length - 1];
  const { width } = lastTick.label.getBBox();
  const { chartWidth } = this;
  lastTick.label.attr({ x: chartWidth - (0.7) * width });

</code>```

This is highcharts code. I want meaning of { width } , { chartWidth }.

答:
It's called Destructuring assignment. It is similar to writing

const chartWidth = this.chartWidth;
const width = lastTick.label.getBBox().width;
```

Title: Can anybody explain syntax

Body:
  const lastTick = this.xAxis[0].ticks[this.xAxis[0].tickPositions.length - 1];
  const { width } = lastTick.label.getBBox();
  const { chartWidth } = this;
  lastTick.label.attr({ x: chartWidth - (0.7) * width });

This is highcharts code. I want meaning of { width } , { chartWidth }.


问:
How to configure Asp.Net Web Application with IIS
I am using Asp.Net Standard version 4.7 with MVC and attempting to deploy to IIS Express. I am facing several issues in the configuration and cant seem to find straight forward documentation for asp.Net standard. I added a website named localHost aside from Default Website in IIS. I am facing 2 issues.
 When I click browse from IIS,  it navigates http://localhost/Views/Home/Index.cshtml  I get a 404 error.

Server Error in '/' Application. The resource cannot be found

When Debugging From Visual studio 2019 I get

Process with Id of xxxx cant be found
  .
  Description: HTTP 404.

I am thinking there some port configuration issue but I am unclear on how to configure.

I attached screenshots of my configuration settings.

答:
To host the site .net application you need to publish it and use that publish folder as site folder path in iis.

1)open visual studio, select your project.

2)right-click on your project and choose publish:

3)in publish target select folder and create a new folder in c or another drive where can you access the folder.

4)click on the publish

5)open iis and create a new site

6)choose the folder path and site binding

7)browser your site.

Note:

Assign iis_iusrs and iusr full permission to the site folder. you need to set the physical path credential with your Gmail account.


问:
php - how to increment a user's known earning every day for 4 months
I want to display  to a user an amount per day and increment it until the next 124 days assumed to be four months.

I have a system where a user invest and a total ernable profit is calculated with the percentage ROI for such stock. Assuming someone invested in a stockA that has 20% ROI and matures in 4 months; assuming a user purchased that stockA that is sold $100 and he bought 4 units meaning he spent $400 and will earn
as follows:

```<code>$units = 4;
$cost = 100;
$roi = 20/100;
$total_invested = $units * $cost;

$profit  = $total_invest *  $roi;
// $profit will be $80
</code>```

My problem is I want to display value of $profit/124 that is the displaying a fraction of total earning to the user daily until maturity of 4 months. I can't figure out how to do that daily not just with loop of 124 iterations.

that is if the user total earning is $80/124 giving 0.65 on the first day and increment it with same value the next day until it reached the end date which is 4 months from now

/**
 *
 * display and increment earning every day for 4 months or 124 days
 *
 */

function display_earning() {
  $profit = $profit_roi;
  $dateBegin = now();
  $dateEnd = "date of 4 month from now";
  $earning = 0;

  for ($i = 0; $i < 124; $i++) {
    $earning += $profit / 124;
    return $earning;
  }
}
```

答:
I think your problem is to update and save the updated earning of user for 4 months. To do that you need to write a server level cron-job that run on every day and a script in which you update and save the earning of user and check it has reached 4 months for that user since you started or not.

I hope you want this and that will help you. Happy Learning.

Body:
I want to display  to a user an amount per day and increment it until the next 124 days assumed to be four months.

I have a system where a user invest and a total ernable profit is calculated with the percentage ROI for such stock. Assuming someone invested in a stockA that has 20% ROI and matures in 4 months; assuming a user purchased that stockA that is sold $100 and he bought 4 units meaning he spent $400 and will earn
as follows:

$units = 4;
$cost = 100;
$roi = 20/100;
$total_invested = $units * $cost;

$profit  = $total_invest *  $roi;
// $profit will be $80

My problem is I want to display value of $profit/124 that is the displaying a fraction of total earning to the user daily until maturity of 4 months. I can't figure out how to do that daily not just with loop of 124 iterations.

that is if the user total earning is $80/124 giving 0.65 on the first day and increment it with same value the next day until it reached the end date which is 4 months from now

/**
 *
 * display and increment earning every day for 4 months or 124 days
 *
 */

function display_earning() {
  $profit = $profit_roi;
  $dateBegin = now();
  $dateEnd = "date of 4 month from now";
  $earning = 0;

  for ($i = 0; $i < 124; $i++) {
    $earning += $profit / 124;
    return $earning;
  }
}


问:
from C++ to C#
What are good c++ to C# articles/tutorial or books?
I am reading http://msdn.microsoft.com/en-us/magazine/cc301520.aspx and will read http://andymcm.com/csharpfaq.htm and http://www.ondotnet.com/pub/a/dotnet/2002/02/11/csharp_traps.html afterwards. Have any of you read any good books for ppl who have a strong understanding of programming && || C++ on the C# language (and libraries)?</p>

答:
Personally when I had to learn C# I would type the name of what I was looking for in the C++ term and tack on C#. For example:

std::vector C#

which gave me several pages dedicated to explaining lists and other types in C# that did what that exact code did in C++. Worked fairly well, even for some of the lesser used parts of the STL/Templating library.

ContentLicense: CC BY-SA 2.5

Title: from C++ to C#

OwnerDisplayName: X-Istence


问:
Is there a tool to convert SVG line paths from absolute to relative?
Looking for a tool to convert something like

```<code>M10 20L0 0 5 5 10 10
</code>```

from the absolute position to relative, something like:

```<code>M10 20l-10 -20 5 5 5 5
</code>```

Notice the uppercase L for absolute and lowercase l for relative?

Body:
Looking for a tool to convert something like

M10 20L0 0 5 5 10 10

from the absolute position to relative, something like:

M10 20l-10 -20 5 5 5 5

Notice the uppercase L for absolute and lowercase l for relative?

Body:
For who's still searching for this tool. There is one made by Lea Verou on codepen that convert paths to relative or absolute.

Example convert this:

M233.51,56.8c-0.57,0.24-1.33,0.52-2.28,0.86c-0.95,0.33-1.93,0.5-2.92,0.5s-1.84-0.27-2.53-0.82
c-0.69-0.55-1.03-1.49-1.03-2.82V36.25h7.85V28.9h-7.85V16.77h-9.56V28.9h-17.84V16.77h-9.56V28.9h-4.92v7.35h4.92v21.48
c0,1.67,0.26,3.08,0.79,4.25c0.52,1.17,1.22,2.12,2.1,2.85c0.88,0.74,1.9,1.27,3.07,1.61c1.16,0.33,2.41,0.5,3.75,0.5
c2.05,0,4-0.28,5.85-0.86c1.86-0.57,3.42-1.14,4.71-1.71l-1.93-7.56c-0.57,0.24-1.33,0.52-2.28,0.86c-0.95,0.33-1.93,0.5-2.92,0.5
c-1,0-1.84-0.27-2.53-0.82c-0.69-0.55-1.03-1.49-1.03-2.82V36.25h17.84v21.48c0,1.67,0.26,3.08,0.79,4.25
c0.52,1.17,1.22,2.12,2.1,2.85c0.88,0.74,1.9,1.27,3.07,1.61c1.16,0.33,2.41,0.5,3.75,0.5c2.05,0,4-0.28,5.85-0.86
c1.86-0.57,3.42-1.14,4.71-1.71L233.51,56.

Into this:

M233.51,56.8c-0.57,0.24,-1.33,0.52,-2.28,0.86c-0.95,0.33,-1.93,0.5,-2.92,0.5s-1.84,-0.27,-2.53,-0.82c-0.69,-0.55,-1.03,-1.49,-1.03,-2.82v-18.27h7.85v-7.35h-7.85v-12.13h-9.56v12.13h-17.84v-12.13h-9.56v12.13h-4.92v7.35h4.92v21.48c0,1.67,0.26,3.08,0.79,4.25c0.52,1.17,1.22,2.12,2.1,2.85c0.88,0.74,1.9,1.27,3.07,1.61c1.16,0.33,2.41,0.5,3.75,0.5c2.05,0,4,-0.28,5.85,-0.86c1.86,-0.57,3.42,-1.14,4.71,-1.71l-1.93,-7.56c-0.57,0.24,-1.33,0.52,-2.28,0.86c-0.95,0.33,-1.93,0.5,-2.92,0.5c-1,0,-1.84,-0.27,-2.53,-0.82c-0.69,-0.55,-1.03,-1.49,-1.03,-2.82v-18.28h17.84v21.48c0,1.67,0.26,3.08,0.79,4.25c0.52,1.17,1.22,2.12,2.1,2.85c0.88,0.74,1.9,1.27,3.07,1.61c1.16,0.33,2.41,0.5,3.75,0.5c2.05,0,4,-0.28,5.85,-0.86c1.86,-0.57,3.42,-1.14,4.71,-1.71l-1.97,-7.57z

https://codepen.io/leaverou/pen/RmwzKv


问:
Spring Data JPA - How to implement LIKE search with multiple values on the same column
Lets say I've the following table,

MOVIE_TITLE

Batman Begins

Batman Returns

Return of the Jedi

The Lord of the Rings: The Return of the King

Shakespeare in Love

Dead Poets Society

Deadpool

The Lord of the Rings: The Fellowship of the Ring

I'd like to implement a search on the movie title and pass comma separated values (search with multiple keywords)

For example,

search text: Batman
result: Records #1,2

search text: Batman, Return
result: Records #1,2,3,4

search text: Lord, Love
result: Records #4,5,8

Without looping for each of the keyword, can this be implemented in one call using the LIKE search (or something else) in Spring Data JPA?

Thanks

答:
In case you really don't want to combine multiple LIKEs in a loop, you can use Regular Expressions. However, there is no standard RegEx matching in T-SQL, but there are database-dependent solutions.

For example in Postgres you can use ~* operator to match column against Regular Expression

```<code>sql> select 'The Lord of the Rings: The Return of the King' ~* '(King|Queen|Princess|Lord|Duke|Baron)'
[2020-06-03 14:09:28] 1 row retrieved
</code>```

And of course you have to do some preparations before query.

Repository layer:

```<code>@Query(value = "select * from Movie_table where movie_title ~* :term", nativeQuery = true)
public List<Object[]> findMovies(@Param("term") String term);
</code>```

Service layer:

```<code>String searchText = "Lord, Love";
String searchTerm = Arrays.stream(searchText.split(","))
                    .map(String::trim)
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.joining("|", "(", ")"));

List<Object[]> movies = movieRepository.findMovies(searchTerm);
// ... code to convert `Object[]`-s to `Movie` entities ...

</code>```

P.S. This solution is less elegant in compare to multiple LIKE/OR query

Body:
In case you really don't want to combine multiple LIKEs in a loop, you can use Regular Expressions. However, there is no standard RegEx matching in T-SQL, but there are database-dependent solutions.

For example in Postgres you can use ~* operator to match column against Regular Expression

sql> select 'The Lord of the Rings: The Return of the King' ~* '(King|Queen|Princess|Lord|Duke|Baron)'
[2020-06-03 14:09:28] 1 row retrieved

And of course you have to do some preparations before query.

Repository layer:

@Query(value = "select * from Movie_table where movie_title ~* :term", nativeQuery = true)
public List<Object[]> findMovies(@Param("term") String term);

Service layer:

String searchText = "Lord, Love";
String searchTerm = Arrays.stream(searchText.split(","))
                    .map(String::trim)
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.joining("|", "(", ")"));

List<Object[]> movies = movieRepository.findMovies(searchTerm);
// ... code to convert `Object[]`-s to `Movie` entities ...

P.S. This solution is less elegant in compare to multiple LIKE/OR query


问:
Getting vertical lists of lists of lists in prolog?
a List of Lists like

Lists=[ [1,2,3],
          [4,5,6],
          [7,8,3] ]

and i want to get in this case all vertical lists like

[1,4,7], [2,5,8], [3,6,3]

how to do that? i thought about 2 counters witch work together like two "for to do" repeats.
i need to check with "is_set" if [1,4,7] is a set or [3,6,3] witch of course is not.

like this:

el_at(Llist,Gl,1),

```<code>el_at(EList, Llist,1),
</code>```

```<code>         globalListVertikalCheck(ListVertikal),
         addlist(Elist,ListVertikal,NewListVertikal),
</code>```

el_at(Llist,Gl,2),

```<code>el_at(EList, Llist,2),
</code>```

```<code>       globalListVertikalCheck(ListVertikal),
       addlist(Elist,ListVertikal,NewListVertikal),
</code>```

thanks

答:
I didn't fully understand the solution you propose, but I have another one. I will try to describe how it works and maybe than you can see what was wrong with your solution and why it didn't work.

Let's consider an example of [[1,2], [3,4]]. The idea is to go through the first sub-list [1,2] and create an incomplete result [[1],[2]], then go through the next one [3,4] and prepend (which is easier than append in Prolog) each item in it to the each sub-list in the result. We will end up with [[3,1], [4,1]]. The sub-lists are then reversed and we have the result [[1,3],[1,4]].

Now the implementation:
The vertical predicate is the core, it goes through the list of lists and the result is step by step accumulated in the Acc varible.

For each of the sublists, the vertical predicate calls the addfirst predicate, which takes each element of that sublist and prepends it to the list in which the previous results were accumulated.

```<code>vertical([X|Xs],Result):-
    createempty(X, Acc),
    vertical([X|Xs], Acc, ReversedResults),
    reverseall(ReversedResults, Result).

reverseall([], []).
reverseall([X|Xs], [XReversed|Rest]):-
    reverse(X, XReversed),
    reverseall(Xs, Rest).

createempty([], []).
createempty([X|Xs], [[]|R]):-createempty(Xs,R).

vertical([], Result, Result).
vertical([X|Xs], Acc, Result):-
    addfirst(X, Acc2, Acc),
    vertical(Xs, Acc2, Result).

addfirst([], [], []).
addfirst(
    [Y|Ys],
    [[Y|YVerticalRest]|ResultRest],
    [YVerticalRest|VerticalsRest]):-
    addfirst(Ys, ResultRest, VerticalsRest).
</code>```

Body:
a List of Lists like

Lists=[ [1,2,3],
          [4,5,6],
          [7,8,3] ]

and i want to get in this case all vertical lists like

[1,4,7], [2,5,8], [3,6,3]

how to do that? i thought about 2 counters witch work together like two "for to do" repeats.
i need to check with "is_set" if [1,4,7] is a set or [3,6,3] witch of course is not.

like this:

el_at(Llist,Gl,1),

el_at(EList, Llist,1),

         globalListVertikalCheck(ListVertikal),
         addlist(Elist,ListVertikal,NewListVertikal),

el_at(Llist,Gl,2),

el_at(EList, Llist,2),

       globalListVertikalCheck(ListVertikal),
       addlist(Elist,ListVertikal,NewListVertikal),

thanks

Body:
I didn't fully understand the solution you propose, but I have another one. I will try to describe how it works and maybe than you can see what was wrong with your solution and why it didn't work.

Let's consider an example of [[1,2], [3,4]]. The idea is to go through the first sub-list [1,2] and create an incomplete result [[1],[2]], then go through the next one [3,4] and prepend (which is easier than append in Prolog) each item in it to the each sub-list in the result. We will end up with [[3,1], [4,1]]. The sub-lists are then reversed and we have the result [[1,3],[1,4]].

Now the implementation:
The vertical predicate is the core, it goes through the list of lists and the result is step by step accumulated in the Acc varible.

For each of the sublists, the vertical predicate calls the addfirst predicate, which takes each element of that sublist and prepends it to the list in which the previous results were accumulated.

vertical([X|Xs],Result):-
    createempty(X, Acc),
    vertical([X|Xs], Acc, ReversedResults),
    reverseall(ReversedResults, Result).

reverseall([], []).
reverseall([X|Xs], [XReversed|Rest]):-
    reverse(X, XReversed),
    reverseall(Xs, Rest).

createempty([], []).
createempty([X|Xs], [[]|R]):-createempty(Xs,R).

vertical([], Result, Result).
vertical([X|Xs], Acc, Result):-
    addfirst(X, Acc2, Acc),
    vertical(Xs, Acc2, Result).

addfirst([], [], []).
addfirst(
    [Y|Ys],
    [[Y|YVerticalRest]|ResultRest],
    [YVerticalRest|VerticalsRest]):-
    addfirst(Ys, ResultRest, VerticalsRest).


问:
Regex incorrect
I'm trying to do a regex for this string:

1.0.0-toto1-TEST

This is my regex but incorrect :

```<code> ^(\d+)\.(\d+)\.(\d+)-(\[a-z]*)-(TEST)$
</code>```

Thanks for your help :)

Title: Regex incorrect

Body:
I'm trying to do a regex for this string:

1.0.0-toto1-TEST

This is my regex but incorrect :

 ^(\d+)\.(\d+)\.(\d+)-(\[a-z]*)-(TEST)$

Thanks for your help :)

Body: console.log(/^(\d+)\.(\d+)\.(\d+)-([a-z0-9]*)-(TEST)$/.test("1.0.0-toto1-TEST"));


问:
GraphLab installation when Python 2.7 is no longer supported
i need to install GraphLab in jupyter notebook to do a coursera project but all instructions that i found and my research in stackoverflow shows that it require python-2.x or now python-2.7 is no longer supported so what can i do ? </p>

答:
I faced the same issue. This is how I solved it. I hope it'll help you too.

First, you need to open your anaconda navigator.

Then Go to the Environment tab.

Click create option

Then provide a name for your environment and choose the appropriate python version. (GraphLab Create installation requires a Python 2.7.x environment and pip version >= 7)

When your environment ready you can open it with the terminal as follows.

In command prompt type conda update pip to ensure pip is updated to the latest version

Now run this command pip install --upgrade --no-cache-dir https://get.graphlab.com/GraphLab-Create/2.1/your registered email address here/your product key here/GraphLab-Create-License.tar.gz

To Install or update IPython and IPython Notebook
conda install ipython-notebook

I hope it will help you. Thanks!