问:
Json4s: Decomposing to JValue gives ArrayIndexOutOfBoundsException
I am using Extraction.decompose to produce a JValue and it is intermittently failing. I am asking it to decompose a Seq of the following case class:

```<code>case class Item(locators: Seq[String], dateAdded: DateTime = new DateTime(0L), newVersionSinceCuration: Option[Boolean] = None)
</code>```

The DateTime is a org.joda.time.DateTime.

The same line of code will work the majority of times but every few minutes will fail with the following stack trace:

```<code>java.lang.ArrayIndexOutOfBoundsException: 14
    at sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate(BaseCalendar.java:453)
    at java.util.GregorianCalendar.computeFields(GregorianCalendar.java:2397)
    at java.util.GregorianCalendar.computeFields(GregorianCalendar.java:2312)
    at java.util.Calendar.complete(Calendar.java:2268)
    at java.util.Calendar.get(Calendar.java:1826)
    at java.text.SimpleDateFormat.subFormat(SimpleDateFormat.java:1119)
    at java.text.SimpleDateFormat.format(SimpleDateFormat.java:966)
    at java.text.SimpleDateFormat.format(SimpleDateFormat.java:936)
    at java.text.DateFormat.format(DateFormat.java:345)
    at org.json4s.DefaultFormats$$anon$4.format(Formats.scala:358)
    at org.json4s.ext.DateTimeSerializer$$anonfun$$lessinit$greater$4$$anonfun$apply$8.applyOrElse(JodaTimeSerializers.scala:78)
    at scala.PartialFunction$OrElse.apply(PartialFunction.scala:167)
    at org.json4s.ext.InstantSerializer$$anonfun$$lessinit$greater$3$$anonfun$apply$6.applyOrElse(JodaTimeSerializers.scala:57)
    at scala.PartialFunction$OrElse.apply(PartialFunction.scala:167)
    at org.json4s.ext.DurationSerializer$$anonfun$$lessinit$greater$2$$anonfun$apply$4.applyOrElse(JodaTimeSerializers.scala:47)
    at scala.PartialFunction$OrElse.apply(PartialFunction.scala:167)
    at scala.PartialFunction$class.applyOrElse(PartialFunction.scala:123)
    at scala.collection.AbstractMap.applyOrElse(Map.scala:59)
    at scala.PartialFunction$OrElse.apply(PartialFunction.scala:167)
    at org.json4s.Extraction$.internalDecomposeWithBuilder(Extraction.scala:146)
    at org.json4s.Extraction$.addField$1(Extraction.scala:110)
    at org.json4s.Extraction$.decomposeObject$1(Extraction.scala:140)
    at org.json4s.Extraction$.internalDecomposeWithBuilder(Extraction.scala:228)
    at org.json4s.Extraction$.internalDecomposeWithBuilder(Extraction.scala:189)
    at org.json4s.Extraction$.decomposeWithBuilder(Extraction.scala:64)
    at org.json4s.Extraction$.decompose(Extraction.scala:242)

    ...
</code>```

So it seems to fail to parse the DateTime. I'm overriding the date format as per the Json4s documentation with the following:

```<code>implicit def json4sFormats = new DefaultFormats {
    override val dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
    dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"))
} ++ JodaTimeSerializers.all
</code>```

I've googled around ArrayIndexOutOfBoundsException problems with sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate and SimpleDateFormat and there's lots of posts about SimpleDateFormat not being thread safe. That seems like it could explain the error but I can see that Json4s wraps the dateFormatter in a ThreadLocal, which I understand should make it thread safe.

Any thoughts on what might be going on here?

I am using Scala 2.11.8, Json4s 3.5.1, OpenJDK 1.8.0.

Cheers,
Paul

答: You are defeating the ThreadLocal by making your dateFormatter a val instead of def as in the linked source for DefaultFormats, so all threads end up referring to the same instance. Of course, when you make it a def, setTimeZone needs to be done inside the definition.

Body:
I am using Extraction.decompose to produce a JValue and it is intermittently failing. I am asking it to decompose a Seq of the following case class:

case class Item(locators: Seq[String], dateAdded: DateTime = new DateTime(0L), newVersionSinceCuration: Option[Boolean] = None)

The DateTime is a org.joda.time.DateTime.

The same line of code will work the majority of times but every few minutes will fail with the following stack trace:

java.lang.ArrayIndexOutOfBoundsException: 14
    at sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate(BaseCalendar.java:453)
    at java.util.GregorianCalendar.computeFields(GregorianCalendar.java:2397)
    at java.util.GregorianCalendar.computeFields(GregorianCalendar.java:2312)
    at java.util.Calendar.complete(Calendar.java:2268)
    at java.util.Calendar.get(Calendar.java:1826)
    at java.text.SimpleDateFormat.subFormat(SimpleDateFormat.java:1119)
    at java.text.SimpleDateFormat.format(SimpleDateFormat.java:966)
    at java.text.SimpleDateFormat.format(SimpleDateFormat.java:936)
    at java.text.DateFormat.format(DateFormat.java:345)
    at org.json4s.DefaultFormats$$anon$4.format(Formats.scala:358)
    at org.json4s.ext.DateTimeSerializer$$anonfun$$lessinit$greater$4$$anonfun$apply$8.applyOrElse(JodaTimeSerializers.scala:78)
    at scala.PartialFunction$OrElse.apply(PartialFunction.scala:167)
    at org.json4s.ext.InstantSerializer$$anonfun$$lessinit$greater$3$$anonfun$apply$6.applyOrElse(JodaTimeSerializers.scala:57)
    at scala.PartialFunction$OrElse.apply(PartialFunction.scala:167)
    at org.json4s.ext.DurationSerializer$$anonfun$$lessinit$greater$2$$anonfun$apply$4.applyOrElse(JodaTimeSerializers.scala:47)
    at scala.PartialFunction$OrElse.apply(PartialFunction.scala:167)
    at scala.PartialFunction$class.applyOrElse(PartialFunction.scala:123)
    at scala.collection.AbstractMap.applyOrElse(Map.scala:59)
    at scala.PartialFunction$OrElse.apply(PartialFunction.scala:167)
    at org.json4s.Extraction$.internalDecomposeWithBuilder(Extraction.scala:146)
    at org.json4s.Extraction$.addField$1(Extraction.scala:110)
    at org.json4s.Extraction$.decomposeObject$1(Extraction.scala:140)
    at org.json4s.Extraction$.internalDecomposeWithBuilder(Extraction.scala:228)
    at org.json4s.Extraction$.internalDecomposeWithBuilder(Extraction.scala:189)
    at org.json4s.Extraction$.decomposeWithBuilder(Extraction.scala:64)
    at org.json4s.Extraction$.decompose(Extraction.scala:242)

    ...

So it seems to fail to parse the DateTime. I'm overriding the date format as per the Json4s documentation with the following:

implicit def json4sFormats = new DefaultFormats {
    override val dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
    dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"))
} ++ JodaTimeSerializers.all

I've googled around ArrayIndexOutOfBoundsException problems with sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate and SimpleDateFormat and there's lots of posts about SimpleDateFormat not being thread safe. That seems like it could explain the error but I can see that Json4s wraps the dateFormatter in a ThreadLocal, which I understand should make it thread safe.

Any thoughts on what might be going on here?

I am using Scala 2.11.8, Json4s 3.5.1, OpenJDK 1.8.0.

Cheers,
Paul


来源: stackexchange

问:
Connection pooling and Multithreading for TCP Socket?
I have a java application(say A) which communicate with an application(say B) via TCP Socket. My java application is multithreaded, can handle up to 100 threads. To communicate between A --> B we have 10 sockets.

Challenges -

Connection Pooling - need connection pooling mechanism to handle n(say 100) number of thread(of application A), communicating to
application B via x(say 10) number of TCP Socket.

Multithreading - How can two thread access same socket send the request one by one and get back the response mapped to appropriate
thread.

Multiple request - Is it possible that two thread can send the request on single socket simultaneously.

Can we over come this challenge via any framework? Is it possible?
I heard that Spring Integration/ApacheCamel/Local MQ can resolve this solutions. Any examples.

答:
With Spring Integration:

CachingClientConnectionFactory

TcpOutboundGateway (with CachingClientConnectionFactory).

Collaborating Outbound and Inbound Channel Adapters.

But you have to do your own request/reply collaboration (usually based on something in the message); the replies may not come back in the order they were sent. Since there is no standard way to perform that collaboration, the framework doesn't support it itself.

ContentLicense: CC BY-SA 3.0


问:
Test the behavior of a java web service for multiple concurrent requests
How do I test the behavior of a java restful web service in case of multiple concurrent requests? Is there any 3rd party tool that can be leveraged?

The service accepts POST method. It expects a couple of parameters in it's request body and produces the response in the form of JSON.

The functionality of the service is to perform database read operations using the request body parameters and populate the fetched data in the JSON.

答:
You can try Gatling to generate some load.

It has nice documentation and easy QuickStart .

For advanced usage it requires some knowledge of Scala, but it also features GUI tool for simple scenarios recording, so you can run some scripts by postman or whatever browser tool you use for debugging, record it and make that scenario automated.

After running scenarios it generates nice reports using Graphite, so you can see response times and general stats.

Later you can also use Gatling for load and performance tests of your web service, it's convenient and fast as soon as you start playing with it. It can easily generate up to 5k requests per second from my old Mac, or hold up to 1k connections.


问:
How can dhclient be made namespace aware?
I am using namespaces to separate a few physical interfaces on a server. The routing works perfectly.
Also I have a folder for each namespace in /etc/netns/ e.g. /etc/netns/namespaceA/resolv.conf so that DNS works fine as well.

The problem arises when using DHCP with dhclient.
I am running dhclient from inside a namespace and am getting this error.

```<code>(namespaceA)root@tc-vm:~#dhclient
RTNETLINK answers: File exists
mv: cannot move '/etc/resolv.conf.dhclient-new.2740' to '/etc/resolv.conf': Device or resource busy
</code>```

I found out that the mv in /etc/resolvconf/update.d/libc contains a mv which might cause the problem.

How can dhclient be made namespace aware?

答:
I looked into the issue myself.

What happens is that when you create a network namespace, you see /etc/resolv.conf of the host machine unless you create explicitly /etc/netns/<namespace_name>/resolv.conf, which will bind mount automatically to /etc/resolv.conf when looked up inside the network namespace. Therefore, by simply creating that path, the resolv.conf of the host won't be visibile any more on the network namespace, which will have its own resolv.conf.

The manual page of ip netns explains this:

For applications that are aware of network namespaces, the convention
         is to look for global network configuration files first in
         /etc/netns/NAME/ then in /etc/.  For example, if you want a different
         version of /etc/resolv.conf for a network namespace used to isolate
         your vpn you would name it /etc/netns/myvpn/resolv.conf.

Ip netns exec automates handling of this configuration, file
  convention for network namespace unaware applications, by creating a
  mount namespace and bind mounting all of the per network namespace
  configure files into their traditional location in /etc.

As far as updating resolv.conf, dhclient doesn't work in network namespaces out of the box when /etc/netns/<namespace_name>/resolv.conf exists (on the other hand, when it doesn't exist, it will overwrite the resolv.conf of the host machine, since it's the only one available, but that's not really desirable). As the error in the question above shows, what happens is that dhclient prepares a temporary file with the new nameserver details in /etc/resolv.conf.dhclient-new.2740 and then tries to rename it as /etc/resolv.conf. It generates an error because /etc/resolv.conf is already bind-mounted and apparently mv isn't allowed to do this trick.

In order to make dhclient work in network namespaces, /sbin/dhclient-script should be modified.
I removed this:

```<code>mv -f $new_resolv_conf /etc/resolv.conf
</code>```

And replaced it with:

```<code>cat $new_resolv_conf > /etc/resolv.conf
rm -f $new_resolv_conf
</code>```

Otherwise, dhcpcd seems to do this job correctly.

Body:
I am using namespaces to separate a few physical interfaces on a server. The routing works perfectly.
Also I have a folder for each namespace in /etc/netns/ e.g. /etc/netns/namespaceA/resolv.conf so that DNS works fine as well.

The problem arises when using DHCP with dhclient.
I am running dhclient from inside a namespace and am getting this error.

(namespaceA)root@tc-vm:~#dhclient
RTNETLINK answers: File exists
mv: cannot move '/etc/resolv.conf.dhclient-new.2740' to '/etc/resolv.conf': Device or resource busy

I found out that the mv in /etc/resolvconf/update.d/libc contains a mv which might cause the problem.

How can dhclient be made namespace aware?

Body:
I looked into the issue myself.

What happens is that when you create a network namespace, you see /etc/resolv.conf of the host machine unless you create explicitly /etc/netns/<namespace_name>/resolv.conf, which will bind mount automatically to /etc/resolv.conf when looked up inside the network namespace. Therefore, by simply creating that path, the resolv.conf of the host won't be visibile any more on the network namespace, which will have its own resolv.conf.

The manual page of ip netns explains this:

For applications that are aware of network namespaces, the convention
         is to look for global network configuration files first in
         /etc/netns/NAME/ then in /etc/.  For example, if you want a different
         version of /etc/resolv.conf for a network namespace used to isolate
         your vpn you would name it /etc/netns/myvpn/resolv.conf.

Ip netns exec automates handling of this configuration, file
  convention for network namespace unaware applications, by creating a
  mount namespace and bind mounting all of the per network namespace
  configure files into their traditional location in /etc.

As far as updating resolv.conf, dhclient doesn't work in network namespaces out of the box when /etc/netns/<namespace_name>/resolv.conf exists (on the other hand, when it doesn't exist, it will overwrite the resolv.conf of the host machine, since it's the only one available, but that's not really desirable). As the error in the question above shows, what happens is that dhclient prepares a temporary file with the new nameserver details in /etc/resolv.conf.dhclient-new.2740 and then tries to rename it as /etc/resolv.conf. It generates an error because /etc/resolv.conf is already bind-mounted and apparently mv isn't allowed to do this trick.

In order to make dhclient work in network namespaces, /sbin/dhclient-script should be modified.
I removed this:

mv -f $new_resolv_conf /etc/resolv.conf

And replaced it with:

cat $new_resolv_conf > /etc/resolv.conf
rm -f $new_resolv_conf

Otherwise, dhcpcd seems to do this job correctly.


问:
How do I implement a "phonetical"-like search
Currently I'm trying to enhance my search algorithm.

For better understanding, here's the current logic behind it:

we have objects with attached n keywords in db. in database this is solved via 2 tables (Object, Keyword) where the Keyword-table has a FK to Object. When i'm building my searchtrees I create a line-value (ad: remove umlauts, convert to lower-case, ...) of all keywords of an object. the same convertion-routine (NormalizeSearchPattern()) is done with the search-patterns. I'm supporting AND-search and keywords with minimum length of 2 characters only!

The search-algorithm is currently a variant of fast-reverse-search (this example is not optimized):

```<code>bool IsMatch(string source, string searchPattern)
{
    // example:
    // source: "hello world"
    // searchPattern: "hello you freaky funky world"
    // patterns[]: { "hello", "you", "freaky", "funky", "world" }

    searchPattern = NormalizeSearchPattern(searchPattern);
    var patterns = MagicMethodToSplitPatternIntoPatterns(searchPattern);
    foreach (var pattern in patterns)
    {
        var success = false;
        var patternLength = pattern.Length;
        var firstChar = pattern[0];
        var secondChar = pattern[1];

        var lengthDifference = input.Length - patternLength;
        while (lengthDifference >= 0)
        {
            if (source[lengthDifference--] != firstChar)
            {
                continue;
            }
            if (source[lengthDifference + 2] != secondChar)
            {
                continue;
            }

            var l = lengthDifference + 3;
            var m = 2;
            while (m < patternLength)
            {
                if (input[l] != pattern[m])
                {
                    break;
                }
                l++;
                m++;
            }

            if (m == patternLength)
            {
                success = true;
            }
        }
        if (!success)
        {
            return false;
        }
    }
    return true;
}
</code>```

Normalization is done with (this example is not optimized)

```<code>    string RemoveTooShortKeywords(string keywords)
    {
        while (Regex.IsMatch(keywords, TooShortKeywordPattern, RegexOptions.Compiled | RegexOptions.Singleline))
        {
            keywords = Regex.Replace(keywords, TooShortKeywordPattern, " ", RegexOptions.Compiled | RegexOptions.Singleline);
        }

        return keywords;
    }

    string RemoveNonAlphaDigits(string value)
    {
        value = value.ToLower();
        value = value.Replace("ä", "ae");
        value = value.Replace("ö", "oe");
        value = value.Replace("ü", "ue");
        value = value.Replace("ß", "ss");

        return Regex.Replace(value, "[^a-z 0-9]", " ", RegexOptions.Compiled | RegexOptions.Singleline);
    }

    string NormalizeSearchPattern(string searchPattern)
    {
        var resultNonAlphaDigits = RemoveNonAlphaDigits(searchPattern);
        var resultTrimmed = RemoveTooShortKeywords(resultNonAlphaDigits);
        return resultTrimmed;
    }
</code>```

So this is pretty straight forward, thus it's obvious, that I can only cope with variants of source and searchPattern which I've implemented in NormalizeSearchPattern() (as mentioned above: umlauts, case-differences, …).

But how should I enhance the algorithm (or NormalizeSearchPattern()) to be non-sensitive when it comes down to:

singular/plural

misstyping (eg. "hauserr" <-> "hauser")

...

Just to know more about the design:

This app is done in c#, it stores the searchtrees and objects in a static variable (to query the database only once at init), the performance has to be outstanding (currently 500.000 lineValues are queried within less than 300msec).

答:
You might also be interested in a Trigram and Bigram search matching algorithm:

Trigram search is a powerful method of searching for text when the exact syntax or spelling of the target object is not precisely known. It finds objects which match the maximum number of three-character strings in the entered search terms, i.e. near matches. A threshold can be specified as a cutoff point, after which a result is no longer regarded as a match.

Body:
Currently I'm trying to enhance my search algorithm.

For better understanding, here's the current logic behind it:

we have objects with attached n keywords in db. in database this is solved via 2 tables (Object, Keyword) where the Keyword-table has a FK to Object. When i'm building my searchtrees I create a line-value (ad: remove umlauts, convert to lower-case, ...) of all keywords of an object. the same convertion-routine (NormalizeSearchPattern()) is done with the search-patterns. I'm supporting AND-search and keywords with minimum length of 2 characters only!

The search-algorithm is currently a variant of fast-reverse-search (this example is not optimized):

bool IsMatch(string source, string searchPattern)
{
    // example:
    // source: "hello world"
    // searchPattern: "hello you freaky funky world"
    // patterns[]: { "hello", "you", "freaky", "funky", "world" }

    searchPattern = NormalizeSearchPattern(searchPattern);
    var patterns = MagicMethodToSplitPatternIntoPatterns(searchPattern);
    foreach (var pattern in patterns)
    {
        var success = false;
        var patternLength = pattern.Length;
        var firstChar = pattern[0];
        var secondChar = pattern[1];

        var lengthDifference = input.Length - patternLength;
        while (lengthDifference >= 0)
        {
            if (source[lengthDifference--] != firstChar)
            {
                continue;
            }
            if (source[lengthDifference + 2] != secondChar)
            {
                continue;
            }

            var l = lengthDifference + 3;
            var m = 2;
            while (m < patternLength)
            {
                if (input[l] != pattern[m])
                {
                    break;
                }
                l++;
                m++;
            }

            if (m == patternLength)
            {
                success = true;
            }
        }
        if (!success)
        {
            return false;
        }
    }
    return true;
}

Normalization is done with (this example is not optimized)

    string RemoveTooShortKeywords(string keywords)
    {
        while (Regex.IsMatch(keywords, TooShortKeywordPattern, RegexOptions.Compiled | RegexOptions.Singleline))
        {
            keywords = Regex.Replace(keywords, TooShortKeywordPattern, " ", RegexOptions.Compiled | RegexOptions.Singleline);
        }

        return keywords;
    }

    string RemoveNonAlphaDigits(string value)
    {
        value = value.ToLower();
        value = value.Replace("ä", "ae");
        value = value.Replace("ö", "oe");
        value = value.Replace("ü", "ue");
        value = value.Replace("ß", "ss");

        return Regex.Replace(value, "[^a-z 0-9]", " ", RegexOptions.Compiled | RegexOptions.Singleline);
    }

    string NormalizeSearchPattern(string searchPattern)
    {
        var resultNonAlphaDigits = RemoveNonAlphaDigits(searchPattern);
        var resultTrimmed = RemoveTooShortKeywords(resultNonAlphaDigits);
        return resultTrimmed;
    }

So this is pretty straight forward, thus it's obvious, that I can only cope with variants of source and searchPattern which I've implemented in NormalizeSearchPattern() (as mentioned above: umlauts, case-differences, …).

But how should I enhance the algorithm (or NormalizeSearchPattern()) to be non-sensitive when it comes down to:

singular/plural

misstyping (eg. "hauserr" <-> "hauser")

...

Just to know more about the design:

This app is done in c#, it stores the searchtrees and objects in a static variable (to query the database only once at init), the performance has to be outstanding (currently 500.000 lineValues are queried within less than 300msec).

ContentLicense: CC BY-SA 2.5


问:
javascript how to stop loop four less than elems.length?
This should be easy, but I'm apparently ridiculous with syntax if I have

```<code>var elems = document.getElementsByTagName("details");

function openAll() {
  for (var i = 0; i < elems.length; i++){
    elems[i].setAttribute("open", "true");
  }
</code>```

but I want to stop 4 tags before the end. How do I write that? The below does not work or a variety of other variations.

```<code>var elems = document.getElementsByTagName("details");

function openAll() {
  for (var i = 0; i < elems.length -4; i++){
    elems[i].setAttribute("open", "true");
  }
</code>```

答:
You did it right, but you forgot to check if elems.length-4 is greater than 0. If it is not, your for-loop will never execute.

You probably want something like this:

```<code>var l = elems.length;
for (i = 0; i < (l > 4 ? l - 4 : l; i++) {
   elems[i].setAttribute("open", "true");
}
</code>```

This loop will skip the last four elements, but only if there are more than four elements in total.

Body:
This should be easy, but I'm apparently ridiculous with syntax if I have

var elems = document.getElementsByTagName("details");

function openAll() {
  for (var i = 0; i < elems.length; i++){
    elems[i].setAttribute("open", "true");
  }

but I want to stop 4 tags before the end. How do I write that? The below does not work or a variety of other variations.

var elems = document.getElementsByTagName("details");

function openAll() {
  for (var i = 0; i < elems.length -4; i++){
    elems[i].setAttribute("open", "true");
  }

Body:
You did it right, but you forgot to check if elems.length-4 is greater than 0. If it is not, your for-loop will never execute.

You probably want something like this:

var l = elems.length;
for (i = 0; i < (l > 4 ? l - 4 : l; i++) {
   elems[i].setAttribute("open", "true");
}

This loop will skip the last four elements, but only if there are more than four elements in total.


问:
Vlcj - How to get the timestamp using Java?
sorry for bothering you but I have another question about vlcj. For this school project, I need to know how to catch the timestamp of the video that I'm currently playing on my MediaPlayer and add this information to a database.

At the moment I'm using the getTime() method:

```<code>start = (int)mediaPlayerComponent.getMediaPlayer().getTime();
</code>```

The "start" is the column's name (integer type) of my database where this information is stored. It's ok achieve the current play-back time like this but if I can catch the timestamp like a camcorder (where you know when the video was recorded) that would be a big help for what my program is going to be used in the future.

I searched online and the API of the vlcj but I can't find informations. Can you help me?

Thanks in advance for any possible answer and have a nice day.

答:
Ok, so for what I know, there isn't a "direct" solution for this but my teacher suggest me to make a five steps path instead of one. And thanks to her now is possible to get the time of the video when it was recorded. So here are the instructions:

```<code>//I'll take the time where I'm in the video
long time = mediaPlayerComponent.getMediaPlayer().getTime();

//I'll take the lenght of the video
long lenght = mediaPlayerComponent.getMediaPlayer().getLength();

//Now I need to know the path
File file = choosed.getSelectedFile();
String uri = file.getPath();
Path path = Paths.get(uri);

//I'll take the last time this video was modified and
//transform that information in milliseconds
FileTime fileTime = Files.getLastModifiedTime(path);
long lastModifiedTime = fileTime.toMillis();

//I'll make a simple equation
start = (lastModifiedTime - lenght) + time;
</code>```

I change the start integer type in a long type for having a more readable code and don't having: "start = (int)(lastModifiedTime - lenght) + (int)time".

I hope that could help someone else. Sorry for my English and have a nice day!

P.S. Forgot to add a
link where you can convert the millisecond time in
year, month, day, hour...

Body:
sorry for bothering you but I have another question about vlcj. For this school project, I need to know how to catch the timestamp of the video that I'm currently playing on my MediaPlayer and add this information to a database.

At the moment I'm using the getTime() method:

start = (int)mediaPlayerComponent.getMediaPlayer().getTime();

The "start" is the column's name (integer type) of my database where this information is stored. It's ok achieve the current play-back time like this but if I can catch the timestamp like a camcorder (where you know when the video was recorded) that would be a big help for what my program is going to be used in the future.

I searched online and the API of the vlcj but I can't find informations. Can you help me?

Thanks in advance for any possible answer and have a nice day.

Body:
Ok, so for what I know, there isn't a "direct" solution for this but my teacher suggest me to make a five steps path instead of one. And thanks to her now is possible to get the time of the video when it was recorded. So here are the instructions:

//I'll take the time where I'm in the video
long time = mediaPlayerComponent.getMediaPlayer().getTime();

//I'll take the lenght of the video
long lenght = mediaPlayerComponent.getMediaPlayer().getLength();

//Now I need to know the path
File file = choosed.getSelectedFile();
String uri = file.getPath();
Path path = Paths.get(uri);

//I'll take the last time this video was modified and
//transform that information in milliseconds
FileTime fileTime = Files.getLastModifiedTime(path);
long lastModifiedTime = fileTime.toMillis();

//I'll make a simple equation
start = (lastModifiedTime - lenght) + time;

I change the start integer type in a long type for having a more readable code and don't having: "start = (int)(lastModifiedTime - lenght) + (int)time".

I hope that could help someone else. Sorry for my English and have a nice day!

P.S. Forgot to add a
link where you can convert the millisecond time in
year, month, day, hour...


问:
How do i get the day after in the following format Month,day,year (March,31,2017)
I have the following code and i can get the next day but the issue is prime example if it's the last day of the month it wont skip to the next month for example today the 31st it will go to 32

Here is the code i have got:

```<code>var objToday = new Date(),
            weekday = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),
            dayOfWeek = weekday[objToday.getDay()],
            domEnder = function() { var a = objToday; if (/1/.test(parseInt((a + "").charAt(0)))) return ""; a = parseInt((a + "").charAt(1)); return 1 == a ? "" : 2 == a ? "" : 3 == a ? "" : "" }(),
            dayOfMonth = today + ( objToday.getDate() < 10) ? '' + objToday.getDate() + domEnder : objToday.getDate() + domEnder,
            months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),
            curMonth = months[objToday.getMonth()],
            nextMonth = months[objToday.getMonth() + 1],
            curYear = objToday.getFullYear(),
            curHour = objToday.getHours() > 12 ? objToday.getHours() - 12 : (objToday.getHours() < 10 ? "0" + objToday.getHours() : objToday.getHours()),
            curMinute = objToday.getMinutes() < 10 ? "0" + objToday.getMinutes() : objToday.getMinutes(),
            curSeconds = objToday.getSeconds() < 10 ? "0" + objToday.getSeconds() : objToday.getSeconds(),
            curMeridiem = objToday.getHours() > 12 ? "PM" : "AM";
var today = ab + ":" + curMinute + "." + curSeconds + curMeridiem + " " + dayOfWeek + " " + dayOfMonth + " of " + curMonth + ", " + curYear;

dayOfMonth_formatted = parseInt(dayOfMonth);

currentDay_formatted = curMonth + " " + dayOfMonth + 1 + "," + " " + curYear;
tomorrow_formatted = curMonth + " " + dayOfMonth_tomorrow + "," + " " + curYear;
</code>```

答:
I'd strongly suggest using https://momentjs.com/ , it would do nearly everything you're wanting to do and a lot cleaner, but more importantly more manageable. </p>

```<code>moment(new Date()).add(1,'days');
</code>```

Body:
I have the following code and i can get the next day but the issue is prime example if it's the last day of the month it wont skip to the next month for example today the 31st it will go to 32

Here is the code i have got:

var objToday = new Date(),
            weekday = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),
            dayOfWeek = weekday[objToday.getDay()],
            domEnder = function() { var a = objToday; if (/1/.test(parseInt((a + "").charAt(0)))) return ""; a = parseInt((a + "").charAt(1)); return 1 == a ? "" : 2 == a ? "" : 3 == a ? "" : "" }(),
            dayOfMonth = today + ( objToday.getDate() < 10) ? '' + objToday.getDate() + domEnder : objToday.getDate() + domEnder,
            months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),
            curMonth = months[objToday.getMonth()],
            nextMonth = months[objToday.getMonth() + 1],
            curYear = objToday.getFullYear(),
            curHour = objToday.getHours() > 12 ? objToday.getHours() - 12 : (objToday.getHours() < 10 ? "0" + objToday.getHours() : objToday.getHours()),
            curMinute = objToday.getMinutes() < 10 ? "0" + objToday.getMinutes() : objToday.getMinutes(),
            curSeconds = objToday.getSeconds() < 10 ? "0" + objToday.getSeconds() : objToday.getSeconds(),
            curMeridiem = objToday.getHours() > 12 ? "PM" : "AM";
var today = ab + ":" + curMinute + "." + curSeconds + curMeridiem + " " + dayOfWeek + " " + dayOfMonth + " of " + curMonth + ", " + curYear;

dayOfMonth_formatted = parseInt(dayOfMonth);

currentDay_formatted = curMonth + " " + dayOfMonth + 1 + "," + " " + curYear;
tomorrow_formatted = curMonth + " " + dayOfMonth_tomorrow + "," + " " + curYear;

Body:
I'd strongly suggest using https://momentjs.com/ , it would do nearly everything you're wanting to do and a lot cleaner, but more importantly more manageable.

moment(new Date()).add(1,'days');


问:
How can I get the created date of a file on the web (with Python)?
I have a python application that relies on a file that is downloaded by a client from a website.

The website is not under my control and has no API to check for a "latest version" of the file.

Is there a simple way to access the file (in python) via a URL and check it's date (or size) without having to download it to the clients machine each time?

update: Thanks to those who mentioned the"last-modified" date.  This is the correct parameter to look at.

I guess I didn't state the question well enough.  How do I do this from a python script?  I want to application to check the file and then download it if (last-modified date < current file date).

答:
Take into account that 'last-modified' may not be present:

```
>>> from urllib import urlopen
>>> f=urlopen('http://google.com/')
>>> i=f.info()
>>> i.keys()
['set-cookie', 'expires', 'server', 'connection', 'cache-control', 'date', 'content-type']
>>> i.getdate('date')
(2009, 1, 10, 16, 17, 8, 0, 1, 0)
>>> i.getheader('date')
'Sat, 10 Jan 2009 16:17:08 GMT'
>>> i.getdate('last-modified')
>>>
```

Now you can compare:

```
if (i.getdate('last-modified') or i.getheader('date')) > current_file_date:
  open('file', 'w').write(f.read())
```

OwnerDisplayName: Paige Watson

LastEditorDisplayName: Hank Gay

Body:
Take into account that 'last-modified' may not be present:

>>> from urllib import urlopen
>>> f=urlopen('http://google.com/')
>>> i=f.info()
>>> i.keys()
['set-cookie', 'expires', 'server', 'connection', 'cache-control', 'date', 'content-type']
>>> i.getdate('date')
(2009, 1, 10, 16, 17, 8, 0, 1, 0)
>>> i.getheader('date')
'Sat, 10 Jan 2009 16:17:08 GMT'
>>> i.getdate('last-modified')
>>>

Now you can compare:

if (i.getdate('last-modified') or i.getheader('date')) > current_file_date:
  open('file', 'w').write(f.read())

OwnerDisplayName: Mike


问:
how to achieve this cascading dropdown lists like country,state,city using ajax and jquery code in mvc
how to achieve this cascading dropdown lists like country,state,city
using ajax and jquer in mvc
I have a page called company details where I need to enter company Address like country,state,city. now, my requirement is if I select INDIA as Country so all the list of states in INDIA should be displayed in state drop down-box from that I should pick one state say Andhra Pradesh if I pick it all the cities in Andhra Pradesh should be displayed in city drop down-box.</p>
```<code>               @model CascadingDropdown.Models.Country
                  @{
                      ViewBag.Title = "Index";
                  }

                  <script src="~/Scripts/jquery-1.7.1.min.js"></script>

                  <h2>Cascading Dropdownlist</h2>
                  <table>
                      <tr>
                          <td>
                              <label>Country</label>
                          </td>
                          <td id="Country">

                              @Html.DropDownListFor(x => x.CountryName, Model.lstCountry, "--Select--", new { @id =
"ddlCountry" })

       - List item

                          </td>
                      </tr>
                      <tr>
                          <td>
                              <label>State</label>
                          </td>
                          <td id="State">

                              @Html.DropDownListFor(x => x.StateName, new List<SelectListItem>(), "--Select--", new { @id =
"ddlState" })
                          </td>
                      </tr>

                      <tr>
                          <td>
                              <label>City</label>
                          </td>
                          <td id="City">

                              @Html.DropDownListFor(x => x.CityName, new List<SelectListItem>(), "--Select--", new { @id = "ddlCity" })
                          </td>
                      </tr>

                  </table>

                  <script type="text/javascript">
                              $(document).ready(function () {
                                  $('#ddlCountry').change(function () {
                                      $.ajax({
                                          type: "post",
                                          url: "/Home/GetState",
                                          data: { Country_Code: $('#ddlCountry').val() },
                                          datatype: "json",
                                          traditional: true,
                                          success: function (data) {
                                              var state = "<select id='ddlState'>";
                                              state = state + '<option value="">--Select--</option>';
                                              for (var i = 0; i < data.length; i++) {
                                                  state = state + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
                                              }
                                              state = state + '</select>';
                                              $('#State').html(state);
                                          }
                                      });
                                  });
                              });

                  </script>*****
</code>```

答:
```<code>controller code

   [HttpPost]
        public JsonResult GetStatesByCountry(string id)
        {
            int ids = Convert.ToInt32(id);
            var states = model.GetStateByCountry(ids);
           SelectList obgcity = new SelectList(states, "StateId", "State", 0);
            return Json(obgcity);
        }

         public ActionResult Country()
         {
             IEnumerable<Country> country;
             country = model.GetCountryList();
             ViewBag.Country = new SelectList(country, "CountryId", "County", "CountryId");
             return View();
         }
    }

cshtml code will be this

@{
    ViewBag.Title = "Country";
}

<h2>Country</h2>
@using (Html.BeginForm())
{
    @Html.DropDownList("Country", ViewData["country"] as List<SelectListItem>)

    @Html.DropDownList("State", new SelectList(string.Empty, "Value", "Text"), "Please select a State", new { style = "width:250px", @class = "dropdown1" })
}

<script type="text/javascript">

    $(document).ready(function () {
        $("#Country").change(function () {
            var url = "/ManageEmployee/GetStatesByCountry";
            var countryID = $("#Country").val();
         $.ajax({
                url: url,
                data: { id: countryID },
                cache: false,
                type: "POST",
                success: function (data) {
                    var markup = "<option value='0'>Select City</option>";
                    for (var x = 0; x < data.length; x++) {
                        markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                    }
                    $("#State").html(markup).show();
                },
                error: function (reponse) {
                    alert("error : " + reponse);
                }
            });
        });

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

ContentLicense: CC BY-SA 4.0

Body:
how to achieve this cascading dropdown lists like country,state,city
using ajax and jquer in mvc
I have a page called company details where I need to enter company Address like country,state,city. now, my requirement is if I select INDIA as Country so all the list of states in INDIA should be displayed in state drop down-box from that I should pick one state say Andhra Pradesh if I pick it all the cities in Andhra Pradesh should be displayed in city drop down-box.

               @model CascadingDropdown.Models.Country
                  @{
                      ViewBag.Title = "Index";
                  }

Cascading Dropdownlist

                              Country

                              @Html.DropDownListFor(x => x.CountryName, Model.lstCountry, "--Select--", new { @id =
"ddlCountry" })

       - List item

                              State

                              @Html.DropDownListFor(x => x.StateName, new List<SelectListItem>(), "--Select--", new { @id =
"ddlState" })

                              City

                              @Html.DropDownListFor(x => x.CityName, new List<SelectListItem>(), "--Select--", new { @id = "ddlCity" })

                  *****


问:
PHP from associative array to User Class

I know that I can cast an associative array to object doing this:

```<code>$user = (object) $_POST["user"];
</code>```

I have a class User that has method getName, getEmail etc.
If I do

```<code>$user = (object) $_POST["user"];
$user->getName();
</code>```

It gives this error

```<code>Fatal error: Call to undefined method stdClass::getName()
</code>```

Can I do something like this?

```<code>$user = (user) $_POST["user"];
</code>```

Thank you

答:
Not directly. What you could do is make a new user and set all the info in the constructor of your user class

```<code>Class User {
   public $name;
   public $otherData;

   function __construct ($userdata) {
      $name = $userdata['name'];
      $otherData = $userdata['otherData'];
   }

   function GetName() {
      return $name;
   }

}
</code>```

Then you could call it like this:
$user = new User($_POST["user"]);

Body:
I know that I can cast an associative array to object doing this:

$user = (object) $_POST["user"];

I have a class User that has method getName, getEmail etc.
If I do

$user = (object) $_POST["user"];
$user->getName();

It gives this error

Fatal error: Call to undefined method stdClass::getName()

Can I do something like this?

$user = (user) $_POST["user"];

Thank you

Body:
Not directly. What you could do is make a new user and set all the info in the constructor of your user class

Class User {
   public $name;
   public $otherData;

   function __construct ($userdata) {
      $name = $userdata['name'];
      $otherData = $userdata['otherData'];
   }

   function GetName() {
      return $name;
   }

}

Then you could call it like this:
$user = new User($_POST["user"]);


问:
Fill 2D array square and print in specific patterns
Ive been working on this assignment question for about 4 days now and I'm about to go crazy. We have specific directions to follow for this code;

"Your program should proceed as follows:

Display a welcome message.

Prompt the user for an integer which is  3. If the number entered is < 3. keep prompting the user until they enter a number  3 (use a do/while).    This number will determine the size of the square array.

Fill the array as per pattern 1 and display it using printf to format the array.

Fill the same array as per pattern 2 and display it using printf t0 format the array.

Display a closing message."

Pattern:

I'm still stuck on pattern one. I tried to do first do a for loop which in it there's an if statement that checks if the column number is even or not, if it is, to print out the code backwards. The question also recommends using a while loop and a do/while loop...?

Also any tips on to how to go about the second patterns.

Here is my code.

```<code>import java.util.Scanner;
public class a3q33
{

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

    int n;

    do
    {
        System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");

        n=keyboard.nextInt();

    } while(n < 3);

    int [][] arr = new int [n][n];

     int i, j, k=1;

    for(i=0;i<n;i++)
    {
         if(i % 2 != 0)
         {
             for(j=n;j>0;j--)
             {
                 k = k+n;
                 arr[i][j]=k;
                 k--;
             }
         }

         else
         {
             for(j=0;j<n;j++)
             {
                 arr[i][j]=k;
                 k++;
             }
         }
    }

    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            System.out.printf(arr[i][j]+" ");

        }
            System.out.printf("");
            System.out.println();
    }

    }
}
</code>```

Any help would be greatly appreciated!

答:
I assume that you meant "row" instead of "column" for the condition check given that the convention is arr[row][column]?

Also, the for loop in your code:

```<code>for(j=n;j>0;j--)
</code>```

This will decrement the row/column index down to 1 and not 0. So you will miss one element at arr[0][...] or arr[...][0].
Also, j=n will be out of bound.

Instead, try using:

```<code>for(j=n-1;j>-1;j--)
</code>```

It would be a good first steps to look into.

Body:
Ive been working on this assignment question for about 4 days now and I'm about to go crazy. We have specific directions to follow for this code;

"Your program should proceed as follows:

Display a welcome message.

Prompt the user for an integer which is  3. If the number entered is < 3. keep prompting the user until they enter a number  3 (use a do/while).    This number will determine the size of the square array.

Fill the array as per pattern 1 and display it using printf to format the array.

Fill the same array as per pattern 2 and display it using printf t0 format the array.

Display a closing message."

Pattern:

I'm still stuck on pattern one. I tried to do first do a for loop which in it there's an if statement that checks if the column number is even or not, if it is, to print out the code backwards. The question also recommends using a while loop and a do/while loop...?

Also any tips on to how to go about the second patterns.

Here is my code.

import java.util.Scanner;
public class a3q33
{

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

    int n;

    do
    {
        System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");

        n=keyboard.nextInt();

    } while(n < 3);

    int [][] arr = new int [n][n];

     int i, j, k=1;

    for(i=0;i<n;i++)
    {
         if(i % 2 != 0)
         {
             for(j=n;j>0;j--)
             {
                 k = k+n;
                 arr[i][j]=k;
                 k--;
             }
         }

         else
         {
             for(j=0;j<n;j++)
             {
                 arr[i][j]=k;
                 k++;
             }
         }
    }

    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            System.out.printf(arr[i][j]+" ");

        }
            System.out.printf("");
            System.out.println();
    }

    }
}

Any help would be greatly appreciated!

Body:
I assume that you meant "row" instead of "column" for the condition check given that the convention is arr[row][column]?

Also, the for loop in your code:

for(j=n;j>0;j--)

This will decrement the row/column index down to 1 and not 0. So you will miss one element at arr[0][...] or arr[...][0].
Also, j=n will be out of bound.

Instead, try using:

for(j=n-1;j>-1;j--)

It would be a good first steps to look into.


问:
can not modify the member value of struct array in C programming
Here is my code:

```<code>#include <stdio.h>
struct book
    {
        char bookID[20];
        char name[20];
        double price;
    };

void input(struct book bs[], int n)
{
    for (int i = 0; i < n; i++)
    {
    printf("Please input the price of book %s:\n",bs[i].name );
    scanf("%f",&bs[i].price);
    }
}

void print(struct book bs[], int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("%s\t%s\t%.2f\n", bs[i].bookID, bs[i].name, bs[i].price );
    }
}

int main(void)
{
    book books[4] = {{"0101","Computer",1.5},{"0102","Programming",4.1},{"0103","Math",3.3},{"0104","English",1.2}};
    input(books, 4);
    print(books, 4);
    return 0;
}
</code>```

But when I input ANY price of four books, the print function always output the default value: 1.5, 4.1, 3.3, 1.2

Wondering where is wrong. Thanks!

答:
You have undefined behavior in your code, as you use the wrong scanf format for reading into a double.

The correct format for scanf and double is "%lf".

Note that for printf it doesn't matter, "%f" and "%lf" are both valid for float and double.

Body:
Here is my code:

#include <stdio.h>
struct book
    {
        char bookID[20];
        char name[20];
        double price;
    };

void input(struct book bs[], int n)
{
    for (int i = 0; i < n; i++)
    {
    printf("Please input the price of book %s:\n",bs[i].name );
    scanf("%f",&bs[i].price);
    }
}

void print(struct book bs[], int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("%s\t%s\t%.2f\n", bs[i].bookID, bs[i].name, bs[i].price );
    }
}

int main(void)
{
    book books[4] = {{"0101","Computer",1.5},{"0102","Programming",4.1},{"0103","Math",3.3},{"0104","English",1.2}};
    input(books, 4);
    print(books, 4);
    return 0;
}

But when I input ANY price of four books, the print function always output the default value: 1.5, 4.1, 3.3, 1.2

Wondering where is wrong. Thanks!


问:
WCF failing is NOD32 is installed
I've an app using WCF (with WSHttpBinding), which is failing in computers where ESET NOD32 is installed.... There's a windows kernel service called ekrn.exe that starts using lots of CPU (near 100%) and makes the app fail after 1 minute. The error thrown by the application is:

"Client is unable to finish the security negotiation within the configured timeout. The current negotiation leg is 1."

Any suggestion? Thanks!

答: Simply consult NOD32 if they have a newer version for you. As far as I know, some versions of NOD32 is interrupting socket related applications on Windows.</p>

Title: WCF failing is NOD32 is installed


问:
How to Pass Bitmap[] between 2 fragments
Im using AsyncTask to download some images from url. The downloaded images i save in Bitmap array. Once they are saved i dont know how to pass them from one fragment to another. Can someone help please?

Pressing download Button:

```<code>d.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String [] urlArray = new String[]{URL_IMAGE_1, URL_IMAGE_2,URL_IMAGE_3,URL_IMAGE_4, URL_IMAGE_5};
            asyncTaskA.execute(urlArray);
            FrameLayout frameLayout = (FrameLayout)getView().findViewById(R.id.fragmentMain);
            frameLayout.removeAllViewsInLayout();
            FragmentTransaction ft = getChildFragmentManager().beginTransaction();
            FragmentImages fragmentImages = new FragmentImages ();
            ft.replace(R.id.fragmentMain,fragmentImages );
            ft.addToBackStack(null);
            ft.commit();
        }
    });
</code>```

In MainFragment method:

```<code> public void getImages(Bitmap [] bitmaps){
    imagesDownloaded = bitmaps;//private Bitmap [] imagesDownloaded;
    images = imageDownloaded; //public stati Bitmap [] images;

}
</code>```

In AsyncTask

```<code>@Override
protected void onPostExecute(Bitmap[] bitmaps) {

    fragmentMain.getImages(bitmaps);

}
</code>```

In FragmentImages so far

```<code> @Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Bitmap[] bitmaps = FragmentA.images; // The array is null, why??

}
</code>```

What im missing?
Im new with programming.
Thanks in advance.

答:
Its null because you dont know how to AsyncTask works

```<code>asyncTaskA.execute(urlArray);
</code>```

So AsyncTask started

```<code>       FragmentImages fragmentImages = new FragmentImages ();
        ft.replace(R.id.fragmentMain,fragmentImages );
        ft.addToBackStack(null);
        ft.commit();
</code>```

You opened fragment and ask for images - there are no images, so you have null

After some time images downloaded here. So you have:

No images diplayed

Memory leak

Good way is passing url of image to other fragment and download it with Picasso or same library.

If you SO need to use AsyncTask you had to open fragment in onPostExecute method. Also if you need to pass Bitmap variable you can set it to Application class or custom singleton or to your Activity class for example.

Body:
Im using AsyncTask to download some images from url. The downloaded images i save in Bitmap array. Once they are saved i dont know how to pass them from one fragment to another. Can someone help please?

Pressing download Button:

d.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String [] urlArray = new String[]{URL_IMAGE_1, URL_IMAGE_2,URL_IMAGE_3,URL_IMAGE_4, URL_IMAGE_5};
            asyncTaskA.execute(urlArray);
            FrameLayout frameLayout = (FrameLayout)getView().findViewById(R.id.fragmentMain);
            frameLayout.removeAllViewsInLayout();
            FragmentTransaction ft = getChildFragmentManager().beginTransaction();
            FragmentImages fragmentImages = new FragmentImages ();
            ft.replace(R.id.fragmentMain,fragmentImages );
            ft.addToBackStack(null);
            ft.commit();
        }
    });

In MainFragment method:

 public void getImages(Bitmap [] bitmaps){
    imagesDownloaded = bitmaps;//private Bitmap [] imagesDownloaded;
    images = imageDownloaded; //public stati Bitmap [] images;

}

In AsyncTask

@Override
protected void onPostExecute(Bitmap[] bitmaps) {

    fragmentMain.getImages(bitmaps);

}

In FragmentImages so far

 @Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Bitmap[] bitmaps = FragmentA.images; // The array is null, why??

}

What im missing?
Im new with programming.
Thanks in advance.

Body:
Its null because you dont know how to AsyncTask works

asyncTaskA.execute(urlArray);

So AsyncTask started

       FragmentImages fragmentImages = new FragmentImages ();
        ft.replace(R.id.fragmentMain,fragmentImages );
        ft.addToBackStack(null);
        ft.commit();

You opened fragment and ask for images - there are no images, so you have null

After some time images downloaded here. So you have:

No images diplayed

Memory leak

Good way is passing url of image to other fragment and download it with Picasso or same library.

If you SO need to use AsyncTask you had to open fragment in onPostExecute method. Also if you need to pass Bitmap variable you can set it to Application class or custom singleton or to your Activity class for example.


问:
Halarious - Embedded resource field names not being converted with custom naming strategy
I am using the HAL-Specification framework:

https://github.com/surech/halarious

http://confluence.surech.ch/display/HAL/halarious+Home

http://stateless.co/hal_specification.html

It appears that embedded resource field names are not being converted correctly when using a custom naming strategy.  Only 'non-HAL' fields are being converted.

Question: Is there a way to ensure custom naming conventions are applied to embedded resources and not just regular fields?

I have the following Gson configuration in a custom MessageBodyWriter...

```<code>GsonBuilder builder = new GsonBuilder();
builder.setFieldNamingStrategy(new AllLowercaseFieldNamingStrategy());
builder.registerTypeAdapter(HalResource.class, new HalSerializer());
builder.setExclusionStrategies(new HalExclusionStrategy());
Gson gson = builder.create();
try (OutputStreamWriter writer = new OutputStreamWriter(entityStream)) {
    writer.write(gson.toJson(resource, HalResource.class));
}
</code>```

The AllLowercaseFieldNamingStrategy implementation simply converts the field name to lowercase like so @Override public String translateName(Field f) { return f.getName().toLowerCase(); }

For example:

```<code>public class MyResource implements HalResource {
   private final String myField;
   private final MyResource myEmbeddedResource;
   ...
}
</code>```

results in inconsistent field names (should be all lower case based on naming strategy)...

```<code>{
    "myfield": "...",
    "_embedded": {
        "myEmbeddedResource": {...}
    }
}
</code>```

答:
My workaround solution was to use the @HalEmbedded annotation and assign a lowercase name directly.

```<code>public class MyResource implements HalResource {
   private final String myField;
   @HalEmbedded(name = "myembeddedresource")
   private final MyResource myEmbeddedResource;
   ...
}
</code>```

An issue has been created for the project: https://github.com/surech/halarious/issues/21

Body:
I am using the HAL-Specification framework:

https://github.com/surech/halarious

http://confluence.surech.ch/display/HAL/halarious+Home

http://stateless.co/hal_specification.html

It appears that embedded resource field names are not being converted correctly when using a custom naming strategy.  Only 'non-HAL' fields are being converted.

Question: Is there a way to ensure custom naming conventions are applied to embedded resources and not just regular fields?

I have the following Gson configuration in a custom MessageBodyWriter...

GsonBuilder builder = new GsonBuilder();
builder.setFieldNamingStrategy(new AllLowercaseFieldNamingStrategy());
builder.registerTypeAdapter(HalResource.class, new HalSerializer());
builder.setExclusionStrategies(new HalExclusionStrategy());
Gson gson = builder.create();
try (OutputStreamWriter writer = new OutputStreamWriter(entityStream)) {
    writer.write(gson.toJson(resource, HalResource.class));
}

The AllLowercaseFieldNamingStrategy implementation simply converts the field name to lowercase like so @Override public String translateName(Field f) { return f.getName().toLowerCase(); }

For example:

public class MyResource implements HalResource {
   private final String myField;
   private final MyResource myEmbeddedResource;
   ...
}

results in inconsistent field names (should be all lower case based on naming strategy)...

{
    "myfield": "...",
    "_embedded": {
        "myEmbeddedResource": {...}
    }
}

Body:
My workaround solution was to use the @HalEmbedded annotation and assign a lowercase name directly.

public class MyResource implements HalResource {
   private final String myField;
   @HalEmbedded(name = "myembeddedresource")
   private final MyResource myEmbeddedResource;
   ...
}

An issue has been created for the project: https://github.com/surech/halarious/issues/21


问:
How to set environment variable in the .Net Core app which is automated deployed with Teamcity
I have configured continuous integration (BitBucket) of my .Net Core app to Azure/IIS using Teamcity. I am following this article.

Now my continuous integration is happening properly and app is deployed to Azure correctly whenever I check in any changes to Bitbucket repo.

The problem is, environment variable of my .Net Core app is by default set to Production.

I know we can set environment variable using command:

```<code>set ASPNETCORE_ENVIRONMENT="Development"
</code>```

But I wonder, how I can specify this setting in my Teamcity build?

答:
At the end of the linked article you can find an update and another link to the TeamCity team blog article, where you can find a way to set up the environment variable:

If you want to tune some parameters in your build steps, the .NET Core plugin provides details about configuration options and hints at their possible values

So you need to select Runner type equal to .Net Core (dotnet), and Configuration equal to Development:

Body:
I have configured continuous integration (BitBucket) of my .Net Core app to Azure/IIS using Teamcity. I am following this article.

Now my continuous integration is happening properly and app is deployed to Azure correctly whenever I check in any changes to Bitbucket repo.

The problem is, environment variable of my .Net Core app is by default set to Production.

I know we can set environment variable using command:

set ASPNETCORE_ENVIRONMENT="Development"

But I wonder, how I can specify this setting in my Teamcity build?


问:
Chat via WIFI platform independent
I'm thinking of creating a chat app which is similar like firechat. which needs no internet for communication and depends only on BT or WIFI to communicate and also have an advantage of platform independent.
      I've seen many sites referring some sites like open garden for firechat and alljoyn framework. I really don't understand what this things are for. Its really hard to find a solution for this.

I tried alljoyn initially, but the last update was about 3 years ago. the sample apps crashes in devices.
      So any one who worked in this kinda project or or sharing some knowledge will be more helpful!

Thanks in advance!

答:
Also there is a well-known chat sample in AllJoyn Core, which discovers other peers and connect them. It works on Android App too. </p>

<p>Here you can download the AllJoyn Android Chat sample https://cgit.allseenalliance.org/core/alljoyn.git/tree/alljoyn_java/samples/android/chat </p>

Title: Chat via WIFI platform independent

Body:
Also there is a well-known chat sample in AllJoyn Core, which discovers other peers and connect them. It works on Android App too.

Here you can download the AllJoyn Android Chat sample https://cgit.allseenalliance.org/core/alljoyn.git/tree/alljoyn_java/samples/android/chat


问:
Google Charts: Is there a way to re-render the chart when the screen changes sizes? (javascript only please)
I am trying to make a javascript google chart that renders and when I test responsiveness the chart does not move until I refresh the screen and the chart re-renders. Where I see this becoming a problem is  turning an Ipad or phone to portrait or resizing of a window  and the chart no longer being centered. Is there a way to re-render the Charts on the screen size changing? </p>

答:
sure, just need to re-draw when the the 'resize' event occurs,

something like...

```<code>window.addEventListener('resize', drawChart, false);

function drawChart() {
  chart.draw();
}
</code>```

Body:
sure, just need to re-draw when the the 'resize' event occurs,

something like...

window.addEventListener('resize', drawChart, false);

function drawChart() {
  chart.draw();
}


问:
change Datetime format django rest framework
I want to change date time format in django rest framework

I have implement one logic but it's not fullfill my requirement

Model

```<code>class User (models.Model):
    user_id = models.AutoField(primary_key=True)
    user_name = models.CharField(max_length=150)
    created_at = models.DateTimeField()
</code>```

setting.py file I have define the datetime format

```<code>REST_FRAMEWORK = {

    'DATETIME_FORMAT': "%m/%d/%Y %H:%M:%S",
}
</code>```

Query

```<code>data = User.objects.filter(pk=51)
serializer = UserSerializer(data, many=True)
</code>```

result after serializer data

```<code> {
      "user_id": 41406,
      "user_name": "abc@gmail.com",
      "created_at": "09/26/2016 22:52:16",
 }
</code>```

Now when I hit another model then datetime format is also same like this "09/26/2016 22:52:16" but i do not want this date format in anthor model.

Please let me know if we can change in particular Model datetime format and call it in serializer

答:
You can override to_representation method in a model serializer which required different date output:

```<code>class UserSerializer(serializers.ModelSerializer):
    ...
    def to_representation(self, instance):
        representation = super(UserSerializer, self).to_representation(instance)
        representation['created_at'] = instance.created_at.strftime(<your format string>)
        return representation
</code>```

Or you can write custom field and use it instead of default.

```<code>class UserSerializer(serializers.ModelSerializer):
    created_at = serializers.DateTimeField(format='%Y')
    # add read_only=True to the field in case if date created automatically
    ...
</code>```

Body:
I want to change date time format in django rest framework

I have implement one logic but it's not fullfill my requirement

Model

class User (models.Model):
    user_id = models.AutoField(primary_key=True)
    user_name = models.CharField(max_length=150)
    created_at = models.DateTimeField()

setting.py file I have define the datetime format

REST_FRAMEWORK = {

    'DATETIME_FORMAT': "%m/%d/%Y %H:%M:%S",
}

Query

data = User.objects.filter(pk=51)
serializer = UserSerializer(data, many=True)

result after serializer data

 {
      "user_id": 41406,
      "user_name": "abc@gmail.com",
      "created_at": "09/26/2016 22:52:16",
 }

Now when I hit another model then datetime format is also same like this "09/26/2016 22:52:16" but i do not want this date format in anthor model.

Please let me know if we can change in particular Model datetime format and call it in serializer

Body:
You can override to_representation method in a model serializer which required different date output:

class UserSerializer(serializers.ModelSerializer):
    ...
    def to_representation(self, instance):
        representation = super(UserSerializer, self).to_representation(instance)
        representation['created_at'] = instance.created_at.strftime(<your format string>)
        return representation

Or you can write custom field and use it instead of default.

class UserSerializer(serializers.ModelSerializer):
    created_at = serializers.DateTimeField(format='%Y')
    # add read_only=True to the field in case if date created automatically
    ...


答:
You want to use the Series.where function on the columns you want to change. For example the first column can be acheived by:

```<code>df['val_2001'] = df['val_2001'].where( df['val_2001']>df['val_2000']*1.5 )
</code>```

Edit (in response to OP comment): You can add OR using the python notation |, for example, as follows:

```<code>df['val_2001'] = df['val_2001'].where( (df['val_2001']>df['val_2000']*1.5) |  (df['val_2001']<df['val_2000']*0.75) )
</code>```

Title: How to iterate over columns in a df and compare value with previous column and perform a action in Python

Body:
The operation I am trying to perform is similar to this mysql delete statement :

   DELETE FROM ABCD WHERE val_2001>val_2000*1.5 OR val_2001>val_1999*POW(1.5,2);

And the column_names varies from val_2001 to val_2017.

All the data from the table ABCD is dumped into a csv and loaded into df.

How to iterate over each column and compare with previous column and perform a delete? ( new to python)

The table data sample :

val_2000   val_2001        val_2002            val_2003
100     112.058663384525    119.070787312921    117.033250060214
100     118.300395256917    124.655238202362    128.723125524235
100     109.333236619151    116.785836024946    117.390803371386
100     120.954175930764    126.099776250454    124.491022271481
100     107.776153227575    105.560100052722    108.07490649383
100     151.596517146962    306.608812920781    124.610273175528

Note: there are columns which need not be iterated as well.

The sample output :

val_2000   val_2001        val_2002            val_2003
100     112.058663384525    119.070787312921    117.033250060214
100     118.300395256917    124.655238202362    128.723125524235
100     109.333236619151    116.785836024946    117.390803371386
100     120.954175930764    126.099776250454    124.491022271481
100     107.776153227575    105.560100052722    108.07490649383
100     NULL                   NULL             124.610273175528

EDIT : - Currently trying this way:

    df = pd.read_csv("singleDataFile.csv")
   for values in xrange(2000,2016):
        val2 = values+1
        df['val_'+str(val2)] = df['val_'+str(val2)].where((df['val_'+str(val2)]>df['val_'+str(values)]*1.5) |  (df['val_'+str(val2)]<df['val_'+str(values)]*0.75))

   print(df)

Getting a format error

Body:
You want to use the Series.where function on the columns you want to change. For example the first column can be acheived by:

df['val_2001'] = df['val_2001'].where( df['val_2001']>df['val_2000']*1.5 )

Edit (in response to OP comment): You can add OR using the python notation |, for example, as follows:

df['val_2001'] = df['val_2001'].where( (df['val_2001']>df['val_2000']*1.5) |  (df['val_2001']<df['val_2000']*0.75) )


问:
How to blur imageview in android
I have an imageview and i set Image Resources programmatically like this:

```<code>int resourceId = getResources().getIdentifier("imagename", "drawable", "mypackage");
imgLock.setImageResource(resourceId);
</code>```

Is there any easy way to show my ImageView with blurry image?

答:
There are different ways to make view blur in android, But i found the easiest and fastest way to make views blur using Fresco library.

Add following dependency inside your build.gradle of your module.

```<code>   compile 'jp.wasabeef:fresco-processors:2.1.0'
</code>```

And inside onCreate() of Activity.

```<code>        Fresco.initialize(this);
    setContentView(R.layout.activity_main);

    SimpleDraweeView  simpleDraweeView = (SimpleDraweeView) findViewById(R.id.sdv_image);

    //INSTANTIATE BLUR POST PROCESSOR
    Postprocessor  postprocessor = new BlurPostprocessor(this, BLUR_PRECENTAGE);

    //INSTATNTING IMAGE REQUEST USING POST PROCESSOR AS PARAMETER
    ImageRequest  imageRequest = ImageRequestBuilder.newBuilderWithSource(Uri.parse(IMAGE_URL))
            .setPostprocessor(postprocessor)
            .build();

    //INSTANTATE CONTROLLOR()
    PipelineDraweeController  controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
            .setImageRequest(imageRequest)
            .setOldController(simpleDraweeView.getController())
            .build();

    //LOAD BLURRED IMAGE ON SimpleDraweeView(VIEW)
    simpleDraweeView.setController(controller);
</code>```

If you need complete implementation please visit this blog
Fastest Image Blur in Android Using Fresco.

Title: How to blur imageview in android

Body:
I have an imageview and i set Image Resources programmatically like this:

int resourceId = getResources().getIdentifier("imagename", "drawable", "mypackage");
imgLock.setImageResource(resourceId);

Is there any easy way to show my ImageView with blurry image?

Body:
There are different ways to make view blur in android, But i found the easiest and fastest way to make views blur using Fresco library.

Add following dependency inside your build.gradle of your module.

   compile 'jp.wasabeef:fresco-processors:2.1.0'

And inside onCreate() of Activity.

        Fresco.initialize(this);
    setContentView(R.layout.activity_main);

    SimpleDraweeView  simpleDraweeView = (SimpleDraweeView) findViewById(R.id.sdv_image);

    //INSTANTIATE BLUR POST PROCESSOR
    Postprocessor  postprocessor = new BlurPostprocessor(this, BLUR_PRECENTAGE);

    //INSTATNTING IMAGE REQUEST USING POST PROCESSOR AS PARAMETER
    ImageRequest  imageRequest = ImageRequestBuilder.newBuilderWithSource(Uri.parse(IMAGE_URL))
            .setPostprocessor(postprocessor)
            .build();

    //INSTANTATE CONTROLLOR()
    PipelineDraweeController  controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
            .setImageRequest(imageRequest)
            .setOldController(simpleDraweeView.getController())
            .build();

    //LOAD BLURRED IMAGE ON SimpleDraweeView(VIEW)
    simpleDraweeView.setController(controller);

If you need complete implementation please visit this blog
Fastest Image Blur in Android Using Fresco.


问:
Run arbitrary zsh command for all subfolders
I'm currently using this function to run a command for all subfolders in zsh.

```<code>forsubdirs() {
   for dir in *; do
     (cd ${dir} && echo $fg_bold[yellow]${PWD##*/}$reset_color && $@ && echo '\n')
   done
}
</code>```

I use it like this: forsubdirs git pull
The problem, though: it does not work with aliases. How to execute an arbitrary ZSH command (including aliases and lists of commands separated with "&" or ";") for all subfolders?

答:
In order to be able to pass complex commands as argument you need to quote syntactic elements like ; and &. The arguments then need to be explicitly evaluated with the eval command. For example:

```<code>forsubdirs () {
    for dir in *(/) ; do
        ( cd $dir && echo $fg_bold[yellow]${PWD##*/}$reset_color && eval $@ && echo '\n' )
    done
}

forsubdir 'ls -1 | sed "s/^/    /"'
</code>```

Also, I would suggest using *(/) instead of plain *. It matches only directories, so that the function does not even try to run cd on regular files.

Body:
I'm currently using this function to run a command for all subfolders in zsh.

forsubdirs() {
   for dir in *; do
     (cd ${dir} && echo $fg_bold[yellow]${PWD##*/}$reset_color && $@ && echo '\n')
   done
}

I use it like this: forsubdirs git pull
The problem, though: it does not work with aliases. How to execute an arbitrary ZSH command (including aliases and lists of commands separated with "&" or ";") for all subfolders?

Body:
In order to be able to pass complex commands as argument you need to quote syntactic elements like ; and &. The arguments then need to be explicitly evaluated with the eval command. For example:

forsubdirs () {
    for dir in *(/) ; do
        ( cd $dir && echo $fg_bold[yellow]${PWD##*/}$reset_color && eval $@ && echo '\n' )
    done
}

forsubdir 'ls -1 | sed "s/^/    /"'

Also, I would suggest using *(/) instead of plain *. It matches only directories, so that the function does not even try to run cd on regular files.


问:
How to make single instance of Activity with different data passed through Intents in Android?
I want to make an Activity which should be created only once and then it should be updated based on certain values. First I tried to pass data through Intent but since I have made that activity as singleTask it do not get the new Intent object and uses the previous one.

What can be the way of passing the data to an Activity that is singleTask and needs to be updated on certain values?

答: If your activity is singleTask, you need to handle new intents in onNewIntent method


问:
Most parts of the address return null when using the OneLine Search in SKMaps
When I use the oneline search in SKMaps most parts of the address will return null. In android I use the below code:

```<code>SKSearchResult result = results.get(i);
SKAddress address = result.getAddress();
String houseNumber = address.getHouseNumber();
String street = address.getStreet();
String town = address.getCity();
String zipCode = address.getZipCode();
String formatted = houseNumber + " " + street + " " + town + " " + zipCode;
</code>```

When I print out the formatted address it will say

null null city null

How do I get the components of the address without them being null?

答: If some component of the address is null that means there is no information about that component and there is no other way to get the value of that component through the SKMaps library. </p>

Body:
When I use the oneline search in SKMaps most parts of the address will return null. In android I use the below code:

SKSearchResult result = results.get(i);
SKAddress address = result.getAddress();
String houseNumber = address.getHouseNumber();
String street = address.getStreet();
String town = address.getCity();
String zipCode = address.getZipCode();
String formatted = houseNumber + " " + street + " " + town + " " + zipCode;

When I print out the formatted address it will say

null null city null

How do I get the components of the address without them being null?


问:
Jaxb generated xml - problem with root element prefix
I am trying to generate xml using jaxb. I created xsd and generated java classes.
But when I generate xml, I am geeting prefix ns2 to the root tag, which I don't want.

ex: I want root tag to be

```<code> <report>
   <id>rep 1</id>
</report>
</code>```

, But getting as

```<code><ns2:report>
....
</ns2:report>
</code>```

In the generated java class, I gave annotation as @XmlRootElement(name="report",namespace="urn:report")

Can some one pls help

答:
Somehow the accepted answer did not work for me. I got success when I found solutions in some related stockOverflow questions involving DelegatingXMLStreamWriter from cxf and a filter, NoNamesWriter. The implementation I used with NoNamesWriter:

```<code>public class NoNamesWriter extends DelegatingXMLStreamWriter
{
    @Override
    public void writeStartElement(String prefix, String local, String uri) throws XMLStreamException {
        delegate.writeStartElement("", local, uri);
    }

    public static XMLStreamWriter filter(FileOutputStream fileOutputStream) throws XMLStreamException {
        return new NoNamesWriter(XMLOutputFactory.newInstance().createXMLStreamWriter(fileOutputStream));
    }

    public NoNamesWriter(XMLStreamWriter writer) {
        super(writer);
    }

}
</code>```

Invoke the same as described here, like:

xmlmarshaller.marshal(xc, NoNamesWriter.filter(new FileOutputStream(outfile, false));

Body:
I am trying to generate xml using jaxb. I created xsd and generated java classes.
But when I generate xml, I am geeting prefix ns2 to the root tag, which I don't want.

ex: I want root tag to be

 <report>
   <id>rep 1</id>
</report>

, But getting as

<ns2:report>
....
</ns2:report>

In the generated java class, I gave annotation as @XmlRootElement(name="report",namespace="urn:report")

Can some one pls help

Body:
Somehow the accepted answer did not work for me. I got success when I found solutions in some related stockOverflow questions involving DelegatingXMLStreamWriter from cxf and a filter, NoNamesWriter. The implementation I used with NoNamesWriter:

public class NoNamesWriter extends DelegatingXMLStreamWriter
{
    @Override
    public void writeStartElement(String prefix, String local, String uri) throws XMLStreamException {
        delegate.writeStartElement("", local, uri);
    }

    public static XMLStreamWriter filter(FileOutputStream fileOutputStream) throws XMLStreamException {
        return new NoNamesWriter(XMLOutputFactory.newInstance().createXMLStreamWriter(fileOutputStream));
    }

    public NoNamesWriter(XMLStreamWriter writer) {
        super(writer);
    }

}

Invoke the same as described here, like:

xmlmarshaller.marshal(xc, NoNamesWriter.filter(new FileOutputStream(outfile, false));


问:
How to store data to database with Ajax on Model Class Codeigniter
We want to put data from view () to database. We use Ajax to running some background process (insert data to database). But We can't save the data to database. I'm appreciate and thank's a lot for any suggest and good avice do you give. I'm sorry if this is just a newbie's question.

This is the View (form, fieldset, javascript, and ajax)

var popup, x, f31, f32, f33, f4, f5, f6, f7, f7a, f81, f82, f11, f14, f161, f17a1;

function _(x){
    return document.getElementById(x);
}

//fungsi tutup popup
function tutupPopup(){
    _("popup").style.display = "none";
}

function prosesc11(){
    f31 = _("f31").value;
    f32 = _("f32").value;
    f33 = _("f33").value;
    $.ajax({
        url    : "<?php echo base_url().'index.php/TracerStudy_model/simpan_data_ts';?>",
        type   : 'post',
        data   : {'f31' : f31, 'f32' : f32},
        success: function(data){
            console.log(data);
        }
    });

    if(f31.length>0||f32.length>0){
        _("formc1-1").style.display = "none";
        _("formc1-2").style.display = "block";
        _("progressBar").value = 50;
    }else{
        alert("Maaf data anda ada yang belum diisi.")
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="multiphaseForm" id="multiphaseForm" onsubmit="return false"
    method="post" action="<?php base_url();?>TracerStudy/masuk_data_ts"
>
<fieldset class="formc1-1" id="formc1-1"><!--fieldset pertama-->
    <!-- f3 -->
    <div class="form-group">
        <div class="row">
            <div class="col-md-8">
                <label>1. Kapan anda mulai mencari pekerjaan ?</label>
            </div>
        </div>
        <div class="row ">
            <input class="col-lg-1" id="f31" name="f3" type="radio" value="1" class="form-control">
            <label class="col-md-8" for="f31">Sebelum lulus</label>
        </div>
        <div class="row ">
            <input class="col-lg-1" id="f32" name="f3" type="radio" value="2" class="form-control">
            <label class="col-md-8" for="f32">Setelah lulus</label>
        </div>
        <div class="row ">
            <input class="col-lg-1" id="f33" name="f3" type="radio" value="3" class="form-control">
            <label class="col-md-8" for="f33">Tidak mencari kerja</label>
        </div>
    </div>
    <!-- <input class="btn_c1-1" id="simpan" name="simpan" type="submit" onclick="prosesc11" value="simpan"/> -->
    <button onclick="prosesc11()">Selanjutnya</button>
</fieldset><!--formc1-1-->
</form></code>```

This is Model Class

public function simpan_data_ts(){
      $idAlumni = $this->session->userdata('id_alumni');
      // $default = null;
      // $satu = $this->input->post('f3');
      // $datetime = date('Y-m-d');
      // $dataSimpan = array( 'f3' => $satu);

      //$f31 = $this->input->post('f31');
      $f32 = $this->input->post('f32');
      $data = array(
        'id_alumni_fk' => $idAlumni,
        'f3' => $this->input->post('f31')
      );
      $this->db->insert('tracer_study', $data);
}```

We hope, anyone can tell us what's wrong with it. And I have to say thank you for all your response.

答:
You can't call the model class directly from ajax, as a model class can't be accessed from an HTTP request.  You have to pass it first to a controller function, for example with a controller called Foo with a function called bar() the ajax you have would be:

```<code>$.ajax({
            url    : "<?php echo base_url().'index.php/foo/bar';?>",
            type   : 'post',
            data   : {'f31' : f31, 'f32' : f32},
            success: function(data){
                console.log(data);
            }
        });
</code>```

Then in the Foo::Bar function, load model and call your function to save the data:

```<code>public function bar() {
$this->load->model('your_model_name');
$this->your_model_name->simpan_data_ts($this->input->post);
</code>```

Body:
We want to put data from view () to database. We use Ajax to running some background process (insert data to database). But We can't save the data to database. I'm appreciate and thank's a lot for any suggest and good avice do you give. I'm sorry if this is just a newbie's question.

This is the View (form, fieldset, javascript, and ajax)

var popup, x, f31, f32, f33, f4, f5, f6, f7, f7a, f81, f82, f11, f14, f161, f17a1;

function _(x){
    return document.getElementById(x);
}

//fungsi tutup popup
function tutupPopup(){
    _("popup").style.display = "none";
}

function prosesc11(){
    f31 = _("f31").value;
    f32 = _("f32").value;
    f33 = _("f33").value;
    $.ajax({
        url    : "<?php echo base_url().'index.php/TracerStudy_model/simpan_data_ts';?>",
        type   : 'post',
        data   : {'f31' : f31, 'f32' : f32},
        success: function(data){
            console.log(data);
        }
    });

    if(f31.length>0||f32.length>0){
        _("formc1-1").style.display = "none";
        _("formc1-2").style.display = "block";
        _("progressBar").value = 50;
    }else{
        alert("Maaf data anda ada yang belum diisi.")
    }
}

<form class="multiphaseForm" id="multiphaseForm" onsubmit="return false"
    method="post" action="<?php base_url();?>TracerStudy/masuk_data_ts"
>
<fieldset class="formc1-1" id="formc1-1">

                1. Kapan anda mulai mencari pekerjaan ?

            <input class="col-lg-1" id="f31" name="f3" type="radio" value="1" class="form-control">
            Sebelum lulus

            <input class="col-lg-1" id="f32" name="f3" type="radio" value="2" class="form-control">
            Setelah lulus

            <input class="col-lg-1" id="f33" name="f3" type="radio" value="3" class="form-control">
            Tidak mencari kerja

    <button onclick="prosesc11()">Selanjutnya</button>
</fieldset>
</form>

This is Model Class

public function simpan_data_ts(){
      $idAlumni = $this->session->userdata('id_alumni');
      // $default = null;
      // $satu = $this->input->post('f3');
      // $datetime = date('Y-m-d');
      // $dataSimpan = array( 'f3' => $satu);

      //$f31 = $this->input->post('f31');
      $f32 = $this->input->post('f32');
      $data = array(
        'id_alumni_fk' => $idAlumni,
        'f3' => $this->input->post('f31')
      );
      $this->db->insert('tracer_study', $data);
}

We hope, anyone can tell us what's wrong with it. And I have to say thank you for all your response.

Body:
You can't call the model class directly from ajax, as a model class can't be accessed from an HTTP request.  You have to pass it first to a controller function, for example with a controller called Foo with a function called bar() the ajax you have would be:

$.ajax({
            url    : "<?php echo base_url().'index.php/foo/bar';?>",
            type   : 'post',
            data   : {'f31' : f31, 'f32' : f32},
            success: function(data){
                console.log(data);
            }
        });

Then in the Foo::Bar function, load model and call your function to save the data:

public function bar() {
$this->load->model('your_model_name');
$this->your_model_name->simpan_data_ts($this->input->post);


问:
Does Ping support multiple Audience restriction values in SAML?
Using PING as my identity provider do I have an option to set multiple audience values (in the service provider configuration I add for my application) so they will be returned within AudienceRestriction element of the SAML assertion?
As I see PING adds issuer value as audience and nothing else.

Example condition element

```<code><ns2:Conditions NotBefore="2011-01-10T20:52:56Z" NotOnOrAfter="2011-01-10T20:54:56Z">
  <ns2:AudienceRestriction>
    <ns2:Audience>urn:saml2:partnerspid</ns2:Audience>
  </ns2:AudienceRestriction>
  <ns2:AudienceRestriction>
    <ns2:Audience>Audience-IDP</ns2:Audience>
  </ns2:AudienceRestriction>
</ns2:Conditions>
</code>```

答:
You'll have to be running PingFed 8.0+ for this to work, which is where Ping began allowing the customization of request and response XML. You should read more on that subject in their documentation.

Using this:

```<code>#AssertionType.getConditions().addNewAudienceRestriction().addAudience("whatever:eh")
</code>```

will give you something like the following element:

```<code><saml:Conditions NotBefore="2017-03-24T20:23:55.341Z" NotOnOrAfter="2017-03-24T20:38:55.341Z">
  <saml:AudienceRestriction>
    <saml:Audience>pingfederate:default:entityId</saml:Audience>
  </saml:AudienceRestriction>
  <saml:AudienceRestriction>
    <saml:Audience>whatever:eh</saml:Audience>
  </saml:AudienceRestriction>
</saml:Conditions>
</code>```

However, SAML spec (SAML-CORE-2.0, 2.5.1.4) states:

Note that multiple  elements MAY be included in a
  single assertion, and each MUST be evaluated independently. The effect
  of this requirement and the preceding definition is that within a
  given condition, the audiences form a disjunction (an "OR") while
  multiple conditions form a conjunction (an "AND").

So, in that format that you are talking about, you will get an "AND". It's highly unlikely that your partner will be able to fulfill both, so I think you may be looking for an "OR". If that's the case, you'll want to use the following:

```<code>#AssertionType.getConditions().getAudienceRestrictionArray(0).addAudience("whatever:eh")
</code>```

Which should produce something like:

```<code><saml:Conditions NotBefore="2017-03-24T20:20:37.046Z" NotOnOrAfter="2017-03-24T20:35:37.046Z">
  <saml:AudienceRestriction>
    <saml:Audience>pingfederate:default:entityId</saml:Audience>
    <saml:Audience>whatever:eh</saml:Audience>
  </saml:AudienceRestriction>
</saml:Conditions>
</code>```

Body:
Using PING as my identity provider do I have an option to set multiple audience values (in the service provider configuration I add for my application) so they will be returned within AudienceRestriction element of the SAML assertion?
As I see PING adds issuer value as audience and nothing else.

Example condition element

<ns2:Conditions NotBefore="2011-01-10T20:52:56Z" NotOnOrAfter="2011-01-10T20:54:56Z">
  <ns2:AudienceRestriction>
    <ns2:Audience>urn:saml2:partnerspid</ns2:Audience>
  </ns2:AudienceRestriction>
  <ns2:AudienceRestriction>
    <ns2:Audience>Audience-IDP</ns2:Audience>
  </ns2:AudienceRestriction>
</ns2:Conditions>

Body:
You'll have to be running PingFed 8.0+ for this to work, which is where Ping began allowing the customization of request and response XML. You should read more on that subject in their documentation.

Using this:

#AssertionType.getConditions().addNewAudienceRestriction().addAudience("whatever:eh")

will give you something like the following element:

<saml:Conditions NotBefore="2017-03-24T20:23:55.341Z" NotOnOrAfter="2017-03-24T20:38:55.341Z">
  <saml:AudienceRestriction>
    <saml:Audience>pingfederate:default:entityId</saml:Audience>
  </saml:AudienceRestriction>
  <saml:AudienceRestriction>
    <saml:Audience>whatever:eh</saml:Audience>
  </saml:AudienceRestriction>
</saml:Conditions>

However, SAML spec (SAML-CORE-2.0, 2.5.1.4) states:

Note that multiple  elements MAY be included in a
  single assertion, and each MUST be evaluated independently. The effect
  of this requirement and the preceding definition is that within a
  given condition, the audiences form a disjunction (an "OR") while
  multiple conditions form a conjunction (an "AND").

So, in that format that you are talking about, you will get an "AND". It's highly unlikely that your partner will be able to fulfill both, so I think you may be looking for an "OR". If that's the case, you'll want to use the following:

#AssertionType.getConditions().getAudienceRestrictionArray(0).addAudience("whatever:eh")

Which should produce something like:

<saml:Conditions NotBefore="2017-03-24T20:20:37.046Z" NotOnOrAfter="2017-03-24T20:35:37.046Z">
  <saml:AudienceRestriction>
    <saml:Audience>pingfederate:default:entityId</saml:Audience>
    <saml:Audience>whatever:eh</saml:Audience>
  </saml:AudienceRestriction>
</saml:Conditions>


问:
Control if a 3x3 matrix is in an N x N Matrix with N>=3
Here is an example of what I mean.

I got two multidimensional arrays w and z.
z is a 3x3 matrix.
Now I want to controll if z is part of the bigger multidimensional array w.
Like z= (1,2,3),
        (1,2,3),
        (1,2,3)

w= (4,7,1,2,3)
   (7,8,1,2,3)
   (9,0,1,2,3)
   (8,1,5,3,6)
   (4,6,6,6,6)

In that case my function would give me a true.
I know how to acess all elements and single rows and columns.
Could someone give me a little push in the right direction?
My try

答:
Here is the function that return 1 if sub matrix of order 3x3 exist , else returns 0.    </p>

```<code>int submatrixcheck(int a[][10],int b[3][3],int n)
{
    int i,j,k,l,p=0;
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            if( (a[i][j] == b[0][0]) && i<(n-4) && (j<n-4))
            {
                for(k = 0;k<3;k++)
                    for(l= 0;l<3;l++)
                        if(a[i+k][j+l]!=b[k][l])
                        {
                            p=1;
                            goto c;
                        }

                if(p==0)
                   return 1;
                c:
            }
    return 0;

}
</code>```

Body:
Here is the function that return 1 if sub matrix of order 3x3 exist , else returns 0.

int submatrixcheck(int a[][10],int b[3][3],int n)
{
    int i,j,k,l,p=0;
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            if( (a[i][j] == b[0][0]) && i<(n-4) && (j<n-4))
            {
                for(k = 0;k<3;k++)
                    for(l= 0;l<3;l++)
                        if(a[i+k][j+l]!=b[k][l])
                        {
                            p=1;
                            goto c;
                        }

                if(p==0)
                   return 1;
                c:
            }
    return 0;

}


问:
Google Map with Default direction
In my site I've already implemented Google Map Direction API Version-3. With this I can show the direction between places by choosing from the selectbox.

Now I want to implement another map which will load initially with the directions I have given. Also with point to point direction. I want to print the map with the map and the directions. But I cannot load the map with directions when the page loads. Anyone have any idea?

答:
It would be great if you could show some code so we can tell you what is wrong...

Here are the steps that you should take in order to show the directions when the page loads:

show the map

find the coordinates for the locations (if you haven't got them
already, use the geocoding service
from google maps)

create a request to send to the directions service from google

send the request and get the result from it

show the result on the map

Don't forget that the geocoding and directions services are asynchronous and you will have to write the code for what happens after the results are received in a callback function.

Title: Google Map with Default direction