问:
How to use ZeroLog from F#?
I could not find any details on this.

Here is the code:

```<code>// external
open ZeroLog
open ZeroLog.Appenders
open ZeroLog.Config
open System.Collections.Generic
// internal

module Logging =

  let logManager =
    let appender = new ConsoleAppender()
    let defaultAppenderConfig = DefaultAppenderConfig()
    defaultAppenderConfig.PrefixPattern <- "[%level] @ %time - %logger :: "
    appender.Configure(defaultAppenderConfig)
    let appenders =  new List<IAppender>(capacity=1)
    appenders.Add(appender)
    BasicConfigurator.Configure(appenders)

  let getLogger (name:string) =
    LogManager.GetLogger(name)

  let testLogging () =
    let logger = getLogger "Main"
    logger.Info("test")
</code>```

It compiles but when I try to use testLogging it does not print anything. Maybe I need to configure some additional details but I am not sure what.

答:
Static initializer for Logging.fs file is not being called (12.5.1 Execution of Static Initializers) because it's not an entry point file and you are not accessing any value which has observable initialization (yes, that's a vague definition). The point is - if static initializer wasn't called, then logManager value wasn't initialized. Which means in your case that all logger configuration code wasn't executed.

The simplest way to make sure logger is initialized is to move initialization logic to function and call it explicitely:

```<code>let init () =
    let appender = new ConsoleAppender()
    let defaultAppenderConfig = DefaultAppenderConfig()
    defaultAppenderConfig.PrefixPattern <- "[%level] @ %time - %logger :: "
    appender.Configure(defaultAppenderConfig)
    let appenders = new List<IAppender>(capacity=1)
    appenders.Add(appender)
    BasicConfigurator.Configure(appenders) |> ignore
</code>```

Make sure you call it at the top of Main before you use logging

```<code>Logging.init()
Logging.testLogging()
</code>```

Note that even direct access to logManager value will trigger static initializer only in Debug mode (because of unused values optimizations in Release mode):

```<code>let _ = Logging.logManager // works in Debug only
Logging.testLogging()
</code>```

Title: How to use ZeroLog from F#?

Body:
I could not find any details on this.

Here is the code:

// external
open ZeroLog
open ZeroLog.Appenders
open ZeroLog.Config
open System.Collections.Generic
// internal

module Logging =

  let logManager =
    let appender = new ConsoleAppender()
    let defaultAppenderConfig = DefaultAppenderConfig()
    defaultAppenderConfig.PrefixPattern <- "[%level] @ %time - %logger :: "
    appender.Configure(defaultAppenderConfig)
    let appenders =  new List<IAppender>(capacity=1)
    appenders.Add(appender)
    BasicConfigurator.Configure(appenders)

  let getLogger (name:string) =
    LogManager.GetLogger(name)

  let testLogging () =
    let logger = getLogger "Main"
    logger.Info("test")

It compiles but when I try to use testLogging it does not print anything. Maybe I need to configure some additional details but I am not sure what.

Body:
Static initializer for Logging.fs file is not being called (12.5.1 Execution of Static Initializers) because it's not an entry point file and you are not accessing any value which has observable initialization (yes, that's a vague definition). The point is - if static initializer wasn't called, then logManager value wasn't initialized. Which means in your case that all logger configuration code wasn't executed.

The simplest way to make sure logger is initialized is to move initialization logic to function and call it explicitely:

let init () =
    let appender = new ConsoleAppender()
    let defaultAppenderConfig = DefaultAppenderConfig()
    defaultAppenderConfig.PrefixPattern <- "[%level] @ %time - %logger :: "
    appender.Configure(defaultAppenderConfig)
    let appenders = new List<IAppender>(capacity=1)
    appenders.Add(appender)
    BasicConfigurator.Configure(appenders) |> ignore

Make sure you call it at the top of Main before you use logging

Logging.init()
Logging.testLogging()

Note that even direct access to logManager value will trigger static initializer only in Debug mode (because of unused values optimizations in Release mode):

let _ = Logging.logManager // works in Debug only
Logging.testLogging()


来源: stackexchange

问:
Is it possible how many people visited my github project
I am created one website and upload github. How to check the how many people visited in my website </p>

答:
You may use Hits, which is a simple & easy way to see how many people have viewed your GitHub Repository.

You just type your github username & repository in Hits, and get a markdown snippet to insert in your README.md repository. The result is:

From Hits README.md:

While GitHub has a basic "traffic" tab which displays page view stats, GitHub only records the data for the past 14 days and then it gets reset. The data is not relayed to the "owner" in "real time" and you would need to use the API and "poll" for data ... Manually checking who has viewed a project is exceptionally tedious when you have more than a handful of projects.

ContentLicense: CC BY-SA 4.0


问:
Is there any way to configure Struts to bind null instead of empty String?
When user decides to leave the field in the form empty the Apache Struts binds empty String as value for properties in the ActionForm. Is there any way to modify the behavior globally and opt for null instead of empty String?

I know that Spring MVC does exactly the same, but there is also StringTrimmerEditor that can be registered as property editor to trim strings to null.

答:
A possible solution - one that will allow a single conversion entry point for all your String fields - would be to register a custom convertor, but not with Struts but with BeanUtils.

For mapping request parameters to form properties, Struts makes use of the populate method of its RequestUtils class. This class in turn uses a BeanUtils implementation do do its work.

A simplistic flow would be something of the likes of Struts' RequestUtils > BeanUtils > BeanUtilsBean > ConvertUtils > ConvertUtilsBean > Converter.

The interesting thing is that there is also a StringConverter which converts from String to... aaaaaa... String!

The ConvertUtils class has a register method which you can use to register convertors, overwriting the existing ones. This means you could write yourself the custom String convertor which returns null for empty strings and then you could wait for your Struts application to load completely so that you have no surprises (i.e. make sure your converter is the last registered for type String).

After the application loads, you step in and overwrite the default String convertor with your own implementation. For example, you could do that using a ServletContextListener and call the ConvertUtils.register(...) in the contextInitialized method.

You then configure the listener in web.xml and you should be good to go.

ContentLicense: CC BY-SA 3.0


问:
How to move in the 2d/3d array using pointers in C?
Today I was coding a little bit for my studies. And I have a problem with 2d (and also 3d arrays in C). When I allocate memory for an array or make a static array for example:

```<code>//dynamic
int *a=(int *)malloc(5*5*sizeof(int));
     //OR
//static
int ar[5][5] = {0};
int *a= ar[0][0];
</code>```

I don't know how to properly move in this matrix using pointers. I tried a for loop looking like this to print its elements:

```<code>for(int i=0;i<5;i++){
   for(int j=0;j<5;j++){
     printf("%d ",*((a+i)+j));
   }
   puts("\n");
 }
</code>```

But it doesn't work. When i inputed to the array first 25 int numbers starting with 1,like this:

```<code>1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
</code>```

I got printf output like:

```<code>1 6 11 16 21
6 11 16 21 22
11 16 21 22 23
16 21 22 23 24
21 22 23 24 25
</code>```

The output includes only first column and last row.

I saw a tutorial on youtube how to properly do this, but somehow i missunderstood this topic. Can somebody show me how to do this using pointers, please?

Thanks for your time!

答:
You need to multiply the row index by the row length to get to that row.</p>

```<code> printf("%d ",*((a+i*5)+j));
</code>```

Body:
Today I was coding a little bit for my studies. And I have a problem with 2d (and also 3d arrays in C). When I allocate memory for an array or make a static array for example:

//dynamic
int *a=(int *)malloc(5*5*sizeof(int));
     //OR
//static
int ar[5][5] = {0};
int *a= ar[0][0];

I don't know how to properly move in this matrix using pointers. I tried a for loop looking like this to print its elements:

for(int i=0;i<5;i++){
   for(int j=0;j<5;j++){
     printf("%d ",*((a+i)+j));
   }
   puts("\n");
 }

But it doesn't work. When i inputed to the array first 25 int numbers starting with 1,like this:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

I got printf output like:

1 6 11 16 21
6 11 16 21 22
11 16 21 22 23
16 21 22 23 24
21 22 23 24 25

The output includes only first column and last row.

I saw a tutorial on youtube how to properly do this, but somehow i missunderstood this topic. Can somebody show me how to do this using pointers, please?

Thanks for your time!

Body:
You need to multiply the row index by the row length to get to that row.

 printf("%d ",*((a+i*5)+j));


问:
How to get the date time picker and convert it into the server format (toISOString)
I am trying to get the datetime picker, convert it in order to send it to the server.

but it does not work. Here is what I tried out.

```<code><html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
            <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

        <!-- Bootstrap Date-Picker Plugin -->
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>

        <title> date picker</title>
    </head>
    <body>
        <h1> date picker </h1>

        <div class="input-append date form_datetime">
            <input size="16" type="text" value="" readonly id="date_time">
            <span class="add-on"><i class="icon-th"></i></span>
        </div>

        <script type="text/javascript">
            $(".form_datetime").datetimepicker({
                format: "DD MM yyyy - hh:ii",
                autoclose: true,
                todayBtn: true,
                pickerPosition: "bottom-left"
            });

            var a_date = document.getElementById("date_time");;
            var ser_date = new Date(a_date).toISOString();

        </script>

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

I get this error:

TypeError: undefined is not a function (near '...$(".form_datetime").datetimepicker...')

How can I handle that?

答:
use datepicker . try this</p>

```<code><html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
            <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

        <!-- Bootstrap Date-Picker Plugin -->
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>

        <title> date picker</title>
    </head>
    <body>
        <h1> date picker </h1>

        <div class="input-append date form_datetime">
            <input size="16" type="text" value="" readonly id="date_time">
            <span class="add-on"><i class="icon-th"></i></span>
        </div>
        <div> <input type="button" value="Click me" onclick="ServerDate()"></div>

        <script type="text/javascript">
            $(".form_datetime").datepicker({
                format:'mm/dd/yyyy',
                autoclose: true,
                todayBtn: true,
                pickerPosition: "bottom-left"
            });

            function ServerDate() {
            console.log($('#date_time').val());
            var ser_date = new Date($('#date_time').val()).toISOString();
            alert(ser_date);

                   }

        </script>

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

Body:
I am trying to get the datetime picker, convert it in order to send it to the server.

but it does not work. Here is what I tried out.

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>

        <title> date picker</title>

 date picker

            <input size="16" type="text" value="" readonly id="date_time">

I get this error:

TypeError: undefined is not a function (near '...$(".form_datetime").datetimepicker...')

How can I handle that?

Body:
use datepicker . try this

<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
            <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

        <!-- Bootstrap Date-Picker Plugin -->
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>

        <title> date picker</title>
    </head>
    <body>
        <h1> date picker </h1>

        <div class="input-append date form_datetime">
            <input size="16" type="text" value="" readonly id="date_time">
            <span class="add-on"><i class="icon-th"></i></span>
        </div>
        <div> <input type="button" value="Click me" onclick="ServerDate()"></div>

        <script type="text/javascript">
            $(".form_datetime").datepicker({
                format:'mm/dd/yyyy',
                autoclose: true,
                todayBtn: true,
                pickerPosition: "bottom-left"
            });

            function ServerDate() {
            console.log($('#date_time').val());
            var ser_date = new Date($('#date_time').val()).toISOString();
            alert(ser_date);

                   }

        </script>

    </body>
</html>


问:
Alert button to dismiss Alert and go back to previous View Controller
I'm kind of new to Swift and I can't figure this out. I have an Alert that should show on a successful URL request. After a user clicks an Ok button on the alert, I need the alert dismissed and I need the presented controller to go back in the navigation stack to the previous view controller. I don't get any errors but nothing happens. If I move the entire code for the Alert inside the CustomClass, then it works fine. I assume I am not referencing the CustomClass the right way. Any help would be greatly appreciated!

```<code> struct Alert {
    static func CustomAlert(vc: UIViewController, title: String, message: String){

        var title = "Title...!"
        var message = "Message..."
        let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        myAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (actin) in
            myAlert.dismiss(animated: true, completion: nil)
            let vc = CustomClass()
            vc.GoBackToPreviousVC()
        }))
         vc.present(myAlert, animated: true, completion: nil)
    }
 }

 class: CustomClass: UIViewController {

    func GoBackToPreviousVC(){
        navigationController?popViewController(animated: true)
    }

    function Download(){

      code for URLRequest...

      DispatchQueue.main.async {
        if (self.response.Status == "200"){
            Alert.CustomAlert(vc: self, title: "", message: "")
        }

      }

    }
}
</code>```

答: Looks like each time you call your function - you create new View Controller. That why nothing happens. Try to use closure, implement alert function as extension for UIViewController or pass it as function input.Choose what most fits your needs.</p>

Body:
I'm kind of new to Swift and I can't figure this out. I have an Alert that should show on a successful URL request. After a user clicks an Ok button on the alert, I need the alert dismissed and I need the presented controller to go back in the navigation stack to the previous view controller. I don't get any errors but nothing happens. If I move the entire code for the Alert inside the CustomClass, then it works fine. I assume I am not referencing the CustomClass the right way. Any help would be greatly appreciated!

 struct Alert {
    static func CustomAlert(vc: UIViewController, title: String, message: String){

        var title = "Title...!"
        var message = "Message..."
        let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        myAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (actin) in
            myAlert.dismiss(animated: true, completion: nil)
            let vc = CustomClass()
            vc.GoBackToPreviousVC()
        }))
         vc.present(myAlert, animated: true, completion: nil)
    }
 }

 class: CustomClass: UIViewController {

    func GoBackToPreviousVC(){
        navigationController?popViewController(animated: true)
    }

    function Download(){

      code for URLRequest...

      DispatchQueue.main.async {
        if (self.response.Status == "200"){
            Alert.CustomAlert(vc: self, title: "", message: "")
        }

      }

    }
}


问:
Spring boot: Using Async method as sync method
I have some scenario

scheduler(call repeatedly) should call  for a async function say fun().

Controller should call same function fun() and return result based on successful completion(By checking exception)

Please provide me some skeleton with appropriate notations.

答:
You should have your method as sync, but if you want to call your async methd, inside of your async method you should call your sync method.

```<code>public void mySyncMethod(){
   //whatever you want.
}
</code>```

Async method

```<code>@Async
public void myAsyncMethod(){
   mySyncMethod();
}
</code>```

I supposed you are using spring boot

Body:
You should have your method as sync, but if you want to call your async methd, inside of your async method you should call your sync method.

public void mySyncMethod(){
   //whatever you want.
}

Async method

@Async
public void myAsyncMethod(){
   mySyncMethod();
}

I supposed you are using spring boot


问:
XML - simplexml_load_file - foreach
I need for my project echo xml data from xml

I use simplexml_load_file

I have

```<code>      <group>
        <admin>
          <id>605</id>
        </admin>
        <members>
          <id>2154</id>
          <id>2256</id>
          <id>3179</id>
        </menbers>
      </group>
      <group>
        <admin>
          ....
        </admin>
        <members>
          ...
          ...
        </members>
      </group>
</code>```

My code is

```<code>$soubor="platebniudaje.xml";
$xml = simplexml_load_file($soubor);

  foreach ($xml->group as $group) {
        echo $group->admin->id . "<br>";

        foreach ($group->members as $members) {
            echo $members->id . "<br>";
        }

  }
</code>```

My output is

```<code>605
2154
</code>```

but i need

```<code>605
2154
2256
3179
</code>```

Can you help me? Where is mistake?

答:
I'm not sure this is what your are looking for, but based only on the xml snippet in your question, this:

```<code>foreach($xml->xpath('//group//id') as $node) {

    echo $node, PHP_EOL;
}
</code>```

should output:

```<code>605
2154
2256
3179
</code>```

Title: XML - simplexml_load_file - foreach

Body:
I need for my project echo xml data from xml

I use simplexml_load_file

I have

      <group>
        <admin>
          <id>605</id>
        </admin>
        <members>
          <id>2154</id>
          <id>2256</id>
          <id>3179</id>
        </menbers>
      </group>
      <group>
        <admin>
          ....
        </admin>
        <members>
          ...
          ...
        </members>
      </group>

My code is

$soubor="platebniudaje.xml";
$xml = simplexml_load_file($soubor);

  foreach ($xml->group as $group) {
        echo $group->admin->id . "
";

        foreach ($group->members as $members) {
            echo $members->id . "
";
        }

  }

My output is

605
2154

but i need

605
2154
2256
3179

Can you help me? Where is mistake?

Body:
I'm not sure this is what your are looking for, but based only on the xml snippet in your question, this:

foreach($xml->xpath('//group//id') as $node) {

    echo $node, PHP_EOL;
}

should output:

605
2154
2256
3179


问:
Specifying process priority in Ansible
Is it possible to specify the process priority for an Ansible task?

The use case is setting a low priority for an expensive and long-running backup task. In a bash script I'd use nice for this. I did not find anything by searching using keywords "process priority" and "nice" combined with "Ansible".

答:
async tasks allow you to run tasks in background. This helps in avoiding long-running tasks from blocking remaining tasks. The approach works as long as the remaining tasks are independent of the task marked async, this can reduce wait time.

For example, waiting for huge file to complete download and the next task is c completely independent command which can take some time. Since async task will run in the background by the time it is completed the rest of the independent commands are done.

Link on documentation below
https://docs.ansible.com/ansible/latest/user_guide/playbooks_async.html

Title: Specifying process priority in Ansible


问:
How to register this in xml configuration
How do I register something like this in the xml configuration (i know, i know, convention over config, but I'm supporting legacy code, so i need to do it in the xml config).

Specifically, I'm unclear on how to register AssignTechniciansFactory with the abstract base class AND the interface type. Normally, i get how to do it for either a base class OR just the interface. But how about registering both to the component?

```<code>public class AssignTechniciansFactory:
         BaseAssignTechniciansFactory<Service>, IAssignTechniciansFactory
</code>```

Where:

```<code>public class Service : BaseAssignTechnician
</code>```

And:

```<code>public abstract class BaseAssignTechniciansFactory<T>
                         where T: BaseAssignTechnician
</code>```

This is what I have, and I know it's not correct:

```<code><component id="assignTechniciansFactory"
           service="MyNamespace.IAssignTechniciansFactory, MyAssembly"
           type="MyNamespace.AssignTechniciansFactory, MyAssembly">
   <parameters>
     <dmq>${dmq}</dmq>
     <builder>${builder}</builder>
   </parameters>
</component>
</code>```

答: In addition to what @adymitruk said, you can specify additional services for a component via forwardedTypes element in XML configuration.

Body:
How do I register something like this in the xml configuration (i know, i know, convention over config, but I'm supporting legacy code, so i need to do it in the xml config).

Specifically, I'm unclear on how to register AssignTechniciansFactory with the abstract base class AND the interface type. Normally, i get how to do it for either a base class OR just the interface. But how about registering both to the component?

public class AssignTechniciansFactory:
         BaseAssignTechniciansFactory<Service>, IAssignTechniciansFactory

Where:

public class Service : BaseAssignTechnician

And:

public abstract class BaseAssignTechniciansFactory<T>
                         where T: BaseAssignTechnician

This is what I have, and I know it's not correct:

<component id="assignTechniciansFactory"
           service="MyNamespace.IAssignTechniciansFactory, MyAssembly"
           type="MyNamespace.AssignTechniciansFactory, MyAssembly">
   <parameters>
     <dmq>${dmq}</dmq>
     <builder>${builder}</builder>
   </parameters>
</component>


问:
Hello, I am trying to arrange an array from the small value to big value, but its not working
I am trying to arrange an array from the small value to grow, and for some reason this function does not work (SmallToGrow), the rest is excellent. Thanks.

There are auxiliary functions that I use and are excellent facts, only the (SmallToGrow) function does not work for me and I cannot understand why. I'd love anyone who can help. Thanks
    enter code here

```<code>  //this check if all cells equals
   public bool EverybodyAreEqual(int [] array)
        {
            for (int i = 0; i < array.Length - 1; i++)
                if (array[i] != array[i + 1])
                return false;
            return true;
        }
//This function changes all the values in the array that contain the -numInArray- value you entered,
 // to the -numChanged- value you entered
 public void ChangNumWhere(ref  int []  array,int numInArray,int numChanged)
        {
            for (int i = 0; i < array.Length; i++)
                if (array[i] == numInArray)
                    array[i] = numChanged;
        }
   //A function that returns the number of values that are not equal in the array
    public int NumDifferentArray(int [] array)
        {
             int[] arr = new int[array.Length];
               for (int i = 0; i < arr.Length; i++)
                  arr[i] = array[i];
             bool con = true;
             int contain = 0;
             int index = 0;
             for(int i=0; con;i++)
             {
                if (!arr.Contains(i))
                 {
                  contain = i;
                  con = false;
                }
             }
            while(!this.EverybodyAreEqual(arr))
            {
                for (int i = 0; i < arr.Length; i++)
                    if (arr[i] != contain)
                    {
                        this.ChangNumWhere(ref arr, arr[i], contain);
                        index++;
                    }
            }
            return index;
        }
 public int HowTimesExsist(int [] array,int num)
        {
            int index = 0;
            for(int i=0;i<array.Length;i++)
            {
                if (array[i] == num)
                    index++;
            }
            return index;
        }
  /// This function returns a minimum value as required,
  /// for example if you requested 0 the smallest value is returned,
  /// if 1 is returned one above it and so on,
  /// if the index is greater than the length of the array the largest number is returned
    public int MinBottom(int[] array, int num)
        {
            if (num < 0)
                throw new Exception("num canot be less then 0");
            int max = this.MaxArray(array);
            while (num > 0)
            {
               int min = this.MinArray(array);
               for (int i = 0; i < array.Length; i++)
                    if(array[i]==min)
                         array[i] = max;
                num--;
            }
            return this.MinArray(array);
        }
 public  int[]  SmallToGrow(int [] array)
        {
            int i = 0;
            int[] arr = new int[array.Length];
             for (int j = 0; j < this.NumDifferentArray(array); j++)
                for (int b = 0; b < this.HowTimesExsist(array, MinBottom(array, j)); i++, b++)
                    arr[i] = this.MinBottom(array, j);
            return arr;
         }
</code>```

答:
It looks like you are in large part re-engineering some common functionality in System.Collections.Generic and System.Linq -

```<code>public bool EverybodyAreEqual(int[] array)
{
    // If all items are the same,
    // there should only be one distinct item in the collection
    return array.Distinct().Length == 1;
}

public int NumDifferentArray(int[] array)
{
    // Group the numbers in the array and
    // count the number of groups with only one item
    return array.GroupBy(number => number).Where(g => g.Count() == 1);
}

public int HowTimesExsist(int[] array, int num)
{
    // Count the number of times a number appears in the array
    return array.Count(n => n == num);
}

/// This function returns a minimum value as required,
/// for example if you requested 0 the smallest value is returned,
/// if 1 is returned one above it and so on,
/// if the index is greater than the length of the array the largest number is returned
public int MinBottom(int[] array, int num)
{
    if (num < 0)
    {
        // Be specific about the type of exception you are throwing
        throw new ArgumentOutOfRangeException(nameof(num));
    }

    // Sort a copy of your array
    var sorted = Array.Copy(array);
    Array.Sort(sorted);

    // If there are any items over the specified minimum, return those
    // otherwise, return the highest number in the array
    // Using LastOrDefault for the maximum will return 0 if the initial array is empty
    var itemsOverMinimum = sorted.Where(n => n >= num);
    return itemsOverMinimum.Any() ? itemsOverMinimum.First() : sorted.LastOrDefault();
}

public int[] SmallToGrow(int[] array)
{
    // Because you are returning an array, that implies that the original array should not change
    // Copy the array and sort it
    var copy = Array.Copy(array);
    Array.Sort(copy);
    return copy;
}
</code>```

I saw that you mentioned that you are trying to find alternative ways to accomplish some of these things, and I want to give you some advice about that.

I think it's pretty cool that you want to challenge yourself. However, this specific functionality is part of System libraries. One of the best parts about working in C# is how much of this sort of thing is already written for you, and this functionality being added to System means that Microsoft believes these pieces are the core (pun intended) building blocks for working in .NET.

Unless your project is to specifically write a better sorting algorithm, you are not going to write this better than it is in those libraries. I've been doing this for a while, and I'm not going to be able to either.

But that doesn't mean you should stop learning. Instead, I would encourage you to look at the github source for the methods I used in my snippets above. I think that will probably be a lot more helpful than re-engineering this stuff from scratch.

https://github.com/dotnet/runtime/blob/master/src/libraries/System.Linq/src/System/Linq/Distinct.cs
https://github.com/dotnet/runtime/blob/master/src/libraries/System.Linq/src/System/Linq/Grouping.cs
https://github.com/dotnet/runtime/blob/master/src/libraries/System.Linq/src/System/Linq/Where.cs
https://github.com/dotnet/runtime/blob/master/src/libraries/System.Linq/src/System/Linq/Count.cs

Body:
I am trying to arrange an array from the small value to grow, and for some reason this function does not work (SmallToGrow), the rest is excellent. Thanks.

There are auxiliary functions that I use and are excellent facts, only the (SmallToGrow) function does not work for me and I cannot understand why. I'd love anyone who can help. Thanks
    enter code here

  //this check if all cells equals
   public bool EverybodyAreEqual(int [] array)
        {
            for (int i = 0; i < array.Length - 1; i++)
                if (array[i] != array[i + 1])
                return false;
            return true;
        }
//This function changes all the values in the array that contain the -numInArray- value you entered,
 // to the -numChanged- value you entered
 public void ChangNumWhere(ref  int []  array,int numInArray,int numChanged)
        {
            for (int i = 0; i < array.Length; i++)
                if (array[i] == numInArray)
                    array[i] = numChanged;
        }
   //A function that returns the number of values that are not equal in the array
    public int NumDifferentArray(int [] array)
        {
             int[] arr = new int[array.Length];
               for (int i = 0; i < arr.Length; i++)
                  arr[i] = array[i];
             bool con = true;
             int contain = 0;
             int index = 0;
             for(int i=0; con;i++)
             {
                if (!arr.Contains(i))
                 {
                  contain = i;
                  con = false;
                }
             }
            while(!this.EverybodyAreEqual(arr))
            {
                for (int i = 0; i < arr.Length; i++)
                    if (arr[i] != contain)
                    {
                        this.ChangNumWhere(ref arr, arr[i], contain);
                        index++;
                    }
            }
            return index;
        }
 public int HowTimesExsist(int [] array,int num)
        {
            int index = 0;
            for(int i=0;i<array.Length;i++)
            {
                if (array[i] == num)
                    index++;
            }
            return index;
        }
  /// This function returns a minimum value as required,
  /// for example if you requested 0 the smallest value is returned,
  /// if 1 is returned one above it and so on,
  /// if the index is greater than the length of the array the largest number is returned
    public int MinBottom(int[] array, int num)
        {
            if (num < 0)
                throw new Exception("num canot be less then 0");
            int max = this.MaxArray(array);
            while (num > 0)
            {
               int min = this.MinArray(array);
               for (int i = 0; i < array.Length; i++)
                    if(array[i]==min)
                         array[i] = max;
                num--;
            }
            return this.MinArray(array);
        }
 public  int[]  SmallToGrow(int [] array)
        {
            int i = 0;
            int[] arr = new int[array.Length];
             for (int j = 0; j < this.NumDifferentArray(array); j++)
                for (int b = 0; b < this.HowTimesExsist(array, MinBottom(array, j)); i++, b++)
                    arr[i] = this.MinBottom(array, j);
            return arr;
         }

Body:
It looks like you are in large part re-engineering some common functionality in System.Collections.Generic and System.Linq -

public bool EverybodyAreEqual(int[] array)
{
    // If all items are the same,
    // there should only be one distinct item in the collection
    return array.Distinct().Length == 1;
}

public int NumDifferentArray(int[] array)
{
    // Group the numbers in the array and
    // count the number of groups with only one item
    return array.GroupBy(number => number).Where(g => g.Count() == 1);
}

public int HowTimesExsist(int[] array, int num)
{
    // Count the number of times a number appears in the array
    return array.Count(n => n == num);
}

/// This function returns a minimum value as required,
/// for example if you requested 0 the smallest value is returned,
/// if 1 is returned one above it and so on,
/// if the index is greater than the length of the array the largest number is returned
public int MinBottom(int[] array, int num)
{
    if (num < 0)
    {
        // Be specific about the type of exception you are throwing
        throw new ArgumentOutOfRangeException(nameof(num));
    }

    // Sort a copy of your array
    var sorted = Array.Copy(array);
    Array.Sort(sorted);

    // If there are any items over the specified minimum, return those
    // otherwise, return the highest number in the array
    // Using LastOrDefault for the maximum will return 0 if the initial array is empty
    var itemsOverMinimum = sorted.Where(n => n >= num);
    return itemsOverMinimum.Any() ? itemsOverMinimum.First() : sorted.LastOrDefault();
}

public int[] SmallToGrow(int[] array)
{
    // Because you are returning an array, that implies that the original array should not change
    // Copy the array and sort it
    var copy = Array.Copy(array);
    Array.Sort(copy);
    return copy;
}

I saw that you mentioned that you are trying to find alternative ways to accomplish some of these things, and I want to give you some advice about that.

I think it's pretty cool that you want to challenge yourself. However, this specific functionality is part of System libraries. One of the best parts about working in C# is how much of this sort of thing is already written for you, and this functionality being added to System means that Microsoft believes these pieces are the core (pun intended) building blocks for working in .NET.

Unless your project is to specifically write a better sorting algorithm, you are not going to write this better than it is in those libraries. I've been doing this for a while, and I'm not going to be able to either.

But that doesn't mean you should stop learning. Instead, I would encourage you to look at the github source for the methods I used in my snippets above. I think that will probably be a lot more helpful than re-engineering this stuff from scratch.

https://github.com/dotnet/runtime/blob/master/src/libraries/System.Linq/src/System/Linq/Distinct.cs
https://github.com/dotnet/runtime/blob/master/src/libraries/System.Linq/src/System/Linq/Grouping.cs
https://github.com/dotnet/runtime/blob/master/src/libraries/System.Linq/src/System/Linq/Where.cs
https://github.com/dotnet/runtime/blob/master/src/libraries/System.Linq/src/System/Linq/Count.cs


问:
After $npm install, Getting Error: Cannot find module '../lib/utils/unsupported.js'
I just came back to work on a React project after working in the Rails environment and found that I cannot run any NPM commands in my Mac terminal. I've tried all the remedies that I have come across but none have worked. The bigger issue is what caused this and how can I avoid it again.

Here is the error. What do I need to do? Please help.

```<code>$npm install

internal/modules/cjs/loader.js:550
    throw err;
    ^

Error: Cannot find module '../lib/utils/unsupported.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:548:15)
    at Function.Module._load (internal/modules/cjs/loader.js:475:25)
    at Module.require (internal/modules/cjs/loader.js:598:17)
    at require (internal/modules/cjs/helpers.js:11:18)
    at /usr/local/lib/node_modules/npm/bin/npm-cli.js:19:21
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:92:3)
    at Module._compile (internal/modules/cjs/loader.js:654:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
    at Module.load (internal/modules/cjs/loader.js:566:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
</code>```

I have tried the following:

```<code>$brew update
$brew uninstall node
$brew install node
</code>```

After which the following commands come up as so when $which npm was unknown command before:

```<code>$which npm
/usr/local/bin/npm

$which node
/usr/local/bin/node
</code>```

I even tried running:

```<code>/usr/local/bin/npm -v
</code>```

but get the same error as above while

```<code>/usr/local/bin/node -v
v9.11.1
</code>```

works fine.

added the following to my .zshrc file:

```<code>export PATH=/usr/local/bin/node:$PATH
export PATH=/usr/local/bin/npm:$PATH
</code>```

I have also tried:

```<code>$brew uninstall --force node
$brew link --overwrite node
Warning: Already linked: /usr/local/Cellar/node/9.11.1
To relink: brew unlink node && brew link node

$rm -rf /usr/local/lib/node_modules/npm
</code>```

then,

```<code>$node install
</code>```

but that does not work, either.

```<code>$echo $NODE_PATH
</code>```

does come up empty, so I may need to added the following to my .bashrc.

```<code>export PATH="/usr/local/bin/npm:/usr/local/bin/node:/usr/local/bin:$PATH"
</code>```

That does not work either.

答:
One other suggestion after trying these that finally worked for me was simply upgrading my node by downloading the latest via the download and package installer from here:

https://nodejs.org/en/download/

Before doing this trying to run any npm command gave me the same error brought in OP's question

npm commands started working for me after that.

Body:
I just came back to work on a React project after working in the Rails environment and found that I cannot run any NPM commands in my Mac terminal. I've tried all the remedies that I have come across but none have worked. The bigger issue is what caused this and how can I avoid it again.

Here is the error. What do I need to do? Please help.

$npm install

internal/modules/cjs/loader.js:550
    throw err;
    ^

Error: Cannot find module '../lib/utils/unsupported.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:548:15)
    at Function.Module._load (internal/modules/cjs/loader.js:475:25)
    at Module.require (internal/modules/cjs/loader.js:598:17)
    at require (internal/modules/cjs/helpers.js:11:18)
    at /usr/local/lib/node_modules/npm/bin/npm-cli.js:19:21
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:92:3)
    at Module._compile (internal/modules/cjs/loader.js:654:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
    at Module.load (internal/modules/cjs/loader.js:566:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:506:12)

I have tried the following:

$brew update
$brew uninstall node
$brew install node

After which the following commands come up as so when $which npm was unknown command before:

$which npm
/usr/local/bin/npm

$which node
/usr/local/bin/node

I even tried running:

/usr/local/bin/npm -v

but get the same error as above while

/usr/local/bin/node -v
v9.11.1

works fine.

added the following to my .zshrc file:

export PATH=/usr/local/bin/node:$PATH
export PATH=/usr/local/bin/npm:$PATH

I have also tried:

$brew uninstall --force node
$brew link --overwrite node
Warning: Already linked: /usr/local/Cellar/node/9.11.1
To relink: brew unlink node && brew link node

$rm -rf /usr/local/lib/node_modules/npm

then,

$node install

but that does not work, either.

$echo $NODE_PATH

does come up empty, so I may need to added the following to my .bashrc.

export PATH="/usr/local/bin/npm:/usr/local/bin/node:/usr/local/bin:$PATH"

That does not work either.


问:
What is the easiest FLV player for embedding video on a website?
I have video that I've converted to FLV format.  I'd rather host it on my own site than use a service like YouTube.  What is the easiest player to use?  I'd like to just put the .swf file of the player somewhere on my server, and give it the video as a parameter.</p>

答:
I haven't tried yet Flowplayer which seems well documented

it is featured on arctic startup and only restriction to use it with opensource licence is to have their logo displayed

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Kip

OwnerDisplayName: smoothdeveloper


问:
Adding Chronicle Queue to project using Maven conflicts with Lombok
I was using Chronicle Queue in a project that does not have Lombok. Everything was okey. Then I tried to use same Maven dependency in a project that have Lombok dependency. But it crashed this time. I see the below error in my all Lombok Getter and Setter annotations.

```<code>The package java.lang is accessible from more than one module: <unnamed>, java.base
</code>```

I can run the project. But Eclipse shows red warning in classes that use Lombok annotations. Here is my Chronicle Queue dependency.

```<code>  <!-- https://mvnrepository.com/artifact/net.openhft/chronicle-queue -->
    <dependency>
      <groupId>net.openhft</groupId>
      <artifactId>chronicle-queue</artifactId>
      <version>5.17.22</version>
    </dependency>
</code>```

Image Here

Any idea about solution? Thanks.

答:
The problem is, I think, that a transitive dependency of chronicle-queue has some classes in the java.lang package, which is not allowed anymore.

Basically, you have to exclude the net.openhft:affinity package.  Something like:

Maven Snippet

    <dependency>
      <groupId>net.openhft</groupId>
      <artifactId>chronicle-queue</artifactId>
      <version>5.17.22</version>
      <exclusions>
            <exclusion>
                <groupId>net.openhft</groupId>
                <artifactId>affinity</artifactId>
            </exclusion>
        </exclusions>

    </dependency>
```

P.S. Techically, we were having the same problem with chronicle-map instead of chronicle-queue, but I believe it's for that same reason so I'm posting anyway.

Body:
I was using Chronicle Queue in a project that does not have Lombok. Everything was okey. Then I tried to use same Maven dependency in a project that have Lombok dependency. But it crashed this time. I see the below error in my all Lombok Getter and Setter annotations.

The package java.lang is accessible from more than one module: <unnamed>, java.base

I can run the project. But Eclipse shows red warning in classes that use Lombok annotations. Here is my Chronicle Queue dependency.

    <dependency>
      <groupId>net.openhft</groupId>
      <artifactId>chronicle-queue</artifactId>
      <version>5.17.22</version>
    </dependency>

Image Here

Any idea about solution? Thanks.

Body:
The problem is, I think, that a transitive dependency of chronicle-queue has some classes in the java.lang package, which is not allowed anymore.

Basically, you have to exclude the net.openhft:affinity package.  Something like:

Maven Snippet

    <dependency>
      <groupId>net.openhft</groupId>
      <artifactId>chronicle-queue</artifactId>
      <version>5.17.22</version>
      <exclusions>
            <exclusion>
                <groupId>net.openhft</groupId>
                <artifactId>affinity</artifactId>
            </exclusion>
        </exclusions>

    </dependency>

P.S. Techically, we were having the same problem with chronicle-map instead of chronicle-queue, but I believe it's for that same reason so I'm posting anyway.


问:
How to Trigger child method in ReactJS Functional Component
I have some inline edit fields, clicking on save should trigger child method which executes the API call with other properties. Currently using useState to set the flag, but it is working only once, if I resubmit it is not working, instead I want to use the method.</p>

答:
From the documentation:

useImperativeHandle

js useImperativeHandle(ref, createHandle, [deps])

useImperativeHandle customizes the instance value that is exposed to
  parent components when using ref. As always, imperative code using
  refs should be avoided in most cases. useImperativeHandle should be
  used with forwardRef:

```<code>useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }   }));   return <input ref={inputRef} ... />; }

FancyInput = forwardRef(FancyInput);
</code>```

In this example, a parent component that renders <FancyInput
  ref={inputRef} /> would be able to call inputRef.current.focus().

Body:
From the documentation:

useImperativeHandle

js useImperativeHandle(ref, createHandle, [deps])

useImperativeHandle customizes the instance value that is exposed to
  parent components when using ref. As always, imperative code using
  refs should be avoided in most cases. useImperativeHandle should be
  used with forwardRef:

useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }   }));   return <input ref={inputRef} ... />; }

FancyInput = forwardRef(FancyInput);

In this example, a parent component that renders <FancyInput
  ref={inputRef} /> would be able to call inputRef.current.focus().


答:
Modify the alert to be inside an extension of UIViewController and use self to dismiss and popViewController in the navigational stack, here is the code:

extension UIViewController {
    func CustomAlert(title: String, message: String){

        var title = "Title...!"
        var message = "Message..."
        let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        myAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (actin) in
            myAlert.dismiss(animated: true, completion: nil)
            self.navigationController?.popViewController(animated: true)
        }))
         present(myAlert, animated: true, completion: nil)
    }
 }
```

<p>Usage:</p>

```class: CustomClass: UIViewController {

    function Download(){

      // code for URLRequest...

      DispatchQueue.main.async {
        if (self.response.Status == "200") {
            self.CustomAlert(title: "", message: "")
        }
      }
    }
}
```

Title: Alert button to dismiss Alert and go back to previous View Controller

Body:
Modify the alert to be inside an extension of UIViewController and use self to dismiss and popViewController in the navigational stack, here is the code:

extension UIViewController {
    func CustomAlert(title: String, message: String){

        var title = "Title...!"
        var message = "Message..."
        let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        myAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (actin) in
            myAlert.dismiss(animated: true, completion: nil)
            self.navigationController?.popViewController(animated: true)
        }))
         present(myAlert, animated: true, completion: nil)
    }
 }

Usage:

class: CustomClass: UIViewController {

    function Download(){

      // code for URLRequest...

      DispatchQueue.main.async {
        if (self.response.Status == "200") {
            self.CustomAlert(title: "", message: "")
        }
      }
    }
}


问:
Sending an HTTP request using QNetworkAccessManager
I've got a problem trying to send a request using QNetworkAccessManager from a QObject derived class.

Firstly in my constructor I do the following:

```<code>QObject::connect( &mAccessManager, SIGNAL( finished( QNetworkReply* ) ), this, SLOT( requestFinished( QNetworkReply* ) ) );
</code>```

Then when I wish to send the request I do the following:

```<code>QNetworkRequest checkLogin( QUrl( address ) );
checkLogin.setHeader( QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded" );

mByteArray  = QByteArray( "POST \"client\" : oxres" );
QNetworkReply* pReply   = mAccessManager.post( checkLogin, mByteArray );
</code>```

Now at this point I expect to wait around for a few seconds and then receive a response to my class's slot requestFinished.  It doesn't however get called.

I'm at a loss as to what I'm doing wrong.  Anyone got any ideas? (I'm sure its something stupidly simple).

Edit: Ok this is very weird.  I have wireshark collecting packets in the background and when i generate that post request I see nothing happening in wireshark.  So why isn't it sending??

Edit 2: Hmm it seems that the problem lies with me sending a request to an https:// address ... why would that be??

答:
A few points:

1) The thread your QNetworkRequest belongs to must be running event loop (only this way you can receive signals).

2) If you "wait around" with something like sleep after mAccessManager.post it is not going to work. You have to let event loop iterate to process signals, etc. You can run event loop yourself after post.

ADD:

I did it synchronously like this

```<code>QNetworkRequest request;

request.setHeader(
            QNetworkRequest::ContentTypeHeader,
            QVariant( QString("text/xml") )
            );
request.setHeader(
            QNetworkRequest::ContentLengthHeader,
            QVariant( qulonglong(mesPOST.size()) )
            );
request.setHeader(...);
//etc....

request.setAttribute(
            QNetworkRequest::CacheLoadControlAttribute,
            QVariant( int(QNetworkRequest::AlwaysNetwork) )
            );
request.setUrl( QUrl( "http://bla.bla", QUrl::StrictMode ) );

QNetworkReply* pReply = m_NetMgr->post( request, mesPOST );
QEventLoop eLoop;

QObject::connect( pReply, SIGNAL(finished()), &eLoop, SLOT(quit()) );
eLoop.exec( QEventLoop::ExcludeUserInputEvents );
</code>```

Body:
I've got a problem trying to send a request using QNetworkAccessManager from a QObject derived class.

Firstly in my constructor I do the following:

QObject::connect( &mAccessManager, SIGNAL( finished( QNetworkReply* ) ), this, SLOT( requestFinished( QNetworkReply* ) ) );

Then when I wish to send the request I do the following:

QNetworkRequest checkLogin( QUrl( address ) );
checkLogin.setHeader( QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded" );

mByteArray  = QByteArray( "POST \"client\" : oxres" );
QNetworkReply* pReply   = mAccessManager.post( checkLogin, mByteArray );

Now at this point I expect to wait around for a few seconds and then receive a response to my class's slot requestFinished.  It doesn't however get called.

I'm at a loss as to what I'm doing wrong.  Anyone got any ideas? (I'm sure its something stupidly simple).

Edit: Ok this is very weird.  I have wireshark collecting packets in the background and when i generate that post request I see nothing happening in wireshark.  So why isn't it sending??

Edit 2: Hmm it seems that the problem lies with me sending a request to an https:// address ... why would that be??

Body:
A few points:

1) The thread your QNetworkRequest belongs to must be running event loop (only this way you can receive signals).

2) If you "wait around" with something like sleep after mAccessManager.post it is not going to work. You have to let event loop iterate to process signals, etc. You can run event loop yourself after post.

ADD:

I did it synchronously like this

QNetworkRequest request;

request.setHeader(
            QNetworkRequest::ContentTypeHeader,
            QVariant( QString("text/xml") )
            );
request.setHeader(
            QNetworkRequest::ContentLengthHeader,
            QVariant( qulonglong(mesPOST.size()) )
            );
request.setHeader(...);
//etc....

request.setAttribute(
            QNetworkRequest::CacheLoadControlAttribute,
            QVariant( int(QNetworkRequest::AlwaysNetwork) )
            );
request.setUrl( QUrl( "http://bla.bla", QUrl::StrictMode ) );

QNetworkReply* pReply = m_NetMgr->post( request, mesPOST );
QEventLoop eLoop;

QObject::connect( pReply, SIGNAL(finished()), &eLoop, SLOT(quit()) );
eLoop.exec( QEventLoop::ExcludeUserInputEvents );


问:
Text slide in on hover CSS
I want the text Along came to slide in when mouse hovers over the wolf.
But the position of the wolf should not change. Along came should simply slide in and fade in from the left to complete the sentence.

.main {
  width: 100vw;
  text-align:center;
}

.addText {
  display: none;
  color: rgba(255,255,255,0);
  transition: .5s;
}

.link:hover .addText {
  display: inline;
  color: red;
  transform: translate(-10px, 00%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">
  <div class="link">
      <span class="addText">Along came </span>
      the wolf
  </div>
</div></code>```

答:
Here is an idea where you can make the element width:0 so it doesn't affect the other element:

.main {
  text-align:center;
}
.link {
  display:inline-block;
}
.addText {
  display:inline-block; /* inline-block so we can set a width */
  width:0;
  white-space:nowrap; /* keep text one line */
  direction:rtl; /* change direction so the text overflow on the left */
  color: rgba(255,255,255,0);
  transition: .5s;
  transform: translateX(20px); /* put the value you want here */
  pointer-events:none; /* to avoid the hover on the text, remove to see the difference */
}

.link:hover .addText {
  color: red;
  transform: translateX(0);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">
  <div class="link">
      <span class="addText">Along came </span>
      the wolf
  </div>
</div></code>```

You can also do only the translation in case you want the text to take the space:

.main {
  text-align:center;
}
.link {
  display:inline-block;
}
.addText {
  display:inline-block;
  color: rgba(255,255,255,0);
  transition: .5s;
  transform: translateX(100%);
}

.link:hover .addText {
  color: red;
  transform: translateX(0);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">
  <div class="link">
      <span class="addText">Along came </span>
      the wolf
  </div>
</div></code>```

Title: Text slide in on hover CSS

Body:
I want the text Along came to slide in when mouse hovers over the wolf.
But the position of the wolf should not change. Along came should simply slide in and fade in from the left to complete the sentence.

.main {
  width: 100vw;
  text-align:center;
}

.addText {
  display: none;
  color: rgba(255,255,255,0);
  transition: .5s;
}

.link:hover .addText {
  display: inline;
  color: red;
  transform: translate(-10px, 00%);
}

      Along came
      the wolf

Body:
Here is an idea where you can make the element width:0 so it doesn't affect the other element:

.main {
  text-align:center;
}
.link {
  display:inline-block;
}
.addText {
  display:inline-block; /* inline-block so we can set a width */
  width:0;
  white-space:nowrap; /* keep text one line */
  direction:rtl; /* change direction so the text overflow on the left */
  color: rgba(255,255,255,0);
  transition: .5s;
  transform: translateX(20px); /* put the value you want here */
  pointer-events:none; /* to avoid the hover on the text, remove to see the difference */
}

.link:hover .addText {
  color: red;
  transform: translateX(0);
}

<div class="main">
  <div class="link">
      <span class="addText">Along came </span>
      the wolf
  </div>
</div>

You can also do only the translation in case you want the text to take the space:

.main {
  text-align:center;
}
.link {
  display:inline-block;
}
.addText {
  display:inline-block;
  color: rgba(255,255,255,0);
  transition: .5s;
  transform: translateX(100%);
}

.link:hover .addText {
  color: red;
  transform: translateX(0);
}

<div class="main">
  <div class="link">
      <span class="addText">Along came </span>
      the wolf
  </div>
</div>


问:
QML: move to next control in form
How can I move focus from one control to next one inside QML form?
By default it works with Tab button but I need to change it to Enter.
All the control are ordered with Gridlayout with 2 columns.

答:
In order to make it more robust and flexible, you should make same behaviour
for Tab and Enter/Return keys.

Handle keyPressed event and use KeyNavigation.tab instead of nextItemInFocusChain to focus next element as follow:

```<code>import QtQuick 2.12
import QtQuick.Controls 1.12

Column {
    TextField {
        id: field1
        KeyNavigation.tab: field2
        activeFocusOnTab: true
        Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
    }
    TextField {
        id: field2
        KeyNavigation.tab: field3
        activeFocusOnTab: true
        Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
    }
    TextField {
        id: field3
        KeyNavigation.tab: field1
        activeFocusOnTab: true
        Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
    }
}
</code>```

So you controlled order of focus and users can use both tab and return keys interchangeably which results better UX.

Whenever you want to change order, just change KeyNavigation.tab values :)

Note: I extremely suggest you to avoid using nextItemInFocusChain because of future changes and flexibility

Title: QML: move to next control in form

Body:
In order to make it more robust and flexible, you should make same behaviour
for Tab and Enter/Return keys.

Handle keyPressed event and use KeyNavigation.tab instead of nextItemInFocusChain to focus next element as follow:

import QtQuick 2.12
import QtQuick.Controls 1.12

Column {
    TextField {
        id: field1
        KeyNavigation.tab: field2
        activeFocusOnTab: true
        Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
    }
    TextField {
        id: field2
        KeyNavigation.tab: field3
        activeFocusOnTab: true
        Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
    }
    TextField {
        id: field3
        KeyNavigation.tab: field1
        activeFocusOnTab: true
        Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
    }
}

So you controlled order of focus and users can use both tab and return keys interchangeably which results better UX.

Whenever you want to change order, just change KeyNavigation.tab values :)

Note: I extremely suggest you to avoid using nextItemInFocusChain because of future changes and flexibility


问:
iOS Get user location in Notification Service Extension
Is it possible to use CoreLocation framework in UNNotificationServiceExtension?
What I've tried:

```<code>class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?
    private let locationManager = CLLocationManager()

    override func didReceive(_ request: UNNotificationRequest,
                             withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        os_log("%{public}@",
        log: OSLog(subsystem: "bundleIdentifier", category: "WakeUpExtension"),
        type: OSLogType.debug,
        "Push received")
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
    }

    override func serviceExtensionTimeWillExpire() {
        os_log("%{public}@",
        log: OSLog(subsystem: "bundleIdentifier", category: "WakeUpExtension"),
        type: OSLogType.debug,
        "Task expired")
        locationManager.stopUpdatingLocation()
        locationManager.delegate = nil

        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }

}
</code>```

```<code>extension NotificationService: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        locations.forEach {
            os_log("%{public}@",
            log: OSLog(subsystem: "bundleIdentifier", category: "WakeUpExtension"),
            type: OSLogType.debug,
            $0.horizontalAccuracy)
        }

        for location in locations {
            let locationAge = -location.timestamp.timeIntervalSinceNow
            if locationAge < 5 {
                os_log("%{public}@",
                log: OSLog(subsystem: "bundleIdentifier", category: "WakeUpExtension"),
                type: OSLogType.debug,
                "Send")
                locationManager.stopUpdatingLocation()
                locationManager.delegate = nil
                contentHandler?(UNNotificationContent())
            }
        }
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        os_log("%{public}@",
        log: OSLog(subsystem: "bundleIdentifier", category: "WakeUpExtension"),
        type: OSLogType.debug,
        error.localizedDescription)
    }
}
</code>```

All I've got in Console is:

答:
Looks like CLLocationManagerDelegate methods never gets called in UNNotificationServiceExtension. But it is possible to get last received location from the CLLocationManager location property:

```<code> let locationManager = CLLocationManager()
 let lastLocation = locationManager.location
</code>```

Body:
Is it possible to use CoreLocation framework in UNNotificationServiceExtension?
What I've tried:

class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?
    private let locationManager = CLLocationManager()

    override func didReceive(_ request: UNNotificationRequest,
                             withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        os_log("%{public}@",
        log: OSLog(subsystem: "bundleIdentifier", category: "WakeUpExtension"),
        type: OSLogType.debug,
        "Push received")
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
    }

    override func serviceExtensionTimeWillExpire() {
        os_log("%{public}@",
        log: OSLog(subsystem: "bundleIdentifier", category: "WakeUpExtension"),
        type: OSLogType.debug,
        "Task expired")
        locationManager.stopUpdatingLocation()
        locationManager.delegate = nil

        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }

}

extension NotificationService: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        locations.forEach {
            os_log("%{public}@",
            log: OSLog(subsystem: "bundleIdentifier", category: "WakeUpExtension"),
            type: OSLogType.debug,
            $0.horizontalAccuracy)
        }

        for location in locations {
            let locationAge = -location.timestamp.timeIntervalSinceNow
            if locationAge < 5 {
                os_log("%{public}@",
                log: OSLog(subsystem: "bundleIdentifier", category: "WakeUpExtension"),
                type: OSLogType.debug,
                "Send")
                locationManager.stopUpdatingLocation()
                locationManager.delegate = nil
                contentHandler?(UNNotificationContent())
            }
        }
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        os_log("%{public}@",
        log: OSLog(subsystem: "bundleIdentifier", category: "WakeUpExtension"),
        type: OSLogType.debug,
        error.localizedDescription)
    }
}

All I've got in Console is:

Body:
Looks like CLLocationManagerDelegate methods never gets called in UNNotificationServiceExtension. But it is possible to get last received location from the CLLocationManager location property:

 let locationManager = CLLocationManager()
 let lastLocation = locationManager.location


问:
Why Are My Cell's Images Being Pixelated?
I am using an iPhone 4 with retina display.

I have a 60x60 png that was downsized from a 500x500 png that I am using as the cell's imageView.

For some reason, the image looks a bit pixelated and blurry, basically not up to retina display standards.

What am I doing wrong?

I am using cell.imageView.image = [UIImage imageNamed:@"picture.png"];

答:
Since the filename doesn't follow the base@2x.ext format, iOS doesn't recognize it should use a scale factor of 2. There are two solutions:

The best is to provide two versions of the image: one for non-retina displays, which would be named picture.png and another one twice as big for retina displays, which would be named picture@2x.png. You would still use [UIImage imageNamed:@"picture.png"];, iOS automagically notices when the device has a retina display and there is a file called picture@2x.png that it needs to use that instead.

The hacky solution (which would make your image appear twice as big on non-retina devices) is to do this:

```<code>cell.imageView.image = [UIImage imageNamed:@"picture.png"];
cell.imageView.image.scale = [UIScreen mainScreen].scale;
</code>```

I recommend to go the @2x way, this is how it's supposed to be done.

Body:
Since the filename doesn't follow the base@2x.ext format, iOS doesn't recognize it should use a scale factor of 2. There are two solutions:

The best is to provide two versions of the image: one for non-retina displays, which would be named picture.png and another one twice as big for retina displays, which would be named picture@2x.png. You would still use [UIImage imageNamed:@"picture.png"];, iOS automagically notices when the device has a retina display and there is a file called picture@2x.png that it needs to use that instead.

The hacky solution (which would make your image appear twice as big on non-retina devices) is to do this:

cell.imageView.image = [UIImage imageNamed:@"picture.png"];
cell.imageView.image.scale = [UIScreen mainScreen].scale;

I recommend to go the @2x way, this is how it's supposed to be done.


问:
getting more informative log output in PHP on webhosting PDO
I have been developing complex platform, on which to build latter. I have reached the point when it works on mine lamp, but not when via webhosting. One of mine function designed to log the variables to the database during operation keeps sending just a petty

Fatal error:   in /home/.../asi/kluckaSpolocne.php on line 51

This points to the exception of execute statement:

```<code>throw new \PDOException($e->getMessage(), (int)$e->getCode());
</code>```

the code in question:

```<code>//echo "\n Spolocne ";
    //require 'ochrana.php';
    // include 'databazaCitaj.php';
    $dbuzyvatel = "mine login";
    $dbheslo    = "mine password";
//$charset = 'utf8mb4';
    $opt        = [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ];
    try {
        $databaza   = new PDO("mysql:host=localhost;dbname=mine_database", $dbuzyvatel, $dbheslo);
        $databaza->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (\PDOException $e) {
     throw new \PDOException($e->getMessage(), (int)$e->getCode());
    }

# $preloz = $databaza->prepare('select ? from preklady where jazyk=?');

    $GLOBALS['nová']=false;
    $DlzkaVystupu=1;
    $IC=0;
    $Hesla=json_encode(array(1,1));
    $HlavnýÚčel=0;
    $Kolá=array(0);
    $Hlasenia['Premenna']=' ';
    $Hlasenia['Text']=' ';
    $Hlasenia['Cislo']=1;
    $Hlasenia['JS']='[0]';
    $Hlasenia['Kdo']=0;
    $Hlasenia['Vlastnosti']='[0]';
    //print_r($Hlasenia);

    /*$hlásenie=$databaza->prepare('insert into Hlásenia (Premenná, Text)
    values (:Premenna, :Text)');//*/
    $hlásenie=$databaza->prepare('insert into Hlásenia (Premenná, Text, Cislo, JS, Kdo, Vlastnosti)
    values (:Premenna, :Text, :Cislo, :JS, :Kdo, :Vlastnosti)');//*/
    $hlásenie->bindParam(':Premenna', $Hlasenia['Premenna']);
    $hlásenie->bindParam(':Text', $Hlasenia['Text']);
    $hlásenie->bindParam(':Cislo', $Hlasenia['Cislo']);
    $hlásenie->bindParam(':JS', $Hlasenia['JS']);
    $hlásenie->bindParam(':Kdo', $Hlasenia['Kdo']);
    $hlásenie->bindParam(':Vlastnosti', $Hlasenia['Vlastnosti']);//*/
    // print_r($hlásenie);
    try { $hlásenie->execute();
    } catch (\PDOException $e) {
            throw new \PDOException($e->getMessage(), (int)$e->getCode());
    }//*/
</code>```

Any idea about how to get some useful info about what is wrong?

答:
Looks like it's your "function designed to log the variables" is messing with the error message.

Make it this way:

```<code>set_exception_handler(function ($e)
{
    error_log($e);
    http_response_code(500);
    if (ini_get('display_errors')) {
        echo $e;
    } else {
        echo "<h1>500 Internal Server Error</h1>
              An internal server error has been occurred.<br>
              Please try again later.";
    }
});
</code>```

It will catch every exception and log it into web-server's error log.
It's part of a complete error handling solution I wrote.

Body:
I have been developing complex platform, on which to build latter. I have reached the point when it works on mine lamp, but not when via webhosting. One of mine function designed to log the variables to the database during operation keeps sending just a petty

Fatal error:   in /home/.../asi/kluckaSpolocne.php on line 51

This points to the exception of execute statement:

throw new \PDOException($e->getMessage(), (int)$e->getCode());

the code in question:

//echo "\n Spolocne ";
    //require 'ochrana.php';
    // include 'databazaCitaj.php';
    $dbuzyvatel = "mine login";
    $dbheslo    = "mine password";
//$charset = 'utf8mb4';
    $opt        = [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ];
    try {
        $databaza   = new PDO("mysql:host=localhost;dbname=mine_database", $dbuzyvatel, $dbheslo);
        $databaza->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (\PDOException $e) {
     throw new \PDOException($e->getMessage(), (int)$e->getCode());
    }

# $preloz = $databaza->prepare('select ? from preklady where jazyk=?');

    $GLOBALS['nová']=false;
    $DlzkaVystupu=1;
    $IC=0;
    $Hesla=json_encode(array(1,1));
    $HlavnýÚčel=0;
    $Kolá=array(0);
    $Hlasenia['Premenna']=' ';
    $Hlasenia['Text']=' ';
    $Hlasenia['Cislo']=1;
    $Hlasenia['JS']='[0]';
    $Hlasenia['Kdo']=0;
    $Hlasenia['Vlastnosti']='[0]';
    //print_r($Hlasenia);

    /*$hlásenie=$databaza->prepare('insert into Hlásenia (Premenná, Text)
    values (:Premenna, :Text)');//*/
    $hlásenie=$databaza->prepare('insert into Hlásenia (Premenná, Text, Cislo, JS, Kdo, Vlastnosti)
    values (:Premenna, :Text, :Cislo, :JS, :Kdo, :Vlastnosti)');//*/
    $hlásenie->bindParam(':Premenna', $Hlasenia['Premenna']);
    $hlásenie->bindParam(':Text', $Hlasenia['Text']);
    $hlásenie->bindParam(':Cislo', $Hlasenia['Cislo']);
    $hlásenie->bindParam(':JS', $Hlasenia['JS']);
    $hlásenie->bindParam(':Kdo', $Hlasenia['Kdo']);
    $hlásenie->bindParam(':Vlastnosti', $Hlasenia['Vlastnosti']);//*/
    // print_r($hlásenie);
    try { $hlásenie->execute();
    } catch (\PDOException $e) {
            throw new \PDOException($e->getMessage(), (int)$e->getCode());
    }//*/

Any idea about how to get some useful info about what is wrong?

Body:
Looks like it's your "function designed to log the variables" is messing with the error message.

Make it this way:

set_exception_handler(function ($e)
{
    error_log($e);
    http_response_code(500);
    if (ini_get('display_errors')) {
        echo $e;
    } else {
        echo "<h1>500 Internal Server Error</h1>
              An internal server error has been occurred.<br>
              Please try again later.";
    }
});

It will catch every exception and log it into web-server's error log.
It's part of a complete error handling solution I wrote.


问:
Ansible: Load contents of files in directory into dict

TL;DR

In ansible, how do I load the contents of the files in a directory into a dict, such that the key: value pairs are filename: 'file_contents'?

The rest of the story...

I have a use case in Ansible, in which I need to provide the contents of a number of files to a helm chart, so that the helm chart can convert them to a ConfigMap for later inclusion in a pod.

The structure of the directory is:

foo/
  bar.txt
  baz.txt
  bat.txt
```

<p>I essentially need to convert the files to:</p>

<pre class="lang-yaml prettyprint-override"><code>config_map:
  bar\.txt: 'contents of bar.txt'
  baz\.txt: 'contents of baz.txt'
  bat\.txt: 'contents of bat.txt'
</code>```

When doing this as a shell script, I simply iterate over the files, and create a set of options in the form:

--set-file configMap.bar\\.txt=foo/bar.txt
```

<p>What it seems to me that I <strong>should</strong> be able to do is dynamically build the <code>dict</code> <code>config_map</code> and then pass it to <code>helm</code> as follows:</p>

<pre class="lang-yaml prettyprint-override"><code>- name: 'sample playbook'
  tasks:
    - name 'install helm chart'
      helm:
        ...
        values:
          configMap: '{{ config_map }}'
        ...
</code>```

The following task displays the files just fine, but I am at a loss regarding how to get to the next step.

- name: 'test fileglob'
  debug:
    msg: '{{ lookup("file", "{{ item }}") }}'
  loop: '{{ lookup("fileglob", "foo/*.txt").split(",") }}'

```

<h1>Edit</h1>

<p>On further consideration, it seems to me that something like the following might work:</p>

<pre class="lang-yaml prettyprint-override"><code>- name: 'mytask'
  execute_jinja2: '{{ vars["config_map"][item.split("/")[-1]] = lookup("file", "{{ item }}") }}'
  loop: '{{ lookup("fileglob", "foo/*.txt").split(",") }}'
</code>```

...except I haven't been able to determine how to execute an arbitrary Jinja2 statement like that, if it's even possible.

答:
There are more options.

The tasks below

    - set_fact:
        config_map: "{{ config_map|default({})|
                        combine({item|basename: lookup('file', item)}) }}"
      with_fileglob: "foo/*.txt"

    - debug:
        var: config_map
```
<p>give the expected result</p>
<pre class="lang-yaml prettyprint-override"><code>  config_map:
    bar.txt: contents of bar.txt
    bat.txt: contents of bat.txt
    baz.txt: contents of baz.txt
</code>```

The next option is to create a file and include it. The tasks below give the same result

    - copy:
        dest: "{{ playbook_dir }}/config_map.yml"
        content: |
          {% for file in q('fileglob', 'foo/*.txt') %}
          {{ file|basename }}: {{ lookup('file', file) }}
          {% endfor %}
      tags: configure

    - include_vars:
        file: config_map.yml
        name: config_map

    - debug:
        var: config_map
```
<p>The advantage is that you can run such a playbook with the tag <code>-t configure</code> and create the file</p>
<pre class="lang-yaml prettyprint-override"><code>shell> cat config_map.yml
bar.txt: contents of bar.txt
baz.txt: contents of baz.txt
bat.txt: contents of bat.txt
</code>```

In the next run, you simply include this file.

Body:
TL;DR

In ansible, how do I load the contents of the files in a directory into a dict, such that the key: value pairs are filename: 'file_contents'?

The rest of the story...

I have a use case in Ansible, in which I need to provide the contents of a number of files to a helm chart, so that the helm chart can convert them to a ConfigMap for later inclusion in a pod.

The structure of the directory is:

foo/
  bar.txt
  baz.txt
  bat.txt

I essentially need to convert the files to:

config_map:
  bar\.txt: 'contents of bar.txt'
  baz\.txt: 'contents of baz.txt'
  bat\.txt: 'contents of bat.txt'

When doing this as a shell script, I simply iterate over the files, and create a set of options in the form:

--set-file configMap.bar\\.txt=foo/bar.txt

What it seems to me that I should be able to do is dynamically build the dict config_map and then pass it to helm as follows:

- name: 'sample playbook'
  tasks:
    - name 'install helm chart'
      helm:
        ...
        values:
          configMap: '{{ config_map }}'
        ...

The following task displays the files just fine, but I am at a loss regarding how to get to the next step.

- name: 'test fileglob'
  debug:
    msg: '{{ lookup("file", "{{ item }}") }}'
  loop: '{{ lookup("fileglob", "foo/*.txt").split(",") }}'

Edit

On further consideration, it seems to me that something like the following might work:

- name: 'mytask'
  execute_jinja2: '{{ vars["config_map"][item.split("/")[-1]] = lookup("file", "{{ item }}") }}'
  loop: '{{ lookup("fileglob", "foo/*.txt").split(",") }}'

...except I haven't been able to determine how to execute an arbitrary Jinja2 statement like that, if it's even possible.

Body:
There are more options.

The tasks below

    - set_fact:
        config_map: "{{ config_map|default({})|
                        combine({item|basename: lookup('file', item)}) }}"
      with_fileglob: "foo/*.txt"

    - debug:
        var: config_map

give the expected result

  config_map:
    bar.txt: contents of bar.txt
    bat.txt: contents of bat.txt
    baz.txt: contents of baz.txt

The next option is to create a file and include it. The tasks below give the same result

    - copy:
        dest: "{{ playbook_dir }}/config_map.yml"
        content: |
          {% for file in q('fileglob', 'foo/*.txt') %}
          {{ file|basename }}: {{ lookup('file', file) }}
          {% endfor %}
      tags: configure

    - include_vars:
        file: config_map.yml
        name: config_map

    - debug:
        var: config_map

The advantage is that you can run such a playbook with the tag -t configure and create the file

shell> cat config_map.yml
bar.txt: contents of bar.txt
baz.txt: contents of baz.txt
bat.txt: contents of bat.txt

In the next run, you simply include this file.


问:
Need to create Excel File and download in client browser - Is it possible to create a file stream and send it in the Node Express response?
I'd like to create an Excel File stream in Node Express and send the Excel file in the Node Express response to then be downloaded by the client browser. Problem is I'm completely inexperienced with streams and I'm not even sure this is possible.

A little background: I'm using a node package ExcelJs (https://www.npmjs.com/package/exceljs) to create an Excel document. I can create the Excel file just fine. I know that Express provides res.download option to download files to the client browser, but I think res.download requires an actual file with a path in order to download to the client browser. This code will be hosted on AWS, and I want to avoid having to create and save a file in S3 before grabbing the file and downloading it to the client browser.

ExcelJS has an option to create a; file, stream, or buffer excel. Is it be possible to create a stream with the required data and then send that file stream in the response to be downloaded in the client browser?

答:
My favourite (awesome) solution:

res.xlsx('awesome-template.xlsx', awesomeViewModel, 'report.xlsx');
```

<p>My favourite solution is to expand response object by function <code>xlsx</code> which generate the file using a template with view model and write it into <code>res</code> (download into browser)</p>

<pre class="lang-js prettyprint-override"><code>import {Renderer} from 'xls-renderer'

const renderer = new Renderer();

router.use((req, res, next) => { // register middleware

  res.xlsx = (template, vm, fileName) => { // add function into res object
    const workbook = renderer.renderFromFile(template, vm);

    res.set({
      'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'Content-Disposition': `attachment; filename="${filenName}"`,
    });

    await (await workbook).xlsx.write(res);
  };

  next();
});
</code>```

Alternate solutions:

I. ExcelJS workbook.xlsx.write(res) way:

import {Workbook} from 'exceljs'

// creation code
const wb = new Workbook();
// ... const wsA = wb.addWorksheet("WsA");

// response headers
res.set({
  'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'Content-Disposition': `attachment; filename="from-exceljs.xlsx"`,
});

// write into response
wb.xlsx.write(res);

```

<h2>II. pure XlsxRender way:</h2>

<pre class="lang-sh prettyprint-override"><code>npm install --save xlsx-renderer
</code>```

const workbook = renderer.renderFromFile('template.xlsx', viewModel);

res.set({
    'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'Content-Disposition': `attachment; filename="from-xlsx-renderer.xlsx"`,
});

await (await workbook).xlsx.write(res); // yeah, it returns ExcelJs Workbook, so same as above.
```

Body:
My favourite (awesome) solution:

res.xlsx('awesome-template.xlsx', awesomeViewModel, 'report.xlsx');

My favourite solution is to expand response object by function xlsx which generate the file using a template with view model and write it into res (download into browser)

import {Renderer} from 'xls-renderer'

const renderer = new Renderer();

router.use((req, res, next) => { // register middleware

  res.xlsx = (template, vm, fileName) => { // add function into res object
    const workbook = renderer.renderFromFile(template, vm);

    res.set({
      'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'Content-Disposition': `attachment; filename="${filenName}"`,
    });

    await (await workbook).xlsx.write(res);
  };

  next();
});

Alternate solutions:

I. ExcelJS workbook.xlsx.write(res) way:

import {Workbook} from 'exceljs'

// creation code
const wb = new Workbook();
// ... const wsA = wb.addWorksheet("WsA");

// response headers
res.set({
  'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'Content-Disposition': `attachment; filename="from-exceljs.xlsx"`,
});

// write into response
wb.xlsx.write(res);

II. pure XlsxRender way:

npm install --save xlsx-renderer

const workbook = renderer.renderFromFile('template.xlsx', viewModel);

res.set({
    'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'Content-Disposition': `attachment; filename="from-xlsx-renderer.xlsx"`,
});

await (await workbook).xlsx.write(res); // yeah, it returns ExcelJs Workbook, so same as above.


问:
Compare two files if they both match first column then replace the values of column 2 and 3 (Python)
There are two files. If the ID number matches both files, then I want only the value 1 and value 2 from File2.txt , Please let me know if my question is unclear

```<code>File1.txt

ID Number   Value 1     Value 2     Country
0001        23            55        Spain
0231        15            23        USA
4213        10            11        Canada
7541        32            29        Italy

File2.txt

0001        5       6
0231        7       18
4213        54      87
5554        12      10
1111        31      13
6422        66      51
</code>```

The output should look like this.

```<code>ID Number   Value 1     Value 2     Country
0001          5           6         Spain
0231          7          18         USA
4213          54         87         Canada
7541          32         29         Italy
</code>```

New example:

```<code>File3.txt

#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.739000  -114.635700
01711 CX 21 --   3  32.779700  -115.567500
08433 CX 21 --   2  31.919930  -123.321000

File4.txt

20022,32.45,-114.88
01192,32.839,-115.487
01711,32.88,-115.45
01218,32.717,-115.637

output
#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.45  -114.88
01711 CX 21 --   3  32.88  -115.45
08433 CX 21 --   2  31.919930  -123.321000
</code>```

Code I got so far

```<code>f = open("File3.txt", "r")
x= open("File4.txt","r")

df1 = pd.read_csv(f, sep=' ', engine='python')
df2 = pd.read_csv(x, sep=' ', header=None, engine='python')

df2 = df2.set_index(0).rename_axis("#ID")
df2 = df2.rename(columns={5:'LATITUDE', 6: 'LONGITUDE'})
df1 = df1.set_index('#ID')
df1.update(df2)
print(df1)
</code>```

答:
Something like this, possibly:

file1_data = []
file1_headers = []

with open("File1.txt") as file1:
    for line in file1:
        file1_data.append(line.strip().split("\t"))
    file1_headers = file1_data[0]
    del file1_data[0]

file2_data = []

with open("File2.txt") as file2:
    for line in file2:
        file2_data.append(line.strip().split("\t"))

file2_ids = [x[0] for x in file2_data]

final_data = [file1_headers] + file1_data

for i in range(1, len(final_data)):
    if final_data[i][0] in file2_ids:
        match = [x for x in file2_data if x[0] == final_data[i][0]]
        final_data[i] = [match[0] + [final_data[i][3]]]

with open("output.txt", "w") as output:
    output.writelines(["\t".join(x) for x in final_data])
```

final_data becomes an alias of file1_data and then is selectively replacing rows with matching id's in file2_data, but keeping the country.

Body:
There are two files. If the ID number matches both files, then I want only the value 1 and value 2 from File2.txt , Please let me know if my question is unclear

File1.txt

ID Number   Value 1     Value 2     Country
0001        23            55        Spain
0231        15            23        USA
4213        10            11        Canada
7541        32            29        Italy

File2.txt

0001        5       6
0231        7       18
4213        54      87
5554        12      10
1111        31      13
6422        66      51

The output should look like this.

ID Number   Value 1     Value 2     Country
0001          5           6         Spain
0231          7          18         USA
4213          54         87         Canada
7541          32         29         Italy

New example:

File3.txt

#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.739000  -114.635700
01711 CX 21 --   3  32.779700  -115.567500
08433 CX 21 --   2  31.919930  -123.321000

File4.txt

20022,32.45,-114.88
01192,32.839,-115.487
01711,32.88,-115.45
01218,32.717,-115.637

output
#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.45  -114.88
01711 CX 21 --   3  32.88  -115.45
08433 CX 21 --   2  31.919930  -123.321000

Code I got so far

f = open("File3.txt", "r")
x= open("File4.txt","r")

df1 = pd.read_csv(f, sep=' ', engine='python')
df2 = pd.read_csv(x, sep=' ', header=None, engine='python')

df2 = df2.set_index(0).rename_axis("#ID")
df2 = df2.rename(columns={5:'LATITUDE', 6: 'LONGITUDE'})
df1 = df1.set_index('#ID')
df1.update(df2)
print(df1)

Body:
Something like this, possibly:

file1_data = []
file1_headers = []

with open("File1.txt") as file1:
    for line in file1:
        file1_data.append(line.strip().split("\t"))
    file1_headers = file1_data[0]
    del file1_data[0]

file2_data = []

with open("File2.txt") as file2:
    for line in file2:
        file2_data.append(line.strip().split("\t"))

file2_ids = [x[0] for x in file2_data]

final_data = [file1_headers] + file1_data

for i in range(1, len(final_data)):
    if final_data[i][0] in file2_ids:
        match = [x for x in file2_data if x[0] == final_data[i][0]]
        final_data[i] = [match[0] + [final_data[i][3]]]

with open("output.txt", "w") as output:
    output.writelines(["\t".join(x) for x in final_data])

final_data becomes an alias of file1_data and then is selectively replacing rows with matching id's in file2_data, but keeping the country.