问:
why do we need thunk.withExtraArgument?
I currently have an issue with my code so while I am debugging i am trying to understand which approach shall I take in order to solve the issue.

I am using google oauth with passport.js. from client I have an action to fetch the authentication.

```<code>import axios from "axios";
const axiosInstance = axios.create({
  baseURL: "http://localhost:3000/api",
  timeout: 3000,
});

export const fetchUser = () => async (dispatch, getState, api) => {
  try {
    await axiosInstance.get("/auth/current_user").then((res) => {
      dispatch({ type: FETCH_USER, payload: res.data });
    });
  } catch (e) {
    console.log(e.message);
  }
};
</code>```

here is the client-side store set up:

```<code>const store = createStore(
  reducers,
  window.INITIAL_STATE, //
  applyMiddleware(thunk)
);
</code>```

and this is the server side store set up:

```<code>export default (req) => {
  const store = createStore(reducers, {}, applyMiddleware(thunk));
  console.log("store from servre", store);
  return store;
};
</code>```

Another approach would be instead of defining axiosInstance in action, i define it when I create the client side store and pass it to thunk.withExtraArgument iike this.

```<code>const axiosInstance = axios.create({
  baseURL: "/",
});
const store = createStore(
  reducers,
  window.INITIAL_STATE,
  applyMiddleware(thunk.withExtraArgument(axiosInstance))
);
</code>```

I changed the action accordingly:

```<code>export const fetchUser = () => async (dispatch, getState, api) => {
  try {
    await api.get("/auth/current_user").then((res) => {
      dispatch({ type: FETCH_USER, payload: res.data });
    });
  } catch (e) {
    console.log(e.message);
  }
};
</code>```

My question which method should I use. CUrrently I have issue in both methods :) . But if i know which way is correct then I will solely focus on that method.

Thank You

答:
I will suggest you go with with creating an instance of axios in a file and importing it whereever you need it, instead of adding it as an argument to thunk

api.js

```<code>import axios from "axios";
const axiosInstance = axios.create({
  baseURL: "http://localhost:3000/api",
  timeout: 3000,
});

export default axiosInstance;
</code>```

actions.js

```<code>import api from '/path/to/api';

export const fetchUser = () => async (dispatch, getState) => {
  try {
    await api.get("/auth/current_user").then((res) => {
      dispatch({ type: FETCH_USER, payload: res.data });
    });
  } catch (e) {
    console.log(e.message);
  }
};
</code>```

The advantage of the above solution is that you can import and use the instance for making direct API calls too in your components for which you do not need to dispatch actions to the reducers.

Title: why do we need thunk.withExtraArgument?

Body:
I currently have an issue with my code so while I am debugging i am trying to understand which approach shall I take in order to solve the issue.

I am using google oauth with passport.js. from client I have an action to fetch the authentication.

import axios from "axios";
const axiosInstance = axios.create({
  baseURL: "http://localhost:3000/api",
  timeout: 3000,
});

export const fetchUser = () => async (dispatch, getState, api) => {
  try {
    await axiosInstance.get("/auth/current_user").then((res) => {
      dispatch({ type: FETCH_USER, payload: res.data });
    });
  } catch (e) {
    console.log(e.message);
  }
};

here is the client-side store set up:

const store = createStore(
  reducers,
  window.INITIAL_STATE, //
  applyMiddleware(thunk)
);

and this is the server side store set up:

export default (req) => {
  const store = createStore(reducers, {}, applyMiddleware(thunk));
  console.log("store from servre", store);
  return store;
};

Another approach would be instead of defining axiosInstance in action, i define it when I create the client side store and pass it to thunk.withExtraArgument iike this.

const axiosInstance = axios.create({
  baseURL: "/",
});
const store = createStore(
  reducers,
  window.INITIAL_STATE,
  applyMiddleware(thunk.withExtraArgument(axiosInstance))
);

I changed the action accordingly:

export const fetchUser = () => async (dispatch, getState, api) => {
  try {
    await api.get("/auth/current_user").then((res) => {
      dispatch({ type: FETCH_USER, payload: res.data });
    });
  } catch (e) {
    console.log(e.message);
  }
};

My question which method should I use. CUrrently I have issue in both methods :) . But if i know which way is correct then I will solely focus on that method.

Thank You

Body:
I will suggest you go with with creating an instance of axios in a file and importing it whereever you need it, instead of adding it as an argument to thunk

api.js

import axios from "axios";
const axiosInstance = axios.create({
  baseURL: "http://localhost:3000/api",
  timeout: 3000,
});

export default axiosInstance;

actions.js

import api from '/path/to/api';

export const fetchUser = () => async (dispatch, getState) => {
  try {
    await api.get("/auth/current_user").then((res) => {
      dispatch({ type: FETCH_USER, payload: res.data });
    });
  } catch (e) {
    console.log(e.message);
  }
};

The advantage of the above solution is that you can import and use the instance for making direct API calls too in your components for which you do not need to dispatch actions to the reducers.


来源: stackexchange

问:
How to implement a FIFO queue in a multi-threaded environment
I am trying to implement a queue for a class that fetches OpenGraph data for a url.  The idea is that the OpenGraphIO service only allows for one request at a time if the request requires their "proxy" service. To eliminate the "simultaneous proxy request" errors from the service, I would like to implement a request queue inside a service class called OpenGraphFetcherImpl.  However, I can't figure out how to implement the actual queue itself inside the fetch() method.  Obviously the fetch() method can be called in a multi-threaded environment.

My class shell is below:

```<code>public class OpenGraphFetcherImpl implements OpenGraphFetcher {

    private static final String[] domainsThatRequireProxy = {"instagram.com","facebook.com"};

    private static final LinkedList<URL> proxyQueue = new LinkedList<>();

    private final String api_key;

    public OpenGraphFetcherImpl(String api_key) {
        this.api_key = api_key;
    }

    /**
     * Fetch OpenGraph information for a url.  If the url is invalid or no data is returned, the OpenGraph
     * object will be "empty" (non-null)
     *
     * Only one "proxy" request can be made at a time. Should a proxy be needed, the request will be queued
     * and returned once previous requests have been completed.
     *
     * @param url end point to fetch OpenGraph data
     * @return OpenGraph object
     */
    @Override
    @Nonnull
    public OpenGraph fetch(URL url) {
        if (useProxy(url)) {
            // Clearly this code doesn't work, but logic should be to add the request to the queue and then make requests in FIFO order
            proxyQueue.add(url);
            return OpenGraphIO.fetchOpenGraphInfo(api_key, proxyQueue.poll(), true);
        } else {
            return OpenGraphIO.fetchOpenGraphInfo(api_key, url, false);
        }
    }

    /**
     * @param url url to test
     * @return true if the host of the url matches any domains that require use of a proxy
     */
    private boolean useProxy(URL url) {
        return Arrays.stream(domainsThatRequireProxy).parallel().anyMatch(url.getHost()::contains);
    }
}
</code>```

答:
Based on your description, you'd want to limit synchronous calls to fetch() when useProxy is true. Then, you can use an object to synchronize that case only:

```<code>public class OpenGraphFetcherImpl implements OpenGraphFetcher {
    private static final Object fetchLock=new Object();

     public OpenGraph fetch(URL url) {
        if (useProxy(url)) {
            synchronized(fetchLock) {
               return OpenGraphIO.fetchOpenGraphInfo(api_key, url, true);
            }
        } else {
            return OpenGraphIO.fetchOpenGraphInfo(api_key, url, false);
        }
    }
...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to implement a queue for a class that fetches OpenGraph data for a url.  The idea is that the OpenGraphIO service only allows for one request at a time if the request requires their "proxy" service. To eliminate the "simultaneous proxy request" errors from the service, I would like to implement a request queue inside a service class called OpenGraphFetcherImpl.  However, I can't figure out how to implement the actual queue itself inside the fetch() method.  Obviously the fetch() method can be called in a multi-threaded environment.

My class shell is below:

public class OpenGraphFetcherImpl implements OpenGraphFetcher {

    private static final String[] domainsThatRequireProxy = {"instagram.com","facebook.com"};

    private static final LinkedList<URL> proxyQueue = new LinkedList<>();

    private final String api_key;

    public OpenGraphFetcherImpl(String api_key) {
        this.api_key = api_key;
    }

    /**
     * Fetch OpenGraph information for a url.  If the url is invalid or no data is returned, the OpenGraph
     * object will be "empty" (non-null)
     *
     * Only one "proxy" request can be made at a time. Should a proxy be needed, the request will be queued
     * and returned once previous requests have been completed.
     *
     * @param url end point to fetch OpenGraph data
     * @return OpenGraph object
     */
    @Override
    @Nonnull
    public OpenGraph fetch(URL url) {
        if (useProxy(url)) {
            // Clearly this code doesn't work, but logic should be to add the request to the queue and then make requests in FIFO order
            proxyQueue.add(url);
            return OpenGraphIO.fetchOpenGraphInfo(api_key, proxyQueue.poll(), true);
        } else {
            return OpenGraphIO.fetchOpenGraphInfo(api_key, url, false);
        }
    }

    /**
     * @param url url to test
     * @return true if the host of the url matches any domains that require use of a proxy
     */
    private boolean useProxy(URL url) {
        return Arrays.stream(domainsThatRequireProxy).parallel().anyMatch(url.getHost()::contains);
    }
}

Body:
Based on your description, you'd want to limit synchronous calls to fetch() when useProxy is true. Then, you can use an object to synchronize that case only:

public class OpenGraphFetcherImpl implements OpenGraphFetcher {
    private static final Object fetchLock=new Object();

     public OpenGraph fetch(URL url) {
        if (useProxy(url)) {
            synchronized(fetchLock) {
               return OpenGraphIO.fetchOpenGraphInfo(api_key, url, true);
            }
        } else {
            return OpenGraphIO.fetchOpenGraphInfo(api_key, url, false);
        }
    }
...


问:
Xcode 4 crashes when opening project
Full assertion is below!

I am trying to open our project on a fresh XCode 4 install (4.0.2) on a fresh new Sandy Bridge iMac Core i5.  This project worked and continues to work on my older MacMini and my partner's Core 2 Duo iMac.

I am suspecting this might be caused by this new machine never having had any older versions of XCode 4 or XCode 3 and the older SDKs ever installed onto it.  Just 4.02 and whatever comes with it.  Thats the only this I can think of ... and the only difference we know of between machines.  The file specified below indeed is not there ... so its a problem generating the PCH maybe???

Can anyone please help with this?

We cannot open our XCode project at all on the new machine and the assertion below is most unfriendly ...

Thanks!

```<code>ASSERTION FAILURE in /SourceCache/IDEFoundation/IDEFoundation-287/Framework/Classes/Index/IDEIndex.m:2186
Details:  Error launching clang to create PCH file: /Users/sukichima/Library/Developer/Xcode/DerivedData/LeapLanguage-gtjaysymsmxhiifrufylngcjwyxb/Index/PrecompiledHeaders/LeapLanguage_Prefix-bvjcknzwkkcgeydmvtyeuddafzgu_ast/LeapLanguage_Prefix.pch.pth
Error Domain=NSPOSIXErrorDomain Code=2 "The operation couldn’t be completed. No such file or directory"
Object:   <IDEIndex: 0x200c257c0>
Method:   -createPCHFile:willIndex:arguments:
Thread:   <NSThread: 0x2036dfe80>{name = (null), num = 12}
Hints:   None
Backtrace:
  0  0x0000000100949773 -[IDEAssertionHandler handleFailureInMethod:object:fileName:lineNumber:messageFormat:arguments:] (in IDEKit)
  1  0x000000010006d394 _DVTAssertionFailureHandler (in DVTFoundation)
  2  0x0000000100564e3d __46-[IDEIndex createPCHFile:willIndex:arguments:]_block_invoke_0 (in IDEFoundation)
  3  0x0000000100005fdc __38-[DVTDispatchLock performLockedBlock:]_block_invoke_0 (in DVTFoundation)
  4  0x00007fff88b6d4db dispatch_barrier_sync_f (in libSystem.B.dylib)
  5  0x0000000100005f83 -[DVTDispatchLock performLockedBlock:] (in DVTFoundation)
  6  0x0000000100564a34 -[IDEIndex createPCHFile:willIndex:arguments:] (in IDEFoundation)
  7  0x0000000100570b4c -[IDEIndexClangDataSource generateDataForFile:settings:] (in IDEFoundation)
  8  0x00000001005706c1 -[IDEIndexDataSource processFile:settings:] (in IDEFoundation)
  9  0x000000010056ffbe __70-[IDEIndex _indexFile:object:settings:afterOperation:beforeOperation:]_block_invoke_0 (in IDEFoundation)
10  0x00007fff86976cc7 -[__NSOperationInternal start] (in Foundation)
11  0x00007fff86a55af2 __doStart2 (in Foundation)
12  0x00007fff88b74284 _dispatch_call_block_and_release (in libSystem.B.dylib)
13  0x00007fff88b527f1 _dispatch_worker_thread2 (in libSystem.B.dylib)
14  0x00007fff88b52128 _pthread_wqthread (in libSystem.B.dylib)
15  0x00007fff88b51fc5 start_wqthread (in libSystem.B.dylib)
</code>```

答: The problem was with the source paths under XCode 4 preferences.  If you see the above error make sure you check your source paths and source path names with a fine tooth comb!</p>

ContentLicense: CC BY-SA 3.0

Title: Xcode 4 crashes when opening project

Body:
Full assertion is below!

I am trying to open our project on a fresh XCode 4 install (4.0.2) on a fresh new Sandy Bridge iMac Core i5.  This project worked and continues to work on my older MacMini and my partner's Core 2 Duo iMac.

I am suspecting this might be caused by this new machine never having had any older versions of XCode 4 or XCode 3 and the older SDKs ever installed onto it.  Just 4.02 and whatever comes with it.  Thats the only this I can think of ... and the only difference we know of between machines.  The file specified below indeed is not there ... so its a problem generating the PCH maybe???

Can anyone please help with this?

We cannot open our XCode project at all on the new machine and the assertion below is most unfriendly ...

Thanks!

ASSERTION FAILURE in /SourceCache/IDEFoundation/IDEFoundation-287/Framework/Classes/Index/IDEIndex.m:2186
Details:  Error launching clang to create PCH file: /Users/sukichima/Library/Developer/Xcode/DerivedData/LeapLanguage-gtjaysymsmxhiifrufylngcjwyxb/Index/PrecompiledHeaders/LeapLanguage_Prefix-bvjcknzwkkcgeydmvtyeuddafzgu_ast/LeapLanguage_Prefix.pch.pth
Error Domain=NSPOSIXErrorDomain Code=2 "The operation couldn’t be completed. No such file or directory"
Object:   <IDEIndex: 0x200c257c0>
Method:   -createPCHFile:willIndex:arguments:
Thread:   <NSThread: 0x2036dfe80>{name = (null), num = 12}
Hints:   None
Backtrace:
  0  0x0000000100949773 -[IDEAssertionHandler handleFailureInMethod:object:fileName:lineNumber:messageFormat:arguments:] (in IDEKit)
  1  0x000000010006d394 _DVTAssertionFailureHandler (in DVTFoundation)
  2  0x0000000100564e3d __46-[IDEIndex createPCHFile:willIndex:arguments:]_block_invoke_0 (in IDEFoundation)
  3  0x0000000100005fdc __38-[DVTDispatchLock performLockedBlock:]_block_invoke_0 (in DVTFoundation)
  4  0x00007fff88b6d4db dispatch_barrier_sync_f (in libSystem.B.dylib)
  5  0x0000000100005f83 -[DVTDispatchLock performLockedBlock:] (in DVTFoundation)
  6  0x0000000100564a34 -[IDEIndex createPCHFile:willIndex:arguments:] (in IDEFoundation)
  7  0x0000000100570b4c -[IDEIndexClangDataSource generateDataForFile:settings:] (in IDEFoundation)
  8  0x00000001005706c1 -[IDEIndexDataSource processFile:settings:] (in IDEFoundation)
  9  0x000000010056ffbe __70-[IDEIndex _indexFile:object:settings:afterOperation:beforeOperation:]_block_invoke_0 (in IDEFoundation)
10  0x00007fff86976cc7 -[__NSOperationInternal start] (in Foundation)
11  0x00007fff86a55af2 __doStart2 (in Foundation)
12  0x00007fff88b74284 _dispatch_call_block_and_release (in libSystem.B.dylib)
13  0x00007fff88b527f1 _dispatch_worker_thread2 (in libSystem.B.dylib)
14  0x00007fff88b52128 _pthread_wqthread (in libSystem.B.dylib)
15  0x00007fff88b51fc5 start_wqthread (in libSystem.B.dylib)


问:
How to write a C or Java application to handle TCP SYN requests
I want to handle TCP SYN requests from users to denied some invalid requests to web server (Apache) on a CentOS server

How to write an application in C++ or Java or any programming languages?

答:
You can create a netfilter kernel module (in C language), and hook yourself for various packet events such as receiving a packet on a particular interface etc. You will need to check the packet header to figure out whether it is a TCP SYN request, and then decide what to do with it.

https://www.netfilter.org/

You cannot create a user mode C++ or Java program to achieve this.

That being the answer for what you are asking, perhaps a better alternative would be to add rules to the firewall depending on what invalid requests you want to disable.


问:
How to add a favicon to a Next.js static site?
I'm trying to add a favicon to a Next.js static site without much luck.

I've tried customising the document with components from 'next/document'
https://nextjs.org/docs/#custom-document

A straight link to the favicon.ico file doesn't work because the file isn't included in the build and the href doesn't update to /_next/static/...

Importing the image and adding to the link's href doesn't work either (see commented out lines).

import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';

// import favicon from '../data/imageExports';

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  render() {
    return (

          {/* <link rel="shortcut icon" href={favicon} /> */}
          <link rel="shortcut icon" href="../images/icons/favicon.ico" />

          <NextScript />

    );
  }
}
```

The favicon links get added however it doesn't display. I'd expect it to work when I import the file, but it just adds a <link rel="shortcut icon" href="[object Object]"> link.

Has anyone done this yet?

答: As of June 2020, you don't have to add/edit the document.js or _head.js files. All you need do to is place the favicon.ico file inside the public directory and that's it.

Body:
I'm trying to add a favicon to a Next.js static site without much luck.

I've tried customising the document with components from 'next/document'
https://nextjs.org/docs/#custom-document

A straight link to the favicon.ico file doesn't work because the file isn't included in the build and the href doesn't update to /_next/static/...

Importing the image and adding to the link's href doesn't work either (see commented out lines).

import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';

// import favicon from '../data/imageExports';

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  render() {
    return (

          {/* <link rel="shortcut icon" href={favicon} /> */}
          <link rel="shortcut icon" href="../images/icons/favicon.ico" />

          <NextScript />

    );
  }
}

The favicon links get added however it doesn't display. I'd expect it to work when I import the file, but it just adds a <link rel="shortcut icon" href="[object Object]"> link.

Has anyone done this yet?


问:
Property 'get' does not exist on type 'HttpClientModule'

Am very new to Angular js , Trying to learn it from youtube, and i was facing mentioned issue
 in my code, I don't understand what was missing in my code

ERROR

am getting " Property 'get' does not exist on type 'HttpClientModule'"  error when am trying to access get service of HttpClientModule.,

Below are the code details

app.component.ts file is

```<code>import { Component,OnInit  } from '@angular/core';
   import {HttpClientModule} from '@angular/common/http';
     @Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
   })
   export class AppComponent {

   constructor(private http:HttpClientModule){};
   title = 'app';
   ngOnInit() {
   this.http.get('https://my-json-server.typicode.com/techsithgit/json-faker-
   directory/profiles').
    subscribe((data)=>{
      console.log(data);
    });

   }

}
</code>```

app.module.ts file is

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {HttpClientModule} from '@angular/common/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Package.json file is

```<code>{
  "name": "trust",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.0.2",
    "@angular/common": "^5.0.2",
    "@angular/compiler": "^5.0.2",
    "@angular/compiler-cli": "^5.0.2",
    "@angular/core": "^5.0.2",
    "@angular/forms": "^5.0.2",
    "@angular/http": "^5.0.2",
    "@angular/platform-browser": "^5.0.2",
    "@angular/platform-browser-dynamic": "^5.0.2",
    "@angular/platform-server": "^5.0.2",
    "@angular/router": "^5.0.2",
    "core-js": "^2.4.1",
    "rxjs": "^5.4.2",
    "typescript": "^2.6.1",
    "zone.js": "^0.8.18"
  },
  "devDependencies": {
    "@angular/cli": "1.4.9",
    "@angular/compiler-cli": "^4.2.4",
    "@angular/language-service": "^4.2.4",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.3.3"
  }
}
</code>```

答:
Please check your files like this, my environmental parameters:

```<code>Angular CLI: 9.1.7
Node: 12.7.0
OS: darwin x64

Angular:
...
Ivy Workspace:

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.901.7
@angular-devkit/core         9.1.7
@angular-devkit/schematics   9.1.7
@schematics/angular          9.1.7
@schematics/update           0.901.7
rxjs                         6.5.4
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CribListingComponent } from './crib-listing/crib-listing.component';
import { CribCardComponent } from './crib-card/crib-card.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    CribListingComponent,
    CribCardComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

</code>```

app.component.ts:

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'hello-world';
}
</code>```

crib-listing.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-crib-listing',
  templateUrl: './crib-listing.component.html',
  styleUrls: ['./crib-listing.component.css']
})
export class CribListingComponent implements OnInit {

  cribs: Array<any>;
  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    // make an http request
    this.http.get('data/cribs.json')
    .subscribe(
      data => console.log(data)
    );
  }

}

</code>```

Body:
Am very new to Angular js , Trying to learn it from youtube, and i was facing mentioned issue
 in my code, I don't understand what was missing in my code

ERROR

am getting " Property 'get' does not exist on type 'HttpClientModule'"  error when am trying to access get service of HttpClientModule.,

Below are the code details

app.component.ts file is

import { Component,OnInit  } from '@angular/core';
   import {HttpClientModule} from '@angular/common/http';
     @Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
   })
   export class AppComponent {

   constructor(private http:HttpClientModule){};
   title = 'app';
   ngOnInit() {
   this.http.get('https://my-json-server.typicode.com/techsithgit/json-faker-
   directory/profiles').
    subscribe((data)=>{
      console.log(data);
    });

   }

}

app.module.ts file is

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {HttpClientModule} from '@angular/common/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Package.json file is

{
  "name": "trust",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.0.2",
    "@angular/common": "^5.0.2",
    "@angular/compiler": "^5.0.2",
    "@angular/compiler-cli": "^5.0.2",
    "@angular/core": "^5.0.2",
    "@angular/forms": "^5.0.2",
    "@angular/http": "^5.0.2",
    "@angular/platform-browser": "^5.0.2",
    "@angular/platform-browser-dynamic": "^5.0.2",
    "@angular/platform-server": "^5.0.2",
    "@angular/router": "^5.0.2",
    "core-js": "^2.4.1",
    "rxjs": "^5.4.2",
    "typescript": "^2.6.1",
    "zone.js": "^0.8.18"
  },
  "devDependencies": {
    "@angular/cli": "1.4.9",
    "@angular/compiler-cli": "^4.2.4",
    "@angular/language-service": "^4.2.4",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.3.3"
  }
}

Body:
Please check your files like this, my environmental parameters:

Angular CLI: 9.1.7
Node: 12.7.0
OS: darwin x64

Angular:
...
Ivy Workspace:

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.901.7
@angular-devkit/core         9.1.7
@angular-devkit/schematics   9.1.7
@schematics/angular          9.1.7
@schematics/update           0.901.7
rxjs                         6.5.4

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CribListingComponent } from './crib-listing/crib-listing.component';
import { CribCardComponent } from './crib-card/crib-card.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    CribListingComponent,
    CribCardComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'hello-world';
}

crib-listing.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-crib-listing',
  templateUrl: './crib-listing.component.html',
  styleUrls: ['./crib-listing.component.css']
})
export class CribListingComponent implements OnInit {

  cribs: Array<any>;
  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    // make an http request
    this.http.get('data/cribs.json')
    .subscribe(
      data => console.log(data)
    );
  }

}


问:
Why the output is a string array even after assigning the variable as number in typescript?
Code:

```<code>function fun(example:string|number|string[])
{
    if(typeof example == "string")
    {
        console.log("Example is String " + example);
    }
    else if(typeof example == "number")
    {
        console.log("Example is Number " + example);
    }
    else{
        console.log("Example is String Array " + example);
    }
}
var example:number; //Here i have assigned the var as a number
fun(example);
</code>```

Output:

```<code>Example is String Array undefined
</code>```

I have given the var type as a "number", but why the output screen shows "String array"?

答:
You haven't given a value to the variable example, hence by default it's undefined, that's why your code runs the last else statement.

Try with:

var example = 3
fun(example)
// Example is Number 3
```

Remember that type annotations are used at compile time. This means that when your code runs, it doesn't know anything about the types you declared.

Body:
Code:

function fun(example:string|number|string[])
{
    if(typeof example == "string")
    {
        console.log("Example is String " + example);
    }
    else if(typeof example == "number")
    {
        console.log("Example is Number " + example);
    }
    else{
        console.log("Example is String Array " + example);
    }
}
var example:number; //Here i have assigned the var as a number
fun(example);

Output:

Example is String Array undefined

I have given the var type as a "number", but why the output screen shows "String array"?

Body:
You haven't given a value to the variable example, hence by default it's undefined, that's why your code runs the last else statement.

Try with:

var example = 3
fun(example)
// Example is Number 3

Remember that type annotations are used at compile time. This means that when your code runs, it doesn't know anything about the types you declared.


问:
Unable to add an array index
I would like to allocate names for the index in an array while using for loop. how can i achieve this. please guide me.

```<code>// using in a http response
   for (let i = 0; i <= 6; i++) {
            this.sf.push({f(i) : // do something)
          };
</code>```

i want to get something like

```<code>f0: 1,
f1: 5,
f2: 9
</code>```

答:
You can use map function for that. Such as:

test = [1,5,9,10,15,25];
new_arr = [];
test.map(function(element, index) {new_arr.push('f'+index+':'+element);})
console.log(new_arr);```

Title: Unable to add an array index

Body:
I would like to allocate names for the index in an array while using for loop. how can i achieve this. please guide me.

// using in a http response
   for (let i = 0; i <= 6; i++) {
            this.sf.push({f(i) : // do something)
          };

i want to get something like

f0: 1,
f1: 5,
f2: 9


问:
Fetch JS retreive eror response
I am calling an API which could potentially return a 40x response with an associated error body which I want to use. I've tried to use a check if the response.ok() and then throw a error with the response.json()  which a catch statement will handle however when the catch runs it will only have a Promise {<pending>}.

This was my resulting attempt which returned a promise to setError().

```<code>getAPI(path)
      .then((result) => {
        setResult(result);
      })
      .catch((resError) => {
        setError(`${resError}`);
      });

function getAPI(path) {
  return fetch(
    `http://localhost:3000/${path}`,
    {
      method: "GET",
    }
  ).then((res) => {
    if (res.ok) {
      return res.json();
    } else {
      throw res.json();
    }
  });
}
</code>```

If in my getAPI I simply return res.json() and not check for a success error code then I get the body of the 400 error however I have no way of checking that the response had an error code.

```<code>function getAPI(path) {
  return fetch(
    `http://localhost:3000/${path}`,
    {
      method: "GET",
    }
  ).then((res) => {
    res.json();
  });
}

</code>```

I can see twhen the fetch is resolved res contains the following attributes.

```<code>body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 400
statusText: "Bad Request"
type: "cors"
url: "http://localhost:3000/"
</code>```

答:
The problem is

} else {
  throw res.json();
}
```
</blockquote>

<p><code>res.json()</code> returns a promise which will not be resolved by <code>throw</code>. </p>

<p>In your <code>else</code> block, try </p>

<pre class="lang-js prettyprint-override"><code>return res.json().then(err => throw err)
</code>```

or

return res.json().then(err => Promise.reject(err))
```

Title: Fetch JS retreive eror response

Body:
I am calling an API which could potentially return a 40x response with an associated error body which I want to use. I've tried to use a check if the response.ok() and then throw a error with the response.json()  which a catch statement will handle however when the catch runs it will only have a Promise {<pending>}.

This was my resulting attempt which returned a promise to setError().

getAPI(path)
      .then((result) => {
        setResult(result);
      })
      .catch((resError) => {
        setError(`${resError}`);
      });

function getAPI(path) {
  return fetch(
    `http://localhost:3000/${path}`,
    {
      method: "GET",
    }
  ).then((res) => {
    if (res.ok) {
      return res.json();
    } else {
      throw res.json();
    }
  });
}

If in my getAPI I simply return res.json() and not check for a success error code then I get the body of the 400 error however I have no way of checking that the response had an error code.

function getAPI(path) {
  return fetch(
    `http://localhost:3000/${path}`,
    {
      method: "GET",
    }
  ).then((res) => {
    res.json();
  });
}

I can see twhen the fetch is resolved res contains the following attributes.

body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 400
statusText: "Bad Request"
type: "cors"
url: "http://localhost:3000/"

Body:
The problem is

} else {
  throw res.json();
}

res.json() returns a promise which will not be resolved by throw.

In your else block, try

return res.json().then(err => throw err)

or

return res.json().then(err => Promise.reject(err))


问:
How to make a function in Vanilla JS that puts checked attribute to the radio inputs before the selected input?
I can't find solution for this one.

Need to put attribute checked on the inputs that are before the selected input with JavaScript and the inputs after it unchecked.

UPD: changed the input type to the "checkbox" and now I need a function that marks "checked" the checkboxes before the last checked one, while unchecking succeeding boxes in case they were checked before.

Note: The solution has to use ES5 compatible syntax.

With code examples, please !

<input type="checkbox" id="product-1" name="toggle">
<input type="checkbox" id="product-2" name="toggle">
<input type="checkbox" id="product-3" name="toggle">
<input type="checkbox" id="product-4" name="toggle">
<input type="checkbox" id="product-5" name="toggle">
```

答:
Then, my friend, it can be as simple as this:

// checkbox elements
var boxes = document.getElementsByName('toggle');

// function to bind to each of the input tags' change event
function markPreceding() {

  // retrieve the value from the clicked input
  var curIndex = this.value;

  // iterate through every single checkbox named toggle
  for (var i = 0, box = boxes[i]; i < boxes.length; box = boxes[++i]) {
    // if data-index is lower or equal to curIndex, then true; else, false
    box.checked = box.value <= curIndex;
  }

}

// add function to the onchange handler of each input
for (var i = 0, box = boxes[i]; i < boxes.length; box = boxes[++i]) {
  box.onchange = markPreceding;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="product-1" name="toggle" value="1">
<input type="checkbox" id="product-2" name="toggle" value="2">
<input type="checkbox" id="product-3" name="toggle" value="3">
<input type="checkbox" id="product-4" name="toggle" value="4">
<input type="checkbox" id="product-5" name="toggle" value="5"></code>```

Notes

I stored each of the checkboxes' index using data attributes.

I could have used the value property, for instance. I preferred using data attributes because you might want to use value for something else. It's your call. (see bottom of the post)

We can retrieve each attribute data-index from the HTML view in JavaScript with .dataset.index. It could've been any other name instead of "index". Just remember that if you're using multiple words, such as data-my-custom-prop in HTML, you have to call it in JS as .dataset.myCustomProp (they get camelCased).

The .checked property stores a boolean anyways, so you can pass the comparison box.dataset.index <= curIndex that will evaluate to either true or false, respectfully checking or unchecking the box.

EDIT: Since you asked in the comments, I tried converting it to ES5 compatible syntax. I stopped using data attributes, for one thing, and I retrieved the input value with the this keyword, not event.target (maybe I didn't need to change this, but I get the impression that was more common back in the day).

Body:
Then, my friend, it can be as simple as this:

// checkbox elements
var boxes = document.getElementsByName('toggle');

// function to bind to each of the input tags' change event
function markPreceding() {

  // retrieve the value from the clicked input
  var curIndex = this.value;

  // iterate through every single checkbox named toggle
  for (var i = 0, box = boxes[i]; i < boxes.length; box = boxes[++i]) {
    // if data-index is lower or equal to curIndex, then true; else, false
    box.checked = box.value <= curIndex;
  }

}

// add function to the onchange handler of each input
for (var i = 0, box = boxes[i]; i < boxes.length; box = boxes[++i]) {
  box.onchange = markPreceding;
}

<input type="checkbox" id="product-1" name="toggle" value="1">
<input type="checkbox" id="product-2" name="toggle" value="2">
<input type="checkbox" id="product-3" name="toggle" value="3">
<input type="checkbox" id="product-4" name="toggle" value="4">
<input type="checkbox" id="product-5" name="toggle" value="5">

Notes

I stored each of the checkboxes' index using data attributes.

I could have used the value property, for instance. I preferred using data attributes because you might want to use value for something else. It's your call. (see bottom of the post)

We can retrieve each attribute data-index from the HTML view in JavaScript with .dataset.index. It could've been any other name instead of "index". Just remember that if you're using multiple words, such as data-my-custom-prop in HTML, you have to call it in JS as .dataset.myCustomProp (they get camelCased).

The .checked property stores a boolean anyways, so you can pass the comparison box.dataset.index <= curIndex that will evaluate to either true or false, respectfully checking or unchecking the box.

EDIT: Since you asked in the comments, I tried converting it to ES5 compatible syntax. I stopped using data attributes, for one thing, and I retrieved the input value with the this keyword, not event.target (maybe I didn't need to change this, but I get the impression that was more common back in the day).


问:
multiple Toggle event for multiple divs
here is my requirements.<br>
here when i click buynow i want to disable this button and want to show content and when i click again content then i want to hide this content and want to show buynow text. </p>

```<code><div class="btn button-success" >Buy Now</div>
<div class="book" style="display: none;">
 content
</div>

<div class="btn button-success" >Buy Now</div>
<div class="book" style="display: none;">
 content
</div>

  am used below script its working but in browser hiding is not looking good.

   $(".btn").click(function () {
        $(this).hide();
        $(this).next(".book").toggle();
    });
    $(".book").click(function () {
        $(this).hide();
        $(this).prev(".btn").toggle();
    });
</code>```

答:
You cannot have clicked event on disable button. So,to overcome this you can add custom css to some class using addClass or removeClass and make button look like disable .Also, i have use toggle to show or hide your div.

Demo Code :

//onclick of button
$('.btn').click(function() {
  //checking if button has disabled class
  if ($(this).hasClass('disabled')) {
    $(this).removeClass('disabled'); //remove class
    console.log("remove")
  } else {
    console.log("add")
    $(this).addClass('disabled') //add
  }
//button->next->div show
  $(this).next('.book').toggle("show"); //toggle for book div
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.disabled {
  opacity: 0.6;
  background-color: #DDD;
  color: #999;
}</code>```

<button class="btn button-success">Buy Now</button>

  content

<button class="btn button-success">Buy Now</button>

  content

<button class="btn button-success">Buy Now</button>

  Content here

<button class="btn button-success">Buy Now</button>

  content

```

Title: multiple Toggle event for multiple divs

Body:
here is my requirements.

here when i click buynow i want to disable this button and want to show content and when i click again content then i want to hide this content and want to show buynow text.

Buy Now

 content

Buy Now

 content

  am used below script its working but in browser hiding is not looking good.

   $(".btn").click(function () {
        $(this).hide();
        $(this).next(".book").toggle();
    });
    $(".book").click(function () {
        $(this).hide();
        $(this).prev(".btn").toggle();
    });

Body:
You cannot have clicked event on disable button. So,to overcome this you can add custom css to some class using addClass or removeClass and make button look like disable .Also, i have use toggle to show or hide your div.

Demo Code :

//onclick of button
$('.btn').click(function() {
  //checking if button has disabled class
  if ($(this).hasClass('disabled')) {
    $(this).removeClass('disabled'); //remove class
    console.log("remove")
  } else {
    console.log("add")
    $(this).addClass('disabled') //add
  }
//button->next->div show
  $(this).next('.book').toggle("show"); //toggle for book div
});

.disabled {
  opacity: 0.6;
  background-color: #DDD;
  color: #999;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn button-success">Buy Now</button>
<div class="book" style="display: none;">
  content
</div>

<button class="btn button-success">Buy Now</button>
<div class="book" style="display: none;">
  content
</div>

<button class="btn button-success">Buy Now</button>
<div class="book" style="display: none;">
  Content here
</div>

<button class="btn button-success">Buy Now</button>
<div class="book" style="display: none;">
  content
</div>


问:
How can I insert emoji unicode in Language Generation file template?
I can't show emoji using unicode in the template.lg in bot framework emulator.</p>

```<code># ContactBot
- Thank you. Don't hesitate to contact me anytime. \U0001F60A
</code>```

答: Please be aware that Encoding.Unicode is UTF-16 in C#. To read 32 bits Unicode, there is this Encoding.UTF32. Link on MSDN for Encoding.UTF32

Body:
I can't show emoji using unicode in the template.lg in bot framework emulator.

# ContactBot
- Thank you. Don't hesitate to contact me anytime. \U0001F60A


问:
Reuse same DOM element in two different react components
I have a small question.

Let's imagine I have component A which holds , after component A does it's job I render component B. I would like that same DOM element (textarea) would be reused in component B.
The reason is if new textarea is rendered in component B it loses focus as it's just new DOM element. It's like after component A lifetame take textarea element from it and just put it in component B instead of rendering new one.

Sample APP
https://jsfiddle.net/remdex/v67gqyLa/1/#&togetherjs=aiRvTGhRK2

class AComponent extends React.Component {
  render() {
      return ( <textarea>A Component</textarea>  )
 }
}

class BComponent extends React.Component {
  render() {
      return ( <textarea>Should be A Component text</textarea>  )
 }
}

class ABComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {'component' : 'A'};
  }

  render() {
    return (

<button onClick={(e) => this.setState({component:'B'})}>Switch to B Component</button>
      {this.state.component == 'A' && <AComponent/>}
      {this.state.component == 'B' && <BComponent/>}

    )
  }
}

ReactDOM.render(<ABComponent />, document.querySelector("#app"))```

答:
In your sandbox example, ComponentA and ComponentB are redundant. You can create ComponentA and ComponentB as a class if they are using same element and operate them with ComponentAB. You can change your ComponentAB like:

class A {
  handle(input) {
    // Do your A job here and return result
    console.log("Handler A is running");
  };
}

class B {
  handle(input) {
    // Do your B job here and return result
    console.log("Handler B is running");
  };
}

class ABComponent extends React.Component {
  currentHandler = new A();

  handleClick = () => {
   this.currentHandler = new B();
  };

  handleChange = (event) => {
    // Handle the input with current handler
    var result = this.currentHandler.handle(event.target.value);
    // If you want you can use result to cahnge something in view
    // this.setState({value: result});
  }

  render() {
    return (

          <button onClick={this.handleClick}>
              Switch to B Component
          </button>
          <textarea onChange={this.handleChange}>Text Area used between A class and B class</textarea>

    )
  }
}
```

I also edit the codebox example. You can find it here.

Body:
In your sandbox example, ComponentA and ComponentB are redundant. You can create ComponentA and ComponentB as a class if they are using same element and operate them with ComponentAB. You can change your ComponentAB like:

class A {
  handle(input) {
    // Do your A job here and return result
    console.log("Handler A is running");
  };
}

class B {
  handle(input) {
    // Do your B job here and return result
    console.log("Handler B is running");
  };
}

class ABComponent extends React.Component {
  currentHandler = new A();

  handleClick = () => {
   this.currentHandler = new B();
  };

  handleChange = (event) => {
    // Handle the input with current handler
    var result = this.currentHandler.handle(event.target.value);
    // If you want you can use result to cahnge something in view
    // this.setState({value: result});
  }

  render() {
    return (
      <div>
          <button onClick={this.handleClick}>
              Switch to B Component
          </button>
          <textarea onChange={this.handleChange}>Text Area used between A class and B class</textarea>
      </div>
    )
  }
}

I also edit the codebox example. You can find it here.


问:
C++ While statement not working with string and "or"
I'm new to C++, teaching myself via youtube and some books I bought. I can not for the life of me figure out why the 2nd while statement will not work. from a mathematical stand point I feel it should work. If month does not = june or july then do the if else statement. But even when I run the right answer it always runs the if not the else. I feel it has something to do with it being a string, so I tested it without the or "||" and it worked. So maybe it has to do with combining strings and or statements. So did research on using these together and could not find much. Thanks for the help.  </p>

```<code>int main()
{
    int year;
    int day = 0;
    string month = "x";

    do
    {
        if (day == 0)
        {
            cout << "hello" << endl;
            cout << "Please Enter your B-Day as Day, Month, Year" << endl;
            cout << "day" << endl;
            cin >> day;
        }
        else
        {
            cout << "Please enter a correct day" << endl;
            cin >> day;
        }

    } while (day > 31 || day < 1);

    do
    {
        if (month == "x")
        {
            cout << "Please enter the month you were born" << endl;
            cin >> month;
        }
        else
        {
            cout << "Please Enter a correct Month." << endl;
            cin >> month;
        }
    }
    **while (month != "june" || month != "july");**

    return 0;
}
</code>```

答:
If you do:

```<code>while (month != "june" && month != "july");
</code>```

Or alternatively,

```<code>while (!(month == "june" || month == "july"));
</code>```

Rather than:

```<code>while (month != "june" || month != "july");
</code>```

Your program will be working fine even with multiple logical OR.

Body:
I'm new to C++, teaching myself via youtube and some books I bought. I can not for the life of me figure out why the 2nd while statement will not work. from a mathematical stand point I feel it should work. If month does not = june or july then do the if else statement. But even when I run the right answer it always runs the if not the else. I feel it has something to do with it being a string, so I tested it without the or "||" and it worked. So maybe it has to do with combining strings and or statements. So did research on using these together and could not find much. Thanks for the help.

int main()
{
    int year;
    int day = 0;
    string month = "x";

    do
    {
        if (day == 0)
        {
            cout << "hello" << endl;
            cout << "Please Enter your B-Day as Day, Month, Year" << endl;
            cout << "day" << endl;
            cin >> day;
        }
        else
        {
            cout << "Please enter a correct day" << endl;
            cin >> day;
        }

    } while (day > 31 || day < 1);

    do
    {
        if (month == "x")
        {
            cout << "Please enter the month you were born" << endl;
            cin >> month;
        }
        else
        {
            cout << "Please Enter a correct Month." << endl;
            cin >> month;
        }
    }
    **while (month != "june" || month != "july");**

    return 0;
}

Body:
If you do:

while (month != "june" && month != "july");

Or alternatively,

while (!(month == "june" || month == "july"));

Rather than:

while (month != "june" || month != "july");

Your program will be working fine even with multiple logical OR.


问:
Python and random keys of 21 char max
I am using an api which takes a name of 21 char max to represent an internal session which has a lifetime of around "two days". I would like the name not to be meaningfull using some kind of hasing ? md5 generates 40 chars, is there something else i could use ?

For now i use 'userid[:10]' + creation time: ddhhmmss + random 3 chars.

Thanks,

答:
The hexadecimal representation of MD5 has very poor randomness: you only get 4 bits of entropy per character.

Use random characters, something like:

```<code>import random
import string
"".join([random.choice(string.ascii_letters + string.digits + ".-")
        for i in xrange(21)])
</code>```

In the choice put all the acceptable characters.

While using a real hash function such as SHA1 will also get you nice results if used correctly, the added complexity and CPU consumption seems not justified for your needs.  You only want a random string.

OwnerDisplayName: coulix

ContentLicense: CC BY-SA 2.5

Title: Python and random keys of 21 char max

Body:
The hexadecimal representation of MD5 has very poor randomness: you only get 4 bits of entropy per character.

Use random characters, something like:

import random
import string
"".join([random.choice(string.ascii_letters + string.digits + ".-")
        for i in xrange(21)])

In the choice put all the acceptable characters.

While using a real hash function such as SHA1 will also get you nice results if used correctly, the added complexity and CPU consumption seems not justified for your needs.  You only want a random string.

OwnerDisplayName: kmkaplan

LastEditorDisplayName: kmkaplan


问:
How to cancel editing in Halo/Spark TextInput and TextArea components
I am using Flex 4, ActionScript 3.

In the AdvancedDataGrid component, when you are in Edit mode in a cell, you can hit the Escape key to cancel editing (i.e. return to the previous value in the cell).

I had expected the same behaviour while in Edit mode in both the Halo and Spark TextInput and TextArea components, and was surprised to find out that this is not the case.

I looked at the attributes of all four components to see if this is something that I need to configure, but couldn't find anything.

Is this something that needs to be coded?

答:
Yes, this is something that will have to be coded. Here's the approach I would take:

Create a custom component that extends the TextInput. Let's call it UndoTextInput.

Add a new variable to UndoTextInput to store the original text of the TextInput. We'll call it originalText.

Add an event listener on the focusIn event. In the focusIn event handler, store the current text value in the originalText variable.

Add an event on the focusOut event. In the focusOut event, set the value of originalText back to an empty String.

Add an event listener on the keyDown event. In the event listener, check to see if the Escape (Keyboard.ESCAPE) key was pressed. If it was, reset the text back to what was stored in originalText.

I hope this helps!

UPDATE:

Here's a quick example on how to do this using an Actionscript class. Feel free to modify as needed.

```<code>package
{
    import flash.events.FocusEvent;
    import flash.events.KeyboardEvent;
    import flash.ui.Keyboard;

    import spark.components.TextInput;

    public class UndoTextInput extends TextInput
    {
        private var originalText:String = "";

        public function UndoTextInput()
        {
            super();
            this.addEventListener(FocusEvent.FOCUS_IN, focusInEventHandler);
            this.addEventListener(FocusEvent.FOCUS_OUT, focusOutEventHandler);
            this.addEventListener(KeyboardEvent.KEY_DOWN, checkKeyPress);
        }

        protected function focusOutEventHandler(event:FocusEvent):void
        {
            this.originalText = "";
        }

        protected function focusInEventHandler(event:FocusEvent):void
        {
            this.originalText = this.text;
        }

        protected function checkKeyPress(event:KeyboardEvent):void
        {
            if (event.keyCode == Keyboard.ESCAPE)
            {
                event.stopImmediatePropagation();
                this.text = this.originalText;
            }
        }
    }
}
</code>```

Body:
Yes, this is something that will have to be coded. Here's the approach I would take:

Create a custom component that extends the TextInput. Let's call it UndoTextInput.

Add a new variable to UndoTextInput to store the original text of the TextInput. We'll call it originalText.

Add an event listener on the focusIn event. In the focusIn event handler, store the current text value in the originalText variable.

Add an event on the focusOut event. In the focusOut event, set the value of originalText back to an empty String.

Add an event listener on the keyDown event. In the event listener, check to see if the Escape (Keyboard.ESCAPE) key was pressed. If it was, reset the text back to what was stored in originalText.

I hope this helps!

UPDATE:

Here's a quick example on how to do this using an Actionscript class. Feel free to modify as needed.

package
{
    import flash.events.FocusEvent;
    import flash.events.KeyboardEvent;
    import flash.ui.Keyboard;

    import spark.components.TextInput;

    public class UndoTextInput extends TextInput
    {
        private var originalText:String = "";

        public function UndoTextInput()
        {
            super();
            this.addEventListener(FocusEvent.FOCUS_IN, focusInEventHandler);
            this.addEventListener(FocusEvent.FOCUS_OUT, focusOutEventHandler);
            this.addEventListener(KeyboardEvent.KEY_DOWN, checkKeyPress);
        }

        protected function focusOutEventHandler(event:FocusEvent):void
        {
            this.originalText = "";
        }

        protected function focusInEventHandler(event:FocusEvent):void
        {
            this.originalText = this.text;
        }

        protected function checkKeyPress(event:KeyboardEvent):void
        {
            if (event.keyCode == Keyboard.ESCAPE)
            {
                event.stopImmediatePropagation();
                this.text = this.originalText;
            }
        }
    }
}


问:
Class 'App\Http\Controllers\Hash' not found
I'm trying to use Hash in my global functions file.

I keep getting this error.

Class 'App\Http\Controllers\Hash' not found

where my file below is located at:

/app/Helpers/functions.php

```<code><?php

    use App\Http\Controllers\Hash;

    // If old password matches password
    function checkOldPassword($oldPassword, $user) {
        if (Hash::check($oldPassword, $user->password)) {
            dd('a');
        }
        else {
            return back()->withErrors([
                'message' => 'Your old password is incorrect.'
            ]);
        }
    }
</code>```

答: import the hash class from use Illuminate\Support\Facades\Hash;

Body:
I'm trying to use Hash in my global functions file.

I keep getting this error.

Class 'App\Http\Controllers\Hash' not found

where my file below is located at:

/app/Helpers/functions.php

<?php

    use App\Http\Controllers\Hash;

    // If old password matches password
    function checkOldPassword($oldPassword, $user) {
        if (Hash::check($oldPassword, $user->password)) {
            dd('a');
        }
        else {
            return back()->withErrors([
                'message' => 'Your old password is incorrect.'
            ]);
        }
    }


问:
File not converting to JSON properly from xml
I am using Python to convert data from a xml file to json and putting it in a file. I am using xmltodict to convert to dictionary using 'parse' and then converting into json using 'dumps'. Here is the code below: -

```<code>import xmltodict
import json
with open('note.xml') as xml_file:
    my_dict=xmltodict.parse(xml_file.read())
xml_file.close()
json_data=json.dumps(my_dict)
with open('note.json', 'w') as f:
    json.dump(json_data, f)
</code>```

Here is a sample xml file that I have used. However, in the output, I am getting something not quite json like, with the added backslash. Looks like gibberish: -

```<code>"{\"note\": {\"to\": \"Tove\", \"from\": \"Jani\", \"heading\": \"Reminder\", \"body\": \"Don't forget me this weekend!\"}}"
</code>```

I am trying to understand why I am not able to get data in proper json form. Is there anything wrong with my code? Please note that I am not a very skilled programmer and have only used Python sporadically.

答:
You need to add below code after json_data=json.dumps(my_dict) to convert string to json object

```<code>json_data = json.loads(json_data)
</code>```

Body:
I am using Python to convert data from a xml file to json and putting it in a file. I am using xmltodict to convert to dictionary using 'parse' and then converting into json using 'dumps'. Here is the code below: -

import xmltodict
import json
with open('note.xml') as xml_file:
    my_dict=xmltodict.parse(xml_file.read())
xml_file.close()
json_data=json.dumps(my_dict)
with open('note.json', 'w') as f:
    json.dump(json_data, f)

Here is a sample xml file that I have used. However, in the output, I am getting something not quite json like, with the added backslash. Looks like gibberish: -

"{\"note\": {\"to\": \"Tove\", \"from\": \"Jani\", \"heading\": \"Reminder\", \"body\": \"Don't forget me this weekend!\"}}"

I am trying to understand why I am not able to get data in proper json form. Is there anything wrong with my code? Please note that I am not a very skilled programmer and have only used Python sporadically.

Body:
You need to add below code after json_data=json.dumps(my_dict) to convert string to json object

json_data = json.loads(json_data)


问:
React/Redux question about dispatching an action to add an item to an array
I am building a flashcard app and I would like to store the id of seen cards in an array so my GET_RANDOM_CARD action does not select the same card twice.

Inside my componentDidMount method, I dispatch the addSeenCard action like so:

```<code>addSeenCard(this.props.randomCard)
</code>```

Here is my portable action creator function for addSeenCard:

```<code>export function addSeenCard(randomCard) {

 return {
    type: 'ADD_SEEN_CARD',
    randomCard: randomCard
  }
}
</code>```

Here is my reducer function:

```<code> case 'ADD_SEEN_CARD':
  return {
      ...state,
     seenCard: [state.seenCard, action.randomCard.id]
    }
</code>```

However, the Redux tool instead of showing an array with an id value shows an array with a nested empty array and a value of null.  I am learning Redux and I am blocked as to where I am going wrong in my code.

Redux state Raw

答:
You need to deconstruct state.seenCard, like you did with ...state:

```<code> case 'ADD_SEEN_CARD':
  return {
      ...state,
     seenCard: [...state.seenCard, action.randomCard.id]
    }
</code>```

Body:
I am building a flashcard app and I would like to store the id of seen cards in an array so my GET_RANDOM_CARD action does not select the same card twice.

Inside my componentDidMount method, I dispatch the addSeenCard action like so:

addSeenCard(this.props.randomCard)

Here is my portable action creator function for addSeenCard:

export function addSeenCard(randomCard) {

 return {
    type: 'ADD_SEEN_CARD',
    randomCard: randomCard
  }
}

Here is my reducer function:

 case 'ADD_SEEN_CARD':
  return {
      ...state,
     seenCard: [state.seenCard, action.randomCard.id]
    }

However, the Redux tool instead of showing an array with an id value shows an array with a nested empty array and a value of null.  I am learning Redux and I am blocked as to where I am going wrong in my code.

Redux state Raw

Body:
You need to deconstruct state.seenCard, like you did with ...state:

 case 'ADD_SEEN_CARD':
  return {
      ...state,
     seenCard: [...state.seenCard, action.randomCard.id]
    }


问:
Customize .NET framework generated exception messages?
I was wondering if there was a reasonable way to customize messages on exceptions that are thrown by the .NET framework?  Below is a chunk of code that I write often, in many different scenarios to achieve the effect of providing reasonable exception messages to my users.

```<code>public string GetMetadata(string metaDataKey)
{
  // As you can see, I am doing what the dictionary itself will normally do, but my exception message has some context, and is therefore more descriptive of the actual problem.
  if (!_Metadata.ContainsKey(metaDataKey))
  {
    throw new KeyNotFoundException(string.Format("There is no metadata that contains the key '{0}'!", metaDataKey));
  }

  // This will throw a 'KeyNotFoundException' in normal cases, which I want, but the message "The key is not present in the dictionary" is not very informative.  This is the exception who's message I wish to alter.
  string val = _Metadata[metaDataKey].TrimEnd();
  return val;
}
</code>```

As you can see, I am essentially producing duplicate code just to use a different (better) message.

Edit:

What I am looking for, essentially is something like this:

```<code>KeyNotFoundException.SetMessage("this is my custom message!")
{
// OK, now this will send off the message I want when the exception appears!
// Now I can avoid all of that silly boilerplate!
string val = _Metadata[metaDataKey].TrimEnd();
}
</code>```

At any rate, i don't think that such a feature exists, but if it did I would be very pleased indeed.  Has anyone tackled this type of problem before?  It's looking like I am going to wind up needed some type of extension method in the end...

答:
An exception is an object. As with most objects, you can't control how the creator creates the object, whether or not the creator is the .NET Framework.

How would you even tell the .NET Framework what message to create under which circumstances? You would want one message on a KeyNotFoundException in the case you posted, and another message in a different circumstance. How would you distinguish the two situations?

Body:
I was wondering if there was a reasonable way to customize messages on exceptions that are thrown by the .NET framework?  Below is a chunk of code that I write often, in many different scenarios to achieve the effect of providing reasonable exception messages to my users.

public string GetMetadata(string metaDataKey)
{
  // As you can see, I am doing what the dictionary itself will normally do, but my exception message has some context, and is therefore more descriptive of the actual problem.
  if (!_Metadata.ContainsKey(metaDataKey))
  {
    throw new KeyNotFoundException(string.Format("There is no metadata that contains the key '{0}'!", metaDataKey));
  }

  // This will throw a 'KeyNotFoundException' in normal cases, which I want, but the message "The key is not present in the dictionary" is not very informative.  This is the exception who's message I wish to alter.
  string val = _Metadata[metaDataKey].TrimEnd();
  return val;
}

As you can see, I am essentially producing duplicate code just to use a different (better) message.

Edit:

What I am looking for, essentially is something like this:

KeyNotFoundException.SetMessage("this is my custom message!")
{
// OK, now this will send off the message I want when the exception appears!
// Now I can avoid all of that silly boilerplate!
string val = _Metadata[metaDataKey].TrimEnd();
}

At any rate, i don't think that such a feature exists, but if it did I would be very pleased indeed.  Has anyone tackled this type of problem before?  It's looking like I am going to wind up needed some type of extension method in the end...


问:
Select between two maps based on values
I have this dataset:

```<code>%{
  "away" => %{
    "id" => "575ec304-wlk3-239n-3032jdns3944",
    "points" => 115
  },
  "home" => %{
    "id" => "583ec7cd-fb46-11e1-82cb-f4ce4684ea4c",
    "points" => 120
  }
}
</code>```

I want to return the map with the most points so that I end up with this.

```<code>%{
  "home" => %{
    "id" => "583ec7cd-fb46-11e1-82cb-f4ce4684ea4c",
    "points" => 120
  }
}
</code>```

I was thinking the enum.find would work for this but I haven't had any luck. Any help would be great.

答:
While Enum.max_by/4 might seem a perfect fit here, the most performant solution would be to use plain old good Enum.reduce/3 with guarded clauses.

input = %{ ... }

Enum.reduce(input, nil, fn
  {_, %{"points" => pe}}, {_, %{"points" => pa}} = acc when pa > pe -> acc
  e, _ -> e
end)
#⇒ {"home", %{"id" => "583ec7cd-fb46-11e1-82cb-f4ce4684ea4c", "points" => 120}}
```

<p>To get back from tuple to map, one might wrap the result with <code>List.wrap/1</code> and <code>Map.new/1</code></p>

<pre class="lang-rb prettyprint-override"><code>input
|> Enum.reduce(nil, fn
  {_, %{"points" => pe}}, {_, %{"points" => pa}} = acc when pa > pe -> acc
  e, _ -> e
end)
|> List.wrap()
|> Map.new()
#⇒ %{"home" => %{"id" => "583ec7cd-fb46-11e1-82cb-f4ce4684ea4c", "points" => 120}}
</code>```

Title: Select between two maps based on values

Body:
I have this dataset:

%{
  "away" => %{
    "id" => "575ec304-wlk3-239n-3032jdns3944",
    "points" => 115
  },
  "home" => %{
    "id" => "583ec7cd-fb46-11e1-82cb-f4ce4684ea4c",
    "points" => 120
  }
}

I want to return the map with the most points so that I end up with this.

%{
  "home" => %{
    "id" => "583ec7cd-fb46-11e1-82cb-f4ce4684ea4c",
    "points" => 120
  }
}

I was thinking the enum.find would work for this but I haven't had any luck. Any help would be great.

Body:
While Enum.max_by/4 might seem a perfect fit here, the most performant solution would be to use plain old good Enum.reduce/3 with guarded clauses.

input = %{ ... }

Enum.reduce(input, nil, fn
  {_, %{"points" => pe}}, {_, %{"points" => pa}} = acc when pa > pe -> acc
  e, _ -> e
end)
#⇒ {"home", %{"id" => "583ec7cd-fb46-11e1-82cb-f4ce4684ea4c", "points" => 120}}

To get back from tuple to map, one might wrap the result with List.wrap/1 and Map.new/1

input
|> Enum.reduce(nil, fn
  {_, %{"points" => pe}}, {_, %{"points" => pa}} = acc when pa > pe -> acc
  e, _ -> e
end)
|> List.wrap()
|> Map.new()
#⇒ %{"home" => %{"id" => "583ec7cd-fb46-11e1-82cb-f4ce4684ea4c", "points" => 120}}


问:
Problem generating valid oauth2 token to access PowerBI APIs
The Setup :

Am trying to access Azure PowerBI based APIs using console application since my company wants to Suspend/Resume PBI capacity to optimize costing.

Have been successful in accessing those apis as per official documentation API Emulator Window, it works by perfect as it just asks with a authentication window for username and password of my outlook account and it generates authentication token implicitly successful.

When i tried to implement calling api from my console application which will be triggered automatically scheduled, there are ways to generate authentication token programmatically. Following are the methods i used to generate the same before accessing the PBI APIs.

Approach #1 : Generating token by using Azure Active Directory Authentication Libraries..

This approach asks to add AAD authentication libraries via Nuget, upon adding the same and it goes unsuccessful as the method AcquireTokenAsync takes no parameters but tutorial specified 4 parameters to be feed into this method (function overloading missing?). So i couldnt generate token using this approach. Surely a library version problem but the official MS documentation didnt explain anything above versions available over same.

Approach #2: Authorize Active Directory without dialog box StackOverflow Question with marked as answer

This approach upon calling HTTPResponseMessage, it gets hung up without going next line or catch statement.

Approach #3: Trying to emulate token generation using POSTMAN and using the generated token on my console app to check accessibility.

This approach gives a successful token generation but when using the generated token in the console app, it says unauthorised token.

Doubt Part:
Have generated ClientID, ClientSecretID and TenantID in Azure using AppRegisteration but dont know how this gets associated with PowerBI Service in azure. Do Azure Active Directory comes in place betweeen PBIService and AppRegisteration? Based on generated AppRegisteration details have tried to access this authentication api (https://login.microsoftonline.com/tenantId/oauth2/token) to generate token. This is successfully generates a token but miserably getting failed with unauthorised access on PBI api.

Am i badly missing something? will be helpful on what wrong about this concept of accessing PBI based API getting authenticated via console app. Asusual PBI community sites didnt help much.

答:
1. How to manage  Azure Power BI Embedded capacity

If you want to manage  Azure Power BI Embedded capacity with rest API, please refer to the following steps.

create a service principal and assign Azure RABC role to the sp(I use Azure CLI)

```<code>az login
#it will create a service principal and assign contributor role to the sp
az ad sp create-for-rbac -n "jonsp2"
</code>```

Get Token

```<code>Post https://login.microsoftonline.com/tenantId/oauth2/token
Content-Type: application/x-www-form-urlencoded

grant_type =client_credentials
&client_id=<sp app id>
&client_secret=<sp app password>
&scope=https://management.azure.com/
</code>```

Call Rest API

```<code>POST https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}/suspend?api-version=2017-10-01

Authorization: Bearer <token>
</code>```

2. How to call Power BI rest api

If you want to call Power BI rest api, please refer to the document and the document.

The detailed steps are as below

Register Azure AD application in Azure portal

Configure API permissions

Test (I test in postman)
a. get access token

b. call API

Body:
1. How to manage  Azure Power BI Embedded capacity

If you want to manage  Azure Power BI Embedded capacity with rest API, please refer to the following steps.

create a service principal and assign Azure RABC role to the sp(I use Azure CLI)

az login
#it will create a service principal and assign contributor role to the sp
az ad sp create-for-rbac -n "jonsp2"

Get Token

Post https://login.microsoftonline.com/tenantId/oauth2/token
Content-Type: application/x-www-form-urlencoded

grant_type =client_credentials
&client_id=<sp app id>
&client_secret=<sp app password>
&scope=https://management.azure.com/

Call Rest API

POST https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}/suspend?api-version=2017-10-01

Authorization: Bearer <token>

2. How to call Power BI rest api

If you want to call Power BI rest api, please refer to the document and the document.

The detailed steps are as below

Register Azure AD application in Azure portal

Configure API permissions

Test (I test in postman)
a. get access token

b. call API


问:
How to connect to remote hive server using spark2.0
I m trying to connect to a remote hive server which is in different cluster using spark. Used both hive2 and thrift but no luck

```<code>val s = SparkSession.builder().appName("Man test").config("hive.metastore.uris", "jdbc:hive2://abc.svr.yy.xxxx.net:2171/default;serviceDiscoveryMode=zooKeeper;zooKeeperNamespace=hiveserver2;principal=hive/_HOST@abc.AD.xxx.COM").enableHiveSupport().getOrCreate()

val s = SparkSession.builder().appName("Man test").config("hive.metastore.uris", "thrift://xxxx.svr.us.yyyy.net:2000").config("spark.sql.warehouse.dir", "/apps/hive/warehouse").enableHiveSupport().getOrCreate()
println("in method session created")
s.sql("show databases").show()
</code>```

I m getting the below error when use jdbc:hive2

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

and when I use thrift :
javax.security.sasl.SaslException: No common protection layer between client and server.

please let me know if I am missing something here.

答:
I solved the same issue by adding the following to the JVM options.

```<code>-Djavax.security.sasl.qop="auth-conf"
</code>```

See: https://github.com/prestodb/presto/issues/8604

Body:
I m trying to connect to a remote hive server which is in different cluster using spark. Used both hive2 and thrift but no luck

val s = SparkSession.builder().appName("Man test").config("hive.metastore.uris", "jdbc:hive2://abc.svr.yy.xxxx.net:2171/default;serviceDiscoveryMode=zooKeeper;zooKeeperNamespace=hiveserver2;principal=hive/_HOST@abc.AD.xxx.COM").enableHiveSupport().getOrCreate()

val s = SparkSession.builder().appName("Man test").config("hive.metastore.uris", "thrift://xxxx.svr.us.yyyy.net:2000").config("spark.sql.warehouse.dir", "/apps/hive/warehouse").enableHiveSupport().getOrCreate()
println("in method session created")
s.sql("show databases").show()

I m getting the below error when use jdbc:hive2

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

and when I use thrift :
javax.security.sasl.SaslException: No common protection layer between client and server.

please let me know if I am missing something here.

Body:
I solved the same issue by adding the following to the JVM options.

-Djavax.security.sasl.qop="auth-conf"

See: https://github.com/prestodb/presto/issues/8604


问:
Copying from one stream to another?
For work, the specification on my project is to use .Net 2.0 so I don't get the handy CopyTo function brought about later on.

I need to copy the response stream from an HttpWebResponse to another stream (most likely a MemoryStream, but it could be any subclass of Stream). My normal tactic has been something along the lines of:

```<code>BufferedStream bufferedresponse = new BufferedStream(HttpResponse.GetResponseStream());
int count = 0;
byte[] buffer = new byte[1024];
do {
    count = bufferedresponse.Read(buffer, 0, buffer.Length);
    target.Write(buffer, 0, count);
} while (count > 0);
bufferedresponse.Close();
</code>```

Are there more efficient ways to do this? Does the size of the buffer really matter? What is the best way to copy from one stream to another in .Net 2.0?

P.S. This is for downloading large, 200+ MB GIS tif images. Of course reliability is paramount.

答:
I can think of two ways.

Check if Stream.MemberWiseClone() fits your need. It gets you a shallow copy of your object.

Check if this works, if both the ends are of the Stream type.

BufferedStream bs = new BufferedStream((Stream)memoryStreamObject);

Title: Copying from one stream to another?

Body:
For work, the specification on my project is to use .Net 2.0 so I don't get the handy CopyTo function brought about later on.

I need to copy the response stream from an HttpWebResponse to another stream (most likely a MemoryStream, but it could be any subclass of Stream). My normal tactic has been something along the lines of:

BufferedStream bufferedresponse = new BufferedStream(HttpResponse.GetResponseStream());
int count = 0;
byte[] buffer = new byte[1024];
do {
    count = bufferedresponse.Read(buffer, 0, buffer.Length);
    target.Write(buffer, 0, count);
} while (count > 0);
bufferedresponse.Close();

Are there more efficient ways to do this? Does the size of the buffer really matter? What is the best way to copy from one stream to another in .Net 2.0?

P.S. This is for downloading large, 200+ MB GIS tif images. Of course reliability is paramount.


问:
Bootstrap right col right absolute aligned to page with no-padding
I'm trying to create a row with two cols. And right col should be right aligned to the page... I don't want use container-fluid... please help...

Thanks

答:
As for now to align the one column to the right so that it takes up the whole screen, I would think that you would be better off with custom styling.

```<code>https://www.codeply.com/go/oPTBdCw1JV
</code>```

It would be a lot easier to figure out this problem if you post an example code snippet with the picture.

Body:
As for now to align the one column to the right so that it takes up the whole screen, I would think that you would be better off with custom styling.

https://www.codeply.com/go/oPTBdCw1JV

It would be a lot easier to figure out this problem if you post an example code snippet with the picture.


问:
Finding the kth quantiles of an n-elements set. (From cormen)
The kth quantiles of an n-element set are the k - 1 order statistics that divide the sorted set into  k equal-sized sets (to within 1). Give an O(n lg k)-time algorithm to list the kth quantiles of a  set.

The straight forward solution would be to select every k, 2k, 3k .. ik the smallest element, whose running time is O(kn) (k calls to select procedure of O(n)). But this can be optimized to do better than O(kn). After finding the median of medians at the index 'i' in the select procedure, we make the following recursive call.

if the index of the median of medians i is > k, recursively call select the kth smallest element in the left subarray A[0 ... i]

if the i is < k, recursively select the n - i + k th smallest element in the right subarray A[i+1 ... n].

Can the above recursive calls be modified as below which would reduce the factor 'k' to 'log k' ?

if the index of the median of medians i is > k, recursively select the kth smallest element in the left subarray A[0 ... i] and also recursively select the n - k th smallest element in the right subarray A[i+1 ... n].

if the i is < k, recursively select the n - i + k th smallest element in the right subarray A[i+1 ... n] and also recursively select k th smallest element in the left subarray A[0 ... i].

The main call would be just select(A, k, n).

答:
"""
kth Quantiles
"""

import random, math

import SelectDetermin_1 as SD

Q=[]

def kQuantiles(A,l,r,k): # O(nlgk)

```<code>global Q
if k == 1:
    return
i = math.floor(k/2)
n = r-l+1
incr = math.floor(i*n/k)
p = SD.Dselect(A,l,r,l+incr,5)
Q.append((l+incr,p))
q = SD.partition(A,l,r,l+incr)
kQuantiles(A,l,q,math.floor(k/2))
kQuantiles(A,q,r,math.ceil(k/2))
</code>```

k = 13

A=list(range(100))

random.shuffle(A)

kQuantiles(A,0,len(A)-1,k)

Q.sort() # O(klgk)

print([x for _,x in Q])

def BFkQuantile(A,k): #O(kn)

```<code>out = []
Q = [math.floor(i * len(A)/k + 1/2) for i in range(1,k)]
for stat in Q:
    out.append(SD.Dselect(A,0,len(A)-1,stat,5))
return out
</code>```

print(BFkQuantile(A,k))

Where Dselect and partition are as in Avi Cohen's post, returning the entry in A at the required index, and the index at which the list is partitioned.

I couldn't make the previous code work so I wanted to check if this is ok

Body:
"""
kth Quantiles
"""

import random, math

import SelectDetermin_1 as SD

Q=[]

def kQuantiles(A,l,r,k): # O(nlgk)

global Q
if k == 1:
    return
i = math.floor(k/2)
n = r-l+1
incr = math.floor(i*n/k)
p = SD.Dselect(A,l,r,l+incr,5)
Q.append((l+incr,p))
q = SD.partition(A,l,r,l+incr)
kQuantiles(A,l,q,math.floor(k/2))
kQuantiles(A,q,r,math.ceil(k/2))

k = 13

A=list(range(100))

random.shuffle(A)

kQuantiles(A,0,len(A)-1,k)

Q.sort() # O(klgk)

print([x for _,x in Q])

def BFkQuantile(A,k): #O(kn)

out = []
Q = [math.floor(i * len(A)/k + 1/2) for i in range(1,k)]
for stat in Q:
    out.append(SD.Dselect(A,0,len(A)-1,stat,5))
return out

print(BFkQuantile(A,k))

Where Dselect and partition are as in Avi Cohen's post, returning the entry in A at the required index, and the index at which the list is partitioned.

I couldn't make the previous code work so I wanted to check if this is ok


问:
React Navigation: best way to implement logout navigation?
I'm using react-navigation@4.0.10 in my React Native app, and have a Login screen and two TabNavigator screens. Logging in from the Login screen takes me to TabNavigator_1, and if I log out from TabNavigator_1 I just use this.props.navigation.goBack(). The problem is, to get to TabNavigator_2 I click a button in TabNavigator_1 which triggers this.props.navigation.navigate('TabNavigator_2'), so TabNavigator_2 is now on top of the stack, and calling this.props.navigation.goBack() would just take me back to TabNavigator_1 instead of Login.

What's the best way to approach this, so that clicking Log out from TabNavigator_1 and TabNavigator_2 takes me back to Login?

答:
Using

```<code>this.props.navigation.goBack()
</code>```

to go back to login screen is pretty bad pattern to me.

Pattern I recommend:

1) After successfull login, you store logged-in user(only id and essentials credentials) in your asyncstorage.

2)After pressing Logout Button, you clear that credentials from asyncStorage.

In your Initial screeen

Check if there is logged-in user info inside asyncStorage

If yes   ->   got to tabNavigator screen

else     ->   go to login screen

Rough Demo

```<code><Stack.Navigator>
  {isLoggedIn ? (

    <Stack.Screen name="Home" component={TabNavigator} />

  ) : (
    <Stack.Screen name="SignIn" component={LogInScreen} />
  )}
</Stack.Navigator>
</code>```

Body:
Using

this.props.navigation.goBack()

to go back to login screen is pretty bad pattern to me.

Pattern I recommend:

1) After successfull login, you store logged-in user(only id and essentials credentials) in your asyncstorage.

2)After pressing Logout Button, you clear that credentials from asyncStorage.

In your Initial screeen

Check if there is logged-in user info inside asyncStorage

If yes   ->   got to tabNavigator screen

else     ->   go to login screen

Rough Demo

<Stack.Navigator>
  {isLoggedIn ? (

    <Stack.Screen name="Home" component={TabNavigator} />

  ) : (
    <Stack.Screen name="SignIn" component={LogInScreen} />
  )}
</Stack.Navigator>


问:
Deselecting the selected row in Xamarin forms list view
I have a list view. On Tapping the selected row, how do I deselect? If I select a different row which is not selected, it must select it. How do I do this? Thanks</p>

```<code>  <ListView x:Name="DimensionListView" HasUnevenRows="True"  ItemTapped="OnItemSelected"  SeparatorVisibility="Default" VerticalOptions="FillAndExpand"  >
</code>```

答:
Do you mean you want to deselect the item which is selected when you click it again ?

If yes,you could check below:

```<code><ListView x:Name="DimensionListView" HasUnevenRows="True"  ItemTapped="OnItemSelected"  SeparatorVisibility="Default" VerticalOptions="FillAndExpand"  >
</code>```

in the page.xaml.cs:

```<code>int preIndex = -1;

private void OnItemSelected(object sender, ItemTappedEventArgs e)
    {

        if (preIndex == e.ItemIndex)
        {
            DimensionListView.SelectedItem = null;
            preIndex = -1;
        }
        else
        {
            preIndex = e.ItemIndex;
        }
    }
</code>```

Body:
I have a list view. On Tapping the selected row, how do I deselect? If I select a different row which is not selected, it must select it. How do I do this? Thanks

  <ListView x:Name="DimensionListView" HasUnevenRows="True"  ItemTapped="OnItemSelected"  SeparatorVisibility="Default" VerticalOptions="FillAndExpand"  >

Body:
Do you mean you want to deselect the item which is selected when you click it again ?

If yes,you could check below:

<ListView x:Name="DimensionListView" HasUnevenRows="True"  ItemTapped="OnItemSelected"  SeparatorVisibility="Default" VerticalOptions="FillAndExpand"  >

in the page.xaml.cs:

int preIndex = -1;

private void OnItemSelected(object sender, ItemTappedEventArgs e)
    {

        if (preIndex == e.ItemIndex)
        {
            DimensionListView.SelectedItem = null;
            preIndex = -1;
        }
        else
        {
            preIndex = e.ItemIndex;
        }
    }


问:
Create h2 backup without alter statements
There's H2's specific statement Script, i'm using it to create sql file without any data:

```<code>script NODATA to 'db.sql'
</code>```

But i can't find an option to say that i don't want alter statements. I would name this option like 'ONLYDATA'.
I want to create sql file without statements like 'create table, create sequence, alter table...' but only with insert statements.

I want this because i want to load data on existing database, that already has some data, and sql script with create statements fails on it

答:
H2 has BACKUP TO 'filename.zip' command for online backups. SCRIPT can be used for this purpose too (and should be used if you need to move your data to another version of H2), but it's not a backup command, it's a data export command.

If you want to export SQL script into existing non-empty database you have two alternatives.

Execute DROP ALL OBJECTS in target database to make it empty before execution of RUNSCRIPT FROM. This way is reliable.

Use SCRIPT DROP … when you create this script. It will generate additional DROP commands for your tables. You can also use SCHEMA schemaName or TABLE tableName clause if you want to export only some tables. You may run into some other issue, however, with sequences or something else.

If you need to merge existing data with data from the script, you can't do it in that way. You need to import it in another database and create linked tables from it (or into existing database under another schema) and run MERGE INTO tableName USING scriptTableName ON … commands for each table with properly written matching rules and actions, for example.

Body:
There's H2's specific statement Script, i'm using it to create sql file without any data:

script NODATA to 'db.sql'

But i can't find an option to say that i don't want alter statements. I would name this option like 'ONLYDATA'.
I want to create sql file without statements like 'create table, create sequence, alter table...' but only with insert statements.

I want this because i want to load data on existing database, that already has some data, and sql script with create statements fails on it


问:
WinAPI mouse move notification for full desktop
In WinAPI is there a mouse move notification for the full desktop (full screen) and not for a window only?

I would like to receive mouse screen coordinates in my main window procedure.

Edit:

What I try to do is getting the coordinates from the mouse when dragging from a button in my window to outside that window.

答: You can set a mouse hook to be notified about all mouse events.</p>


问:
How to clear "Reserved Space for Replicas" without restart Hadoop services
How to find why "Reserved Space for Replicas" constantly increasing and how to limit space for this type of cache? We found that the "Reserved Space for Replicas" exceeds the Non DFS used space (last month). But we didn't find why :(

We know how to calculate "Non DFS" but the "Reserved Space for Replicas" shows a space size that doesn't correspond to actually occupied by "Non DFS". For example we have 6 TB volume:

"DFS Used" takes 4 TB

"Free space" on volume is 2 TB (this info getting by "df -h")

"Non DFS" takes 2 TB (why??? if "df -h" shows that we have 2 TB free
space)

At the current time to free up the space allocated for this type of cache ("Reserved Space for Replicas"), we need to restart the datanode services. But in our opinion this is not the solution!

We use HDP v3.0.1, HDFS v3.1, Oracle JDK 8u181

答:
For people who faced with that type of problem. First of all you should understand the nature of the problem. To do that please read the description of the following issues:

https://issues.apache.org/jira/browse/HDFS-8072

https://issues.apache.org/jira/browse/HDFS-9530

https://issues.apache.org/jira/browse/HDFS-6489

The following links will be useful to understand what block replica is:

https://blog.cloudera.com/understanding-hdfs-recovery-processes-part-1/

https://blog.cloudera.com/understanding-hdfs-recovery-processes-part-2/

Solutions

Find the wrong software which often broke connection with Hadoop during the write or append processes

Try to change replication policy (risky)

Update Hadoop up to late version

You can't reset “Reserved Space for Replicas” without restart Hadoop services!


问:
RISC-V return from exception handler with compressed instructions
I see the standard way of exiting RISC-V exception handler is update mepc to mepc+4 before mret.

But won't this cause problem if the next instruction is only 2-bytes long in compressed instruction mode?

In compressed instruction mode there are mixed of 4-bytes and 2-bytes instructions. If you not update mepc and just mret then you keep getting same exception.  But always adding 4 to trapped mepc seem like a bug for mixed compressed instruction.

Am I missing something?

答:
I see the standard way of exiting risc-v exception handler is update mepc to mepc+4 before mret.

These are not serious exception handlers; they are illustrative only — to show catching of exceptions at all, and returning back to the interrupted code without having done the actual exception processing needed for the given situation.  Thus, the easiest thing to do to prevent an infinite loop is to simply skip past the offending instruction.

One of the few places where we advance the pc in order to return to the code that cause the exception is in handling an ecall.  As far as I know there is no compressed (16-bit) ecall instruction.

Many resumable exceptions need to rerun the instruction that caused the exception — loads & stores that cause page faults (available in both 32-bit and 16-bit form), for example, need to re-execute once the page tables have been fixed (the page read in from disc and mapped into the user's address space).

Many other exceptions are not generally resumable.

However, emulation of an instruction requires knowing its size, as is the case with ecall.  if you choose to emulate, for example, misaligned memory accesses, you will indeed have to make a decision as to the size of the instruction, as emulating it means resuming past it.  Also note that RISC V supports 16-bit, 32-bit, 48-bit, 64-bit and longer instructions, so an exception handler that is going to emulate instructions will need to be able to decode their length (only the instructions chosen for emulation, though).

The other thing to add is that the sample exception handlers you may be looking at are designed to work without the compressed instruction set, and since RVC is optional that is a reasonable design choice (though ideally, of course, would be clearly stated).


问:
React Native: Double back press to Exit App

How to exit application with twice clicking the back button without needing Redux

I was looking for a solution to limit the user and do not get out of the application with one click in react native.

答:
the most simple approach for now:

in App.js：

```<code>componentDidMount() {
    const backHandler=BackHandler.addEventListener('hardwareBackPress', ()=>{
        if(this.backHandler){
            return false;
        }
        Toast.show('再按一次退出应用');
        this.backHandler=backHandler;
        setTimeout(()=>{
            this.backHandler=null;
        },2000);
        return true;
    });
}

componentWillUnmount() {
    this.backHandler.remove();
}
</code>```

Body:
the most simple approach for now:

in App.js：

componentDidMount() {
    const backHandler=BackHandler.addEventListener('hardwareBackPress', ()=>{
        if(this.backHandler){
            return false;
        }
        Toast.show('再按一次退出应用');
        this.backHandler=backHandler;
        setTimeout(()=>{
            this.backHandler=null;
        },2000);
        return true;
    });
}

componentWillUnmount() {
    this.backHandler.remove();
}