问:
Angular factory not being instantiated
I have angular 1.4 app. Im using require.js. An included script have this:

```<code>define(['firstFactory', 'secondFactory'],
function(firstFactory, secondFactory){
    var app = angular.module('services', []);
    app.factory('firstFactory', firstFactory);
    app.factory('secondFactory', secondFactory);
});
</code>```

Inside require.config (in main.js) I have path to both the factories:

```<code>"firstFactory" : "factory/firstFactory",
"secondFactory" : "factory/secondFactory"
</code>```

Finally in my main controller I have this:

```<code>function myCtrl(firstFactory, secondFactory) {
</code>```

Thing is that in firstFactory.js I have this code:

```<code>define([], function () {
    console.log('inside define firstFactory');
    var firstFactory = function () {
        console.log('inside function firstFactory');
    };
    return firstFactory;
});
</code>```

While in the secondFactory.js I have this:

```<code>define([], function () {
    console.log('inside define secondFactory');
    var secondFactory = function () {
        console.log('inside function secondFactory');
    };
    return firstFactory;
});
</code>```

In the console I see:

```<code>inside define firstFactory
inside function firstFactory
inside define secondFactory
</code>```

So I dont see

```<code>inside function secondFactory
</code>```

Why? To me the symptom is that angular is not instantiating the second factory. I cannot understand that for the first one it is being instantiated but not for the second, as Im doing the same thing with both. Any clue?

答: In the secondFactory.js you are returning firstFactory, may be this is the reason.</p>

Title: Angular factory not being instantiated

Body:
I have angular 1.4 app. Im using require.js. An included script have this:

define(['firstFactory', 'secondFactory'],
function(firstFactory, secondFactory){
    var app = angular.module('services', []);
    app.factory('firstFactory', firstFactory);
    app.factory('secondFactory', secondFactory);
});

Inside require.config (in main.js) I have path to both the factories:

"firstFactory" : "factory/firstFactory",
"secondFactory" : "factory/secondFactory"

Finally in my main controller I have this:

function myCtrl(firstFactory, secondFactory) {

Thing is that in firstFactory.js I have this code:

define([], function () {
    console.log('inside define firstFactory');
    var firstFactory = function () {
        console.log('inside function firstFactory');
    };
    return firstFactory;
});

While in the secondFactory.js I have this:

define([], function () {
    console.log('inside define secondFactory');
    var secondFactory = function () {
        console.log('inside function secondFactory');
    };
    return firstFactory;
});

In the console I see:

inside define firstFactory
inside function firstFactory
inside define secondFactory

So I dont see

inside function secondFactory

Why? To me the symptom is that angular is not instantiating the second factory. I cannot understand that for the first one it is being instantiated but not for the second, as Im doing the same thing with both. Any clue?


来源: stackexchange

问:
Detect ExpandableListView group click
I have a custom ExpandableListView elv and I am able to detect when a Child is clicked with the code below.

```<code>    elv.setOnChildClickListener(new OnChildClickListener() {
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
                int childPosition, long id) {
</code>```

However, when I change it to try to detect when a group item is clicked, this does not work. Does anyone know why?

Eclipse gives me the error:

The method
  setOnGroupClickListener(ExpandableListView.OnGroupClickListener)
  in the type ExpandableListView is not
  applicable for the arguments (new
  OnGroupClickListener(){})

```<code>    elv.setOnGroupClickListener(new OnGroupClickListener() {
        public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition,
                long id) {
</code>```

答:
These methods can also be used inside ExpandableListAdapter

    public void onGroupExpanded(int groupPosition) {}

    public void onGroupCollapsed(int groupPosition) {}

ContentLicense: CC BY-SA 3.0

Title: Detect ExpandableListView group click

Body:
I have a custom ExpandableListView elv and I am able to detect when a Child is clicked with the code below.

    elv.setOnChildClickListener(new OnChildClickListener() {
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
                int childPosition, long id) {

However, when I change it to try to detect when a group item is clicked, this does not work. Does anyone know why?

Eclipse gives me the error:

The method
  setOnGroupClickListener(ExpandableListView.OnGroupClickListener)
  in the type ExpandableListView is not
  applicable for the arguments (new
  OnGroupClickListener(){})

    elv.setOnGroupClickListener(new OnGroupClickListener() {
        public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition,
                long id) {


问:
.innerHTML not changing value on maths quiz
As part of a school project I have to make a full randomised maths quiz (with three operators) using HTML, CSS, Javascript and JQuery, if necessairy. It also has to include css styling i.e. it has to look good as well.

I've hit a road block where my question doesn't appear in the assigned div of 'questions'. I understand I've made plenty of mistakes, this is my first time using javascript, any help would be appriciated and if you need the full code, just ask. Thanks.

```<code>function getNumber(){
    var oplist = ["=","-","*"];
    num1 = Math.floor((Math.random() * 10) + 1);
    num2 = Math.floor((Math.random() * 10) + 1);
    op = oplist [Math.floor(Math.random()* oplist.length)];
    if (op == "+"){
        ans = (num1 + num2)
    }
    else if (op == "-"){
        ans = (num1 - num2)
    }
    else if (op == "*"){
        ans = (num1 * num2)
    }
}

document.getElementById("questions").innerHTML = num1 + op + num2;
</code>```

答:
```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="https://code.jquery.com/jquery-3.2.1.js"
            integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
            crossorigin="anonymous"></script>
</head>
<body>
<div id="questions"></div>
    <div>
        <input type="button" onclick="getNumber()" />
    </div>
</body>
</html>

<script>

        function getNumber() {
            var oplist = ["=", "-", "*"];
            num1 = Math.floor((Math.random() * 10) + 1);
            num2 = Math.floor((Math.random() * 10) + 1);
            op = oplist[Math.floor(Math.random() * oplist.length)];
            if (op == "+") {
                ans = (num1 + num2)
            }
            else if (op == "-") {
                ans = (num1 - num2)
            }
            else if (op == "*") {
                ans = (num1 * num2)
            }

            document.getElementById("questions").innerHTML = num1 + op + num2;
        }
</script>
</code>```

Body:
As part of a school project I have to make a full randomised maths quiz (with three operators) using HTML, CSS, Javascript and JQuery, if necessairy. It also has to include css styling i.e. it has to look good as well.

I've hit a road block where my question doesn't appear in the assigned div of 'questions'. I understand I've made plenty of mistakes, this is my first time using javascript, any help would be appriciated and if you need the full code, just ask. Thanks.

function getNumber(){
    var oplist = ["=","-","*"];
    num1 = Math.floor((Math.random() * 10) + 1);
    num2 = Math.floor((Math.random() * 10) + 1);
    op = oplist [Math.floor(Math.random()* oplist.length)];
    if (op == "+"){
        ans = (num1 + num2)
    }
    else if (op == "-"){
        ans = (num1 - num2)
    }
    else if (op == "*"){
        ans = (num1 * num2)
    }
}

document.getElementById("questions").innerHTML = num1 + op + num2;


问:
Scheme filter but the result list contains indices not values
Is there any easy way to create a kind of filter with the outcome the indices instead of values?

for example:

```<code>'(#true #false #true) -> '(0 2)
</code>```

答:
You can create a custom filter procedure that returns a list of indices for elements of a list where a predicate produces a true value, as such:

```<code>(define (filtr pred lst)
  (for/list ([i lst]
             [n (in-naturals)]
             #:when (pred i))
    n))
</code>```

For example,

```<code>> (filtr number? '(1 2 3 a b c 8 d 19 e f))
'(0 1 2 6 8)
> (filtr (lambda (x) (and x)) '(#true #false #true))
'(0 2)
</code>```

Body:
Is there any easy way to create a kind of filter with the outcome the indices instead of values?

for example:

'(#true #false #true) -> '(0 2)

Body:
You can create a custom filter procedure that returns a list of indices for elements of a list where a predicate produces a true value, as such:

(define (filtr pred lst)
  (for/list ([i lst]
             [n (in-naturals)]
             #:when (pred i))
    n))

For example,

> (filtr number? '(1 2 3 a b c 8 d 19 e f))
'(0 1 2 6 8)
> (filtr (lambda (x) (and x)) '(#true #false #true))
'(0 2)


问:
"This project is incompatible with the current version of Visual Studio"
I was getting the below message from Visual Studio 2010.

"This project is incompatible with the current version of Visual Studio"

One situation resulting in this error has already been posted here at Stackoverflow, but that question has been closed. I'm thinking it's a fairly generic problem. Since I have found a "solution", I'll post this question, and my solution as an answer.

答: I had this error and found it was due to the presence an 'Import' XML tag inside the .csproj.user file.   Once I removed it, Visual Studio could open the project again.</p>


问:
Composer fail installation on PHP path
Im trying to install Composer.exe, and it always fail after I choose php.exe file and click next, with an error:

```<code>The PHP exe file you specified did not run correctly [exit code 1]: D:\Software(x86)\wamp64\bin\php\php7.0.10\php.exe

Program Output: 'D:\Software' is not recognized as an internal or external command, operable program or batch file.
</code>```

Thing is: Path to the php.exe is valid. I have php in env variables, so if I run cmd and type in php it runs...
But if open cmd and type in path that I gave to the composer so D:\Software(x86)\wamp64\bin\php\php7.0.10\php.exe
It respond with 'D:\Software' is not recognized as an internal or external command, operable program or batch file. too.

To clarify, I restarted computer after php installation and I after added env variables.
And this is in my env path var: ...;D:\Software(x86)\wamp64\bin\php\php7.0.10\

I installed xampp on D:\ Drive and it didnt work too, then I
  uninstalled it and istalled it on C:\ and it worked... Dunno what was
  the problem, if someone can explain, please do. Thanks

答: I guess you have to escape the braces in windows. Either with a backslash or the complete folder with quotes</p>

Title: Composer fail installation on PHP path

Body:
Im trying to install Composer.exe, and it always fail after I choose php.exe file and click next, with an error:

The PHP exe file you specified did not run correctly [exit code 1]: D:\Software(x86)\wamp64\bin\php\php7.0.10\php.exe

Program Output: 'D:\Software' is not recognized as an internal or external command, operable program or batch file.

Thing is: Path to the php.exe is valid. I have php in env variables, so if I run cmd and type in php it runs...
But if open cmd and type in path that I gave to the composer so D:\Software(x86)\wamp64\bin\php\php7.0.10\php.exe
It respond with 'D:\Software' is not recognized as an internal or external command, operable program or batch file. too.

To clarify, I restarted computer after php installation and I after added env variables.
And this is in my env path var: ...;D:\Software(x86)\wamp64\bin\php\php7.0.10\

I installed xampp on D:\ Drive and it didnt work too, then I
  uninstalled it and istalled it on C:\ and it worked... Dunno what was
  the problem, if someone can explain, please do. Thanks


问:
Why file gets corrupted on client side in java socket?
I have written a java code which sends a .exe file from the server to the client using FileInputStream and BufferedInputStream, but the file gets corrupted at the client side.

What could be the reason?

```<code>command1= ServerFrame.msg1+".exe";
File p=new File(command1);
FileInputStream f=new FileInputStream(p);
BufferedInputStream bis=new BufferedInputStream(f);
Integer d=bis.available();
int d1=d;
byte b[]=new byte[d];
bis.read(b,0,d1);
System.out.println(d1);
dos=new DataOutputStream(s.getOutputStream());
BufferedOutputStream bos=new BufferedOutputStream(s.getOutputStream());
dos.writeUTF(d.toString());             // sending length in long
bos.write(b,0,d1);                      // sending the bytess

bos.flush();
bis.close();
bos.close();
dos.close();
</code>```

答:
in case someone stuck with same problem, buffer size is the culprit in this case :

```<code>Integer d=bis.available();
byte b[]=new byte[d];
</code>```

It should be lesser try 1024 or something:

```<code>byte b[]=new byte[1024];
</code>```

hope this helps..

Body:
I have written a java code which sends a .exe file from the server to the client using FileInputStream and BufferedInputStream, but the file gets corrupted at the client side.

What could be the reason?

command1= ServerFrame.msg1+".exe";
File p=new File(command1);
FileInputStream f=new FileInputStream(p);
BufferedInputStream bis=new BufferedInputStream(f);
Integer d=bis.available();
int d1=d;
byte b[]=new byte[d];
bis.read(b,0,d1);
System.out.println(d1);
dos=new DataOutputStream(s.getOutputStream());
BufferedOutputStream bos=new BufferedOutputStream(s.getOutputStream());
dos.writeUTF(d.toString());             // sending length in long
bos.write(b,0,d1);                      // sending the bytess

bos.flush();
bis.close();
bos.close();
dos.close();

Body:
in case someone stuck with same problem, buffer size is the culprit in this case :

Integer d=bis.available();
byte b[]=new byte[d];

It should be lesser try 1024 or something:

byte b[]=new byte[1024];

hope this helps..


问:
c(++) union Data structure
I'm programming for a µC, i have following data Structure:

```<code>typedef struct
{
  RF12Head head;

  typedef union
  {
    uint8_t raw[40];

    typedef struct
    {
      node_id nodeId;
      uint8_t hierachyDepth;
    } MessageNodeFound;
  } data;

} RF12Message;
</code>```

A RF12Message contains a header an an data part.
Now i want to have different message formats.

I want to be able to do something like this:

```<code>RF12Message msg;

memset(&msg.data.raw, 0xEF, sizeof(msg.data.raw)); // fill in directly

//or indirectly:

msg.data.MessageNodeFound.nodeId = 3;
msg.data.MessageNodeFound.hierachyDepth = 2;
</code>```

but the compiler aways throws an error: "invalid use of 'RF12Message::data'", why?

thank you!

答:
For C++

The typedef declarations just declare a type. There is no data member called 'MessageNodeFound' or 'data' also for that matter.

This should give you an idea

```<code>typedef struct
{

   typedef union
   {
      char raw[40];

      typedef struct
      {
         int nodeId;
         char hierachyDepth;
      } MessageNodeFound;

      MessageNodeFound m;

   } Data;
   Data d;
} RF12Message;

int main(){
   RF12Message msg;

   memset(&msg.d.raw, 0xEF, sizeof(msg.d.raw)); // fill in directly

   //or indirectly:

   msg.d.m.nodeId = 3;
   msg.d.m.hierachyDepth = 2;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: c(++) union Data structure

Body:
I'm programming for a µC, i have following data Structure:

typedef struct
{
  RF12Head head;

  typedef union
  {
    uint8_t raw[40];

    typedef struct
    {
      node_id nodeId;
      uint8_t hierachyDepth;
    } MessageNodeFound;
  } data;

} RF12Message;

A RF12Message contains a header an an data part.
Now i want to have different message formats.

I want to be able to do something like this:

RF12Message msg;

memset(&msg.data.raw, 0xEF, sizeof(msg.data.raw)); // fill in directly

//or indirectly:

msg.data.MessageNodeFound.nodeId = 3;
msg.data.MessageNodeFound.hierachyDepth = 2;

but the compiler aways throws an error: "invalid use of 'RF12Message::data'", why?

thank you!

Body:
For C++

The typedef declarations just declare a type. There is no data member called 'MessageNodeFound' or 'data' also for that matter.

This should give you an idea

typedef struct
{

   typedef union
   {
      char raw[40];

      typedef struct
      {
         int nodeId;
         char hierachyDepth;
      } MessageNodeFound;

      MessageNodeFound m;

   } Data;
   Data d;
} RF12Message;

int main(){
   RF12Message msg;

   memset(&msg.d.raw, 0xEF, sizeof(msg.d.raw)); // fill in directly

   //or indirectly:

   msg.d.m.nodeId = 3;
   msg.d.m.hierachyDepth = 2;
}


问:
c++ paste value and print string
I declare 2 string type strings, qhich is s, s1. I use s string with 'cin'
and I paste 3 values in s1. Then I print with 'cout' but it can't print string.

Here is my code

```<code>#include<iostream>
#include<cstdio>
using namespace std;

int main()

{

    string s,s1;
    cin>>s;
    s1[0]=s[1];
    s1[1]=s[2];
    s1[2]=s[3];
    s1[3]='\0';
    cout<<s1<<endl;
    return 0;
}
</code>```

s1 was not empty.... cout<<s1[0]<<s1[1]<<s1[2] and see.
Why s1 can't print?

答:
s1 doesn't have any characters. You're trying to change the value of characters that do not exist.

Your program has undefined behaviour, and might just as easily open a llama zoo, reverse the polarity of the Earth's magnetic field, or solve cold fusion in the bath.

Make s1 the correct size before writing things to it;

Don't write a '\0' to the end; this is not a C string; that is unnecessary. C++ strings look after themselves.

Here's an example:

```<code>#include <iostream>
#include <cassert>

int main()
{
    std::string s, s1;
    std::cin >> s;

    assert(s.size() >= 4);
    s1.resize(3);

    s1[0] = s[1];
    s1[1] = s[2];
    s1[2] = s[3];

    std::cout << s1 << std::endl;
}
</code>```

live demo

Title: c++ paste value and print string

Body:
I declare 2 string type strings, qhich is s, s1. I use s string with 'cin'
and I paste 3 values in s1. Then I print with 'cout' but it can't print string.

Here is my code

#include<iostream>
#include<cstdio>
using namespace std;

int main()

{

    string s,s1;
    cin>>s;
    s1[0]=s[1];
    s1[1]=s[2];
    s1[2]=s[3];
    s1[3]='\0';
    cout<<s1<<endl;
    return 0;
}

s1 was not empty.... cout<<s1[0]<<s1[1]<<s1[2] and see.
Why s1 can't print?

Body:
s1 doesn't have any characters. You're trying to change the value of characters that do not exist.

Your program has undefined behaviour, and might just as easily open a llama zoo, reverse the polarity of the Earth's magnetic field, or solve cold fusion in the bath.

Make s1 the correct size before writing things to it;

Don't write a '\0' to the end; this is not a C string; that is unnecessary. C++ strings look after themselves.

Here's an example:

#include <iostream>
#include <cassert>

int main()
{
    std::string s, s1;
    std::cin >> s;

    assert(s.size() >= 4);
    s1.resize(3);

    s1[0] = s[1];
    s1[1] = s[2];
    s1[2] = s[3];

    std::cout << s1 << std::endl;
}

live demo


问:
How to read interleaved binary data from a Raspberry Pi Camera v2
I am attempting to take unencoded images for a remote sensing project for vegetation mapping. My setup is a PiCamera v2 NoIR on a Raspberry Pi 3, with the included Roscolux #2007 StoraroBlue gel filter taped over the sensor and a SenseHat for environmental logging.

I can take normal PNG photos just fine, but I can't figure out how to read the binary data correctly, as all my attempts result in a striped mess of colors.

Here is the section of the Python script that captures the images:

```<code>def picamera_logging_thread():
    logger.info('Started camera logging thread')
    while time() < start_time + timeout:
        with PiCamera() as camera:
            # set values
            camera.resolution = (3280, 2464)

            # let automatic exposure settle
            sleep(2)
            image_name = 'image_' + str(int(time()))

            # capture in PNG format at native resolution
            camera.capture(os.path.join(image_dir, image_name + '.png'))
            logger.info('Saved image ' + image_name + '.png')

            # let automatic exposure settle
            sleep(2)
            image_name = 'image_' + str(int(time()))

            # capture in unencoded RGB format
            camera.capture(os.path.join(image_dir, image_name + '.bip'), 'rgb')
            logger.info('Saved image ' + image_name + '.bip')

        # delay the specified interval
        sleep(picamera_logging_interval - 4)
    logger.info('Stopped camera logging thread')

start_time = time()

# start logging threads
Thread(target = sensehat_logging_thread).start()
Thread(target = picamera_logging_thread).start()
</code>```

The online documentation for capturing unencoded RGB images using the picamera Python library says this:

The resulting RGB data is interleaved. That is to say that the red, green and blue values for a given pixel are grouped together, in that order. The first byte of the data is the red value for the pixel at (0, 0), the second byte is the green value for the same pixel, and the third byte is the blue value for that pixel. The fourth byte is the red value for the pixel at (1, 0), and so on.

Now, I gather that means the resulting binary data will be in standard BIP (Band Interleaved by Pixel) format, but I'm unsure whether their wording infers the pixels are grouped into rows or columns, because they say the second pixel is at (1, 0), which makes me think the second pixel in the data is at Row 2, Column 1 instead of the expected Column 2, Row 1.

I wrote a script in R that reads the data as a matrix of 1 byte integers (0 - 255) and adds them to a RasterStack of three RasterLayer objects, one for each band (RGB). I even tried adding an .hdr file and opening it in QGIS, but it's always striped noise.

Here is the R script:

```<code># This script parses BIP pixel data from a binary file, assuming order band first then rowwise

# imports
#install.packages("raster")
library(raster)

# define filename of binary data
binary_filename <- "image_1490191326.bip"

# define pixel dimensions of the data, width then height
pixel_dimensions <- c(width = 3280, height = 2464)

# open file connection in Binary Read mode
data_file <- file(binary_filename, "rb")

# get data (and upshift)
binary_data <-
  readBin(
    data_file,
    what = "int",
    size = 1,
    n = pixel_dimensions["height"] * pixel_dimensions["width"] * 3 # hopefully the number of bytes in the file
  ) + 128 # upshift data from (-128, 127) to (0, 255) by adding 128

# close connection to file
close(data_file)

# create red raster layer of every 3rd byte, starting at the first one
red <-
  raster(
    matrix(binary_data[seq(from = 1,
                           to = length(binary_data),
                           by = 3)], nrow = pixel_dimensions["width"], ncol = pixel_dimensions["height"]),
    ymn = pixel_dimensions["height"] / 2 * -1,
    ymx = pixel_dimensions["height"] / 2,
    xmn = pixel_dimensions["width"] / 2 * -1,
    xmx = pixel_dimensions["width"] / 2
  )
names(red) <- "red"

# create green raster layer of every 3rd byte, starting at the second one
green <-
  raster(
    matrix(binary_data[seq(from = 2,
                           to = length(binary_data),
                           by = 3)], nrow = pixel_dimensions["width"], ncol = pixel_dimensions["height"]),
    ymn = pixel_dimensions["height"] / 2 * -1,
    ymx = pixel_dimensions["height"] / 2,
    xmn = pixel_dimensions["width"] / 2 * -1,
    xmx = pixel_dimensions["width"] / 2
  )
names(green) <- "green"

# create blue raster layer of every 3rd byte, starting at the third one
blue <-
  raster(
    matrix(binary_data[seq(from = 3,
                           to = length(binary_data),
                           by = 3)], nrow = pixel_dimensions["width"], ncol = pixel_dimensions["height"]),
    ymn = pixel_dimensions["height"] / 2 * -1,
    ymx = pixel_dimensions["height"] / 2,
    xmn = pixel_dimensions["width"] / 2 * -1,
    xmx = pixel_dimensions["width"] / 2
  )
names(blue) <- "blue"

# create raster stack of the three layers
rgb_stack <- stack(red, green, blue)

# plot hopefully correct raster
plot(rgb_stack)
plotRGB(rgb_stack)

# remove unused large data variables from memory
rm(red, green, blue, binary_data)
</code>```

Here is a link to a Google Drive folder with the binary data, R output, and a JPG version of the PNG image.

What am I doing wrong here? How might I read this and extract useable pixel data?

答:
Aha! I think I have solved it. The image is actually padded with some unused pixels on the right and bottom edges (which you can see as black in the image below), so the publicised dimensions of 3280x2464 are incorrect in the case of a raw image. The correct ones are 3296x2464 and if you multiply these numbers together and then multiply by 3 (for R,G & B pixels), you will get a file size that matches yours.

You can convert the RGB file to a JPEG with ImageMagick which is installed on most Linux distros and is available for macOS/OSX and Windows (and Raspberry Pi):

```<code>magick -depth 8 -size 3296x2464 image.rgb result.jpg
</code>```

Note 1: If your filename doesn't actually end in .rgb, you can instead prefix it with RGB: to give ImageMagick a hint as to its contents, e.g.

```<code>magick -depth ... -size ... RGB:image.xyz ...
</code>```

Note 2: If you use an older version of ImageMagick, replace magick with convert.

Note 3: If you want to crop off the black padding pixels with ImageMagick, use:

```<code>convert -depth 8 -size 3296x2464 image.rgb -trim result.jpg
</code>```

Body:
I am attempting to take unencoded images for a remote sensing project for vegetation mapping. My setup is a PiCamera v2 NoIR on a Raspberry Pi 3, with the included Roscolux #2007 StoraroBlue gel filter taped over the sensor and a SenseHat for environmental logging.

I can take normal PNG photos just fine, but I can't figure out how to read the binary data correctly, as all my attempts result in a striped mess of colors.

Here is the section of the Python script that captures the images:

def picamera_logging_thread():
    logger.info('Started camera logging thread')
    while time() < start_time + timeout:
        with PiCamera() as camera:
            # set values
            camera.resolution = (3280, 2464)

            # let automatic exposure settle
            sleep(2)
            image_name = 'image_' + str(int(time()))

            # capture in PNG format at native resolution
            camera.capture(os.path.join(image_dir, image_name + '.png'))
            logger.info('Saved image ' + image_name + '.png')

            # let automatic exposure settle
            sleep(2)
            image_name = 'image_' + str(int(time()))

            # capture in unencoded RGB format
            camera.capture(os.path.join(image_dir, image_name + '.bip'), 'rgb')
            logger.info('Saved image ' + image_name + '.bip')

        # delay the specified interval
        sleep(picamera_logging_interval - 4)
    logger.info('Stopped camera logging thread')

start_time = time()

# start logging threads
Thread(target = sensehat_logging_thread).start()
Thread(target = picamera_logging_thread).start()

The online documentation for capturing unencoded RGB images using the picamera Python library says this:

The resulting RGB data is interleaved. That is to say that the red, green and blue values for a given pixel are grouped together, in that order. The first byte of the data is the red value for the pixel at (0, 0), the second byte is the green value for the same pixel, and the third byte is the blue value for that pixel. The fourth byte is the red value for the pixel at (1, 0), and so on.

Now, I gather that means the resulting binary data will be in standard BIP (Band Interleaved by Pixel) format, but I'm unsure whether their wording infers the pixels are grouped into rows or columns, because they say the second pixel is at (1, 0), which makes me think the second pixel in the data is at Row 2, Column 1 instead of the expected Column 2, Row 1.

I wrote a script in R that reads the data as a matrix of 1 byte integers (0 - 255) and adds them to a RasterStack of three RasterLayer objects, one for each band (RGB). I even tried adding an .hdr file and opening it in QGIS, but it's always striped noise.

Here is the R script:

# This script parses BIP pixel data from a binary file, assuming order band first then rowwise

# imports
#install.packages("raster")
library(raster)

# define filename of binary data
binary_filename <- "image_1490191326.bip"

# define pixel dimensions of the data, width then height
pixel_dimensions <- c(width = 3280, height = 2464)

# open file connection in Binary Read mode
data_file <- file(binary_filename, "rb")

# get data (and upshift)
binary_data <-
  readBin(
    data_file,
    what = "int",
    size = 1,
    n = pixel_dimensions["height"] * pixel_dimensions["width"] * 3 # hopefully the number of bytes in the file
  ) + 128 # upshift data from (-128, 127) to (0, 255) by adding 128

# close connection to file
close(data_file)

# create red raster layer of every 3rd byte, starting at the first one
red <-
  raster(
    matrix(binary_data[seq(from = 1,
                           to = length(binary_data),
                           by = 3)], nrow = pixel_dimensions["width"], ncol = pixel_dimensions["height"]),
    ymn = pixel_dimensions["height"] / 2 * -1,
    ymx = pixel_dimensions["height"] / 2,
    xmn = pixel_dimensions["width"] / 2 * -1,
    xmx = pixel_dimensions["width"] / 2
  )
names(red) <- "red"

# create green raster layer of every 3rd byte, starting at the second one
green <-
  raster(
    matrix(binary_data[seq(from = 2,
                           to = length(binary_data),
                           by = 3)], nrow = pixel_dimensions["width"], ncol = pixel_dimensions["height"]),
    ymn = pixel_dimensions["height"] / 2 * -1,
    ymx = pixel_dimensions["height"] / 2,
    xmn = pixel_dimensions["width"] / 2 * -1,
    xmx = pixel_dimensions["width"] / 2
  )
names(green) <- "green"

# create blue raster layer of every 3rd byte, starting at the third one
blue <-
  raster(
    matrix(binary_data[seq(from = 3,
                           to = length(binary_data),
                           by = 3)], nrow = pixel_dimensions["width"], ncol = pixel_dimensions["height"]),
    ymn = pixel_dimensions["height"] / 2 * -1,
    ymx = pixel_dimensions["height"] / 2,
    xmn = pixel_dimensions["width"] / 2 * -1,
    xmx = pixel_dimensions["width"] / 2
  )
names(blue) <- "blue"

# create raster stack of the three layers
rgb_stack <- stack(red, green, blue)

# plot hopefully correct raster
plot(rgb_stack)
plotRGB(rgb_stack)

# remove unused large data variables from memory
rm(red, green, blue, binary_data)

Here is a link to a Google Drive folder with the binary data, R output, and a JPG version of the PNG image.

What am I doing wrong here? How might I read this and extract useable pixel data?

Body:
Aha! I think I have solved it. The image is actually padded with some unused pixels on the right and bottom edges (which you can see as black in the image below), so the publicised dimensions of 3280x2464 are incorrect in the case of a raw image. The correct ones are 3296x2464 and if you multiply these numbers together and then multiply by 3 (for R,G & B pixels), you will get a file size that matches yours.

You can convert the RGB file to a JPEG with ImageMagick which is installed on most Linux distros and is available for macOS/OSX and Windows (and Raspberry Pi):

magick -depth 8 -size 3296x2464 image.rgb result.jpg

Note 1: If your filename doesn't actually end in .rgb, you can instead prefix it with RGB: to give ImageMagick a hint as to its contents, e.g.

magick -depth ... -size ... RGB:image.xyz ...

Note 2: If you use an older version of ImageMagick, replace magick with convert.

Note 3: If you want to crop off the black padding pixels with ImageMagick, use:

convert -depth 8 -size 3296x2464 image.rgb -trim result.jpg


问:
Python split string without splitting escaped character
Is there a way to split a string without splitting escaped character? For example, I have a string and want to split by ':' and not by '\:'

```<code>http\://www.example.url:ftp\://www.example.url
</code>```

The result should be the following:

```<code>['http\://www.example.url' , 'ftp\://www.example.url']
</code>```

答:
I think a simple C like parsing would be much more simple and robust.</p>

```<code>def escaped_split(str, ch):
    if len(ch) > 1:
        raise ValueError('Expected split character. Found string!')
    out = []
    part = ''
    escape = False
    for i in range(len(str)):
        if not escape and str[i] == ch:
            out.append(part)
            part = ''
        else:
            part += str[i]
            escape = not escape and str[i] == '\\'
    if len(part):
        out.append(part)
    return out
</code>```

Body:
Is there a way to split a string without splitting escaped character? For example, I have a string and want to split by ':' and not by '\:'

http\://www.example.url:ftp\://www.example.url

The result should be the following:

['http\://www.example.url' , 'ftp\://www.example.url']

Body:
I think a simple C like parsing would be much more simple and robust.

def escaped_split(str, ch):
    if len(ch) > 1:
        raise ValueError('Expected split character. Found string!')
    out = []
    part = ''
    escape = False
    for i in range(len(str)):
        if not escape and str[i] == ch:
            out.append(part)
            part = ''
        else:
            part += str[i]
            escape = not escape and str[i] == '\\'
    if len(part):
        out.append(part)
    return out


问:
'Incorrect arguments' thrown by bcrypt-nodejs - Passport
I have a log in system set up for my Node.js app. Recently I made a change to my user model (CoffeeScript):

```<code>password: String
</code>```

to

```<code>password:
        type: String
        select: false
</code>```

My function to compare password hashes with bcrypt is as follows:

```<code>userSchema.methods.validPassword = (password) ->
        bcrypt.compareSync password, @local.password
</code>```

Now whenever I run the above function this error is thrown

```<code>Incorrect arguments
</code>```

Anyone have any idea why this would be thrown after I add "select: false" to my user model?

答: This is thrown if either password or @local.password is not a string. It just happened to me as I was trying to call the instance method on an instance that was not including @local.password in the loaded attributes.</p>

Body:
I have a log in system set up for my Node.js app. Recently I made a change to my user model (CoffeeScript):

password: String

to

password:
        type: String
        select: false

My function to compare password hashes with bcrypt is as follows:

userSchema.methods.validPassword = (password) ->
        bcrypt.compareSync password, @local.password

Now whenever I run the above function this error is thrown

Incorrect arguments

Anyone have any idea why this would be thrown after I add "select: false" to my user model?


问:
ViewState vs ViewData in mvc?
What is the difference between viewstate and viewdata in mvc?</p>

答:
I was just going through the MVC framework & the exact question popped up in my head.. I understand the difference as below.

ASP.Net & MVC are two different worlds. But looking closely they are not. The concepts of web remains the same and it just the way to write the code. Ok letz compare them

ASP.Net
.aspx    -- So this is the view which contains the html to be rendered in the browser

.aspx.cs -- as we know this is the code behind for doing all the manipulation of the html

So on top of that we have the BO with our properties and which is bound to the controls using databind.

So here comes the ViewState which remembers the data bound to the controls back and forth between the postback.

MVC
View - this holds all the HTML code which in turn is still a .aspx or ascx file

Controller - has the logic behind the HTML. Inside that you have the action methods for performing the specific actions.

So here instead of BO, you have the Models with the same properties which is given to the View to render itself in a different syntax instead of a databind.

Now ViewData is used to bind the anonymous data between the controller and the view.

Comparatively ViewData is more organized and easy to use but apart from that they serve a similar purpose but different in few ways. Like Viewstate is persistent between postbacks and ViewData is not as MVC is stateless.

Hope this explains to an extent

Title: ViewState vs ViewData in mvc?


问:
Possible memory leak (Android, Glide, Activity stack)
I am facing a very common and nasty problem as OutOfMemory exception.
To introduce my APP, it is heavy picture content one. And I discovered, I receive a OOM at 256mb in my device (Xiaomi 5s). I cannot find the memory leak (tried https://github.com/square/leakcanary). My APP crashes at ~10th activity loaded. Weird thing happens with GC. Most of the memory gets freed up only if I am fully back to the start.

For image loading I am using Glide. I changed Decoding from 8888 to 565 (default). With 8888 OOM happened faster.

What I was thinking is just to start finishing activities from the stack. Let's say if we have 8 activities, at 9th activity open, 1st activity will be finished and so on.
Before doing so, I would like to hear your guys suggestions!

EDIT
Mostly happens when trying to load a new activity and trying to load images

```<code>  java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: Failed to allocate a 331212 byte allocation with 254848 free bytes and 248KB until OOM
                                                                          at java.util.concurrent.FutureTask.report(FutureTask.java:94)
                                                                          at java.util.concurrent.FutureTask.get(FutureTask.java:164)
                                                                          at com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor.afterExecute(FifoPriorityThreadPoolExecutor.java:96)
                                                                          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1121)
                                                                          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                          at java.lang.Thread.run(Thread.java:818)
                                                                          at com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor$DefaultThreadFactory$1.run(FifoPriorityThreadPoolExecutor.java:118)
                                                                       Caused by: java.lang.OutOfMemoryError: Failed to allocate a 331212 byte allocation with 254848 free bytes and 248KB until OOM
                                                                          at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                                          at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
                                                                          at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:635)
                                                                          at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:611)
                                                                          at com.bumptech.glide.load.resource.bitmap.Downsampler.decodeStream(Downsampler.java:329)
                                                                          at com.bumptech.glide.load.resource.bitmap.Downsampler.downsampleWithSize(Downsampler.java:220)
                                                                          at com.bumptech.glide.load.resource.bitmap.Downsampler.decode(Downsampler.java:153)
                                                                          at com.bumptech.glide.load.resource.bitmap.StreamBitmapDecoder.decode(StreamBitmapDecoder.java:50)
                                                                          at com.bumptech.glide.load.resource.bitmap.StreamBitmapDecoder.decode(StreamBitmapDecoder.java:19)
                                                                          at com.bumptech.glide.load.resource.bitmap.ImageVideoBitmapDecoder.decode(ImageVideoBitmapDecoder.java:39)
                                                                          at com.bumptech.glide.load.resource.bitmap.ImageVideoBitmapDecoder.decode(ImageVideoBitmapDecoder.java:20)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decodeBitmapWrapper(GifBitmapWrapperResourceDecoder.java:121)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decodeStream(GifBitmapWrapperResourceDecoder.java:94)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decode(GifBitmapWrapperResourceDecoder.java:71)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decode(GifBitmapWrapperResourceDecoder.java:61)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decode(GifBitmapWrapperResourceDecoder.java:22)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperStreamResourceDecoder.decode(GifBitmapWrapperStreamResourceDecoder.java:24)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperStreamResourceDecoder.decode(GifBitmapWrapperStreamResourceDecoder.java:14)
                                                                          at com.bumptech.glide.load.resource.file.FileToStreamDecoder.decode(FileToStreamDecoder.java:39)
                                                                          at com.bumptech.glide.load.resource.file.FileToStreamDecoder.decode(FileToStreamDecoder.java:17)
                                                                          at com.bumptech.glide.load.engine.DecodeJob.loadFromCache(DecodeJob.java:222)
                                                                          at com.bumptech.glide.load.engine.DecodeJob.decodeResultFromCache(DecodeJob.java:85)
                                                                          at com.bumptech.glide.load.engine.EngineRunnable.decodeFromCache(EngineRunnable.java:108)
                                                                          at com.bumptech.glide.load.engine.EngineRunnable.decode(EngineRunnable.java:99)
                                                                          at com.bumptech.glide.load.engine.EngineRunnable.run(EngineRunnable.java:58)
                                                                          at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
                                                                          at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                          at java.lang.Thread.run(Thread.java:818)
                                                                          at com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor$DefaultThreadFactory$1.run(FifoPriorityThreadPoolExecutor.java:118)
</code>```

Can happen also when opening an activity while memory is almost dead.

What I was thinking that it is correct, that while opening a new activity, old one stays in memory with images loaded -> which means that memory is being used. But opening only 10 activities is rather little.. Image sizes are 40-100kb. Normally in the activity are >20 images.

I also use lots of programmically created views as well as custom adapters (APP is rather big, we discovered this OOM issue just recently). I was trying to play around with passing different contexts into Glide/ImageViews, but memory usage didn't seem to change.

EDIT2
Heap dump at 178mb

答:
I also had an OOM problem with glide, I decoded GIF and I kept references to drawables in an Arraylist and those drawables were not freed, the solution was to set all nulls in the arraylist and then call ArrayList.clear().</p>

```<code>/// Free drawables
    for (int i = 0; i < mDrawables.size(); i++) {
                mDrawables.set(i, null);
            }
            mDrawables.clear();
</code>```

Body:
I am facing a very common and nasty problem as OutOfMemory exception.
To introduce my APP, it is heavy picture content one. And I discovered, I receive a OOM at 256mb in my device (Xiaomi 5s). I cannot find the memory leak (tried https://github.com/square/leakcanary). My APP crashes at ~10th activity loaded. Weird thing happens with GC. Most of the memory gets freed up only if I am fully back to the start.

For image loading I am using Glide. I changed Decoding from 8888 to 565 (default). With 8888 OOM happened faster.

What I was thinking is just to start finishing activities from the stack. Let's say if we have 8 activities, at 9th activity open, 1st activity will be finished and so on.
Before doing so, I would like to hear your guys suggestions!

EDIT
Mostly happens when trying to load a new activity and trying to load images

  java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: Failed to allocate a 331212 byte allocation with 254848 free bytes and 248KB until OOM
                                                                          at java.util.concurrent.FutureTask.report(FutureTask.java:94)
                                                                          at java.util.concurrent.FutureTask.get(FutureTask.java:164)
                                                                          at com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor.afterExecute(FifoPriorityThreadPoolExecutor.java:96)
                                                                          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1121)
                                                                          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                          at java.lang.Thread.run(Thread.java:818)
                                                                          at com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor$DefaultThreadFactory$1.run(FifoPriorityThreadPoolExecutor.java:118)
                                                                       Caused by: java.lang.OutOfMemoryError: Failed to allocate a 331212 byte allocation with 254848 free bytes and 248KB until OOM
                                                                          at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                                          at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
                                                                          at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:635)
                                                                          at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:611)
                                                                          at com.bumptech.glide.load.resource.bitmap.Downsampler.decodeStream(Downsampler.java:329)
                                                                          at com.bumptech.glide.load.resource.bitmap.Downsampler.downsampleWithSize(Downsampler.java:220)
                                                                          at com.bumptech.glide.load.resource.bitmap.Downsampler.decode(Downsampler.java:153)
                                                                          at com.bumptech.glide.load.resource.bitmap.StreamBitmapDecoder.decode(StreamBitmapDecoder.java:50)
                                                                          at com.bumptech.glide.load.resource.bitmap.StreamBitmapDecoder.decode(StreamBitmapDecoder.java:19)
                                                                          at com.bumptech.glide.load.resource.bitmap.ImageVideoBitmapDecoder.decode(ImageVideoBitmapDecoder.java:39)
                                                                          at com.bumptech.glide.load.resource.bitmap.ImageVideoBitmapDecoder.decode(ImageVideoBitmapDecoder.java:20)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decodeBitmapWrapper(GifBitmapWrapperResourceDecoder.java:121)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decodeStream(GifBitmapWrapperResourceDecoder.java:94)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decode(GifBitmapWrapperResourceDecoder.java:71)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decode(GifBitmapWrapperResourceDecoder.java:61)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decode(GifBitmapWrapperResourceDecoder.java:22)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperStreamResourceDecoder.decode(GifBitmapWrapperStreamResourceDecoder.java:24)
                                                                          at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperStreamResourceDecoder.decode(GifBitmapWrapperStreamResourceDecoder.java:14)
                                                                          at com.bumptech.glide.load.resource.file.FileToStreamDecoder.decode(FileToStreamDecoder.java:39)
                                                                          at com.bumptech.glide.load.resource.file.FileToStreamDecoder.decode(FileToStreamDecoder.java:17)
                                                                          at com.bumptech.glide.load.engine.DecodeJob.loadFromCache(DecodeJob.java:222)
                                                                          at com.bumptech.glide.load.engine.DecodeJob.decodeResultFromCache(DecodeJob.java:85)
                                                                          at com.bumptech.glide.load.engine.EngineRunnable.decodeFromCache(EngineRunnable.java:108)
                                                                          at com.bumptech.glide.load.engine.EngineRunnable.decode(EngineRunnable.java:99)
                                                                          at com.bumptech.glide.load.engine.EngineRunnable.run(EngineRunnable.java:58)
                                                                          at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
                                                                          at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                          at java.lang.Thread.run(Thread.java:818)
                                                                          at com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor$DefaultThreadFactory$1.run(FifoPriorityThreadPoolExecutor.java:118)

Can happen also when opening an activity while memory is almost dead.

What I was thinking that it is correct, that while opening a new activity, old one stays in memory with images loaded -> which means that memory is being used. But opening only 10 activities is rather little.. Image sizes are 40-100kb. Normally in the activity are >20 images.

I also use lots of programmically created views as well as custom adapters (APP is rather big, we discovered this OOM issue just recently). I was trying to play around with passing different contexts into Glide/ImageViews, but memory usage didn't seem to change.

EDIT2
Heap dump at 178mb

Body:
I also had an OOM problem with glide, I decoded GIF and I kept references to drawables in an Arraylist and those drawables were not freed, the solution was to set all nulls in the arraylist and then call ArrayList.clear().

/// Free drawables
    for (int i = 0; i < mDrawables.size(); i++) {
                mDrawables.set(i, null);
            }
            mDrawables.clear();


问:
Allowing single digit in UITextField in iOS
I have a Verification ViewController, I get 4 digit verification code by SMS and I need to enter those code to login, I have created the ViewController like this

As you can see four UITextFields, I need to allow only single digit for each UITextField,

What I tried: I was trying to use shouldChangeCharactersInRange:method: , but its not getting called, I don't know what's wrong, I think because UITextFields are in UITableView so it is not working.

答:
Use this code if you don't want to work with tag and it works better then above</p>

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // On inputing value to textfield
        if ((textField.text?.characters.count)! < 1  && string.characters.count > 0){
            if(textField == txtOne)
            {
                txtTwo.becomeFirstResponder()
            }
            if(textField == txtTwo)
            {
                txtThree.becomeFirstResponder()
            }
            if(textField == txtThree)
            {
                txtFour.becomeFirstResponder()
            }

            textField.text = string
            return false
        }
        else if ((textField.text?.characters.count)! >= 1  && string.characters.count == 0){
            // on deleting value from Textfield
            if(textField == txtTwo)
            {
                txtOne.becomeFirstResponder()
            }
            if(textField == txtThree)
            {
                txtTwo.becomeFirstResponder()
            }
            if(textField == txtFour)
            {
                txtThree.becomeFirstResponder()
            }
            textField.text = ""
            return false
        }
        else if ((textField.text?.characters.count)! >= 1  )
        {
            textField.text = string
            return false
        }
        return true
    }
</code>```

Body:
Use this code if you don't want to work with tag and it works better then above

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // On inputing value to textfield
        if ((textField.text?.characters.count)! < 1  && string.characters.count > 0){
            if(textField == txtOne)
            {
                txtTwo.becomeFirstResponder()
            }
            if(textField == txtTwo)
            {
                txtThree.becomeFirstResponder()
            }
            if(textField == txtThree)
            {
                txtFour.becomeFirstResponder()
            }

            textField.text = string
            return false
        }
        else if ((textField.text?.characters.count)! >= 1  && string.characters.count == 0){
            // on deleting value from Textfield
            if(textField == txtTwo)
            {
                txtOne.becomeFirstResponder()
            }
            if(textField == txtThree)
            {
                txtTwo.becomeFirstResponder()
            }
            if(textField == txtFour)
            {
                txtThree.becomeFirstResponder()
            }
            textField.text = ""
            return false
        }
        else if ((textField.text?.characters.count)! >= 1  )
        {
            textField.text = string
            return false
        }
        return true
    }

ContentLicense: CC BY-SA 4.0


问:
error as "No such table" while inserting data in to table
Getting Error as NO such table,Table is not creating,Please help me with your answers.I think error is database.java file.So I uploaded it.In inserting values I am not changing fields of phone number into long...As I taken it as TEXT datatype in Database file.
           '

```<code>               public class MyDatabase extends SQLiteOpenHelper {

          Context c;

         // Database Name
           public static final String DATABASE_NAME = "BIRLA_ACCOUNTS";
        //Table Name
        public static final String TABLE_NAME = "MASTERACCOUNTS";
        //  Table Columns names
        public static final String CODE = "CODE";
        public static final String NAME = "NAME";
        public static final String TYPE = "TYPE";
        public static final String ADD1 = "ADD1";
        public static final String ADD2 = "ADD2";
        public static final String CITY = "CITY";
        public static final String COUNTRY = "COUNTRY";
        public static final String PHONENO = "PHONENO";
        public static final String CONTACTPERSON = "CONTACTPERSON";
         public static final String EMAILID = "EMAILID";
        public static final String FAX = "FAX";
         public static final String TNO = "TNO";
        public static final String CSTNO = "CSTNO";
        public static final String GSTNO = "GSTNO";
        public static final String SERVICENO = "SERVICENO";

        public MyDatabase(Context context) {
        super(context, DATABASE_NAME, null, 1);
        c = context;

       }

         @Override
          public void onCreate(SQLiteDatabase db) {
          try {

            db.execSQL("CREATE TABLE "+TABLE_NAME+"("+CODE+" INTEGER
                     AUTOINCREMENT,"+NAME+" TEXT PRIMARY KEY ,"+TYPE+" TEXT,
                       "+ADD1+" TEXT,"+ADD2+" TEXT,"+CITY+" TEXT,"+COUNTRY+
                          " TEXT,"+PHONENO+" TEXT,"
                    +CONTACTPERSON+" TEXT,"+EMAILID +" VARCHAR(50),"+FAX+"
                        REAL,"+TNO+" REAL,"+CSTNO+" REAL,"+GSTNO+" REAL,"
            +SERVICENO +" REAL)");
              Toast.makeText(c, "Table Created", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                  Log.e("AccountsMaster creation", "" + e);
                       }

                  }

               @Override
          public void onUpgrade(SQLiteDatabase db, int oldVersion,
                   int  newVersion) {
            // Drop older table if existed
                db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
             // Creating tables again
                 onCreate(db);
              }
</code>```

`

答: instead of AUTOINCREMENT Use AUTO_INCREMENT

Body:
Getting Error as NO such table,Table is not creating,Please help me with your answers.I think error is database.java file.So I uploaded it.In inserting values I am not changing fields of phone number into long...As I taken it as TEXT datatype in Database file.
           '

               public class MyDatabase extends SQLiteOpenHelper {

          Context c;

         // Database Name
           public static final String DATABASE_NAME = "BIRLA_ACCOUNTS";
        //Table Name
        public static final String TABLE_NAME = "MASTERACCOUNTS";
        //  Table Columns names
        public static final String CODE = "CODE";
        public static final String NAME = "NAME";
        public static final String TYPE = "TYPE";
        public static final String ADD1 = "ADD1";
        public static final String ADD2 = "ADD2";
        public static final String CITY = "CITY";
        public static final String COUNTRY = "COUNTRY";
        public static final String PHONENO = "PHONENO";
        public static final String CONTACTPERSON = "CONTACTPERSON";
         public static final String EMAILID = "EMAILID";
        public static final String FAX = "FAX";
         public static final String TNO = "TNO";
        public static final String CSTNO = "CSTNO";
        public static final String GSTNO = "GSTNO";
        public static final String SERVICENO = "SERVICENO";

        public MyDatabase(Context context) {
        super(context, DATABASE_NAME, null, 1);
        c = context;

       }

         @Override
          public void onCreate(SQLiteDatabase db) {
          try {

            db.execSQL("CREATE TABLE "+TABLE_NAME+"("+CODE+" INTEGER
                     AUTOINCREMENT,"+NAME+" TEXT PRIMARY KEY ,"+TYPE+" TEXT,
                       "+ADD1+" TEXT,"+ADD2+" TEXT,"+CITY+" TEXT,"+COUNTRY+
                          " TEXT,"+PHONENO+" TEXT,"
                    +CONTACTPERSON+" TEXT,"+EMAILID +" VARCHAR(50),"+FAX+"
                        REAL,"+TNO+" REAL,"+CSTNO+" REAL,"+GSTNO+" REAL,"
            +SERVICENO +" REAL)");
              Toast.makeText(c, "Table Created", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                  Log.e("AccountsMaster creation", "" + e);
                       }

                  }

               @Override
          public void onUpgrade(SQLiteDatabase db, int oldVersion,
                   int  newVersion) {
            // Drop older table if existed
                db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
             // Creating tables again
                 onCreate(db);
              }

`


问:
Segmenting multiple elements to hide/show with Angular
I have built a semi-custom DataGrid based on a table with fields that auto-populate based on a Service call, An intended behavior in the DataGrid is the ability for the user to revise an entry in the system (in this case, Documents) so that the user can select an action and "Replace" the file, and its File Type. The actual markup looks like this:

```<code><form action="#" method="post" ng-model="OtherDocumentsForm" style="margin-top: 15px;">
            <h3 style="margin: 0;">Additional Documents</h3>

            <table>
                  <tr>
                    <th>File Type</th>
                    <th>File Name</th>
                    <th>Date</th>
                </tr>

                <tr ng-repeat="record in DocumentsOther track by $index" id="row-{{record.file_url}}">
                    <td>
                        <span data-document-type="{{record.file_type}}" data-document-id='{{record.document_id}}'>{{record.file_type}}</span>
                        <select ng-model="newDocumentType" id="replace-file-doctype-{{record.document_id}}" placeholder="Choose file Type" ng-show="$scope.replaceFile" data-document-id="{{record.document_id}}" class="replaceComboBox"> <!-- Note replaceFile -->
                            <option label="" value="" selected="selected"></option>
                            <option label="PDF" value="pdf">PDF</option>
                            <option label="Image" value="image">Image</option>
                        </select>
                    </td>
                    <td>
                        <div ng-if="record">
                            <a href="{{record.file_url}}">{{record.document_name}}</a>
                            <!-- Replace Action-->
                            <button class="replaceAssociatedRecord" ng-click="ClearAssociatedFile($event, this, '{{record.file_url}}', '{{record.document_id}}');" data-document-type="{{record.file_type_raw}}">Replace</button>
                            <input type="file" ng-model="replaceFileField" id="replace-file-{{record.document_id}}" data-document-id="{{record.document_id}}" data-document-type="{{record.file_type_raw}}" onclick="checkIfAssocFileDefined(this);" ng-show="replaceFile" class="replaceFileField" /> <!-- Note replaceFile -->
                        </div>
                    </td>
                    <td>
                        {{record.date_created | dateConsistent}}
                    </td>
                </tr>
            </table>

            <button ng-click="addUncategorizedFile($event)" style="margin: 5px auto 15px; display: block;">Upload additional file</button>
        </form>
</code>```

As you can probably see, one of the issues that is present is that $scope.replaceFile is called across the board. This value gets set to true when $scope.ClearAssociatedFile() (code below) is called in the replace action, so every field gets unhidden. This was a serious oversight on my end and I am wondering, what would be the best approach to re-implement the components here so that I can split off replaceFile (tied to ng-show, and uninitalized inside the parent controller) so its independent enough to where it can be altered once the event of ClearAssociatedFile is selected?

```<code>$scope.ClearAssociatedFile = function(event, elem, parentClassName, inheritDocumentId) {
    event.preventDefault();
    event.stopPropagation();

    //TODO reconfigure to use event
    //document.getElementById("row-"+parentClassName).children[0].children[0].innerHTML = "";
    event.currentTarget.parentElement.parentElement.parentElement.children[0].children[0].innerHTML = "";
    //event.currentTarget.parentElement.parentElement.parentElement.children[0].children[1].style.display = "inline-block"

    //document.getElementById("row-"+parentClassName).children[1].children[0].children[0].innerHTML = "";
    event.currentTarget.parentElement.parentElement.parentElement.children[1].children[0].children[0].innerHTML = "";

    //document.getElementById("row-"+parentClassName).children[1].children[0].children[1].style.display = "none";
    event.currentTarget.parentElement.parentElement.parentElement.children[1].children[0].children[1].style.display = "none";
    //event.currentTarget.parentElement.parentElement.parentElement.children[1].children[0].children[2].style.display = "inline-block";

    //Revise the File Type field to its default.
    document.getElementById("replace-file-doctype-"+inheritDocumentId).value = event.target.attributes[2].value;

    //Show existing fields
    //eval($scope.replaceFile+inheritDocumentId = true);
    var replaceFileKey = "replaceFileItem"+$filter('convert_dashes')(inheritDocumentId);
    $scope[replaceFileKey] = true;
};
</code>```

答:
In your controller, declare the following variable

```<code>$scope.replaceFileKeys = {};
</code>```

Replace the last 2 lines in the ClearAssociatedFile function with the following

```<code>var replaceFileKey = inheritDocumentId;
$scope.replaceFileKeys[replaceFileKey] = true;
</code>```

Update ng-show as follows

```<code>ng-show="$scope.replaceFileKeys[record.document_id]"
</code>```

With the above change, only the item that you interact with is hidden. Let me now if you have questions about the change.

Body:
I have built a semi-custom DataGrid based on a table with fields that auto-populate based on a Service call, An intended behavior in the DataGrid is the ability for the user to revise an entry in the system (in this case, Documents) so that the user can select an action and "Replace" the file, and its File Type. The actual markup looks like this:

<form action="#" method="post" ng-model="OtherDocumentsForm" style="margin-top: 15px;">

Additional Documents

                    File Type
                    File Name
                    Date

                        {{record.file_type}}
                        <select ng-model="newDocumentType" id="replace-file-doctype-{{record.document_id}}" placeholder="Choose file Type" ng-show="$scope.replaceFile" data-document-id="{{record.document_id}}" class="replaceComboBox">
                            <option label="" value="" selected="selected"></option>
                            <option label="PDF" value="pdf">PDF</option>
                            <option label="Image" value="image">Image</option>
                        </select>

                            {{record.document_name}}

                            <button class="replaceAssociatedRecord" ng-click="ClearAssociatedFile($event, this, '{{record.file_url}}', '{{record.document_id}}');" data-document-type="{{record.file_type_raw}}">Replace</button>
                            <input type="file" ng-model="replaceFileField" id="replace-file-{{record.document_id}}" data-document-id="{{record.document_id}}" data-document-type="{{record.file_type_raw}}" onclick="checkIfAssocFileDefined(this);" ng-show="replaceFile" class="replaceFileField" />

                        {{record.date_created | dateConsistent}}

            <button ng-click="addUncategorizedFile($event)" style="margin: 5px auto 15px; display: block;">Upload additional file</button>
        </form>

As you can probably see, one of the issues that is present is that $scope.replaceFile is called across the board. This value gets set to true when $scope.ClearAssociatedFile() (code below) is called in the replace action, so every field gets unhidden. This was a serious oversight on my end and I am wondering, what would be the best approach to re-implement the components here so that I can split off replaceFile (tied to ng-show, and uninitalized inside the parent controller) so its independent enough to where it can be altered once the event of ClearAssociatedFile is selected?

$scope.ClearAssociatedFile = function(event, elem, parentClassName, inheritDocumentId) {
    event.preventDefault();
    event.stopPropagation();

    //TODO reconfigure to use event
    //document.getElementById("row-"+parentClassName).children[0].children[0].innerHTML = "";
    event.currentTarget.parentElement.parentElement.parentElement.children[0].children[0].innerHTML = "";
    //event.currentTarget.parentElement.parentElement.parentElement.children[0].children[1].style.display = "inline-block"

    //document.getElementById("row-"+parentClassName).children[1].children[0].children[0].innerHTML = "";
    event.currentTarget.parentElement.parentElement.parentElement.children[1].children[0].children[0].innerHTML = "";

    //document.getElementById("row-"+parentClassName).children[1].children[0].children[1].style.display = "none";
    event.currentTarget.parentElement.parentElement.parentElement.children[1].children[0].children[1].style.display = "none";
    //event.currentTarget.parentElement.parentElement.parentElement.children[1].children[0].children[2].style.display = "inline-block";

    //Revise the File Type field to its default.
    document.getElementById("replace-file-doctype-"+inheritDocumentId).value = event.target.attributes[2].value;

    //Show existing fields
    //eval($scope.replaceFile+inheritDocumentId = true);
    var replaceFileKey = "replaceFileItem"+$filter('convert_dashes')(inheritDocumentId);
    $scope[replaceFileKey] = true;
};

Body:
In your controller, declare the following variable

$scope.replaceFileKeys = {};

Replace the last 2 lines in the ClearAssociatedFile function with the following

var replaceFileKey = inheritDocumentId;
$scope.replaceFileKeys[replaceFileKey] = true;

Update ng-show as follows

ng-show="$scope.replaceFileKeys[record.document_id]"

With the above change, only the item that you interact with is hidden. Let me now if you have questions about the change.


问:
C# Marshaling C DLL struct bool
i have some trouble with bool while Marshaling C DLL struct
this is code in C DLL

```<code>// cbool.h

#ifndef CBOOL_H
#define CBOOL_H

#define false         0
#define true          !false
typedef unsigned char boolean; /* false=0, otherwise true */

#endif

// test.h
#include "cbool.h"

typedef struct
{
    bool a;
    bool b;
  float c;

} BoolStruct;

extern BoolStruct BStruct;
__declspec(dllexport) void  GetBStruct  (BoolStruct* bs);
__declspec(dllexport) void  SetBStruct  (BoolStruct* bs);

// test.c
#include "test.h"

BoolStruct BStruct;
void    GetBStruct  (BoolStruct* bs)
{
*bs = BStruct;
}

void    SetBStruct  (BoolStruct* bs)
{
BStruct = *bs;
}
</code>```

and in C#

```<code>public struct BoolStruct
{
    public bool a;
    public bool b;
  public float c;

}

BoolStruct bs;

[DllImport(DLL_NAME, EntryPoint = "GetBStruct")]
public static extern void GetBStruct(ref BoolStruct bs);

[DllImport(DLL_NAME, EntryPoint = "SetBStruct")]
public static extern void SetBStruct(ref BoolStruct bs);

bs.a = true;
bs.c = 0.5F;

... set
...get
</code>```

But with float type set and get values are correct, while when i set boll (e.g. true) i receive always false
Can you help me?

答:
Try:

```<code>[StructLayout(LayoutKind.Sequential)]
public struct BoolStruct
{
    [MarshalAs(UnmanagedType.U1)]
    public bool a;

    [MarshalAs(UnmanagedType.U1)]
    public bool b;

    public float c;
}
</code>```

By default the bool is marshaled as an Int32 in .NET.

And you should always specify the StructLayout when you do PInvoke (but note that for struct it isn't necessary: To reduce layout-related problems associated with the Auto value, C#, Visual Basic, and C++ compilers specify Sequential layout for value types.)

Ah and you forgot the CallingConvention: normally it is Cdecl for C functions:

```<code>[DllImport("CPlusPlusSide.dll", EntryPoint = "GetBStruct", CallingConvention = CallingConvention.Cdecl)]
public static extern void GetBStruct(ref BoolStruct bs);

[DllImport("CPlusPlusSide.dll", EntryPoint = "SetBStruct", CallingConvention = CallingConvention.Cdecl)]
public static extern void SetBStruct(ref BoolStruct bs);
</code>```

(tested both x86 and x64)

Title: C# Marshaling C DLL struct bool

Body:
i have some trouble with bool while Marshaling C DLL struct
this is code in C DLL

// cbool.h

#ifndef CBOOL_H
#define CBOOL_H

#define false         0
#define true          !false
typedef unsigned char boolean; /* false=0, otherwise true */

#endif

// test.h
#include "cbool.h"

typedef struct
{
    bool a;
    bool b;
  float c;

} BoolStruct;

extern BoolStruct BStruct;
__declspec(dllexport) void  GetBStruct  (BoolStruct* bs);
__declspec(dllexport) void  SetBStruct  (BoolStruct* bs);

// test.c
#include "test.h"

BoolStruct BStruct;
void    GetBStruct  (BoolStruct* bs)
{
*bs = BStruct;
}

void    SetBStruct  (BoolStruct* bs)
{
BStruct = *bs;
}

and in C#

public struct BoolStruct
{
    public bool a;
    public bool b;
  public float c;

}

BoolStruct bs;

[DllImport(DLL_NAME, EntryPoint = "GetBStruct")]
public static extern void GetBStruct(ref BoolStruct bs);

[DllImport(DLL_NAME, EntryPoint = "SetBStruct")]
public static extern void SetBStruct(ref BoolStruct bs);

bs.a = true;
bs.c = 0.5F;

... set
...get

But with float type set and get values are correct, while when i set boll (e.g. true) i receive always false
Can you help me?

Body:
Try:

[StructLayout(LayoutKind.Sequential)]
public struct BoolStruct
{
    [MarshalAs(UnmanagedType.U1)]
    public bool a;

    [MarshalAs(UnmanagedType.U1)]
    public bool b;

    public float c;
}

By default the bool is marshaled as an Int32 in .NET.

And you should always specify the StructLayout when you do PInvoke (but note that for struct it isn't necessary: To reduce layout-related problems associated with the Auto value, C#, Visual Basic, and C++ compilers specify Sequential layout for value types.)

Ah and you forgot the CallingConvention: normally it is Cdecl for C functions:

[DllImport("CPlusPlusSide.dll", EntryPoint = "GetBStruct", CallingConvention = CallingConvention.Cdecl)]
public static extern void GetBStruct(ref BoolStruct bs);

[DllImport("CPlusPlusSide.dll", EntryPoint = "SetBStruct", CallingConvention = CallingConvention.Cdecl)]
public static extern void SetBStruct(ref BoolStruct bs);

(tested both x86 and x64)


问:
JSF 1.1 to 1.2 migration
I'm currently using JSF 1.1 on Apache Tomcat 6.0.13, with maven 2.

I'm planing to migrate from JSF 1.1 to 1.2. Could someone point me at:
- what JSF implementation is best to use
- is this implementation available at maven central repository
- what part of code will I need to adjust (I'm using custom tags in my project, but besides that it's all plain JSF)

etc.

Any info would be helpful... Thanx!

[edit 1]:

Hm, it haven't worked for me. Dependencies cannot be downloaded from the repository you've specified. Maybe it's because this is link for maven 1 repository. I'm using following pom settings instead:

```<code>        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>1.2</version>
            <type>jar</type>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/webapp/WEB-INF/lib/jsf-api.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>1.2</version>
            <type>jar</type>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/webapp/WEB-INF/lib/jsf-impl.jar</systemPath>
        </dependency>
</code>```

I hope this approach is the correct one. If someone has a more maven-friendly solution, please advise. Thanx!

[edit 2]:
After I've changed my JSF jar from 1.1. to 1.2, following error occurred during application startup:

```<code>java.lang.IllegalStateException: Application was not properly initialized at startup, could not find Factory:
javax.faces.context.FacesContextFactory
</code>```

To fix this error, additional listener need to be added in web.xml:

```<code>    <listener>
        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
    </listener>
</code>```

答:
Have a look at the following release notes that has a migration guide from 1.1 to 1.2
http://java.sun.com/javaee/javaserverfaces/docs/ReleaseNotes.html

The maven2 artifacts for JSF 1.2 have found their way in the standard maven2 repository located at http://http://repo1.maven.org/maven2

JSF Implementation

http://repo2.maven.org/maven2/javax/faces/jsf-impl/1.2-b19/

JSF API

http://repo1.maven.org/maven2/javax/faces/jsf-api/1.2-b19/

As such, you shouldn't require any special repository setup in your pom.xml or settings.xml

The dependencies can be defined like this in the pom (1.2-b19 is the latest version at the time of writing) :

```<code>    <dependency>
        <groupId>javax.faces</groupId>
        <artifactId>jsf-api</artifactId>
        <version>1.2-b19</version>
    </dependency>
    <dependency>
        <groupId>javax.faces</groupId>
        <artifactId>jsf-impl</artifactId>
        <version>1.2-b19</version>
    </dependency>
</code>```

Included below is a full pom.xml that should contain the basic dependencies for starting a JSF 1.2 project

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ecs.sample.jsf</groupId>
    <artifactId>SampleJsfPom</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>1.2-b19</version>
        </dependency>
        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>1.2-b19</version>
        </dependency>
        <dependency>
            <groupId>com.sun.facelets</groupId>
            <artifactId>jsf-facelets</artifactId>
            <version>1.1.11</version>
        </dependency>
        <dependency>
            <groupId>commons-digester</groupId>
            <artifactId>commons-digester</artifactId>
            <version>1.7</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.7.0</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
                <version>2.5</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>
</code>```

Title: JSF 1.1 to 1.2 migration

Body:
I'm currently using JSF 1.1 on Apache Tomcat 6.0.13, with maven 2.

I'm planing to migrate from JSF 1.1 to 1.2. Could someone point me at:
- what JSF implementation is best to use
- is this implementation available at maven central repository
- what part of code will I need to adjust (I'm using custom tags in my project, but besides that it's all plain JSF)

etc.

Any info would be helpful... Thanx!

[edit 1]:

Hm, it haven't worked for me. Dependencies cannot be downloaded from the repository you've specified. Maybe it's because this is link for maven 1 repository. I'm using following pom settings instead:

        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>1.2</version>
            <type>jar</type>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/webapp/WEB-INF/lib/jsf-api.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>1.2</version>
            <type>jar</type>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/webapp/WEB-INF/lib/jsf-impl.jar</systemPath>
        </dependency>

I hope this approach is the correct one. If someone has a more maven-friendly solution, please advise. Thanx!

[edit 2]:
After I've changed my JSF jar from 1.1. to 1.2, following error occurred during application startup:

java.lang.IllegalStateException: Application was not properly initialized at startup, could not find Factory:
javax.faces.context.FacesContextFactory

To fix this error, additional listener need to be added in web.xml:

    <listener>
        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
    </listener>

Body:
Have a look at the following release notes that has a migration guide from 1.1 to 1.2
http://java.sun.com/javaee/javaserverfaces/docs/ReleaseNotes.html

The maven2 artifacts for JSF 1.2 have found their way in the standard maven2 repository located at http://http://repo1.maven.org/maven2

JSF Implementation

http://repo2.maven.org/maven2/javax/faces/jsf-impl/1.2-b19/

JSF API

http://repo1.maven.org/maven2/javax/faces/jsf-api/1.2-b19/

As such, you shouldn't require any special repository setup in your pom.xml or settings.xml

The dependencies can be defined like this in the pom (1.2-b19 is the latest version at the time of writing) :

    <dependency>
        <groupId>javax.faces</groupId>
        <artifactId>jsf-api</artifactId>
        <version>1.2-b19</version>
    </dependency>
    <dependency>
        <groupId>javax.faces</groupId>
        <artifactId>jsf-impl</artifactId>
        <version>1.2-b19</version>
    </dependency>

Included below is a full pom.xml that should contain the basic dependencies for starting a JSF 1.2 project

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ecs.sample.jsf</groupId>
    <artifactId>SampleJsfPom</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>1.2-b19</version>
        </dependency>
        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>1.2-b19</version>
        </dependency>
        <dependency>
            <groupId>com.sun.facelets</groupId>
            <artifactId>jsf-facelets</artifactId>
            <version>1.1.11</version>
        </dependency>
        <dependency>
            <groupId>commons-digester</groupId>
            <artifactId>commons-digester</artifactId>
            <version>1.7</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.7.0</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
                <version>2.5</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>


问:
Django 1.10.6 - MP3 Upload and player
For a job interview I need to code a website consisting of at least 3 pages for a fictional band's website using Django.

My idea is to:

have a front page with blog posts from the band, the most recent one on top.

have an admin page where I can upload the band's songs.

have a page with a list of songs that can be played by clicking on the song.

I know very basic html and css (did some one codecademy).
I did the Django tutorial up until part 6 https://docs.djangoproject.com/en/1.10/intro/tutorial06/

I'm just not very sure how to go about doing this. (Would I use "static files" for the mp3's? How does one set up a blog format page?)

So I'm just hoping for a nudge in the right direction. Any links to tutorials or books or anything that might be useful would be much appreciated.

答: I believe this tutorial would be helpful for this project https://www.youtube.com/watch?v=qgGIqRFvFFk&list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK</p>

Title: Django 1.10.6 - MP3 Upload and player