问:
How to take an IntoIterator of references and return a boxed Iterator of references to the modified values?
I've grasped the basics of Rust lifetimes and how to work with iterators in it, but still have troubles to define a function that takes an iterable of tuples and return an iterable of tuples also allocated on the heap.

(I know that "iterable" doesn't mean anything in Rust but I will still use it instead of IntoInterator)

```<code>use std::iter::{once, repeat};

fn foo<'a, I>(costs: I) -> Box<Iterator<Item = &'a (i32, f32)>>
where
    I: IntoIterator<Item = &'a (usize, f32)>,
{
    let preliminary_examination_costs = once(10.0).chain(repeat(20.0));
    let id_assignment_costs = once(10.0).chain(repeat(20.0));
    let batch_fixed = once(10.0).chain(repeat(0.0));
    let temp: Vec<(usize, &(i32, f32))> = costs.into_iter().enumerate().collect();
    temp.sort_by_key(|&(_, &(n, cost))| n);
    Box::new(temp.into_iter().map(|(i, &(n, cost))| {
        (
            i,
            cost + preliminary_examination_costs.next().unwrap()
                + id_assignment_costs.next().unwrap() + batch_fixed.next().unwrap(),
        )
    }))
}
</code>```

(playground)

Here's the errors:

error[E0277]: the trait bound `std::vec::Vec<(usize, &(i32, f32))>: std::iter::FromIterator<(usize, &'a (usize, f32))>` is not satisfied
  --> src/main.rs:10:73
   |
10 |     let temp: Vec<(usize, &(i32, f32))> = costs.into_iter().enumerate().collect();
   |                                                                         ^^^^^^^ a collection of type `std::vec::Vec<(usize, &(i32, f32))>` cannot be built from an iterator over elements of type `(usize, &'a (usize, f32))`
   |
   = help: the trait `std::iter::FromIterator<(usize, &'a (usize, f32))>` is not implemented for `std::vec::Vec<(usize, &(i32, f32))>`

error[E0271]: type mismatch resolving `<[closure@src/main.rs:12:35: 18:6 preliminary_examination_costs:_, id_assignment_costs:_, batch_fixed:_] as std::ops::FnOnce<((usize, &(i32, f32)),)>>::Output == &(i32, f32)`
  --> src/main.rs:12:5
   |
12 | /     Box::new(temp.into_iter().map(|(i, &(n, cost))| {
13 | |         (
14 | |             i,
15 | |             cost + preliminary_examination_costs.next().unwrap()
16 | |                 + id_assignment_costs.next().unwrap() + batch_fixed.next().unwrap(),
17 | |         )
18 | |     }))
   | |_______^ expected tuple, found &(i32, f32)
   |
   = note: expected type `(usize, f32)`
              found type `&(i32, f32)`
   = note: required because of the requirements on the impl of `std::iter::Iterator` for `std::iter::Map<std::vec::IntoIter<(usize, &(i32, f32))>, [closure@src/main.rs:12:35: 18:6 preliminary_examination_costs:_, id_assignment_costs:_, batch_fixed:_]>`
   = note: required for the cast to the object type `std::iter::Iterator<Item=&(i32, f32)>`
```

答:
It's very useful to create a MCVE when encountering a problem, and it's something I encourage all learners to undertake. Here's one such MCVE that mirrors your code:

```<code>fn foo<'a, I>(costs: I) -> Box<Iterator<Item = &'a i32>>
where
    I: IntoIterator<Item = &'a i32>,
{
    Box::new(costs.into_iter().map(|i| i + 1))
}
</code>```

error[E0271]: type mismatch resolving `<[closure@src/main.rs:5:36: 5:45] as std::ops::FnOnce<(&'a i32,)>>::Output == &i32`
 --> src/main.rs:5:5
  |
5 |     Box::new(costs.into_iter().map(|i| i + 1))
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected i32, found &i32
  |
  = note: expected type `i32`
             found type `&i32`
  = note: required because of the requirements on the impl of `std::iter::Iterator` for `std::iter::Map<<I as std::iter::IntoIterator>::IntoIter, [closure@src/main.rs:5:36: 5:45]>`
  = note: required for the cast to the object type `std::iter::Iterator<Item=&i32>`
```

<p>You are accepting a reference then creating a brand new value based on the reference. That means that the return type is no longer a reference, thus your function signature is not upheld. You need to change it:</p>

```fn foo<'a, I>(costs: I) -> Box<Iterator<Item = i32>>
```

<p>This will unlock another error because the compiler doesn't know enough about the concrete type of <code>I::IntoIter</code>:</p>

<pre class="lang-none prettyprint-override"><code>error[E0310]: the associated type `<I as std::iter::IntoIterator>::IntoIter` may not live long enough
 --> src/main.rs:6:5
  |
6 |     Box::new(costs.into_iter().map(|i| i + 1))
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: consider adding an explicit lifetime bound `<I as std::iter::IntoIterator>::IntoIter: 'static`...
note: ...so that the type `std::iter::Map<<I as std::iter::IntoIterator>::IntoIter, [closure@src/main.rs:6:36: 6:45]>` will meet its required lifetime bounds
 --> src/main.rs:6:5
  |
6 |     Box::new(costs.into_iter().map(|i| i + 1))
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</code>```

We do as it suggests and add the 'static bound:

fn foo<'a, I>(costs: I) -> Box<Iterator<Item = i32>>
where
    I: IntoIterator<Item = &'a i32>,
    I::IntoIter: 'static,
{
    Box::new(costs.into_iter().map(|i| i + 1))
}
```

<p>See also:</p>

<ul>
<li>Is there any way to return a reference to a variable created in a function?</li>
</ul>

<hr>

<pre class="lang-none prettyprint-override"><code>error[E0277]: the trait bound `std::vec::Vec<(usize, &(i32, f32))>: std::iter::FromIterator<(usize, &'a (usize, f32))>` is not satisfied
</code>```

This error is because you have an iterator of (usize, &'a (usize, f32)) and you are trying to make them into (usize, &(i32, f32)). You can't convert types like this.

Body:
I've grasped the basics of Rust lifetimes and how to work with iterators in it, but still have troubles to define a function that takes an iterable of tuples and return an iterable of tuples also allocated on the heap.

(I know that "iterable" doesn't mean anything in Rust but I will still use it instead of IntoInterator)

use std::iter::{once, repeat};

fn foo<'a, I>(costs: I) -> Box<Iterator<Item = &'a (i32, f32)>>
where
    I: IntoIterator<Item = &'a (usize, f32)>,
{
    let preliminary_examination_costs = once(10.0).chain(repeat(20.0));
    let id_assignment_costs = once(10.0).chain(repeat(20.0));
    let batch_fixed = once(10.0).chain(repeat(0.0));
    let temp: Vec<(usize, &(i32, f32))> = costs.into_iter().enumerate().collect();
    temp.sort_by_key(|&(_, &(n, cost))| n);
    Box::new(temp.into_iter().map(|(i, &(n, cost))| {
        (
            i,
            cost + preliminary_examination_costs.next().unwrap()
                + id_assignment_costs.next().unwrap() + batch_fixed.next().unwrap(),
        )
    }))
}

(playground)

Here's the errors:

error[E0277]: the trait bound `std::vec::Vec<(usize, &(i32, f32))>: std::iter::FromIterator<(usize, &'a (usize, f32))>` is not satisfied
  --> src/main.rs:10:73
   |
10 |     let temp: Vec<(usize, &(i32, f32))> = costs.into_iter().enumerate().collect();
   |                                                                         ^^^^^^^ a collection of type `std::vec::Vec<(usize, &(i32, f32))>` cannot be built from an iterator over elements of type `(usize, &'a (usize, f32))`
   |
   = help: the trait `std::iter::FromIterator<(usize, &'a (usize, f32))>` is not implemented for `std::vec::Vec<(usize, &(i32, f32))>`

error[E0271]: type mismatch resolving `<[closure@src/main.rs:12:35: 18:6 preliminary_examination_costs:_, id_assignment_costs:_, batch_fixed:_] as std::ops::FnOnce<((usize, &(i32, f32)),)>>::Output == &(i32, f32)`
  --> src/main.rs:12:5
   |
12 | /     Box::new(temp.into_iter().map(|(i, &(n, cost))| {
13 | |         (
14 | |             i,
15 | |             cost + preliminary_examination_costs.next().unwrap()
16 | |                 + id_assignment_costs.next().unwrap() + batch_fixed.next().unwrap(),
17 | |         )
18 | |     }))
   | |_______^ expected tuple, found &(i32, f32)
   |
   = note: expected type `(usize, f32)`
              found type `&(i32, f32)`
   = note: required because of the requirements on the impl of `std::iter::Iterator` for `std::iter::Map<std::vec::IntoIter<(usize, &(i32, f32))>, [closure@src/main.rs:12:35: 18:6 preliminary_examination_costs:_, id_assignment_costs:_, batch_fixed:_]>`
   = note: required for the cast to the object type `std::iter::Iterator<Item=&(i32, f32)>`

Body:
It's very useful to create a MCVE when encountering a problem, and it's something I encourage all learners to undertake. Here's one such MCVE that mirrors your code:

fn foo<'a, I>(costs: I) -> Box<Iterator<Item = &'a i32>>
where
    I: IntoIterator<Item = &'a i32>,
{
    Box::new(costs.into_iter().map(|i| i + 1))
}

error[E0271]: type mismatch resolving `<[closure@src/main.rs:5:36: 5:45] as std::ops::FnOnce<(&'a i32,)>>::Output == &i32`
 --> src/main.rs:5:5
  |
5 |     Box::new(costs.into_iter().map(|i| i + 1))
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected i32, found &i32
  |
  = note: expected type `i32`
             found type `&i32`
  = note: required because of the requirements on the impl of `std::iter::Iterator` for `std::iter::Map<<I as std::iter::IntoIterator>::IntoIter, [closure@src/main.rs:5:36: 5:45]>`
  = note: required for the cast to the object type `std::iter::Iterator<Item=&i32>`

You are accepting a reference then creating a brand new value based on the reference. That means that the return type is no longer a reference, thus your function signature is not upheld. You need to change it:

fn foo<'a, I>(costs: I) -> Box<Iterator<Item = i32>>

This will unlock another error because the compiler doesn't know enough about the concrete type of I::IntoIter:

error[E0310]: the associated type `<I as std::iter::IntoIterator>::IntoIter` may not live long enough
 --> src/main.rs:6:5
  |
6 |     Box::new(costs.into_iter().map(|i| i + 1))
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: consider adding an explicit lifetime bound `<I as std::iter::IntoIterator>::IntoIter: 'static`...
note: ...so that the type `std::iter::Map<<I as std::iter::IntoIterator>::IntoIter, [closure@src/main.rs:6:36: 6:45]>` will meet its required lifetime bounds
 --> src/main.rs:6:5
  |
6 |     Box::new(costs.into_iter().map(|i| i + 1))
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

We do as it suggests and add the 'static bound:

fn foo<'a, I>(costs: I) -> Box<Iterator<Item = i32>>
where
    I: IntoIterator<Item = &'a i32>,
    I::IntoIter: 'static,
{
    Box::new(costs.into_iter().map(|i| i + 1))
}

See also:

Is there any way to return a reference to a variable created in a function?

error[E0277]: the trait bound `std::vec::Vec<(usize, &(i32, f32))>: std::iter::FromIterator<(usize, &'a (usize, f32))>` is not satisfied

This error is because you have an iterator of (usize, &'a (usize, f32)) and you are trying to make them into (usize, &(i32, f32)). You can't convert types like this.


来源: stackexchange

问:
Get JS date format string
For our Angular 4 application I'm using ngx-translate with messageformat.js for handling internationalization and localization. Is it possible to get the format string of shortdate of a date object ie. 'YYYY-MM-dd'?

ie: new Date().formatString('en-US') returns: 'YYYY-MM-dd'

答:
```<code>const pipe: DatePipe = new DatePipe(locale) //en-Ukr
return pipe.transform(value, 'y-MM-DD') // value = new Date()
'2017-12-04'
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get JS date format string


问:
log4net is not logging to log file or console (external log4net.config file)
I created a a file called log4net.config in my project and added the following configuration:

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="console" />
      <appender-ref ref="RollingFileAppender" />
    </root>
    <appender name="console" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="${LOCALAPPDATA}\MyApp\LogFile.log" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%-5level [%d{yyyy-MM-dd hh:mm:ss}] [%thread] (Line:%line) %M: - %m%n" />
      </layout>
    </appender>
  </log4net>
</configuration>
</code>```

After that, I added the line below to my AssemblyInfo.cs file:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

In the application, I have the following static class:

```<code>public static class Logger
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static void LogInfo(string msg)
        {
            log.Info(msg);
        }

        public static void LogDebug(string msg)
        {
            log.Debug(msg);
        }

        public static void LogWarn(string msg, Exception e)
        {
            log.Warn(msg, e);
        }

        public static void LogError(string msg, Exception e)
        {
            log.Error(msg, e);
        }
    }
</code>```

Then I'm trying to log somewhere in the application in another class using Logger.LogDebug("Error logger working.");

However, I can't see any log file being created or written to it. What am I doing wrong?

UPDATE:

I also added the following in my app.config file but I see nothing at all on my Output console...

```<code><appSettings>
    <add key="log4net.Internal.Debug" value="true"/>
</appSettings>
</code>```

答:
I could not reproduce your mistake. Configure log4net in AssemblyInfo  works fine. maybe the problem in configuration. let me show you another implementation </p>

```<code>    private static readonly ILog log = LogManager.GetLogger("myLogger");
    private static string configFile = "log4net.config";
    static Logger()
    {
        XmlConfigurator.Configure(new FileInfo(configFile));
    }
</code>```

<p>log4net.config: </p>

```<code><log4net>
<logger name="myLogger">
  <level value="ALL" />
  <appender-ref ref="console" />
  <appender-ref ref="RollingFileAppender" />
</logger>
<appender name="console" type="log4net.Appender.ConsoleAppender">
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %level %logger - %message%newline" />
  </layout>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
  <param name="File" value="${LOCALAPPDATA}\MyApp\LogFile.log" />
  <param name="AppendToFile" value="true" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="10MB" />
  <staticLogFileName value="true" />
  <layout type="log4net.Layout.PatternLayout">
    <param name="ConversionPattern" value="%-5level [%d{yyyy-MM-dd hh:mm:ss}] [%thread] (Line:%line) %M: - %m%n" />
  </layout>
</appender>
</log4net>
</code>```

Body:
I created a a file called log4net.config in my project and added the following configuration:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

  </configSections>
  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="console" />
      <appender-ref ref="RollingFileAppender" />
    </root>
    <appender name="console" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="${LOCALAPPDATA}\MyApp\LogFile.log" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%-5level [%d{yyyy-MM-dd hh:mm:ss}] [%thread] (Line:%line) %M: - %m%n" />
      </layout>
    </appender>
  </log4net>
</configuration>

After that, I added the line below to my AssemblyInfo.cs file:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

In the application, I have the following static class:

public static class Logger
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static void LogInfo(string msg)
        {
            log.Info(msg);
        }

        public static void LogDebug(string msg)
        {
            log.Debug(msg);
        }

        public static void LogWarn(string msg, Exception e)
        {
            log.Warn(msg, e);
        }

        public static void LogError(string msg, Exception e)
        {
            log.Error(msg, e);
        }
    }

Then I'm trying to log somewhere in the application in another class using Logger.LogDebug("Error logger working.");

However, I can't see any log file being created or written to it. What am I doing wrong?

UPDATE:

I also added the following in my app.config file but I see nothing at all on my Output console...

<appSettings>
    <add key="log4net.Internal.Debug" value="true"/>
</appSettings>

Body:
I could not reproduce your mistake. Configure log4net in AssemblyInfo  works fine. maybe the problem in configuration. let me show you another implementation

    private static readonly ILog log = LogManager.GetLogger("myLogger");
    private static string configFile = "log4net.config";
    static Logger()
    {
        XmlConfigurator.Configure(new FileInfo(configFile));
    }

log4net.config:

<log4net>
<logger name="myLogger">
  <level value="ALL" />
  <appender-ref ref="console" />
  <appender-ref ref="RollingFileAppender" />
</logger>
<appender name="console" type="log4net.Appender.ConsoleAppender">
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %level %logger - %message%newline" />
  </layout>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
  <param name="File" value="${LOCALAPPDATA}\MyApp\LogFile.log" />
  <param name="AppendToFile" value="true" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="10MB" />
  <staticLogFileName value="true" />
  <layout type="log4net.Layout.PatternLayout">
    <param name="ConversionPattern" value="%-5level [%d{yyyy-MM-dd hh:mm:ss}] [%thread] (Line:%line) %M: - %m%n" />
  </layout>
</appender>
</log4net>


问:
Search for a string in a text file, and output the line after the string searched for
I am looking for a solution for searching a text file for a string let's say "Hello" and each time it finds "Hello" in the text file, it skips to the next line and prints that entire line into a new text file

example Text file contents:

```
Hello
password:xxxxx user:xxxxx
Foo
password:xxxx user:xxxxxx
Foo
password:xxxxx user:xxxxx
Hello
password:xxxxx user:xxxxx
Foo
password:xxxx user:xxxx
```

答:
try this:</p>

```<code>  if {[string match $::StringToFind $line]} {
  continue
 }
</code>```

Body:
I am looking for a solution for searching a text file for a string let's say "Hello" and each time it finds "Hello" in the text file, it skips to the next line and prints that entire line into a new text file

example Text file contents:

Hello
password:xxxxx user:xxxxx
Foo
password:xxxx user:xxxxxx
Foo
password:xxxxx user:xxxxx
Hello
password:xxxxx user:xxxxx
Foo
password:xxxx user:xxxx

Body:
try this:

  if {[string match $::StringToFind $line]} {
  continue
 }


问:
Removing /EHsc from single target
I have CMake project with multi targets. One of them is CLR wrapper for native C++ code. I want to disable the /EHsc flag for only this target. I tried:

```<code>get_target_property(MYPROPS ${DOT_NET_WRAPPER_NAME} COMPILE_FLAGS)
message(${MYPROPS})
STRING( REPLACE "/EHsc" "" MYPROPS ${MYPROPS})
set_target_properties(${DOT_NET_WRAPPER_NAME} PROPERTIES COMPILE_FLAGS ${MYPROPS})
</code>```

It prints : MYPROPS-NOTFOUND

What did I miss?

答:
Firstly, COMPILE_FLAGS is deprecated, its written in the property documentation. Use COMPILE_OPTIONS instead.

Secondly, the problem might occur due to not quoting strings. I cannot reproduce when quoting:

```<code>project(demo LANGUAGES C)

file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/a.c"
    [[
    #include <stdio.h>
    int main(void) { printf("a\n"); return 0; }
    ]])

add_executable(A "${CMAKE_CURRENT_BINARY_DIR}/a.c")

target_compile_options(A PRIVATE "/EHsc")

get_property(options TARGET A PROPERTY COMPILE_OPTIONS)
message("Initial COMPILE_OPTIONS: ${options}")

string(REPLACE "/EHsc" "" new_options "${options}")

set_property(TARGET A PROPERTY COMPILE_OPTIONS "${new_options}")

get_property(options TARGET A PROPERTY COMPILE_OPTIONS)
message("New COMPILE_OPTIONS: ${options}")
</code>```

The above produces

```<code>Initial COMPILE_OPTIONS: /EHsc
New COMPILE_OPTIONS:
-- Configuring done
-- Generating done
-- Build files have been written to: <...>
</code>```

Title: Removing /EHsc from single target

Body:
I have CMake project with multi targets. One of them is CLR wrapper for native C++ code. I want to disable the /EHsc flag for only this target. I tried:

get_target_property(MYPROPS ${DOT_NET_WRAPPER_NAME} COMPILE_FLAGS)
message(${MYPROPS})
STRING( REPLACE "/EHsc" "" MYPROPS ${MYPROPS})
set_target_properties(${DOT_NET_WRAPPER_NAME} PROPERTIES COMPILE_FLAGS ${MYPROPS})

It prints : MYPROPS-NOTFOUND

What did I miss?

Body:
Firstly, COMPILE_FLAGS is deprecated, its written in the property documentation. Use COMPILE_OPTIONS instead.

Secondly, the problem might occur due to not quoting strings. I cannot reproduce when quoting:

project(demo LANGUAGES C)

file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/a.c"
    [[
    #include <stdio.h>
    int main(void) { printf("a\n"); return 0; }
    ]])

add_executable(A "${CMAKE_CURRENT_BINARY_DIR}/a.c")

target_compile_options(A PRIVATE "/EHsc")

get_property(options TARGET A PROPERTY COMPILE_OPTIONS)
message("Initial COMPILE_OPTIONS: ${options}")

string(REPLACE "/EHsc" "" new_options "${options}")

set_property(TARGET A PROPERTY COMPILE_OPTIONS "${new_options}")

get_property(options TARGET A PROPERTY COMPILE_OPTIONS)
message("New COMPILE_OPTIONS: ${options}")

The above produces

Initial COMPILE_OPTIONS: /EHsc
New COMPILE_OPTIONS:
-- Configuring done
-- Generating done
-- Build files have been written to: <...>


问:
How to check if my iPhone app is hacked/cracked?
I'm wondering if there are some ways to check if my application is hacked?

I mean, I don't really want to prevent my application from hacking, but I would like to list all iPhone (UUID) that use my hacked application.

答:
Check to see if encryption was removed from you app bundle or any other changes were made.

If you don't prevent your app from being cracked by any different behavior, such as not working, this makes your detection code much harder to find.

ContentLicense: CC BY-SA 2.5


问:
Fetch data with Vue from Web API
I have a Web API and I'm trying to get JSON Data from it by using Vue, but I get neither data or errors, so I don't what is wrong. I want to load the data when the page is loaded.

Here is my code:

```<code>const v = new Vue({
    el: '#divContent',
    ready: function () {
        this.loadData();
    },
    data: {
        content: 'loading',
        serverData: null
    },
    methods: {
        loadData: function (viewerUserId, posterUserId) {
            const that = this;
            $.ajax({
                contentType: "application/json",
                dataType: "json",
                url: "http://my-webapi/",
                method: "Post",
                success: function (response) {
                    that.$data.serverData = response;

                },
                error: function () {
                    alert('Error')
                }
            });
        }
    }
});
</code>```

My HTML

```<code><div id="divContent" class="content">
 {{ content }}
</div>
</code>```

答:
Anything your put inside methods: {} won't work
unless you call loadData() with  @click on the element or when page loads.

So, you should call it on the element or using either created/mount methods:

So, in your case either do this.

```<code><div id="divContent" class="content" @click='loadData'>
</code>```

or call the method when the page loads as:

```<code>created () {
 this.loadData()
}
</code>```

Title: Fetch data with Vue from Web API

Body:
I have a Web API and I'm trying to get JSON Data from it by using Vue, but I get neither data or errors, so I don't what is wrong. I want to load the data when the page is loaded.

Here is my code:

const v = new Vue({
    el: '#divContent',
    ready: function () {
        this.loadData();
    },
    data: {
        content: 'loading',
        serverData: null
    },
    methods: {
        loadData: function (viewerUserId, posterUserId) {
            const that = this;
            $.ajax({
                contentType: "application/json",
                dataType: "json",
                url: "http://my-webapi/",
                method: "Post",
                success: function (response) {
                    that.$data.serverData = response;

                },
                error: function () {
                    alert('Error')
                }
            });
        }
    }
});

My HTML

 {{ content }}

Body:
Anything your put inside methods: {} won't work
unless you call loadData() with  @click on the element or when page loads.

So, you should call it on the element or using either created/mount methods:

So, in your case either do this.

<div id="divContent" class="content" @click='loadData'>

or call the method when the page loads as:

created () {
 this.loadData()
}


问:
Set StashNotifier with Groovy
I am trying to add the StashNotifier configuration to Jenkins via Groovy

```<code>import jenkins.model.*;
import org.jenkinsci.plugins.stashNotifier.*

def instance = Jenkins.getInstance()
def bitbucket = instance.getDescriptor(StashNotifier)

println "--> configure Stash Notifier..."

def bitBucketNotifier = new StashNotifier (
    "https://servername:8443", //stashServerBaseUrl
    "user", //credentialsId
    false,  //ignoreUnverifiedSSLPeer
    "",  //commitSha1
    false,  //includeBuildNumberInKey
    "",  //projectKey
    false, //prependParentProjectKey
    false //disableInprogressNotification
)

bitbucket.save()
println "--> configure Stash Notifier... done"
</code>```

The xml configuration I am trying to implement is

```<code><?xml version='1.0' encoding='UTF-8'?>
<org.jenkinsci.plugins.stashNotifier.StashNotifier_-DescriptorImpl plugin="stashNotifier@1.11.6">
  <credentialsId>user</credentialsId>
  <stashRootUrl>https://servername:8443/</stashRootUrl>
  <ignoreUnverifiedSsl>false</ignoreUnverifiedSsl>
  <includeBuildNumberInKey>false</includeBuildNumberInKey>
  <prependParentProjectKey>false</prependParentProjectKey>
  <disableInprogressNotification>false</disableInprogressNotification>
</org.jenkinsci.plugins.stashNotifier.StashNotifier_-DescriptorImpl>
</code>```

I am new to Java and groovy, but I cannot get this to work. I feel I am close, probably missing one or two little bits.

I am trying to get Jenkins to configure upon start-up and then reconfigure itself if any changes are made to core integrations. In this case, the BitBucket server won't change but if users do make the change to point at something else, Jenkins is reconfigured to point at the correct thing

答:
I've done something like that :

```<code>#!groovy
import jenkins.model.*;
import org.jenkinsci.plugins.*;
import net.sf.json.JSONObject;

String url = 'https://stashblablablabla';
String credentials = '01111111-e222-3333-eeff-4f4444e44bc4';

def j = Jenkins.getInstance();

def stash = j.getExtensionList(
  stashNotifier.StashNotifier.DescriptorImpl.class)[0];

def formData = [
  stashRootUrl: url,
  credentialsId: credentials,
  ignoreUnverifiedSsl: false,
  includeBuildNumberInKey: false,
  prependParentProjectKey: false,
  disableInprogressNotification: false,
  considerUnstableAsSuccess: false
] as JSONObject;

stash.configure(null, formData);
j.save();
</code>```

I've figured that solution out reading that:

https://github.com/jenkinsci/stashnotifier-plugin/blob/release/1.x/src/main/java/org/jenkinsci/plugins/stashNotifier/StashNotifier.java

https://github.com/samrocketman/jenkins-bootstrap-slack/blob/master/scripts/configure-slack.groovy

It appears to be working in my test platform.

Title: Set StashNotifier with Groovy

Body:
I am trying to add the StashNotifier configuration to Jenkins via Groovy

import jenkins.model.*;
import org.jenkinsci.plugins.stashNotifier.*

def instance = Jenkins.getInstance()
def bitbucket = instance.getDescriptor(StashNotifier)

println "--> configure Stash Notifier..."

def bitBucketNotifier = new StashNotifier (
    "https://servername:8443", //stashServerBaseUrl
    "user", //credentialsId
    false,  //ignoreUnverifiedSSLPeer
    "",  //commitSha1
    false,  //includeBuildNumberInKey
    "",  //projectKey
    false, //prependParentProjectKey
    false //disableInprogressNotification
)

bitbucket.save()
println "--> configure Stash Notifier... done"

The xml configuration I am trying to implement is

<?xml version='1.0' encoding='UTF-8'?>
<org.jenkinsci.plugins.stashNotifier.StashNotifier_-DescriptorImpl plugin="stashNotifier@1.11.6">
  <credentialsId>user</credentialsId>
  <stashRootUrl>https://servername:8443/</stashRootUrl>
  <ignoreUnverifiedSsl>false</ignoreUnverifiedSsl>
  <includeBuildNumberInKey>false</includeBuildNumberInKey>
  <prependParentProjectKey>false</prependParentProjectKey>
  <disableInprogressNotification>false</disableInprogressNotification>
</org.jenkinsci.plugins.stashNotifier.StashNotifier_-DescriptorImpl>

I am new to Java and groovy, but I cannot get this to work. I feel I am close, probably missing one or two little bits.

I am trying to get Jenkins to configure upon start-up and then reconfigure itself if any changes are made to core integrations. In this case, the BitBucket server won't change but if users do make the change to point at something else, Jenkins is reconfigured to point at the correct thing

Body:
I've done something like that :

#!groovy
import jenkins.model.*;
import org.jenkinsci.plugins.*;
import net.sf.json.JSONObject;

String url = 'https://stashblablablabla';
String credentials = '01111111-e222-3333-eeff-4f4444e44bc4';

def j = Jenkins.getInstance();

def stash = j.getExtensionList(
  stashNotifier.StashNotifier.DescriptorImpl.class)[0];

def formData = [
  stashRootUrl: url,
  credentialsId: credentials,
  ignoreUnverifiedSsl: false,
  includeBuildNumberInKey: false,
  prependParentProjectKey: false,
  disableInprogressNotification: false,
  considerUnstableAsSuccess: false
] as JSONObject;

stash.configure(null, formData);
j.save();

I've figured that solution out reading that:

https://github.com/jenkinsci/stashnotifier-plugin/blob/release/1.x/src/main/java/org/jenkinsci/plugins/stashNotifier/StashNotifier.java

https://github.com/samrocketman/jenkins-bootstrap-slack/blob/master/scripts/configure-slack.groovy

It appears to be working in my test platform.


问:
Adding post parameters to request before making the request go somewhere else in Java
In a JSP page, I need to do the following (this is psuedo-code):

```<code>//Attach new POST params to request
//Make the request go to a 3rd party URL
</code>```

How do I do this?

The way we are solving this right now (is terrible):

```<code>//populate and generate an HTML form
//on window.load submit the HTML form (as a POST) to a 3rd party URL
</code>```

We want all this to be done on the server side instead of having this JS hack

答: You can use URLConnection to make POST request, here is an example

Body:
In a JSP page, I need to do the following (this is psuedo-code):

//Attach new POST params to request
//Make the request go to a 3rd party URL

How do I do this?

The way we are solving this right now (is terrible):

//populate and generate an HTML form
//on window.load submit the HTML form (as a POST) to a 3rd party URL

We want all this to be done on the server side instead of having this JS hack


问:
Sorting a list of lists based on the third element
I've got an object names x which is a list containing inner lists.

```<code>`x$population`

output
[[1]]
[[1]][[1]]
[1] 1

[[1]][[2]]
[1] 11

[[1]][[3]]
[1] 1

[[2]]
[[2]][[1]]
[1] 1

[[2]][[2]]
[1] 20

[[2]][[3]]
[1] 2
</code>```

I want to be able to sort the list based on the third elements:
x$population[[2]][[3]] but I have no idea how to do it.

I have no idea how to start so instead of got some mock code that re-creates the problem:

```<code>z <- list()

z[[1]] <- list(1, 10, 0.5)
z[[2]] <- list(1, 10, 0.87)
</code>```

How would I go about sorting z based on the third elements of each list (0.5, 0.87) such that the larger value is at the top.

Thanks in advance.

答:
To do it explicitly: I would extract the third element and sort it.

I create a more complex list:

```<code>z <- list()

z[[1]] <- list(1, 10, 0.5)
z[[2]] <- list(1, 10, 0.87)
z[[3]] <- list(1, 10, 0.2)
</code>```

I extract third element of each element:

```<code>thirdelt <- sapply(z, function(x)x[[3]])
</code>```

Then I sort it:

```<code>thirdelt_order <- order(thirdelt)
</code>```

Finaly I apply it:

```<code>z <- z[thirdelt_order]
</code>```

Body:
I've got an object names x which is a list containing inner lists.

`x$population`

output
[[1]]
[[1]][[1]]
[1] 1

[[1]][[2]]
[1] 11

[[1]][[3]]
[1] 1

[[2]]
[[2]][[1]]
[1] 1

[[2]][[2]]
[1] 20

[[2]][[3]]
[1] 2

I want to be able to sort the list based on the third elements:
x$population[[2]][[3]] but I have no idea how to do it.

I have no idea how to start so instead of got some mock code that re-creates the problem:

z <- list()

z[[1]] <- list(1, 10, 0.5)
z[[2]] <- list(1, 10, 0.87)

How would I go about sorting z based on the third elements of each list (0.5, 0.87) such that the larger value is at the top.

Thanks in advance.

Body:
To do it explicitly: I would extract the third element and sort it.

I create a more complex list:

z <- list()

z[[1]] <- list(1, 10, 0.5)
z[[2]] <- list(1, 10, 0.87)
z[[3]] <- list(1, 10, 0.2)

I extract third element of each element:

thirdelt <- sapply(z, function(x)x[[3]])

Then I sort it:

thirdelt_order <- order(thirdelt)

Finaly I apply it:

z <- z[thirdelt_order]


问:
Common SQL query in Zend-Framework
How i can use a sql-query code that i already have on Zend-Framework using Model and Controller?

I'm tried of many ways and i can't solve this.

This is a example of "common sql-query code" to test:
"SELECT id_arquivos_retorno FROM sa_arquivos_retorno LIMIT 100"

*My original code it's a big query and it's terrible transform to a zend-select()

This is my Model:

```<code>class PedidosInscricoesModel extends Zend_Db_Table_Abstract{

protected $_name = 'sa_arquivos_retorno';

public function getPedidosInscricoes(array $params) {

$this->_db = Zend_Registry::get('db2');

$session = new Zend_Session_Namespace('autenticacao');

    $query =    $this->query("SELECT id_arquivos_retorno FROM sa_arquivos_retorno LIMIT 100");

    $retorno = $this->fetchAll($query)->toArray();

    return $retorno;
}}
</code>```

And That's my Controller:

```<code>public function indexAction()
{
    $PedidosInscricoesModel = new PedidosInscricoesModel();

    $this->view->id_arquivos_retorno = $_REQUEST['id_arquivos_retorno'];

    $params = $this->_request->getParams();
    $data = $PedidosInscricoesModel->getPedidosInscricoes($params);

    $this->view->data = $retorno;
}
</code>```

My index view:

```<code><?php
    foreach($this->data as $dados) {
?>
        <tr>
            <td><?php echo $dados["id_arquivos_retorno"]; ?></td>
        </tr>
<?php
    }
?>
</code>```

-Sorry for bad english guys

答:
I got it!
Just modifying the Model using "zend_db_statement" in this way:

```<code>class PedidosInscricoesModel extends Zend_Db_Table_Abstract{

public function getPedidosInscricoes()
{

    $db = Zend_Registry::get('db2');

    $sql = "SELECT id_arquivos_retorno FROM sa_arquivos_retorno LIMIT 20";

    $stmt = $db->query($sql);

    $retorno = $stmt->fetchAll();

    return $retorno;
}
}
</code>```

Title: Common SQL query in Zend-Framework

Body:
How i can use a sql-query code that i already have on Zend-Framework using Model and Controller?

I'm tried of many ways and i can't solve this.

This is a example of "common sql-query code" to test:
"SELECT id_arquivos_retorno FROM sa_arquivos_retorno LIMIT 100"

*My original code it's a big query and it's terrible transform to a zend-select()

This is my Model:

class PedidosInscricoesModel extends Zend_Db_Table_Abstract{

protected $_name = 'sa_arquivos_retorno';

public function getPedidosInscricoes(array $params) {

$this->_db = Zend_Registry::get('db2');

$session = new Zend_Session_Namespace('autenticacao');

    $query =    $this->query("SELECT id_arquivos_retorno FROM sa_arquivos_retorno LIMIT 100");

    $retorno = $this->fetchAll($query)->toArray();

    return $retorno;
}}

And That's my Controller:

public function indexAction()
{
    $PedidosInscricoesModel = new PedidosInscricoesModel();

    $this->view->id_arquivos_retorno = $_REQUEST['id_arquivos_retorno'];

    $params = $this->_request->getParams();
    $data = $PedidosInscricoesModel->getPedidosInscricoes($params);

    $this->view->data = $retorno;
}

My index view:

<?php
    foreach($this->data as $dados) {
?>

            <?php echo $dados["id_arquivos_retorno"]; ?>

<?php
    }
?>

-Sorry for bad english guys

Body:
I got it!
Just modifying the Model using "zend_db_statement" in this way:

class PedidosInscricoesModel extends Zend_Db_Table_Abstract{

public function getPedidosInscricoes()
{

    $db = Zend_Registry::get('db2');

    $sql = "SELECT id_arquivos_retorno FROM sa_arquivos_retorno LIMIT 20";

    $stmt = $db->query($sql);

    $retorno = $stmt->fetchAll();

    return $retorno;
}
}


问:
Device Orientation and Motion on Webview and Chrome
I'm developing an application that lauches a webview that needs to acces the devices's orientation and motion.
I have a few devices with different Android versions, listed below, and I have different behaviours.

On all devices I can access the devices's orientation on the webview and on Chrome.
The problem is that on some devices I can't access the device's motion on the webview but I can access them on Chrome.
Here's the list:

```<code>|=======================================================================|
|     Device      | Samsung Galxy   | Vodafone Smart | Samsung Galxy S6 |
|                 |    S4 mini      |    Prime 6     |                  |
|=======================================================================|
| Android Version |       4.4.4     |       5.0.2    |       7.0        |
|=======================================================================|
|                            Device Motion                              |
|-----------------+------------------+----------------+-----------------|
|    Webview      |         X        |                |                 |
|-----------------+------------------+----------------+-----------------|
|    Chrome       |         X        |        X       |         X       |
|=======================================================================|
</code>```

I use to following link to test the device's orientation and motion:
http://code.viget.com/device-motion-demo/

Is there any reason that it works on Android 4.4.4 and it doesn't on Android 5 and greater versions?

Must I add any configuration when I initialize the webview?

Thanks.

答:
So, it seems that there is a bug on the webview.

https://bugs.chromium.org/p/chromium/issues/detail?id=779443

I uninstalled the webview's updates and I get the device's motion events.

Body:
I'm developing an application that lauches a webview that needs to acces the devices's orientation and motion.
I have a few devices with different Android versions, listed below, and I have different behaviours.

On all devices I can access the devices's orientation on the webview and on Chrome.
The problem is that on some devices I can't access the device's motion on the webview but I can access them on Chrome.
Here's the list:

|=======================================================================|
|     Device      | Samsung Galxy   | Vodafone Smart | Samsung Galxy S6 |
|                 |    S4 mini      |    Prime 6     |                  |
|=======================================================================|
| Android Version |       4.4.4     |       5.0.2    |       7.0        |
|=======================================================================|
|                            Device Motion                              |
|-----------------+------------------+----------------+-----------------|
|    Webview      |         X        |                |                 |
|-----------------+------------------+----------------+-----------------|
|    Chrome       |         X        |        X       |         X       |
|=======================================================================|

I use to following link to test the device's orientation and motion:
http://code.viget.com/device-motion-demo/

Is there any reason that it works on Android 4.4.4 and it doesn't on Android 5 and greater versions?

Must I add any configuration when I initialize the webview?

Thanks.


问:
Twitter API responds with "Your credentials do not allow access to this resource" while calling statuses/update.json
I'm using Hybridauth 3 in my PHP app to make some periodical tweets on behalf of my account.
The app has all possible permissions. I'm giving it all permissions when it asks for them on the first auth step.
After that Twitter redirects me to the specified callback URL and there I'm getting a pair of access_token and access_token_secret.
But when I'm trying to make a tweet using these tokens - it gives me:

```<code>{"errors":[{"code":220,"message":"Your credentials do not allow access to this resource."}]}
</code>```

Here's how I'm trying to make a tweet:

```<code>$config = [
    'authentication_parameters' => [
    //Location where to redirect users once they authenticate
    'callback' => 'https://mysite/twittercallback/',
    //Twitter application credentials
    'keys' => [
            'key'     => 'xxx',
            'secret' => 'yyy'
    ],
    'authorize' => true
    ]
];

$adapter = new Hybridauth\Provider\Twitter($config['authentication_parameters']);

//Attempt to authenticate the user
$adapter->setAccessToken(/*tokens I've got from getAccessToken() on /twittercallback/*/);

if(! $adapter->isConnected()) {
    // never goes here, so adapter is connected
    return null;
}

try{
    $response = $adapter->setUserStatus('Hello world!');
}
catch (\Exception $e) {
    // here I've got the error
    echo $e->getMessage();
    return;
}
</code>```

Tried to recreate tokens and key\secret pairs and passed auth process for the app many times, including entering password for my Twitter account (as suggested in some posts on stackoverflow) but still have this error.

P.S. According to this, Hybridauth has fixed the issue in the recent release.

答: For your info setAccessToken was fixed in v3.0.0-beta.2 (see PR https://github.com/hybridauth/hybridauth/pull/880)

Body:
I'm using Hybridauth 3 in my PHP app to make some periodical tweets on behalf of my account.
The app has all possible permissions. I'm giving it all permissions when it asks for them on the first auth step.
After that Twitter redirects me to the specified callback URL and there I'm getting a pair of access_token and access_token_secret.
But when I'm trying to make a tweet using these tokens - it gives me:

{"errors":[{"code":220,"message":"Your credentials do not allow access to this resource."}]}

Here's how I'm trying to make a tweet:

$config = [
    'authentication_parameters' => [
    //Location where to redirect users once they authenticate
    'callback' => 'https://mysite/twittercallback/',
    //Twitter application credentials
    'keys' => [
            'key'     => 'xxx',
            'secret' => 'yyy'
    ],
    'authorize' => true
    ]
];

$adapter = new Hybridauth\Provider\Twitter($config['authentication_parameters']);

//Attempt to authenticate the user
$adapter->setAccessToken(/*tokens I've got from getAccessToken() on /twittercallback/*/);

if(! $adapter->isConnected()) {
    // never goes here, so adapter is connected
    return null;
}

try{
    $response = $adapter->setUserStatus('Hello world!');
}
catch (\Exception $e) {
    // here I've got the error
    echo $e->getMessage();
    return;
}

Tried to recreate tokens and key\secret pairs and passed auth process for the app many times, including entering password for my Twitter account (as suggested in some posts on stackoverflow) but still have this error.

P.S. According to this, Hybridauth has fixed the issue in the recent release.


问:
Reordering nodes in increasing order in pandas dataframe
```<code>data1 = { 'node1': [2,2,3,6],
     'node2': [6,7,7,28],
     'weight': [1,2,1,1], }
df1 = pd.DataFrame(data1, columns = ['node1','node2','weight'])
</code>```

I want to rename the node1 and node 2 in the data1 according in increasing order.
Nodes are 2 3 6 7 28 so they become 1 2 3 4 5 respectively.

So the dataframe becomes-

```<code>data1 = { 'node1': [1,1,2,3],
     'node2': [3,4,4,5],
     'weight': [1,2,1,1], }
df1 = pd.DataFrame(data1, columns = ['node1','node2','weight'])
</code>```

The data looked like this before

but now looks like this

答:
Use rank with reshape by stack and then unstack:

```<code>df2 = (df1.set_index('weight', append=True)
          .stack()
          .rank(method='dense')
          .astype(int)
          .unstack()
          .reset_index(level=1))
print (df2)
   weight  node1  node2
0       1      1      3
1       2      1      4
2       1      2      4
3       1      3      5
</code>```

Body:
data1 = { 'node1': [2,2,3,6],
     'node2': [6,7,7,28],
     'weight': [1,2,1,1], }
df1 = pd.DataFrame(data1, columns = ['node1','node2','weight'])

I want to rename the node1 and node 2 in the data1 according in increasing order.
Nodes are 2 3 6 7 28 so they become 1 2 3 4 5 respectively.

So the dataframe becomes-

data1 = { 'node1': [1,1,2,3],
     'node2': [3,4,4,5],
     'weight': [1,2,1,1], }
df1 = pd.DataFrame(data1, columns = ['node1','node2','weight'])

The data looked like this before

but now looks like this

Body:
Use rank with reshape by stack and then unstack:

df2 = (df1.set_index('weight', append=True)
          .stack()
          .rank(method='dense')
          .astype(int)
          .unstack()
          .reset_index(level=1))
print (df2)
   weight  node1  node2
0       1      1      3
1       2      1      4
2       1      2      4
3       1      3      5


问:
Possible JQuery functions to use
I am currently working on a website which has a fixed header and body and within the body is a main DIV.

For the page to change, the contents of the main DIV is changed. (Not my development)

I would like to display a notice to the user (Please wait loading) for any DB requests to the server or if the page changes. (The contents of the main DIV is changed for this to occur). Once the results from the DB has been returned or the main DIV has completed loading, I would like for the notice to be removed.

I am considering using JQuery to achieve this, by having a loader DIV within the body and for this to be visible when required and hidden when not.

What would be the best JQuery function to use to achieve my requirements?

There is no AJAX used on the site.

Many thanks

答:
Here's some pseudo-code:</p>

```<code>$(document).ready
(
    function()
    {
        $("#cmdQuery").click
        (
            function()
            {
                setProgressMessage();
                executeQuery();
            }
        );
    }
);

function setProgressMessage()
{
    // show query in progress message
}

function closeProgressMessage()
{
    // close query in progress message
}

function executeQuery()
{
    serverQuery(localCallBackFunction);
}

function localCallBackFunction(result)
{
    // process result of query
    closeProgressMessage();
}

<input type="button" id="cmdQuery" Text="Execute Query" />
</code>```

Title: Possible JQuery functions to use

Body:
Here's some pseudo-code:

$(document).ready
(
    function()
    {
        $("#cmdQuery").click
        (
            function()
            {
                setProgressMessage();
                executeQuery();
            }
        );
    }
);

function setProgressMessage()
{
    // show query in progress message
}

function closeProgressMessage()
{
    // close query in progress message
}

function executeQuery()
{
    serverQuery(localCallBackFunction);
}

function localCallBackFunction(result)
{
    // process result of query
    closeProgressMessage();
}

<input type="button" id="cmdQuery" Text="Execute Query" />


问:
Expect scripting taking user prompt
Below is my sample expect script.

```<code>#!/usr/bin/expect

set pem [lindex $argv 2]
puts -nonewline "do you want to take histogram\r"
flush stdout
gets stdin pem
if { $pem == "y" } {
    send "./statsCollector.sh\r"
} else {
    puts "aborting\r"
}
expect " bin\]\$ "
</code>```

I need user prompt like yes,Y or y to run the my script (i.e. statsCollector.sh). If user inputs anything other like this then "aborting" should be message on window.

Here user input is not working properly, also after the aborting it hangs with that same message. Please correct me if I'm doing wrong here.

答:
I'd use this:

```<code>if {[string match {y*} [string tolower [string trimleft $pem]]]} {...
</code>```

Removing leading whitespace, if the first character is "y" case insensitively, then ... do stuff

ref: https://tcl.tk/man/tcl8.6/TclCmd/string.htm

Title: Expect scripting taking user prompt

Body:
Below is my sample expect script.

#!/usr/bin/expect

set pem [lindex $argv 2]
puts -nonewline "do you want to take histogram\r"
flush stdout
gets stdin pem
if { $pem == "y" } {
    send "./statsCollector.sh\r"
} else {
    puts "aborting\r"
}
expect " bin\]\$ "

I need user prompt like yes,Y or y to run the my script (i.e. statsCollector.sh). If user inputs anything other like this then "aborting" should be message on window.

Here user input is not working properly, also after the aborting it hangs with that same message. Please correct me if I'm doing wrong here.

Body:
I'd use this:

if {[string match {y*} [string tolower [string trimleft $pem]]]} {...

Removing leading whitespace, if the first character is "y" case insensitively, then ... do stuff

ref: https://tcl.tk/man/tcl8.6/TclCmd/string.htm


问:
Can I remove the S3 bucket from my Elastic Beanstalk deployment?
Yesterday I hosted my basic web app in Elastic Beanstalk, which works fine. Now each time I deploy the app by running eb deploy, it creates a zip file which is also uploaded (together with logs) to S3. Since I have a basic app, I don't want those zip stored in S3. Is it safe enough to delete the S3 bucket from Elastic Beanstalk?

Note:
I am using Single-instance Environment

答:
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/AWSHowTo.S3.html

Not sure if the next time you do a deployment the S3 bucket will be recreated.

ContentLicense: CC BY-SA 4.0


问:
RichTextBox doesn't start selection on mouse down when the form has not focus
I'm using WinForms and on my Form I have a RichTextBox.  When my form is out of focus but visible and I try to highlight/select text, it does not allow me to until the form or textbox itself has focus.

I've tried:

```<code>txtInput.MouseDown += (s, e) => { txtInput.Focus(); }
</code>```

but to no avail and I can't seem to find anything online about this issue.

When testing with another program like Notepad, it does possess the desired behavior.

答:
This worked for me;

Extend RichTextBox and override WindowProc with this

```<code>protected override void WndProc(ref Message m) {
    const int WM_MOUSEACTIVATE = 0x21;

    if (m.Msg == WM_MOUSEACTIVATE) {
        // Take focus to enable click-through behavior for setting selection
        this.Focus();
    }

    // Let the base handle the event.
    base.WndProc(ref m);
}
</code>```

Body:
I'm using WinForms and on my Form I have a RichTextBox.  When my form is out of focus but visible and I try to highlight/select text, it does not allow me to until the form or textbox itself has focus.

I've tried:

txtInput.MouseDown += (s, e) => { txtInput.Focus(); }

but to no avail and I can't seem to find anything online about this issue.

When testing with another program like Notepad, it does possess the desired behavior.

Body:
This worked for me;

Extend RichTextBox and override WindowProc with this

protected override void WndProc(ref Message m) {
    const int WM_MOUSEACTIVATE = 0x21;

    if (m.Msg == WM_MOUSEACTIVATE) {
        // Take focus to enable click-through behavior for setting selection
        this.Focus();
    }

    // Let the base handle the event.
    base.WndProc(ref m);
}


问:
Changing CSS attribute with JQuery
Today I was shown a really simple way to change the font-size  of an element using jQuery.
It looked very similar to the following:

```<code><script  type="text/javascript">
    jQuery(document.body) ({font-size:5em;});
</script>
</code>```

This obviously doesn't work, but I was wondering what's missing? I remember it being just one line of code.

Note: I have tried jQuery(document.body).css({font-size:5em;}); as well, without success.

Thanks.

Title: Changing CSS attribute with JQuery

Body:
Today I was shown a really simple way to change the font-size  of an element using jQuery.
It looked very similar to the following:

This obviously doesn't work, but I was wondering what's missing? I remember it being just one line of code.

Note: I have tried jQuery(document.body).css({font-size:5em;}); as well, without success.

Thanks.


问:
eslint object-shorthand error with variable passed in
I have the following function that is setting up a select2 plugin, which needs selects to stay open if they are multiple but closed if they are not:

function setUpSelects($selects, closeOnSelect) {
  $selects.each((i, item) => {
    const $item = $(item);

    $item.select2({
      closeOnSelect: closeOnSelect,  // <-- error on this line
      minimumResultsForSearch: Infinity,
      placeholder: $item.data('placeholder') || $item.attr('placeholder'),
    });
  });
}

setUpSelects($('select:not([multiple])'), false);
setUpSelects($('select[multiple]'), true);
```

However, when I try to run this code, the eslint checker is giving me an error (on the line shown above) of:

error  Expected property shorthand  object-shorthand

I have done a search and read the docs but it doesn't show how you are meant to use a variable and the unaccepted answer on this question seems to think it may be a bug in eslint (although I have found no evidence to support that)

Is there a way to make this work or should I just disable the rule for that line?

答:
An excerpt from eslint regarding the issue:

Require Object Literal Shorthand Syntax (object-shorthand) - Rule Details

This rule enforces the use of the shorthand syntax. This applies to
  all methods (including generators) defined in object literals and any
  properties defined where the key name matches name of the assigned
  variable.

Change

```<code>closeOnSelect: closeOnSelect
</code>```

to just

```<code>closeOnSelect
</code>```

Body:
I have the following function that is setting up a select2 plugin, which needs selects to stay open if they are multiple but closed if they are not:

function setUpSelects($selects, closeOnSelect) {
  $selects.each((i, item) => {
    const $item = $(item);

    $item.select2({
      closeOnSelect: closeOnSelect,  // <-- error on this line
      minimumResultsForSearch: Infinity,
      placeholder: $item.data('placeholder') || $item.attr('placeholder'),
    });
  });
}

setUpSelects($('select:not([multiple])'), false);
setUpSelects($('select[multiple]'), true);

However, when I try to run this code, the eslint checker is giving me an error (on the line shown above) of:

error  Expected property shorthand  object-shorthand

I have done a search and read the docs but it doesn't show how you are meant to use a variable and the unaccepted answer on this question seems to think it may be a bug in eslint (although I have found no evidence to support that)

Is there a way to make this work or should I just disable the rule for that line?

Body:
An excerpt from eslint regarding the issue:

Require Object Literal Shorthand Syntax (object-shorthand) - Rule Details

This rule enforces the use of the shorthand syntax. This applies to
  all methods (including generators) defined in object literals and any
  properties defined where the key name matches name of the assigned
  variable.

Change

closeOnSelect: closeOnSelect

to just

closeOnSelect


问:
ngFor with index as value in attribute
I have a simple ngFor loop which also keeps track of the current index. I want to store that index value in an attribute so I can print it. But I can't figure out how this works.

I basically have this:

```<code><ul *ngFor="#item of items; #i = index" data-index="#i">
    <li>{{item}}</li>
</ul>
</code>```

I want to store the value of #i in the attribute data-index. I tried several methods but none of them worked.

I have a demo here: http://plnkr.co/edit/EXpOKAEIFlI9QwuRcZqp?p=preview

How can I store the index value in the data-index attribute?

答:
In Angular 5/6/7/8:

    {{i+1}} {{item}}

```
<hr />
<p>In older versions</p>
<pre class="lang-html prettyprint-override"><code><ul *ngFor="let item of items; let i = index">
  <li>{{i+1}} {{item}}</li>
</ul>
</code>```

Angular.io ▸ API ▸ NgForOf

Description

Local variables

Unit test examples

ng_for_spec.ts

Another interesting example

Grouping

Title: ngFor with index as value in attribute

Body:
I have a simple ngFor loop which also keeps track of the current index. I want to store that index value in an attribute so I can print it. But I can't figure out how this works.

I basically have this:

{{item}}

I want to store the value of #i in the attribute data-index. I tried several methods but none of them worked.

I have a demo here: http://plnkr.co/edit/EXpOKAEIFlI9QwuRcZqp?p=preview

How can I store the index value in the data-index attribute?

Body:
In Angular 5/6/7/8:

<ul>
  <li *ngFor="let item of items; index as i">
    {{i+1}} {{item}}
  </li>
</ul>

In older versions

<ul *ngFor="let item of items; let i = index">
  <li>{{i+1}} {{item}}</li>
</ul>

Angular.io ▸ API ▸ NgForOf

Description

Local variables

Unit test examples

ng_for_spec.ts

Another interesting example

Grouping


问:
maven - java compiler version set to older version automatically
For some reason maven automatically chooses java compiler 1.5 when building my project although I have jdk 1.8 installed

Step 1

Project -> Properties -> Java Build Path -> JRE System Library -> Edit,
and then choose "Workspace default JRE (jdk1.8.0_102)".

Step 2

Just in case I also set Eclipse -> Preferences -> Installed JREs -> JavaSE-1.8 (jdk.1.8.0_102)

What I noticed in that window: There is only J2SE-1.x where x<=5

Step 3

Then I go to `Project -> Java Compiler, where I find the compiler compliance level set to 1.5 (see screenshot). So I change "Compiler compliance level to 1.8"

When I do maven update, everything is reset to compiler compliance 1.5. If I do a mvn clean compile I also get a build failure that source is 1.5 and some of my code is not compatible.

Thanks for the help

答:
Add this in your pom.xml file under <plugins>:

```<code>      <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
      </plugin>
</code>```

Body:
Add this in your pom.xml file under <plugins>:

      <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
      </plugin>


问:
Is there any measurable overhead using ob_get_contents()?
I want to flush the contents of a WordPress function into a variable using ob_get_contents() but I've heard that there is sometimes overhead associated with it. Has anyone had any actual experience measuring overhead of this function or thoughts on its cost?</p>

答: Since ob_get_contents just needs to copy its internal buffers into a new string object, there is actually very little overhead. However, if your internal buffer is huge(measured in MB), this could be problematic. Your WordPress function is likely to be at the other end of the spectrum unless it's outputting zip or image files, so using ob_get_contents will be pretty fast.


问:
Start reading a line after n characters
I am making a program that take the data from internet, more specifically this url: https://raw.githubusercontent.com/openfootball/eng-england/master/2017-18/1-premierleague-i.txt

I want to calculate the standings based on the result, but I'm struggling with reading the file since I haven't figured out how to get the result in the middle of the line. I noticed there is a certain pattern in the text such as the results are always written after 27 characters, beginning with a white space but I don't know how to implement that into my code in order to extract the results and I also wonder if there were any better way to achieve this (I tried using delimiter but it didn't work).
Therefore, any help or advice would be very appreciated.

答:
Just use a combination of substring and trim and a bit of parsing.

```<code>public Map<String, Integer> getScore(String line) {
  String host = line.substring(2,25).trim();
  String guest = line.substring(32).trim();
  String[] scores = line.substring(25, 32).trim().split("-");
  Map<String,Integer> matchScore = new LinkedHashMap<>();
  matchScore.put(host, Integer.valueOf(scores[0]));
  matchScore.put(guest, Integer.valueOf(scores[1]))
  return matchScore;
}
</code>```

Title: Start reading a line after n characters

Body:
Just use a combination of substring and trim and a bit of parsing.

public Map<String, Integer> getScore(String line) {
  String host = line.substring(2,25).trim();
  String guest = line.substring(32).trim();
  String[] scores = line.substring(25, 32).trim().split("-");
  Map<String,Integer> matchScore = new LinkedHashMap<>();
  matchScore.put(host, Integer.valueOf(scores[0]));
  matchScore.put(guest, Integer.valueOf(scores[1]))
  return matchScore;
}


问:
convert table to div as per bootstrap v4 beta
I am using bootstrap v4 beta. I have created a table. How can i create the same table using div.

```<code><div class="container">
  <table class="table">
    <thead>
      <tr>
        <th>#</th>
        <th class="text-center"><b>Id</b></th>
        <th class="text-center"><b>Name</b></th>
        <th class="text-center"><b>Munit</b></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td> 1</td>
        <td class="text-center"> 294</td>
        <td class="text-center"> nimai</td>
        <td class="text-center"> kg</td>
      </tr>
      <tr>
        <td> 2</td>
        <td class="text-center"> 200</td>
        <td class="text-center"> nitai</td>
        <td class="text-center"> kg</td>
      </tr>
    </tbody>
  </table>
</div>
</code>```

I also want the same format it looks like in the below picture:

答:
Try this

.col {
display: inline-block;
}

row {
display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
   <div class="col">
     <div>First column</div>
     <div> 1</div>
     <div> 2</div>
      <div>3</div>
   </div>
   <div class="col">
     <div>Second column</div>
     <div>1</div>
     <div>2</div>
     <div>3</div>
   </div>

      <div class="col">
     <div>Third column</div>
     <div>1</div>
     <div>2</div>
     <div>3</div>
   </div></code>```

Body:
I am using bootstrap v4 beta. I have created a table. How can i create the same table using div.

        #
        Id
        Name
        Munit

         1
         294
         nimai
         kg

         2
         200
         nitai
         kg

I also want the same format it looks like in the below picture:

Body:
Try this

.col {
display: inline-block;
}

row {
display: block;
}

<div class="row">
   <div class="col">
     <div>First column</div>
     <div> 1</div>
     <div> 2</div>
      <div>3</div>
   </div>
   <div class="col">
     <div>Second column</div>
     <div>1</div>
     <div>2</div>
     <div>3</div>
   </div>

      <div class="col">
     <div>Third column</div>
     <div>1</div>
     <div>2</div>
     <div>3</div>
   </div>


问:
Compute variable according to factor levels
I am kind of new to R and programming in general. I am currently strugling with a piece of code for data transformation and hope someone can take a little bit of time to help me.

Below a reproducible exemple :

```<code>#    Data
a <- c(rnorm(12, 20))
b <- c(rnorm(12, 25))
f1 <- rep(c("X","Y","Z"), each=4) #family
f2 <- rep(x = c(0,1,50,100), 3) #reference and test levels

dt <- data.frame(f1=factor(f1), f2=factor(f2), a,b)

#library loading
library(tidyverse)
</code>```

Goal : Compute all values (a,b) using a reference value. Calculation should be : a/a_ref  with a_ref = a when f2=0 depending on the family (f1 can be X,Y or Z).

I tried to solve this by using this code :

```<code>    test <- filter(dt, f2!=0) %>% group_by(f1) %>%
    mutate("a/a_ref"=a/(filter(dt, f2==0) %>% group_by(f1) %>% distinct(a) %>% pull))
</code>```

I get :

test results

as you can see a is divided by a_ref. But my script seems to recycle the use of reference values (a_ref) regardless of the family f1.

Do you have any suggestion so A is computed with regard of the family (f1) ?

Thank you for reading !

EDIT

I found a way to do it 'manualy'

```<code>   filter(dt, f1=="X") %>% mutate("a/a_ref"=a/(filter(dt, f1=="X" & f2==0) %>% distinct(a) %>% pull()))
      f1  f2        a        b         a/a_ref
    1  X   0 21.77605 24.53115 1.0000000
    2  X   1 20.17327 24.02512 0.9263973
    3  X  50 19.81482 25.58103 0.9099366
    4  X 100 19.90205 24.66322 0.9139422
</code>```

the problem is that I'd have to update the code for each variable and family and thus is not a clean way to do it.

答:
```<code># use this to reproduce the same dataset and results
set.seed(5)

# Data
a <- c(rnorm(12, 20))
b <- c(rnorm(12, 25))
f1 <- rep(c("X","Y","Z"), each=4) #family
f2 <- rep(x = c(0,1,50,100), 3) #reference and test levels

dt <- data.frame(f1=factor(f1), f2=factor(f2), a,b)

#library loading
library(tidyverse)

dt %>%
  group_by(f1) %>%                 # for each f1 value
  mutate(a_ref = a[f2 == 0],       # get the a_ref and add it in each row
         "a/a_ref" = a/a_ref) %>%  # divide a and a_ref
  ungroup() %>%                    # forget the grouping
  filter(f2 != 0)                  # remove rows where f2 == 0

# # A tibble: 9 x 6
#       f1     f2        a        b    a_ref `a/a_ref`
#   <fctr> <fctr>    <dbl>    <dbl>    <dbl>     <dbl>
# 1      X      1 21.38436 24.84247 19.15914 1.1161437
# 2      X     50 18.74451 23.92824 19.15914 0.9783583
# 3      X    100 20.07014 24.86101 19.15914 1.0475490
# 4      Y      1 19.39709 22.81603 21.71144 0.8934042
# 5      Y     50 19.52783 25.24082 21.71144 0.8994260
# 6      Y    100 19.36463 24.74064 21.71144 0.8919090
# 7      Z      1 20.13811 25.94187 19.71423 1.0215013
# 8      Z     50 21.22763 26.46796 19.71423 1.0767671
# 9      Z    100 19.19822 25.70676 19.71423 0.9738257
</code>```

You can do this for more than one variable using:

```<code>dt %>%
  group_by(f1) %>%
  mutate_at(vars(a:b), funs(./.[f2 == 0])) %>%
  ungroup()
</code>```

Or generally use vars(a:z) to use all variables between a and z as long as they are one after the other in your dataset.

Another solution could be using mutate_if like:

```<code>dt %>%
  group_by(f1) %>%
  mutate_if(is.numeric, funs(./.[f2 == 0])) %>%
  ungroup()
</code>```

Where the function will be applied to all numeric variables you have. The variables f1 and f2 will be factor variables, so it just excludes those ones.

Body:
I am kind of new to R and programming in general. I am currently strugling with a piece of code for data transformation and hope someone can take a little bit of time to help me.

Below a reproducible exemple :

#    Data
a <- c(rnorm(12, 20))
b <- c(rnorm(12, 25))
f1 <- rep(c("X","Y","Z"), each=4) #family
f2 <- rep(x = c(0,1,50,100), 3) #reference and test levels

dt <- data.frame(f1=factor(f1), f2=factor(f2), a,b)

#library loading
library(tidyverse)

Goal : Compute all values (a,b) using a reference value. Calculation should be : a/a_ref  with a_ref = a when f2=0 depending on the family (f1 can be X,Y or Z).

I tried to solve this by using this code :

    test <- filter(dt, f2!=0) %>% group_by(f1) %>%
    mutate("a/a_ref"=a/(filter(dt, f2==0) %>% group_by(f1) %>% distinct(a) %>% pull))

I get :

test results

as you can see a is divided by a_ref. But my script seems to recycle the use of reference values (a_ref) regardless of the family f1.

Do you have any suggestion so A is computed with regard of the family (f1) ?

Thank you for reading !

EDIT

I found a way to do it 'manualy'

   filter(dt, f1=="X") %>% mutate("a/a_ref"=a/(filter(dt, f1=="X" & f2==0) %>% distinct(a) %>% pull()))
      f1  f2        a        b         a/a_ref
    1  X   0 21.77605 24.53115 1.0000000
    2  X   1 20.17327 24.02512 0.9263973
    3  X  50 19.81482 25.58103 0.9099366
    4  X 100 19.90205 24.66322 0.9139422

the problem is that I'd have to update the code for each variable and family and thus is not a clean way to do it.

Body:
# use this to reproduce the same dataset and results
set.seed(5)

# Data
a <- c(rnorm(12, 20))
b <- c(rnorm(12, 25))
f1 <- rep(c("X","Y","Z"), each=4) #family
f2 <- rep(x = c(0,1,50,100), 3) #reference and test levels

dt <- data.frame(f1=factor(f1), f2=factor(f2), a,b)

#library loading
library(tidyverse)

dt %>%
  group_by(f1) %>%                 # for each f1 value
  mutate(a_ref = a[f2 == 0],       # get the a_ref and add it in each row
         "a/a_ref" = a/a_ref) %>%  # divide a and a_ref
  ungroup() %>%                    # forget the grouping
  filter(f2 != 0)                  # remove rows where f2 == 0

# # A tibble: 9 x 6
#       f1     f2        a        b    a_ref `a/a_ref`
#   <fctr> <fctr>    <dbl>    <dbl>    <dbl>     <dbl>
# 1      X      1 21.38436 24.84247 19.15914 1.1161437
# 2      X     50 18.74451 23.92824 19.15914 0.9783583
# 3      X    100 20.07014 24.86101 19.15914 1.0475490
# 4      Y      1 19.39709 22.81603 21.71144 0.8934042
# 5      Y     50 19.52783 25.24082 21.71144 0.8994260
# 6      Y    100 19.36463 24.74064 21.71144 0.8919090
# 7      Z      1 20.13811 25.94187 19.71423 1.0215013
# 8      Z     50 21.22763 26.46796 19.71423 1.0767671
# 9      Z    100 19.19822 25.70676 19.71423 0.9738257

You can do this for more than one variable using:

dt %>%
  group_by(f1) %>%
  mutate_at(vars(a:b), funs(./.[f2 == 0])) %>%
  ungroup()

Or generally use vars(a:z) to use all variables between a and z as long as they are one after the other in your dataset.

Another solution could be using mutate_if like:

dt %>%
  group_by(f1) %>%
  mutate_if(is.numeric, funs(./.[f2 == 0])) %>%
  ungroup()

Where the function will be applied to all numeric variables you have. The variables f1 and f2 will be factor variables, so it just excludes those ones.


问:
Puppet reference enviornment name from .pp file?
I have external node classifier that manages the environment for each device in my puppet fleet.

When a device checks-in I'm updating it's configuration file so it knows what environment it's in:

```<code>ini_setting { 'set local enviornment':
  ensure  => present,
  path    => '/etc/puppetlabs/puppet/puppet.conf',
  section => 'agent',
  setting => 'environment',
  value   => 'environment_name',
}
</code>```

I currently have each r10k branch hard-coding the name.

Instead I'd like to be able to use the same code block on all environments, something like:

```<code>ini_setting { 'set local enviornment':
  ...
  value   => $environment_name,
}
</code>```

答:
When a device checks-in I'm updating it's configuration file so it knows what environment it's in:

You do know that you don't need to do that for Puppet's sake, right?  If you are (properly; see below) using an ENC to control nodes' environments then that overrides anything the nodes self-report, so you could do without nodes being locally configured to know their own environments at all.

Instead I'd like to be able to use the same code block on all
  environments, something like:

```<code>ini_setting { 'set local enviornment':
  ...
  value   => $environment_name,
}
</code>```

The correct way for an ENC to specify a node's environment to Puppet is by setting the environment key in its output for that node.  This is how an ENC directly puts the node into the specified environment.  Like any other top-level parameter emitted by the ENC, however, you can reference its value as a top-scope variable.  Thus, if you want to update node's Puppet configuration to explicitly specify (after the fact) the environment that the ENC assigns to the node, then you can use that, much as you propose:

```<code>ini_setting { 'set local enviornment':
  ...
  value   => $::environment,
}
</code>```

Body:
I have external node classifier that manages the environment for each device in my puppet fleet.

When a device checks-in I'm updating it's configuration file so it knows what environment it's in:

ini_setting { 'set local enviornment':
  ensure  => present,
  path    => '/etc/puppetlabs/puppet/puppet.conf',
  section => 'agent',
  setting => 'environment',
  value   => 'environment_name',
}

I currently have each r10k branch hard-coding the name.

Instead I'd like to be able to use the same code block on all environments, something like:

ini_setting { 'set local enviornment':
  ...
  value   => $environment_name,
}

Body:
When a device checks-in I'm updating it's configuration file so it knows what environment it's in:

You do know that you don't need to do that for Puppet's sake, right?  If you are (properly; see below) using an ENC to control nodes' environments then that overrides anything the nodes self-report, so you could do without nodes being locally configured to know their own environments at all.

Instead I'd like to be able to use the same code block on all
  environments, something like:

ini_setting { 'set local enviornment':
  ...
  value   => $environment_name,
}

The correct way for an ENC to specify a node's environment to Puppet is by setting the environment key in its output for that node.  This is how an ENC directly puts the node into the specified environment.  Like any other top-level parameter emitted by the ENC, however, you can reference its value as a top-scope variable.  Thus, if you want to update node's Puppet configuration to explicitly specify (after the fact) the environment that the ENC assigns to the node, then you can use that, much as you propose:

ini_setting { 'set local enviornment':
  ...
  value   => $::environment,
}


问:
Building QGIS on windows 7 error
I followed the instructions here to build the latest Qgis source code on windows 7 x64, but when i build the solution for the first time i encounter this error:

cannot open source file "qgsversion.h"    qgis_core

identifier "QGSVERSION" is undefined  qgis_core

in the source file qgis.cpp at the lines:

```<code>#ifndef QGSVERSION
#include "qgsversion.h"
#endif
</code>```

and:

```<code>const char *Qgis::QGIS_DEV_VERSION = QGSVERSION;
</code>```

The problem is the file qgsversion.h is not exists in the source code which i cloned it from the github.
I think it must be created after executing the CMake build file but not created.

Regards.

答:
I have the same problem, I solved this by building the "version" project first. It will give an error indicating the problem.

As a workaround I created the qgsversion.h file in the build directory myself. There is only one row inside the file with #define QGSVERSION "3b7d2e3360"

This row and the correct version number is shown in the output window of visual studio when you try to build the "version" project (when rebuilding fails).

I hope this helps, by making qgsversion.h, I was able to build qgis_core.dll

Title: Building QGIS on windows 7 error

Body:
I followed the instructions here to build the latest Qgis source code on windows 7 x64, but when i build the solution for the first time i encounter this error:

cannot open source file "qgsversion.h"    qgis_core

identifier "QGSVERSION" is undefined  qgis_core

in the source file qgis.cpp at the lines:

#ifndef QGSVERSION
#include "qgsversion.h"
#endif

and:

const char *Qgis::QGIS_DEV_VERSION = QGSVERSION;

The problem is the file qgsversion.h is not exists in the source code which i cloned it from the github.
I think it must be created after executing the CMake build file but not created.

Regards.


问:
explain how to use this specific function of foldl
```<code> sum :: (Num a) => [a] -> a
 sum xs = foldl (\acc x -> acc + x) 0 xs
</code>```

foldl is folds the list up from the left side. So first we get the acc=0 and put the list xs to x ,then doing the function ->acc+x.After calculation, we get the new acc which is equal to acc+x. But why is that? I think this result of acc+x is the new value of x based on the function x->acc+x.

答:
Let's take a look at your definition of sum

```<code>sum :: (Num a) => [a] -> a
sum xs = foldl (\acc x -> acc + x) 0 xs
</code>```

Let's also take a peek at foldl's signature:

```<code>foldl :: (a -> b -> a) -> a -> [b] -> a
</code>```

Hmm, ok, what do we have to feed foldl in order to get the value at the very, very end (->a)?

It needs a curried function (a->b->a). All though not accurate, for brevity's sake, we'll say its a function that takes two arguments (but you and I know that really, it takes one argument and returns another function that takes one argument).

It needs a value of type a. Notice that our curried function from Step 1. takes something of type a and returns something of type a. Interesting...hmmm...

It needs a list of type b. Notice our curried function from Step 1 takes, as well as something of type a, something of type b.

So, do we give it what it wants?

We give it (\acc x -> acc + x). This is an anonymous function, or lambda, that takes two arguments, (remember, it's curried, though), acc and x, and return's their sum.

We give it 0 as our starting value

We give it xs as the list to fold.

Ok dokie. So, let's just let foldl work its Haskell magic. Let's imagine we called sum [1,2,3]

foldl calls our function (\acc x -> acc + x), using 0 for acc and the first value of xs, 1.

```<code> 0 + 1
</code>```

This result does not get stored away in acc or x, since they are just arguments in our little lambda function. foldl is going to use that value (see SanSS's answer for the specific implementation).

Remember that the result of our lambda function is the same type as the first parameter? foldl can use that previous sum and pass it back to the lambda function, along with the second element.

```<code>(0 + 1) + 2
</code>```

And again until it has done this for all the elements:

```<code>((0 + 1) + 2) + 3
6
</code>```

As pointed out by Dan, this is the same if you had done:

```<code>sum xs = foldl (+) 0 xs
</code>```

You can tell more easily with this function that we aren't just 'setting' some variable and adding onto it.

Hope this helps.

Side note:
For your definition of sum, you don't have to explicitly state that sum takes xs. You could leave it as:

sum = foldl (\acc x -> acc + x) 0

This takes advantage of currying, because if we provide foldl just its first two arguments -- a curried function like (a->b->a) and a value of type a -- what do we get?

[b] -> a

A function that takes a list of type b and returns a value of type a! This is called pointfree style. Just something to consider :-)

Body:
 sum :: (Num a) => [a] -> a
 sum xs = foldl (\acc x -> acc + x) 0 xs

foldl is folds the list up from the left side. So first we get the acc=0 and put the list xs to x ,then doing the function ->acc+x.After calculation, we get the new acc which is equal to acc+x. But why is that? I think this result of acc+x is the new value of x based on the function x->acc+x.

Body:
Let's take a look at your definition of sum

sum :: (Num a) => [a] -> a
sum xs = foldl (\acc x -> acc + x) 0 xs

Let's also take a peek at foldl's signature:

foldl :: (a -> b -> a) -> a -> [b] -> a

Hmm, ok, what do we have to feed foldl in order to get the value at the very, very end (->a)?

It needs a curried function (a->b->a). All though not accurate, for brevity's sake, we'll say its a function that takes two arguments (but you and I know that really, it takes one argument and returns another function that takes one argument).

It needs a value of type a. Notice that our curried function from Step 1. takes something of type a and returns something of type a. Interesting...hmmm...

It needs a list of type b. Notice our curried function from Step 1 takes, as well as something of type a, something of type b.

So, do we give it what it wants?

We give it (\acc x -> acc + x). This is an anonymous function, or lambda, that takes two arguments, (remember, it's curried, though), acc and x, and return's their sum.

We give it 0 as our starting value

We give it xs as the list to fold.

Ok dokie. So, let's just let foldl work its Haskell magic. Let's imagine we called sum [1,2,3]

foldl calls our function (\acc x -> acc + x), using 0 for acc and the first value of xs, 1.

 0 + 1

This result does not get stored away in acc or x, since they are just arguments in our little lambda function. foldl is going to use that value (see SanSS's answer for the specific implementation).

Remember that the result of our lambda function is the same type as the first parameter? foldl can use that previous sum and pass it back to the lambda function, along with the second element.

(0 + 1) + 2

And again until it has done this for all the elements:

((0 + 1) + 2) + 3
6

As pointed out by Dan, this is the same if you had done:

sum xs = foldl (+) 0 xs

You can tell more easily with this function that we aren't just 'setting' some variable and adding onto it.

Hope this helps.

Side note:
For your definition of sum, you don't have to explicitly state that sum takes xs. You could leave it as:

sum = foldl (\acc x -> acc + x) 0

This takes advantage of currying, because if we provide foldl just its first two arguments -- a curried function like (a->b->a) and a value of type a -- what do we get?

[b] -> a

A function that takes a list of type b and returns a value of type a! This is called pointfree style. Just something to consider :-)


问:
Replace method used along-side Select-String not working
I am trying to search for the string, replace it and then output the file. I believe I have the syntax correct but for whatever reason it is not working. Can anyone spot why or is this even possible?

```<code>$DesiredTimeoutTime = '<Settings maxTimeout="04:00:00" />'
$path = "C:\Windows\Settings.log"

$currentTimeoutTime = Select-String -Path $path -SimpleMatch '<Settings maxTimeout=' -CaseSensitive
Write-Host $currentTimeoutTime
(Get-Content $path).Replace((Select-String -Path $path -SimpleMatch '<Settings maxTimeout="'), $DesiredTimeoutTime) | out-file $path
</code>```

It finds the line and path but it is not saving the changes.

Thank you

答:
You're overcomplicating things. Simply use the -replace operator with an appropriate regular expression:

```<code>$DesiredTimeoutTime = '04:00:00'
(Get-Content $path) -replace '(?<=<Settings maxTimeout=")[^"]*', $DesiredTimeoutTime |
    Set-Content $path
</code>```

(?<=...) is a positive lookbehind assertion, which basically means "look for something that is preceded by this pattern".

Body:
I am trying to search for the string, replace it and then output the file. I believe I have the syntax correct but for whatever reason it is not working. Can anyone spot why or is this even possible?

$DesiredTimeoutTime = '<Settings maxTimeout="04:00:00" />'
$path = "C:\Windows\Settings.log"

$currentTimeoutTime = Select-String -Path $path -SimpleMatch '<Settings maxTimeout=' -CaseSensitive
Write-Host $currentTimeoutTime
(Get-Content $path).Replace((Select-String -Path $path -SimpleMatch '<Settings maxTimeout="'), $DesiredTimeoutTime) | out-file $path

It finds the line and path but it is not saving the changes.

Thank you

Body:
You're overcomplicating things. Simply use the -replace operator with an appropriate regular expression:

$DesiredTimeoutTime = '04:00:00'
(Get-Content $path) -replace '(?<=<Settings maxTimeout=")[^"]*', $DesiredTimeoutTime |
    Set-Content $path

(?<=...) is a positive lookbehind assertion, which basically means "look for something that is preceded by this pattern".


问:
Fetch data with Vue from Web API
I have a Web API and I'm trying to get JSON Data from it by using Vue, but I get neither data or errors, so I don't what is wrong. I want to load the data when the page is loaded.

Here is my code:

```<code>const v = new Vue({
    el: '#divContent',
    ready: function () {
        this.loadData();
    },
    data: {
        content: 'loading',
        serverData: null
    },
    methods: {
        loadData: function (viewerUserId, posterUserId) {
            const that = this;
            $.ajax({
                contentType: "application/json",
                dataType: "json",
                url: "http://my-webapi/",
                method: "Post",
                success: function (response) {
                    that.$data.serverData = response;

                },
                error: function () {
                    alert('Error')
                }
            });
        }
    }
});
</code>```

My HTML

```<code><div id="divContent" class="content">
 {{ content }}
</div>
</code>```

答:
For Loading it on the page load, you can do the following:</p>

```<code>const v = new Vue({
    el: '#divContent',
    data: {
        content: 'loading',
        serverData: null
    },
    methods: {
        loadData(viewerUserId, posterUserId) {
            $.ajax({
                contentType: "application/json",
                dataType: "json",
                url: "http://my-webapi/",
                method: "POST",
                success: function (response) {
                    this.content = 'loaded';
                    this.serverData = response;

                },
                error: function () {
                    alert('Error')
                }
            });
        }
    },
    mounted() {
       this.loadData()
    }
});
</code>```

Title: Fetch data with Vue from Web API

Body:
I have a Web API and I'm trying to get JSON Data from it by using Vue, but I get neither data or errors, so I don't what is wrong. I want to load the data when the page is loaded.

Here is my code:

const v = new Vue({
    el: '#divContent',
    ready: function () {
        this.loadData();
    },
    data: {
        content: 'loading',
        serverData: null
    },
    methods: {
        loadData: function (viewerUserId, posterUserId) {
            const that = this;
            $.ajax({
                contentType: "application/json",
                dataType: "json",
                url: "http://my-webapi/",
                method: "Post",
                success: function (response) {
                    that.$data.serverData = response;

                },
                error: function () {
                    alert('Error')
                }
            });
        }
    }
});

My HTML

 {{ content }}

Body:
For Loading it on the page load, you can do the following:

const v = new Vue({
    el: '#divContent',
    data: {
        content: 'loading',
        serverData: null
    },
    methods: {
        loadData(viewerUserId, posterUserId) {
            $.ajax({
                contentType: "application/json",
                dataType: "json",
                url: "http://my-webapi/",
                method: "POST",
                success: function (response) {
                    this.content = 'loaded';
                    this.serverData = response;

                },
                error: function () {
                    alert('Error')
                }
            });
        }
    },
    mounted() {
       this.loadData()
    }
});


问:
The method "resize()" does not work for Webview in JavaFX
In a part of my code, I want to change a WebView object's size. Here is that part of code:

```<code>    textbox.setOnKeyPressed(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent ke) {
        if(ke.getCode() == KeyCode.ENTER){

            System.out.println("Enter pressed!");
            if(webEngine.isResizable())
                  System.out.println("It's Resizable!");
            webEngine.resize(300,200);     //doesn't work!

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

It compiles and runs without giving errors and "Enter pressed!" and "It's Resizable!" messages are shown on the console when I press enter, yet the webEngine object does not change in size!!!

Can anybody help me about that? Thanks.

答:
You should try putting your WebView inside of a container of your choice and then resize the container you should also put brackets around your if statement and add the resize in that like so

```<code>VBox vbox = new VBox();
vbox.getChildren().add(webView);
if(vbox.isResizable()){
    System.out.println("It's Resizable!");
    vbox.resize(300,200);     //doesn't work!
}
</code>```

I ran this code to test it and it ran perfectly by that I mean it resized

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        VBox vbox = new VBox();
        TextField textbox = new TextField();
        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();
        webEngine.load("https://www.google.com/");

        textbox.setOnKeyPressed(ke -> {
            if(ke.getCode() == KeyCode.ENTER){

                System.out.println("Enter pressed!");

                if(vbox.isResizable()) {
                    System.out.println("It's Resizable!");
                    vbox.resize(300, 200);     //doesn't work!
                }
            }
        });

        vbox.getChildren().addAll(textbox,webView);
        Scene scene = new Scene(vbox);
        Stage stage = new Stage();
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) { launch(args); }
}
</code>```

Body:
In a part of my code, I want to change a WebView object's size. Here is that part of code:

    textbox.setOnKeyPressed(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent ke) {
        if(ke.getCode() == KeyCode.ENTER){

            System.out.println("Enter pressed!");
            if(webEngine.isResizable())
                  System.out.println("It's Resizable!");
            webEngine.resize(300,200);     //doesn't work!

        }
    }
    });

It compiles and runs without giving errors and "Enter pressed!" and "It's Resizable!" messages are shown on the console when I press enter, yet the webEngine object does not change in size!!!

Can anybody help me about that? Thanks.

Body:
You should try putting your WebView inside of a container of your choice and then resize the container you should also put brackets around your if statement and add the resize in that like so

VBox vbox = new VBox();
vbox.getChildren().add(webView);
if(vbox.isResizable()){
    System.out.println("It's Resizable!");
    vbox.resize(300,200);     //doesn't work!
}

I ran this code to test it and it ran perfectly by that I mean it resized

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        VBox vbox = new VBox();
        TextField textbox = new TextField();
        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();
        webEngine.load("https://www.google.com/");

        textbox.setOnKeyPressed(ke -> {
            if(ke.getCode() == KeyCode.ENTER){

                System.out.println("Enter pressed!");

                if(vbox.isResizable()) {
                    System.out.println("It's Resizable!");
                    vbox.resize(300, 200);     //doesn't work!
                }
            }
        });

        vbox.getChildren().addAll(textbox,webView);
        Scene scene = new Scene(vbox);
        Stage stage = new Stage();
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) { launch(args); }
}


问:
Using data from php in angular5
Pls am new to angular, I sent data from my angular to my PHP in my registration page, and I also did server-side validation, but my problem is how can I use the data I got like of the response is 'am error occur'  then I can do something but if the response is 'ok' then I can do something else,

I used this to send data

```<code>this.http.post('http://127.0.0.1/Ana/index.php',
  {name: name, username: username, password: password})
.map(res => res.json())
.subscribe(res => this.getit = res);
</code>```

I was able to send and get a response back but how can I use it like when doing server-side validation. Thanks

答:
First time I misunderstood your question

I guess you're trying to check if the server validation was sucessful or not?

In that case, if you designed it correctly, you can use the following code (straight from the docs of Angular)

```<code>http
  .get<ItemsResponse>('/api/items')
  .subscribe(
    // Successful responses call the first callback.
    data => {...},
    // Errors will call this callback instead:
    err => {
      console.log('Something went wrong!');
    }
  );
</code>```

Title: Using data from php in angular5

Body:
Pls am new to angular, I sent data from my angular to my PHP in my registration page, and I also did server-side validation, but my problem is how can I use the data I got like of the response is 'am error occur'  then I can do something but if the response is 'ok' then I can do something else,

I used this to send data

this.http.post('http://127.0.0.1/Ana/index.php',
  {name: name, username: username, password: password})
.map(res => res.json())
.subscribe(res => this.getit = res);

I was able to send and get a response back but how can I use it like when doing server-side validation. Thanks

Body:
First time I misunderstood your question

I guess you're trying to check if the server validation was sucessful or not?

In that case, if you designed it correctly, you can use the following code (straight from the docs of Angular)

http
  .get<ItemsResponse>('/api/items')
  .subscribe(
    // Successful responses call the first callback.
    data => {...},
    // Errors will call this callback instead:
    err => {
      console.log('Something went wrong!');
    }
  );


问:
MultiFieldPanel width in Wagtail and displayed name
I have the following MultiFieldPanel.

```<code>class TeamRooster(Page):
    staff = StreamField([
        ('staff', CardsBlock(Staff(), icon="plus")),
    ], blank=True)
    content_panels = [
        MultiFieldPanel(
            [ StreamFieldPanel('staff') ],
            heading="Staff", classname="col12"
        ),
</code>```

three times "Staff" is too much. I looked in the documentation and tried to delete the names but I have a bug.

And how to change the width of MultiFieldPanel? I tried to add classname="full" but it doesn't help me.

答:
As @lb-ben-johnston said I changed content_panels []

Thanks @lb-ben-johnston!

Body:
I have the following MultiFieldPanel.

class TeamRooster(Page):
    staff = StreamField([
        ('staff', CardsBlock(Staff(), icon="plus")),
    ], blank=True)
    content_panels = [
        MultiFieldPanel(
            [ StreamFieldPanel('staff') ],
            heading="Staff", classname="col12"
        ),

three times "Staff" is too much. I looked in the documentation and tried to delete the names but I have a bug.

And how to change the width of MultiFieldPanel? I tried to add classname="full" but it doesn't help me.