问:
How to initialize an array of arrays in awk?
Is it possible to initialize an array like this in AWK ?

```<code>Colors[1] = ("Red", "Green", "Blue")
Colors[2] = ("Yellow", "Cyan", "Purple")
</code>```

And then to have a two dimensional array where Colors[2,3]="Purple".

From another thread I understand that it's not possible ( "sadly, there is no way to set an array all at once without abusing split()" ). Anyways I want to be 100% sure and I'm sure that there are others with the same question.

I am looking for the easiest method to initialize arrays like the one above, will be nice to have it well written.

答:
The existing answers are helpful and together cover all aspects, but I thought I'd give a more focused summary.

The question conflates two aspects:

initializing arrays in Awk in general

doing so to fill a two-dimensional array in particular

Array initialization:

Awk has no array literal (initializer) syntax.

The simplest workaround is to:

represent the array elements as a single string and

use the split() function to split that string into the elements of an array.

```<code>$ awk 'BEGIN { n=split("Red Green Blue", arr); for (i=1;i<=n;++i) print arr[i] }'
Red
Green
Blue
</code>```

This is what the OP did in their own helpful answer.

If the elements themselves contain whitespace, use a custom separator that's not part of the data, | in this example:

```<code>$ awk 'BEGIN { n=split("Red (1)|Green (2)", arr, "|"); for (i=1;i<=n;++i) print arr[i] }'
Red (1)
Green (2)
</code>```

Initialization of a 2-dimensional array:

Per POSIX, Awk has no true multi-dimensional arrays, only an emulation of it using a one-dimensional array whose indices are implicitly concatenated with the value of built-in variable SUBSEP to form a single key (index; note that all Awk arrays are associative).

arr[1, 2] is effectively the same as arr[1 SUBSEP 2], where 1 SUBSEP 2 is a string concatenation that builds the key value.

Because there aren't truly multiple dimensions - only a flat array of compound keys - you cannot enumerate the (pseudo-)dimensions individually with for (i in ...), such as to get all sub-indices for primary (pseudo-)dimension 1 only.

The default value of SUBSEP is the "INFORMATION SEPARATOR ONE" character, a a rarely used control character that's unlikely to appear in date; in ASCII and UTF-8 it is represented as single byte 0x1f; if needed, you change the value.

By contrast, GNU Awk, as a nonstandard extension, does have support for true multi-dimensional arrays.

Important: You must then always specify the indices separately; e.g., instead of arr[1,2] you must use arr[1][2].

POSIX-compliant example (similar to TrueY's helpful answer):

```<code>awk 'BEGIN {
  n=split("Red Green Blue", arrAux); for (i in arrAux) Colors[1,i] = arrAux[i]
  n=split("Yellow Cyan Purple", arrAux); for (i in arrAux) Colors[2,i] = arrAux[i]
  print Colors[1,2]
  print "---"
  # Enumerate all [2,*] values - see comments below.
  for (i in Colors) { if (index(i, 2 SUBSEP)==1) print Colors[i] }
}'
Green
---
Yellow
Cyan
Purple
</code>```

Note that the emulation of multi-dimensional arrays with a one-dimensional array using compound keys has the following inconvenient implications:

Auxiliary array auxArr is needed, because you cannot directly populate a given (pseudo-)dimension of an array.

You cannot enumerate just one (pseudo-)dimension with for (i in ...), you can only enumerate all indices, across (pseudo-)dimensions.

for (i in Colors) { if (index(i, 2 SUBSEP)==1) print Colors[i] }
 above shows how to work around that by enumerating all keys and then matching only the ones whose first constituent index is 2, which means that the key value must start with 2, followed by SUBSEP.

GNU Awk example (similar to Steve's helpful answer, improved with Ed Morton's comment):

GNU Awk's (nonstandard) support for true multi-dimensional arrays makes the inconveniences of the POSIX-compliant solution (mostly) go away

(GNU Awk also doesn't have array initializers, however):

```<code>gawk 'BEGIN {
  Colors[1][""]; split("Red Green Blue", Colors[1])
  Colors[2][""]; split("Yellow Cyan Purple", Colors[2])
  # NOTE: Always use *separate* indices: [1][2] instead of [1,2]
  print Colors[1][2]
  print "---"
  # Enumerate all [2][*] values
  for (i in Colors[2]) print Colors[2][i]
}'
</code>```

Note:

Important: As stated, to address a specific element in a multi-dimensional array, always use separate indices; e.g., [1][2] rather than [1,2].

If you use [1,2] you'll get the standard POSIX-mandated behavior, and you'll mistakenly create a new, single index (key) with (string-concatenated) value 1 SUBSEP 2.

split() can conveniently be used to directly populate a sub-array.

As a prerequisite, however, the 2-dimensional target arrays must be initialized:

Colors[1][""] and Colors[2][""] do just that.

Dummy index [""] is just there to create a 2-dimensional array; it is discarded when split() fills that dimension later.

Enumerating a specific dimension with for (i in ...) is supported:

for (i in Colors[2]) ... conveniently enumerates only the sub-indices of Colors[2].

Body:
Is it possible to initialize an array like this in AWK ?

Colors[1] = ("Red", "Green", "Blue")
Colors[2] = ("Yellow", "Cyan", "Purple")

And then to have a two dimensional array where Colors[2,3]="Purple".

From another thread I understand that it's not possible ( "sadly, there is no way to set an array all at once without abusing split()" ). Anyways I want to be 100% sure and I'm sure that there are others with the same question.

I am looking for the easiest method to initialize arrays like the one above, will be nice to have it well written.

Body:
The existing answers are helpful and together cover all aspects, but I thought I'd give a more focused summary.

The question conflates two aspects:

initializing arrays in Awk in general

doing so to fill a two-dimensional array in particular

Array initialization:

Awk has no array literal (initializer) syntax.

The simplest workaround is to:

represent the array elements as a single string and

use the split() function to split that string into the elements of an array.

$ awk 'BEGIN { n=split("Red Green Blue", arr); for (i=1;i<=n;++i) print arr[i] }'
Red
Green
Blue

This is what the OP did in their own helpful answer.

If the elements themselves contain whitespace, use a custom separator that's not part of the data, | in this example:

$ awk 'BEGIN { n=split("Red (1)|Green (2)", arr, "|"); for (i=1;i<=n;++i) print arr[i] }'
Red (1)
Green (2)

Initialization of a 2-dimensional array:

Per POSIX, Awk has no true multi-dimensional arrays, only an emulation of it using a one-dimensional array whose indices are implicitly concatenated with the value of built-in variable SUBSEP to form a single key (index; note that all Awk arrays are associative).

arr[1, 2] is effectively the same as arr[1 SUBSEP 2], where 1 SUBSEP 2 is a string concatenation that builds the key value.

Because there aren't truly multiple dimensions - only a flat array of compound keys - you cannot enumerate the (pseudo-)dimensions individually with for (i in ...), such as to get all sub-indices for primary (pseudo-)dimension 1 only.

The default value of SUBSEP is the "INFORMATION SEPARATOR ONE" character, a a rarely used control character that's unlikely to appear in date; in ASCII and UTF-8 it is represented as single byte 0x1f; if needed, you change the value.

By contrast, GNU Awk, as a nonstandard extension, does have support for true multi-dimensional arrays.

Important: You must then always specify the indices separately; e.g., instead of arr[1,2] you must use arr[1][2].

POSIX-compliant example (similar to TrueY's helpful answer):

awk 'BEGIN {
  n=split("Red Green Blue", arrAux); for (i in arrAux) Colors[1,i] = arrAux[i]
  n=split("Yellow Cyan Purple", arrAux); for (i in arrAux) Colors[2,i] = arrAux[i]
  print Colors[1,2]
  print "---"
  # Enumerate all [2,*] values - see comments below.
  for (i in Colors) { if (index(i, 2 SUBSEP)==1) print Colors[i] }
}'
Green
---
Yellow
Cyan
Purple

Note that the emulation of multi-dimensional arrays with a one-dimensional array using compound keys has the following inconvenient implications:

Auxiliary array auxArr is needed, because you cannot directly populate a given (pseudo-)dimension of an array.

You cannot enumerate just one (pseudo-)dimension with for (i in ...), you can only enumerate all indices, across (pseudo-)dimensions.

for (i in Colors) { if (index(i, 2 SUBSEP)==1) print Colors[i] }
 above shows how to work around that by enumerating all keys and then matching only the ones whose first constituent index is 2, which means that the key value must start with 2, followed by SUBSEP.

GNU Awk example (similar to Steve's helpful answer, improved with Ed Morton's comment):

GNU Awk's (nonstandard) support for true multi-dimensional arrays makes the inconveniences of the POSIX-compliant solution (mostly) go away

(GNU Awk also doesn't have array initializers, however):

gawk 'BEGIN {
  Colors[1][""]; split("Red Green Blue", Colors[1])
  Colors[2][""]; split("Yellow Cyan Purple", Colors[2])
  # NOTE: Always use *separate* indices: [1][2] instead of [1,2]
  print Colors[1][2]
  print "---"
  # Enumerate all [2][*] values
  for (i in Colors[2]) print Colors[2][i]
}'

Note:

Important: As stated, to address a specific element in a multi-dimensional array, always use separate indices; e.g., [1][2] rather than [1,2].

If you use [1,2] you'll get the standard POSIX-mandated behavior, and you'll mistakenly create a new, single index (key) with (string-concatenated) value 1 SUBSEP 2.

split() can conveniently be used to directly populate a sub-array.

As a prerequisite, however, the 2-dimensional target arrays must be initialized:

Colors[1][""] and Colors[2][""] do just that.

Dummy index [""] is just there to create a 2-dimensional array; it is discarded when split() fills that dimension later.

Enumerating a specific dimension with for (i in ...) is supported:

for (i in Colors[2]) ... conveniently enumerates only the sub-indices of Colors[2].


来源: stackexchange

问:
About the open-source project Maate
I want to use the open source LAME library to manipulate MP3 files. After carefully read information on main page of LAME, I find the Maate lib maybe more proper to my task and I also want to read the "good description of MP3 frames" from Maate as claimed by LAME.

Unfortunately, I can't find Maate through the link provided by LAME. So what's going on? Is the project Maate still available? If yes, where can I find it? Any suggestion will be highly appriciated. Thank you all in advance.

Regards!

答:
They moved to sourceforge, see http://maaate.sourceforge.net/ .

The fact that the ancient link in the LAME pages had the name misspelled (or perhaps they changed it halfway the project) didn't help... nor did the fact that they temporarily moved the website to a place that was blocked from archive.org first.

ContentLicense: CC BY-SA 2.5

Title: About the open-source project Maate


问:
Login into database with hibernate dynamically
I have to make an application that has a login to enter the database as admin, without having to use the username and password parameters of the configuration file, but I can not get it, could you help me?

```<code>public class HibernateUtil {

private static SessionFactory sessionFactory;

public static void configureHibernateUtil(String user, String pass) {
    try {
        Configuration cfg = new Configuration();
        cfg.configure("/dao/hibernate.cfg.xml"); //hibernate config xml file name
        String newUserName = null, newPassword = null;//set them as per your needs
        cfg.getProperties().setProperty("hibernate.connection.password", newPassword);
        cfg.getProperties().setProperty("hibernate.connection.username", newUserName);
        //In next line you just tell Hibernate which classes are you going to query

        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties());
        sessionFactory = cfg.buildSessionFactory(ssrb.build());
    } catch (HibernateException he) {
        System.err.println("Ocurrió un error en la inicialización de la SessionFactory: " + he);
        throw new ExceptionInInitializerError(he);
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
</code>```

}

答:
The method parameter user and pass does NOT replace the properties of cfg. So the method does not work. Here is the amended code:

```<code>public static void configureHibernateUtil(String user, String pass) {
    try {
        Configuration cfg = new Configuration();
        cfg.configure("/dao/hibernate.cfg.xml"); //hibernate config xml file name
        //String newUserName = null, newPassword = null;//set them as per your needs
        cfg.getProperties().setProperty("hibernate.connection.password", pass);
        cfg.getProperties().setProperty("hibernate.connection.username", user);
        //In next line you just tell Hibernate which classes are you going to query

        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties());
        sessionFactory = cfg.buildSessionFactory(ssrb.build());
    } catch (HibernateException he) {
        System.err.println("Ocurrió un error en la inicialización de la SessionFactory: " + he);
        throw new ExceptionInInitializerError(he);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have to make an application that has a login to enter the database as admin, without having to use the username and password parameters of the configuration file, but I can not get it, could you help me?

public class HibernateUtil {

private static SessionFactory sessionFactory;

public static void configureHibernateUtil(String user, String pass) {
    try {
        Configuration cfg = new Configuration();
        cfg.configure("/dao/hibernate.cfg.xml"); //hibernate config xml file name
        String newUserName = null, newPassword = null;//set them as per your needs
        cfg.getProperties().setProperty("hibernate.connection.password", newPassword);
        cfg.getProperties().setProperty("hibernate.connection.username", newUserName);
        //In next line you just tell Hibernate which classes are you going to query

        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties());
        sessionFactory = cfg.buildSessionFactory(ssrb.build());
    } catch (HibernateException he) {
        System.err.println("Ocurrió un error en la inicialización de la SessionFactory: " + he);
        throw new ExceptionInInitializerError(he);
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}

}

Body:
The method parameter user and pass does NOT replace the properties of cfg. So the method does not work. Here is the amended code:

public static void configureHibernateUtil(String user, String pass) {
    try {
        Configuration cfg = new Configuration();
        cfg.configure("/dao/hibernate.cfg.xml"); //hibernate config xml file name
        //String newUserName = null, newPassword = null;//set them as per your needs
        cfg.getProperties().setProperty("hibernate.connection.password", pass);
        cfg.getProperties().setProperty("hibernate.connection.username", user);
        //In next line you just tell Hibernate which classes are you going to query

        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties());
        sessionFactory = cfg.buildSessionFactory(ssrb.build());
    } catch (HibernateException he) {
        System.err.println("Ocurrió un error en la inicialización de la SessionFactory: " + he);
        throw new ExceptionInInitializerError(he);
    }
}


问:
Circle with two borders
How can I style a a circle (a div) with two borders responsively so that it reacts to a container's size?

Suppose circles like this for example:

Here is a working CSS for a circle:

div.circle {
  width: 90%;
  height: 0;
  padding-bottom: 90%;
  margin: auto;
  float: none;
  border-radius: 50%;
  border: 1px solid green;
  background: pink;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="circle"></div></code>```

How can I add a border with two colors? I tried outline but it came out as a rectangle. I tried to place another div inside the circle div and use background color but I can't align the inner div vertically.

答:
Here is a fiddle where I draw one circle with a border and box-shadow to create the outer circle effect  https://jsfiddle.net/salientknight/k18fmepL/1/
Tested and works in Chrome, Safari and Opera -- Fails in Firefox if text gets too large Good for about 3 characters font size 1em then height and width get out of sync -- will work in FireFox with a fixed size height and width...

```<code><!-- Inside H1 -->
<h1><p class='circleBlue'>10000%</p></h1>
<!-- Regular -->
<p class='circleBlue'>10000%</p>

p.circleBlue{
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-color: #159fda;
 border: 5px Solid #fff;
  color: #fff;
  min-width: 1em;
  border-radius: 50%;
  vertical-align: middle;
  padding:20px;
   box-shadow: 0px -0px  0px 3px #159fda;
   -webkit-box-shadow: 0px -0px  0px 3px  #159fda;
 -moz-box-shadow: 0px -0px  0px 3px #159fda;
   margin:5px;
}

p.circle:before{
  content:'';
  float: left;
  width: auto;
  padding-bottom: 100%;
}
</code>```

update I could not get this to work with a variety of text sizes and in all browsers so I added some js. I'm pasting it here so their is one complete solution all together. changesSizes is a function that makes sure that height and width always match... first checking which is bigger and then setting the value of both to the larger of the two (yes one of these assignments is redundant but it gives me peace of mind). The final effect is that I can add content of many shapes and sizes. The only real limitation I have found is taste.

```<code>   changeSizes(".circleBlue");
   //changeSizes(".circleGreen");
   //changeSizes(".circleOrange");

---------

function changeSizes(cirlceColor){
    var circle = $(cirlceColor);
 circle.each(function(){
   var cw = $(this).width();
   var ch = $(this).height();

   if(cw>ch){
       $(this).width(cw);
       $(this).height(cw);
   }else{
        $(this).width(ch);
       $(this).height(ch);
   }
   });
}

Example:
</code>```

Title: Circle with two borders

Body:
How can I style a a circle (a div) with two borders responsively so that it reacts to a container's size?

Suppose circles like this for example:

Here is a working CSS for a circle:

div.circle {
  width: 90%;
  height: 0;
  padding-bottom: 90%;
  margin: auto;
  float: none;
  border-radius: 50%;
  border: 1px solid green;
  background: pink;
}

How can I add a border with two colors? I tried outline but it came out as a rectangle. I tried to place another div inside the circle div and use background color but I can't align the inner div vertically.

Body:
Here is a fiddle where I draw one circle with a border and box-shadow to create the outer circle effect  https://jsfiddle.net/salientknight/k18fmepL/1/
Tested and works in Chrome, Safari and Opera -- Fails in Firefox if text gets too large Good for about 3 characters font size 1em then height and width get out of sync -- will work in FireFox with a fixed size height and width...

<!-- Inside H1 -->
<h1><p class='circleBlue'>10000%</p></h1>
<!-- Regular -->
<p class='circleBlue'>10000%</p>

p.circleBlue{
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-color: #159fda;
 border: 5px Solid #fff;
  color: #fff;
  min-width: 1em;
  border-radius: 50%;
  vertical-align: middle;
  padding:20px;
   box-shadow: 0px -0px  0px 3px #159fda;
   -webkit-box-shadow: 0px -0px  0px 3px  #159fda;
 -moz-box-shadow: 0px -0px  0px 3px #159fda;
   margin:5px;
}

p.circle:before{
  content:'';
  float: left;
  width: auto;
  padding-bottom: 100%;
}

update I could not get this to work with a variety of text sizes and in all browsers so I added some js. I'm pasting it here so their is one complete solution all together. changesSizes is a function that makes sure that height and width always match... first checking which is bigger and then setting the value of both to the larger of the two (yes one of these assignments is redundant but it gives me peace of mind). The final effect is that I can add content of many shapes and sizes. The only real limitation I have found is taste.

   changeSizes(".circleBlue");
   //changeSizes(".circleGreen");
   //changeSizes(".circleOrange");

---------

function changeSizes(cirlceColor){
    var circle = $(cirlceColor);
 circle.each(function(){
   var cw = $(this).width();
   var ch = $(this).height();

   if(cw>ch){
       $(this).width(cw);
       $(this).height(cw);
   }else{
        $(this).width(ch);
       $(this).height(ch);
   }
   });
}

Example:


问:
I want to use image_tag for the [ number set ] not just one number. (Ruby)
It is kind of lottery, when you press F5 , new balls come out in the site.
My goal is to show the organized number balls in Ascending order.
(and I use Cloud9)
of course I have numbered photos like 1.jpg , 2.jpg ...
and add them in the folder of C9 (Cloud9)

there are two solution I think

I want to re-organized the "sampled number"

image tag to listed number set

This is my trial

```<code>    @todaynum= @allnum.sample
    @todaynum1= @allnum.sample
    @todaynum2= @allnum.sample
    @todaynum3= @allnum.sample
    @todaynum4= @allnum.sample
    @todaynum5= @allnum.sample

    @numimg= @todaynum+".jpg"
    @numimg1= @todaynum1+".jpg"
    @numimg2= @todaynum2+".jpg"
    @numimg3= @todaynum3+".jpg"
    @numimg4= @todaynum4+".jpg"
    @numimg5= @todaynum5+".jpg"

    arr = (@todaynum,@todaynum1,@todaynum2,@todaynum3,@todaynum4,@todaynum5)
    arr.sort!

    puts arr $array = Array.new(45)
    $array = (1..45).to_a
    @lotto_list = $array.sample(6).sort
    @lotto_list_image = $array.sample(6).sort ".jpg"
</code>```

html.erb file

```<code><%=@lotto_list%>
<%=image_tag lotto_list_image %>
</code>```

but, it doesn't work at all ..

or

```<code>lotto list image = ~~ something(I don't know..) ~~ ".jpg"I want to do like this.
</code>```

It is so hard for me to go over this problem...
How should I do?

This is my code

```<code>class numbersetController < ApplicationController
  def numbers
    @allnum=["1","2","3","4","5","6","7","8","9","10","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45"]

    @todaynum= @allnum.sample
    @todaynum1= @allnum.sample
    @todaynum2= @allnum.sample
    @todaynum3= @allnum.sample
    @todaynum4= @allnum.sample
    @todaynum5= @allnum.sample

    @numimg= @todaynum+".jpg"
    @numimg1= @todaynum1+".jpg"
    @numimg2= @todaynum2+".jpg"
    @numimg3= @todaynum3+".jpg"
    @numimg4= @todaynum4+".jpg"
    @numimg5= @todaynum5+".jpg"

    arr = (@todaynum,@todaynum1,@todaynum2,@todaynum3,@todaynum4,@todaynum5)
    arr.sort!
    puts arr

    $array = Array.new(45)
    $array = (1..45).to_a

    @lotto_list = $array.sample(6).sort

  end
end
</code>```

html.erb file

```<code><h1>lotto balls newbie.version</h1>

<p><%=image_tag @numimg%></p>
<h2><%=image_tag @numimg1%></h2>
<h3><%=image_tag @numimg2%></h3>
<h4><%=image_tag @numimg3%></h4>
<h5><%=image_tag @numimg4%></h5>
<h6><%=image_tag @numimg5%></h6>

<%=@todaynum%>
<%=@todaynum1%>
<%=@todaynum2%>
<%=@todaynum3%>
<%=@todaynum4%>
<%=@todaynum5%>

<h1> ruby random number (for test) </h1>
<%=@lotto_list%>
</code>```

答:
You are on the right track on the second try you did, just need a second call to map to format it the way you want it.

```<code># note: probably want to rename the controller like so
class NumbersetController < ApplicationController
  def numbers
    @lotto_ball_images = *(1..45).to_a.sample(6).sort.map(&:to_s).map{|n| "lotto-ball-image-number#{n}.jpg"}
  end
end
</code>```

then something like this in the template.

```<code><h1>lotto balls </h1>

<% @lotto_ball_images.each do |src| %>
   <%= image_tag(src) %>
<% end %>
</code>```

Body:
It is kind of lottery, when you press F5 , new balls come out in the site.
My goal is to show the organized number balls in Ascending order.
(and I use Cloud9)
of course I have numbered photos like 1.jpg , 2.jpg ...
and add them in the folder of C9 (Cloud9)

there are two solution I think

I want to re-organized the "sampled number"

image tag to listed number set

This is my trial

    @todaynum= @allnum.sample
    @todaynum1= @allnum.sample
    @todaynum2= @allnum.sample
    @todaynum3= @allnum.sample
    @todaynum4= @allnum.sample
    @todaynum5= @allnum.sample

    @numimg= @todaynum+".jpg"
    @numimg1= @todaynum1+".jpg"
    @numimg2= @todaynum2+".jpg"
    @numimg3= @todaynum3+".jpg"
    @numimg4= @todaynum4+".jpg"
    @numimg5= @todaynum5+".jpg"

    arr = (@todaynum,@todaynum1,@todaynum2,@todaynum3,@todaynum4,@todaynum5)
    arr.sort!

    puts arr $array = Array.new(45)
    $array = (1..45).to_a
    @lotto_list = $array.sample(6).sort
    @lotto_list_image = $array.sample(6).sort ".jpg"

html.erb file

<%=@lotto_list%>
<%=image_tag lotto_list_image %>

but, it doesn't work at all ..

or

lotto list image = ~~ something(I don't know..) ~~ ".jpg"I want to do like this.

It is so hard for me to go over this problem...
How should I do?

This is my code

class numbersetController < ApplicationController
  def numbers
    @allnum=["1","2","3","4","5","6","7","8","9","10","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45"]

    @todaynum= @allnum.sample
    @todaynum1= @allnum.sample
    @todaynum2= @allnum.sample
    @todaynum3= @allnum.sample
    @todaynum4= @allnum.sample
    @todaynum5= @allnum.sample

    @numimg= @todaynum+".jpg"
    @numimg1= @todaynum1+".jpg"
    @numimg2= @todaynum2+".jpg"
    @numimg3= @todaynum3+".jpg"
    @numimg4= @todaynum4+".jpg"
    @numimg5= @todaynum5+".jpg"

    arr = (@todaynum,@todaynum1,@todaynum2,@todaynum3,@todaynum4,@todaynum5)
    arr.sort!
    puts arr

    $array = Array.new(45)
    $array = (1..45).to_a

    @lotto_list = $array.sample(6).sort

  end
end

html.erb file

lotto balls newbie.version

<%=image_tag @numimg%>

<%=image_tag @numimg1%>

<%=image_tag @numimg2%>

<%=image_tag @numimg3%>

<%=image_tag @numimg4%>

<%=image_tag @numimg5%>

<%=@todaynum%>
<%=@todaynum1%>
<%=@todaynum2%>
<%=@todaynum3%>
<%=@todaynum4%>
<%=@todaynum5%>

 ruby random number (for test)

<%=@lotto_list%>

Body:
You are on the right track on the second try you did, just need a second call to map to format it the way you want it.

# note: probably want to rename the controller like so
class NumbersetController < ApplicationController
  def numbers
    @lotto_ball_images = *(1..45).to_a.sample(6).sort.map(&:to_s).map{|n| "lotto-ball-image-number#{n}.jpg"}
  end
end

then something like this in the template.

<h1>lotto balls </h1>

<% @lotto_ball_images.each do |src| %>
   <%= image_tag(src) %>
<% end %>


问:
JavaScript Nativescript: Make ListView height equal to total height of rows

Context

I have a listView element that pulls in its elements via external source. As such I can't be sure how many rows there will be.

I therefore set the listView attribute height to a bound variable, and the attribute rowHeight to a constant.

However, if I multiply multiply the rowHeight by the number of list items, the height of the listView is always too much and leaves empty space.

Code

page.xml

```<code><StackLayout class="group-meta-active" visibility="{{ userCanSelect ? 'visible' : 'collapsed' }}" ontap="teamSelect">
    <Label text="Selection" class="group-meta-active-team-label" />
    <Label text="{{ selectionName || '' }}" id="{{ selectionId || 0 }}" visibility="{{ selectionId ? 'visible' : 'collapsed'}}" class="group-meta-active-team-name" />
    <Label text="Tap To Decide" visibility="{{ selectionId ? 'collapsed' : 'visible'}}" class="group-meta-active-team-decide" />
    <ListView items="{{ userAllowedSelections }}" height="{{ userSelectionHeight }}" class="list-clubs" itemTap="selectTeam" rowHeight="35" visibility="{{ selectionSelect ? 'visible' : 'collapsed' }}">
        <ListView.itemTemplate>
            <StackLayout orientation="horizontal" class="list-clubs-cont">
                <Label text="{{ clubName || 'Loading...' }}" textWrap="false" class="list-clubs-label" />
                <Label text="vs" textWrap="false" class="list-clubs-vs" />
                <Label text="{{ clubOpponent || 'Loading...' }}" textWrap="false" class="list-clubs-opp" />
            </StackLayout>
        </ListView.itemTemplate>
    </ListView>
</StackLayout>
</code>```

page.js

```<code>//When setting page variables; e is the retrieved object;
//e.allowedSelections is an array
pageData.set("userAllowedSelections", (e.allowedSelections));
pageData.set("userSelectionHeight", (e.allowedSelections.length * 35));
</code>```

Output Images

Top of list element

Bottom of list element

Question

As you can see, the listView element is a few pixels taller than the elements inside, despite the rowHeight being set to 35, and the listView height attribute set to 35 x listView element array length.

I have tried:

Setting the multiplication to one-off (e.g. 34/36)

Setting the multiplication to a half-value (e.g. 34.5, 35.5)

Mixing and matching with multiple values

Removing all padding and margins on the list items (the only CSS now is font styling and vertical-align: middle

Is this possible?

答:
I am thinking of two possible reasons for this to happen.

Using DP (a.k.a device independent pixels) in NativeScript is implemented by calculating the actual pixel for the current device and the actual device density.This might lead to a different result when using hard coded values as the density of different devices varies and those calculations might need some rounding.

the separator width (approx. 1dp or less)

Using your code base this solution is perfect on API19 and about half pixel off in API23 (for each)

```<code>var size = (e.allowedSelections.length * 35) + (e.allowedSelections.length * 0.9);
pageData.set("userSelectionHeight", size);
</code>```

Still, you can check the current device screen scale and dimensions and make better calculation for each device using the platform module

```<code>import { screen, ScreenMetrics } from "platform";
var mainScreen = screen.mainScreen;
console.log(mainScreen.heightDIPs);
console.log(mainScreen.heightPixels);
console.log(mainScreen.scale);
console.log(mainScreen.widthDIPs);
console.log(mainScreen.widthPixels);
</code>```

Body:
Context

I have a listView element that pulls in its elements via external source. As such I can't be sure how many rows there will be.

I therefore set the listView attribute height to a bound variable, and the attribute rowHeight to a constant.

However, if I multiply multiply the rowHeight by the number of list items, the height of the listView is always too much and leaves empty space.

Code

page.xml

<StackLayout class="group-meta-active" visibility="{{ userCanSelect ? 'visible' : 'collapsed' }}" ontap="teamSelect">

    <ListView items="{{ userAllowedSelections }}" height="{{ userSelectionHeight }}" class="list-clubs" itemTap="selectTeam" rowHeight="35" visibility="{{ selectionSelect ? 'visible' : 'collapsed' }}">
        <ListView.itemTemplate>
            <StackLayout orientation="horizontal" class="list-clubs-cont">

            </StackLayout>
        </ListView.itemTemplate>
    </ListView>
</StackLayout>

page.js

//When setting page variables; e is the retrieved object;
//e.allowedSelections is an array
pageData.set("userAllowedSelections", (e.allowedSelections));
pageData.set("userSelectionHeight", (e.allowedSelections.length * 35));

Output Images

Top of list element

Bottom of list element

Question

As you can see, the listView element is a few pixels taller than the elements inside, despite the rowHeight being set to 35, and the listView height attribute set to 35 x listView element array length.

I have tried:

Setting the multiplication to one-off (e.g. 34/36)

Setting the multiplication to a half-value (e.g. 34.5, 35.5)

Mixing and matching with multiple values

Removing all padding and margins on the list items (the only CSS now is font styling and vertical-align: middle

Is this possible?

Body:
I am thinking of two possible reasons for this to happen.

Using DP (a.k.a device independent pixels) in NativeScript is implemented by calculating the actual pixel for the current device and the actual device density.This might lead to a different result when using hard coded values as the density of different devices varies and those calculations might need some rounding.

the separator width (approx. 1dp or less)

Using your code base this solution is perfect on API19 and about half pixel off in API23 (for each)

var size = (e.allowedSelections.length * 35) + (e.allowedSelections.length * 0.9);
pageData.set("userSelectionHeight", size);

Still, you can check the current device screen scale and dimensions and make better calculation for each device using the platform module

import { screen, ScreenMetrics } from "platform";
var mainScreen = screen.mainScreen;
console.log(mainScreen.heightDIPs);
console.log(mainScreen.heightPixels);
console.log(mainScreen.scale);
console.log(mainScreen.widthDIPs);
console.log(mainScreen.widthPixels);


问:
How to delete a specific  cell with no id from a dynamically added table using jquery?
The table involves a dropdown box and a normal  with a value. When onChange of the dropdown, the specific  must change to another dropdown. I've used jQuery to implement the function, but while I change the dropdown for the first row, the change is happening for the entire table. I just need the change to happen for the single row where the onChange function has been called.

```<code>$('td:nth-child(11),th:nth-child(11)').hide();
$('td:nth-child(10),th:nth-child(10)').show();
</code>```

is used to hide and show the 10th and 11th columns.

doc.ready function() :

```<code>$(document).ready(function() {
  $('td:nth-child(11),th:nth-child(11)').show();
  $('td:nth-child(10),th:nth-child(10)').hide();
  // ...
</code>```

onChange function used :

```<code>$(document).on('change','.mySelect', function(event) {
  event.preventDefault();

  $('td:nth-child(11),th:nth-child(11)').hide();
  $('td:nth-child(10),th:nth-child(10)').show();
  //$(this).closest("td").show();

  var _this = $(this);
  var id =_this.val();
  var statusValue = id;

  $.get('AssignedTo', { statusVal : statusValue }, function(response) {
    var select = _this.closest("tr").find("select[name='assigned']");
    /* var select = $('#assigned'); */
    select.find('option').remove();

    $.each(response, function(index, value) {
      $('<option>').val(value).text(value).appendTo(select);
    });
  });
});
</code>```

答:
Rather than using nth-child, consider using eq() - it's cleaner and doesn't come with some of the specificity issues of nth-child.

To get all  elements in the "changed" row, you can get the parent by doing .closest("td") and select all of its siblings using .siblings("td")

To include the original one (and not only siblings), you'd use .addBack().

Finally, now that we have all the cells in the row, select the one you want using eq().

Put all together, it looks like this:

```<code>//Select the 11th cell in the row
var $cell = $(this).closest('td').siblings('td').addBack().eq(10);
</code>```

Or, you could get the parent and choose all its children (instead of siblings) using .closest("tr") and children():

```<code>//Select the 11th cell in the row
var $cell = $(this).closest("tr").children("td").eq(10);
</code>```

Title: How to delete a specific <td> cell with no id from a dynamically added table using jquery?

Body:
The table involves a dropdown box and a normal  with a value. When onChange of the dropdown, the specific  must change to another dropdown. I've used jQuery to implement the function, but while I change the dropdown for the first row, the change is happening for the entire table. I just need the change to happen for the single row where the onChange function has been called.

$('td:nth-child(11),th:nth-child(11)').hide();
$('td:nth-child(10),th:nth-child(10)').show();

is used to hide and show the 10th and 11th columns.

doc.ready function() :

$(document).ready(function() {
  $('td:nth-child(11),th:nth-child(11)').show();
  $('td:nth-child(10),th:nth-child(10)').hide();
  // ...

onChange function used :

$(document).on('change','.mySelect', function(event) {
  event.preventDefault();

  $('td:nth-child(11),th:nth-child(11)').hide();
  $('td:nth-child(10),th:nth-child(10)').show();
  //$(this).closest("td").show();

  var _this = $(this);
  var id =_this.val();
  var statusValue = id;

  $.get('AssignedTo', { statusVal : statusValue }, function(response) {
    var select = _this.closest("tr").find("select[name='assigned']");
    /* var select = $('#assigned'); */
    select.find('option').remove();

    $.each(response, function(index, value) {
      $('<option>').val(value).text(value).appendTo(select);
    });
  });
});

Body:
Rather than using nth-child, consider using eq() - it's cleaner and doesn't come with some of the specificity issues of nth-child.

To get all <td> elements in the "changed" row, you can get the parent<td> by doing .closest("td") and select all of its siblings using .siblings("td")

To include the original one (and not only siblings), you'd use .addBack().

Finally, now that we have all the cells in the row, select the one you want using eq().

Put all together, it looks like this:

//Select the 11th cell in the row
var $cell = $(this).closest('td').siblings('td').addBack().eq(10);

Or, you could get the parent and choose all its children (instead of siblings) using .closest("tr") and children():

//Select the 11th cell in the row
var $cell = $(this).closest("tr").children("td").eq(10);


问:
How to get desired height of ListBox so it doesn't have scrollbar and its content fits there
I have a ListBox inside a DockPanel. I want to find out what should be the size of the ListBox so it doesn't have the scroll bar. I use ListBox.DesiredSize but actually DesiredSize is equal to ListBox.ActualWidth / Height and the ListBox has scrollbar because there are more items that can fit its height.
How to get real desired size ?

答:
How to get real desired size ?

The desired size of the ListBox is calculated automatically if you don't explicitly set its Height or VerticalAlignment property and avoid putting it in a Panel that measures its children with an infinite space such as a StackPanel.

The desired size of the ListBox itself is however not the same as the aggregated size of all ListBoxItem containers. In fact, there is no easy way to calculate this height exactly since not all containers are generated up front provided that you haven't disabled the UI virtualization of the ListBox.

The easiest workaround/solution would probably be to get the height of the first container once the ListBox has been loaded and then multiply this value with the actual number of items, e.g.:

```<code><ListBox x:Name="lb" Loaded="lb_Loaded">
    <ListBoxItem>1</ListBoxItem>
    <ListBoxItem>2</ListBoxItem>
    <ListBoxItem>3</ListBoxItem>
</ListBox>
</code>```

```<code>private void lb_Loaded(object sender, RoutedEventArgs e)
{
    ListBoxItem lbi = lb.ItemContainerGenerator.ContainerFromIndex(0) as ListBoxItem;
    if (lbi != null)
    {
        lb.Height = lbi.ActualHeight * lb.Items.Count + /* add some offset */ 5;
    }
}
</code>```

Body:
How to get real desired size ?

The desired size of the ListBox is calculated automatically if you don't explicitly set its Height or VerticalAlignment property and avoid putting it in a Panel that measures its children with an infinite space such as a StackPanel.

The desired size of the ListBox itself is however not the same as the aggregated size of all ListBoxItem containers. In fact, there is no easy way to calculate this height exactly since not all containers are generated up front provided that you haven't disabled the UI virtualization of the ListBox.

The easiest workaround/solution would probably be to get the height of the first container once the ListBox has been loaded and then multiply this value with the actual number of items, e.g.:

<ListBox x:Name="lb" Loaded="lb_Loaded">
    <ListBoxItem>1</ListBoxItem>
    <ListBoxItem>2</ListBoxItem>
    <ListBoxItem>3</ListBoxItem>
</ListBox>

private void lb_Loaded(object sender, RoutedEventArgs e)
{
    ListBoxItem lbi = lb.ItemContainerGenerator.ContainerFromIndex(0) as ListBoxItem;
    if (lbi != null)
    {
        lb.Height = lbi.ActualHeight * lb.Items.Count + /* add some offset */ 5;
    }
}


问:
How to avoid overfitting Recurrent Neural Network
I have been training Bidirectional LSTM based RNN for Speech Recognition, and the network appears to forget the old context as soon as a new context arrives. I am unsure how to explain its behaviour though; it appears that the network is being overfit such that it remembers only one specific case at a time.

The link to code is https://github.com/rajkumarcm15/Speech-Recognition/blob/master/MFCC_SWN_BN_Affine/train.py and its output in https://github.com/rajkumarcm15/Speech-Recognition/blob/master/MFCC_SWN_BN_Affine/Results.pdf.

Need some help in understanding its output pattern.

答:
Other recommendations (apart from the one dv3 suggested) you can try that often help me:

increase your hidden_size (try multiplying by 4)

increase your batch_size (again, try multiplying by 4)

Also, it looks like your loss is still going down. Maybe more training would help (also, you only adjusted your learning rate once with this amount of epochs).

Hope this helps! Let me know if one of the suggestions did something.


问:
How to use andOperator inside orOperator
I have a function

```<code>Criteria[] regexBuilder(String field, String[] patterns) {
    return Arrays.stream(keyWordPattern)
            .map(it -> Criteria.where(field).regex(Pattern.compile(it, Pattern.LITERAL).toString(), "si"))
            .toArray(Criteria[]::new);
}
</code>```

That I use like so:

```<code>// Assume type: String and keywords: String[]
Criteria.where("type").is(type).andOperator(regexBuilder("description", keywords));
</code>```

What I want is to search for a match if the description field has all the keywords or the notes field has all the keywords. Something like:

```<code>Criteria.where("type").is(type).orOperator(
    andOperator(regexBuilder("description", keywords)),
    andOperator(regexBuilder("notes", keywords)),
);
</code>```

How would I construct such a query?

答:
You can try something like below.</p>

```<code>Criteria.where("type").is(type).orOperator(
    new Criteria().andOperator(regexBuilder("description", keywords)),
    new Criteria().andOperator(regexBuilder("notes", keywords)),
);
</code>```

Body:
I have a function

Criteria[] regexBuilder(String field, String[] patterns) {
    return Arrays.stream(keyWordPattern)
            .map(it -> Criteria.where(field).regex(Pattern.compile(it, Pattern.LITERAL).toString(), "si"))
            .toArray(Criteria[]::new);
}

That I use like so:

// Assume type: String and keywords: String[]
Criteria.where("type").is(type).andOperator(regexBuilder("description", keywords));

What I want is to search for a match if the description field has all the keywords or the notes field has all the keywords. Something like:

Criteria.where("type").is(type).orOperator(
    andOperator(regexBuilder("description", keywords)),
    andOperator(regexBuilder("notes", keywords)),
);

How would I construct such a query?

Body:
You can try something like below.

Criteria.where("type").is(type).orOperator(
    new Criteria().andOperator(regexBuilder("description", keywords)),
    new Criteria().andOperator(regexBuilder("notes", keywords)),
);


问:
What data type should I use for variable length with German characters?
What data type should I use for variable length with German characters?

I'm not sure the following is ok.

```<code>public const string stFIELD_DEFINITIONS = " fstInfo VARCHAR(100) CHARACTER SET UNICODE_FSS, fiKeyID INTEGER PRIMARY KEY ";
</code>```

"VARCHAR(x) CHARACTER SET UNICODE_FSS" is described as "fixed length" per https://firebirdsql.org/manual/migration-mssql-data-types.html.

答:
VARCHAR is not fixed-length, it only has a maximum length. It looks like a copy and paste error from the entry of nchar three lines above.

However that said, instead of UNICODE_FSS, you should use UTF8. The difference is that UNICODE_FSS is restricted to 1-3 bytes UTF-8 (the so called 'file system safe'-set), while UTF8 allows the full range. That  document seems to be a bit outdated to be honest, for example the equivalent of bigint is BIGINT, not INT64, and unique identifier would be better as a CHAR(16) CHARACTER SET OCTETS together with the UUID functions

Body:
What data type should I use for variable length with German characters?

I'm not sure the following is ok.

public const string stFIELD_DEFINITIONS = " fstInfo VARCHAR(100) CHARACTER SET UNICODE_FSS, fiKeyID INTEGER PRIMARY KEY ";

"VARCHAR(x) CHARACTER SET UNICODE_FSS" is described as "fixed length" per https://firebirdsql.org/manual/migration-mssql-data-types.html.


问:
Convert long format with only unique comparisons to full square matrix with the diag
Let's say I have that kind of input data
A file with a data.frame with data in long format, and only uniques comparisons between Species_A and Species_B as follow:

```<code>Species_A Species_B values
A B 58
A C 64
A D 78
A E 32
B C 10
B D 12
B E 54
C D 99
C E 84
D E 42
</code>```

I wonder how I can easily convert the input file into the square matrix

```<code>    A   B   C   D   E
A   100 58  64  78  32
B   58  100 10  12  54
C   64  10  100 99  84
D   78  12  99  100 42
E   32  54  84  42  100
</code>```

答:
Ok i finally did the trick</p>

```<code>1/ Add self comparison in the data table
2/ Use reshape(df, idvar = "Species_A", timevar = "Species_B", direction = "wide"), constructing sqaure matrix with NA as missing values
3/ reorder the matrix  row and column by counting NA ( in order to retrieve the lower or upper triangular matrix) and now we have half_matrix
4/ then fill the missing part of the matrix by sum the half_matrix and its transposed matrix
square_matrix_full = t(half_matrix) + half_matrix
5/ diag(square_matrix_full) = 100
</code>```

Body:
Let's say I have that kind of input data
A file with a data.frame with data in long format, and only uniques comparisons between Species_A and Species_B as follow:

Species_A Species_B values
A B 58
A C 64
A D 78
A E 32
B C 10
B D 12
B E 54
C D 99
C E 84
D E 42

I wonder how I can easily convert the input file into the square matrix

    A   B   C   D   E
A   100 58  64  78  32
B   58  100 10  12  54
C   64  10  100 99  84
D   78  12  99  100 42
E   32  54  84  42  100

Body:
Ok i finally did the trick

1/ Add self comparison in the data table
2/ Use reshape(df, idvar = "Species_A", timevar = "Species_B", direction = "wide"), constructing sqaure matrix with NA as missing values
3/ reorder the matrix  row and column by counting NA ( in order to retrieve the lower or upper triangular matrix) and now we have half_matrix
4/ then fill the missing part of the matrix by sum the half_matrix and its transposed matrix
square_matrix_full = t(half_matrix) + half_matrix
5/ diag(square_matrix_full) = 100


问:
Converting FORTRAN to C / C++
As part of my Final Year Project, I need to convert some FORTRAN code into C or C++ (it doesn't matter which language as long as I can understand it, and I can understand C style languages).

I have discovered f2c, a program that allegedly converts FORTRAN to C, and tried to install it, following instructions, by saving a makefile.vc file on my drive and then doing

```<code>copy makefile.vc makefile
nmake
</code>```

(here is the part of the README file about installing f2c that is included in the f2c download page)

To compile f2c on Linux or Unix
  systems, copy makefile.u to makefile,
  edit makefile if necessary (see the
  comments in it and below) and type
  "make" (or maybe "nmake", depending on
  your system).

To compile f2c.exe on MS Windows
  systems with Microsoft Visual C++,

copy makefile.vc makefile  nmake

With other PC compilers, you may need
  to compile xsum.c with -DMSDOS (i.e.,
  with MSDOS #defined).

If your compiler does not understand
  ANSI/ISO C syntax (i.e., if you have a
  K&R C compiler), compile with
  -DKR_headers .

On non-Unix systems where files have
  separate binary and text modes, you
  may need to "make xsumr.out" rather
  than "make xsum.out".

I am running x64 bit version of Windows Vista and tried "nmake", but I get

'nmake' is not recognised as an internal or external command, operable program or batch file.

I downloaded Nmake15.exe after some searching but it doesn't work on x64 bit machines and apparently there is not version of it that does. So I downloaded the Windows SDK, after being told that would work, but it didn't change anything.

Where have I gone wrong in all this, if I have, and is there any way of converting that FORTRAN code into C or C++?

答: Have you tried the binary?</p>

Title: Converting FORTRAN to C / C++

Body:
As part of my Final Year Project, I need to convert some FORTRAN code into C or C++ (it doesn't matter which language as long as I can understand it, and I can understand C style languages).

I have discovered f2c, a program that allegedly converts FORTRAN to C, and tried to install it, following instructions, by saving a makefile.vc file on my drive and then doing

copy makefile.vc makefile
nmake

(here is the part of the README file about installing f2c that is included in the f2c download page)

To compile f2c on Linux or Unix
  systems, copy makefile.u to makefile,
  edit makefile if necessary (see the
  comments in it and below) and type
  "make" (or maybe "nmake", depending on
  your system).

To compile f2c.exe on MS Windows
  systems with Microsoft Visual C++,

copy makefile.vc makefile  nmake

With other PC compilers, you may need
  to compile xsum.c with -DMSDOS (i.e.,
  with MSDOS #defined).

If your compiler does not understand
  ANSI/ISO C syntax (i.e., if you have a
  K&R C compiler), compile with
  -DKR_headers .

On non-Unix systems where files have
  separate binary and text modes, you
  may need to "make xsumr.out" rather
  than "make xsum.out".

I am running x64 bit version of Windows Vista and tried "nmake", but I get

'nmake' is not recognised as an internal or external command, operable program or batch file.

I downloaded Nmake15.exe after some searching but it doesn't work on x64 bit machines and apparently there is not version of it that does. So I downloaded the Windows SDK, after being told that would work, but it didn't change anything.

Where have I gone wrong in all this, if I have, and is there any way of converting that FORTRAN code into C or C++?

Body: Have you tried the binary?


问:
Can't download iOS app using in house at iOS 10.3 release version
I update the iOS to iOS 10.3 release version,

I try to download the in-house app through the safari,

but show the below error message(the log from device ).

```<code>  itunesstored(libsystem_network.dylib)[240] <Error>: nw_coretls_callback_handshake_message_block_invoke_3 tls_handshake_continue: [-9812]
  itunesstored(CFNetwork)[240] <Notice>:      NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
  itunesstored(CFNetwork)[240] <Error>: HTTP load failed (error code: -1202 [3:-9813])
  itunesstored(CFNetwork)[240] <Error>:      NSURLSessionTask finished with error - code: -1202
  itunesstored[240] <Notice>: LoadExternalDownloadManifestOperation: Request failed with error: <private>
  itunesstored[240] <Error>: Could not load download manifest with underlying error: <private>
</code>```

I test the in house to install at the iOS 10.2.1. It is install correct.

But the iOS 10.3 will show the alert ( cannot connect to IP ).

Have anyone known what happened in my case?

thank you very much.

答: I figured it out, it seems just trusting the certificate is no longer enough.  You need to go into General -> About (yes, About, what a great place) -> Certificate Trust Settings.  Then tick the switch next to your CA to trust it.

Body:
I update the iOS to iOS 10.3 release version,

I try to download the in-house app through the safari,

but show the below error message(the log from device ).

  itunesstored(libsystem_network.dylib)[240] <Error>: nw_coretls_callback_handshake_message_block_invoke_3 tls_handshake_continue: [-9812]
  itunesstored(CFNetwork)[240] <Notice>:      NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
  itunesstored(CFNetwork)[240] <Error>: HTTP load failed (error code: -1202 [3:-9813])
  itunesstored(CFNetwork)[240] <Error>:      NSURLSessionTask finished with error - code: -1202
  itunesstored[240] <Notice>: LoadExternalDownloadManifestOperation: Request failed with error: <private>
  itunesstored[240] <Error>: Could not load download manifest with underlying error: <private>

I test the in house to install at the iOS 10.2.1. It is install correct.

But the iOS 10.3 will show the alert ( cannot connect to IP ).

Have anyone known what happened in my case?

thank you very much.


问:
Exception in thread "StreamThread-1" java.lang.UnsatisfiedLinkError. Cannot load module /tmp/librocksdbjni*.so
I have created one kafka streaming application. In that, I am trying to aggregate a KStream into KTable. There, i have specified one statestore which is used internally by Kafka. However, on running the application, I am getting below error.

```<code>Exception in thread "StreamThread-1" java.lang.UnsatisfiedLinkError: /tmp/librocksdbjni858257496864179953.so (  0509-022 Cannot load module /tmp/librocksdbjni858257496864179953.so.
    0509-026 System error: Cannot run a file that does not have a valid format.)
    at java.lang.ClassLoader.loadLibraryWithPath(ClassLoader.java:1213)
    at java.lang.System.load(System.java:517)
    at org.rocksdb.NativeLibraryLoader.loadLibraryFromJar(NativeLibraryLoader.java:78)
    at org.rocksdb.NativeLibraryLoader.loadLibrary(NativeLibraryLoader.java:56)
    at org.rocksdb.RocksDB.loadLibrary(RocksDB.java:64)
    at org.rocksdb.RocksDB.<clinit>(RocksDB.java:35)
    at java.lang.J9VMInternals.initializeImpl(Native Method)
    at java.lang.J9VMInternals.initialize(J9VMInternals.java:236)
    at org.rocksdb.Options.<clinit>(Options.java:22)
    at java.lang.J9VMInternals.initializeImpl(Native Method)
    at java.lang.J9VMInternals.initialize(J9VMInternals.java:236)
    at org.apache.kafka.streams.state.internals.RocksDBStore.openDB(RocksDBStore.java:115)
    at org.apache.kafka.streams.state.internals.RocksDBStore.init(RocksDBStore.java:148)
    at org.apache.kafka.streams.state.internals.ChangeLoggingKeyValueBytesStore.init(ChangeLoggingKeyValueBytesStore.java:39)
    at org.apache.kafka.streams.state.internals.MeteredKeyValueStore$7.run(MeteredKeyValueStore.java:100)
    at org.apache.kafka.streams.processor.internals.StreamsMetricsImpl.measureLatencyNs(StreamsMetricsImpl.java:188)
    at org.apache.kafka.streams.state.internals.MeteredKeyValueStore.init(MeteredKeyValueStore.java:131)
    at org.apache.kafka.streams.state.internals.CachingKeyValueStore.init(CachingKeyValueStore.java:62)
    at org.apache.kafka.streams.processor.internals.AbstractTask.initializeStateStores(AbstractTask.java:86)
    at org.apache.kafka.streams.processor.internals.StreamTask.<init>(StreamTask.java:141)
    at org.apache.kafka.streams.processor.internals.StreamThread.createStreamTask(StreamThread.java:834)
    at org.apache.kafka.streams.processor.internals.StreamThread$TaskCreator.createTask(StreamThread.java:1207)
    at org.apache.kafka.streams.processor.internals.StreamThread$AbstractTaskCreator.retryWithBackoff(StreamThread.java:1180)
    at org.apache.kafka.streams.processor.internals.StreamThread.addStreamTasks(StreamThread.java:937)
    at org.apache.kafka.streams.processor.internals.StreamThread.access$500(StreamThread.java:69)
    at org.apache.kafka.streams.processor.internals.StreamThread$1.onPartitionsAssigned(StreamThread.java:236)
    at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.onJoinComplete(ConsumerCoordinator.java:255)
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.joinGroupIfNeeded(AbstractCoordinator.java:339)
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.ensureActiveGroup(AbstractCoordinator.java:303)
    at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.poll(ConsumerCoordinator.java:286)
    at org.apache.kafka.clients.consumer.KafkaConsumer.pollOnce(KafkaConsumer.java:1030)
    at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:995)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:582)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:368)
</code>```

Kafka version: 10.2.0

答:
This has been addressed here - https://github.com/facebook/rocksdb/issues/2071

We don't provide builds of the native component for AIX in the Jar file. As you are on AIX you will need to build your own.

Body:
I have created one kafka streaming application. In that, I am trying to aggregate a KStream into KTable. There, i have specified one statestore which is used internally by Kafka. However, on running the application, I am getting below error.

Exception in thread "StreamThread-1" java.lang.UnsatisfiedLinkError: /tmp/librocksdbjni858257496864179953.so (  0509-022 Cannot load module /tmp/librocksdbjni858257496864179953.so.
    0509-026 System error: Cannot run a file that does not have a valid format.)
    at java.lang.ClassLoader.loadLibraryWithPath(ClassLoader.java:1213)
    at java.lang.System.load(System.java:517)
    at org.rocksdb.NativeLibraryLoader.loadLibraryFromJar(NativeLibraryLoader.java:78)
    at org.rocksdb.NativeLibraryLoader.loadLibrary(NativeLibraryLoader.java:56)
    at org.rocksdb.RocksDB.loadLibrary(RocksDB.java:64)
    at org.rocksdb.RocksDB.<clinit>(RocksDB.java:35)
    at java.lang.J9VMInternals.initializeImpl(Native Method)
    at java.lang.J9VMInternals.initialize(J9VMInternals.java:236)
    at org.rocksdb.Options.<clinit>(Options.java:22)
    at java.lang.J9VMInternals.initializeImpl(Native Method)
    at java.lang.J9VMInternals.initialize(J9VMInternals.java:236)
    at org.apache.kafka.streams.state.internals.RocksDBStore.openDB(RocksDBStore.java:115)
    at org.apache.kafka.streams.state.internals.RocksDBStore.init(RocksDBStore.java:148)
    at org.apache.kafka.streams.state.internals.ChangeLoggingKeyValueBytesStore.init(ChangeLoggingKeyValueBytesStore.java:39)
    at org.apache.kafka.streams.state.internals.MeteredKeyValueStore$7.run(MeteredKeyValueStore.java:100)
    at org.apache.kafka.streams.processor.internals.StreamsMetricsImpl.measureLatencyNs(StreamsMetricsImpl.java:188)
    at org.apache.kafka.streams.state.internals.MeteredKeyValueStore.init(MeteredKeyValueStore.java:131)
    at org.apache.kafka.streams.state.internals.CachingKeyValueStore.init(CachingKeyValueStore.java:62)
    at org.apache.kafka.streams.processor.internals.AbstractTask.initializeStateStores(AbstractTask.java:86)
    at org.apache.kafka.streams.processor.internals.StreamTask.<init>(StreamTask.java:141)
    at org.apache.kafka.streams.processor.internals.StreamThread.createStreamTask(StreamThread.java:834)
    at org.apache.kafka.streams.processor.internals.StreamThread$TaskCreator.createTask(StreamThread.java:1207)
    at org.apache.kafka.streams.processor.internals.StreamThread$AbstractTaskCreator.retryWithBackoff(StreamThread.java:1180)
    at org.apache.kafka.streams.processor.internals.StreamThread.addStreamTasks(StreamThread.java:937)
    at org.apache.kafka.streams.processor.internals.StreamThread.access$500(StreamThread.java:69)
    at org.apache.kafka.streams.processor.internals.StreamThread$1.onPartitionsAssigned(StreamThread.java:236)
    at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.onJoinComplete(ConsumerCoordinator.java:255)
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.joinGroupIfNeeded(AbstractCoordinator.java:339)
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.ensureActiveGroup(AbstractCoordinator.java:303)
    at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.poll(ConsumerCoordinator.java:286)
    at org.apache.kafka.clients.consumer.KafkaConsumer.pollOnce(KafkaConsumer.java:1030)
    at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:995)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:582)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:368)

Kafka version: 10.2.0


问:
How to keep two databases with different schemas up-to-date
Our company has really old legacy system with such a bad database design (no foreign keys, columns with serialized PHP arrays, etc. :(). We decided to rewrite a system from a scratch with new database schema.

We want to rewrite a system by parts. So we will split old monolithic application to many smaller ones.

Problem is: we want to have live data in two databases. Old and New schema.
I'd like to ask you if anyone of you knows best practices how to do this.

What we think of:

asynchronous data synchronization with message queue

make a REST API in new system and make legacy application to use
    it instead of db calls

some kind of table replication

Thank you very much

答:
I had to deal with a similar problem in the past. There was a system which didn't have support but there was people using it because, It had some features (security holes) which allowed them certain functionalities. However, they also needed new functionalities.

I selected the tables which involved the new system and I created some triggers for cross update the tables, so when I created a register on the old system the trigger created a copy in the new system and reversal. If you design this system properly you would have both systems working at the same time in real time.

The drawback is that while the both system are running the system is going to become slower since you have to maintain the integrity of two databases in every operation.


问:
Filling the space supressed with the data below in report builder
Good day,

I am fairly new to report layouts and i require some assistance on Report Builder 3, i have developed my report and there is a section the gets supressed on a certain condition, i would like to move the data below into the space that is left vacant when the data is supressed.

Thanks,

Dean

答:
Use a list to hide it.

Create a new report

Right-click, add List

Put the first part (before the bit you want hiding) of the report into the new list box

Right-click on the (Details) group and group it on 1 (this makes it just show once - no repeating per page of something)

Right-click on the same group and click "Add Group - Adjacent After)

Group this on 1 as well

Insert a rectangle into the new textbox that shows

Add the items to this rectangle you wish to hide

Repeat steps 5-8 to add a new element below the bit you wish to hide

Should look like..

Right-click on the middle row group and select Group Properties

In the Visibility box, put your expression to determine when to show or hide the stuff you want to hide

When you run the report and the criteria for hiding are met then the row group will not generate and the bits below will move up (so no empty whitespace). It also makes it much easier to manage your report in the future as you know everything in that group will be hidden based on your criteria.


问:
How to pass the contents of the file in String format as a parameter to a java method from shell script?
I am calling a java method from shell script.It accepts String parameter. I am supposed to pass whole file content as a parameter.

Now from shell script I am getting the whole file Content using

orgFileContent=$(awk '$1=$1' ORS='\\n' $orgFile)

when I try to print this in sh..I am getting the whole content.But When I try to print this the called java method.I am just getting first two lines.

What will be the reason? How can I pass the whole file as a string?

Thanks in advance

答:
Just double quote the variable </p>

```<code>java -classpath CLASSPATH Main "$orgFileContent"
</code>```

Body:
Just double quote the variable

java -classpath CLASSPATH Main "$orgFileContent"


问:
Flux Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch
My code
https://gist.github.com/ButuzGOL/707d1605f63eef55e4af

So when I get sign-in success callback I want to make redirect,

redirect works through dispatcher too.

And I am getting Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.

Is there any hack to call action in the middle ?

答:
You can check if the dispatcher is dispatching, such as:</p>

```<code>if(!MyDispatcher.isDispatching()) {
    MyDispatcher.dispatch({...});
}
</code>```

Body:
You can check if the dispatcher is dispatching, such as:

if(!MyDispatcher.isDispatching()) {
    MyDispatcher.dispatch({...});
}


问:
Remove an If Statement after it has been fired once
Is there anyway of removing an if statement after it has been fired once?

I have a menu container that shows on page load and want it so when the user scrolls 1px it slides away.  I don't though want a the browser constantly tracking a scrollTop() method because of the performance hit from this.

What's the best way to remove or cancel an if statement after it has been used once?

The code is below and I have a codepen here: http://codepen.io/emilychews/pen/evbzMQ

jQuery(document).ready(function($) {
  $(window).scroll(function() {
    if ($(document).scrollTop() > 1) {
      $('.menubox').css('left', '-25%');
    }
  });

  $('.mybutton').on('click', function() {
    $('.menubox').css('left', '0%');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  padding: 0;
  height: 200vh;
}

.menubox {
  top: 100;
  position: fixed;
  width: 20%;
  height: 100%;
  background: red;
  padding: 10px;
  color: white;
  transition: all 1s;
}

.mybutton {
  position: fixed;
  left: 40%;
  top: 50px;
  padding: 5px 10px;
}</code>```

Menu Box

<button class="mybutton">menu</button>```

答:
You can call off() within the if statement to remove the event handler.

Also note that if you're concerned about performance you can debounce the event handler so that it only executes the logic once scrolling stops for N ms:

```<code>var scrollTimer;

$(window).scroll(function() {
  clearTimeout(scrollTimer)
  scrollTimer = setTimeout(function() {
    if ($(document).scrollTop() > 1) {
      $('.menubox').css('left', '-25%');
      $(window).off('scroll');
    }
  }, 150);
});
</code>```

Body:
Is there anyway of removing an if statement after it has been fired once?

I have a menu container that shows on page load and want it so when the user scrolls 1px it slides away.  I don't though want a the browser constantly tracking a scrollTop() method because of the performance hit from this.

What's the best way to remove or cancel an if statement after it has been used once?

The code is below and I have a codepen here: http://codepen.io/emilychews/pen/evbzMQ

jQuery(document).ready(function($) {
  $(window).scroll(function() {
    if ($(document).scrollTop() > 1) {
      $('.menubox').css('left', '-25%');
    }
  });

  $('.mybutton').on('click', function() {
    $('.menubox').css('left', '0%');
  });
});

body {
  margin: 0;
  padding: 0;
  height: 200vh;
}

.menubox {
  top: 100;
  position: fixed;
  width: 20%;
  height: 100%;
  background: red;
  padding: 10px;
  color: white;
  transition: all 1s;
}

.mybutton {
  position: fixed;
  left: 40%;
  top: 50px;
  padding: 5px 10px;
}

Menu Box

<button class="mybutton">menu</button>

Body:
You can call off() within the if statement to remove the event handler.

Also note that if you're concerned about performance you can debounce the event handler so that it only executes the logic once scrolling stops for N ms:

var scrollTimer;

$(window).scroll(function() {
  clearTimeout(scrollTimer)
  scrollTimer = setTimeout(function() {
    if ($(document).scrollTop() > 1) {
      $('.menubox').css('left', '-25%');
      $(window).off('scroll');
    }
  }, 150);
});


问:
Appending a line in sed doesn't work even with escape characters
I'm trying to use Bash scripts in Vagrant to automate the setup of an ELK stack. One of the nginx configuration files requires the right amount of indentation.

I tried:

```<code>sudo sed -i '28 a \ \ \ \ \ \ \ \ auth_basic_user_file /etc/nginx/htpasswd.users;' /etc/nginx/sites-available/default
</code>```

which should append a line that is 8 spaces away from the margin and right where I need it but when I check the configuration file, the spaces aren't added in.

I have successfully used:

```<code>sudo sed -i '73 a \ \ \ \ bika.lims' /usr/local/Plone/zeocluster/buildout.cfg
</code>```

in a different project before, which added the correct number of spaces.
Am I doing something wrong this time?

Thanks in advance.

答:
You can get indentation from line 28 and use it when you added new line.

For example, in /etc/nginx/sites-available/default in line 28 you have
something like this:

```<code>    # include snippets/snakeoil.conf;
</code>```

Then you can do this:

```<code>sudo sed -i 's,^\([[:space:]]*\).*include snippets/snakeoil.conf.*,&\n\1auth_basic_user_file /etc/nginx/htpasswd.users,' /etc/nginx/sites-available/default
</code>```

In substitute command s/regexp/replacement/ used comma as separator s,regexp,replacement,. It's help do not quote / inside regexp.

^\([[:space:]]*\).*include snippets/snakeoil.conf.* regexp to match line with # include snippets/snakeoil.conf;

2.1 ^\([[:space:]]*\) matching sub-expressions group\(\). Match all spaces from beginning of the line. Now it can be refer with special escapes \1 (see step 3.3).

&\n\1auth_basic_user_file /etc/nginx/htpasswd.users this what will be replaced.

3.1 & -  special character & to refer to that portion of the pattern space which matched. So it's just preserving old line
# include snippets/snakeoil.conf; on place.

3.2 \n - new line

3.3 \1 - special escapes \1 to refer to the sub-expressions from step 2.1

3.4 auth_basic_user_file /etc/nginx/htpasswd.users - text what need to be added

Body:
I'm trying to use Bash scripts in Vagrant to automate the setup of an ELK stack. One of the nginx configuration files requires the right amount of indentation.

I tried:

sudo sed -i '28 a \ \ \ \ \ \ \ \ auth_basic_user_file /etc/nginx/htpasswd.users;' /etc/nginx/sites-available/default

which should append a line that is 8 spaces away from the margin and right where I need it but when I check the configuration file, the spaces aren't added in.

I have successfully used:

sudo sed -i '73 a \ \ \ \ bika.lims' /usr/local/Plone/zeocluster/buildout.cfg

in a different project before, which added the correct number of spaces.
Am I doing something wrong this time?

Thanks in advance.

Body:
You can get indentation from line 28 and use it when you added new line.

For example, in /etc/nginx/sites-available/default in line 28 you have
something like this:

    # include snippets/snakeoil.conf;

Then you can do this:

sudo sed -i 's,^\([[:space:]]*\).*include snippets/snakeoil.conf.*,&\n\1auth_basic_user_file /etc/nginx/htpasswd.users,' /etc/nginx/sites-available/default

In substitute command s/regexp/replacement/ used comma as separator s,regexp,replacement,. It's help do not quote / inside regexp.

^\([[:space:]]*\).*include snippets/snakeoil.conf.* regexp to match line with # include snippets/snakeoil.conf;

2.1 ^\([[:space:]]*\) matching sub-expressions group\(\). Match all spaces from beginning of the line. Now it can be refer with special escapes \1 (see step 3.3).

&\n\1auth_basic_user_file /etc/nginx/htpasswd.users this what will be replaced.

3.1 & -  special character & to refer to that portion of the pattern space which matched. So it's just preserving old line
# include snippets/snakeoil.conf; on place.

3.2 \n - new line

3.3 \1 - special escapes \1 to refer to the sub-expressions from step 2.1

3.4 auth_basic_user_file /etc/nginx/htpasswd.users - text what need to be added


问:
issues loading items from firebase to a pickerview
I have successfully created a QuestionModel class which retrieves items from firebase such, as a Question, string of answers and a correct question. I am however now having difficulty in terms of getting these items to go into a picker view from another class. The class called QuestionsViewController is where I am having an issue in terms of using the questions class to retrieve data from. The QuestionModel class contains retrieving data from firebase. I am having bad execution errors throughout the code in the QuestionsViewController class. This mainly occurs when trying to set the itemlabel text before the pickverview and code for the pickerview functions. </p>

```<code>import Foundation
import Firebase
import FirebaseDatabase
import FirebaseAuth
import CoreData

class QuestionList
{
//properties
public static var Username: String = ""
private static var quiz = [Question]()

static func getDummyQuestions()->[Question]
{
    //create some dummy data for the model
    var ref: FIRDatabaseReference!
    var refHandle: UInt!
    ref = FIRDatabase.database().reference() //reference

    refHandle = ref.child("Questions").child("Q1").observe(.value,       with: { (snapshot)in
        if let dataDict = snapshot.value as? [String: Any] {

            if let quest = dataDict["Question"] as? String,
                let Answers = dataDict["Answers"] as? [String],
                let Correct = dataDict["Correct"] as? Int {
                quiz.append(Question(q: quest, a: Answers, c: Correct))
            }
            print (dataDict)
        }
    })
    return quiz
  }
}

class Question {
  var quest:String
  var answers:[String]
  var correct:Int

  init(q: String, a:[String], c:Int)
  {
      quest = q
      answers = a
      correct = c
  }

  func isCorrectQuestion(itemSelected: String)->Bool {
      if (itemSelected == answers[correct]) {
          return true
      } else {
          return false
      }
  }
}

import UIKit
import Firebase
import FirebaseAuth

class QuestionsViewController: UIViewController, UIPickerViewDelegate {

@IBOutlet weak var usernamelabel: UILabel! //sets username label
@IBOutlet weak var Next: UIButton! //next button
@IBOutlet weak var itemLabel: UILabel! //item user has selected
@IBOutlet weak var Question: UILabel! //sets question label
@IBOutlet weak var pickerview: UIPickerView! //sets picker view

public var totalQuestions: Int = 0 //sets total question to 0
public var currentQuestion = 0  //sets current question to 0
public var totalCorrect: Int = 0 //sets totalcorrect to 0
var itemSelected: String = "" //item selected
var LabelText = String()
let Exam = QuestionList() //uses the questions class for instances
var Questions = QuestionList.getDummyQuestions()

var ref: FIRDatabaseReference!
var refHandle: UInt!

override func viewDidLoad() {
    super.viewDidLoad() //when the app is loaded

    ref = FIRDatabase.database().reference() //reference
    refHandle = ref.child("Questions").observe(.value, with: { (snapshot)in
        let dataDict = snapshot.value as! [String: AnyObject]
        print (dataDict)
    })
     usernamelabel.text = LabelText //username

    pickerview.delegate = self

    itemLabel.text = "" //loads the item label of whats selected
    itemSelected = QuestionList.getDummyQuestions()[currentQuestion].answers[0] //initially when loaded first item is selected
    Question.text = QuestionList.getDummyQuestions()[currentQuestion].quest
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1 //return one component from the picker
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
    return QuestionList.getDummyQuestions()[currentQuestion].answers.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int,    forComponent component: Int) -> String?{
    return QuestionList.getDummyQuestions().  [currentQuestion].answers[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){

    itemSelected = QuestionList.getDummyQuestions(). [currentQuestion].answers[row]
}

@IBAction func NextAction(_ sender: Any){

   currentQuestion = currentQuestion + 1 //moves onto next question and   increments

    if (QuestionList.getDummyQuestions()[currentQuestion].isCorrectQuestion(itemSelected: itemSelected)) {
        totalCorrect += 1
        itemLabel.text = String(totalCorrect) + "/" + String(totalQuestions)
    }

    if(currentQuestion < QuestionList.getDummyQuestions().count) {
        pickerview.reloadAllComponents()
        itemSelected = QuestionList.getDummyQuestions()[currentQuestion].answers[1]
        Question.text = QuestionList.getDummyQuestions() [currentQuestion].quest
    } else {
        pickerview.isHidden = true
        Question.text = "You have finished"
        Next.isHidden = true
    }
}
</code>```

<p>}</p>

答:
Firebase functions do not (and should not) return values as they are asynchronous.

So the return quiz line will fail most of the time as it will try to return data before Firebase has had time to retrieve it from the server.

When coding with Firebase, data is only valid inside the closure following the function. So for example, this what NOT to do:

```<code>func someFunc() {
    ref.child("Questions").child("Q1").observe(.value, with: { snapshot in
      print(snap)
    })

    print(snap) //this will not print the snap as this line executes *before* the closure
}
</code>```

So doing it the right way; retrieve the data from Firebase, populate the array and refresh the tableview all within the closure.

```<code>static func populateArrayAndRefreshTableView()
{
    var ref: FIRDatabaseReference!= FIRDatabase.database().reference()
    let questionsRef = ref.child("Questions")

    questionsRef.child("Q1").observeSingleEvent(of: .value, with: { snapshot in
        if let dataDict = snapshot.value as? [String: Any] {
            let quest = dataDict["Question"] as? String,
            let Answers = dataDict["Answers"] as? [String],
            let Correct = dataDict["Correct"] as? Int {
            self.quizArray.append(Question(q: quest, a: Answers, c: Correct))
            self.tableView.reloadData()
        }
    })
  }
}
</code>```

Also note that the original code was using observe(.value). That will leave an observer attached to the ref and if the question changes, the code will be called. It doesn't look like that should be the behavior so using observeSingleEvent will call it once without adding an observer.

Finally - you may want to re-consider how the nodes are named in your structure. It's often best practice to disassociate node name keys from the data they contain.

```<code>questions
   -UYiuokoksokda
      question: "What significant contribution to bioengineering was made on the Loonkerian outpost on Klendth?"
      correct_answer: answer_1
      answers:
        answer_0: "Left handed smoke shifter"
        answer_1: "The universal atmospheric element compensator"
        answer_2: "Warp coil nullification amplifier"
        answer_3: "H.A.L. 9000"
   -YY8jioijasdjd
      question: "What is Kiri-kin-tha's first law of metaphysics?"
      correct_answer: answer_2
      answers:
        answer_0: "No matter where you go, there you are"
        answer_1: "Only people with sunroofs use them"
        answer_2: "Nothing unreal exists"
        answer_3: "Gravity is heavy"
</code>```

The keys, UYiuokoksokda, are created with childByAutoId().

If you need to query answers you may want to even denormalize them into their own node and use the question key as the node key for the answers or keep a child node with the question key.

Body:
I have successfully created a QuestionModel class which retrieves items from firebase such, as a Question, string of answers and a correct question. I am however now having difficulty in terms of getting these items to go into a picker view from another class. The class called QuestionsViewController is where I am having an issue in terms of using the questions class to retrieve data from. The QuestionModel class contains retrieving data from firebase. I am having bad execution errors throughout the code in the QuestionsViewController class. This mainly occurs when trying to set the itemlabel text before the pickverview and code for the pickerview functions.

import Foundation
import Firebase
import FirebaseDatabase
import FirebaseAuth
import CoreData

class QuestionList
{
//properties
public static var Username: String = ""
private static var quiz = [Question]()

static func getDummyQuestions()->[Question]
{
    //create some dummy data for the model
    var ref: FIRDatabaseReference!
    var refHandle: UInt!
    ref = FIRDatabase.database().reference() //reference

    refHandle = ref.child("Questions").child("Q1").observe(.value,       with: { (snapshot)in
        if let dataDict = snapshot.value as? [String: Any] {

            if let quest = dataDict["Question"] as? String,
                let Answers = dataDict["Answers"] as? [String],
                let Correct = dataDict["Correct"] as? Int {
                quiz.append(Question(q: quest, a: Answers, c: Correct))
            }
            print (dataDict)
        }
    })
    return quiz
  }
}

class Question {
  var quest:String
  var answers:[String]
  var correct:Int

  init(q: String, a:[String], c:Int)
  {
      quest = q
      answers = a
      correct = c
  }

  func isCorrectQuestion(itemSelected: String)->Bool {
      if (itemSelected == answers[correct]) {
          return true
      } else {
          return false
      }
  }
}

import UIKit
import Firebase
import FirebaseAuth

class QuestionsViewController: UIViewController, UIPickerViewDelegate {

@IBOutlet weak var usernamelabel: UILabel! //sets username label
@IBOutlet weak var Next: UIButton! //next button
@IBOutlet weak var itemLabel: UILabel! //item user has selected
@IBOutlet weak var Question: UILabel! //sets question label
@IBOutlet weak var pickerview: UIPickerView! //sets picker view

public var totalQuestions: Int = 0 //sets total question to 0
public var currentQuestion = 0  //sets current question to 0
public var totalCorrect: Int = 0 //sets totalcorrect to 0
var itemSelected: String = "" //item selected
var LabelText = String()
let Exam = QuestionList() //uses the questions class for instances
var Questions = QuestionList.getDummyQuestions()

var ref: FIRDatabaseReference!
var refHandle: UInt!

override func viewDidLoad() {
    super.viewDidLoad() //when the app is loaded

    ref = FIRDatabase.database().reference() //reference
    refHandle = ref.child("Questions").observe(.value, with: { (snapshot)in
        let dataDict = snapshot.value as! [String: AnyObject]
        print (dataDict)
    })
     usernamelabel.text = LabelText //username

    pickerview.delegate = self

    itemLabel.text = "" //loads the item label of whats selected
    itemSelected = QuestionList.getDummyQuestions()[currentQuestion].answers[0] //initially when loaded first item is selected
    Question.text = QuestionList.getDummyQuestions()[currentQuestion].quest
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1 //return one component from the picker
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
    return QuestionList.getDummyQuestions()[currentQuestion].answers.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int,    forComponent component: Int) -> String?{
    return QuestionList.getDummyQuestions().  [currentQuestion].answers[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){

    itemSelected = QuestionList.getDummyQuestions(). [currentQuestion].answers[row]
}

@IBAction func NextAction(_ sender: Any){

   currentQuestion = currentQuestion + 1 //moves onto next question and   increments

    if (QuestionList.getDummyQuestions()[currentQuestion].isCorrectQuestion(itemSelected: itemSelected)) {
        totalCorrect += 1
        itemLabel.text = String(totalCorrect) + "/" + String(totalQuestions)
    }

    if(currentQuestion < QuestionList.getDummyQuestions().count) {
        pickerview.reloadAllComponents()
        itemSelected = QuestionList.getDummyQuestions()[currentQuestion].answers[1]
        Question.text = QuestionList.getDummyQuestions() [currentQuestion].quest
    } else {
        pickerview.isHidden = true
        Question.text = "You have finished"
        Next.isHidden = true
    }
}

}

Body:
Firebase functions do not (and should not) return values as they are asynchronous.

So the return quiz line will fail most of the time as it will try to return data before Firebase has had time to retrieve it from the server.

When coding with Firebase, data is only valid inside the closure following the function. So for example, this what NOT to do:

func someFunc() {
    ref.child("Questions").child("Q1").observe(.value, with: { snapshot in
      print(snap)
    })

    print(snap) //this will not print the snap as this line executes *before* the closure
}

So doing it the right way; retrieve the data from Firebase, populate the array and refresh the tableview all within the closure.

static func populateArrayAndRefreshTableView()
{
    var ref: FIRDatabaseReference!= FIRDatabase.database().reference()
    let questionsRef = ref.child("Questions")

    questionsRef.child("Q1").observeSingleEvent(of: .value, with: { snapshot in
        if let dataDict = snapshot.value as? [String: Any] {
            let quest = dataDict["Question"] as? String,
            let Answers = dataDict["Answers"] as? [String],
            let Correct = dataDict["Correct"] as? Int {
            self.quizArray.append(Question(q: quest, a: Answers, c: Correct))
            self.tableView.reloadData()
        }
    })
  }
}

Also note that the original code was using observe(.value). That will leave an observer attached to the ref and if the question changes, the code will be called. It doesn't look like that should be the behavior so using observeSingleEvent will call it once without adding an observer.

Finally - you may want to re-consider how the nodes are named in your structure. It's often best practice to disassociate node name keys from the data they contain.

questions
   -UYiuokoksokda
      question: "What significant contribution to bioengineering was made on the Loonkerian outpost on Klendth?"
      correct_answer: answer_1
      answers:
        answer_0: "Left handed smoke shifter"
        answer_1: "The universal atmospheric element compensator"
        answer_2: "Warp coil nullification amplifier"
        answer_3: "H.A.L. 9000"
   -YY8jioijasdjd
      question: "What is Kiri-kin-tha's first law of metaphysics?"
      correct_answer: answer_2
      answers:
        answer_0: "No matter where you go, there you are"
        answer_1: "Only people with sunroofs use them"
        answer_2: "Nothing unreal exists"
        answer_3: "Gravity is heavy"

The keys, UYiuokoksokda, are created with childByAutoId().

If you need to query answers you may want to even denormalize them into their own node and use the question key as the node key for the answers or keep a child node with the question key.


问:
Plotting the cell array in MATLAB
I have two 1-D cell arrays with numbers inside, how can I plot this?

```<code>X = {'1' '2' '35' }
Y = {'23' '30' '90' }
</code>```

I am trying to plot the two cell arrays using plot command:

```<code>plot (X,Y);
</code>```

And I received the following the error:

```<code>Not enough input arguments.
</code>```

Any suggestions?

答:
You need to first convert your cell arrays of strings to an array of numbers. You can do this using str2double

```<code>X = {'1' '2' '35' }
Y = {'23' '30' '90' }

plot(str2double(X), str2double(Y))
</code>```

Title: Plotting the cell array in MATLAB

Body:
I have two 1-D cell arrays with numbers inside, how can I plot this?

X = {'1' '2' '35' }
Y = {'23' '30' '90' }

I am trying to plot the two cell arrays using plot command:

plot (X,Y);

And I received the following the error:

Not enough input arguments.

Any suggestions?

Body:
You need to first convert your cell arrays of strings to an array of numbers. You can do this using str2double

X = {'1' '2' '35' }
Y = {'23' '30' '90' }

plot(str2double(X), str2double(Y))


问:
Passing a Varible through a form
I am still new to PHP but I have been making good progress on my site. However I seem to have hit a bit of a roadblock. I have a page that has a URL and in that URL there is a category Identifier. so it looks like;

```<code>www.website.com/createpage?cat=1
</code>```

Now in the previous pages I have been passing the variable from page to page doing the following;

```<code>$cat = $_GET['cat'];
<a href="nextpage.php?cat=$cat">
</code>```

However I have now come to the point where I need to use a form to process the information. I have a special script that runs on submit using the action= attribute.

If I try amending the link there to like the ones above, it just passes a string '$cat' through. I have read on several topics here that I can achieve the same thing by creating a hidden field in a form and calling it out on the new page like I would with the rest of the information. But in both cases it only passes a string through. If I echo the variable on the form before submission it reports the correct number, and if I put the processing script on the same page as the form it gets further than it does without (i have an error somewhere at the bottom of my script but I was expecting that)

Is there anything special about passing through values on forms that I am missing? Everyone post I read makes it sound simple, but I am struggling to replicate it on my own script.

I can post the script, but it is a hell of a long one.

```<code>echo '<form action="topic_process.php" method="POST">
    <p>Topic Subject:<input name="topic_subject" type="text"></p><br>
    <p>Post: <textarea name="post_content"></textarea></p><br>
    <input type="hidden" name="cat" value="$cat">
    <p><input type="submit" value="Create"></p>';
</code>```

答:
You can write it into a hidden input field of that form:

First, in PHP:

```<code>$cat = $_GET['cat'];
</code>```

Later on, inside the HTML form:

```<code><input type="hidden" value="<?php echo $cat; ?>" name="cat">
</code>```

This will pass that value to the form processing page as a  POST variable, which can be fetched (like all the other input values) as $_POST['cat']

Title: Passing a Varible through a form

Body:
I am still new to PHP but I have been making good progress on my site. However I seem to have hit a bit of a roadblock. I have a page that has a URL and in that URL there is a category Identifier. so it looks like;

www.website.com/createpage?cat=1

Now in the previous pages I have been passing the variable from page to page doing the following;

$cat = $_GET['cat'];

However I have now come to the point where I need to use a form to process the information. I have a special script that runs on submit using the action= attribute.

If I try amending the link there to like the ones above, it just passes a string '$cat' through. I have read on several topics here that I can achieve the same thing by creating a hidden field in a form and calling it out on the new page like I would with the rest of the information. But in both cases it only passes a string through. If I echo the variable on the form before submission it reports the correct number, and if I put the processing script on the same page as the form it gets further than it does without (i have an error somewhere at the bottom of my script but I was expecting that)

Is there anything special about passing through values on forms that I am missing? Everyone post I read makes it sound simple, but I am struggling to replicate it on my own script.

I can post the script, but it is a hell of a long one.

echo '<form action="topic_process.php" method="POST">

Topic Subject:<input name="topic_subject" type="text">

Post: <textarea name="post_content"></textarea>

    <input type="hidden" name="cat" value="$cat">

<input type="submit" value="Create">
';

Body:
You can write it into a hidden input field of that form:

First, in PHP:

$cat = $_GET['cat'];

Later on, inside the HTML form:

<input type="hidden" value="<?php echo $cat; ?>" name="cat">

This will pass that value to the form processing page as a  POST variable, which can be fetched (like all the other input values) as $_POST['cat']


问:
dig -x +short to file without STDERR
When I do:
dig -x  +short
I get only the hosts output,
but when doing dig -x <ip> +short > file.txt I get all the rubbish, as if it was not executed with +short.

I have tried:

```<code>dig -x <ip> +short 2>&1 > file.txt
</code>```

also

```<code>dig -x <ip> +short 2>/dev/null > file.txt
</code>```

But didn't work, Thank you

答:
As @anubhava observed in a comment, ordering matters:</p>

```<code>dig +short -x "$ip"
</code>```

Title: dig -x +short to file without STDERR

Body:
When I do:
dig -x  +short
I get only the hosts output,
but when doing dig -x <ip> +short > file.txt I get all the rubbish, as if it was not executed with +short.

I have tried:

dig -x <ip> +short 2>&1 > file.txt

also

dig -x <ip> +short 2>/dev/null > file.txt

But didn't work, Thank you

Body:
As @anubhava observed in a comment, ordering matters:

dig +short -x "$ip"


问:
Python OOP - Should def main() be outside of any class in a .py file?
I have a question when it comes to OOP in general, as well as Python in particular. Let's say that I have, for instance, priorities.py - a simple GUI program to manage priorities and there are three classes: Priority, Client, GuiPart:

```<code># priorities.py
#   GUI program to manage priorities

from tkinter import *

class Priority:
    pass

class GuiPart:
    def __init__(self):
        self.root = self.createWindow()

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title("Priorities")

        return root

    def display(self):

        Label(self.root,
              text = "testes").grid(row = 0, column = 1)

class Client:
    pass

def main():
    g = GuiPart()
    g.display()
    root = g.root.mainloop()

main()
</code>```

Should I put def main() outside of any classes, or should I put it in Client class?

答:
My preferred approach:

separate main file with the if __name__ == '__main__': directive

Reasons:

Application Logic and calling logic is separate. so you can scale easily

Can maintain and apply different environment settings effectively. so, we can seamlessly transition between dev/test/stage/prod setup

Increases code readability as well

Body:
I have a question when it comes to OOP in general, as well as Python in particular. Let's say that I have, for instance, priorities.py - a simple GUI program to manage priorities and there are three classes: Priority, Client, GuiPart:

# priorities.py
#   GUI program to manage priorities

from tkinter import *

class Priority:
    pass

class GuiPart:
    def __init__(self):
        self.root = self.createWindow()

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title("Priorities")

        return root

    def display(self):

        Label(self.root,
              text = "testes").grid(row = 0, column = 1)

class Client:
    pass

def main():
    g = GuiPart()
    g.display()
    root = g.root.mainloop()

main()

Should I put def main() outside of any classes, or should I put it in Client class?


答: If I had to install f2c on Windows I would use Cygwin. Now there is g77 I expect not many people use f2c any more.</p>

Title: Converting FORTRAN to C / C++

Body:
As part of my Final Year Project, I need to convert some FORTRAN code into C or C++ (it doesn't matter which language as long as I can understand it, and I can understand C style languages).

I have discovered f2c, a program that allegedly converts FORTRAN to C, and tried to install it, following instructions, by saving a makefile.vc file on my drive and then doing

copy makefile.vc makefile
nmake

(here is the part of the README file about installing f2c that is included in the f2c download page)

To compile f2c on Linux or Unix
  systems, copy makefile.u to makefile,
  edit makefile if necessary (see the
  comments in it and below) and type
  "make" (or maybe "nmake", depending on
  your system).

To compile f2c.exe on MS Windows
  systems with Microsoft Visual C++,

copy makefile.vc makefile  nmake

With other PC compilers, you may need
  to compile xsum.c with -DMSDOS (i.e.,
  with MSDOS #defined).

If your compiler does not understand
  ANSI/ISO C syntax (i.e., if you have a
  K&R C compiler), compile with
  -DKR_headers .

On non-Unix systems where files have
  separate binary and text modes, you
  may need to "make xsumr.out" rather
  than "make xsum.out".

I am running x64 bit version of Windows Vista and tried "nmake", but I get

'nmake' is not recognised as an internal or external command, operable program or batch file.

I downloaded Nmake15.exe after some searching but it doesn't work on x64 bit machines and apparently there is not version of it that does. So I downloaded the Windows SDK, after being told that would work, but it didn't change anything.

Where have I gone wrong in all this, if I have, and is there any way of converting that FORTRAN code into C or C++?