问:
ArrayIndexOutOfBoundsException when trying to access parameter annotations for inner class constructor via reflection
I am trying to perform null checks on my methods using simple custom @NotNull annotation i.e.
I declare method as myMethod(@NotNull String name, String description) and when someone calls this method with null value passed as the 'name' argument an exception is thrown.

I already have an implementation of a simple aspect using aspectj. This solution works quite well for me. The one exception is constructors of inner classes. In such case the aspect crashes because of an exception inside java.lang.reflect.Parameter:

```<code>Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at java.lang.reflect.Parameter.getDeclaredAnnotations(Parameter.java:305)
    at java.lang.reflect.Parameter.declaredAnnotations(Parameter.java:342)
    at java.lang.reflect.Parameter.getAnnotation(Parameter.java:287)
    at java.lang.reflect.Parameter.getDeclaredAnnotation(Parameter.java:315)
    at ValidationAspect.checkNotNullArguments(ValidationAspect.java:22)
    at OuterClass$InnerClass.<init>(OuterClass.java:4)
    at OuterClass.constructInnerClass(OuterClass.java:14)
    at Main.main(Main.java:5)
</code>```

Simplified implementation:

Aspect:

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.ConstructorSignature;

import java.lang.reflect.Parameter;

@Aspect
public class ValidationAspect {

  @Pointcut("execution(*.new(.., @NotNull (*), ..))")
  private void anyConstructorWithNotNullParam() {}

  @Before("anyConstructorWithNotNullParam()")
  public void checkNotNullArguments(JoinPoint joinPoint) {
    ConstructorSignature signature = (ConstructorSignature) joinPoint.getSignature();
    Object[] args = joinPoint.getArgs();
    Parameter[] params = signature.getConstructor().getParameters();

    for(int i = 0; i < args.length; i++) {
      if(params[i].getDeclaredAnnotation(NotNull.class) != null) {
        if (args[i] == null) {
          throw new IllegalArgumentException("Illegal null argument");
        }
      }
    }
  }
}
```

<p>Annotation:</p>

<pre class="lang-java prettyprint-override"><code>import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.PARAMETER})
public @interface NotNull { }
</code>```

Test class:

public class OuterClass {

  public class InnerClass {
    public InnerClass(
        @NotNull String name
    ) {
      System.out.println(String.format("Construct inner class with name: %s", name));
    }
  }

  public InnerClass constructInnerClass(
      String name
  ) {
    return new InnerClass(name);
  }
}
```

<p>Usage:</p>

<pre class="lang-java prettyprint-override"><code>public class Main {

  public static void main(String[] args) {
    OuterClass outObj = new OuterClass();
    outObj.constructInnerClass("myName");
  }
}
</code>```

As far as I can tell, this is caused by java passing the enclosing class object as the first argument to the constructor of the inner class (which I was told is standard behavior). The problem is, that params[i].executable.getParameterAnnotations() does not seem to know about the additional argument and returns annotations only for the "normal" parameters

I feel like this is a bug in either aspectj or java.lang.reflection. But as I cannot find any bug report for this, it seems more likely to me that I am doing something wrong. The app runs on java 8 (tried multiple different builds of the oracle jdk and the last openjkd build) and aspectj 1.8.13 (but tried also 1.9.4).

So my question(s): Is this a known bug? Is there some flaw in my implementation? Is there some workaround? (I guess it would not be that hard to match the annotations to the parameters manually. But as I have very limited knowledge about java reflection, I am not really able to foresee the consequences).

Edited: provided working example

答:
Okay, I was too curious and played around with my own MCVE. I could rule out AspectJ as the culprit and pinned the problem down to a JDK/JRE problem:

The thing with inner (non-static) class constructors is that their first parameter is always an instance of the outer object. Java 8 - I tried with both 1.8.0_152 and 1.8.0_211 - contains a reflection off-by-one bug. Basically it moves the annotations of real inner constructor parameters one index up, e.g. the annotation parameters for the first constructor argument are stored in index 0 which actually should contain the annotations for the outer object instance. My sample code explains it better, I guess:

package de.scrum_master.app;

import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target(PARAMETER)
public @interface NotNull {}
```

<pre class="lang-java prettyprint-override"><code>package de.scrum_master.app;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Parameter;

public class Application {
  class Inner {
    public Inner(@NotNull String text) {
      System.out.println("Constructing inner with " + text);
    }
  }

  public static void main(String[] args) throws NoSuchMethodException, SecurityException {
      Constructor<Inner> constructor = Inner.class.getConstructor(Application.class, String.class);
      System.out.println(constructor);
      for (Parameter parameter : constructor.getParameters()) {
        System.out.println("  " + parameter);
        for (Annotation annotation : parameter.getAnnotations())
          System.out.println("    " + annotation);
      }
  }
}
</code>```

This reproduces your problem for JDK 8:

public de.scrum_master.app.Application$Inner(de.scrum_master.app.Application,java.lang.String)
  de.scrum_master.app.Application arg0
    @de.scrum_master.app.NotNull()
  java.lang.String arg1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at java.lang.reflect.Parameter.getDeclaredAnnotations(Parameter.java:305)
    at java.lang.reflect.Parameter.getAnnotations(Parameter.java:333)
    at de.scrum_master.app.Application.main(Application.java:19)
```

<p>But if you run with JDK 11 (I used 11.0.2) everything works as expected, also if I use an aspect with an advice like yours:</p>

<pre class="lang-none prettyprint-override"><code>public de.scrum_master.app.Application$Inner(de.scrum_master.app.Application,java.lang.String)
  de.scrum_master.app.Application arg0
  java.lang.String arg1
    @de.scrum_master.app.NotNull()
</code>```

I haven't bothered to look through all JDK release notes in order to find out whether this was fixed on purpose or by chance and in which JDK version (9, 10, 11), but at least I can tell you that after an update to JDK 11 you should be fine.

Body:
I am trying to perform null checks on my methods using simple custom @NotNull annotation i.e.
I declare method as myMethod(@NotNull String name, String description) and when someone calls this method with null value passed as the 'name' argument an exception is thrown.

I already have an implementation of a simple aspect using aspectj. This solution works quite well for me. The one exception is constructors of inner classes. In such case the aspect crashes because of an exception inside java.lang.reflect.Parameter:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at java.lang.reflect.Parameter.getDeclaredAnnotations(Parameter.java:305)
    at java.lang.reflect.Parameter.declaredAnnotations(Parameter.java:342)
    at java.lang.reflect.Parameter.getAnnotation(Parameter.java:287)
    at java.lang.reflect.Parameter.getDeclaredAnnotation(Parameter.java:315)
    at ValidationAspect.checkNotNullArguments(ValidationAspect.java:22)
    at OuterClass$InnerClass.<init>(OuterClass.java:4)
    at OuterClass.constructInnerClass(OuterClass.java:14)
    at Main.main(Main.java:5)

Simplified implementation:

Aspect:

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.ConstructorSignature;

import java.lang.reflect.Parameter;

@Aspect
public class ValidationAspect {

  @Pointcut("execution(*.new(.., @NotNull (*), ..))")
  private void anyConstructorWithNotNullParam() {}

  @Before("anyConstructorWithNotNullParam()")
  public void checkNotNullArguments(JoinPoint joinPoint) {
    ConstructorSignature signature = (ConstructorSignature) joinPoint.getSignature();
    Object[] args = joinPoint.getArgs();
    Parameter[] params = signature.getConstructor().getParameters();

    for(int i = 0; i < args.length; i++) {
      if(params[i].getDeclaredAnnotation(NotNull.class) != null) {
        if (args[i] == null) {
          throw new IllegalArgumentException("Illegal null argument");
        }
      }
    }
  }
}

Annotation:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.PARAMETER})
public @interface NotNull { }

Test class:

public class OuterClass {

  public class InnerClass {
    public InnerClass(
        @NotNull String name
    ) {
      System.out.println(String.format("Construct inner class with name: %s", name));
    }
  }

  public InnerClass constructInnerClass(
      String name
  ) {
    return new InnerClass(name);
  }
}

Usage:

public class Main {

  public static void main(String[] args) {
    OuterClass outObj = new OuterClass();
    outObj.constructInnerClass("myName");
  }
}

As far as I can tell, this is caused by java passing the enclosing class object as the first argument to the constructor of the inner class (which I was told is standard behavior). The problem is, that params[i].executable.getParameterAnnotations() does not seem to know about the additional argument and returns annotations only for the "normal" parameters

I feel like this is a bug in either aspectj or java.lang.reflection. But as I cannot find any bug report for this, it seems more likely to me that I am doing something wrong. The app runs on java 8 (tried multiple different builds of the oracle jdk and the last openjkd build) and aspectj 1.8.13 (but tried also 1.9.4).

So my question(s): Is this a known bug? Is there some flaw in my implementation? Is there some workaround? (I guess it would not be that hard to match the annotations to the parameters manually. But as I have very limited knowledge about java reflection, I am not really able to foresee the consequences).

Edited: provided working example

Body:
Okay, I was too curious and played around with my own MCVE. I could rule out AspectJ as the culprit and pinned the problem down to a JDK/JRE problem:

The thing with inner (non-static) class constructors is that their first parameter is always an instance of the outer object. Java 8 - I tried with both 1.8.0_152 and 1.8.0_211 - contains a reflection off-by-one bug. Basically it moves the annotations of real inner constructor parameters one index up, e.g. the annotation parameters for the first constructor argument are stored in index 0 which actually should contain the annotations for the outer object instance. My sample code explains it better, I guess:

package de.scrum_master.app;

import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target(PARAMETER)
public @interface NotNull {}

package de.scrum_master.app;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Parameter;

public class Application {
  class Inner {
    public Inner(@NotNull String text) {
      System.out.println("Constructing inner with " + text);
    }
  }

  public static void main(String[] args) throws NoSuchMethodException, SecurityException {
      Constructor<Inner> constructor = Inner.class.getConstructor(Application.class, String.class);
      System.out.println(constructor);
      for (Parameter parameter : constructor.getParameters()) {
        System.out.println("  " + parameter);
        for (Annotation annotation : parameter.getAnnotations())
          System.out.println("    " + annotation);
      }
  }
}

This reproduces your problem for JDK 8:

public de.scrum_master.app.Application$Inner(de.scrum_master.app.Application,java.lang.String)
  de.scrum_master.app.Application arg0
    @de.scrum_master.app.NotNull()
  java.lang.String arg1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at java.lang.reflect.Parameter.getDeclaredAnnotations(Parameter.java:305)
    at java.lang.reflect.Parameter.getAnnotations(Parameter.java:333)
    at de.scrum_master.app.Application.main(Application.java:19)

But if you run with JDK 11 (I used 11.0.2) everything works as expected, also if I use an aspect with an advice like yours:

public de.scrum_master.app.Application$Inner(de.scrum_master.app.Application,java.lang.String)
  de.scrum_master.app.Application arg0
  java.lang.String arg1
    @de.scrum_master.app.NotNull()

I haven't bothered to look through all JDK release notes in order to find out whether this was fixed on purpose or by chance and in which JDK version (9, 10, 11), but at least I can tell you that after an update to JDK 11 you should be fine.


来源: stackexchange

问:
Is this the correct syntax to validate authorization of API? given().get("url").when().auth("username","pwd").then().assertthat().statuscode(200)
I am testing for preemptive authorization using BDD for API automation using       Rest assured. Is this the correct syntax?

```<code>given().get("url").when().auth("username","pwd").then().assertthat().statuscode(200)
</code>```

Can I write get() after given() or should it be in when()?

答:
Try this, it works for me when i use this with Testng.

```<code>httpreq.auth().preemptive().basic("ToolsQA", "TestPassword");
        reponse = httpreq.request(Method.GET,"/authentication/CheckForAuthentication");
</code>```

Thanks for Asking,

ContentLicense: CC BY-SA 4.0

Body:
I am testing for preemptive authorization using BDD for API automation using       Rest assured. Is this the correct syntax?

given().get("url").when().auth("username","pwd").then().assertthat().statuscode(200)

Can I write get() after given() or should it be in when()?

Body:
Try this, it works for me when i use this with Testng.

httpreq.auth().preemptive().basic("ToolsQA", "TestPassword");
        reponse = httpreq.request(Method.GET,"/authentication/CheckForAuthentication");

Thanks for Asking,


问:
In a python list which is sorted, find the closest value to target value and its index in the list
I am trying to get both the closest value and its index in a sorted list in python.

In MATLAB this is possible with:

```<code>[closest_val,index] = min(abs(array - target))
</code>```

I was wondering if there is a similar way this can be implemented in python.

I've seen posts which do one or the other, but I haven't seen both done together.

Link to finding closest value in list post.

答:
bisect wasn't used in the linked question because the list was not sorted. Here, we don't have the same problem, and we can use bisect for the speed it provides:

```<code>import bisect

def find_closest_index(a, x):
    i = bisect.bisect_left(a, x)
    if i >= len(a):
        i = len(a) - 1
    elif i and a[i] - x > x - a[i - 1]:
        i = i - 1
    return (i, a[i])

find_closest_index([1, 2, 3, 7, 10, 11], 0)   # => 0, 1
find_closest_index([1, 2, 3, 7, 10, 11], 7)   # => 3, 7
find_closest_index([1, 2, 3, 7, 10, 11], 8)   # => 3, 7
find_closest_index([1, 2, 3, 7, 10, 11], 9)   # => 4, 10
find_closest_index([1, 2, 3, 7, 10, 11], 12)  # => 5, 11
</code>```

EDIT: In case of descending array:

```<code>def bisect_left_rev(a, x, lo=0, hi=None):
    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if a[mid] > x: lo = mid+1
        else: hi = mid
    return lo

def find_closest_index_rev(a, x):
    i = bisect_left_rev(a, x)
    if i >= len(a):
        i = len(a) - 1
    elif i and a[i] - x < x - a[i - 1]:
        i = i - 1
    return (i, a[i])

find_closest_index_rev([11, 10, 7, 3, 2, 1], 0)   # => 5, 1
find_closest_index_rev([11, 10, 7, 3, 2, 1], 7)   # => 2, 7
find_closest_index_rev([11, 10, 7, 3, 2, 1], 8)   # => 2, 7
find_closest_index_rev([11, 10, 7, 3, 2, 1], 9)   # => 1, 10
find_closest_index_rev([11, 10, 7, 3, 2, 1], 12)  # => 0, 11
</code>```

Body:
I am trying to get both the closest value and its index in a sorted list in python.

In MATLAB this is possible with:

[closest_val,index] = min(abs(array - target))

I was wondering if there is a similar way this can be implemented in python.

I've seen posts which do one or the other, but I haven't seen both done together.

Link to finding closest value in list post.

Body:
bisect wasn't used in the linked question because the list was not sorted. Here, we don't have the same problem, and we can use bisect for the speed it provides:

import bisect

def find_closest_index(a, x):
    i = bisect.bisect_left(a, x)
    if i >= len(a):
        i = len(a) - 1
    elif i and a[i] - x > x - a[i - 1]:
        i = i - 1
    return (i, a[i])

find_closest_index([1, 2, 3, 7, 10, 11], 0)   # => 0, 1
find_closest_index([1, 2, 3, 7, 10, 11], 7)   # => 3, 7
find_closest_index([1, 2, 3, 7, 10, 11], 8)   # => 3, 7
find_closest_index([1, 2, 3, 7, 10, 11], 9)   # => 4, 10
find_closest_index([1, 2, 3, 7, 10, 11], 12)  # => 5, 11

EDIT: In case of descending array:

def bisect_left_rev(a, x, lo=0, hi=None):
    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if a[mid] > x: lo = mid+1
        else: hi = mid
    return lo

def find_closest_index_rev(a, x):
    i = bisect_left_rev(a, x)
    if i >= len(a):
        i = len(a) - 1
    elif i and a[i] - x < x - a[i - 1]:
        i = i - 1
    return (i, a[i])

find_closest_index_rev([11, 10, 7, 3, 2, 1], 0)   # => 5, 1
find_closest_index_rev([11, 10, 7, 3, 2, 1], 7)   # => 2, 7
find_closest_index_rev([11, 10, 7, 3, 2, 1], 8)   # => 2, 7
find_closest_index_rev([11, 10, 7, 3, 2, 1], 9)   # => 1, 10
find_closest_index_rev([11, 10, 7, 3, 2, 1], 12)  # => 0, 11


问:
Why are all my component rerendering when I change an unrelated state?
I'm trying to change a state without having the entire app reload. For some reason that's not happening, and when I set the state of an object that isn't even passed down to a specific component, then that component updates for no reason.

So in the code below, I'm when I set the message, MainContent should not reload.

```<code>const [message, setMessage] = useState({});
setMessage('my message'); // This causes the entire app, including 'MyComponent' to reload

return (
    <div className='App'>
        <Header user={user} message={message} setMessage={setMessage} />

        <div id='main-site'>
            <Switch>
                // SHOULD NOT RELOAD UNLESS PASSED IN PROP CHANGED
                <Route path='/main' component={MainContent} />

            </Switch>
        </div>
    </div>
);
</code>```

Header.jsx

```<code>return (
    {message && (
        <div>
            <span>{message.text}</span>
            // This on click makes the entire app reload
            <button className='close' onClick={() => setMessage({})}>
                X
            </button>
        </div>
    )}
);
</code>```

How can I make sure the only components that have the message prop get updated, and no other components rerender?

答:
There are two ways to fix your issue.

The First one involved moving your state down to the Child Component i.e Header since only Header uses message state. The Other thing to keep in mind is that you don't call state updater directly in render since it will keep calling the react state updater although it won't affect your app since react internally prevents re-render if the same state is supplied to state updater again.

```<code>const [message, setMessage] = useState({});
setMessage('my message');

return (
    {message && (
        <div>
            <span>{message.text}</span>
            // This on click makes the entire app reload
            <button className='close' onClick={() => setMessage({})}>
                X
            </button>
        </div>
    )}
);
</code>```

The second way which is a more reliable way when you have to pass on message to more than one component is to make use of React.memo for the component

```<code>const MyComponent = () => (
   ...
);

export default React.memo(MyComponent)
</code>```

Body:
I'm trying to change a state without having the entire app reload. For some reason that's not happening, and when I set the state of an object that isn't even passed down to a specific component, then that component updates for no reason.

So in the code below, I'm when I set the message, MainContent should not reload.

const [message, setMessage] = useState({});
setMessage('my message'); // This causes the entire app, including 'MyComponent' to reload

return (

            <Switch>
                // SHOULD NOT RELOAD UNLESS PASSED IN PROP CHANGED
                <Route path='/main' component={MainContent} />

            </Switch>

);

Header.jsx

return (
    {message && (

            {message.text}
            // This on click makes the entire app reload
            <button className='close' onClick={() => setMessage({})}>
                X
            </button>

    )}
);

How can I make sure the only components that have the message prop get updated, and no other components rerender?

Body:
There are two ways to fix your issue.

The First one involved moving your state down to the Child Component i.e Header since only Header uses message state. The Other thing to keep in mind is that you don't call state updater directly in render since it will keep calling the react state updater although it won't affect your app since react internally prevents re-render if the same state is supplied to state updater again.

const [message, setMessage] = useState({});
setMessage('my message');

return (
    {message && (
        <div>
            <span>{message.text}</span>
            // This on click makes the entire app reload
            <button className='close' onClick={() => setMessage({})}>
                X
            </button>
        </div>
    )}
);

The second way which is a more reliable way when you have to pass on message to more than one component is to make use of React.memo for the component

const MyComponent = () => (
   ...
);

export default React.memo(MyComponent)


答:
You can use case when first record of group display the value, otherwise empty string:</p>

```<code>SELECT ID,
  CASE ROW_NUMBER() OVER (PARTITION BY field1) WHEN 1 THEN field1 ELSE "" END AS FIELD1,
  field2
FROM table
;
</code>```

Title: Group or eliminate duplicates fields in columns

Body:
I want to group the data of the field 1 that has more data in the field 2

+-----+----------+---------------+
| id  |  field1  |    field2     |
+-----+----------+---------------+
|  1  |   ONE    |   Medicine    |
|  2  |   TWO    |   Food        |
|  3  |   TWO    |   Medicine    |
+-----+----------+---------------+

I want something like this

+-----+----------+---------------+
| id  |  field1  |    field2     |
+-----+----------+---------------+
|  1  |   ONE    |   Medicine    |
|  2  |   TWO    |   Food        |
|  3  |          |   Medicine    |
+-----+----------+---------------+

I dont know if is possible im new in mysql

thanks for your time

Body:
You can use case when first record of group display the value, otherwise empty string:

SELECT ID,
  CASE ROW_NUMBER() OVER (PARTITION BY field1) WHEN 1 THEN field1 ELSE "" END AS FIELD1,
  field2
FROM table
;


问:
How to add half link in href?
I want to create half-links in href means, for example, suppose I want to create code to check Alexa ranking so when user come on my website they enter their website URL to check rank so in this https://www.alexa.com/siteinfo/ will come automatically and the URL that enters by the user will add after this link.</p>

答:
$('input').on('keyup', function(){
var value = $( this ).val();
 $('.urlPlace').text('https://www.alexa.com/siteinfo/' + value);
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}
input{
  font-size:18px;
  height: 40px;
}
div{
  color:black;
  font-size: 14px;
  margin-top: 15px;
}</code>```

<input type="text" id="urlVal" />

```

I hope this will help

Title: How to add half link in href?

Body:
$('input').on('keyup', function(){
var value = $( this ).val();
 $('.urlPlace').text('https://www.alexa.com/siteinfo/' + value);
})

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}
input{
  font-size:18px;
  height: 40px;
}
div{
  color:black;
  font-size: 14px;
  margin-top: 15px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="urlVal" />

<div class="urlPlace">
</div>

I hope this will help


问:
Ionic package build failed - ionic-plugin-keyboard
I have an app that works fine in ionic serve. I am now trying to create a build -- this normally works but today I am running into problems.

```<code>ionic package build ios --profile development
</code>```

This gives me a success message.

```<code>Uploading your project to Ionic...
Submitting your app to Ionic Package...
Your app has been successfully submitted to Ionic Package!
Build ID: 103
We are now packaging your app.
</code>```

But when I check the app in Ionic Package I see that the build failed. There is just one error:

```<code>In file included from /Users/package/workspace/apps-96ff266e-5/cordova/platforms/ios/wurkclient/Plugins/ionic-plugin-keyboard/IonicKeyboard.m:1:
/Users/package/workspace/apps-96ff266e-5/cordova/platforms/ios/wurkclient/Plugins/ionic-plugin-keyboard/IonicKeyboard.h:8:5: error: unknown type name 'Method'
    Method wkMethod, uiMethod;
    ^
</code>```

My ionic info output is:

```<code>Your system information:

Cordova CLI: 6.5.0
Ionic Framework Version: 2.0.0-rc.3
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 0.0.46
ios-deploy version: 1.9.0
ios-sim version: 5.0.8
OS: macOS Sierra
Node Version: v7.4.0
Xcode version: Xcode 8.1 Build version 8B62
</code>```

I have tried the ionic platform remove ios and then the ionic platform add ios but no improvements.

I am out of ideas!

答:
This one is a very common issue, just try to remove node_modules and plugins folder and use below command to build the project again. This worked for me!

ionic build

Android

ionic cordova build ios --prod

iOS

ionic cordova build android --prod

Body:
I have an app that works fine in ionic serve. I am now trying to create a build -- this normally works but today I am running into problems.

ionic package build ios --profile development

This gives me a success message.

Uploading your project to Ionic...
Submitting your app to Ionic Package...
Your app has been successfully submitted to Ionic Package!
Build ID: 103
We are now packaging your app.

But when I check the app in Ionic Package I see that the build failed. There is just one error:

In file included from /Users/package/workspace/apps-96ff266e-5/cordova/platforms/ios/wurkclient/Plugins/ionic-plugin-keyboard/IonicKeyboard.m:1:
/Users/package/workspace/apps-96ff266e-5/cordova/platforms/ios/wurkclient/Plugins/ionic-plugin-keyboard/IonicKeyboard.h:8:5: error: unknown type name 'Method'
    Method wkMethod, uiMethod;
    ^

My ionic info output is:

Your system information:

Cordova CLI: 6.5.0
Ionic Framework Version: 2.0.0-rc.3
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 0.0.46
ios-deploy version: 1.9.0
ios-sim version: 5.0.8
OS: macOS Sierra
Node Version: v7.4.0
Xcode version: Xcode 8.1 Build version 8B62

I have tried the ionic platform remove ios and then the ionic platform add ios but no improvements.

I am out of ideas!


问:
Q: I can't understand "var variable = {" in jquery
I'm modifying the jQuery source code which another person has programmed.

But there was a var definition which I can't understand.

I had no idea about this code, so I googled and searching, but couldn't find any answers.

js

```<code>var isMobile = {
  Android: function() {
    return navigator.userAgent.match(/Android/i);
  },
    BlackBerry: function() {
    return navigator.userAgent.match(/BlackBerry/i);
  },
    iOS: function() {
    return navigator.userAgent.match(/iPhone|iPad|iPod/i);
  },
    Opera: function() {
    return navigator.userAgent.match(/Opera Mini/i);
  },
    Windows: function() {
    return navigator.userAgent.match(/IEMobile/i);
  },
    any: function() {
    return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
  }
};
</code>```

I want to know what does this code mean.

Also, I'd like to know the syntax, such as

js

```<code> var isMobile = {
   Android: function() {
     return window.navigator.userAgent.match(/Android/i);
 },
</code>```

What Android: means?

答:
This code creates "isMobile" object and declares functions to check the kind of mobile browser. Check https://www.w3schools.com/js/js_object_definition.asp for creating objects in JavaScript.

To explain following piece of code:

```<code>    var isMobile = {
  Android: function() {
    return window.navigator.userAgent.match(/Android/i);
  }
</code>```

isMobile is a JavaScript object.

Andorid is a property of "isMobile" object. This property check whether the browser being used to navigate the web page is "Android browser". "window.navigator.userAgent.match(/Android/i)" this part in code returns true if the browser is "Andorid" browser.

Body:
I'm modifying the jQuery source code which another person has programmed.

But there was a var definition which I can't understand.

I had no idea about this code, so I googled and searching, but couldn't find any answers.

js

var isMobile = {
  Android: function() {
    return navigator.userAgent.match(/Android/i);
  },
    BlackBerry: function() {
    return navigator.userAgent.match(/BlackBerry/i);
  },
    iOS: function() {
    return navigator.userAgent.match(/iPhone|iPad|iPod/i);
  },
    Opera: function() {
    return navigator.userAgent.match(/Opera Mini/i);
  },
    Windows: function() {
    return navigator.userAgent.match(/IEMobile/i);
  },
    any: function() {
    return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
  }
};

I want to know what does this code mean.

Also, I'd like to know the syntax, such as

js

 var isMobile = {
   Android: function() {
     return window.navigator.userAgent.match(/Android/i);
 },

What Android: means?

Body:
This code creates "isMobile" object and declares functions to check the kind of mobile browser. Check https://www.w3schools.com/js/js_object_definition.asp for creating objects in JavaScript.

To explain following piece of code:

    var isMobile = {
  Android: function() {
    return window.navigator.userAgent.match(/Android/i);
  }

isMobile is a JavaScript object.

Andorid is a property of "isMobile" object. This property check whether the browser being used to navigate the web page is "Android browser". "window.navigator.userAgent.match(/Android/i)" this part in code returns true if the browser is "Andorid" browser.


问:
Stored procedure azure Cosmos DB returns empty collection
I tried to create a stored procedure using the sample sp creation code from Azure docs, but i couldn't fetch the collection details. It always returns null.

Stored Procedure

```<code>// SAMPLE STORED PROCEDURE
function sample(prefix) {
    var collection = getContext().getCollection();
    console.log(JSON.stringify(collection));

    // Query documents and take 1st item.
    var isAccepted = collection.queryDocuments(
        collection.getSelfLink(),
        'SELECT * FROM root r',
    function (err, feed, options) {
        if (err) throw err;

        // Check the feed and if empty, set the body to 'no docs found',
        // else take 1st element from feed
        if (!feed || !feed.length) {
            var response = getContext().getResponse();
            response.setBody('no docs found');
        }
        else {
            var response = getContext().getResponse();
            var body = { prefix: prefix, feed: feed[0] };
            response.setBody(JSON.stringify(body));
        }
    });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
</code>```

The console shows only this.

the results shows no doc found because of not getting collection.I have passed the partition key at time of execution via explorer.

答:
I had a similar issue. I think the Azure portal doesn't execute stored procedures properly when the partition key is not a string.

In my case I had a partitionKey that is a number. When I executed the stored procedure via the portal I always got an empty resultSet, even though I had documents in my database. When I changed the structure a little, and made my partitionKey a string, the stored procedure worked fine.

Body:
I tried to create a stored procedure using the sample sp creation code from Azure docs, but i couldn't fetch the collection details. It always returns null.

Stored Procedure

// SAMPLE STORED PROCEDURE
function sample(prefix) {
    var collection = getContext().getCollection();
    console.log(JSON.stringify(collection));

    // Query documents and take 1st item.
    var isAccepted = collection.queryDocuments(
        collection.getSelfLink(),
        'SELECT * FROM root r',
    function (err, feed, options) {
        if (err) throw err;

        // Check the feed and if empty, set the body to 'no docs found',
        // else take 1st element from feed
        if (!feed || !feed.length) {
            var response = getContext().getResponse();
            response.setBody('no docs found');
        }
        else {
            var response = getContext().getResponse();
            var body = { prefix: prefix, feed: feed[0] };
            response.setBody(JSON.stringify(body));
        }
    });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}

The console shows only this.

the results shows no doc found because of not getting collection.I have passed the partition key at time of execution via explorer.


问:
Time series prediction: need help using series with different periods of days
There's this event that my organization runs, and we have the ticket sales historic data from 2016, 2017, 2018. This data contains the quantity of tickets selled by day, considering all the sales period.

To the 2019 edition of this event, I was asked to make a prediction of the quantity of tickets selled by day, considering all the sales period, sort of to guide us through this period, meaning we would have the information if we are above or below the expected sales average.

The problem is that the historic data has a different size of sales period in days:

In 2016, the total sales period was 46 days.
In 2017, 77 days.
In 2018, 113 days.

In 2019 we are planning 85 days. So how do I  ajust those historical data, in a logic/statistical way, so I could use them as inputs to a statistical predictive model (such as ARIMA model)?

Also, I'm planning to do this on Python, so if you have any suggestions about that, I would love to hear them too!

Thank you!

答:
Based on what I understand after reading your question, I would approach this problem in the following way.

For each day, find how far out the event is from that day. The max
value for this number is 46 in 2016, 77 in 2017 etc. Scale this value
by the max day.

Use the above variable, along with day of the month, day of the week
etc as extraneous variable

Additionally, use lag information from ticket sales. You can try one
day lag, one week lag etc.

You would be able to generate all this data from the sale start until
end.

Use the generated variables as predictor for each day and use ticket
sales as target variable and generate a machine learning model
instead of forecasting.

Use the machine learning model along with generated variables to predict future sales.


问:
run external application in linux using qprocess
I am creating an GUI application using QT creater in Raspbian. When I click a button I want to open an external application like terminal, or browser, etc.

I have tried many attempts

attempt 1

std::system("/usr/share/raspi-ui-overrides/applications/scratch.desktop&");
```

<p>it says me permission denied</p>

<ul>
<li>attempt 2</li>
</ul>

<pre class="lang-cpp prettyprint-override"><code>QDesktopServices::openUrl(QUrl("/usr/share/raspi-ui-overrides/applications/scratch.desktop"));
</code>```

this one is working but its not opening the application but its opening in terminal:

QDesktopServices::openUrl(QUrl("/usr/share/raspi-ui-overrides/applications/scratch.desktop"));
```

答:
I'm assuming the question is about Raspberry Pi and Raspbian.

In Raspbian, the scratch.desktop and other *.desktop files are not executables, but just text files that describe which application to run.

Example:

```<code>pi@raspberrypi:~ $ cat /usr/share/raspi-ui-overrides/applications/scratch.desktop
[Desktop Entry]
Encoding=UTF-8
Version=1.0
Type=Application
TryExec=scratch
Exec=scratch
Icon=scratch
Terminal=false
Name=Scratch
Comment= Programming system and content development tool
Categories=Application;Development;
MimeType=application/x-scratch-project
</code>```

You need to use an actual binary to start the process. For scratch, it would be /usr/bin/scratch. For a browser, it's likely to be /usr/bin/epiphany-browser. Look at Exec= line in the *.desktop file to see the name of the executable, then use which in the terminal to see its location:

```<code>pi@raspberrypi:~ $ which epiphany-browser
/usr/bin/epiphany-browser
</code>```

Body:
I am creating an GUI application using QT creater in Raspbian. When I click a button I want to open an external application like terminal, or browser, etc.

I have tried many attempts

attempt 1

std::system("/usr/share/raspi-ui-overrides/applications/scratch.desktop&");

it says me permission denied

attempt 2

QDesktopServices::openUrl(QUrl("/usr/share/raspi-ui-overrides/applications/scratch.desktop"));

this one is working but its not opening the application but its opening in terminal:

QDesktopServices::openUrl(QUrl("/usr/share/raspi-ui-overrides/applications/scratch.desktop"));

Body:
I'm assuming the question is about Raspberry Pi and Raspbian.

In Raspbian, the scratch.desktop and other *.desktop files are not executables, but just text files that describe which application to run.

Example:

pi@raspberrypi:~ $ cat /usr/share/raspi-ui-overrides/applications/scratch.desktop
[Desktop Entry]
Encoding=UTF-8
Version=1.0
Type=Application
TryExec=scratch
Exec=scratch
Icon=scratch
Terminal=false
Name=Scratch
Comment= Programming system and content development tool
Categories=Application;Development;
MimeType=application/x-scratch-project

You need to use an actual binary to start the process. For scratch, it would be /usr/bin/scratch. For a browser, it's likely to be /usr/bin/epiphany-browser. Look at Exec= line in the *.desktop file to see the name of the executable, then use which in the terminal to see its location:

pi@raspberrypi:~ $ which epiphany-browser
/usr/bin/epiphany-browser


问:
How to make bootstrap carousel with cards
I try to make a bootstrap carousel with cards in my website. I have a code from here.

The code I used is

```<code><section class="carousel slide" data-ride="carousel">
    <div class="container">
        <div class="row">
            <div class="col-xs-12 text-md-right lead">
                <a class="btn btn-outline-secondary prev" href="" title="go back"><i class="fa fa-lg fa-chevron-left"></i></a>
                <a class="btn btn-outline-secondary next" href="" title="more"><i class="fa fa-lg fa-chevron-right"></i></a>
            </div>
        </div>
    </div>
    <div class="container p-t-0 m-t-2 carousel-inner">

        <div class="row row-equal carousel-item active m-t-0">
            {% capture category_name %}{{ page.category }}{% endcapture %}
          {% for post in site.categories[category_name] limit:4 %}
 {% if post.url != page.url %}
            <div class="col-md-4">
                <div class="card mb-2">
                    <div class="card-img-top card-img-top-250">
                      {% assign image = post.content | split:"!-- ![header](" %}
      {% assign html = image[1] | split:") -->" | first %}
      {% if html and html != "" %}
                        <img class="img-fluid" src="{{ html }}" alt="Carousel 1">
                        {% endif %}
                    </div>
                    <div class="card-block p-t-2">
                      <h4 class="card-title text-center " itemprop="name headline">{{ post.title }}</h4>
                      <div class="text-center">
                      <a href="{{ post.url | prepend: site.baseurl }}" class="btn btn-info my-2 text-center shadow-sm text-white" role="button">View Now</a>
                      </div>
                    </div>
                </div>
            </div>
         {% endif %}
{% endfor %}

        </div>

<div class="row row-equal carousel-item m-t-0">
    {% for post in site.categories[category_name] offset:3 limit:3 %}

            <div class="col-md-4">
                <div class="card mb-2">
                    <div class="card-img-top card-img-top-250">
                         {% assign image = post.content | split:"!-- ![header](" %}
      {% assign html = image[1] | split:") -->" | first %}
      {% if html and html != "" %}
                        <img class="img-fluid" src="{{ html }}" alt="Carousel 4">
                        {% endif %}
                    </div>
                    <div class="card-block p-t-2">
                       <h4 class="card-title text-center text-info" itemprop="name headline">{{ post.title }}</h4>
                       <div class="text-center">
                      <a href="{{ post.url | prepend: site.baseurl }}" class="text-center btn btn-info shadow-sm my-2 text-white" role="button">View Now</a>
                      </div>
                    </div>
                </div>
            </div>

{% endfor %}
        </div>

    </div>
</section>
</code>```

javascript

```<code>(function($) {
    "use strict";

    // manual carousel controls
    $('.next').click(function(){ $('.carousel').carousel('next');return false; });
    $('.prev').click(function(){ $('.carousel').carousel('prev');return false; });

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

and css

```<code>
/* equal card height */
.row-equal > div[class*='col-'] {
    display: flex;
    flex: 1 0 auto;
}

.row-equal .card {
   width: 100%;
}

/* ensure equal card height inside carousel */
.carousel-inner>.row-equal.active,
.carousel-inner>.row-equal.next,
.carousel-inner>.row-equal.prev {
    display: flex;
}

/* prevent flicker during transition */
.carousel-inner>.row-equal.active.left,
.carousel-inner>.row-equal.active.right {
    opacity: 0.5;
    display: flex;
}

/* control image height */
.card-img-top-250 {
    max-height: 250px;
    overflow:hidden;
}
</code>```

I think I have some bootstrap.css problem. My css loaded at https://demo.justinechacko.in/css/main.css

But when I apply that to my site, I have some problems like,

1. Carousel indicators are fixed to left (In codeply page it is in right position).

2. Carousel width is not proper in mobile view, it positioned little bit left.

3.Also carousel give 3 cards at a time in mobile view(In codeply it shows only one card at a time).

Here is my site.

答:
Solution for First two points

1. Carousel indicators are fixed to left (In codeply page it is in right position).

2. Carousel width is not proper in mobile view, it positioned little bit left.
Above points

Main.css (Line no.: 947)    Replace below class

```<code>.row {
display: flex;
flex-wrap: wrap;
/* margin-right: -15px; */
/* margin-left: -15px; */
}
</code>```

For 3rd point
  I will say you implement the wrong thing for your card. You can not put your card in normal carousel For that you have to use Owl CarouselI gave line below

Owl Carousel Official Link

Owl Carousel Example Link

Body:
I try to make a bootstrap carousel with cards in my website. I have a code from here.

The code I used is

            {% capture category_name %}{{ page.category }}{% endcapture %}
          {% for post in site.categories[category_name] limit:4 %}
 {% if post.url != page.url %}

                      {% assign image = post.content | split:"!-- ![header](" %}
      {% assign html = image[1] | split:") -->" | first %}
      {% if html and html != "" %}

                        {% endif %}

{{ post.title }}

                      View Now

         {% endif %}
{% endfor %}

    {% for post in site.categories[category_name] offset:3 limit:3 %}

                         {% assign image = post.content | split:"!-- ![header](" %}
      {% assign html = image[1] | split:") -->" | first %}
      {% if html and html != "" %}

                        {% endif %}

{{ post.title }}

                      View Now

{% endfor %}

javascript

(function($) {
    "use strict";

    // manual carousel controls
    $('.next').click(function(){ $('.carousel').carousel('next');return false; });
    $('.prev').click(function(){ $('.carousel').carousel('prev');return false; });

})(jQuery);

and css

/* equal card height */
.row-equal > div[class*='col-'] {
    display: flex;
    flex: 1 0 auto;
}

.row-equal .card {
   width: 100%;
}

/* ensure equal card height inside carousel */
.carousel-inner>.row-equal.active,
.carousel-inner>.row-equal.next,
.carousel-inner>.row-equal.prev {
    display: flex;
}

/* prevent flicker during transition */
.carousel-inner>.row-equal.active.left,
.carousel-inner>.row-equal.active.right {
    opacity: 0.5;
    display: flex;
}

/* control image height */
.card-img-top-250 {
    max-height: 250px;
    overflow:hidden;
}

I think I have some bootstrap.css problem. My css loaded at https://demo.justinechacko.in/css/main.css

But when I apply that to my site, I have some problems like,

1. Carousel indicators are fixed to left (In codeply page it is in right position).

2. Carousel width is not proper in mobile view, it positioned little bit left.

3.Also carousel give 3 cards at a time in mobile view(In codeply it shows only one card at a time).

Here is my site.

Body:
Solution for First two points

1. Carousel indicators are fixed to left (In codeply page it is in right position).

2. Carousel width is not proper in mobile view, it positioned little bit left.
Above points

Main.css (Line no.: 947)    Replace below class

.row {
display: flex;
flex-wrap: wrap;
/* margin-right: -15px; */
/* margin-left: -15px; */
}

For 3rd point
  I will say you implement the wrong thing for your card. You can not put your card in normal carousel For that you have to use Owl CarouselI gave line below

Owl Carousel Official Link

Owl Carousel Example Link


问:
Conditionally convert string to int
In the line data=[int(x) if x else None for x in line.replace("\n","").split(",")] below I'd like to keep string values as string instead of throwing an exception if a value that can't be casted to int is encountered. Are there any elegant ways to do this? For instance, if you have on a given line 9327,Garlic Powder,104,13 then data would be [9327, "Garlic Powder", 104, 13]

Rik

```<code>file = open(file_path, 'r')

# get headers
try:
    header=next(file).replace("\n","").split(",")
except:
    raise Exception("The file {} is empty.".format(file.file_path))

count = 0 # to count number of rows

# loop through file and process data
for line in file:
    try:
        data=[int(x) if x else None for x in line.replace("\n","").split(",")]
    except:
        raise Exception("The file {} contains invalid data.".format(file.file_path))
    count += 1
    for f in callback_array:
        f(header,data)
</code>```

答:
You can keep your oneliner by using isnumeric:

```<code>data=[int(x) if x and x.isnumeric() else x for x in line.replace("\n","").split(",")]
</code>```

Title: Conditionally convert string to int

Body:
In the line data=[int(x) if x else None for x in line.replace("\n","").split(",")] below I'd like to keep string values as string instead of throwing an exception if a value that can't be casted to int is encountered. Are there any elegant ways to do this? For instance, if you have on a given line 9327,Garlic Powder,104,13 then data would be [9327, "Garlic Powder", 104, 13]

Rik

file = open(file_path, 'r')

# get headers
try:
    header=next(file).replace("\n","").split(",")
except:
    raise Exception("The file {} is empty.".format(file.file_path))

count = 0 # to count number of rows

# loop through file and process data
for line in file:
    try:
        data=[int(x) if x else None for x in line.replace("\n","").split(",")]
    except:
        raise Exception("The file {} contains invalid data.".format(file.file_path))
    count += 1
    for f in callback_array:
        f(header,data)

Body:
You can keep your oneliner by using isnumeric:

data=[int(x) if x and x.isnumeric() else x for x in line.replace("\n","").split(",")]


问:
How to dispose shared variable in VB.NET
How to dispose the shared variable in vb.net

i am using shared object of Asterisk.NET Manager Variable, i assigned it in form load
and i dispose it in main form closing, My problem is after closing the application, application.exe keeps live in task manager, if i not initializing the shared object in form load there is no problem,

My code in form open

```<code>  Public Shared WithEvents objManager As Asterisk.NET.Manager.ManagerConnection

  Public Shared Sub ConnectAsterisk()
    Try
        objManager = New Asterisk.NET.Manager.ManagerConnection(ELASTIX_IP_ADDRESS, ASTERISK_PORT, ASTERISK_USER_NAME, ASTERISK_PASSWORD)
        objManager.Login()
    Catch ex As Exception

    End Try
End Sub

 Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    AsteriskManager.objManager = Nothing
End Sub
</code>```

can any one please help to do that

Thanks,
Senthil

答:
You claim to dispose it, but I don't see that in your code.
You could call Dispose on it if it implements IDisposable.

ContentLicense: CC BY-SA 3.0

Body:
How to dispose the shared variable in vb.net

i am using shared object of Asterisk.NET Manager Variable, i assigned it in form load
and i dispose it in main form closing, My problem is after closing the application, application.exe keeps live in task manager, if i not initializing the shared object in form load there is no problem,

My code in form open

  Public Shared WithEvents objManager As Asterisk.NET.Manager.ManagerConnection

  Public Shared Sub ConnectAsterisk()
    Try
        objManager = New Asterisk.NET.Manager.ManagerConnection(ELASTIX_IP_ADDRESS, ASTERISK_PORT, ASTERISK_USER_NAME, ASTERISK_PASSWORD)
        objManager.Login()
    Catch ex As Exception

    End Try
End Sub

 Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    AsteriskManager.objManager = Nothing
End Sub

can any one please help to do that

Thanks,
Senthil


问:
PKG_CHECK_MODULES syntax error near luajit
I'm new to GNU autotools.In my project when i try ./configure it generates following error :

```<code>./configure: line 9852: syntax error near unexpected token `luajit,'
./configure: line 9852: `    PKG_CHECK_MODULES(luajit, luajit,LLUAJIT="yes",LLUAJIT="no")'
</code>```

In Configure.in :

```<code> PKG_CHECK_MODULES(luajit, luajit,LLUAJIT="yes",LLUAJIT="no")
    if test "x$LLUAJIT" = "xyes"; then
        CONFIGFLAGS="$CONFIGFLAGS -DHAVE_LIBLUAJIT"
        LUA_CFLAGS="$luajit_CFLAGS"
        LUA_LIBS="$luajit_LIBS"
        AC_SUBST(LUA_CFLAGS)
        AC_SUBST(LUA_LIBS)
        if test "x$macos" != "xno"; then
            LDFLAGS="${LDFLAGS} -pagezero_size 10000 -image_base 100000000"
        fi

    else
        echo
        echo "   ERROR!  LuaJIT library not found. For better performance, go get it from"
        echo "   http://www.luajit.org/."
        AC_MSG_ERROR("Fatal!")
    fi
</code>```

It seems autoconf(maybe) is unable to find PKG_CHECK_MODULES macro. I searched the Internet for solution and found that it is because libtool is not installed.I re-installed libtool but error remains same.

Hope Someone recognizes the problem and has quick solution for it.Any help would be appreciated.

答: In my case, I added the conf file before installing the libtool, so you need to run again autoreconf -i -f after installing the libtool

Body:
I'm new to GNU autotools.In my project when i try ./configure it generates following error :

./configure: line 9852: syntax error near unexpected token `luajit,'
./configure: line 9852: `    PKG_CHECK_MODULES(luajit, luajit,LLUAJIT="yes",LLUAJIT="no")'

In Configure.in :

 PKG_CHECK_MODULES(luajit, luajit,LLUAJIT="yes",LLUAJIT="no")
    if test "x$LLUAJIT" = "xyes"; then
        CONFIGFLAGS="$CONFIGFLAGS -DHAVE_LIBLUAJIT"
        LUA_CFLAGS="$luajit_CFLAGS"
        LUA_LIBS="$luajit_LIBS"
        AC_SUBST(LUA_CFLAGS)
        AC_SUBST(LUA_LIBS)
        if test "x$macos" != "xno"; then
            LDFLAGS="${LDFLAGS} -pagezero_size 10000 -image_base 100000000"
        fi

    else
        echo
        echo "   ERROR!  LuaJIT library not found. For better performance, go get it from"
        echo "   http://www.luajit.org/."
        AC_MSG_ERROR("Fatal!")
    fi

It seems autoconf(maybe) is unable to find PKG_CHECK_MODULES macro. I searched the Internet for solution and found that it is because libtool is not installed.I re-installed libtool but error remains same.

Hope Someone recognizes the problem and has quick solution for it.Any help would be appreciated.


答:
Try this,</p>

```<code>>>> def type_convert(var):
    if var.isnumeric():
        return int(var)
    elif isinstance(var, str):
        return var
    else:
        return None

>>> [type_convert(i) for i in a]
[9327, 'Garlic Powder', 104, 13]
>>> new = [type_check(i) for i in a]
>>> [type(n) for n in new]
[<class 'int'>, <class 'str'>, <class 'int'>, <class 'int'>]
</code>```

Title: Conditionally convert string to int

Body:
Try this,

>>> def type_convert(var):
    if var.isnumeric():
        return int(var)
    elif isinstance(var, str):
        return var
    else:
        return None

>>> [type_convert(i) for i in a]
[9327, 'Garlic Powder', 104, 13]
>>> new = [type_check(i) for i in a]
>>> [type(n) for n in new]
[<class 'int'>, <class 'str'>, <class 'int'>, <class 'int'>]


问:
Why Next.js render "

```

why is that and how I can debug next.js to find out why the render method is not working? could it be because of my dependencies?

答:
Your content should be inside

 so don't mind the __NEXT_DATA__ script here. Check your Layout component and make sure you don't have a loading or conditional rendering. You can replace Layout with a simple paragraph to test the app.

Title: Why Next.js render "<script>__NEXT_DATA__ = ..." instead of the render() method of the page?

Body:
I'm using next.js and call my API calls in getInitialProps() and map them to props and its just fine. but when I get my page without JavaScript (like with chrome view-source:localhost) it's not rendering correctly.

this is my getInitialProps():

static async getInitialProps(props) {
    const res = await REQUEST_getCar();
    return {
        //this is for https://github.com/isaachinman/next-i18next
        namespacesRequired: ['common'],
        ...res
    };
}

and this is my first

render() {
    const { t, start, end, search_id } = this.props;
    const { error } = this.state;
    const { media_set, year, mileage_range, owner, body_style, color, color_code, cancellation_policy, transmission_type, location, facility_set, description, capacity, car } = this.props;
   return (

{description}

{capacity}

   );

but all I get inside my body tag is:

why is that and how I can debug next.js to find out why the render method is not working? could it be because of my dependencies?

Body: Your content should be inside <div id="__next"></div> so don't mind the __NEXT_DATA__ script here. Check your Layout component and make sure you don't have a loading or conditional rendering. You can replace Layout with a simple paragraph to test the app.


问:
AWS RDS MySQL database username and password sufficient for commercial security
I'm new to cloud computing so this might be an obvious question. I have a desktop Java application that will connect to an AWS RDS MySQL database using JDBC. Is using the endpoint, username and password for the database the preferred commercial way of connecting to the database?

To encrypt communication I plan to use SSL.

答:
You could open your database instance to the outside, using regular credentials.  But, a safer way to proceed might be to create an endpoint in AWS, possibly running in Java, which would expose one or more APIs which in turn would hit the MySQL database running in RDS.  That is, you would not expose the RDS instance to the outside world directly, but only internally to this API, also running in AWS.  Then, your desktop Java application would talk to this intermediary application when it needs to access the database.

The advantage of this suggestion is that it lessens the risk of your RDS instance being attacked via something like DOS.  Of course, the API you create on top of the database could also be attacked.  But, Java web application running in a container (and other similar applications in other languages) were designed to be exposed to the outside, much less so database instances.


问:
How can i passing data from recyclerview to fragment
I follow a youtube tutorial to write an application. this codes is a part of my recyclerViewAdapter

```<code>        vHolder.item_contact.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TextView dialog_name_tv = (TextView) myDialog.findViewById(R.id.dialog_name_id);
            TextView dialog_phone_tv = (TextView) myDialog.findViewById(R.id.dialog_phone_id);
            ImageView dialog_contact_img = (ImageView) myDialog.findViewById(R.id.dialog_img);
            TextView dialog_detail_tv = (TextView) myDialog.findViewById(R.id.dialog_detail);
            dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
            dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
            dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
            dialog_detail_tv.setText(mData.get(vHolder.getAdapterPosition()).getDetail());
            Toast.makeText(mContext, "Test Click" + String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
            myDialog.show();
            Button dialog_add_tv = (Button) myDialog.findViewById(R.id.dialog_add);
            dialog_add_tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EditText dialog_quantity_tv = (EditText) myDialog.findViewById(R.id.dialog_quantity);
                    quantity = dialog_quantity_tv.getText().toString();
                    name = mData.get(vHolder.getAdapterPosition()).getName()+"\n";
                    price = mData.get(vHolder.getAdapterPosition()).getPhone();
                    Intent i = new
                    Intent(getActivity(),FragmentFav.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("choices",choices);
                    bundle.putDouble("price",price);
                    i.putExtras(bundle);
                    startActivity(i);

                }
            });

        }
    });

    return vHolder;
}
</code>```

I want to Clicking the dialog_add_tv Button to pass the data to the fragment.class

```<code>public class FragmentFav extends Fragment {

View v;

public FragmentFav() {
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.call_fragment, container, false);
    return v;

}
</code>```

}

I try many times by using intent still happen error.

答:
Here are the step you can follow and implement what you need

Step 1:
Create an interface between adapter and fragment

Step 2:
Implement an interface in Adapter like this:

```<code> vHolder.item_contact.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
       mProfileItemClickListener.itemContact(v);
 }
</code>```

// aka Pass the whole view through an interface

Step 3:
In an interface, class add this method

```<code>void itemContact(View mView);
</code>```

Step 4:
Implement an interface in Fragment:

Where you will obtain an override method and perform your operation there

@Override
    public void itemContact(ImageView mProfileImageView) {
    Your code here
    }

You can handle callback properly while passing data between the views.

Body:
I follow a youtube tutorial to write an application. this codes is a part of my recyclerViewAdapter

        vHolder.item_contact.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TextView dialog_name_tv = (TextView) myDialog.findViewById(R.id.dialog_name_id);
            TextView dialog_phone_tv = (TextView) myDialog.findViewById(R.id.dialog_phone_id);
            ImageView dialog_contact_img = (ImageView) myDialog.findViewById(R.id.dialog_img);
            TextView dialog_detail_tv = (TextView) myDialog.findViewById(R.id.dialog_detail);
            dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
            dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
            dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
            dialog_detail_tv.setText(mData.get(vHolder.getAdapterPosition()).getDetail());
            Toast.makeText(mContext, "Test Click" + String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
            myDialog.show();
            Button dialog_add_tv = (Button) myDialog.findViewById(R.id.dialog_add);
            dialog_add_tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EditText dialog_quantity_tv = (EditText) myDialog.findViewById(R.id.dialog_quantity);
                    quantity = dialog_quantity_tv.getText().toString();
                    name = mData.get(vHolder.getAdapterPosition()).getName()+"\n";
                    price = mData.get(vHolder.getAdapterPosition()).getPhone();
                    Intent i = new
                    Intent(getActivity(),FragmentFav.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("choices",choices);
                    bundle.putDouble("price",price);
                    i.putExtras(bundle);
                    startActivity(i);

                }
            });

        }
    });

    return vHolder;
}

I want to Clicking the dialog_add_tv Button to pass the data to the fragment.class

public class FragmentFav extends Fragment {

View v;

public FragmentFav() {
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.call_fragment, container, false);
    return v;

}

}

I try many times by using intent still happen error.

Body:
Here are the step you can follow and implement what you need

Step 1:
Create an interface between adapter and fragment

Step 2:
Implement an interface in Adapter like this:

 vHolder.item_contact.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
       mProfileItemClickListener.itemContact(v);
 }

// aka Pass the whole view through an interface

Step 3:
In an interface, class add this method

void itemContact(View mView);

Step 4:
Implement an interface in Fragment:

Where you will obtain an override method and perform your operation there

@Override
    public void itemContact(ImageView mProfileImageView) {
    Your code here
    }

You can handle callback properly while passing data between the views.


问:
MonoTouch - should we go with the enterprise or professional license?
We are a software development company willing to develop iPhone/iPad apps for one of our clients.

We understand that for being able to deploy our application at our client, they have to register in Apple's iOS Developer Enterprise Program and add us in the development team.

It is unclear if we need to buy a MonoTouch license for Enterprise Distribution or a simple Professional license would allow us to sign and deploy the application on a large number of devices as long as the client is already registered in Apple's Enterprise Program.

Although the question is targeted at MonoTouch's licensing options, any practical advice on how to handle the common scenario described in the first phrase would also be of great help.

Thanks.

答:
There are two differences between the Professional and Enterprise licences for MonoTouch:

The professional license requires you to assign the license to a named developer. This means that you cannot share the license between employees in your organization. Enterprise licenses do not have this restriction.

In addition, the Enterprise license allows you to deploy applications outside the App Store. This is useful for applications deployed internally in an organization.

Apart from that the licenses are identical as far as I know. Both allow you to develop full iOS applications with no restrictions.

Depending on your need, you may want to go for the 5-pack of enterprise licenses. This gives you five licenses for the price of four, and lets all your employees share them. In many cases I think this is the best option.


问:
Is there a way to write to a file on server in react one page app?
Long story short I was asked to create an interface for an API in my internship. Then I don't know why i decided to try react and made a one page static app with it. Now my supervisor wants to keep a log of how people are using the site. Basically I want to add one more line to a file on server everytime a specific button is clicked. I found no answer for this except with a server like nodejs+express. I can add that but I am wondering if its possible without implementing a server myself. Thanks.</p>

答:
Shortest Way:
Use apache to create a web server and you can access the logs from the apache directory.

https://httpd.apache.org/docs/2.4/platform/windows.html

Get apache from here and install it on your system. I am assuming you're using windows

Place your app after building (npm run build) into the htdocs directory.
Check apache access logs to see visitor info

Proper Way:

Create an express app and expose an api: /log_visit
in log_visit, store the request ip, page etc into a database(or file)

Send /log_visit an ajax request everytime your react page changes


问:
How to delete foreign key as well as primary key
I want to use SQL and PHP to delete a specific row, events, and the foreign key eventlocation along with it. I tried to use an inner join function, but this gave me an error. Any ideas?</p>

```<code>DELETE FROM Events, EventLocation JOIN ON EventLocation.EventLocationID = Events.EventLocationID WHERE EventID = '".$_POST["id"]."' AND EventLocationID = '".$_POST["id"]."'
</code>```

答:
Well bellow query works fine.

DELETE Events, EventLocation
     FROM Events INNER JOIN EventLocation
 WHERE Events.EventID=EventLocation.EventID

But in this case you handle easily if the table EventLocation setting Cascade On Delete with EventID whwres EventID is a foreign key of table EventLocation and primary key of table Events.
Then you just delete row of Events. So the row of EventLocation delete autometically which along with Events.

Body:
I want to use SQL and PHP to delete a specific row, events, and the foreign key eventlocation along with it. I tried to use an inner join function, but this gave me an error. Any ideas?

DELETE FROM Events, EventLocation JOIN ON EventLocation.EventLocationID = Events.EventLocationID WHERE EventID = '".$_POST["id"]."' AND EventLocationID = '".$_POST["id"]."'


问:
When I run this code I get error admin is not defined
How to retrieve user list from fire base authentication? I want to retrieve all register user list. When I'm using listAllUsers()-function, I get a message that "admin is not defined".

I'm using this function:

```<code>function listAllUsers(nextPageToken) {
  admin.auth().listUsers(1000, nextPageToken)
    .then(function(listUsersResult) {
        listUsersResult.users.forEach(function(userRecord) {
            console.log('user', userRecord.toJSON());
        });
        if (listUsersResult.pageToken) {
            listAllUsers(listUsersResult.pageToken);
        }
    })
    .catch(function(error) {
          console.log('Error listing users:', error);
    });
}
</code>```

答:
Check everything is imported first.
Then Clear the config cache php artisan config:clear or rebuild it php artisan config:cache.</p>

Body:
How to retrieve user list from fire base authentication? I want to retrieve all register user list. When I'm using listAllUsers()-function, I get a message that "admin is not defined".

I'm using this function:

function listAllUsers(nextPageToken) {
  admin.auth().listUsers(1000, nextPageToken)
    .then(function(listUsersResult) {
        listUsersResult.users.forEach(function(userRecord) {
            console.log('user', userRecord.toJSON());
        });
        if (listUsersResult.pageToken) {
            listAllUsers(listUsersResult.pageToken);
        }
    })
    .catch(function(error) {
          console.log('Error listing users:', error);
    });
}


问:
how to load sql dump using mysql_query in php
To install a cms i have a form in which i ask user to enter a database name he wants the script to make tables into. After that i have my only three cms tables.

i am trying to read that dump.sql file using the file = get_file_contents(dump.sql) and then mysql_query($file);
but nothing is happening please suggest or help.

答:
mysql_query can not run multiple queries in once.

you can try mysqli:multi_query() function

OR

There is another way to do this with exec and mysql command.

You can execute the mysql command to store the tables in database using the exec function of php.

That will be something like this

```<code>$Command = "mysql -u {$username} -p{$password} {$database} < {$BackupFile}";
exec($Command);
</code>```

Body:
mysql_query can not run multiple queries in once.

you can try mysqli:multi_query() function

OR

There is another way to do this with exec and mysql command.

You can execute the mysql command to store the tables in database using the exec function of php.

That will be something like this

$Command = "mysql -u {$username} -p{$password} {$database} < {$BackupFile}";
exec($Command);


问:
Force OpenSSL to not use /etc/pki/CA/newcerts
I am trying to generate the CA key for my server but I don't have root access. So  when I run the code below. I obviously get the permission denied error. Is there a way to force it to write somewhere else like under my users folder?

I looked through the parameters for openssl and couldn't find anything that seemed to be what I needed

```<code>openssl ca -extensions v3_ca -out /home/cdonohue/certs/ca.pem -keyfile /home/cdonohue/certs/server-key.pem -verbose -selfsign -md sha256 -enddate 330630235959Z -infiles /home/cdonohue/certs/server-crt.pem
Using configuration from /etc/pki/tls/openssl.cnf
Enter pass phrase for /home/cdonohue/certs/server-key.pem:
I am unable to access the /etc/pki/CA/newcerts directory
</code>```

答:
The commandline option for ca to override new_certs_dir is -outdir, as stated on the man page.

However, the serial and 'index' files are conventionally in the same place, so you probably won't be able to write them either, and they have no commandline options. To get around those you'll need to create and use your own config file, and once you do that you no longer need most of the options you are now using.

Also using section v3_ca from the default config file will produce a certificate that is not really suitable for a server certificate, although it will probably work at least in some cases. And using any self-signed cert for a server is dubious, unless the server is accessed only by clients within a reasonably small community (like an organization's intranet) or for debugging and testing.

However, once you aren't using any of the files of the 'system' CA configuration and you are issuing a self-signed cert, there isn't really any point to using ca to do this unless you really need that exact expiration (unlikely) or you are using copy_extensions, which is disabled in the default config. Otherwise, either req -x509 or x509 -req -signkey can produce an equivalent self-signed cert from a CSR much more simply. And there are numerous Qs on StackOverflow, SuperUser, ServerFault, and Security.SX about both of them, as well as the man pages.

Body:
I am trying to generate the CA key for my server but I don't have root access. So  when I run the code below. I obviously get the permission denied error. Is there a way to force it to write somewhere else like under my users folder?

I looked through the parameters for openssl and couldn't find anything that seemed to be what I needed

openssl ca -extensions v3_ca -out /home/cdonohue/certs/ca.pem -keyfile /home/cdonohue/certs/server-key.pem -verbose -selfsign -md sha256 -enddate 330630235959Z -infiles /home/cdonohue/certs/server-crt.pem
Using configuration from /etc/pki/tls/openssl.cnf
Enter pass phrase for /home/cdonohue/certs/server-key.pem:
I am unable to access the /etc/pki/CA/newcerts directory


问:
MPI_Irecv doesn't receive message in this easy code
I have this code for testing MPI_Irecv and MPI_Isend

    if(rank==1){
        int cc;
        MPI_Request request;
        MPI_Status status;
        int flag;
        do{
            MPI_Irecv(&cc, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, allcomm, &request);
            //MPI_Wait(&request, &status);
            MPI_Test(&request, &flag, &status);
            if (flag != 0) {
                printf("recv : %d, slave : %d\n", cc, status.MPI_SOURCE);
            }
        } while(flag != 0);

    }
    if(rank==0){
        int cc=0;
        MPI_Request request;
        for(int i=1;i<10;i++){
            cc+=1;
            MPI_Isend(&cc, 1, MPI_INT, 1, 0, allcomm, &request);
        }
    }
```

<p>If I execute this code, sometimes it prints cc from 1 to 9 and sometimes it prints nothing.</p>

<p>It makes sense, since the process 0 may be executed after process 1 finish.</p>

<p>However, if I let process 1 be a infinity loop like this:</p>

<pre class="lang-c prettyprint-override"><code>    if(rank==1){
        int cc;
        MPI_Request request;
        MPI_Status status;
        int flag;
        do{
            MPI_Irecv(&cc, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, allcomm, &request);
            //MPI_Wait(&request, &status);
            MPI_Test(&request, &flag, &status);
            if (flag != 0) {
                printf("recv : %d, slave : %d\n", cc, status.MPI_SOURCE);
            }
        } while(true);

    }
</code>```

I think process 1 will print cc from 1 to 9 every time, but it won't.

If I insert MPI_Wait() in process 1, it seems process 1 will print cc from 1 to 9 every time. But it will also wait forever if there is nothing sent by other process and I want non-blocking communication actually.

Reply to comments:

1.About version:
mpiexec --version
mpiexec (OpenRTE) 2.1.1

2.I don't get the point what 'MPI progress thread' means.

Actually I want each process can communicate with each other without blocking and get the information in the buffer each time when receive.

3.executable code following

#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <unistd.h>

int main(void)
{
    MPI_Comm allcomm;
    int i;
    int size, rank, irank;
    int tablesize, localtablesize;
    int *table,*table2;

    allcomm = MPI_COMM_WORLD;
    MPI_Init(NULL, NULL);
    MPI_Comm_size(allcomm, &size);
    MPI_Comm_rank(allcomm, &rank);

    if(rank==1){
        int cc;
        MPI_Request request;
        MPI_Status status;
        int flag;
        do{
            MPI_Irecv(&cc, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, allcomm, &request);
            //MPI_Wait(&request, &status);
            MPI_Test(&request, &flag, &status);
            if (flag != 0) {
                printf("recv : %d, slave : %d\n", cc, status.MPI_SOURCE);
            }
        } //while(flag!=0);
        while(true);

    }
    if(rank==0){
        int cc=0;
        MPI_Request request;
        for(int i=1;i<10;i++){
            cc+=1;
            MPI_Isend(&cc, 1, MPI_INT, 1, 0, allcomm, &request);
        }
    }
    MPI_Finalize();
}
```

答:
Your program is incorrect.

For example, if rank 1 is faster than rank 0, the first MPI_Test() will not match any message and then go straight to MPI_Finalize()

Bottom line, this program might print between 0 and 10 lines.
This program will only print 10 lines if rank 1 is somehow lagging behind rank 0, but since both ranks are not synchronized, this is quite unlikely to happen.

Body:
I have this code for testing MPI_Irecv and MPI_Isend

    if(rank==1){
        int cc;
        MPI_Request request;
        MPI_Status status;
        int flag;
        do{
            MPI_Irecv(&cc, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, allcomm, &request);
            //MPI_Wait(&request, &status);
            MPI_Test(&request, &flag, &status);
            if (flag != 0) {
                printf("recv : %d, slave : %d\n", cc, status.MPI_SOURCE);
            }
        } while(flag != 0);

    }
    if(rank==0){
        int cc=0;
        MPI_Request request;
        for(int i=1;i<10;i++){
            cc+=1;
            MPI_Isend(&cc, 1, MPI_INT, 1, 0, allcomm, &request);
        }
    }

If I execute this code, sometimes it prints cc from 1 to 9 and sometimes it prints nothing.

It makes sense, since the process 0 may be executed after process 1 finish.

However, if I let process 1 be a infinity loop like this:

    if(rank==1){
        int cc;
        MPI_Request request;
        MPI_Status status;
        int flag;
        do{
            MPI_Irecv(&cc, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, allcomm, &request);
            //MPI_Wait(&request, &status);
            MPI_Test(&request, &flag, &status);
            if (flag != 0) {
                printf("recv : %d, slave : %d\n", cc, status.MPI_SOURCE);
            }
        } while(true);

    }

I think process 1 will print cc from 1 to 9 every time, but it won't.

If I insert MPI_Wait() in process 1, it seems process 1 will print cc from 1 to 9 every time. But it will also wait forever if there is nothing sent by other process and I want non-blocking communication actually.

Reply to comments:

1.About version:
mpiexec --version
mpiexec (OpenRTE) 2.1.1

2.I don't get the point what 'MPI progress thread' means.

Actually I want each process can communicate with each other without blocking and get the information in the buffer each time when receive.

3.executable code following

#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <unistd.h>

int main(void)
{
    MPI_Comm allcomm;
    int i;
    int size, rank, irank;
    int tablesize, localtablesize;
    int *table,*table2;

    allcomm = MPI_COMM_WORLD;
    MPI_Init(NULL, NULL);
    MPI_Comm_size(allcomm, &size);
    MPI_Comm_rank(allcomm, &rank);

    if(rank==1){
        int cc;
        MPI_Request request;
        MPI_Status status;
        int flag;
        do{
            MPI_Irecv(&cc, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, allcomm, &request);
            //MPI_Wait(&request, &status);
            MPI_Test(&request, &flag, &status);
            if (flag != 0) {
                printf("recv : %d, slave : %d\n", cc, status.MPI_SOURCE);
            }
        } //while(flag!=0);
        while(true);

    }
    if(rank==0){
        int cc=0;
        MPI_Request request;
        for(int i=1;i<10;i++){
            cc+=1;
            MPI_Isend(&cc, 1, MPI_INT, 1, 0, allcomm, &request);
        }
    }
    MPI_Finalize();
}


问:
Tree structure using recursion in angular 6
I have this type of json and I want tree structure using recursion in angular 6.
I can't change the json format
I have to create another component for recursion.
I have tried using for loop and also tried using recursive list with the help of ng-container and ng- template. but it doesn't work
For the expected output I have shared a link of the image.

Thanks in advance.

```<code> {
      "layers": [
        {
          "id": 0,
          "name": "Parks",
          "parentLayerId": -1,
          "subLayerIds": [1, 2, 3, 4]
        },
        {
          "id": 2,
          "name": "Trails",
          "parentLayerId": 0,
          "subLayerIds": null,

        },
        {
          "id": 3,
          "name": "Pleasanton_Parks",
          "parentLayerId": 0,
          "subLayerIds": null,

        },

        {
          "id": 9,
          "name": "wManholes",
          "parentLayerId": 5,
          "subLayerIds": null,

        },
        {
          "id": 10,
          "name": "wMeters_CityWater",
          "parentLayerId": 5,
          "subLayerIds": null,

        },{
          "id": 51,
          "name": "parcels",
          "parentLayerId": 46,
          "subLayerIds": [52, 53]
        },
        {
          "id": 52,
          "name": "binit root 31",
          "parentLayerId": 51,
          "subLayerIds": null,
        },
        {
          "id": 53,
          "name": "binit root 32",
          "parentLayerId": 51,
          "subLayerIds": [54],

        },
        {
          "id": 54,
          "name": "binit root 41",
          "parentLayerId": 53,
          "subLayerIds": null,
        },
    ]
    }
</code>```

答:
```<code> public getChildren(arr,parentId ) {
     //console.log("arr , parentId",arr,parentId)
     let output = [];
     for (const obj of arr)
     {
       //console.log("obj",obj)
       if(obj.parentLayerId == parentId)
       {
         var children = this.getChildren(arr,obj.id)
         if(children.length)
         {
           obj.children = children
         }
         output.push(obj)
      }
     }
     console.log("output",output)
     return output
   }
</code>```

Body:
I have this type of json and I want tree structure using recursion in angular 6.
I can't change the json format
I have to create another component for recursion.
I have tried using for loop and also tried using recursive list with the help of ng-container and ng- template. but it doesn't work
For the expected output I have shared a link of the image.

Thanks in advance.

 {
      "layers": [
        {
          "id": 0,
          "name": "Parks",
          "parentLayerId": -1,
          "subLayerIds": [1, 2, 3, 4]
        },
        {
          "id": 2,
          "name": "Trails",
          "parentLayerId": 0,
          "subLayerIds": null,

        },
        {
          "id": 3,
          "name": "Pleasanton_Parks",
          "parentLayerId": 0,
          "subLayerIds": null,

        },

        {
          "id": 9,
          "name": "wManholes",
          "parentLayerId": 5,
          "subLayerIds": null,

        },
        {
          "id": 10,
          "name": "wMeters_CityWater",
          "parentLayerId": 5,
          "subLayerIds": null,

        },{
          "id": 51,
          "name": "parcels",
          "parentLayerId": 46,
          "subLayerIds": [52, 53]
        },
        {
          "id": 52,
          "name": "binit root 31",
          "parentLayerId": 51,
          "subLayerIds": null,
        },
        {
          "id": 53,
          "name": "binit root 32",
          "parentLayerId": 51,
          "subLayerIds": [54],

        },
        {
          "id": 54,
          "name": "binit root 41",
          "parentLayerId": 53,
          "subLayerIds": null,
        },
    ]
    }


问:
getting error while feeding inferences of one model to the generator of another model in keras
I have designed an autoencoder and trained it. Now, I want to extract features from the encoder and feed them to the generator of another model.

This is the autoencoder I have implemented.

```<code>
    x = Conv1D(64, 5, activation="relu", padding="same")(input)
    #x = BatchNormalization()(x)
    x = MaxPooling1D(2, padding="same")(x)
    x = Conv1D(32, 5, activation="relu", padding="same")(x)
    #x = BatchNormalization()(x)
    x = MaxPooling1D(2, padding="same")(x)
    x = Conv1D(16, 5, activation="relu", padding="same")(x)
    x = MaxPooling1D(2, padding="same")(x)
    x = Conv1D(1, 5, activation="relu", padding="same")(x)
    encoded = MaxPooling1D(2, padding="same")(x)

    x = Conv1D(1, 5, activation="relu", padding="same")(encoded)
    #x = BatchNormalization()(x)
    x = UpSampling1D(2)(x)
    x = Conv1D(16, 2, activation='relu',padding='same')(x)
    x = UpSampling1D(2)(x)
    x = Conv1D(32, 2, activation='relu',padding='same')(x)
    #x = BatchNormalization()(x)
    x = UpSampling1D(2, )(x)
    x = Conv1D(64, 2, activation='relu',padding='same')(x)
    x = UpSampling1D(2, )(x)
    decoded = Conv1D(1, 3, activation='sigmoid', padding='same')(x)

    autoencoder = Model(input, decoded)
</code>```

This is where I am getting the outputs of the encoder part.

```<code>def extract_features_from_encoder(left,right):
   get_8th_layer_output = K.function([autoencoder.layers[0].input],

      [autoencoder.layers[8].output])

   left_encoded = get_8th_layer_output([left])[0]
   right_encoded = get_8th_layer_output([right])[0]

</code>```

This is my generator:

```<code>def generator_encoded():
   left = ...
   right = ...

   left_encoded,right_encoded =
   extract_features_from_encoder(left,right)

   yield ({'input_1': left_encoded, 'input_2': right_encoded},
   {'dense_1': y})

</code>```

This is where I am calling the generator:

```<code>model.fit_generator(generator_encoded(),......)

</code>```

This is my model.

```<code>input_l = Input(shape=(1000,1))
input_r = Input(shape=(1000,1))

shared_lstm = CuDNNLSTM(100)
encoded_l = shared_lstm(input_l)
encoded_r = shared_lstm(input_r)

L1_layer = Lambda(lambda tensors:K.abs(tensors[0] - tensors[1]))
L1_distance = L1_layer([encoded_l, encoded_r])

prediction = Dense(1,activation='sigmoid')(L1_distance)

model = Model(inputs=[input_l,input_r],outputs=prediction)

</code>```

This is the error I am getting while running this model.

```<code>tensorflow.python.framework.errors_impl.InvalidArgumentError:
Tensor input_2:0, specified in either feed_devices or
fetch_devices was not found in the Graph

</code>```

Can anyone please tell me what is wrong and how to fix it?

答: The issue has been resolved. Adding with tf.Session: before taking the inferences from the autoencoder made the issue disappear. The model needed to be told explicitly to use the default graph as there were multiple graphs instantiated.

Body:
I have designed an autoencoder and trained it. Now, I want to extract features from the encoder and feed them to the generator of another model.

This is the autoencoder I have implemented.

    x = Conv1D(64, 5, activation="relu", padding="same")(input)
    #x = BatchNormalization()(x)
    x = MaxPooling1D(2, padding="same")(x)
    x = Conv1D(32, 5, activation="relu", padding="same")(x)
    #x = BatchNormalization()(x)
    x = MaxPooling1D(2, padding="same")(x)
    x = Conv1D(16, 5, activation="relu", padding="same")(x)
    x = MaxPooling1D(2, padding="same")(x)
    x = Conv1D(1, 5, activation="relu", padding="same")(x)
    encoded = MaxPooling1D(2, padding="same")(x)

    x = Conv1D(1, 5, activation="relu", padding="same")(encoded)
    #x = BatchNormalization()(x)
    x = UpSampling1D(2)(x)
    x = Conv1D(16, 2, activation='relu',padding='same')(x)
    x = UpSampling1D(2)(x)
    x = Conv1D(32, 2, activation='relu',padding='same')(x)
    #x = BatchNormalization()(x)
    x = UpSampling1D(2, )(x)
    x = Conv1D(64, 2, activation='relu',padding='same')(x)
    x = UpSampling1D(2, )(x)
    decoded = Conv1D(1, 3, activation='sigmoid', padding='same')(x)

    autoencoder = Model(input, decoded)

This is where I am getting the outputs of the encoder part.

def extract_features_from_encoder(left,right):
   get_8th_layer_output = K.function([autoencoder.layers[0].input],

      [autoencoder.layers[8].output])

   left_encoded = get_8th_layer_output([left])[0]
   right_encoded = get_8th_layer_output([right])[0]

This is my generator:

def generator_encoded():
   left = ...
   right = ...

   left_encoded,right_encoded =
   extract_features_from_encoder(left,right)

   yield ({'input_1': left_encoded, 'input_2': right_encoded},
   {'dense_1': y})

This is where I am calling the generator:

model.fit_generator(generator_encoded(),......)

This is my model.

input_l = Input(shape=(1000,1))
input_r = Input(shape=(1000,1))

shared_lstm = CuDNNLSTM(100)
encoded_l = shared_lstm(input_l)
encoded_r = shared_lstm(input_r)

L1_layer = Lambda(lambda tensors:K.abs(tensors[0] - tensors[1]))
L1_distance = L1_layer([encoded_l, encoded_r])

prediction = Dense(1,activation='sigmoid')(L1_distance)

model = Model(inputs=[input_l,input_r],outputs=prediction)

This is the error I am getting while running this model.

tensorflow.python.framework.errors_impl.InvalidArgumentError:
Tensor input_2:0, specified in either feed_devices or
fetch_devices was not found in the Graph

Can anyone please tell me what is wrong and how to fix it?


问:
How do I prevent output ActiveRecord::Base.logger from within a method?
The method below takes a few minutes to print out the database entry each time I call it in the console. I need to see the printing the rest of the time so shutting it off entirely isn't an option.

This is my unsuccessful attempt to stop the printing in the method directly.

def generate_dataset
  old_logger = ActiveRecord::Base.logger
  ActiveRecord::Base.logger = nil

  ProductDatum.create(product_names: Products.all.pluck(:name))

  ActiveRecord::Base.logger = old_logger
end

```

答:
You're looking for #silence, which takes a block during which the logger is silenced:

def generate_dataset
  ActiveRecord::Base.logger.silence do
    ProductDatum.create(product_names: Products.all.pluck(:name))
  end
end
```


问:
Streaming [Random Access] encrypted (AES-CTR) video on the fly using web proxy (nanoHTTPD)
I have an encrypted (128-AES-CTR-NoPadding) video residing on a server which I need to decrypt as it downloads, so that user can stream it (in normal players/web).

I understand the components of this solution and how they should be put together to make this work. It partially works but for the rest I just can't implement streaming right. I have been reading and learning from examples (most of which is playing a file on disk, which is not the case here) on this for the past week and have come to conclusion this is beyond me and I need some help.

Details

I am using a Lightweight webserver (nanoHttpd) acting as a proxy to download the encrypted data from remote server and serve decrypted data. Below are the main codes inside my NanoHTTPD.serve method.

```<code>//create urlConnection to encrypted video file with proper headers (ie range headers) as request received by the proxy server
InputStream inputStream = new CipherInputStream(cipher, urlConnection.getInputStream());
return newChunkedResponse(status, contentType,inputStream);
</code>```

So now if I go to my NanoHttpd webserver (http://localhost:9000), the file starts downloading and after the download completes, the file is fully decrypted and playable as expected.
So this ensures that getting encrypted data from the server and serving decrypted data is working correctly.
But when any video player (html5, vlc) is asked to stream the video from that url, it simply does not work.

If the above code in NanoHTTPD.serve changed to

```<code>//create urlConnection to cleardata video file with proper headers (ie range headers) as request received by the proxy server
    InputStream inputStream = urlConnection.getInputStream();
    return newChunkedResponse(status, contentType,inputStream);
</code>```

And then try to stream from the aforementioned players, it'll work just fine.
So this ensures that the web proxy is correcting retrieving and feeding data.

Potential problem
To support range requests from the video player we will need to correctly skip to block boundary that is a multiple of cipher block size. So it's possible that when video player is requesting data with header (range: bytes 34-44), the CipherInputStream is probably failing to decrypt the data since the inputstream has data from 34-44. But I am at a loss on how to do this with urlConnection.getInputStream() and CipherInputStream.

But even without this, it should at least start playing the first few seconds because the first request video player sends is (range: 0-) which means inputStream is starting from index 0 so CipherInputStream should be able to decrypt and serve those initial bytes and the video should continue playing.

I am at a complete loss because I don't know how to debug this. Any ideas, sample codes are welcome, I'll try them out and post the results here.

答:
I have figure this out. I'll post the solution here for others.

The problem here was the ranged requests. If the proxy does not send proper responses to these range requests, the playback will fail. This can fail due to a number of reasons.

Your requests to remote server is missing proper range headers.

Your requests to remote server is returning proper ranged data, but you are not decrypting it correctly. This was my case. Of course this decryption process will vary cipher to cipher. For me, I used (AES/CRT/NOPADDING), I was supplying correct iv for the offset. How to calculate iv for offset is described here.

As far as code samples go, I only had to add one line before

```<code>InputStream inputStream = new CipherInputStream(cipher, urlConnection.getInputStream());
return newChunkedResponse(status, contentType,inputStream);
</code>```

which is

```<code>jumpToOffset(cipher,....);
</code>```

After this everything was working correctly including seeking of the video.

Body:
I have an encrypted (128-AES-CTR-NoPadding) video residing on a server which I need to decrypt as it downloads, so that user can stream it (in normal players/web).

I understand the components of this solution and how they should be put together to make this work. It partially works but for the rest I just can't implement streaming right. I have been reading and learning from examples (most of which is playing a file on disk, which is not the case here) on this for the past week and have come to conclusion this is beyond me and I need some help.

Details

I am using a Lightweight webserver (nanoHttpd) acting as a proxy to download the encrypted data from remote server and serve decrypted data. Below are the main codes inside my NanoHTTPD.serve method.

//create urlConnection to encrypted video file with proper headers (ie range headers) as request received by the proxy server
InputStream inputStream = new CipherInputStream(cipher, urlConnection.getInputStream());
return newChunkedResponse(status, contentType,inputStream);

So now if I go to my NanoHttpd webserver (http://localhost:9000), the file starts downloading and after the download completes, the file is fully decrypted and playable as expected.
So this ensures that getting encrypted data from the server and serving decrypted data is working correctly.
But when any video player (html5, vlc) is asked to stream the video from that url, it simply does not work.

If the above code in NanoHTTPD.serve changed to

//create urlConnection to cleardata video file with proper headers (ie range headers) as request received by the proxy server
    InputStream inputStream = urlConnection.getInputStream();
    return newChunkedResponse(status, contentType,inputStream);

And then try to stream from the aforementioned players, it'll work just fine.
So this ensures that the web proxy is correcting retrieving and feeding data.

Potential problem
To support range requests from the video player we will need to correctly skip to block boundary that is a multiple of cipher block size. So it's possible that when video player is requesting data with header (range: bytes 34-44), the CipherInputStream is probably failing to decrypt the data since the inputstream has data from 34-44. But I am at a loss on how to do this with urlConnection.getInputStream() and CipherInputStream.

But even without this, it should at least start playing the first few seconds because the first request video player sends is (range: 0-) which means inputStream is starting from index 0 so CipherInputStream should be able to decrypt and serve those initial bytes and the video should continue playing.

I am at a complete loss because I don't know how to debug this. Any ideas, sample codes are welcome, I'll try them out and post the results here.

Body:
I have figure this out. I'll post the solution here for others.

The problem here was the ranged requests. If the proxy does not send proper responses to these range requests, the playback will fail. This can fail due to a number of reasons.

Your requests to remote server is missing proper range headers.

Your requests to remote server is returning proper ranged data, but you are not decrypting it correctly. This was my case. Of course this decryption process will vary cipher to cipher. For me, I used (AES/CRT/NOPADDING), I was supplying correct iv for the offset. How to calculate iv for offset is described here.

As far as code samples go, I only had to add one line before

InputStream inputStream = new CipherInputStream(cipher, urlConnection.getInputStream());
return newChunkedResponse(status, contentType,inputStream);

which is

jumpToOffset(cipher,....);

After this everything was working correctly including seeking of the video.