问:
Magnific Popup - Browser scrolls on the top on image click
I am using Magnific Popup plugin for displaying image in lightbox.When I click on the image  in Chrome, the browser scrolls on the top, after that the menu is not clickable.</p>

```<code>$('.img-item').magnificPopup({
    type: 'image',
    gallery:{
        enabled:true
    }
});
</code>```

答:
Looks like moving the magnificPopup code from $(document).ready() to $(window).load() did it for me. Here is my code:

```<code>$(window).load(function() {
  $('.open-popup-link').magnificPopup({
    type:'inline',
    closeBtnInside: true,
    fixedContentPos: false,
    midClick: true
  });
});
</code>```

Body:
I am using Magnific Popup plugin for displaying image in lightbox.When I click on the image  in Chrome, the browser scrolls on the top, after that the menu is not clickable.

$('.img-item').magnificPopup({
    type: 'image',
    gallery:{
        enabled:true
    }
});

Body:
Looks like moving the magnificPopup code from $(document).ready() to $(window).load() did it for me. Here is my code:

$(window).load(function() {
  $('.open-popup-link').magnificPopup({
    type:'inline',
    closeBtnInside: true,
    fixedContentPos: false,
    midClick: true
  });
});


来源: stackexchange

问:
How to run execute shell command in jenkins in different terminals
I am running my protractor test through jenkins and my package.json looks like this:

```<code>{"name": "ProtractorTest",
  "version": "0.0.1",
  "main": "conf.js",
  "scripts": {
    "setup": "npm install && node node_modules/protractor/bin/webdriver-manager update",
    "e2e-start": "node node_modules/protractor/bin/webdriver-manager start",
    "test": "protractor protractor.conf.js"
  }
</code>```

I am trying to run script using jenkins execute shell build step like below
Jenkins screenshot

but this tries to run setup,e2e-start,test one after other.  Since "e2e-start" starts selenium server,so I see in console "INFO - Selenium Server is up and running...." and then npm run test is never run . I think it's because "npm run test" should be run in different terminal because when we run manually, we start server in one terminal and run test in different terminal. So, how can I achieve this using jenkins.

答:
Try to use the bellow mentioned option in the config file then protractor will take care of starting and stopping of server itself, then you wont need to start and stop wendriver manager

```<code>    directConnect: true
    seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
</code>```

Also you can mention selenium server jar too.

```<code>    seleniumServerJar: '../utils/selenium-server-standalone-2.53.1.jar',
    seleniumPort: 4444,
</code>```

Another approach would be to use jenkins selenium pluggin

ContentLicense: CC BY-SA 3.0

Body:
I am running my protractor test through jenkins and my package.json looks like this:

{"name": "ProtractorTest",
  "version": "0.0.1",
  "main": "conf.js",
  "scripts": {
    "setup": "npm install && node node_modules/protractor/bin/webdriver-manager update",
    "e2e-start": "node node_modules/protractor/bin/webdriver-manager start",
    "test": "protractor protractor.conf.js"
  }

I am trying to run script using jenkins execute shell build step like below
Jenkins screenshot

but this tries to run setup,e2e-start,test one after other.  Since "e2e-start" starts selenium server,so I see in console "INFO - Selenium Server is up and running...." and then npm run test is never run . I think it's because "npm run test" should be run in different terminal because when we run manually, we start server in one terminal and run test in different terminal. So, how can I achieve this using jenkins.

Body:
Try to use the bellow mentioned option in the config file then protractor will take care of starting and stopping of server itself, then you wont need to start and stop wendriver manager

    directConnect: true
    seleniumAddress: 'http://127.0.0.1:4444/wd/hub',

Also you can mention selenium server jar too.

    seleniumServerJar: '../utils/selenium-server-standalone-2.53.1.jar',
    seleniumPort: 4444,

Another approach would be to use jenkins selenium pluggin


问:
Two implementations for List Monad bind in the literature: why are they equivalent?
Reading the Monad chapter in "Programming in Haskell" 2nd ed. from Graham Hutton, I found this example on page 167 to illustrate the behaviour of the List Monad:

```<code>> pairs [1,2] [3,4]
[(1,3),(1,4),(2,3),(2,4)]
</code>```

With pairs defined like this:

```<code>pairs :: [a] -> [b] -> [(a,b)]
pairs xs ys = do x <- xs
                 y <- ys
                 return (x,y)
</code>```

And this implementation of bind:

```<code>instance Monad [] where
   -- (>>=) :: [a] -> (a -> [b]) -> [b]
   xs >>= f = [y | x <- xs, y <- f x]
</code>```

I tried to understand with pencil and paper how the example worked out, but didn't get it.

Then I found, that in other books the bind operation is defined differently:

```<code>...
   xs >>= f = concat (fmap f xs)
</code>```

With this definition I understand why the example works.
But the first definition is the one I found on hackage in the prelude, so I trust its correct.

My question:

Can anybody explain why the first definition is equivalent to the second?          (Where does the concat-stuff happen in the first one?)

答:
List comprehensions are just syntactic sugar. Basically, [f x y | x<-l, y<-m] is sugar for

```<code>concatMap (\x -> concatMap (\y -> return $ f x y) m) l
</code>```

or equivalently

```<code>concat $ fmap (\x -> concat $ fmap (\y -> return $ f x y) m) l
</code>```

thus the two implementations are indeed equivalent by definition.

Anyway you can of course manually evaluate the example from the comprehension-based definition, using “intuitive set comprehension” evaluation:

```<code>pairs [1,2] [3,4]
 ≡ do { x <- [1,2]; y <- [3,4]; return (x,y) }
 ≡ [1,2] >>= \x -> [3,4] >>= \y -> return (x,y)
 ≡ [p | x<-[1,2], p <- (\ξ -> [3,4] >>= \y -> return (ξ,y)) x]
 ≡ [p | x<-[1,2], p <- ([3,4] >>= \y -> return (x,y))]
 ≡ [p | x<-[1,2], p <- [q | y<-[3,4], q <- (\υ -> return (x,υ)) y]]
 ≡ [p | x<-[1,2], p <- [q | y<-[3,4], q <- return (x,y)]]
 ≡ [p | x<-[1,2], p <- [q | y<-[3,4], q <- [(x,y)]]]
 ≡ [p | x<-[1,2], p <- [(x,3), (x,4)]]
 ≡ [(1,3), (1,4)] ++ [(2,3), (2,4)]
 ≡ [(1,3), (1,4), (2,3), (2,4)]
</code>```

Body:
Reading the Monad chapter in "Programming in Haskell" 2nd ed. from Graham Hutton, I found this example on page 167 to illustrate the behaviour of the List Monad:

> pairs [1,2] [3,4]
[(1,3),(1,4),(2,3),(2,4)]

With pairs defined like this:

pairs :: [a] -> [b] -> [(a,b)]
pairs xs ys = do x <- xs
                 y <- ys
                 return (x,y)

And this implementation of bind:

instance Monad [] where
   -- (>>=) :: [a] -> (a -> [b]) -> [b]
   xs >>= f = [y | x <- xs, y <- f x]

I tried to understand with pencil and paper how the example worked out, but didn't get it.

Then I found, that in other books the bind operation is defined differently:

...
   xs >>= f = concat (fmap f xs)

With this definition I understand why the example works.
But the first definition is the one I found on hackage in the prelude, so I trust its correct.

My question:

Can anybody explain why the first definition is equivalent to the second?          (Where does the concat-stuff happen in the first one?)

Body:
List comprehensions are just syntactic sugar. Basically, [f x y | x<-l, y<-m] is sugar for

concatMap (\x -> concatMap (\y -> return $ f x y) m) l

or equivalently

concat $ fmap (\x -> concat $ fmap (\y -> return $ f x y) m) l

thus the two implementations are indeed equivalent by definition.

Anyway you can of course manually evaluate the example from the comprehension-based definition, using “intuitive set comprehension” evaluation:

pairs [1,2] [3,4]
 ≡ do { x <- [1,2]; y <- [3,4]; return (x,y) }
 ≡ [1,2] >>= \x -> [3,4] >>= \y -> return (x,y)
 ≡ [p | x<-[1,2], p <- (\ξ -> [3,4] >>= \y -> return (ξ,y)) x]
 ≡ [p | x<-[1,2], p <- ([3,4] >>= \y -> return (x,y))]
 ≡ [p | x<-[1,2], p <- [q | y<-[3,4], q <- (\υ -> return (x,υ)) y]]
 ≡ [p | x<-[1,2], p <- [q | y<-[3,4], q <- return (x,y)]]
 ≡ [p | x<-[1,2], p <- [q | y<-[3,4], q <- [(x,y)]]]
 ≡ [p | x<-[1,2], p <- [(x,3), (x,4)]]
 ≡ [(1,3), (1,4)] ++ [(2,3), (2,4)]
 ≡ [(1,3), (1,4), (2,3), (2,4)]


问:
Modifying the content of a ingested pdf
I have a pipeline created in elasticsearch that ingests a document with an array of pdfs. I want to modify the content field in order to concatenate other fields at the end for searching purposes.

My pipeline is:

```<code>client.ingest.putPipeline({
  id: 'my-pipeline-id',
  body: {
    "description" : "Extract attachment information",
    "processors" :
    [
      {
        "foreach": {
          "field": "attachments",
          "processor": {
            "attachment": {
              "target_field": "_ingest._value.attachment",
              "field": "_ingest._value.data"
            }
          }
        }
      }
    ]
  }
}, callback);
</code>```

I can't add a set processor after the foreach, because I need to access the content of every pdf in order to put the values of that document at the end of the content.

Some example documents are:

```<code>let doc = {
    matricula: '6789AAA',
    bastidor: 'BASTIDOR789',
    expediente: '79',
    attachments:
    [
        {
            filename: "informe",
            data: /* chunk of data in base64 */
        },
        {
            filename: "ivtm_diba",
            data: /* another chunk of data in base64 */
        }
    ]
};
</code>```

The result document will look like this:

```<code>{
    "_index": "doc",
    "_type": "document",
    "_id": "AVsy85rwMuPe74hQBT8L",
    "_score": 1.2039728,
    "_source": {
      "attachments": [
        {
          "filename": "informe",
          "attachment": {
            "Very very long content",
            "date": "2016-06-08T14:01:25Z",
            "content_type": "application/pdf",
            "language": "es",
            "content_length": 3124
          }
        },
        {
          "filename": "ivtm_diba",
          "attachment": {
            "content": "Very long content here",
            "content_type": "application/pdf",
            "language": "ca",
            "content_length": 5657
          }
        }
      ],
      "expediente": "79",
      "matricula": "6789ZXC",
      "bastidor": "BASTIDOR789"
    }
  }
</code>```

And I want to add to the content field the values of "bastidor", "matricula" and "expediente" fields.

I'm using elasticsearch-js but that's not a requirement.

答: The elasticsearch _all field can be used in most cases like this.  </p>

Title: Modifying the content of a ingested pdf

Body:
I have a pipeline created in elasticsearch that ingests a document with an array of pdfs. I want to modify the content field in order to concatenate other fields at the end for searching purposes.

My pipeline is:

client.ingest.putPipeline({
  id: 'my-pipeline-id',
  body: {
    "description" : "Extract attachment information",
    "processors" :
    [
      {
        "foreach": {
          "field": "attachments",
          "processor": {
            "attachment": {
              "target_field": "_ingest._value.attachment",
              "field": "_ingest._value.data"
            }
          }
        }
      }
    ]
  }
}, callback);

I can't add a set processor after the foreach, because I need to access the content of every pdf in order to put the values of that document at the end of the content.

Some example documents are:

let doc = {
    matricula: '6789AAA',
    bastidor: 'BASTIDOR789',
    expediente: '79',
    attachments:
    [
        {
            filename: "informe",
            data: /* chunk of data in base64 */
        },
        {
            filename: "ivtm_diba",
            data: /* another chunk of data in base64 */
        }
    ]
};

The result document will look like this:

{
    "_index": "doc",
    "_type": "document",
    "_id": "AVsy85rwMuPe74hQBT8L",
    "_score": 1.2039728,
    "_source": {
      "attachments": [
        {
          "filename": "informe",
          "attachment": {
            "Very very long content",
            "date": "2016-06-08T14:01:25Z",
            "content_type": "application/pdf",
            "language": "es",
            "content_length": 3124
          }
        },
        {
          "filename": "ivtm_diba",
          "attachment": {
            "content": "Very long content here",
            "content_type": "application/pdf",
            "language": "ca",
            "content_length": 5657
          }
        }
      ],
      "expediente": "79",
      "matricula": "6789ZXC",
      "bastidor": "BASTIDOR789"
    }
  }

And I want to add to the content field the values of "bastidor", "matricula" and "expediente" fields.

I'm using elasticsearch-js but that's not a requirement.


问:
What are some resources for getting started in operating system development?
One thing I've always wanted to do is develop my very own operating system (not necessarily fancy like Linux or Windows, but better than a simple boot loader which I've already done).

I'm having a hard time finding resources/guides that take you past writing a simple "Hello World" OS.

I know lots of people will probably recommend I look at Linux or BSD; but the code base for systems like that is (presumably) so big that I wouldn't know where to start.

Any suggestions?

Update: To make it easier for people who land on this post through Google here are some OS development resources:

Writing Your Own Operating System (Thanks Adam)

Linux From Scratch (Thanks John)

SharpOS (C# Operating System) (Thanks lomaxx)

Minix3 and Minix2 (Thanks Mike)

OS Dev Wiki and Forums (Thanks Steve)

BonaFide (Thanks Steve)

Bran (Thanks Steve)

Roll your own toy UNIX-clone OS (Thanks Steve)

Broken Thorn OS Development Series

Other resources:

I found a nice resource named MikeOS, "MikeOS is a learning tool to demonstrate how simple OSes work. It uses 16-bit real mode for BIOS access, so that it doesn't need complex drivers"

Updated 11/14/08

I found some resources at Freebyte's Guide to...Free and non-free Operating Systems that links to kits such as OSKit and ExOS library.  These seem super useful in getting started in OS development.

Updated 2/23/09

Ric Tokyo recommended nanoos in this question.  Nanoos is an OS written in C++.

Updated 3/9/09

Dinah provided some useful Stack Overflow discussion of aspiring OS developers: Roadblocks in creating a custom operating system discusses what pitfalls you might encounter while developing an OS
and OS Development is a more general discussion.

Updated 7/9/09

LB provided a link to the Pintos Project, an education OS designed for students learning OS development.

Updated 7/27/09 (Still going strong!)

I stumbled upon an online OS course from Berkley featuring 23 lectures.

TomOS is a fork of MikeOS that includes a little memory manager and mouse support. As MikeOS, it is designed to be an educational project.  It is written in NASM assembler.

Updated 8/4/09

I found the slides and other materials to go along with the online Berkeley lectures listed above.

Updated 8/23/09

All questions tagged osdev on stackoverflow

OS/161 is an academic OS written in c that runs on a simulated hardware.  This OS is similar in Nachos.  Thanks Novelocrat!

tangurena recommends http://en.wikipedia.org/wiki/MicroC/OS-II, an OS designed for embedded systems.  There is a companion book as well.

Linux Kernel Development by Robert Love is suggested by Anders.  It is a "widely acclaimed insider's look at the Linux kernel."

Updated 9/18/2009

Thanks Tim S. Van Haren for telling us about Cosmos, an OS written entirely in c#.

tgiphil tells us about Managed Operating System Alliance (MOSA) Framework, "a set of tools, specifications and source code to foster development of managed operating systems based on the Common Intermediate Language."

Update 9/24/2009

Steve found a couple resources for development on windows using Visual Studio, check out BrokenThorn's guide setup with VS 2005 or OSDev's VS Section.

Updated 9/5/2012

kerneltrap.org is no longer available.  The linux kernel v0.01 is available from kernel.org

Updated 12/21/2012
A basic OS development tutorial designed to be a semester's project. It guides you through to build an OS with basic components. Very good start for beginners. Related paper.  Thanks Srujan!

Updated 11/15/2013

Writing a Simple Operating System From Scratch.  Thanks James Moore!

Updated 12/8/2013

How to make a computer operating system  Thanks ddtoni!

Updated 3/18/2014

ToAruOS an OS built mostly from scratch, including GUI

Updated Sept 12 2016

Writing your own Toy Operating System

Updated Dec 10 2016

Writing a Simple Operating System —from Scratch (thank you @Tyler C)

答:
Minix is a lot smaller, and designed for learning purposes, and the book to go with it is a good one too.

Update: I guess Minix 3 is a bit of a different goal, but Minix 2 (and of course the first version) were for teaching purposes.

OwnerDisplayName: Giovanni Galbo

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Giovanni Galbo

OwnerDisplayName: Mike Stone

ContentLicense: CC BY-SA 2.5


问:
Java: Subtract '0' from char to get an int... why does this work?
This works fine:

```<code>int foo = bar.charAt(1) - '0';
</code>```

Yet this doesn't - because bar.charAt(x) returns a char:

```<code>int foo = bar.charAt(1);
</code>```

It seems that subtracting '0' from the char is casting it to an integer.

Why, or how,  does subtracting the string '0' (or is it a char?) convert another char in to an integer?

答:
That's a clever trick. char's are actually of the same type / length as shorts. Now when you have a char that represents a ASCII/unicode digit (like '1'), and you subtract the smallest possible ASCII/unicode digit from it (e.g. '0'), then you'll be left with the digit's corresponding value (hence, 1)

Because char is the same as short (although, an unsigned short), you can safely cast it to an int. And the casting is always done automatically if arithmetics are involved

Body:
This works fine:

int foo = bar.charAt(1) - '0';

Yet this doesn't - because bar.charAt(x) returns a char:

int foo = bar.charAt(1);

It seems that subtracting '0' from the char is casting it to an integer.

Why, or how,  does subtracting the string '0' (or is it a char?) convert another char in to an integer?


问:
Split and remove particular value in href attribute and add new value using jquery
I have splitted the value in href attribute of a tag.

i splitted the value but i cannot remove the values and append new into it.

My HTML code is

```<code><a class="chapter_video" href="http://localhost/SVE128-portal2/public/video/9/25"></a>
</code>```

And my jquery is

```<code> var new = 4;
 var video_url = $('.chapter_video');
 var href = video_url.attr("href");
 //splitting value of href
 var split = href.split("/");
 if(split[7] !== undefined){
     href.remove(split[7]);
 }

 video_url.attr('href', video_url.attr('href') + '/'+ new);
</code>```

I have tried

```<code> var remove = href.replace('split[7]', '')
</code>```

instead of href.remove(split[7]);

答:
var video_url = $('.chapter_video');
 var href = video_url.attr("href");
 var split = href.split("/");
 var usethis;
 var addthis = 4;
 if(split[7] !== undefined){
     usethis = split.slice(0, -1);
 }
console.log(usethis.join("/")+ "/"+ addthis)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</code>```

To remove the last part use .splice()

Connect again using join("/")

Then add the new value with "/"

Body:
I have splitted the value in href attribute of a tag.

i splitted the value but i cannot remove the values and append new into it.

My HTML code is

And my jquery is

 var new = 4;
 var video_url = $('.chapter_video');
 var href = video_url.attr("href");
 //splitting value of href
 var split = href.split("/");
 if(split[7] !== undefined){
     href.remove(split[7]);
 }

 video_url.attr('href', video_url.attr('href') + '/'+ new);

I have tried

 var remove = href.replace('split[7]', '')

instead of href.remove(split[7]);

Body:
var video_url = $('.chapter_video');
 var href = video_url.attr("href");
 var split = href.split("/");
 var usethis;
 var addthis = 4;
 if(split[7] !== undefined){
     usethis = split.slice(0, -1);
 }
console.log(usethis.join("/")+ "/"+ addthis)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="chapter_video" href="http://localhost/SVE128-portal2/public/video/9/25"></a>

To remove the last part use .splice()

Connect again using join("/")

Then add the new value with "/"


问:
Printing numbers in sequence using 3 threads
I have a program where 3 Threads are trying to print numbers in sequence from 1 to 10. I am using a CountDownLatch to keep keep a count.

But the program stops just after printing 1.

Note: I am aware that using AtomicInteger instead of Integer can work. But I am looking to find out the issue in the current code.

```<code>public class Worker implements Runnable {
    private int id;
    private volatile Integer count;
    private CountDownLatch latch;

    public Worker(int id, Integer count, CountDownLatch latch) {
        this.id = id;
        this.count = count;
        this.latch = latch;
    }

    @Override
    public void run() {
        while (count <= 10) {
            synchronized (latch) {
                if (count % 3 == id) {
                    System.out.println("Thread: " + id + ":" + count);
                    count++;
                    latch.countDown();
                }
            }
        }
    }

}
</code>```

Main program:

```<code>public class ThreadSequence {
    private static CountDownLatch latch = new CountDownLatch(10);
    private volatile static Integer count = 0;

    public static void main(String[] args) {
        Thread t1 = new Thread(new Worker(0, count, latch));
        Thread t2 = new Thread(new Worker(1, count, latch));
        Thread t3 = new Thread(new Worker(2, count, latch));

        t1.start();
        t2.start();
        t3.start();

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
</code>```

Edited program with AtomicInteger:

```<code>public class ThreadSequence {
    private static AtomicInteger atomicInteger = new AtomicInteger(1);

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new WorkerThread(0, atomicInteger));
        Thread t2 = new Thread(new WorkerThread(1, atomicInteger));
        Thread t3 = new Thread(new WorkerThread(2, atomicInteger));
        t1.start();
        t2.start();
        t3.start();

        t1.join();
        t2.join();
        t3.join();

        System.out.println("Done with main");
    }
}

public class WorkerThread implements Runnable {
    private int id;
    private AtomicInteger atomicInteger;

    public WorkerThread(int id, AtomicInteger atomicInteger) {
        this.id = id;
        this.atomicInteger = atomicInteger;
    }

    @Override
    public void run() {
        while (atomicInteger.get() < 10) {
            synchronized (atomicInteger) {
                if (atomicInteger.get() % 3 == id) {
                    System.out.println("Thread:" + id + " = " + atomicInteger);
                    atomicInteger.incrementAndGet();
                }
            }

        }
    }
}
</code>```

答:
You can use below code to print sequential numbers using multiple threads -

```<code>import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ThreadCall extends Thread {

    private BlockingQueue<Integer> bq = new ArrayBlockingQueue<Integer>(10);
    private ThreadCall next;

    public void setNext(ThreadCall t) {
        this.next = t;
    }

    public void addElBQ(int a) {
        this.bq.add(a);
    }

    public ThreadCall(String name) {
        this.setName(name);
    }

    @Override
    public void run() {
        int x = 0;
        while(true) {
            try {
                x = 0;
                x = bq.take();
                if (x!=0) {
                    System.out.println(Thread.currentThread().getName() + " =>" + x);
                    if (x >= 100) System.exit(0); // Need to stop all running threads
                    next.addElBQ(x+1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        int THREAD_COUNT = 10;
        List<ThreadCall> listThread = new ArrayList<>();

        for (int i=1; i<=THREAD_COUNT; i++) {
            listThread.add(new ThreadCall("Thread " + i));
        }

        for (int i = 0; i < listThread.size(); i++) {
            if (i == listThread.size()-1) {
                listThread.get(i).setNext(listThread.get(0));
            }
            else listThread.get(i).setNext(listThread.get(i+1));
        }

        listThread.get(0).addElBQ(1);

        for (int i = 0; i < listThread.size(); i++) {
            listThread.get(i).start();
        }
    }
}
</code>```

I hope this will resolve your problem

Body:
I have a program where 3 Threads are trying to print numbers in sequence from 1 to 10. I am using a CountDownLatch to keep keep a count.

But the program stops just after printing 1.

Note: I am aware that using AtomicInteger instead of Integer can work. But I am looking to find out the issue in the current code.

public class Worker implements Runnable {
    private int id;
    private volatile Integer count;
    private CountDownLatch latch;

    public Worker(int id, Integer count, CountDownLatch latch) {
        this.id = id;
        this.count = count;
        this.latch = latch;
    }

    @Override
    public void run() {
        while (count <= 10) {
            synchronized (latch) {
                if (count % 3 == id) {
                    System.out.println("Thread: " + id + ":" + count);
                    count++;
                    latch.countDown();
                }
            }
        }
    }

}

Main program:

public class ThreadSequence {
    private static CountDownLatch latch = new CountDownLatch(10);
    private volatile static Integer count = 0;

    public static void main(String[] args) {
        Thread t1 = new Thread(new Worker(0, count, latch));
        Thread t2 = new Thread(new Worker(1, count, latch));
        Thread t3 = new Thread(new Worker(2, count, latch));

        t1.start();
        t2.start();
        t3.start();

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

Edited program with AtomicInteger:

public class ThreadSequence {
    private static AtomicInteger atomicInteger = new AtomicInteger(1);

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new WorkerThread(0, atomicInteger));
        Thread t2 = new Thread(new WorkerThread(1, atomicInteger));
        Thread t3 = new Thread(new WorkerThread(2, atomicInteger));
        t1.start();
        t2.start();
        t3.start();

        t1.join();
        t2.join();
        t3.join();

        System.out.println("Done with main");
    }
}

public class WorkerThread implements Runnable {
    private int id;
    private AtomicInteger atomicInteger;

    public WorkerThread(int id, AtomicInteger atomicInteger) {
        this.id = id;
        this.atomicInteger = atomicInteger;
    }

    @Override
    public void run() {
        while (atomicInteger.get() < 10) {
            synchronized (atomicInteger) {
                if (atomicInteger.get() % 3 == id) {
                    System.out.println("Thread:" + id + " = " + atomicInteger);
                    atomicInteger.incrementAndGet();
                }
            }

        }
    }
}

Body:
You can use below code to print sequential numbers using multiple threads -

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ThreadCall extends Thread {

    private BlockingQueue<Integer> bq = new ArrayBlockingQueue<Integer>(10);
    private ThreadCall next;

    public void setNext(ThreadCall t) {
        this.next = t;
    }

    public void addElBQ(int a) {
        this.bq.add(a);
    }

    public ThreadCall(String name) {
        this.setName(name);
    }

    @Override
    public void run() {
        int x = 0;
        while(true) {
            try {
                x = 0;
                x = bq.take();
                if (x!=0) {
                    System.out.println(Thread.currentThread().getName() + " =>" + x);
                    if (x >= 100) System.exit(0); // Need to stop all running threads
                    next.addElBQ(x+1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        int THREAD_COUNT = 10;
        List<ThreadCall> listThread = new ArrayList<>();

        for (int i=1; i<=THREAD_COUNT; i++) {
            listThread.add(new ThreadCall("Thread " + i));
        }

        for (int i = 0; i < listThread.size(); i++) {
            if (i == listThread.size()-1) {
                listThread.get(i).setNext(listThread.get(0));
            }
            else listThread.get(i).setNext(listThread.get(i+1));
        }

        listThread.get(0).addElBQ(1);

        for (int i = 0; i < listThread.size(); i++) {
            listThread.get(i).start();
        }
    }
}

I hope this will resolve your problem


问:
How to combine two different linux commands?
I use the following command to get the MAC address of the system.

```<code>ifconfig | grep enp0s20f6 | awk '{print $5}'
</code>```

The following command is used to get the hash of the string:

```<code>echo -n "string to be hashed"| md5sum | awk '{print $1}'
</code>```

I need to get the hashed string for the MAC address by combining both of these commands.

I tried the following, but didn't work.

```<code>ifconfig | grep enp0s20f6 | awk '{print $5}' | md5sum
</code>```

答:
Try this:

```<code>$ cat /sys/class/net/eth0/address | md5sum
</code>```

Replace eth0 by the name of your interface. Hope it helps! :)

Body:
I use the following command to get the MAC address of the system.

ifconfig | grep enp0s20f6 | awk '{print $5}'

The following command is used to get the hash of the string:

echo -n "string to be hashed"| md5sum | awk '{print $1}'

I need to get the hashed string for the MAC address by combining both of these commands.

I tried the following, but didn't work.

ifconfig | grep enp0s20f6 | awk '{print $5}' | md5sum

Body:
Try this:

$ cat /sys/class/net/eth0/address | md5sum

Replace eth0 by the name of your interface. Hope it helps! :)


问:
rJava install error "JAVA_HOME cannot be determined from the Registry"
I am trying to load the rJava using the command:

```<code> library(rJava)
</code>```

But I get the following error:

```<code> Error : .onLoad failed in loadNamespace() for 'rJava', details:
   call: fun(libname, pkgname)
   error: JAVA_HOME cannot be determined from the Registry
 Error: package or namespace load failed for ‘rJava’
</code>```

I tried reinstalling both the Java and the R program with the latest versions
but still get these errors..
May I know how I can resolve this? Thank you very much!

答:
I got the same error resolved by installing same version of R and Java i.e. 64 bits and manually updating the path i.e. ,</p>

```<code>Sys.setenv(JAVA_HOME='C:/Program Files/Java/jre1.8.0_121') # for 64-bit version
</code>```

Body:
I am trying to load the rJava using the command:

 library(rJava)

But I get the following error:

 Error : .onLoad failed in loadNamespace() for 'rJava', details:
   call: fun(libname, pkgname)
   error: JAVA_HOME cannot be determined from the Registry
 Error: package or namespace load failed for ‘rJava’

I tried reinstalling both the Java and the R program with the latest versions
but still get these errors..
May I know how I can resolve this? Thank you very much!

Body:
I got the same error resolved by installing same version of R and Java i.e. 64 bits and manually updating the path i.e. ,

Sys.setenv(JAVA_HOME='C:/Program Files/Java/jre1.8.0_121') # for 64-bit version


问:
Unable to add my library to JCenter
Hi I am working on one library just for my learning purpose. I am trying to publish it on JCenter. I have followed all the steps of this tutorial https://medium.com/@daniellevass/how-to-publish-your-android-studio-library-to-jcenter-5384172c4739#.fdsjj7qku

I am unable to add to JCenter my library, there is no text of "Add to JCenter" is being shown to me. Can anyone suggest what could be the problem ?

Expected state:

Current state:

答:
You won't be able to link your library if you are using a Trial account, as linking to jcenter is permanent...

Many people have this problem, as you can see here:

Bintray link to jcenter missing

And here:

there is no "add to jcenter" button in "https://bintray.com"

But not to worry... Just create a OSS account and you will be able to link your Open Source libraries.

Title: Unable to add my library to JCenter


问:
Text becomes "Red" color; Can't find the code that makes it "Red"
I have a simple php page which outputs a table (which has been created dynamically).

The text on the page is all red marked, unless you specifically put a font color element and force it to become black.

I use FF and have Firebug installed, so I wonder if you guys have any tips on how to troubleshoot why this text isn't black?

I have tried:

1- Setting the body text color to 000 both with css and html... Didn't work!

2- Checking all classes.

Any tips???

All I have figured out is that when I DONT include my css files, the text becomes black standard. And I have looked at the css files without finding anything suspicious.

How should I troubleshoot?

Isn't there any way to check which styles if any, a text has applied to it somehow?

答:
If you inspect the element in Firebug it should tell you all the styles attached to that element (Including the inherited ones)

Like in the screen shot in the page below.

http://getfirebug.com/css


问:
Spring JDBC using application.properties file
I'm training myself on Spring JDBC and I'm following this tutorial: Spring JDBC Example.

The tutorial is very good and executing the code I have no problem.

Fof simplicity and convenience, I quote here the code.

First class, Student (the entity to store in db):

```<code>package com.tutorialspoint;

public class Student
{
       private Integer age;
       private String name;
       private Integer id;

       public void setAge(Integer age)
       {
          this.age = age;
       }

       public Integer getAge()
       {
          return age;
       }

       public void setName(String name)
       {
          this.name = name;
       }

       public String getName()
       {
          return name;
       }

       public void setId(Integer id)
       {
          this.id = id;
       }

       public Integer getId()
       {
          return id;
       }
    }
</code>```

Interface, StudentDAO (for DAO logic):

```<code>package com.tutorialspoint;

import java.util.List;
import javax.sql.DataSource;

public interface StudentDAO
{
   /**
      * This is the method to be used to initialize
      * database resources ie. connection.
   */
   public void setDataSource(DataSource ds);

   /**
      * This is the method to be used to create
      * a record in the Student table.
   */
   public void create(String name, Integer age);

   /**
      * This is the method to be used to list down
      * a record from the Student table corresponding
      * to a passed student id.
   */
   public Student getStudent(Integer id);

   /**
      * This is the method to be used to list down
      * all the records from the Student table.
   */
   public List<Student> listStudents();

   /**
      * This is the method to be used to delete
      * a record from the Student table corresponding
      * to a passed student id.
   */
   public void delete(Integer id);

   /**
      * This is the method to be used to update
      * a record into the Student table.
   */
   public void update(Integer id, Integer age);
}
</code>```

Then, the class StudentJDBCTemplate (to implements StudentDAO):

```<code>package com.tutorialspoint;

import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;

public class StudentJDBCTemplate implements StudentDAO
{
   private DataSource dataSource;
   private JdbcTemplate jdbcTemplateObject;

   public void setDataSource(DataSource dataSource)
   {
      this.dataSource = dataSource;
      this.jdbcTemplateObject = new JdbcTemplate(dataSource);
   }

   public void create(String name, Integer age)
   {
      String SQL = "insert into Student (name, age) values (?, ?)";
      jdbcTemplateObject.update( SQL, name, age);
      System.out.println("Created Record Name = " + name + " Age = " + age);
      return;
   }

   public Student getStudent(Integer id)
   {
      String SQL = "select * from Student where id = ?";
      Student student = jdbcTemplateObject.queryForObject(SQL,
         new Object[]{id}, new StudentMapper());

      return student;
   }

   public List<Student> listStudents()
   {
      String SQL = "select * from Student";
      List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
      return students;
   }

   public void delete(Integer id)
   {
      String SQL = "delete from Student where id = ?";
      jdbcTemplateObject.update(SQL, id);
      System.out.println("Deleted Record with ID = " + id );
      return;
   }

   public void update(Integer id, Integer age)
   {
      String SQL = "update Student set age = ? where id = ?";
      jdbcTemplateObject.update(SQL, age, id);
      System.out.println("Updated Record with ID = " + id );
      return;
   }
}
</code>```

Third class: StudentMapper (to mapping to MySQL db Student):

```<code>package com.tutorialspoint;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class StudentMapper implements RowMapper<Student>
{
   public Student mapRow(ResultSet rs, int rowNum) throws SQLException
   {
      Student student = new Student();
      student.setId(rs.getInt("id"));
      student.setName(rs.getString("name"));
      student.setAge(rs.getInt("age"));

      return student;
   }
}
</code>```

Last class, MainApp (run the application):

```<code>  package com.tutorialspoint;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tutorialspoint.StudentJDBCTemplate;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      StudentJDBCTemplate studentJDBCTemplate =
         (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");

      System.out.println("------Records Creation--------" );
      studentJDBCTemplate.create("Zara", 11);
      studentJDBCTemplate.create("Nuha", 2);
      studentJDBCTemplate.create("Ayan", 15);

      System.out.println("------Listing Multiple Records--------" );
      List<Student> students = studentJDBCTemplate.listStudents();

      for (Student record : students) {
         System.out.print("ID : " + record.getId() );
         System.out.print(", Name : " + record.getName() );
         System.out.println(", Age : " + record.getAge());
      }

      System.out.println("----Updating Record with ID = 2 -----" );
      studentJDBCTemplate.update(2, 20);

      System.out.println("----Listing Record with ID = 2 -----" );
      Student student = studentJDBCTemplate.getStudent(2);
      System.out.print("ID : " + student.getId() );
      System.out.print(", Name : " + student.getName() );
      System.out.println(", Age : " + student.getAge());
   }
}
</code>```

Finally, the Beans file to configure database connection:

```<code><?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">

   <!-- Initialization for data source -->
   <bean id="dataSource"
      class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
      <property name = "url" value = "jdbc:mysql://localhost:3306/springtraining"/>
      <property name = "username" value = "***"/>
      <property name = "password" value = "***"/>
   </bean>

   <!-- Definition for studentJDBCTemplate bean -->
   <bean id = "studentJDBCTemplate"
      class = "com.tutorialspoint.StudentJDBCTemplate">
      <property name = "dataSource" ref = "dataSource" />
   </bean>

</beans>
</code>```

The tutorial is very clear and if i try it, there is a perfect execution without error and the MySQL Db is correctly updated.

My questions are about a possible variation of this project. More specifically:

If I want to use the application.properties file (as that given by SpringBoot), is it this the correct syntax?

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springtraining
spring.datasource.username=***
spring.datasource.password=***

If I don't want use the RowMapper class, is it correct to use the one given by Spring, the BeanPropertyRowMapper?

Without the Beans file (if I use, for this example, the application.properties, I have no need of it), how can I replace in the MainApp this rows:

ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

```<code>   StudentJDBCTemplate studentJDBCTemplate =
      (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
</code>```

and making so the applications executable?

答:
Firstly, I'd advise you to learn how to do it without application.properties file. We live in 21rst century, where Spring-boot allows us to declare jdbc dataSource as @Bean with database credentials in MySpringBootApplication class. See how to do it here

Secondly, i'd advise not to use jdbcTemplate unless you don't have time. Mark my words, if happens to debug - it would be nightmare. So try to use
pure Jdbc with addition of spring configuration.

Sample example how to do it:

StudentDAO interface

```<code>    public interface StundentDAO {

    void addStudent(String name, String surname);

    List<Student> findStudents();
}
</code>```

JdbcStudentDAO implementation

```<code>    @Repository
    public class JdbcStudentDAO implements StudentDAO {

    //[IMPORTANT] import javax.sql.datasource package (?)
    private Datasource datasource;

    @Autowire
    public JdbcStudentDAO(Datasource datasource) {
        this.datasource = datasource;
    }

    @Override
    public void addStudent(String name, String surname) {
        String query = "INSERT INTO Students VALUES (?,?)";
        try(Connection connection = datasource.getConnection()) {
            try(PreparedStatement statement = connection.preparedStatement(query)) {
                statement.setString(1, name);
                statement.setString(2, surname);
                statement.executeUpdate();
            }
        } catch(SQLException e) {
            e.printStacktrace();
        }
    }

    @Override
    public List<Student> findStudents() {
        String query = "SELECT * FROM Students";
        Student student = null; //will be used soon as DTO
        List<Student> listOfStudents = null;
        try(Connection connection = datasource.getConnection()) {
            try(PreparedStatement statement = connection.preparedStatement(query)) {
                try(ResultSet rs = statement.executeQuery()) {
                    listOfStudents = new ArrayList<>();
                    while(rs.next()) {
                        student = new Student(
                            rs.getString("name");
                            rs.getString("surname");
                        );
                    }
                    listOfStudents.add(student);
                }
            }
        } catch(SQLException e) {
            e.printStacktrace();
        }
        return listOfStudents;
    }
}
</code>```

Please note, that dataSource does only Database connectivity.(see the link)

Good luck!

Body:
I'm training myself on Spring JDBC and I'm following this tutorial: Spring JDBC Example.

The tutorial is very good and executing the code I have no problem.

Fof simplicity and convenience, I quote here the code.

First class, Student (the entity to store in db):

package com.tutorialspoint;

public class Student
{
       private Integer age;
       private String name;
       private Integer id;

       public void setAge(Integer age)
       {
          this.age = age;
       }

       public Integer getAge()
       {
          return age;
       }

       public void setName(String name)
       {
          this.name = name;
       }

       public String getName()
       {
          return name;
       }

       public void setId(Integer id)
       {
          this.id = id;
       }

       public Integer getId()
       {
          return id;
       }
    }

Interface, StudentDAO (for DAO logic):

package com.tutorialspoint;

import java.util.List;
import javax.sql.DataSource;

public interface StudentDAO
{
   /**
      * This is the method to be used to initialize
      * database resources ie. connection.
   */
   public void setDataSource(DataSource ds);

   /**
      * This is the method to be used to create
      * a record in the Student table.
   */
   public void create(String name, Integer age);

   /**
      * This is the method to be used to list down
      * a record from the Student table corresponding
      * to a passed student id.
   */
   public Student getStudent(Integer id);

   /**
      * This is the method to be used to list down
      * all the records from the Student table.
   */
   public List<Student> listStudents();

   /**
      * This is the method to be used to delete
      * a record from the Student table corresponding
      * to a passed student id.
   */
   public void delete(Integer id);

   /**
      * This is the method to be used to update
      * a record into the Student table.
   */
   public void update(Integer id, Integer age);
}

Then, the class StudentJDBCTemplate (to implements StudentDAO):

package com.tutorialspoint;

import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;

public class StudentJDBCTemplate implements StudentDAO
{
   private DataSource dataSource;
   private JdbcTemplate jdbcTemplateObject;

   public void setDataSource(DataSource dataSource)
   {
      this.dataSource = dataSource;
      this.jdbcTemplateObject = new JdbcTemplate(dataSource);
   }

   public void create(String name, Integer age)
   {
      String SQL = "insert into Student (name, age) values (?, ?)";
      jdbcTemplateObject.update( SQL, name, age);
      System.out.println("Created Record Name = " + name + " Age = " + age);
      return;
   }

   public Student getStudent(Integer id)
   {
      String SQL = "select * from Student where id = ?";
      Student student = jdbcTemplateObject.queryForObject(SQL,
         new Object[]{id}, new StudentMapper());

      return student;
   }

   public List<Student> listStudents()
   {
      String SQL = "select * from Student";
      List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
      return students;
   }

   public void delete(Integer id)
   {
      String SQL = "delete from Student where id = ?";
      jdbcTemplateObject.update(SQL, id);
      System.out.println("Deleted Record with ID = " + id );
      return;
   }

   public void update(Integer id, Integer age)
   {
      String SQL = "update Student set age = ? where id = ?";
      jdbcTemplateObject.update(SQL, age, id);
      System.out.println("Updated Record with ID = " + id );
      return;
   }
}

Third class: StudentMapper (to mapping to MySQL db Student):

package com.tutorialspoint;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class StudentMapper implements RowMapper<Student>
{
   public Student mapRow(ResultSet rs, int rowNum) throws SQLException
   {
      Student student = new Student();
      student.setId(rs.getInt("id"));
      student.setName(rs.getString("name"));
      student.setAge(rs.getInt("age"));

      return student;
   }
}

Last class, MainApp (run the application):

  package com.tutorialspoint;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tutorialspoint.StudentJDBCTemplate;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      StudentJDBCTemplate studentJDBCTemplate =
         (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");

      System.out.println("------Records Creation--------" );
      studentJDBCTemplate.create("Zara", 11);
      studentJDBCTemplate.create("Nuha", 2);
      studentJDBCTemplate.create("Ayan", 15);

      System.out.println("------Listing Multiple Records--------" );
      List<Student> students = studentJDBCTemplate.listStudents();

      for (Student record : students) {
         System.out.print("ID : " + record.getId() );
         System.out.print(", Name : " + record.getName() );
         System.out.println(", Age : " + record.getAge());
      }

      System.out.println("----Updating Record with ID = 2 -----" );
      studentJDBCTemplate.update(2, 20);

      System.out.println("----Listing Record with ID = 2 -----" );
      Student student = studentJDBCTemplate.getStudent(2);
      System.out.print("ID : " + student.getId() );
      System.out.print(", Name : " + student.getName() );
      System.out.println(", Age : " + student.getAge());
   }
}

Finally, the Beans file to configure database connection:

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">

   <bean id="dataSource"
      class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
      <property name = "url" value = "jdbc:mysql://localhost:3306/springtraining"/>
      <property name = "username" value = "***"/>
      <property name = "password" value = "***"/>
   </bean>

   <bean id = "studentJDBCTemplate"
      class = "com.tutorialspoint.StudentJDBCTemplate">
      <property name = "dataSource" ref = "dataSource" />
   </bean>

</beans>

The tutorial is very clear and if i try it, there is a perfect execution without error and the MySQL Db is correctly updated.

My questions are about a possible variation of this project. More specifically:

If I want to use the application.properties file (as that given by SpringBoot), is it this the correct syntax?

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springtraining
spring.datasource.username=***
spring.datasource.password=***

If I don't want use the RowMapper class, is it correct to use the one given by Spring, the BeanPropertyRowMapper?

Without the Beans file (if I use, for this example, the application.properties, I have no need of it), how can I replace in the MainApp this rows:

ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

   StudentJDBCTemplate studentJDBCTemplate =
      (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");

and making so the applications executable?

Body:
Firstly, I'd advise you to learn how to do it without application.properties file. We live in 21rst century, where Spring-boot allows us to declare jdbc dataSource as @Bean with database credentials in MySpringBootApplication class. See how to do it here

Secondly, i'd advise not to use jdbcTemplate unless you don't have time. Mark my words, if happens to debug - it would be nightmare. So try to use
pure Jdbc with addition of spring configuration.

Sample example how to do it:

StudentDAO interface

    public interface StundentDAO {

    void addStudent(String name, String surname);

    List<Student> findStudents();
}

JdbcStudentDAO implementation

    @Repository
    public class JdbcStudentDAO implements StudentDAO {

    //[IMPORTANT] import javax.sql.datasource package (?)
    private Datasource datasource;

    @Autowire
    public JdbcStudentDAO(Datasource datasource) {
        this.datasource = datasource;
    }

    @Override
    public void addStudent(String name, String surname) {
        String query = "INSERT INTO Students VALUES (?,?)";
        try(Connection connection = datasource.getConnection()) {
            try(PreparedStatement statement = connection.preparedStatement(query)) {
                statement.setString(1, name);
                statement.setString(2, surname);
                statement.executeUpdate();
            }
        } catch(SQLException e) {
            e.printStacktrace();
        }
    }

    @Override
    public List<Student> findStudents() {
        String query = "SELECT * FROM Students";
        Student student = null; //will be used soon as DTO
        List<Student> listOfStudents = null;
        try(Connection connection = datasource.getConnection()) {
            try(PreparedStatement statement = connection.preparedStatement(query)) {
                try(ResultSet rs = statement.executeQuery()) {
                    listOfStudents = new ArrayList<>();
                    while(rs.next()) {
                        student = new Student(
                            rs.getString("name");
                            rs.getString("surname");
                        );
                    }
                    listOfStudents.add(student);
                }
            }
        } catch(SQLException e) {
            e.printStacktrace();
        }
        return listOfStudents;
    }
}

Please note, that dataSource does only Database connectivity.(see the link)

Good luck!


问:
Change Destination node for Vehicles Dynamically
I am trying to simulate a scenario where after a fixed number of vehicles have reached the destination node, the vehicles after that should go to a different destination.For this I want to have a RSU at the destination that sends message after it has received the fixed number of vehicles??</p>

答:
Something similar to what you are asking is done in the Veins demo scenario:

RSU side

```<code>void TraCIDemoRSU11p::sendMessage(std::string blockedRoadId) {
    sentMessage = true;
    t_channel channel = dataOnSch ? type_SCH : type_CCH;
    WaveShortMessage* wsm = prepareWSM("data", dataLengthBits, channel, dataPriority, -1,2);
    wsm->setWsmData(blockedRoadId.c_str());
    sendWSM(wsm);
}
</code>```

wsm->setWsmData(blockedRoadId.c_str()) encodes the ID of the blocked road to the message, so the vehicles can read that.

Vehicle side

```<code>void TraCIDemo11p::onData(WaveShortMessage* wsm) {
    findHost()->getDisplayString().updateWith("r=16,green");
    annotations->scheduleErase(1, annotations->drawLine(wsm->getSenderPos(), mobility->getPositionAt(simTime()), "blue"));

    if (mobility->getRoadId()[0] != ':') traciVehicle->changeRoute(wsm->getWsmData(), 9999);
    if (!sentMessage) sendMessage(wsm->getWsmData());
}
</code>```

traciVehicle->changeRoute() is used to change the route.

Body:
Something similar to what you are asking is done in the Veins demo scenario:

RSU side

void TraCIDemoRSU11p::sendMessage(std::string blockedRoadId) {
    sentMessage = true;
    t_channel channel = dataOnSch ? type_SCH : type_CCH;
    WaveShortMessage* wsm = prepareWSM("data", dataLengthBits, channel, dataPriority, -1,2);
    wsm->setWsmData(blockedRoadId.c_str());
    sendWSM(wsm);
}

wsm->setWsmData(blockedRoadId.c_str()) encodes the ID of the blocked road to the message, so the vehicles can read that.

Vehicle side

void TraCIDemo11p::onData(WaveShortMessage* wsm) {
    findHost()->getDisplayString().updateWith("r=16,green");
    annotations->scheduleErase(1, annotations->drawLine(wsm->getSenderPos(), mobility->getPositionAt(simTime()), "blue"));

    if (mobility->getRoadId()[0] != ':') traciVehicle->changeRoute(wsm->getWsmData(), 9999);
    if (!sentMessage) sendMessage(wsm->getWsmData());
}

traciVehicle->changeRoute() is used to change the route.


问:
Should ViewModels contain Property Values against Property IDs in the Entity (Model Class)?
So I have CityID (property) in my Interview Entity/Model.

Can(should) I have CityName in my ViewModel (InterviewViewModel.cs)?

If yes, how would I map them using AutoMapper since it (City) is a separate Entity?

```<code>            Mapper.Initialize(cfg =>
        {
        cfg.CreateMap<Interview, InterviewViewModel>()
        .ForMember
            (dst => dst.CityName, src => src.MapFrom (e => e. // how would I do this?? ))

        });
</code>```

答:
Plase create a City navigation property in Interview and do e=> e.City.CityName in automapper conifg.

It will make things easier and you will be able to utilize the full potential of Entity Framework or other ORM you are using. Other wise you will need to manually query the City table and then add the name to you Interview ViewModel.

Body:
So I have CityID (property) in my Interview Entity/Model.

Can(should) I have CityName in my ViewModel (InterviewViewModel.cs)?

If yes, how would I map them using AutoMapper since it (City) is a separate Entity?

            Mapper.Initialize(cfg =>
        {
        cfg.CreateMap<Interview, InterviewViewModel>()
        .ForMember
            (dst => dst.CityName, src => src.MapFrom (e => e. // how would I do this?? ))

        });


问:
Angular CLI - create a new project choosing Angular2 version
Good morning,
I'm trying to use Angular CLI to start a project in Angular 2 and not in Angular 4, I mean I would like to use version 2.4.10 for example.
There are any way to create it using Angular CLI, can't find which parameters I need to use or if it's possible, I would apreciate any help, Googling I haven't found anything.

I mean, if I type ng new myProject, this project is create in Angular4.

Thank you very much

答:
angular-cli v1.0.0 uses angular ^4.0.0 and there is no option to change it.

But it seems like v1.0.0-rc.4 uses ^2.4.0 by default. And it seems there is an option ng new <name> --ng4 to use angular4.

Btw ^4.0.0 is backward compatible with 2.4.


问:
How to use struct in a function
```<code>typedef struct node {
    int num_children;
    struct node *children[ALPHABET_LENGTH];
} trie_node;

void add(char* a, trie_node* node){//need to make sure a is not NULL at beginning
    trie_node* newNode;
    int i;
    if (a != NULL && node->children[(int)a[0] - 97] == NULL)
    {
        node->num_children++;
        //initialize the children array
        for (i = 0; i < ALPHABET_LENGTH; i++)
        {
            if (newNode->children[i] != NULL)
            {
                newNode->children[i] = NULL;
            }
        }
        newNode -> num_children = 0;
        a++;
        add(a, newNode);
    }
    else if (a != NULL && node->children[(int)a[0] - 97] != NULL){
        a++;
        node->num_children++;
        add(a, node->children[(int)a[0] - 97]);
    } else{//a == NULL, which means end of the add procedure
        return;
    }
}

int main()
{
        char* s = "add abc";
        trie_node* contacts;
        add(s,contacts);
        return 0;
}
</code>```

When I intialize the struct trie_node in main function, I can access all member of contacts. However, when I do that in my add function, the newNode doesn't work. I cannot access members like num_children under newNode. How could I fix that if I want to add a new node to the contacts

答:
You don't allocate any stoarge to contacts or set it to NULL in main or test if it is null in add.

If you are lucky, because you are right at the start of the program, contacts is NULL when you pass it in, so the if test at the top of add crashes with a segmentation violation.

Also, you use newNode without allocating space to it.

Title: How to use struct in a function

Body:
typedef struct node {
    int num_children;
    struct node *children[ALPHABET_LENGTH];
} trie_node;

void add(char* a, trie_node* node){//need to make sure a is not NULL at beginning
    trie_node* newNode;
    int i;
    if (a != NULL && node->children[(int)a[0] - 97] == NULL)
    {
        node->num_children++;
        //initialize the children array
        for (i = 0; i < ALPHABET_LENGTH; i++)
        {
            if (newNode->children[i] != NULL)
            {
                newNode->children[i] = NULL;
            }
        }
        newNode -> num_children = 0;
        a++;
        add(a, newNode);
    }
    else if (a != NULL && node->children[(int)a[0] - 97] != NULL){
        a++;
        node->num_children++;
        add(a, node->children[(int)a[0] - 97]);
    } else{//a == NULL, which means end of the add procedure
        return;
    }
}

int main()
{
        char* s = "add abc";
        trie_node* contacts;
        add(s,contacts);
        return 0;
}

When I intialize the struct trie_node in main function, I can access all member of contacts. However, when I do that in my add function, the newNode doesn't work. I cannot access members like num_children under newNode. How could I fix that if I want to add a new node to the contacts


问:
Get matched word count from a variable
I want to get the total count of test word in the $channel variable, but $a returns the same as $channel.

```<code>$channel = "test1 test2 test3 test4 testIgnore1 testIgnore2 testIgnore3"
$a = Select-String -InputObject $channel -Pattern "test"
</code>```

What should be the exact solution here?

答:
Use the -AllMatches parameter switch to get all matches from Select-String:

```<code>$channel = "test1 test2 test3 test4 testIgnore1 testIgnore2 testIgnore3"
$a = Select-String -InputObject $channel -Pattern "test" -AllMatches
</code>```

$a will contain a MatchInfo object. Count its Matches:

```<code>$a.Matches.Count
</code>```

Title: Get matched word count from a variable

Body:
I want to get the total count of test word in the $channel variable, but $a returns the same as $channel.

$channel = "test1 test2 test3 test4 testIgnore1 testIgnore2 testIgnore3"
$a = Select-String -InputObject $channel -Pattern "test"

What should be the exact solution here?

Body:
Use the -AllMatches parameter switch to get all matches from Select-String:

$channel = "test1 test2 test3 test4 testIgnore1 testIgnore2 testIgnore3"
$a = Select-String -InputObject $channel -Pattern "test" -AllMatches

$a will contain a MatchInfo object. Count its Matches:

$a.Matches.Count


问:
Firebase adapter populateViewHolder() is never called
activity layout :

android:layout_height="match_parent"

```<code>    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/activity_list_tasks2"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_list_tasks"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

   ... something else...

    </RelativeLayout>
</code>```

activity class :

rv.setHasFixedSize(true);

```<code>public class AdminActivity2 extends AppCompatActivity {

    RecyclerView rv;

    private DatabaseReference myRef;

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.admin_activity);

        rv = (RecyclerView) findViewById(R.id.rv_list_tasks);

        myRef = FirebaseDatabase.getInstance().getReference();

        FirebaseRecyclerAdapter<Machinist, AdminActivity2.MachinistsViewHolder2> adapter;
        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        rv.setLayoutManager(llm);
        rv.setHasFixedSize(true);
        rv.post(this::supportStartPostponedEnterTransition);
        Query query = myRef.child("Машинисты").orderByChild("points/itogo");

        adapter = new FirebaseRecyclerAdapter<Machinist, MachinistsViewHolder2>(
                Machinist.class,
                R.layout.machinist_item,
                MachinistsViewHolder2.class,
                query){

            @Override
            public void onBindViewHolder(MachinistsViewHolder2 viewHolder, int position) {

            }

            @Override
            protected void populateViewHolder(MachinistsViewHolder2 viewHolder, Machinist model, int position) {

                Log.d("djuyf", "populate");

                Typeface mTypeface;
                mTypeface = Typeface.create("sans-serif-regular", Typeface.NORMAL);

                DatabaseReference itemRef = getRef(position);

                viewHolder.cvRemove.setOnClickListener(view -> {
                    AlertDialog diaBox = askOption(itemRef);
                    diaBox.show();
                });
                viewHolder.cvArchive.setOnClickListener(view -> {
                    Intent startArchiveActivity = new Intent(AdminActivity2.this, Archive.class);
                    startArchiveActivity.putExtra("Name", viewHolder.tvName.getText().toString());
                    Gson gson = new Gson();
                    String myJson = gson.toJson(model);
                    startArchiveActivity.putExtra("myjson", myJson);
                    startActivity(startArchiveActivity);
                });

                viewHolder.tvPosition.setText(String.format(Locale.getDefault(), "%02d", position + 1));
                viewHolder.tvName.setText(model.getLastName() + " " + model.getFirstName().charAt(0) + model.getMiddleName().charAt(0));
                viewHolder.tvName.setTypeface(mTypeface);

                viewHolder.cvTo.setTitleText(pointCount(model.getArchive(), Constants.header.to, false));
                viewHolder.cvTo.setOnClickListener(view -> showDialog("Цикл ТО-1", itemRef, model, TO, viewHolder.cvItogo));

                viewHolder.cvKs.setTitleText(pointCount(model.getArchive(), Constants.header.ks, false));
                viewHolder.cvKs.setOnClickListener(view -> showDialog("Культурное состояние локомотива", itemRef, model, KS, viewHolder.cvItogo));

                viewHolder.cvTz.setTitleText(pointCount(model.getArchive(), Constants.header.tz, false));
                viewHolder.cvTz.setOnClickListener(view -> showDialog("Посещение технических занятий", itemRef, model, TZ, viewHolder.cvItogo));

                viewHolder.cvRl.setTitleText(pointCount(model.getArchive(), Constants.header.rl, false));
                viewHolder.cvRl.setOnClickListener(view -> showDialog("Расшифровка лент", itemRef, model, RL, viewHolder.cvItogo));

                viewHolder.cvOt.setTitleText(pointCount(model.getArchive(), Constants.header.ot, false));
                viewHolder.cvOt.setOnClickListener(view -> showDialog("Охрана труда", itemRef, model, OT, viewHolder.cvItogo));

                viewHolder.cvOtk.setTitleText(pointCount(model.getArchive(), Constants.header.oz, false));
                viewHolder.cvOtk.setOnClickListener(view -> showDialog("Отказы", itemRef, model, OTK, viewHolder.cvItogo));

                viewHolder.cvItogo.setTitleText(pointCount(model.getArchive(), null, true));
                viewHolder.cvItogo.setOnClickListener(view -> setSelected(true, true, viewHolder));

            }
        };

        rv.setAdapter(adapter);

    }

    public static class MachinistsViewHolder2 extends RecyclerView.ViewHolder {

        SwipeLayout sl;

        RelativeLayout rlDataContainer;

        TextView tvPosition;
        TextView tvName;
        CircleView cvTo;
        CircleView cvKs;
        CircleView cvTz;
        CircleView cvRl;
        CircleView cvOt;
        CircleView cvOtk;
        CircleView cvItogo;

        CircleImageView cvRemove;
        CircleImageView cvArchive;

        public MachinistsViewHolder2(View itemView) {
            super(itemView);

            rlDataContainer = (RelativeLayout)itemView.findViewById(R.id.rlDataContainer);

            sl = (SwipeLayout) itemView.findViewById(R.id.sl);
            sl.setShowMode(SwipeLayout.ShowMode.LayDown);
            sl.addDrag(SwipeLayout.DragEdge.Left, itemView.findViewById(R.id.bottom_wrapper));

            tvPosition = (TextView) itemView.findViewById(R.id.tvPosition);
            tvName = (TextView) itemView.findViewById(R.id.tvName);

            cvTo = (CircleView) itemView.findViewById(R.id.cvTo);
            cvKs = (CircleView) itemView.findViewById(R.id.cvKs);
            cvTz = (CircleView) itemView.findViewById(R.id.cvTz);
            cvRl = (CircleView) itemView.findViewById(R.id.cvRl);
            cvOt = (CircleView) itemView.findViewById(R.id.cvOt);
            cvOtk = (CircleView) itemView.findViewById(R.id.cvOtk);
            cvItogo = (CircleView) itemView.findViewById(R.id.cvItogo);

            cvRemove = (CircleImageView) itemView.findViewById(R.id.cvRemove);
            cvArchive = (CircleImageView) itemView.findViewById(R.id.cvArchive);
        }
    }
}
</code>```

As a result, I see the list. But I can not call the setText () method on TextView. Because populateViewHolder is never called.
Where did I make a mistake?

答:
i guess you need to call populateViewHolder from onBindViewHolder like this

```<code>@Override
public void onBindViewHolder(MachinistsViewHolder2 viewHolder, int position) {
        Machinist model = getItem(position);

       populateViewHolder(viewHolder, model, position);

}
</code>```

ref here.

Body:
activity layout :

android:layout_height="match_parent"

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/activity_list_tasks2"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_list_tasks"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

   ... something else...

    </RelativeLayout>

activity class :

rv.setHasFixedSize(true);

public class AdminActivity2 extends AppCompatActivity {

    RecyclerView rv;

    private DatabaseReference myRef;

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.admin_activity);

        rv = (RecyclerView) findViewById(R.id.rv_list_tasks);

        myRef = FirebaseDatabase.getInstance().getReference();

        FirebaseRecyclerAdapter<Machinist, AdminActivity2.MachinistsViewHolder2> adapter;
        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        rv.setLayoutManager(llm);
        rv.setHasFixedSize(true);
        rv.post(this::supportStartPostponedEnterTransition);
        Query query = myRef.child("Машинисты").orderByChild("points/itogo");

        adapter = new FirebaseRecyclerAdapter<Machinist, MachinistsViewHolder2>(
                Machinist.class,
                R.layout.machinist_item,
                MachinistsViewHolder2.class,
                query){

            @Override
            public void onBindViewHolder(MachinistsViewHolder2 viewHolder, int position) {

            }

            @Override
            protected void populateViewHolder(MachinistsViewHolder2 viewHolder, Machinist model, int position) {

                Log.d("djuyf", "populate");

                Typeface mTypeface;
                mTypeface = Typeface.create("sans-serif-regular", Typeface.NORMAL);

                DatabaseReference itemRef = getRef(position);

                viewHolder.cvRemove.setOnClickListener(view -> {
                    AlertDialog diaBox = askOption(itemRef);
                    diaBox.show();
                });
                viewHolder.cvArchive.setOnClickListener(view -> {
                    Intent startArchiveActivity = new Intent(AdminActivity2.this, Archive.class);
                    startArchiveActivity.putExtra("Name", viewHolder.tvName.getText().toString());
                    Gson gson = new Gson();
                    String myJson = gson.toJson(model);
                    startArchiveActivity.putExtra("myjson", myJson);
                    startActivity(startArchiveActivity);
                });

                viewHolder.tvPosition.setText(String.format(Locale.getDefault(), "%02d", position + 1));
                viewHolder.tvName.setText(model.getLastName() + " " + model.getFirstName().charAt(0) + model.getMiddleName().charAt(0));
                viewHolder.tvName.setTypeface(mTypeface);

                viewHolder.cvTo.setTitleText(pointCount(model.getArchive(), Constants.header.to, false));
                viewHolder.cvTo.setOnClickListener(view -> showDialog("Цикл ТО-1", itemRef, model, TO, viewHolder.cvItogo));

                viewHolder.cvKs.setTitleText(pointCount(model.getArchive(), Constants.header.ks, false));
                viewHolder.cvKs.setOnClickListener(view -> showDialog("Культурное состояние локомотива", itemRef, model, KS, viewHolder.cvItogo));

                viewHolder.cvTz.setTitleText(pointCount(model.getArchive(), Constants.header.tz, false));
                viewHolder.cvTz.setOnClickListener(view -> showDialog("Посещение технических занятий", itemRef, model, TZ, viewHolder.cvItogo));

                viewHolder.cvRl.setTitleText(pointCount(model.getArchive(), Constants.header.rl, false));
                viewHolder.cvRl.setOnClickListener(view -> showDialog("Расшифровка лент", itemRef, model, RL, viewHolder.cvItogo));

                viewHolder.cvOt.setTitleText(pointCount(model.getArchive(), Constants.header.ot, false));
                viewHolder.cvOt.setOnClickListener(view -> showDialog("Охрана труда", itemRef, model, OT, viewHolder.cvItogo));

                viewHolder.cvOtk.setTitleText(pointCount(model.getArchive(), Constants.header.oz, false));
                viewHolder.cvOtk.setOnClickListener(view -> showDialog("Отказы", itemRef, model, OTK, viewHolder.cvItogo));

                viewHolder.cvItogo.setTitleText(pointCount(model.getArchive(), null, true));
                viewHolder.cvItogo.setOnClickListener(view -> setSelected(true, true, viewHolder));

            }
        };

        rv.setAdapter(adapter);

    }

    public static class MachinistsViewHolder2 extends RecyclerView.ViewHolder {

        SwipeLayout sl;

        RelativeLayout rlDataContainer;

        TextView tvPosition;
        TextView tvName;
        CircleView cvTo;
        CircleView cvKs;
        CircleView cvTz;
        CircleView cvRl;
        CircleView cvOt;
        CircleView cvOtk;
        CircleView cvItogo;

        CircleImageView cvRemove;
        CircleImageView cvArchive;

        public MachinistsViewHolder2(View itemView) {
            super(itemView);

            rlDataContainer = (RelativeLayout)itemView.findViewById(R.id.rlDataContainer);

            sl = (SwipeLayout) itemView.findViewById(R.id.sl);
            sl.setShowMode(SwipeLayout.ShowMode.LayDown);
            sl.addDrag(SwipeLayout.DragEdge.Left, itemView.findViewById(R.id.bottom_wrapper));

            tvPosition = (TextView) itemView.findViewById(R.id.tvPosition);
            tvName = (TextView) itemView.findViewById(R.id.tvName);

            cvTo = (CircleView) itemView.findViewById(R.id.cvTo);
            cvKs = (CircleView) itemView.findViewById(R.id.cvKs);
            cvTz = (CircleView) itemView.findViewById(R.id.cvTz);
            cvRl = (CircleView) itemView.findViewById(R.id.cvRl);
            cvOt = (CircleView) itemView.findViewById(R.id.cvOt);
            cvOtk = (CircleView) itemView.findViewById(R.id.cvOtk);
            cvItogo = (CircleView) itemView.findViewById(R.id.cvItogo);

            cvRemove = (CircleImageView) itemView.findViewById(R.id.cvRemove);
            cvArchive = (CircleImageView) itemView.findViewById(R.id.cvArchive);
        }
    }
}

As a result, I see the list. But I can not call the setText () method on TextView. Because populateViewHolder is never called.
Where did I make a mistake?

Body:
i guess you need to call populateViewHolder from onBindViewHolder like this

@Override
public void onBindViewHolder(MachinistsViewHolder2 viewHolder, int position) {
        Machinist model = getItem(position);

       populateViewHolder(viewHolder, model, position);

}

ref here.


问:
Bootstrap-tabdrop fix for modals?
This question is based on the very useful bootstrap-tabdrop.js which doesn't appear to be actively supported by its creator: https://github.com/jschab/bootstrap-tabdrop.

How can I amend bootstrap-tabdrop to work inside modals? I thought I might need to call tabdrop('layout') when the modal loads but that doesn't work. Is there a change to the jQuery which anyone can recommend so that tabs stack nicely inside Bootstrap (3.2) modals?

答:
i know it's an old question, but i had to deal with this issue today and come up with this:

```<code>$('#propValsModal').on('shown.bs.modal', function() {
    $('.nav-pills').tabdrop({
        'text': '<i class="icon-align-justify"></i> Choose Something'
    })
})
</code>```

using the tabdrop "text" option you can at least instruct the user

Title: Bootstrap-tabdrop fix for modals?

Body:
i know it's an old question, but i had to deal with this issue today and come up with this:

$('#propValsModal').on('shown.bs.modal', function() {
    $('.nav-pills').tabdrop({
        'text': '<i class="icon-align-justify"></i> Choose Something'
    })
})

using the tabdrop "text" option you can at least instruct the user


问:
How to deal with .gcda and .gcno files in different directory by lcov & code coverage compare
I can generate .info files by lcov with .gcda files and .gcno files in the same directory, BUT how can I generate code coverage with .gcda files and .gcno files in defferent location?

For example,

/Users/swd/Library/Developer/Xcode/DerivedData/test1aaeyiowcssrymfbwtudrqqakuvr/Build/Intermediates/test1.build/Cov/test1.build/Objects-normal/x86_64/AppDelegate.gcno

/Volumes/Data/test1/test1/AppDelegate.gcda

I tried --add-tracefile but failed, and output 'lcov: ERROR: no valid records found in trace file'

My second question is whether lcov have some command to compare my old version coverage html to my new one, so that I can find the difference.

Any ideas? Thanks

答:
Well few things needs to be cleared first to avoid confusion for other people.

.gcno and .gcda are never generated on different location for a single object file. (At least that's what I know from my experience)

When a source file is compiled either by using an automated builder or by manual commands, it generates .gcno files and .o files at the same location. And afterwards when you perform any kind of execution the object files trigger coverage generation functions and generate .gcda files at the same location as '.gcno' and object files.

And if they are generated for different .gcno files then they can not be used together anyway.


问:
AES encryption, InvalidKeyException: Unsupported key size: 6 bytes?
I am trying to encrypt a string as follows

```<code>public class AES256Cipher {
static byte[] ivBytes = new byte[]{0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76};
static String EncryptionKey = "abc123";

public static byte[] encrypt(String plainText)
        throws java.io.UnsupportedEncodingException,
        NoSuchAlgorithmException,
        NoSuchPaddingException,
        InvalidKeyException,
        InvalidAlgorithmParameterException,
        IllegalBlockSizeException,
        BadPaddingException {
    byte[] keyBytes = EncryptionKey.getBytes("UTF-8");

    AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
    Cipher cipher = null;
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
    byte[] cipherData = cipher.doFinal(plainText.getBytes("UTF-8"));
    Log.e("cipher", Base64.encodeToString(cipherData, Base64.DEFAULT));
    return cipher.doFinal(plainText.getBytes("UTF-8"));
}
}
</code>```

I am getting this exception

```<code>java.security.InvalidKeyException: Unsupported key size: 6 bytes
at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER$AES.checkSupportedKeySize(OpenSSLCipher.java:686)
at com.android.org.conscrypt.OpenSSLCipher.checkAndSetEncodedKey(OpenSSLCipher.java:442)
at com.android.org.conscrypt.OpenSSLCipher.engineInit(OpenSSLCipher.java:272)
at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:608)
at javax.crypto.Cipher.tryCombinations(Cipher.java:532)
at javax.crypto.Cipher.getSpi(Cipher.java:437)
at javax.crypto.Cipher.init(Cipher.java:909)
at javax.crypto.Cipher.init(Cipher.java:859)
at com.vfirst.util.netwrok.AES256Cipher.encrypt(AES256Cipher.java:36)
at com.vfirst.LoginActivity.onCreate(LoginActivity.java:61)
at android.app.Activity.performCreate(Activity.java:6321)
</code>```

String to encrypt

```<code>AES256Cipher.encrypt("12345");
</code>```

答:
AES only supports key sizes of 16, 24 or 32 bytes... So you have to change your EncryptionKey.

```<code>SecureRandom random = new SecureRandom();
byte[] EncryptionKey = new byte[16];
random.nextBytes(EncryptionKey);
</code>```

You can use above code sample.

Body:
I am trying to encrypt a string as follows

public class AES256Cipher {
static byte[] ivBytes = new byte[]{0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76};
static String EncryptionKey = "abc123";

public static byte[] encrypt(String plainText)
        throws java.io.UnsupportedEncodingException,
        NoSuchAlgorithmException,
        NoSuchPaddingException,
        InvalidKeyException,
        InvalidAlgorithmParameterException,
        IllegalBlockSizeException,
        BadPaddingException {
    byte[] keyBytes = EncryptionKey.getBytes("UTF-8");

    AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
    Cipher cipher = null;
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
    byte[] cipherData = cipher.doFinal(plainText.getBytes("UTF-8"));
    Log.e("cipher", Base64.encodeToString(cipherData, Base64.DEFAULT));
    return cipher.doFinal(plainText.getBytes("UTF-8"));
}
}

I am getting this exception

java.security.InvalidKeyException: Unsupported key size: 6 bytes
at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER$AES.checkSupportedKeySize(OpenSSLCipher.java:686)
at com.android.org.conscrypt.OpenSSLCipher.checkAndSetEncodedKey(OpenSSLCipher.java:442)
at com.android.org.conscrypt.OpenSSLCipher.engineInit(OpenSSLCipher.java:272)
at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:608)
at javax.crypto.Cipher.tryCombinations(Cipher.java:532)
at javax.crypto.Cipher.getSpi(Cipher.java:437)
at javax.crypto.Cipher.init(Cipher.java:909)
at javax.crypto.Cipher.init(Cipher.java:859)
at com.vfirst.util.netwrok.AES256Cipher.encrypt(AES256Cipher.java:36)
at com.vfirst.LoginActivity.onCreate(LoginActivity.java:61)
at android.app.Activity.performCreate(Activity.java:6321)

String to encrypt

AES256Cipher.encrypt("12345");

Body:
AES only supports key sizes of 16, 24 or 32 bytes... So you have to change your EncryptionKey.

SecureRandom random = new SecureRandom();
byte[] EncryptionKey = new byte[16];
random.nextBytes(EncryptionKey);

You can use above code sample.


问:
Angular2 click event not working
I'm facing an issue with an angular2 click event, it's not launching a simple console.log or an alert.

Here I post my component template:

```<code><div class="col-md-4">
<div *ngFor="let phone of phones">
{{phone.text}}
</div>
<input class="form-control" type="text" [(ngModel)]="phone"/>
<button class="btn btn-primary" (click)="console.log('clicked');" type="button">Call</button>
</div>
</code>```

When I click the button, there is nothing in the console.

I tried to execute a component function, with no luck as well.

I'm doing it the same way than here:
http://learnangular2.com/events/

Do you guys need more files? I just don't understand why this is not working

Thank you so much,
Daniel

Edit:

Ok so now I'm doing it like this:

Template:

```<code><div class="col-md-4">
<div *ngFor="let phone of phones">
    {{phone.text}}
</div>
<input class="form-control" type="text" [(ngModel)]="phone"/>
<button class="btn btn-primary" (click)="callPhone();" type="button">Call</button>
</div>
</code>```

And my ts file component:

```<code>import {Component, OnInit, OnDestroy} from '@angular/core';
import {FormControl} from '@angular/forms';
import {CallService} from '../call.service';

@Component({
moduleId: module.id,
selector: 'app-call-formular',
templateUrl: './call-formular.component.html',
styleUrls: ['./call-formular.component.css'],
providers: [CallService]
})
export class CallFormularComponent implements OnInit, OnDestroy {

phones = [];
connection;
phone;

constructor(private callService: CallService) {
}

callPhone(): any {
    console.log('callPhone executed.');
}

ngOnInit() {
    this.connection = this.callService.getPhones().subscribe(phone =>
{
        this.phones.push(phone);
    });
}

ngOnDestroy() {
    this.connection.unsubscribe();
}

}
</code>```

And still not launching my click event

答:
So yeah, at the end the "solution" was really stupid...

I've used what @Sajeetharan Told me, but the "problem" was that chrome was keeping the cache somehow, even flushing them with Ctr + shift + R.

At some point i deleted the cache from chrome and it worked.

Thank you all!

Edit:

So i explain here how I did it:

I just added some configurations to the virtualhost, so i don't need to use the incognitus mode of chrome, and what I added is:

```<code># DISABLE ALL CACHING WHILE DEVELOPING
<FilesMatch "\.(html|htm|js|css|json)$">
FileETag None

<IfModule mod_headers.c>
  Header unset ETag
  Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
  Header set Pragma "no-cache"
  Header set Note "CACHING IS DISABLED ON LOCALHOST"
  Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</IfModule>
</code>```

Again, thanks to all!

Title: Angular2 click event not working

Body:
I'm facing an issue with an angular2 click event, it's not launching a simple console.log or an alert.

Here I post my component template:

{{phone.text}}

<input class="form-control" type="text" [(ngModel)]="phone"/>
<button class="btn btn-primary" (click)="console.log('clicked');" type="button">Call</button>

When I click the button, there is nothing in the console.

I tried to execute a component function, with no luck as well.

I'm doing it the same way than here:
http://learnangular2.com/events/

Do you guys need more files? I just don't understand why this is not working

Thank you so much,
Daniel

Edit:

Ok so now I'm doing it like this:

Template:

    {{phone.text}}

<input class="form-control" type="text" [(ngModel)]="phone"/>
<button class="btn btn-primary" (click)="callPhone();" type="button">Call</button>

And my ts file component:

import {Component, OnInit, OnDestroy} from '@angular/core';
import {FormControl} from '@angular/forms';
import {CallService} from '../call.service';

@Component({
moduleId: module.id,
selector: 'app-call-formular',
templateUrl: './call-formular.component.html',
styleUrls: ['./call-formular.component.css'],
providers: [CallService]
})
export class CallFormularComponent implements OnInit, OnDestroy {

phones = [];
connection;
phone;

constructor(private callService: CallService) {
}

callPhone(): any {
    console.log('callPhone executed.');
}

ngOnInit() {
    this.connection = this.callService.getPhones().subscribe(phone =>
{
        this.phones.push(phone);
    });
}

ngOnDestroy() {
    this.connection.unsubscribe();
}

}

And still not launching my click event

Body:
So yeah, at the end the "solution" was really stupid...

I've used what @Sajeetharan Told me, but the "problem" was that chrome was keeping the cache somehow, even flushing them with Ctr + shift + R.

At some point i deleted the cache from chrome and it worked.

Thank you all!

Edit:

So i explain here how I did it:

I just added some configurations to the virtualhost, so i don't need to use the incognitus mode of chrome, and what I added is:

# DISABLE ALL CACHING WHILE DEVELOPING
<FilesMatch "\.(html|htm|js|css|json)$">
FileETag None

<IfModule mod_headers.c>
  Header unset ETag
  Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
  Header set Pragma "no-cache"
  Header set Note "CACHING IS DISABLED ON LOCALHOST"
  Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</IfModule>

Again, thanks to all!


问:
Java: Subtract '0' from char to get an int... why does this work?
This works fine:

```<code>int foo = bar.charAt(1) - '0';
</code>```

Yet this doesn't - because bar.charAt(x) returns a char:

```<code>int foo = bar.charAt(1);
</code>```

It seems that subtracting '0' from the char is casting it to an integer.

Why, or how,  does subtracting the string '0' (or is it a char?) convert another char in to an integer?

答:
Because in Java if you do not specify a type indicator with a number then it assumes Integer.
What I mean by that, if you want to set a Long value, it would need to be 0L.

Performing a numerical operation on two different numerics, the result takes the larger. Hence, a char (which is a numerical value) minus an integer, results in an integer.

You will find that this works also

```<code>long val = bar.charAt(1) - 0L;
</code>```

Body:
This works fine:

int foo = bar.charAt(1) - '0';

Yet this doesn't - because bar.charAt(x) returns a char:

int foo = bar.charAt(1);

It seems that subtracting '0' from the char is casting it to an integer.

Why, or how,  does subtracting the string '0' (or is it a char?) convert another char in to an integer?

Body:
Because in Java if you do not specify a type indicator with a number then it assumes Integer.
What I mean by that, if you want to set a Long value, it would need to be 0L.

Performing a numerical operation on two different numerics, the result takes the larger. Hence, a char (which is a numerical value) minus an integer, results in an integer.

You will find that this works also

long val = bar.charAt(1) - 0L;


问:
Jersey difference in time waiting for response first time vs. second time
I am using a Tomcat on which I have deployed a Jersey application.
On a certain REST URL it returns a fixed PNG image.
Prior to requesting the image, I have to initialize the application by providing the base path of the location of the image on the file system. This is done by performing a POST to a different URL after which the location is stored in an object in the context.

Using the network function of Firefox I can see a difference in the time the browser is waiting for the response the first time versus the second time.

Second request waiting network time = 9 ms

Second request waiting network time = 4 ms

I have executed this experiment several times and the first time always seems to take several milliseconds longer than the second or third time.

What is causing this difference?

FYI:

header Cache-control = "no-cache"

答:
If you have deployed your jersery Container as servlet . Than for each Resource
a separate servlet is created to which the request is delegated . So first time when you request for the resource with url . The servlet has to be created . Second time the already existing servlet is used  . That is why there is response delay</p>


问:
Split and remove particular value in href attribute and add new value using jquery
I have splitted the value in href attribute of a tag.

i splitted the value but i cannot remove the values and append new into it.

My HTML code is

```<code><a class="chapter_video" href="http://localhost/SVE128-portal2/public/video/9/25"></a>
</code>```

And my jquery is

```<code> var new = 4;
 var video_url = $('.chapter_video');
 var href = video_url.attr("href");
 //splitting value of href
 var split = href.split("/");
 if(split[7] !== undefined){
     href.remove(split[7]);
 }

 video_url.attr('href', video_url.attr('href') + '/'+ new);
</code>```

I have tried

```<code> var remove = href.replace('split[7]', '')
</code>```

instead of href.remove(split[7]);

答:
Don't use new keyword for variable names

Where is no remove function for string.(use replace('val','') for remove)

```<code>var _new = 4;
var video_url = $('.chapter_video');
var href = video_url.attr("href").toString();
//splitting value of href
var split = href.split("/");
console.log(split);
if(split[7] !== undefined){
     href.replace(split[7],'');
}

video_url.attr('href', video_url.attr('href') + '/'+ _new);
console.log(video_url.attr('href') + '/'+ _new);
</code>```

Body:
I have splitted the value in href attribute of a tag.

i splitted the value but i cannot remove the values and append new into it.

My HTML code is

And my jquery is

 var new = 4;
 var video_url = $('.chapter_video');
 var href = video_url.attr("href");
 //splitting value of href
 var split = href.split("/");
 if(split[7] !== undefined){
     href.remove(split[7]);
 }

 video_url.attr('href', video_url.attr('href') + '/'+ new);

I have tried

 var remove = href.replace('split[7]', '')

instead of href.remove(split[7]);

Body:
Don't use new keyword for variable names

Where is no remove function for string.(use replace('val','') for remove)

var _new = 4;
var video_url = $('.chapter_video');
var href = video_url.attr("href").toString();
//splitting value of href
var split = href.split("/");
console.log(split);
if(split[7] !== undefined){
     href.replace(split[7],'');
}

video_url.attr('href', video_url.attr('href') + '/'+ _new);
console.log(video_url.attr('href') + '/'+ _new);