问:
How can I redirect to auth0 without clicking on the Log In button in react using the new auth0-spa.js?
I was working with the new auth0-spa and followed its tutorial to implement the auth0 SDK given by auth0 here.
I want to automatically redirect to the auth0 login page instead of a page that gives a button saying Log In.
Can anyone help me?
Here is my code </p>

```<code>import PrivateRoute from "./PrivateRoute";
import React,{useState} from "react";
import { useAuth0 } from "../react-auth0-spa";
import {BrowserRouter, HashRouter, Link, Route, Router, Switch} from "react-router-dom";
import DefaultLayout from "../containers/DefaultLayout";
import history from "../utils/history";
const NavBar = () => {
const { isAuthenticated, loginWithRedirect, logout } = useAuth0();

return (

<div>
  {!isAuthenticated && (
    <button id="button" onClick={() => loginWithRedirect({})}>Log in</button>
  )}

  {isAuthenticated && (
    <HashRouter history = {history}>
      <Switch>
        <PrivateRoute path="/" component={DefaultLayout}/>
      </Switch>
    </HashRouter>
  )}
</div>
);
};

export default NavBar;
</code>```

答:
This is what I did:</p>

```<code>const App: React.FC<{}> = () => {

    const { isLoading, loginWithRedirect, user } = useAuth0();

    useEffect(() => {
      (async function login() {
        if (!isLoading && !user) {
          await loginWithRedirect();
        }
      })();
    }, [isLoading]);

    return (
      <React.Fragment>
        {/* your code */}
      </React.Fragment>
    )
  }
</code>```

Body:
I was working with the new auth0-spa and followed its tutorial to implement the auth0 SDK given by auth0 here.
I want to automatically redirect to the auth0 login page instead of a page that gives a button saying Log In.
Can anyone help me?
Here is my code

import PrivateRoute from "./PrivateRoute";
import React,{useState} from "react";
import { useAuth0 } from "../react-auth0-spa";
import {BrowserRouter, HashRouter, Link, Route, Router, Switch} from "react-router-dom";
import DefaultLayout from "../containers/DefaultLayout";
import history from "../utils/history";
const NavBar = () => {
const { isAuthenticated, loginWithRedirect, logout } = useAuth0();

return (

  {!isAuthenticated && (
    <button id="button" onClick={() => loginWithRedirect({})}>Log in</button>
  )}

  {isAuthenticated && (
    <HashRouter history = {history}>
      <Switch>
        <PrivateRoute path="/" component={DefaultLayout}/>
      </Switch>
    </HashRouter>
  )}

);
};

export default NavBar;

Body:
This is what I did:

const App: React.FC<{}> = () => {

    const { isLoading, loginWithRedirect, user } = useAuth0();

    useEffect(() => {
      (async function login() {
        if (!isLoading && !user) {
          await loginWithRedirect();
        }
      })();
    }, [isLoading]);

    return (
      <React.Fragment>
        {/* your code */}
      </React.Fragment>
    )
  }


来源: stackexchange

问:
Ocaml - return number of expressions
I got this string

```<code>let reg = "(((T . (A . G)) + (T . C)) . (A + (C + (G* . T)))*)";;
</code>```

For the given string I want to recursively count how many expressions in the form (expr simbol expr)->(A + C) exist in the string "reg". All possible values

```<code>(A . G);
(T . (A . G));
(T . C);
((T . (A . G)) + (T . C));
(G* . T);
(C + (G* . T));
(A + (C + (G* . T)));
(((T . (A . G)) + (T . C)) . (A + (C + (G* . T)))*)
</code>```

and in end return 8;

I am not able to establish a stop condition for the recursive function. Any suggestion?

答:
I can't really answer because (IMHO) your question isn't specific enough. To get a good answer you need to describe the possible inputs and the desired results very carefully.

It's not even clear whether the desired result is just a number (8 in your example), or if it should include an enumeration of all the subexpressions.

As I pointed out in the comments, if all the expressions are parenthesized then you don't need to work very hard to count them. You can simply count the number of left parentheses. You can check that this works for your example.

```<code> let count_lpar s =
     let rec icount accum index =
         if index >= String.length s then
             accum
         else
             let accum' = if s.[index] = '(' then accum + 1 else accum in
             icount accum' (index + 1)
     in
     icount 0 0
</code>```

Here's how it works on your example string:

```<code>val count_lpar : string -> int = <fun>
# count_lpar "(((T . (A . G)) + (T . C)) . (A + (C + (G* . T)))*)";;
- : int = 8
</code>```

The helper function icount is, indeed, a recursive function. The stop condition is that it reaches the end of the string.

If you need to enumerate the expressions, again assuming that the expressions are always parenthesized, then you can do this by locating the matching right parenthesis of every left parenthesis. You can do this by counting +1 for every left parenthesis and -1 for every right parenthesis and scanning until the count reaches 0.

If your input has a more general form, you need to describe it more carefully if you want to get help from StackOverflow. A careful description cna't be something like "here's an example". It would have to be something like "here's a context free grammar that generates all the possible inputs".

ContentLicense: CC BY-SA 4.0

Title: Ocaml - return number of expressions

Body:
I got this string

let reg = "(((T . (A . G)) + (T . C)) . (A + (C + (G* . T)))*)";;

For the given string I want to recursively count how many expressions in the form (expr simbol expr)->(A + C) exist in the string "reg". All possible values

(A . G);
(T . (A . G));
(T . C);
((T . (A . G)) + (T . C));
(G* . T);
(C + (G* . T));
(A + (C + (G* . T)));
(((T . (A . G)) + (T . C)) . (A + (C + (G* . T)))*)

and in end return 8;

I am not able to establish a stop condition for the recursive function. Any suggestion?

Body:
I can't really answer because (IMHO) your question isn't specific enough. To get a good answer you need to describe the possible inputs and the desired results very carefully.

It's not even clear whether the desired result is just a number (8 in your example), or if it should include an enumeration of all the subexpressions.

As I pointed out in the comments, if all the expressions are parenthesized then you don't need to work very hard to count them. You can simply count the number of left parentheses. You can check that this works for your example.

 let count_lpar s =
     let rec icount accum index =
         if index >= String.length s then
             accum
         else
             let accum' = if s.[index] = '(' then accum + 1 else accum in
             icount accum' (index + 1)
     in
     icount 0 0

Here's how it works on your example string:

val count_lpar : string -> int = <fun>
# count_lpar "(((T . (A . G)) + (T . C)) . (A + (C + (G* . T)))*)";;
- : int = 8

The helper function icount is, indeed, a recursive function. The stop condition is that it reaches the end of the string.

If you need to enumerate the expressions, again assuming that the expressions are always parenthesized, then you can do this by locating the matching right parenthesis of every left parenthesis. You can do this by counting +1 for every left parenthesis and -1 for every right parenthesis and scanning until the count reaches 0.

If your input has a more general form, you need to describe it more carefully if you want to get help from StackOverflow. A careful description cna't be something like "here's an example". It would have to be something like "here's a context free grammar that generates all the possible inputs".


问:
Cannot display image in laravel
I've tried displaying an image with laravel using a Query-- The images are stored in the storage directory and a symlink with "public" has already been established.

I have tried using:
src="{{storage_path('app/public/'.$post->post_image)}}"

src="{{ asset('storage/'.$post->post_image) }}"

src="{{$post->post_image}}"

Testing, I discovered I could use a static path in order to succesfully display the imaage like so:

src="{{ asset('storage/images/image_name.jpeg')}}"

However, this is not what I'm looking for.

The query {{$post->post_image}} returns the following:

127.0.0.1:8000/images/image_name.jpeg

EDIT: If I go edit the database and add "storage/" before the url of the image, then I can use src="{{asset($post->post_image)}}" to display it.

As mentioned before, I already tried src="{{asset('storage/' . $post->post_image)}} without altering the database.

答:
Thank you all for your contribution, here's how I fixed it using contributions from jstarnate & Abiola:

I created a url helper and properly formatted using str_replace like so:

```<code>    public function url()
{
    return str_replace("http://localhost/storage/http://127.0.0.1:8000/","http://127.0.0.1:8000/storage/",Storage::url($this->post_image));
}
</code>```

Title: Cannot display image in laravel

Body:
Thank you all for your contribution, here's how I fixed it using contributions from jstarnate & Abiola:

I created a url helper and properly formatted using str_replace like so:

    public function url()
{
    return str_replace("http://localhost/storage/http://127.0.0.1:8000/","http://127.0.0.1:8000/storage/",Storage::url($this->post_image));
}


问:
DirectX 11 enum D3D11_USAGE and D3D_PRIMITIVE_TOPOLOGY warning
When using DirectX 11 and MSVS2019 I get the following warnings when using the enums 'D3D11_USAGE' and 'D3D_PRIMITIVE_TOPOLOGY:

Warning   C26812  The enum type 'D3D11_USAGE' is unscoped. Prefer 'enum
  class' over 'enum' (Enum.3).

Warning   C26812  The enum type 'D3D_PRIMITIVE_TOPOLOGY' is unscoped.
  Prefer 'enum class' over 'enum' (Enum.3).

What can I do to resolve those warnings? The code works fine with the warnings, but I rather have them gone.

Thank you.

答:
C26812 is part of the Microsoft Visual C++ Code Analysis (/analyze ) C++ Core Guidelines checkers rules.

Generally the warnings in the Windows 10 SDK system headers are automatically suppressed.
 The mostly likely problem is that you are using the legacy DirectX SDK, as those headers will not be automatically suppressed.

First thing to consider is removing all use of the legacy DirectX SDK. The Windows 10 SDK that comes with Visual Studio 2019 already contains all the Direct3D headers you need. If you are using XNAMath, you can use DirectXMath instead. If you are using the legacy D3DX11 library, move to one of the open source alternatives. If you are using XAudio 2.7, use the XAudio2Redist instead. If you are using the D3DX library to compile your HLSL shaders, use D3DCompile directly instead. If you are using XInput 1.3, look at using a built-in XInput version instead.

If removing the legacy DirectX SDK is not a viable option, then adjust your include/lib paths so that you get the Windows 10 SDK headers whenever possible instead. See Microsoft Docs for details, but in short edit VC++ Directories so that the DXSDK_DIR include/lib paths are LAST instead of FIRST in the search order.

You can also ignore the warning by suppressing it with #pragma warning(disable : 26812) and/or the command-line option /wd26812. The C++ Core Guidelines checkers are a little pedantic, and in some cases are really just advice.

The Visual C++ team has removed a lot of the checkers from the Microsoft Native Recommended Rules but still has 26812 listed. You can create a custom ruleset, or disable Code Analysis on Build as well. Personally, I just suppress this one in my projects as I have good reasons to NOT use a class enum.


问:
Which HTTP library is better? Wget, cUrl, LibWWW or ...?
Which library is better for HTTP? Wget, cUrl, LibWWW or any thing else?

I want a portable C/C++ library.

Thanks

答:
wget2 has a backend library. Code using the library can be compiled with lwget flag. Give it a try.

https://gnuwget.gitlab.io/wget2/reference/

ContentLicense: CC BY-SA 3.0


问:
Why does the "Try a higher/lower number." only appear after the second run?
When I run the code with the commented out portion, the program works as intended. After the first guess, it tells the user to try a higher or lower number. Without the commented out portion, the prompts only appear after the second guess.

I just started learning Java and the book I am following does not offer further explanation.

```<code>import static java.lang.System.out;
import java.util.Scanner;
import java.util.Random;

public class GuessAgain {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);

        int numGuesses = 0;
        int randomNumber = new Random().nextInt(100) + 1;

        int minbound = 1;
        int maxbound = 100;

        out.println("          **********          ");
        out.println(" Welcome to the Guessing Game ");
        out.println("          **********          ");
        out.println();

        out.print(" Enter an number from " + minbound + " to " + maxbound + ": ");
        int inputNumber = keyboard.nextInt();
        numGuesses++;

        /*
        if (inputNumber > randomNumber) {
            out.println("Try a lower number!");
        }
        if (inputNumber < randomNumber) {
            out.println("Try a higher number!");

         */

            while (inputNumber != randomNumber) {
                out.println();
                out.print(" Enter an number from " + minbound + " to " + maxbound + ": ");
                inputNumber = keyboard.nextInt();
                numGuesses++;

                if (inputNumber > randomNumber) {
                    out.println("Try a lower number!");
                }
                if (inputNumber < randomNumber) {
                    out.println("Try a higher number!");
                }
            }

            out.println("You win after " + numGuesses + " guesses.");

            keyboard.close();

        }
    }

</code>```

答:
You need to print out the result before asking for the next input.
For example:</p>

```<code>while (inputNumber != randomNumber) {
    if (inputNumber > randomNumber) out.println("Try a lower number!");
    if (inputNumber < randomNumber) out.println("Try a higher number!");

    out.println();
    out.print(" Enter an number from " + minbound + " to " + maxbound + ": ");
    inputNumber = keyboard.nextInt();
    numGuesses++;
}
</code>```

Body:
When I run the code with the commented out portion, the program works as intended. After the first guess, it tells the user to try a higher or lower number. Without the commented out portion, the prompts only appear after the second guess.

I just started learning Java and the book I am following does not offer further explanation.

import static java.lang.System.out;
import java.util.Scanner;
import java.util.Random;

public class GuessAgain {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);

        int numGuesses = 0;
        int randomNumber = new Random().nextInt(100) + 1;

        int minbound = 1;
        int maxbound = 100;

        out.println("          **********          ");
        out.println(" Welcome to the Guessing Game ");
        out.println("          **********          ");
        out.println();

        out.print(" Enter an number from " + minbound + " to " + maxbound + ": ");
        int inputNumber = keyboard.nextInt();
        numGuesses++;

        /*
        if (inputNumber > randomNumber) {
            out.println("Try a lower number!");
        }
        if (inputNumber < randomNumber) {
            out.println("Try a higher number!");

         */

            while (inputNumber != randomNumber) {
                out.println();
                out.print(" Enter an number from " + minbound + " to " + maxbound + ": ");
                inputNumber = keyboard.nextInt();
                numGuesses++;

                if (inputNumber > randomNumber) {
                    out.println("Try a lower number!");
                }
                if (inputNumber < randomNumber) {
                    out.println("Try a higher number!");
                }
            }

            out.println("You win after " + numGuesses + " guesses.");

            keyboard.close();

        }
    }

Body:
You need to print out the result before asking for the next input.
For example:

while (inputNumber != randomNumber) {
    if (inputNumber > randomNumber) out.println("Try a lower number!");
    if (inputNumber < randomNumber) out.println("Try a higher number!");

    out.println();
    out.print(" Enter an number from " + minbound + " to " + maxbound + ": ");
    inputNumber = keyboard.nextInt();
    numGuesses++;
}


问:
Is there a replacement library for CORBA in JDK 11
JDK-11 will remove a lot of older parts of the JDK (JEP-320).
For some of them (e.g. JAXB) functionality will be provided as regular library. You simply add another dependency and everything works fine again.

But not so for CORBA, because

There is no significant interest in developing modern applications with CORBA in Java

I am however in the painful situation of needing to maintain older applications that still require CORBA while still wanting to update to JDK-11.

Is there a replacement-library out there or another good way of migrating to JDK-11 without removing the CORBA functionality of these applications?

答: JDK 11 is fully supported by all of the ORB's supplied by Micro Focus.</p>


问:
how to use setInterval with redux-thunk?
I'm using redux-thunk to manage async functions, and I want to use setInterval within an action creator, this is my code:

```<code>export const startLobbyPolling = () => dispatch => {
  const pollTimer = setInterval(() => {
    dispatch(fetchLobby);
  }, POLL_TIME);
  dispatch({ type: START_LOBBY_POLLING, payload: pollTimer });
};
</code>```

fetchLobby is another action creator that simply fetch a request and store its data.
but surprisingly it's not working as it only shows START_LOBBY_POLLING action in redux debugger tool and nothing happens afterward. I would appreciate it to know how to use setInterval with redux.

答:
I would suggest to not use redux as a polling manager.

Instead you should have a component / container that does that for you. The reason being is, that when the component will get unmounted, also your polling will be properly canceled

```<code>const PollContainer = ({ fetchLoby, children }) => {
   useEffect(() => {
      const ptr = setInterval(fetchLoby, POLL_TIME)
      return () => clearInterval(ptr)
   }, [fetchLoby])

   return children
}
</code>```

you can now use your PollContainer and as long as it is mounted, it will keep fetchLoby.

Body:
I'm using redux-thunk to manage async functions, and I want to use setInterval within an action creator, this is my code:

export const startLobbyPolling = () => dispatch => {
  const pollTimer = setInterval(() => {
    dispatch(fetchLobby);
  }, POLL_TIME);
  dispatch({ type: START_LOBBY_POLLING, payload: pollTimer });
};

fetchLobby is another action creator that simply fetch a request and store its data.
but surprisingly it's not working as it only shows START_LOBBY_POLLING action in redux debugger tool and nothing happens afterward. I would appreciate it to know how to use setInterval with redux.

Body:
I would suggest to not use redux as a polling manager.

Instead you should have a component / container that does that for you. The reason being is, that when the component will get unmounted, also your polling will be properly canceled

const PollContainer = ({ fetchLoby, children }) => {
   useEffect(() => {
      const ptr = setInterval(fetchLoby, POLL_TIME)
      return () => clearInterval(ptr)
   }, [fetchLoby])

   return children
}

you can now use your PollContainer and as long as it is mounted, it will keep fetchLoby.


问:
Exercise 4.2.8 from "Compilers - Principles, Techniques, & Tools" (a.k.a. Dragon Book)
I have been banging my head on this problem for a while.

This is the text of the exercise:

The grammar in Fig. 4.7 generates declarations for a single numerical identifier; these declarations involve four different, independent properties of numbers.

```<code>stmt -> declare id optionList
optionList -> optionList option | ε
option -> mode | scale | precision | base
mode -> real | complex
scale -> fixed | floating
precision -> single | double
base -> binary | decimal
</code>```

1) Generalize the grammar of Fig. 4.7 by allowing n options Ai, for some fixed n and for i = 1,2... ,n, where Ai can be either ai or bi· Your grammar should use only 0(n) grammar symbols and have a total length of productions that is O(n).
2) The grammar of Fig. 4.7 and its generalization in part (a) allow declarations that are contradictory and/or redundant, such as

declare foo real fixed real floating

We could insist that the syntax of the language forbid such declarations; that is, every declaration generated by the grammar has exactly one value for each of the n options. If we do, then for any fixed n there is only a finite number of legal declarations. The language of legal declarations thus has a grammar (and also a regular expression), as any finite language does. The obvious grammar, in which the start symbol has a production for every legal declaration has n! productions and a total production length of O(n x n!). You must do better: a total production length that is O(n2^n)
Show that any grammar for part (b) must have a total production length of at least 2^n.

In particular, I am stuck on part 2. I know that given n binary options, setting an option to a_n or b_n results in 2^n combinations. What I don't know is how to express this without mentioning the position of each option.

I.e., how do I come up with a grammar where I can specify any A1...AN options, without expressing all the N! combinations (e.g., for A1, A2 and A3: A1 A2 A3, A1 A3A 2, A2 A1 A3, A2 A3 A1, A3 A1 A2, A3 A2 A1 )?

Thanks

答:
Instead of trying to write a grammar, we could just create a finite-state machine (which, as we know, is equivalent for a regular grammar). It should be clear that in this finite-state machine, each state will correspond to some subset of the n attribute types, and all of its valid transitions will be to states which represent a subset with exactly one more attribute type. (All of the states are accepting, since there is no minimum number of attributes.) So for the grammar with four attribute types (the original grammar), we end up with 16 states:

To convert that to a grammar, we only need to make each state a non-terminal, and each edge a production. Since there are never more than n transitions from any node, the total number of edges (and hence productions) is less than n·2n. (In fact, there are exactly n·2n-1 transitions in the state machine.) Furthermore, every production right-hand side has at most two symbols.

Body:
I have been banging my head on this problem for a while.

This is the text of the exercise:

The grammar in Fig. 4.7 generates declarations for a single numerical identifier; these declarations involve four different, independent properties of numbers.

stmt -> declare id optionList
optionList -> optionList option | ε
option -> mode | scale | precision | base
mode -> real | complex
scale -> fixed | floating
precision -> single | double
base -> binary | decimal

1) Generalize the grammar of Fig. 4.7 by allowing n options Ai, for some fixed n and for i = 1,2... ,n, where Ai can be either ai or bi· Your grammar should use only 0(n) grammar symbols and have a total length of productions that is O(n).
2) The grammar of Fig. 4.7 and its generalization in part (a) allow declarations that are contradictory and/or redundant, such as

declare foo real fixed real floating

We could insist that the syntax of the language forbid such declarations; that is, every declaration generated by the grammar has exactly one value for each of the n options. If we do, then for any fixed n there is only a finite number of legal declarations. The language of legal declarations thus has a grammar (and also a regular expression), as any finite language does. The obvious grammar, in which the start symbol has a production for every legal declaration has n! productions and a total production length of O(n x n!). You must do better: a total production length that is O(n2^n)
Show that any grammar for part (b) must have a total production length of at least 2^n.

In particular, I am stuck on part 2. I know that given n binary options, setting an option to a_n or b_n results in 2^n combinations. What I don't know is how to express this without mentioning the position of each option.

I.e., how do I come up with a grammar where I can specify any A1...AN options, without expressing all the N! combinations (e.g., for A1, A2 and A3: A1 A2 A3, A1 A3A 2, A2 A1 A3, A2 A3 A1, A3 A1 A2, A3 A2 A1 )?

Thanks


问:
Oracle SQL - select query with where condition greater than certain moment defined in a timestamp column
I have a table where there is a column, report_time, whose type is timestamp. A value of it looks like "25-May-20 05.03.20.12000 PM", now I want to filter out all rows whose report_time is greater than or equal to that moment, a pseudo where clause looks like:

```<code>where report_time >= to_timestamp("25-May-20 05.03.20.12000 PM", "DD-MON-YY HH.MI.SS.FF PM")
</code>```

somehow I failed to get it work, even after googling for quite some time.

Please help.

答:
I think the idea is ok with this syntax:</p>

```<code>report_time >= to_timestamp('25-May-20 05.03.20.12000 PM', 'DD-MON-YY HH.MI.SS.FF PM')
</code>```

Body:
I have a table where there is a column, report_time, whose type is timestamp. A value of it looks like "25-May-20 05.03.20.12000 PM", now I want to filter out all rows whose report_time is greater than or equal to that moment, a pseudo where clause looks like:

where report_time >= to_timestamp("25-May-20 05.03.20.12000 PM", "DD-MON-YY HH.MI.SS.FF PM")

somehow I failed to get it work, even after googling for quite some time.

Please help.

Body:
I think the idea is ok with this syntax:

report_time >= to_timestamp('25-May-20 05.03.20.12000 PM', 'DD-MON-YY HH.MI.SS.FF PM')


问:
How to set a Key Vault secret from Azure Function app in the same resource group?
I would like to set up an Azure Function, which would run every 4h, retrieve a JWK from an URL (it is not the one I show below) and save it into a Key Vault as a secret.

When I try the Powershell code at the command line, it just works:

```<code>PS C:\> $x5c = (Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys |
>> ConvertFrom-Json |
>> Select-Object -expand keys |
>> Where-Object -Property kid -Eq SsZsBNhZcF3Q9S4trpQBTByNRRI) |
>> Select-Object -expand x5c
PS C:\> $secretvalue = ConvertTo-SecureString $x5c -AsPlainText -Force
PS C:\> $secret = Set-AzKeyVaultSecret -VaultName my-keyvault -Name 'MyLittleSecret' -SecretValue $secretvalue
</code>```

and I can see the secret in the Key Vault:

However when I try to set up a timed Azure Function, then nothing happens, when I click "Run":

I suppose that being a Function newbie I am looking in the wrong place for the logs... But even if I find them, is that the correct way to do my task?

Does Azure PowerShell work in a Function?

Does it require a Login-AzAccount first?

答:
```<code>Does Azure PowerShell work in a Function?
</code>```

Yes you can use Powershell to create Azure function. And this should help you

```<code>Does it require a Login-AzAccount first?
</code>```

Yes if you need some logic related to Azure resources you need it.

When it comes to actual question, i think you need to zip the function and upload it to azure function app,

Zip the folder to upload the Azure Function

```<code>Compress-Archive -Path * -DestinationPath Function1.zip
</code>```

Body:
I would like to set up an Azure Function, which would run every 4h, retrieve a JWK from an URL (it is not the one I show below) and save it into a Key Vault as a secret.

When I try the Powershell code at the command line, it just works:

PS C:\> $x5c = (Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys |
>> ConvertFrom-Json |
>> Select-Object -expand keys |
>> Where-Object -Property kid -Eq SsZsBNhZcF3Q9S4trpQBTByNRRI) |
>> Select-Object -expand x5c
PS C:\> $secretvalue = ConvertTo-SecureString $x5c -AsPlainText -Force
PS C:\> $secret = Set-AzKeyVaultSecret -VaultName my-keyvault -Name 'MyLittleSecret' -SecretValue $secretvalue

and I can see the secret in the Key Vault:

However when I try to set up a timed Azure Function, then nothing happens, when I click "Run":

I suppose that being a Function newbie I am looking in the wrong place for the logs... But even if I find them, is that the correct way to do my task?

Does Azure PowerShell work in a Function?

Does it require a Login-AzAccount first?

Body:
Does Azure PowerShell work in a Function?

Yes you can use Powershell to create Azure function. And this should help you

Does it require a Login-AzAccount first?

Yes if you need some logic related to Azure resources you need it.

When it comes to actual question, i think you need to zip the function and upload it to azure function app,

Zip the folder to upload the Azure Function

Compress-Archive -Path * -DestinationPath Function1.zip


问:
My console is saying that it terminated a file but it never wrote the words that I needed in the console
I'm having trouble with a script that I wrote. My code is :

```<code>public void run() {
    init();
    while (true) {
        update();
        render();
    }
}

private void update() {
    System.out.println("Updating");
}

private void render( ) {
    System.out.println("Rendering");
}
</code>```

When I hit run all it says is that it terminated the file javaw.exe. It doesn't output the text in the quotes. Please help by fixing what is wrong

答:
try adding this line after your impressions and validate that you are entering the if </p>

```<code>private void render( ) {
System.out.println("Rendering");
Console.ReadKey();
</code>```

<p>}</p>

Body:
I'm having trouble with a script that I wrote. My code is :

public void run() {
    init();
    while (true) {
        update();
        render();
    }
}

private void update() {
    System.out.println("Updating");
}

private void render( ) {
    System.out.println("Rendering");
}

When I hit run all it says is that it terminated the file javaw.exe. It doesn't output the text in the quotes. Please help by fixing what is wrong

Body:
try adding this line after your impressions and validate that you are entering the if

private void render( ) {
System.out.println("Rendering");
Console.ReadKey();

}


问:
MVC / ASP.NET design templates
Does anyone know of any good sites to download good design templates (master pages, css files) for MVC projects, or ASP.NET projects in general?  I've used the asp.net mvc gallery but the options there are pretty limited.  I'm willing to pay for some if they are good.</p>

答:
take a look at this project : http://mvccontribgallery.codeplex.com/

there are many ASP.NET MVC design samples inside this project.

ContentLicense: CC BY-SA 2.5

Title: MVC / ASP.NET design templates


问:
How to split array into chunks of given size? (JavaScript)
I'm trying to work out how I can get such senario to work:

```<code>MEAL DEAL: $4.99 - Total 3 items
Must includ 1 of each "DRINK, SANCKS, SANDWICH"
</code>```

I have this array:

```<code>[
  { "CAT": "DRINKS", "QTY": 1, "PRICE": 1.2 },
  { "CAT": "DRINKS", "QTY": 1, "PRICE": 1.5 },
  { "CAT": "SANCKS", "QTY": 1, "PRICE": 2.5 },
  { "CAT": "SANCKS", "QTY": 1, "PRICE": 3.5 },
  { "CAT": "SANCKS", "QTY": 1, "PRICE": 1.5 },
  { "CAT": "SANDWICH", "QTY": 1, "PRICE": 5.3 },
  { "CAT": "SANDWICH", "QTY": 1, "PRICE": 3.0 }
]
</code>```

Based on array above, I need to split it into chunks of 3 elements to create a meal deal.

Looking at array above (7 elements) we can only have 2x Meal deals with 1 item "SNACK" that can't be part of the meal deal just yet because its missing other 2 necessary elements.

I have tried the forEach loop but it only works for initial meal deal and than rest it dont work out.

```<code>var PER_CATEGORY_SET ={}
var ITM = "";
MY_ARRAY.forEach(function (my_item){
    var xx = MY_ARRAY.length;

    while (xx > 0) {
        if(ITM !=  my_item.CAT ){
           ITM = my_item.CAT;
           PER_CATEGORY_SET.push({'CAT':my_item.CAT,'QTY':my_item.QTY,'PRICE':my_item.PRICE});
           MY_ARRAY.splice(0, 1);
        }
        xx--;
    }
});
console.log(PER_CATEGORY_SET);
</code>```

Any help would be very much appreciated, I have tried searching for examples to help me work out how I can do it myself (I'm not looking for a copy & paste code)

答:
You could group each object based on the CAT value. Get which of the groups have the smallest number of items. Create a meals of that length and take items from each index of the each group

const input=[{CAT:"DRINKS",QTY:1,PRICE:1.2},{CAT:"DRINKS",QTY:1,PRICE:1.5},{CAT:"SANCKS",QTY:1,PRICE:2.5},{CAT:"SANCKS",QTY:1,PRICE:3.5},{CAT:"SANCKS",QTY:1,PRICE:1.5},{CAT:"SANDWICH",QTY:1,PRICE:5.3},{CAT:"SANDWICH",QTY:1,PRICE:3}];

const group = input.reduce((acc, o) => {
  acc[o.CAT] = acc[o.CAT] || [];
  acc[o.CAT].push(o);
  return acc;
}, {})

const groupedArrays = Object.values(group),
      possibleMeals = Math.min(...groupedArrays.map(a => a.length)),
      meals = Array.from({ length: possibleMeals },
                          (_, i) => groupedArrays.map(g => g[i]))

console.log(meals)```

Body:
I'm trying to work out how I can get such senario to work:

MEAL DEAL: $4.99 - Total 3 items
Must includ 1 of each "DRINK, SANCKS, SANDWICH"

I have this array:

[
  { "CAT": "DRINKS", "QTY": 1, "PRICE": 1.2 },
  { "CAT": "DRINKS", "QTY": 1, "PRICE": 1.5 },
  { "CAT": "SANCKS", "QTY": 1, "PRICE": 2.5 },
  { "CAT": "SANCKS", "QTY": 1, "PRICE": 3.5 },
  { "CAT": "SANCKS", "QTY": 1, "PRICE": 1.5 },
  { "CAT": "SANDWICH", "QTY": 1, "PRICE": 5.3 },
  { "CAT": "SANDWICH", "QTY": 1, "PRICE": 3.0 }
]

Based on array above, I need to split it into chunks of 3 elements to create a meal deal.

Looking at array above (7 elements) we can only have 2x Meal deals with 1 item "SNACK" that can't be part of the meal deal just yet because its missing other 2 necessary elements.

I have tried the forEach loop but it only works for initial meal deal and than rest it dont work out.

var PER_CATEGORY_SET ={}
var ITM = "";
MY_ARRAY.forEach(function (my_item){
    var xx = MY_ARRAY.length;

    while (xx > 0) {
        if(ITM !=  my_item.CAT ){
           ITM = my_item.CAT;
           PER_CATEGORY_SET.push({'CAT':my_item.CAT,'QTY':my_item.QTY,'PRICE':my_item.PRICE});
           MY_ARRAY.splice(0, 1);
        }
        xx--;
    }
});
console.log(PER_CATEGORY_SET);

Any help would be very much appreciated, I have tried searching for examples to help me work out how I can do it myself (I'm not looking for a copy & paste code)


问:
Could not load file or assembly or one of its dependencies
I'm having another of these "Could not load file or assembly or one of its dependencies" problems.

Additional information: Could not load
file or assembly
'Microsoft.Practices.Unity,
Version=1.2.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35' or
one of its dependencies. The located
assembly's manifest definition does
not match the assembly reference.
(Exception from HRESULT: 0x80131040)

I have no idea what is causing this or how I could debug it to find the cause.

I've done a search in my solution catalogs .csproj files, and every where I have Unity I have:

Reference
Include="Microsoft.Practices.Unity,
Version=2.0.414.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35,
processorArchitecture=MSIL"

Can't find any reference anywhere which goes against 1.2.0.0 in any of my projects.

Any ideas how I should go about solving this?

答: Your project's csproj file must contain a package reference of Microsoft.Practices.Unity and this could not be found in the global-packages folder (%userprofile%.nuget\packages), running dotnet restore fixes the issue


问:
Getting JSONP via jQuery
UPDATE 1:

This is what I get in the browser if I type

http://www.remote_host.com/feed.php?callback=jsonpCallBack

```<code>{
    "rss": {
        "channels": [
            {
                "title": "title goes here",
                "link": "http://www.remote_server.com/feed.php",
                "description": "description goes here",
                "items": [
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    }
                ]
            }
        ]
    }
}
</code>```

So this is not jsonp?

ORIGINAL QUESTION:

I have the following script where I am trying to get json data from a remote host:

```<code>$(document).ready(function() {
    get_json_feed();

    function get_json_feed() {
        $.ajax({
            url: 'http://www.remote_host.com/feed.php?type=json',
            type: 'GET',
            dataType: 'jsonp',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(json) {
                alert("success");
            }
        });
    }
});
</code>```

But for some reason I am getting an error and warning:

Warning: Resource interpreted as
  Script but transferred with MIME type
  text/html.

Error: Uncaught SyntaxError:
  Unexpected token :

What am I doing wrong?

答: Looks like server returns wrong Content-type header.</p>

Title: Getting JSONP via jQuery

Body:
UPDATE 1:

This is what I get in the browser if I type

http://www.remote_host.com/feed.php?callback=jsonpCallBack

{
    "rss": {
        "channels": [
            {
                "title": "title goes here",
                "link": "http://www.remote_server.com/feed.php",
                "description": "description goes here",
                "items": [
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    }
                ]
            }
        ]
    }
}

So this is not jsonp?

ORIGINAL QUESTION:

I have the following script where I am trying to get json data from a remote host:

$(document).ready(function() {
    get_json_feed();

    function get_json_feed() {
        $.ajax({
            url: 'http://www.remote_host.com/feed.php?type=json',
            type: 'GET',
            dataType: 'jsonp',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(json) {
                alert("success");
            }
        });
    }
});

But for some reason I am getting an error and warning:

Warning: Resource interpreted as
  Script but transferred with MIME type
  text/html.

Error: Uncaught SyntaxError:
  Unexpected token :

What am I doing wrong?


问:
Can Pyspark Use JDBC to Pass Alter Table
I would like to pass an alter table command to my PostgreSQL database after I load data from a Databricks notebook using pyspark. I know that I can pass a query using spark.read.jdbc but in this case I would like to add a unique constraint once the data has loaded. The purpose is to speed up the data load process into the db by reducing the time to create the unique index.

答:
Spark is a framework for data processing therefore its API mostly developed for read and write operations with data sources. In your case, you have some DDL statements to execute and Spark isn't supposed to perform such operations.

It will better option, to keep DDL operation separate after data processing in spark sql. Here you can add one more PostgreSQL job to perform such operations.


问:
Delete values in line based on column index using shell script
I want to be able to delete the values to the RIGHT(starting from given column index) from the test.txt at the given column index based on a given length, N.

Column index refers to the position when you open the file in the VIM editor in LINUX.

If my test.txt contains 1234 5678, and I call my delete_var function which takes in the column number as 2 to start deleting from and length N as 2 to delete as input, the test.txt would reflect 14 5678 as it deleted the values from column 2 to column 4 as the length to delete was 2.

I have the following code as of now but I am unable to understand what I would put in the sed command.

```<code>delete_var() {

    sed -i -r 's/not sure what goes here' test.txt
}

clmn_index= $1
_N=$2

delete_var "$clmn_index" "$_N"   # call the method with the column index and length to delete
</code>```

```<code>#sample test.txt (before call to fn)
1234 5678
</code>```

```<code>#sample test.txt (after call to fn)
14 5678
</code>```

Can someone guide me?

答:
Looks like:

```<code>cut --complement -c $1-$(($1 + $2 - 1))
</code>```

Should just work and delete columns between $1 and $2 columns behind it.

please provide code how to change test.txt

cut can't modify in place. So either pipe to a temporary file or use sponge.

```<code>tmp=$(mktemp)
cut --complement -c $1-$(($1 + $2 - 1)) test.txt > "$tmp"
mv "$tmp" test.txt
</code>```

Body:
I want to be able to delete the values to the RIGHT(starting from given column index) from the test.txt at the given column index based on a given length, N.

Column index refers to the position when you open the file in the VIM editor in LINUX.

If my test.txt contains 1234 5678, and I call my delete_var function which takes in the column number as 2 to start deleting from and length N as 2 to delete as input, the test.txt would reflect 14 5678 as it deleted the values from column 2 to column 4 as the length to delete was 2.

I have the following code as of now but I am unable to understand what I would put in the sed command.

delete_var() {

    sed -i -r 's/not sure what goes here' test.txt
}

clmn_index= $1
_N=$2

delete_var "$clmn_index" "$_N"   # call the method with the column index and length to delete

#sample test.txt (before call to fn)
1234 5678

#sample test.txt (after call to fn)
14 5678

Can someone guide me?

Body:
Looks like:

cut --complement -c $1-$(($1 + $2 - 1))

Should just work and delete columns between $1 and $2 columns behind it.

please provide code how to change test.txt

cut can't modify in place. So either pipe to a temporary file or use sponge.

tmp=$(mktemp)
cut --complement -c $1-$(($1 + $2 - 1)) test.txt > "$tmp"
mv "$tmp" test.txt


问:
Spring boot path param url encoding issue
I have a spring boot application, where in one of my controller i have a string coming from path parameter. I have my controller like below:

Controller.java

```<code>@GetMapping(value=“/id/{txt}/user”)
public ResponseEntity<MyUser> getUser(@PathVariable String txt) {

}
</code>```

In my requests i will have the txt value as a string with some of the url encoded characters. Below is the example that the request has:

```<code>/id/Siney6jginshbnsu%252Fghshs%253D
</code>```

But when i debug the application the path variable txt  is coming as :

```<code>/id/Siney6jginshbnsu%2Fghshs%3D
</code>```

The problem is i am doing a string comparison for txt using .equals and because of the above encoding/decoding issue, i am seeing the issue.

Is there any way that i can get the url encoded string from request completely as is?

I know i can try to encode the txt which adds %25 but the problem is i might have % in the string which will encode it as %25.  So appreciate if any one can help or suggest a way to fix this.

Thanks in advance.

答:
```<code>@GetMapping("/id/{txt}/user")
public ResponseEntity<MyUser> getUser(HttpServletRequest request, @PathVariable(name="txt") String txt) {
    String urlNotEncoded = request.getRequestURI();
    ...
}
</code>```

In this way urlNotEncoded contains: "/id/Siney6jginshbnsu%252Fghshs%253D/user" and at his point you can create your own function to extract the txt.

Body:
I have a spring boot application, where in one of my controller i have a string coming from path parameter. I have my controller like below:

Controller.java

@GetMapping(value=“/id/{txt}/user”)
public ResponseEntity<MyUser> getUser(@PathVariable String txt) {

}

In my requests i will have the txt value as a string with some of the url encoded characters. Below is the example that the request has:

/id/Siney6jginshbnsu%252Fghshs%253D

But when i debug the application the path variable txt  is coming as :

/id/Siney6jginshbnsu%2Fghshs%3D

The problem is i am doing a string comparison for txt using .equals and because of the above encoding/decoding issue, i am seeing the issue.

Is there any way that i can get the url encoded string from request completely as is?

I know i can try to encode the txt which adds %25 but the problem is i might have % in the string which will encode it as %25.  So appreciate if any one can help or suggest a way to fix this.

Thanks in advance.

Body:
@GetMapping("/id/{txt}/user")
public ResponseEntity<MyUser> getUser(HttpServletRequest request, @PathVariable(name="txt") String txt) {
    String urlNotEncoded = request.getRequestURI();
    ...
}

In this way urlNotEncoded contains: "/id/Siney6jginshbnsu%252Fghshs%253D/user" and at his point you can create your own function to extract the txt.


问:
How do I sort a nested sequence in clojure?
I have a nested map in which the keys are numbers as follows:

```<code>{:18 [Lan Yuhong 165 Happy Lane 345-4533], :33 [Man Yuhong 165 Happy Lane 345-4533], :3 [Tan Yuhong 165 Happy Lane 345-4533], :6 [Jan Yuhong 165 Happy Lane 345-4533], :5 [Han Yuhong 165 Happy Lane 345-4533], :7 [Fan Yuhong 165 Happy Lane 345-4533], :1 [Sue Jones 43 Rose Court Street 345-7867], :9 [John Smith 123 Here Street 456-4567]}
</code>```

which I want to sort on the basis of the first entry (i.e., keys) as follows:

```<code>{:1 [Sue Jones 43 Rose Court Street 345-7867], :3 [Tan Yuhong 165 Happy Lane 345-4533], :5 [Han Yuhong 165 Happy Lane 345-4533], :6 [Jan Yuhong 165 Happy Lane 345-4533], :7 [Fan Yuhong 165 Happy Lane 345-4533], :9 [John Smith 123 Here Street 456-4567], :18 [Lan Yuhong 165 Happy Lane 345-4533], :33 [Man Yuhong 165 Happy Lane 345-4533]}
</code>```

However, the first entry in each list is treated as a string instead of an integer and the sort/sort-by
return a lexographically sorted list as follows. Please note that the mps is stored in the new-map variable in my program.

```<code>(do
    (into (sorted-map) new-map)
)
</code>```

The output is:

```<code>([1 Sue Jones 43 Rose Court Street 345-7867] [18 Lan Yuhong 165 Happy Lane 345-4533] [3 Tan Yuhong 165 Happy Lane 345-4533] [33 Man Yuhong 165 Happy Lane 345-4533] [5 Han Yuhong 165 Happy Lane 345-4533] [6 Jan Yuhong 165 Happy Lane 345-4533] [7 Fan Yuhong 165 Happy Lane 345-4533] [9 John Smith 123 Here Street 456-4567])
</code>```

How can I do this without using any loops? I am trying to avoid the use of loops here. However, a recursive function would be okay.

答:
You almost had it.  Just add:

```<code>(sort-by #(Integer/parseInt (first %)) new-list)
</code>```

full code:

```<code>(ns tst.demo.core
  (:use tupelo.core tupelo.test))

(dotest
  (let [data [["18" "Lan Yuhong" "165" "Happy Lane" "345-4533"]
              ["33" "Man Yuhong" "165" "Happy Lane" "345-4533"]
              ["3" "Tan Yuhong" "165" "Happy Lane" "345-4533"]
              ["6" "Jan Yuhong" "165" "Happy Lane" "345-4533"]
              ["5" "Han Yuhong" "165" "Happy Lane" "345-4533"]
              ["7" "Fan Yuhong" "165" "Happy Lane" "345-4533"]
              ["1" "Sue Jones" "43" "Rose Court Street" "345-7867"]
              ["9" "John Smith" "123 Here Street" "456-4567"]]]
    (spyx-pretty (sort-by #(Integer/parseInt (first %)) data))))
</code>```

with result

```<code>(["1" "Sue Jones" "43" "Rose Court Street" "345-7867"]
 ["3" "Tan Yuhong" "165" "Happy Lane" "345-4533"]
 ["5" "Han Yuhong" "165" "Happy Lane" "345-4533"]
 ["6" "Jan Yuhong" "165" "Happy Lane" "345-4533"]
 ["7" "Fan Yuhong" "165" "Happy Lane" "345-4533"]
 ["9" "John Smith" "123 Here Street" "456-4567"]
 ["18" "Lan Yuhong" "165" "Happy Lane" "345-4533"]
 ["33" "Man Yuhong" "165" "Happy Lane" "345-4533"])
</code>```

Update

For your modified question, see the function group-by

Body:
I have a nested map in which the keys are numbers as follows:

{:18 [Lan Yuhong 165 Happy Lane 345-4533], :33 [Man Yuhong 165 Happy Lane 345-4533], :3 [Tan Yuhong 165 Happy Lane 345-4533], :6 [Jan Yuhong 165 Happy Lane 345-4533], :5 [Han Yuhong 165 Happy Lane 345-4533], :7 [Fan Yuhong 165 Happy Lane 345-4533], :1 [Sue Jones 43 Rose Court Street 345-7867], :9 [John Smith 123 Here Street 456-4567]}

which I want to sort on the basis of the first entry (i.e., keys) as follows:

{:1 [Sue Jones 43 Rose Court Street 345-7867], :3 [Tan Yuhong 165 Happy Lane 345-4533], :5 [Han Yuhong 165 Happy Lane 345-4533], :6 [Jan Yuhong 165 Happy Lane 345-4533], :7 [Fan Yuhong 165 Happy Lane 345-4533], :9 [John Smith 123 Here Street 456-4567], :18 [Lan Yuhong 165 Happy Lane 345-4533], :33 [Man Yuhong 165 Happy Lane 345-4533]}

However, the first entry in each list is treated as a string instead of an integer and the sort/sort-by
return a lexographically sorted list as follows. Please note that the mps is stored in the new-map variable in my program.

(do
    (into (sorted-map) new-map)
)

The output is:

([1 Sue Jones 43 Rose Court Street 345-7867] [18 Lan Yuhong 165 Happy Lane 345-4533] [3 Tan Yuhong 165 Happy Lane 345-4533] [33 Man Yuhong 165 Happy Lane 345-4533] [5 Han Yuhong 165 Happy Lane 345-4533] [6 Jan Yuhong 165 Happy Lane 345-4533] [7 Fan Yuhong 165 Happy Lane 345-4533] [9 John Smith 123 Here Street 456-4567])

How can I do this without using any loops? I am trying to avoid the use of loops here. However, a recursive function would be okay.

Body:
You almost had it.  Just add:

(sort-by #(Integer/parseInt (first %)) new-list)

full code:

(ns tst.demo.core
  (:use tupelo.core tupelo.test))

(dotest
  (let [data [["18" "Lan Yuhong" "165" "Happy Lane" "345-4533"]
              ["33" "Man Yuhong" "165" "Happy Lane" "345-4533"]
              ["3" "Tan Yuhong" "165" "Happy Lane" "345-4533"]
              ["6" "Jan Yuhong" "165" "Happy Lane" "345-4533"]
              ["5" "Han Yuhong" "165" "Happy Lane" "345-4533"]
              ["7" "Fan Yuhong" "165" "Happy Lane" "345-4533"]
              ["1" "Sue Jones" "43" "Rose Court Street" "345-7867"]
              ["9" "John Smith" "123 Here Street" "456-4567"]]]
    (spyx-pretty (sort-by #(Integer/parseInt (first %)) data))))

with result

(["1" "Sue Jones" "43" "Rose Court Street" "345-7867"]
 ["3" "Tan Yuhong" "165" "Happy Lane" "345-4533"]
 ["5" "Han Yuhong" "165" "Happy Lane" "345-4533"]
 ["6" "Jan Yuhong" "165" "Happy Lane" "345-4533"]
 ["7" "Fan Yuhong" "165" "Happy Lane" "345-4533"]
 ["9" "John Smith" "123 Here Street" "456-4567"]
 ["18" "Lan Yuhong" "165" "Happy Lane" "345-4533"]
 ["33" "Man Yuhong" "165" "Happy Lane" "345-4533"])

Update

For your modified question, see the function group-by


问:
Hive on EMR | Number of mappers | Hive pointing to S3 Location
Q1.
I have a hive table 'rates' pointing to S3 location that contains only two files of size 677MB each :
When I am counting total number of records, it is just launching 2 mappers. Why it is so? How can I increase it?

Q2. I have another hive table 'demo_tb1' pointing to S3 location that contains 4000 files of size just 2.7 KB:

When I am counting total number of records, it is just launching 1 mapper. And it is taking too much time to execute.

答:
The number of mappers that get launched for the job is primarily decided by the size of data that you operate on. As you have observed having 4000 files of 2.7 KB each launched only 1 mapper whereas Having 2 files of 677 MB each launched 2 mappers.

How can you increase the number of mappers?

There is one config named as mapreduce.input.fileinputformat.split.maxsize. You need to decrease the value of this config to some smaller number.

How do I know what is the current value of this config?

Simply run this command without specifying a value like this in the hive editor.

```<code>SET mapreduce.input.fileinputformat.split.maxsize;
</code>```

This would give the result in Bytes.

How do I change the value for this config?

Run this command to change it to 16MB for example.

```<code>set mapreduce.input.fileinputformat.split.maxsize=16777216;
</code>```

Note: Please change the value according to the parallelism (number of mappers) that you want to have.

I hope this helps.

Body:
The number of mappers that get launched for the job is primarily decided by the size of data that you operate on. As you have observed having 4000 files of 2.7 KB each launched only 1 mapper whereas Having 2 files of 677 MB each launched 2 mappers.

How can you increase the number of mappers?

There is one config named as mapreduce.input.fileinputformat.split.maxsize. You need to decrease the value of this config to some smaller number.

How do I know what is the current value of this config?

Simply run this command without specifying a value like this in the hive editor.

SET mapreduce.input.fileinputformat.split.maxsize;

This would give the result in Bytes.

How do I change the value for this config?

Run this command to change it to 16MB for example.

set mapreduce.input.fileinputformat.split.maxsize=16777216;

Note: Please change the value according to the parallelism (number of mappers) that you want to have.

I hope this helps.


问:
What is the clean way to call all the previous functions after each move? How to not repeat this code?
I am a newbie and I need help, please. I have been looking for a solution for long time, but cannot go further. I have a chess table with pieces without repeating codes, but I am stuck at a part when the pieces should move to positions I define. Its a chess analysis and all position is defined by me. This code below works, but it is repetitive.

I want the code not repetitive

if I click any button (except the first move), then all the previous button click should fire as well at once. So one move follow another.

if the above things would work, I also want to remove those chess pieces that was defined after a certain button. So if I am at the position of #move4 and I click the button #move3, then I want to move the chess piece back to position #move3

Thank you very much for help and for any advice.

HTML code:

```<code>  <button id="move1" class="move">d4</button>
  <button id="move2" class="move">Nf6</button>
  <button id="move3" class="move">c4</button>
  <button id="move4" class="move">g6</button>
</code>```

jQuery code:

```<code>
$('#move1').on('click', function () {

    pieces[19].y = 4;

    drawBoard();
    drawAllPieces();
});
$('#move2').on('click', function () {

    pieces[11].y = 2;
    pieces[11].x = 5;

    $("#move1").click();
    drawBoard();
    drawAllPieces();
});

$('#move3').on('click', function () {

    pieces[18].y = 4;

    $("#move1").click();
    $("#move2").click();
    drawBoard();
    drawAllPieces();
});

$('#move4').on('click', function () {

    pieces[6].y = 2;

    $("#move1").click();
    $("#move2").click();
    $("#move3").click();
    drawBoard();
    drawAllPieces();
});

</code>```

答:
You can use a loop to make it dynamic - </p>

```<code>for(const i of [1,2,3,4]) {
  $(`#move${i}`').on('click', function () {

    pieces[19].y = 4;

    drawBoard();
    drawAllPieces();
});
</code>```

Body:
I am a newbie and I need help, please. I have been looking for a solution for long time, but cannot go further. I have a chess table with pieces without repeating codes, but I am stuck at a part when the pieces should move to positions I define. Its a chess analysis and all position is defined by me. This code below works, but it is repetitive.

I want the code not repetitive

if I click any button (except the first move), then all the previous button click should fire as well at once. So one move follow another.

if the above things would work, I also want to remove those chess pieces that was defined after a certain button. So if I am at the position of #move4 and I click the button #move3, then I want to move the chess piece back to position #move3

Thank you very much for help and for any advice.

HTML code:

  <button id="move1" class="move">d4</button>
  <button id="move2" class="move">Nf6</button>
  <button id="move3" class="move">c4</button>
  <button id="move4" class="move">g6</button>

jQuery code:

$('#move1').on('click', function () {

    pieces[19].y = 4;

    drawBoard();
    drawAllPieces();
});
$('#move2').on('click', function () {

    pieces[11].y = 2;
    pieces[11].x = 5;

    $("#move1").click();
    drawBoard();
    drawAllPieces();
});

$('#move3').on('click', function () {

    pieces[18].y = 4;

    $("#move1").click();
    $("#move2").click();
    drawBoard();
    drawAllPieces();
});

$('#move4').on('click', function () {

    pieces[6].y = 2;

    $("#move1").click();
    $("#move2").click();
    $("#move3").click();
    drawBoard();
    drawAllPieces();
});

Body:
You can use a loop to make it dynamic -

for(const i of [1,2,3,4]) {
  $(`#move${i}`').on('click', function () {

    pieces[19].y = 4;

    drawBoard();
    drawAllPieces();
});


问:
Why do I get an error when trying to use names_glue in tidyr::pivot_wider?
I get an unused argument error when trying to use the names_glue argument in tidyr::pivot_wider. Here's the example from the help page and my error:

```<code>library(tidyr)
us_rent_income %>%
  pivot_wider(
    names_from = variable,
    names_glue = "{variable}_{.value}",
    values_from = c(estimate, moe)
  )
Error in pivot_wider(., names_from = variable, names_glue = "{variable}_{.value}",  :
  unused argument (names_glue = "{variable}_{.value}")

sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: CentOS Linux 7 (Core)
...
attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] tidyr_1.0.2

loaded via a namespace (and not attached):
 [1] tidyselect_1.0.0 compiler_3.6.1   magrittr_1.5     assertthat_0.2.1
 [5] R6_2.4.1         pillar_1.4.3     glue_1.4.1       dplyr_0.8.5
 [9] tibble_2.1.3     crayon_1.3.4     Rcpp_1.0.4       vctrs_0.2.4
[13] lifecycle_0.2.0  pkgconfig_2.0.3  rlang_0.4.5      purrr_0.3.3
</code>```

I updated tidyr and glue.

I should note that without the names_glue argument, works just fine:

```<code>us_rent_income %>%
  pivot_wider(
    names_from = variable,
    names_sep = ".",
    values_from = c(estimate, moe)
  )
</code>```

答:
According to the changelog, it looks like pivot_wider() gained the names_glue argument in version 1.1.0. You're showing 1.0.2, right? Package ‘tidyr’ version 1.1.0 -also- Hadley's tidyr 1.1.0 blog announcement

This should solve your problem:

```<code>install.packages("tidyr")
library(tidyr)
us_rent_income %>%
  pivot_wider(
    names_from = variable,
    names_glue = "{variable}_{.value}",
    values_from = c(estimate, moe)
  )
</code>```

Note, you may also have to update the vctrs package as well to version 0.3.0.

Body:
I get an unused argument error when trying to use the names_glue argument in tidyr::pivot_wider. Here's the example from the help page and my error:

library(tidyr)
us_rent_income %>%
  pivot_wider(
    names_from = variable,
    names_glue = "{variable}_{.value}",
    values_from = c(estimate, moe)
  )
Error in pivot_wider(., names_from = variable, names_glue = "{variable}_{.value}",  :
  unused argument (names_glue = "{variable}_{.value}")

sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: CentOS Linux 7 (Core)
...
attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] tidyr_1.0.2

loaded via a namespace (and not attached):
 [1] tidyselect_1.0.0 compiler_3.6.1   magrittr_1.5     assertthat_0.2.1
 [5] R6_2.4.1         pillar_1.4.3     glue_1.4.1       dplyr_0.8.5
 [9] tibble_2.1.3     crayon_1.3.4     Rcpp_1.0.4       vctrs_0.2.4
[13] lifecycle_0.2.0  pkgconfig_2.0.3  rlang_0.4.5      purrr_0.3.3

I updated tidyr and glue.

I should note that without the names_glue argument, works just fine:

us_rent_income %>%
  pivot_wider(
    names_from = variable,
    names_sep = ".",
    values_from = c(estimate, moe)
  )

Body:
According to the changelog, it looks like pivot_wider() gained the names_glue argument in version 1.1.0. You're showing 1.0.2, right? Package ‘tidyr’ version 1.1.0 -also- Hadley's tidyr 1.1.0 blog announcement

This should solve your problem:

install.packages("tidyr")
library(tidyr)
us_rent_income %>%
  pivot_wider(
    names_from = variable,
    names_glue = "{variable}_{.value}",
    values_from = c(estimate, moe)
  )

Note, you may also have to update the vctrs package as well to version 0.3.0.


问:
Get all rows data from a table using Cursor in C program
I am using below code in my C program which is connecting to oracle database and getting values from database:

```<code>EXEC SQL DECLARE testCursor CURSOR FOR
 SELECT DISTINCT
    pval1,
    pval2,
  FROM t_table;
</code>```

and then in main function below code:

```<code>EXEC SQL
          FETCH testCursor
          INTO
              :w_val1,
              :w_val2
</code>```

I am getting the value in w_val1 and w_val2 ,but i am just getting a single row data . How to loop it to get all row data.

答:
You need to code a loop in C.

For example:

```<code>EXEC SQL WHENEVER NOT FOUND DO break:
for (;;)
{
    EXEC SQL FETCH testCursor INTO :w_val1, :w_val2;
    ...
}
</code>```

See
19C embedded cursors for details.

Body:
I am using below code in my C program which is connecting to oracle database and getting values from database:

EXEC SQL DECLARE testCursor CURSOR FOR
 SELECT DISTINCT
    pval1,
    pval2,
  FROM t_table;

and then in main function below code:

EXEC SQL
          FETCH testCursor
          INTO
              :w_val1,
              :w_val2

I am getting the value in w_val1 and w_val2 ,but i am just getting a single row data . How to loop it to get all row data.

Body:
You need to code a loop in C.

For example:

EXEC SQL WHENEVER NOT FOUND DO break:
for (;;)
{
    EXEC SQL FETCH testCursor INTO :w_val1, :w_val2;
    ...
}

See
19C embedded cursors for details.


问:
alerting missing metric for many hosts in alertmanager
I have many servers that monitors with Prometheus, every host has the same metrics.

I need an alert rule that alerts when specific metric(such as some_metrics) missing on specific host after 5m.

I checked absent and absent_over_time but these functions do not return the labels of missing metric such as ip or hostname.

Also I should state that I don't want to create a rule for each host.

I have searched about it but I don't find any solution.

Is there any workaround?

答:
In order to get the labels, you need a metric which has all the labels you want. Usually, a good choice is up which also distinguish between a missing metric and an unreachable target.

The rule will alert if up (on a job) is 1 and the UNLESS binary operator will disable the alert if the metric is present on the instance:

```<code>- alert: MissingMetricInFooTarget
  rule: up{job="foo"} == 1 UNLESS ON(instance) some_metrics{job="foo"}
</code>```

Body:
In order to get the labels, you need a metric which has all the labels you want. Usually, a good choice is up which also distinguish between a missing metric and an unreachable target.

The rule will alert if up (on a job) is 1 and the UNLESS binary operator will disable the alert if the metric is present on the instance:

- alert: MissingMetricInFooTarget
  rule: up{job="foo"} == 1 UNLESS ON(instance) some_metrics{job="foo"}


问:
Msg 156, Level 15, State 1, Line 171 Incorrect syntax near the keyword 'FROM'
I have this code which I'm getting this error message "Msg 156, Level 15, State 1, Line 171 Incorrect syntax near the keyword 'FROM'."  I'm new to SQL any help or segetaions will be greatly apprecated.</p>

```<code>-- Import SUBAREA
DROP TABLE VISION_SUBAREA
SELECT *
INTO VISION_SUBAREA
FROM OPENQUERY(TOMSQLVISION,'SELECT *'
FROM [VISION_2020].[REAL_PROP].[SUBAREA]
</code>```

答:
I am guessing you intend:</p>

```<code>SELECT *
INTO VISION_SUBAREA
FROM OPENQUERY(TOMSQLVISION, 'SELECT * FROM [VISION_2020].[REAL_PROP].[SUBAREA]')
</code>```

Body:
I have this code which I'm getting this error message "Msg 156, Level 15, State 1, Line 171 Incorrect syntax near the keyword 'FROM'."  I'm new to SQL any help or segetaions will be greatly apprecated.

-- Import SUBAREA
DROP TABLE VISION_SUBAREA
SELECT *
INTO VISION_SUBAREA
FROM OPENQUERY(TOMSQLVISION,'SELECT *'
FROM [VISION_2020].[REAL_PROP].[SUBAREA]

Body:
I am guessing you intend:

SELECT *
INTO VISION_SUBAREA
FROM OPENQUERY(TOMSQLVISION, 'SELECT * FROM [VISION_2020].[REAL_PROP].[SUBAREA]')


问:
What's fastest way to perform calculation based on values of other columns in a dataframe?
I have df, and I have to apply this formula:

to every row, then add the new series (as a new column).

Right now my code is :

```<code> new_col = deque()
    for i in range(len(df)):
        if i < n:
            new_col.append(0)
        else:
            x = np.log10(np.sum(ATR[i-n:i])/(max(high[i-n:i])-min(low[i-n:i])))
            y = np.log10(n)
            new_col.append(100 * x/y)
    df['new_col'] = pd.DataFrame({"new_col" : new_col})
</code>```

ATR, high, low are obtained from columns of my existing df. But this method is very slow. Is there a faster way to perform the task? Thanks.

答:
Without sample data, I can't test the following, but it should work:</p>

```<code>tmp_df = df.rolling(n).agg({'High':'max', 'Low':'min', 'ATR':'sum'})

df['new_col'] = (100*np.log10(tmp_df['ATR'])) / (tmp_df['High'] - tmp_df['Low']) / np.log10(n)

df['new_col'] = df['new_col'].shift().fillna(0)
</code>```

Body:
I have df, and I have to apply this formula:

to every row, then add the new series (as a new column).

Right now my code is :

 new_col = deque()
    for i in range(len(df)):
        if i < n:
            new_col.append(0)
        else:
            x = np.log10(np.sum(ATR[i-n:i])/(max(high[i-n:i])-min(low[i-n:i])))
            y = np.log10(n)
            new_col.append(100 * x/y)
    df['new_col'] = pd.DataFrame({"new_col" : new_col})

ATR, high, low are obtained from columns of my existing df. But this method is very slow. Is there a faster way to perform the task? Thanks.

Body:
Without sample data, I can't test the following, but it should work:

tmp_df = df.rolling(n).agg({'High':'max', 'Low':'min', 'ATR':'sum'})

df['new_col'] = (100*np.log10(tmp_df['ATR'])) / (tmp_df['High'] - tmp_df['Low']) / np.log10(n)

df['new_col'] = df['new_col'].shift().fillna(0)


问:
How do I trigger a call to dispatch using React Hooks?
I have a save function in a component that makes some calls to an API and changes my local state based on the response. I then want to dispatch an action once AND ONLY ONCE these calls to setState are complete e.g.

```<code>const [myData, setMyData] = useState([{id: 0, name: "Alex"}]);

const save = async () => {

    if (someCondition) {
        let response = await axios.get("/someroute");
        if (response.status === 200) {
            setMyData([...myData, response.data])])
        }
    }

    if (someOtherCondition) {
        let response2 = await axios.get("/someotherroute");
        if (response2.status === 200) {
            setMyData([...myData, response2.data])])
        }
    }

    dispatch(myAction(myData));
}
</code>```

Now I know that useEffect should be the way to go about this. e.g.

```<code>useEffect(() => {
    dispatch(myAction(myData));
}, [myData]);
</code>```

however i'm changing myData at other places in the component, and I only want to dispatch the action once save() has been called and the setMyData calls have finished. I can't think of a condition to check for in useEffect() except maybe adding some kind of flag to myData, like an object saying "Ready to save", but it feels like there should be a simpler way.

Massively appreciate any help on this one!

答:
What do you mean by changing myData at other places? Are you changing myData by fetching it from somewhere? Because if you don't, setMyData will do its job pretty straightforward and fast. So your save function won't need to listen it.

If you change myData as a result of some other fetching and save function should wait it. Then story can little bit complicated. You might like to check middlewares and redux sagas.

I have hard time to understand your scenario and use case; but if state overwriting is your concern during consecutive fetch actions then saga middleware can take care of it.

For example you can create some saga middleware with takeLatest so that it will take last action that dispatched and kill the previous one (not waiting) that ongoing; so you would avoid data overwrite that might occur due side effect. Or similarly you might want to use takeEvery, which will queue every action for setting myData and they will wait each other to end.

check more : https://redux-saga.js.org/

and usage example : https://codesandbox.io/s/385lk3x6v1?file=/src/sagas/index.js

Body:
I have a save function in a component that makes some calls to an API and changes my local state based on the response. I then want to dispatch an action once AND ONLY ONCE these calls to setState are complete e.g.

const [myData, setMyData] = useState([{id: 0, name: "Alex"}]);

const save = async () => {

    if (someCondition) {
        let response = await axios.get("/someroute");
        if (response.status === 200) {
            setMyData([...myData, response.data])])
        }
    }

    if (someOtherCondition) {
        let response2 = await axios.get("/someotherroute");
        if (response2.status === 200) {
            setMyData([...myData, response2.data])])
        }
    }

    dispatch(myAction(myData));
}

Now I know that useEffect should be the way to go about this. e.g.

useEffect(() => {
    dispatch(myAction(myData));
}, [myData]);

however i'm changing myData at other places in the component, and I only want to dispatch the action once save() has been called and the setMyData calls have finished. I can't think of a condition to check for in useEffect() except maybe adding some kind of flag to myData, like an object saying "Ready to save", but it feels like there should be a simpler way.

Massively appreciate any help on this one!


问:
Selenium : Click on a link inside a div
I'm learning selenium and I'm trying a simple thing : click on the first result of a search on wikipedia.

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

PATH = "chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://en.wikipedia.org")

# Input in the search bar
search = driver.find_element_by_id("searchInput")
search.send_keys("python", Keys.RETURN)

wait = WebDriverWait(driver, 10)
first_result = wait.until(
    EC.presence_of_element_located((By.CLASS_NAME, "mw-search-result-heading"))
)

first_result.click()
</code>```

So i'm able to select the heading of the first result. But I can't click on it.
I think it's because I'm clicking on the
 containing the link, rather than the actual link. Here is a snippet of the HTML :

How can I target the actual  link, without it having any class name, id or name ?

答:
Since you are using Selenium you might want to use XPath. This has saved me tons of times! simply right click on the desired tag, and click copy xpath.
then just click on the object using a similar syntax as in here:

```<code>elem = driver.find_element_by_xpath('//some_xpath')
elem.click()
</code>```

Title: Selenium : Click on a link inside a div

Body:
I'm learning selenium and I'm trying a simple thing : click on the first result of a search on wikipedia.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

PATH = "chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://en.wikipedia.org")

# Input in the search bar
search = driver.find_element_by_id("searchInput")
search.send_keys("python", Keys.RETURN)

wait = WebDriverWait(driver, 10)
first_result = wait.until(
    EC.presence_of_element_located((By.CLASS_NAME, "mw-search-result-heading"))
)

first_result.click()

So i'm able to select the heading of the first result. But I can't click on it.
I think it's because I'm clicking on the
 containing the link, rather than the actual link. Here is a snippet of the HTML :

How can I target the actual  link, without it having any class name, id or name ?

Body:
Since you are using Selenium you might want to use XPath. This has saved me tons of times! simply right click on the desired tag, and click copy xpath.
then just click on the object using a similar syntax as in here:

elem = driver.find_element_by_xpath('//some_xpath')
elem.click()


问:
Android Studio Javadoc won't generate because "Selected scope contain no Java classes"
I am trying to generate the JavaDoc for the Activity class source code in Android Studio 3.6.3.  The file is open in the editor, and I use "Tools | Generate JavaDoc".

When I click OK, it fails with the message "Error running 'Javadoc': Selected scope contain no Java classes".  I also tried the "Custom Scope" option with "Current File" choice, but same results.

Can someone help why can I not generate the JavaDoc for this file?

答:
The file is too large to paste here, it is 410832 characters, only 30000 allowed.

I could paste some of it if that would help.


问:
windows service & updating c# console app
I have a windows service that executes a console app every hour and it's running with no problems. I didn't set this up though, and I'm not familiar with windows services at all.

Today I had to update the console app, so I presumed that if I just copied the exe file back into the folder were it was called from the windows service after I modified it it would be fine. But it looks like it stopped working.

I ran the console app mannually from the command prompt and it works fine though.

Any ideas on why this could have stopped working?

Thanks

答:
first try to stop/start your service, then
try to uninstall and install your service again

you can do the first thing in administrative tools/services
install/uninstall with  installUtil


问:
Langdetect Issue With pyinstaller
I'm trying to compile my code in oython that uses the library langdetect into a .app with pyinstaller.

as answered in this question : https://github.com/pyinstaller/pyinstaller/issues/2680

I modified the .spec file to include this :

```<code>a = Analysis(
# your other stuff here...
datas=[
    ('langdetect/utils', 'langdetect/utils'),  # for messages.properties file
    ('langdetect/profiles', 'langdetect/profiles'), # don't forget if you load langdetect as a submodule of your app, change the second string to the relative path from your parent module. The first argument is the relative path inside the pyinstaller bundle.
      ]
# the rest of your analysis spec...
)
</code>```

But pyinstaller stil does not find utils. I think that I didn't enter the right path in the tuple, but I don't know what I'm supposed to do (the program is supposed to already 'be' in the libraries directory, so shouldn't it work in theory ?)

I used anaconda anaconda to install langdetect. The problem is that I'm not using my laptop to build the .app file, so I would refer if it's a generic path rather than specific.

thanks !

答: I had the same issue. The issue was with the langdetect library. I used textblob library instead  and it worked perfectly.</p>

Title: Langdetect Issue With pyinstaller

Body:
I'm trying to compile my code in oython that uses the library langdetect into a .app with pyinstaller.

as answered in this question : https://github.com/pyinstaller/pyinstaller/issues/2680

I modified the .spec file to include this :

a = Analysis(
# your other stuff here...
datas=[
    ('langdetect/utils', 'langdetect/utils'),  # for messages.properties file
    ('langdetect/profiles', 'langdetect/profiles'), # don't forget if you load langdetect as a submodule of your app, change the second string to the relative path from your parent module. The first argument is the relative path inside the pyinstaller bundle.
      ]
# the rest of your analysis spec...
)

But pyinstaller stil does not find utils. I think that I didn't enter the right path in the tuple, but I don't know what I'm supposed to do (the program is supposed to already 'be' in the libraries directory, so shouldn't it work in theory ?)

I used anaconda anaconda to install langdetect. The problem is that I'm not using my laptop to build the .app file, so I would refer if it's a generic path rather than specific.

thanks !


问:
error while putting correct git commit commands
Can you outline why I am receiving this message in git commit despite correct codes. I have tried all the alternatives and even restarting it again but no positive responses.
Here's the error https://i.stack.imgur.com/cr9zd.png</p>

答: There is no such git command as commit-m. Maybe you got that from someone who had it installed as a local command alias?


问:
Why is makefile not calling this function?
I am trying to compile all the files with a .c extension into an object folder and then create an executable. However, the Makefile I am using is not registering the source files at all. Instead it is going ahead and calling the command to create the executable with object files that do not exist.

Here is the Makefile:

```<code>CC = clang

SOURCE_DIR = src
OBJECT_DIR = objects
EXECUTABLE = main

SOURCES = $(wildcard $(SOURCE_DIR)/*.c)
OBJECTS = $(patsubst $(SOURCE_DIR)/%.c, $(OBJECT_DIR)/%.o, $(SOURCES))

all: $(OBJECTS)
    $(CC) $^ -o $(EXECUTABLE)

clean:
    rm objects/*.o main

$(OBJECT_DIR)/%.o: $(SOURCE_DIR)/%.c
    $(CC) -c $< -o $@

.PHONY: all $(OBJECTS)
</code>```

And here is the output:

```<code>me@hostname:~/parent_dir$ make
clang objects/main.o objects/test.o -o main
clang: error: no such file or directory: 'objects/main.o'
clang: error: no such file or directory: 'objects/test.o'
clang: error: no input files
make: *** [Makefile:11: all] Error 1
</code>```

And here is the file structure:

```<code>parent_dir:
   \ objects (empty):
   \ src:
      - main.c
      - test.c
   - Makefile
</code>```

答:
Replace:

```<code>.PHONY: all $(OBJECTS)
</code>```

with:

```<code>.PHONY: all
</code>```

The object files are not phony targets
and telling make they are phony tells it that no such files have to exist.

Body:
I am trying to compile all the files with a .c extension into an object folder and then create an executable. However, the Makefile I am using is not registering the source files at all. Instead it is going ahead and calling the command to create the executable with object files that do not exist.

Here is the Makefile:

CC = clang

SOURCE_DIR = src
OBJECT_DIR = objects
EXECUTABLE = main

SOURCES = $(wildcard $(SOURCE_DIR)/*.c)
OBJECTS = $(patsubst $(SOURCE_DIR)/%.c, $(OBJECT_DIR)/%.o, $(SOURCES))

all: $(OBJECTS)
    $(CC) $^ -o $(EXECUTABLE)

clean:
    rm objects/*.o main

$(OBJECT_DIR)/%.o: $(SOURCE_DIR)/%.c
    $(CC) -c $< -o $@

.PHONY: all $(OBJECTS)

And here is the output:

me@hostname:~/parent_dir$ make
clang objects/main.o objects/test.o -o main
clang: error: no such file or directory: 'objects/main.o'
clang: error: no such file or directory: 'objects/test.o'
clang: error: no input files
make: *** [Makefile:11: all] Error 1

And here is the file structure:

parent_dir:
   \ objects (empty):
   \ src:
      - main.c
      - test.c
   - Makefile

Body:
Replace:

.PHONY: all $(OBJECTS)

with:

.PHONY: all

The object files are not phony targets
and telling make they are phony tells it that no such files have to exist.


问:
Disable spell checking on IntelliJ IDEA
I'm trying to disable spell checking in MacOS's IntelliJ IDEA version 8.1.

How can I disable it?

答:
update for 2020

```<code>File >> Settings >> Editor >> Inspections >> Proofreading (uncheck all)
</code>```

Title: Disable spell checking on IntelliJ IDEA

Body:
update for 2020

File >> Settings >> Editor >> Inspections >> Proofreading (uncheck all)


问:
Issue with sending mails from grafana
I am trying to send mails from grafana but getting below error.

t=2017-12-22T07:24:46+0000 lvl=eror msg="Failed to send alert notifications" logger=context userId=1 orgId=1 uname=admin error="534 5.7.14  Please log in via your web browser and\n5.7.14 then try again.\n5.7.14  Learn more at\n5.7.14  https://support.google.com/mail/answer/78754 j27sm22594347eda.59 - gsmtp"

Can anyone help?

答:
I initially struggled a lot with this issue.
The solution is simple.
Enabling 'allow less secure apps to access your account' solves the problem.
Also make sure to not have 2 factor authentication.</p>

Title: Issue with sending mails from grafana


问:
How to save the state of a button in AndroidStudio?
I am new at programing in Java and I am taking a course of Android application. I am building a button inside an activity. But when I exit the activity, the button changes to it's original state. I know I am not doing anything to save its state, but how do I do it?

Here is the xml file (only the button part):

```<code><Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Catch"
    android:id="@+id/button"
    android:onClick="toggleCatch" />
</code>```

And here is toggleCatch:

```<code>private boolean isCaught = false;
@SuppressLint("SetTextI18n")
    public void toggleCatch(View view) {
        Button button = findViewById(R.id.button);

        if (isCaught) {
            button.setText("Catch");
            isCaught = false;
        } else {
            button.setText("Release");
            isCaught = true;
        }
    }
</code>```

What could I do to make it work?

答:
You need to save button state in persistent storage; there are several types of persistent storage that Android supports, like SharedPreference, DataBase, internal/external storage File... The most appropriate for your question is the SharedPreference as it stores small data.

To achieve that in your code sample

```<code>public static final String PREFS_NAME = "PREFS_NAME";
public static final String BUTTON_STATUS = "status";

private boolean isCaught = false;
@SuppressLint("SetTextI18n")
public void toggleCatch(View view) {
    Button button = findViewById(R.id.button);

    if (isCaught) {
        button.setText("Catch");
        isCaught = false;
    } else {
        button.setText("Release");
        isCaught = true;
    }

    SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean(BUTTON_STATUS, isCaught);
    editor.apply();

}
</code>```

And you need to retrieve the value again from the shared preference when the app is launched, so in your activity onCreate() method:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    Button button = findViewById(R.id.button);
    SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    isCaught = prefs.getBoolean(BUTTON_STATUS, false);

    if (isCaught) {
        button.setText("Release");
    } else {
        button.setText("Catch");
    }

}
</code>```

Body:
I am new at programing in Java and I am taking a course of Android application. I am building a button inside an activity. But when I exit the activity, the button changes to it's original state. I know I am not doing anything to save its state, but how do I do it?

Here is the xml file (only the button part):

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Catch"
    android:id="@+id/button"
    android:onClick="toggleCatch" />

And here is toggleCatch:

private boolean isCaught = false;
@SuppressLint("SetTextI18n")
    public void toggleCatch(View view) {
        Button button = findViewById(R.id.button);

        if (isCaught) {
            button.setText("Catch");
            isCaught = false;
        } else {
            button.setText("Release");
            isCaught = true;
        }
    }

What could I do to make it work?

Body:
You need to save button state in persistent storage; there are several types of persistent storage that Android supports, like SharedPreference, DataBase, internal/external storage File... The most appropriate for your question is the SharedPreference as it stores small data.

To achieve that in your code sample

public static final String PREFS_NAME = "PREFS_NAME";
public static final String BUTTON_STATUS = "status";

private boolean isCaught = false;
@SuppressLint("SetTextI18n")
public void toggleCatch(View view) {
    Button button = findViewById(R.id.button);

    if (isCaught) {
        button.setText("Catch");
        isCaught = false;
    } else {
        button.setText("Release");
        isCaught = true;
    }

    SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean(BUTTON_STATUS, isCaught);
    editor.apply();

}

And you need to retrieve the value again from the shared preference when the app is launched, so in your activity onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    Button button = findViewById(R.id.button);
    SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    isCaught = prefs.getBoolean(BUTTON_STATUS, false);

    if (isCaught) {
        button.setText("Release");
    } else {
        button.setText("Catch");
    }

}


问:
RepositoryRestResource resources started returning 404 errors after running for a while
I have a workaround for this problem, but I wanted to post this in case anybody else ran into this.

We have a Spring boot web application that is being packaged as a war file and deployed to Tomcat. It has several PagingAndSortingRepository classes annotated with @RepositoryRestResource that serve rest requests, and a few other classes annotated with @RestController. The RestController classes do make some calls to the repository classes.

Everything has been working fine through the 2.2.5.RELEASE version of spring-boot. We ran into a problem after upgrading to 2.2.6.RELEASE. Everything was fine (meaning both types of rest resources could be accessed) but after running for about 10-15 minutes, everything that was accessed through a RepositoryRestResource started returning 404 errors. No error messages in any logs, they just started returning 404 errors when they had been working fine previously. The RestControllers kept working fine the whole time. After reverting back to the 2.2.5.RELEASE, we had no more problems.

Since we are using dependencyManagement, I don't think it was a version mismatch issue. None of the spring artifacts in the pom.xml file have versions. Here is what is in the pom:

```<code><dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.2.5.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
</code>```

答:
This was a known issue with 2.2.6.
Specifically:
https://jira.spring.io/browse/DATAREST-1502
Which had side effect of causing 404 errors after a number of hours(observed by others and reported as https://jira.spring.io/browse/DATAREST-1518)

In short Upgrading to 2.2.7+ should resolve this particular issue.

Body:
I have a workaround for this problem, but I wanted to post this in case anybody else ran into this.

We have a Spring boot web application that is being packaged as a war file and deployed to Tomcat. It has several PagingAndSortingRepository classes annotated with @RepositoryRestResource that serve rest requests, and a few other classes annotated with @RestController. The RestController classes do make some calls to the repository classes.

Everything has been working fine through the 2.2.5.RELEASE version of spring-boot. We ran into a problem after upgrading to 2.2.6.RELEASE. Everything was fine (meaning both types of rest resources could be accessed) but after running for about 10-15 minutes, everything that was accessed through a RepositoryRestResource started returning 404 errors. No error messages in any logs, they just started returning 404 errors when they had been working fine previously. The RestControllers kept working fine the whole time. After reverting back to the 2.2.5.RELEASE, we had no more problems.

Since we are using dependencyManagement, I don't think it was a version mismatch issue. None of the spring artifacts in the pom.xml file have versions. Here is what is in the pom:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.2.5.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>


问:
OutOfMemory error while joining large images
I am joining two images using the code below but it throws an OutOfMemory error my images are around 1MB each.

```<code>private Bitmap overlayMark(String first, String second)
{
    Bitmap bmp1, bmp2;
    bmp1 = BitmapFactory.decodeFile(first);
    bmp2 = BitmapFactory.decodeFile(second);
    if (bmp1 == null || bmp2 == null)
        return bmp1;

    int height = bmp1.getHeight();
    if (height < bmp2.getHeight())
        height = bmp2.getHeight();

    Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth() + bmp2.getWidth(), height,
            Bitmap.Config.ARGB_8888);// Out of memory
    Canvas canvas = new Canvas(bmOverlay);
    canvas.drawBitmap(bmp1, 0, 0, null);
    canvas.drawBitmap(bmp2, bmp1.getWidth(), 0, null);
    bmp1.recycle();
    bmp2.recycle();
    return bmOverlay;
}
</code>```

Update: I tried below two answers but it still not allwoing me to create bitmap of such big size the problem is that the resultant bitmap is too large in size around 2400x3200 so its going out of memory.

How can I join large images without running out of memory?

答:
It's not necessary that the space taken by in-memory representation of bitmaps correspond closely with file size. So even if you have 3mb memory available to jvm, you might still get OutOfMemoryException.

Your code is creating three in-memory images simultaneously. If you can find the size of both images without reading the complete files, you can modify the code in a way to have only one of the source images in memory at a time. If even that doesn't prove to be sufficient you might need some sort of streaming method of reading the images.

Body:
I am joining two images using the code below but it throws an OutOfMemory error my images are around 1MB each.

private Bitmap overlayMark(String first, String second)
{
    Bitmap bmp1, bmp2;
    bmp1 = BitmapFactory.decodeFile(first);
    bmp2 = BitmapFactory.decodeFile(second);
    if (bmp1 == null || bmp2 == null)
        return bmp1;

    int height = bmp1.getHeight();
    if (height < bmp2.getHeight())
        height = bmp2.getHeight();

    Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth() + bmp2.getWidth(), height,
            Bitmap.Config.ARGB_8888);// Out of memory
    Canvas canvas = new Canvas(bmOverlay);
    canvas.drawBitmap(bmp1, 0, 0, null);
    canvas.drawBitmap(bmp2, bmp1.getWidth(), 0, null);
    bmp1.recycle();
    bmp2.recycle();
    return bmOverlay;
}

Update: I tried below two answers but it still not allwoing me to create bitmap of such big size the problem is that the resultant bitmap is too large in size around 2400x3200 so its going out of memory.

How can I join large images without running out of memory?


问:
GroupBy of huge spark dataframe
I have a dataframe with thousands of millions of rows with columns 'A', 'B' and others. The df is saved in parquet format partitioned by 'A'. If I run:

```<code>df.groupBy('A').agg(agg_functions)
</code>```

It works, but if I run:

```<code>df.groupBy('B').agg(agg_functions)
</code>```

The process fails because of lack of memory (it tries to bring all data to a executor).
I know there is a relation between A, B: the same value for B can only appear in two consecutive partitions of A. Is there any way to use this fact to perform the operation efficiently?

答:
One approach could be to group by two columns and aggregate twice. For example, If i had three columns (country, city and orders), assume in this case your column 'A' is country and City is 'B'. Now if i want to get all the orders grouped by country, I could do,

```<code>df.groupBy("country").agg(count)
</code>```

Some partitions can be huge like your case, so i could rather do something like,

```<code>intermediateResults = df.groupBy("country","city").agg(count)
intermediateResults.groupBy("country").agg(sum)
</code>```

You might not always have this relation between columns, in which case you could split it up across time or id's.

Title: GroupBy of huge spark dataframe

Body:
I have a dataframe with thousands of millions of rows with columns 'A', 'B' and others. The df is saved in parquet format partitioned by 'A'. If I run:

df.groupBy('A').agg(agg_functions)

It works, but if I run:

df.groupBy('B').agg(agg_functions)

The process fails because of lack of memory (it tries to bring all data to a executor).
I know there is a relation between A, B: the same value for B can only appear in two consecutive partitions of A. Is there any way to use this fact to perform the operation efficiently?

Body:
One approach could be to group by two columns and aggregate twice. For example, If i had three columns (country, city and orders), assume in this case your column 'A' is country and City is 'B'. Now if i want to get all the orders grouped by country, I could do,

df.groupBy("country").agg(count)

Some partitions can be huge like your case, so i could rather do something like,

intermediateResults = df.groupBy("country","city").agg(count)
intermediateResults.groupBy("country").agg(sum)

You might not always have this relation between columns, in which case you could split it up across time or id's.


问:
Why cookie is sent in HTTP post when xhr.withCredentials = true;
If you run below JS code, it will make HTTP POST request to server with cookies, but POST response is blocked by browser because Access-Control-Allow-Credentials: true header wasn't present in response from yahoo.com.

My question is, why browser allow POST request with cookie and doesn't do a preflight, as xhr.withCredentials=true, sends the cookie?

Damage to server is already done, even if browser doesn't allow JS to access the POST request's response?

This looks like CSRF vulnerability.

Am I missing anything here?

Update: Is this the case where CSRF token is required?

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                console.log(xhr.responseText);
            } else {
                console.log("Request was unsuccessful: " + xhr.status);
            }
        }
    };
    xhr.withCredentials = true;
    xhr.open("post", "https://yahoo.com/example", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.send("a=5");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<body>

<p>Hello</p>

</body>
</html></code>```

答:
It's always been possible to make a POST request with application/x-www-form-urlencoded data to any URL by simply submitting a form.

XHR and co don't change that.

There's no point in adding extra security there because that horse has already bolted.

So, yes, there is a risk of CSRF, but not a new risk. Sites need to take the usual defenses against CSRF.

Body:
If you run below JS code, it will make HTTP POST request to server with cookies, but POST response is blocked by browser because Access-Control-Allow-Credentials: true header wasn't present in response from yahoo.com.

My question is, why browser allow POST request with cookie and doesn't do a preflight, as xhr.withCredentials=true, sends the cookie?

Damage to server is already done, even if browser doesn't allow JS to access the POST request's response?

This looks like CSRF vulnerability.

Am I missing anything here?

Update: Is this the case where CSRF token is required?

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                console.log(xhr.responseText);
            } else {
                console.log("Request was unsuccessful: " + xhr.status);
            }
        }
    };
    xhr.withCredentials = true;
    xhr.open("post", "https://yahoo.com/example", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.send("a=5");

<!DOCTYPE html>

Hello