text:
Q: How can I rebuild if the width of the screen changes in web? What I want to achieve is, when the web screen width changes, check if you can add or remove a Widget, and rebuild. The problem I'm having is that when the web screen changes it doesn't rebuild it and some Widgets stays hidden because there is no more screen in there or it should add more Widgets in the line.
The two packages I'm using responsive_builder and flutter_staggered_grid_view.
My code:
List<double> _createSizes() {
  Random random = new Random();
  return List.generate(22, (i) => kDefaultHeightImageFeed + random.nextInt(76));
}

class ImageFeed extends StatelessWidget {
  ImageFeed() : _heights = _createSizes();
  final List<double> _heights;
  @override
  Widget build(BuildContext context) {
    return ResponsiveBuilder(
      builder: (context, sizingInformation) {
        double widthScreen = MediaQuery.of(context).size.width;
        int horizontalValue = 2;
        int tileQuantity = 22;

        if (sizingInformation.deviceScreenType == DeviceScreenType.mobile)
          horizontalValue = (widthScreen - 40.0) ~/ 200;
        else if (sizingInformation.deviceScreenType == DeviceScreenType.tablet)
          horizontalValue = (widthScreen - 40.0) ~/ 200;
        else if (sizingInformation.deviceScreenType == DeviceScreenType.desktop)
          horizontalValue = (widthScreen - kDefaultWebPadding) ~/ 250;

        return StaggeredGridView.countBuilder(
          primary: false,
          crossAxisCount: horizontalValue,
          mainAxisSpacing: 10.0,
          crossAxisSpacing: 10.0,
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemCount: tileQuantity,
          staggeredTileBuilder: (index) => StaggeredTile.fit(1),
          itemBuilder: (context, index) => ImageFeedDesign(
            image:
                'https://images.unsplash.com/photo-1537953773345-d172ccf13cf1?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80',
            place: index.toString(),
            height: _heights[index],
          ),
        );
      },
    );
  }
}

ImageFeedDesign code:
class ImageFeedDesign extends StatelessWidget {
  ImageFeedDesign({this.image, this.place, this.height});
  final String image;
  final String place;
  final String distance = '2.834 km';
  final double height;
  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () => Application.router.navigateTo(context, kPlaceRoute + place,
          transition: TransitionType.none),
      child: Stack(
        children: [
          Container(
            // constraints: BoxConstraints(maxWidth: 600),
            height: height,
            decoration: BoxDecoration(
              image: DecorationImage(
                fit: BoxFit.fill,
                image: NetworkImage(image),
              ),
              borderRadius: BorderRadius.all(Radius.circular(15.0)),
            ),
          ),
          Positioned(
            bottom: 10,
            left: 15,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  place,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: kWhite,
                    fontWeight: FontWeight.bold,
                    fontSize: 16.0,
                  ),
                ),
                const SizedBox(height: 2.0),
                Text(
                  distance,
                  style: TextStyle(color: kWhite),
                ),
              ],
            ),
          ),
          Positioned(bottom: 10, right: 15, child: kInstagramLigth),
        ],
      ),
    );
  }
}

Problem in video:
https://youtu.be/VNxFuLoY6G4

A: List<double> _createSizes() {
  final random = Random();
  return List.generate(40, (i) => 120.0 + random.nextInt(100));
}

class ImageFeed extends StatelessWidget {
  ImageFeed() : _heights = _createSizes();
  final List<double> _heights;

  @override
  Widget build(BuildContext context) {
    return ResponsiveBuilder(
      builder: (context, sizingInformation) {
        int tileQuantity = _heights.length;
        double widthScreen = MediaQuery.of(context).size.width;

        late int horizontalValue;
        if (sizingInformation.deviceScreenType == DeviceScreenType.desktop) {
          horizontalValue = (widthScreen - 40.0) ~/ 250;
        } else {
          horizontalValue = (widthScreen - 40.0) ~/ 200;
        }

        return StaggeredGridView.countBuilder(
          mainAxisSpacing: 10.0,
          crossAxisSpacing: 10.0,
          crossAxisCount: max(1, horizontalValue),
          itemCount: tileQuantity,
          staggeredTileBuilder: (index) => StaggeredTile.fit(1),
          itemBuilder: (context, index) => Container(
            height: _heights[index],
            child: Image.network(
              'https://images.unsplash.com/photo-1537953773345-d172ccf13cf1?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80',
              fit: BoxFit.cover,
            ),
          ),
        );
      },
    );
  }
}

Edit after running your project from github, I've noticed that StaggeredGridView doesn't render it's children properly. After hot restart the problem isn't there.


text:
Q: Applying inferential statistics for census data Let's assume I have a census data of a population which I would like to study and it has variables such as age, gender, sex, occupation etc and the dependent variable which is community participation of the population is in the form of numerical data (mean score). Is it appropriate to apply inferential statistics such as t test, ANOVA etc. to find out the variance/difference between the independent variables such as age group (such as young,middle, and old), sex (male/female), occupation (four categories), level of education (five categories)?

A: If your census is of the -entire population-, I do not think so.  For example, the mean age of NYC in 2011 might be 45. The mean age of SFC in that same year is 46. You can conclude they are not the the same... because you've counted all of them, a full population census count. The question ceases to be statistical.
This depends heavily on a frequentist view of the world, and the idea that it is a full population census, excluding no one. Some Bayesian may be able to argue differently, but their techniques will also be different.

A: You can test hypotheses if you want to generalize your findings beyond the original population; this is the practical meaning of the superpopulation model.  This would apply for a causal and predictive modeling study, or for what Deming calls an "analytic" study. For another related thread, with references, see: Adjusting any power analysis with FPC?
Only you know your study goal. However your proposal to test associations with every demographic/personal variable does not describe a study with a focused set of questions. Nor does it describe a predictive analysis. This might be an analytic analysis, but the inferences will not be strong. Go ahead and test hypotheses; be sure to adjust p-values for multiple comparisons.
Reference
Deming, W. E. (1966). Some theory of sampling. New York: Dover Publications.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como deixar imageView atras dos botoes? como o ramaral postou sete código:
No Layout da sua Activity tem de declarar uma ImageView
Se quiser que ela seja apenas visível após carregar num botão deverá incluir o atributo android:visibility="invisible"
<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/imageView1"
    android:visibility="invisible"
    android:src="@drawable/nomeDaSuaImagem" />
No código da Activity, no onClick do botão, torne-a visível:
`Button button1;
ImageView imageView1;
imageView1 = (ImageView)findViewById(R.id.imageView1);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

    imageView1.setVisibility(View.VISIBLE;
}

});`
eu gostaria de saber se tem como ela deixar escondidas atrás  dos botões .

A: Para montar um layout com sobreposição no eixo Z basta usar o FrameLayout.
O FrameLayout desenha as View's empilhando as mesmas conforme a ordem em que foram declaradas.
Exemplo:

Para trazer uma View para o topo, só usar o método: View.bringToFront, que vai modificar a ordem das View's na lista que o pai mantém. Para dispositivos anteriores ao KitKat (4.4), basta chamar requestLayout e depois invalidate na própria View.
Referências: http://android-developers.blogspot.com.br/2011/09/thinking-like-web-designer.html


text:
Q: Peculiar result relating to struct size and performance I was curious on the overhead of a large structure vs. a small structure in using operators + and * for math. So I made two struct, one Small with 1 double field (8 bytes) and one Big with 10 doubles (80 bytes). In all my operations I only manipulate one field called x.
First I defined in both structures mathematical operators like
public static Small operator +(Small a, Small b)
{
    return new Small(a.x + b.x);
}
public static Small operator *(double x, Small a)
{
    return new Small(x * a.x);
}

which as expected use up a lot of memory in the stack for copying fields around. I run 5,000,000 iterations of a mathematical operation and got what I suspected (3 times slowdown).
public double TestSmall()
{
    pt.Start(); // pt = performance timing object
    Small r = new Small(rnd.NextDouble()); //rnd = Random number generator
    for (int i = 0; i < N; i++)
    {
        a = 0.6 * a + 0.4 * r;   // a is a local field of type Small
    }
    pt.Stop();
    return pt.ElapsedSeconds;
}

results from Release code (in seconds)
Small=0.33940 Big=0.98909     Big is Slower by x2.91

Now for the interesting part. I define the same operations with static methods with ref arguments
public static void Add(ref Small a, ref Small b, ref Small res)
{
    res.x = a.x + b.x;
}
public static void Scale(double x, ref Small a, ref Small res)
{
    res.x = x * a.x;
}

and run the same number of iterations on this test code:
public double TestSmall2()
{
    pt.Start(); // pt = performance timing object
    Small a1 = new Small(); // local
    Small a2 = new Small(); // local
    Small r = new Small(rnd.NextDouble()); //rdn = Random number generator
    for (int i = 0; i < N; i++)
    {
        Small.Scale(0.6, ref a, ref a1);
        Small.Scale(0.4, ref r, ref a2);
        Small.Add(ref a1, ref a2, ref a);
    }
    pt.Stop();
    return pt.ElapsedSeconds;
}

And the results show (in seconds)
Small=0.11765 Big=0.07130     Big is Slower by x0.61

So compared to the mem-copy intensive operators I get a speedup of x3 and x14 which is great, but compare the Small struct times to the Big and you will see that Small is 60% slower than Big.
Can anyone explain this? Does it have to do with CPU pipeline and separating out operations in (spatially) memory makes for more efficient pre-fetch of data?
If you want to try this for yourself grab the code from my dropbox http://dl.dropbox.com/u/11487099/SmallBigCompare.zip

A: There appear to be a couple of flaws in your benchmark.

*

*Use Stopwatch instead of the PerformanceTimer type.  I'm not familiar with the latter and it appears to be a 3rd party component.  It's particularly troubling that it's measuring time in EllapsedSeconds instead of EllapsedMilliseconds.

*Should run each test twice and count only the second to eliminate potential JIT costs

*Marshal.SizeOf is does not produce the actual size of the struct, just it's marshalling size.

After switching to Stopwatch I see the benchmark performing as expected by producing nearly equal times for both types in the static ref case.

A: I can't reproduce your results. On my box, the "ref" version has basically the same performance for Big and Small, within tolerance.
(Running Release mode without the debugger attached, with 10 or 100 times as many iterations just to try to get a nice long run.)
Have you tried running your version for lots of iterations? Is it possible that while the tests are running, your CPU is gradually increasing its clock speed (as it spots that it's having to work hard)?

A: Agreed with Jared, this is a benchmarking error.
The essence of the issue/discrepancy your seeing is a result of not running a 'warmup' on the tests.  This ensures that all types and methods have been loaded in the CLR runtime. You should place a for loop around the main test and always run the benchmarks several times... watch for the change after the first set in the following results:
    Size of Small is 8 bytes
    Size of Big is 80 bytes

    5,000,000.00 Iterations
    Operator Results
      Small=523.00000       Big=1953.00000  Slower=x3.73
    StaticRef Results
      Small=2042.00000      Big=2125.00000  Slower=x1.04
      Small=x0.26   Big=x0.92

    5,000,000.00 Iterations
    Operator Results
      Small=2464.00000      Big=3510.00000  Slower=x1.42
    StaticRef Results
      Small=3578.00000      Big=3647.00000  Slower=x1.02
      Small=x0.69   Big=x0.96

    5,000,000.00 Iterations
    Operator Results
      Small=3921.00000      Big=4817.00000  Slower=x1.23
    StaticRef Results
      Small=4880.00000      Big=4944.00000  Slower=x1.01
      Small=x0.80   Big=x0.97

A: I have a couple of suggestions.

*

*Use the Stopwatch class. It uses the exact same Win32 APIs, but is already coded for you.

*Increase the iteration count so that your benchmarks take at least 1s (or more) to run otherwise anomalies could crop up and dominate the time.

*Consider the effects of the vshost.exe process. You will get different results for both the Debug and Release builds depending on whether your run the application standalone or through the Visual Studio host process.

When I ran your code I saw similiar results for the pass-by-ref test in all test scenarios. What really stuck out for me was just how much faster the smaller struct was in a Release build standalone (ie. not through vshost.exe).
Release build standalone:
Size of Small is 8 bytes
Size of Big is 80 bytes
50,000,000.00 Iterations
Operator Results
  Small=0.57173 Big=25.58988    Slower=x44.76

StaticRef Results
  Small=26.06602        Big=26.68569    Slower=x1.02
  Small=x0.02   Big=x0.96

Release build through vshost:
Size of Small is 8 bytes
Size of Big is 80 bytes
50,000,000.00 Iterations
Operator Results
  Small=4.56601 Big=35.33387    Slower=x7.74

StaticRef Results
  Small=37.94317        Big=39.64959    Slower=x1.04
  Small=x0.12   Big=x0.89

A: Thanks everyone for their input. Here are some final thoughts.
PerformanceCounter yields the same results as Stopwatch so that is a no issue.
Final results:
1. For small struct using an operator or by-ref yields the same performance
2. For big struct using by-ref is like 14x faster
3. Big struct is x20 slower than small struct for operators (as expected)
4. Big struct is about 50% slower than small struct with by-ref (still interesting)
So the final question is what is the mechanism that makes the Big struct slower with by-ref since no stack copying should occur?

Results from release executable external to visual studio.
Size of Small is 8 bytes
Size of Big is 80 bytes
5,000,000.00 Iterations
Warming up the CPU's

Using QueryPerformanceCounter
Operator Results
  Small=0.03545 Big=0.71519     Slower=x20.18

StaticRef Results
  Small=0.03526 Big=0.05194     Slower=x1.47
  Small=x1.01   Big=x13.77


text:
Q: adding javascript variable to actionlink I have AJAX request that looks like this:
jsonData = JSON.stringify({stuff: stuff});
        $.ajax({
            url: '<%=Url.Action("myMethod", "myController") %>',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: jsonData,
            success: function (data) {
            $("#myDiv").append('<%=Html.ActionLink("Details", "myMethod", new {id      = data.id })%>');
         }
)};

EDIT! I am trying to append this Actionlink to a div on "success". I somehow forgot the $("#myDiv").append() code during my initial post.
In the new {id = data.id } section, I'd like to use the data.id (a javascript variable) in this actionlink.
I keep getting errors saying either data is not defined, or too many characters in literal, etc..
Has anyone successfully done this before?

A: Sir I think you confused between server side (<%) tags and cliend side execution context. "data" is a variable defined in the client side and everything between those server side tags will be processed on the server. There is no variable in your page named "data"! cause you want to use it in the server and it's between server side (<% %>) tags.
In the client your script would be something like the code below:
jsonData = JSON.stringify({stuff: stuff});
        $.ajax({
            url: 'THE_PROCESSED_RESULT_OF_SERVER_TAG_GOES_HERE',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: jsonData,
            success: function (data) {
    'THE_PROCESSED_RESULT_OF_SERVER_TAG_GOES_HERE'
         }
)};

Check the file contents with developer tools (or any other things), you will see what is actually happening in the client.
UPDATE
Again! you can't do such a thing as I already mentioned. There is a difference between server side code and client side code. No matter how you want to access the variable named "data". It does not defined in the server side code. It's the parameter of success function which will be executed in the client side execution context.
Hope it helps
Cheers

A: '<a href="<%=Url.Action("Details", "myMethod")%>?id=' + data.id + '">'

A: You cannot directly do it, since one part of the code is run at the server (the Url.Action part) and the data.id is only available once the code reaches the client browser..
But you could do a trick to it like set the id from server to have a dummy unique value, and replace it with javascript..
$("#myDiv")
   .append('<%=Html.ActionLink("Details", "myMethod", new {id = "-dummy-"})%>'.replace('-dummy-',data.id));


text:
Q: why angularJS uses "dirty" ? I only need to know it's "empty"? it's common to see statements like this:
"myForm.user.$dirty && myForm.user.$invalid"
but if "myForm.user" is empty at first, it's strangely valid!
why angularJS uses "dirty" but not "empty"?

A: In Angular all form inputs are invalid initially and $dirty is false as user has not interacted with the form fields.
To use the validation for empty fields we have to check 3 things
1. $dirty
2. $error.required
3. $invalid
Here is an example
<input type="text" name="bookName" ng-model="BookName" ng-maxlength="50" required />

If you want to display the message until the user interacted with the field then there is no need to use $dirty, you can check it like this..
  Book name is required.

But if you want to display the error message after the user interacted with the field but left it blank then use this.
  Book name is required.

So for the validations like format validation, range validations, numeric or alphanumeric validation it is important to check $dirty because all these needs user interaction with fields but for empty field validations $dirty checking can be ignored.
For more help visit below link
http://mrbool.com/the-concepts-of-angularjs-forms/29117

A: Initially the form is considered to be valid as the user has not interacted with it and filled anything.
$dirty specifies that the user has interacted with the form. Only then you would want to check for errors.


text:
Q: how to place image at eight coordinates in canvas ![how place image with in 8 coordinates in canvas in android please help me to solve this
problem, i need to move this image by next new 8 coordinates, these values are from text file help me to find a good solution  this problem
how place image with in 8 coordinates in canvas in android please help me to solve this
problem, i need to move this image by next new 8 coordinates, these values are from text file help me on this problem
cordi.txt (it having like this)
200 110 600 110 200 740 600 740
200 111 600 111 200 741 600 741
200 112 600 112 200 742 600 742
200 113 600 113 200 743 600 743
200 114 600 114 200 744 600 744
// at here getting coordinates from text file
// at here i am drawing joing lines of coordinates but i need to place image with in the coordinates
but i find to place bitmap image at particular position of X,Y by this method
 it working in linear motion moving up and down  ok perfect working but when there is not in linear coordinates that means (image rotation happed) at this time i am unable to find the angle of rotation of bitmap with axis can u give guide lines
    class image_placer extend view {
            BufferedReader reader = new BufferedReader(new  InputStreamReader(context1.getAssets().open("cordi.txt")));
                      String line;
                      while ((line = reader.readLine()) != null)
                  {
                       String[]  saLineElements = line.split("  ");
                      X1.add(Integer.parseInt(saLineElements[0].toString().trim()));
                      Y1.add(Integer.parseInt(saLineElements[1].toString().trim()));

                      X2.add(Integer.parseInt(saLineElements[2].toString().trim()));
                      Y2.add(Integer.parseInt(saLineElements[3].toString().trim()));

                      X3.add(Integer.parseInt(saLineElements[4].toString().trim()));
                      Y3.add(Integer.parseInt(saLineElements[5].toString().trim()));

                      X4.add(Integer.parseInt(saLineElements[6].toString().trim()));
                      Y4.add(Integer.parseInt(saLineElements[7].toString().trim()));
                  }
                  reader.close();
               }
              catch (FileNotFoundException e){
                  System.err.println(
                     "FileNotFoundException: " + e.getMessage());
              } catch (IOException e) {
                  e.printStackTrace();
              }catch (NumberFormatException e) {
                 System.out.println(""+e.getMessage());
            }
// now in on draw method i need to place the image in that coordinates  i=0 (Globally declared )
            public void onDraw(Canvas canvas) {
                  if(i>=X1.size())
            {
                i=0;
                X=X1.get(i);
                Y=Y1.get(i);
                 dx=X2.get(i)-X1.get(i);
                dy=Y3.get(i)-Y1.get(i);
                Path drawPath=new Path();
                drawPath.moveTo(X1.get(i), Y1.get(i));
                drawPath.lineTo(X2.get(i), Y2.get(i));
                drawPath.lineTo(X4.get(i), Y4.get(i));
                drawPath.lineTo(X3.get(i), Y3.get(i));
                drawPath.lineTo(X1.get(i), Y1.get(i));
               canvas.drawPath(drawPath, mPaint);

          }

            else
            {
                X=X1.get(i);
                Y=Y1.get(i);
                dx=X2.get(i)-X1.get(i);
                dy=Y3.get(i)-Y1.get(i);
                Path drawPath=new Path();
                drawPath.moveTo(X1.get(i), Y1.get(i));
                drawPath.lineTo(X2.get(i), Y2.get(i));
                drawPath.lineTo(X4.get(i), Y4.get(i));
                drawPath.lineTo(X3.get(i), Y3.get(i));
                drawPath.lineTo(X1.get(i), Y1.get(i));
               canvas.drawPath(drawPath, mPaint);
                i++;
            }
     float scaleWidth = (dx) / ballW;
        float scaleHeight = (dy) / ballH;
        if(i<=X1.size())
        {
        Matrix matrix_rev = new Matrix();
        matrix_rev.postScale(scaleWidth, scaleHeight);
        resizedBitmap = Bitmap.createBitmap(reverse, 0, 0,
                ballW, ballH, matrix_rev, true);
        }else{
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeight);
            if(i<=X1.size()-1)
           resizedBitmap = Bitmap.createBitmap(ball, 0, 0,
                    ballW, ballH, matrix, true);
        }

         canvas.drawBitmap(bitmap_img, X,Y, null);
             invalidate();
    }}

A: You can use
RectF dstRect=new RectF(x1,y1,width,height);
Canvas can=new Canvas();
can.drawBitmap(bitmap, null, dstRect, paint);


text:
Q: How to apply Newton's method and find behavior of $g'(x)$ for $x$ near $\xi$? Question: Let $f$ be twice differentiable on $[a,b]$, $f(a) < 0,$ $f(b) > 0,$ $f'(x) > \delta,$ and $0 \leq f''(x) \leq M \;\;\forall x \in [a,b]$.
Let $\xi$ be the unique point in $(a,b)$ at which $f(\xi) = 0$.
(i) Show that Newton's method amounts to finding a fixed point of the function $g$ defined by
$g(x)=x-\frac{f(x)}{f'(x)}$.
How does $g'(x)$ behave for $x$ near $\xi$ ?
# I don't know how to proceed for this question. I need help in solving above 2 questions. Thank you.


text:
Q: How to scrape multiple image's links in same position blank that position if there's no picture I have an exam website that has 2 classes that I need (Topic class and Choice class). So, in a choice class (actually, it's a choice to answer) some questions ares image choice (4 choices is image), so, I want to scrape 4 image's links in the same position in array (1 position in array is 1 question).
And another question for me, how can I blank the array position if there is no picture?
Actually, I will random question's number to get data in 4 array (Topic,Choice,topic's image, choice's image) then I will get the data from these array to display in next applications.
Here is an example question and the HTML code:

ข้อที่ 38 :

ภาพใดแสดง เกลียวน๊อตตามแบบมาตรฐาน

<input type="checkbox" name="a"> 1  :

<input type="checkbox" name="a"> 2  :

<input type="checkbox" name="a"> 3  :

<input type="checkbox" name="a"> 4  :

 คำตอบที่ถูกต้อง : 3

The image's URL that I need should be like:
https://my-project-1471674425170.firebaseapp.com/drawing/drawing_files/S190T1P249_20060124_224403_A1.jpg

A: If all of your examples are similar, then the following approach could work. This will also catch the text associated with each
:
from bs4 import BeautifulSoup

html = """

      ข้อที่ 38 :

ภาพใดแสดง เกลียวน๊อตตามแบบมาตรฐาน

<input type="checkbox" name="a"> 1  :

<input type="checkbox" name="a"> 2  :

<input type="checkbox" name="a"> 3  :

<input type="checkbox" name="a"> 4  :

 คำตอบที่ถูกต้อง : 3

"""

base_url = "https://my-project-1471674425170.firebaseapp.com/"
soup = BeautifulSoup(html, "html.parser")
div = soup.find('div', class_="cssExChoice")
urls = []

for li in div.find_all('li'):
    img = li.find('img', src=True)

    # Was there an image present?
    if img:
        urls.append((li.get_text(strip=True), base_url + li.img['src'].lstrip('/.')))
    else:
        urls.append((li.get_text(strip=True), None))

# Display the results
for text, url in urls:
    print(f'"{text}" - {url}')

Giving you the text and URL pairs as follows:

"1  :" - https://my-project-1471674425170.firebaseapp.com/drawing_files/S190T1P249_20060124_224403_A1.jpg
"2  :" - https://my-project-1471674425170.firebaseapp.com/drawing_files/S190T1P249_20060124_224403_A2.jpg
"3  :" - https://my-project-1471674425170.firebaseapp.com/drawing_files/S190T1P249_20060124_224403_A3.jpg
"4  :" - https://my-project-1471674425170.firebaseapp.com/drawing_files/S190T1P249_20060124_224403_A4.jpg
"" - None
"คำตอบที่ถูกต้อง :3" - None

In your example there are 6
 items, but only 4 have images. The list returned has the last two entries as None.
The topic could also be extracted as follows:
div_topic = soup.find('div', class_="cssExTopic")
topic = ' - '.join(text.strip() for text in div_topic.strings if text.strip())
print(topic)

Giving:
อที่ 38 : - ภาพใดแสดง เกลียวน๊อตตามแบบมาตรฐาน


text:
Q: To index geojson data to elasticsearch using curl I'd like to index a geojson data to elasticsearch using curl
The geojson data looks like this:
{
"type": "FeatureCollection",
"name": "telco_new_development",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "ogc_fid": 1, "name": "Yarrabilba", "carrier_name": "OptiComm", "uid": "35", "development_name": "Yarrabilba", "stage": "None", "developer_name": "Refer to Carrier", "development_nature": "Residential", "development_type": "Sub-division", "estimated_number_of_lots_or_units": "18500", "status": "Ready for service", "developer_application_date": "Check with carrier", "contract_date": "TBC", "estimated_service_date": "30 Jul 2013", "technology_type": "FTTP", "last_modified_date": "8 Jul 2020" }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ 153.101112, -27.797998 ], [ 153.09786, -27.807122 ], [ 153.097715, -27.816313 ], [ 153.100598, -27.821068 ], [ 153.103789, -27.825047 ], [ 153.106079, -27.830225 ], [ 153.108248, -27.836107 ], [ 153.110692, -27.837864 ], [ 153.116288, -27.840656 ], [ 153.119923, -27.844818 ], [ 153.122317, -27.853523 ], [ 153.127785, -27.851777 ], [ 153.131234, -27.85115 ], [ 153.135634, -27.849741 ], [ 153.138236, -27.848668 ], [ 153.141703, -27.847075 ], [ 153.152205, -27.84496 ], [ 153.155489, -27.843381 ], [ 153.158613, -27.841546 ], [ 153.161937, -27.84059 ], [ 153.156361, -27.838492 ], [ 153.157097, -27.83451 ], [ 153.15036, -27.832705 ], [ 153.151126, -27.827536 ], [ 153.15169, -27.822564 ], [ 153.148492, -27.820801 ], [ 153.148375, -27.817969 ], [ 153.139019, -27.815804 ], [ 153.139814, -27.808556 ], [ 153.126486, -27.80576 ], [ 153.124679, -27.803584 ], [ 153.120764, -27.802953 ], [ 153.121397, -27.797353 ], [ 153.100469, -27.79362 ], [ 153.099828, -27.793327 ], [ 153.101112, -27.797998 ] ] ] ] } },
{ "type": "Feature", "properties": { "ogc_fid": 2, "name": "Elliot Springs", "carrier_name": "OptiComm", "uid": "63", "development_name": "Elliot Springs", "stage": "None", "developer_name": "Refer to Carrier", "development_nature": "Residential", "development_type": "Sub-division", "estimated_number_of_lots_or_units": "11674", "status": "Ready for service", "developer_application_date": "Check with carrier", "contract_date": "TBC", "estimated_service_date": "29 Nov 2018", "technology_type": "FTTP", "last_modified_date": "8 Jul 2020" }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ 146.862725, -19.401424 ], [ 146.865987, -19.370253 ], [ 146.872767, -19.370901 ], [ 146.874484, -19.354706 ], [ 146.874913, -19.354301 ], [ 146.877059, -19.356811 ], [ 146.87972, -19.35835 ], [ 146.889161, -19.359321 ], [ 146.900062, -19.367581 ], [ 146.884955, -19.38507 ], [ 146.88341, -19.402558 ], [ 146.862725, -19.401424 ] ] ] ] } },
...

However, my curl is returns an error called The bulk request must be terminated by a newline [\\n]
curl -H 'Content-Type: application/x-ndjson' -XPOST 'localhost:9200/geo/building/_bulk?pretty' --data-binary @building.geojson

{
  "error" : {
    "root_cause" : [
      {
        "type" : "illegal_argument_exception",
        "reason" : "The bulk request must be terminated by a newline [\\n]"
      }
    ],
    "type" : "illegal_argument_exception",
    "reason" : "The bulk request must be terminated by a newline [\\n]"
  },
  "status" : 400
}

Any suggestion?

A: your format is not suitable for _bulk like that, as it's missing the structure it expects. https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html goes into that
you need;

*

*to update your json file to have something like { "index" : { "_index" : "INDEX-NAME-HERE" } } before each of the documents

*each document also needs to be on a single line

*each line needs a \n at the end of it so that the bulk API knows when the action/record ends


text:
Q: How to change resting text color on javafx ComboBox I am writing a javafx app that uses css to create a custom look for the entire app. I don't like using external css files so all my styling is done through calls to setStyle for various nodes. I am trying to customize a comboBox and have run into some issues. I have figured out how to style the actual dropdown list using the cell factory, but after hours of googling I haven't been able to figure out how I can change the text color of the combobox when it is just sitting there on the screen. Here is a picture for an example:

As you can see, my list is styled fine, but the "true" being displayed by the box itself is still the default gray color. I want it to be white, but can't find any examples on how to achieve this. All help is appreciated, thanks!


text:
Q: How to remove cache from Fresco Simple drawee I want to remove the cache from simple drawee using Fresco library because if image are changed from server then still show old image in simple drawee. Below are my code.
    public class FrescoSimpleDraweeActivity extends Activity {

    private SimpleDraweeView simpleDraweeView1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Fresco.initialize(this);
        setContentView(R.layout.activity_fresco_simple_drawee);

        Log.e("Fresco simple activity ","is calling...");

        simpleDraweeView1 = (SimpleDraweeView) findViewById(R.id.simpleDraweeView1);

        Uri imageUri = Uri.parse("http://i.imgur.com/76Jfv9b.jpg");
//        simpleDraweeView1.setImageURI(imageUri);

        //If we used to load image from network then use it otherwiese not.
        // return immidiate result if thumb store using (.setProgressiveRenderingEnabled(true)) (only local URI)

        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(imageUri)
                .setProgressiveRenderingEnabled(true)
                .setLocalThumbnailPreviewsEnabled(true)
                .build();

        ControllerListener listener = new BaseControllerListener();

        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setUri(imageUri)
                .setImageRequest(request)
                .setTapToRetryEnabled(true)
                .setOldController(simpleDraweeView1.getController())
                .setControllerListener(listener)
                .setTapToRetryEnabled(true)
                .build();

        simpleDraweeView1.setController(controller);

    }
}

Here is my xml code
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Activity.Fresco.FrescoSimpleDraweeActivity">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="This is Fresco Drawee Example" />
    <!--fresco:failureImage="@drawable/failure"-->

    <com.facebook.drawee.view.SimpleDraweeView
        android:id="@+id/simpleDraweeView1"
        android:layout_width="200dp"
        android:layout_height="200dp"
        fresco:failureImage="@drawable/failure"
        fresco:progressBarImage="@drawable/progress"
        fresco:progressBarImageScaleType="centerInside"
        fresco:roundAsCircle="true"
        fresco:roundBottomLeft="true"
        fresco:roundBottomRight="true"
        fresco:roundTopLeft="true"
        fresco:roundTopRight="true"
        fresco:roundedCornerRadius="50dp"
        fresco:roundingBorderColor="@color/red"
        fresco:roundingBorderWidth="2dp"
        fresco:retryImage="@drawable/retry"
        fresco:retryImageScaleType="centerCrop"
        fresco:actualImageScaleType="centerCrop"
        android:layout_below="@+id/tvTitle"
         />

    <!--for round image border use below-->

    <!--fresco:roundedCornerRadius="50dp"-->
    <!--fresco:roundTopLeft="true"-->
    <!--fresco:roundTopRight="true"-->
    <!--fresco:roundBottomLeft="true"-->
    <!--fresco:roundBottomRight="true"-->

</RelativeLayout>

A: @Sakib Syed you can try to this code hope this can help you.
    ImagePipeline imagePipeline = Fresco.getImagePipeline();
    imagePipeline.clearMemoryCaches();
    imagePipeline.clearDiskCaches();

// combines above two lines
    imagePipeline.clearCaches();


text:
Q: Spring boot service pass java option I have spring-boot application running as a init service through the executable jar. Going through the documentation I wanted pass JAVA_OPTS for heap size to the executable jar.
Currently, the following config is being used
 <embeddedLaunchScriptProperties>
    <inlinedConfScript>JAVA_OPTS=-Xmx8000m -Xms8000m</inlinedConfScript>
 </embeddedLaunchScriptProperties>

I am not sure it works as through jmap maxHeapSize is around 2000mb (2gb)
Has anyone tried this?

A: Why don't you directly add these configurations while running your JAR file?
For example:
java -Xmx8000m -Xms8000m -jar xxx.jar


text:
Q: Jenkins Declarative Pipeline : running a script{} block outside of stages Goal:
I need to run a snippet similar to this, in order to grab some info from a different Jenkins job:
 script {
    def buildJobName = Jenkins.instance.getItemByFullName('Jobs/myOtherJob')
    def buildJobId = buildJobName.getLastSuccessfulBuild()
 }

The documentation explains clearly how a script can be ran in a Declarative Pipeline:
https://jenkins.io/doc/book/pipeline/syntax/#script but it explicitly runs them within stages.

This question scope is specifically about how to run "any" script block outside of pipeline stages, so it's not specific what my script is doing. Can be applied to any groovy script in a declarative pipeline.

My use-case will need this data globally, outside of the scope of a single step
Normally, for "global" things across the whole pipeline, I use the environment{} block to declare variables. However, I can't seem to get the script to execute properly in the environment{} block, at least with the attempts I've made.
So, my question is:
How can I run a script section in a declarative pipeline, defining variables that can be later used in the entire pipeline?

A: Figured it out after doing some more research.
There might be a more optimal way, but I was able to get this working by putting the script in a function, and setting the env var value to the functions return value:
def get_last_build() {
  def buildJobName = Jenkins.instance.getItemByFullName('Jobs/myOtherJob')
  def lastBuildId = buildJobName.getLastSuccessfulBuild()
  echo 'Using Build ID: ' + lastBuildId
  return lastBuildId
}

pipeline {
  agent any
  environment {
    MY_GLOBAL_VAR = get_last_build()
  }
  // other stuff
}


text:
Q: How console.log works behind the scene? When I am running this piece of code in JSEditor.
var obj = {};
console.log(obj);
obj.foo = 'bar';

The o/p is : [object Object]
While the same code in the console tab is giving me this o/p:
{}
"bar"

A: In node js
console instance configured to write to process.stdout and process.stderr.
The global console can be used without calling require('console').
var p={}

console.log function uses process.stdout.write();process.stdout
So you will get object after writing the value


text:
Q: Issues with Functions Defined as Eigenvalues I have to calculate eigenvalues of 4 different matrices.  The code I'm using is below, but essentially three out of the four are working with no problem, and one (the eigenvalues I've defined as y) are giving me a lot of trouble.
J={{1+p a, p a},{-l, 1}}
L={{1,p},{0,b}}
W={{p a,0},{0, 0}}
F={{0.9,0},{0,0.9}}
M[a_,b_,p_,l_]=Inverse[J].L
P[a_,b_,p_,l_]=Inverse[J].W
U[a_,b_,p_,l_]={{1/(1+a p+a l p),p/(1+a p+a l p)-(a b p)/(1+a p+a l p),0,0},
  {l/(1+a p+ a l p),(l p)/(1+a p+a l p)+(b (1+a p))/(1+a p+a l p),0,0},
  {0,0,1,0},{0,0,0,1}}
V[a_,b_,p_,l_]={{1,0,-((a p)/(1+a p+a l p)),0},
  {0,1,-((a l p)/(1+a p+a l p)),0},
  {1,0,0,0},{0,1,0,0}}
Quiet[B[a_,b_,p_,l_]=
  -Inverse[Take[Inverse[SchurDecomposition[{U[a,b,p,l],V[a,b,p,l]}][[3]]],{3,4},{1,2}]].
  Take[Inverse[SchurDecomposition[{U[a,b,p,l],V[a,b,p,l]}][[3]]],{3,4},{3,4}]];
Quiet[v[a_,b_,p_,l_]=Eigenvalues[M[a,b,p,l].(IdentityMatrix[2]+B[a,b,p,l])]];
Quiet[w[a_,b_,p_,l_]=Eigenvalues[KroneckerProduct[Transpose[B[a,b,p,l]],M[a,b,p,l]]+
  KroneckerProduct[IdentityMatrix[2],M[a,b,p,l].B[a,b,p,l]]]];
Quiet[y[a_,b_,p_,l_]=Eigenvalues[KroneckerProduct[F,M[a,b,p,l]]+
  KroneckerProduct[IdentityMatrix[2],M[a,b,p,l].B[a,b,p,l]],Cubics->True,Quartics->True]];
Quiet[z[a_,b_,p_,l_]=Eigenvalues[M[a,b,p,l].B[a,b,p,l]]];
v[1,.99,1,.25]
w[1,.99,1,.25]
z[1,.99,1,.25]
y[1,.99,1,.25]
Eigenvalues[KroneckerProduct[F,M[1,.99,1,.25]]+KroneckerProduct[IdentityMatrix[2],M[1,.99,1,.25].b[1,.99,1,.25]]]

So the quiets are there to ignore Mathematica flipping out about passing symbolic matrices into Schur decomposition, but B produces the same matrices that would be produced by the expression if given a set of parameter values.  When I call v,w, and z with parameter value inputs I get an expected results, but when I call y as above I get 16 eigenvalues instead of 4.  When I leave cubics and quartics off it gives me the following error:
Root::npoly: {{5.25119 -1.3353 #1+0.114118 #1^2-0.0037085 #1^3+0.0000342936 #1^4,
1.1164-0.359741 #1+0.0413553 #1^2-0.00199383 #1^3+0.0000342936 #1^4,<<1>>,
1.1164 -0.359741 #1+0.0413553 #1^2-0.00199383 #1^3+0.0000342936 #1^4},
<<2>>,{<<1>>,<<1>>,<<1>>,<<1>>}} is not a polynomial in #1. >>

Three times.  The values it does return after these errors are long expressions (i.e. it abridges the output) and it features a lot of multiplication of real numbers that hasn't been evaluated.
I also have evaluated the expression for y with the same set of parameter values and it gives me a simple set of four eigenvalues.
Hopefully this makes sense, I've spent a day scouring the internet to see if someone else has run into a similar problem and found nothing.  Any help is greatly appreciated.
Edit:  Realized that v is giving similar issues, giving me 8 values instead of 2.  When I just evaluate the expression with the same parameter values it gives me 2 like it should.

A: Your error is in the fact you don't delay your function. You run the Eigenvalues based on M with [a,b,p,l] as variables.
Please amend your code by adding a : before the =. This ensures that the actual calculations aren't done until you call them.
Now you also don't need the quiets.
v[a_, b_, p_, l_] :=
  Eigenvalues[M[a, b, p, l].(IdentityMatrix[2] + B[a, b, p, l])]
v[1, .99, 1, .25]

{1.32892, 0.662193}

y[a_, b_, p_, l_] :=
   Eigenvalues[
    KroneckerProduct[F, M[a, b, p, l]] +
     KroneckerProduct[IdentityMatrix[2], M[a, b, p, l].B[a, b, p, l]],
     Cubics -> True, Quartics -> True];
y[1, .99, 1, .25]

{1.24153, 1.24153, 0.606027, 0.606027}


text:
Q: Redirecting connection from IP to localhost I'm running localhost server on xampp. I 'm connecting properly with my host computer from other devices with IP address but once i go into wordpress directory i got redirected. Every device i was testing changed entered IP/wordpress to localhost/wordpress.
Strange fact is that i have 3 exact copies of wordpress. One of wchich is installed on Windows8, second Windows10 and 3rd one on Ubuntu. There's no problem to connect with windows installations even from Ubuntu but not the reverse.
I've already tried to change wp-config.php file by modifying :
define('WP_SITEURL', 'http://LOCAL_HOST_IP/wordpress');
define('WP_HOME', 'http://LOCAL_HOST_IP/wordpress');

And it works but only partial. iOS device is connecting properly with host wordpress but windows computer and android based tablet isn't. What can cause such problem?

A: Trying to change edit the wp-config.php file was a good idea, let's try some extra things to see if they solve the problem. Let's add these lines to the bottom of your functions.php:
update_option( 'siteurl', 'http://LOCAL_HOST_IP/wordpress' );
update_option( 'home', 'http://LOCAL_HOST_IP/wordpress' );

Using Relocate method
Edit your wp-config.php file inserting:
define('RELOCATE',true);

After that, from your browser manually access to wp-login.php. For example, type http://LOCAL_HOST_IP/wordpress/wp-login.php into your browser's address bar, and then login as usual.

Changing the URL directly in the database

*

*Login to phpMyAdmin.

*Find your DB and then the table wp_options

*Look for siteurl and home within that table

*Use http://LOCAL_HOST_IP/wordpress for both and save.

Check the full Codex Changing Site URL guide.

A: Problem solved
Wordpress and its configuration wasn't the issue here. The real reason why site was working on some devices and on others don't was cached files in browsers.
Solution was to clear cached files or trying to develop in private mode browsing which isn't caching files.
Also i want to point out that when you want to access host from other computer you have to disable firewall. Strange fact about all this is when you can access to host and see it's dashboard while firewall is enabled going into wordpress directory will cause error.


text:
Q: AES 128 have different results in Arduino ESP8266 and Online Tool I want to encrypt text by AES 128 CBC, but the results is different in Arduino and online tool. I tried different Arduino library, but still have same problem.
my code in arduino as follow.
#include <Crypto.h>
#include <ebase64.h>

#define BLOCK_SIZE 16

byte key[BLOCK_SIZE] = {0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};
byte iv[BLOCK_SIZE] = {0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};

void bufferSize(char* text, int &length)
{
int i = strlen(text);
int buf = round(i / BLOCK_SIZE) * BLOCK_SIZE;
length = (buf < i) ? buf + BLOCK_SIZE : length = buf;
}

void encrypt(char* plain_text, char* output, int length)
{
byte enciphered[length];

AES aesEncryptor(key, iv, AES::AES_MODE_128, AES::CIPHER_ENCRYPT);
aesEncryptor.process((uint8_t*)plain_text, enciphered, length);

int encrypted_size = sizeof(enciphered);
char encoded[encrypted_size];
base64_encode(encoded, (char*)enciphered, encrypted_size);

strcpy(output, encoded);
}

void decrypt(char* enciphered, char* output, int length)
{
length = length + 1; //re-adjust
int decodedLen = base64_dec_len(enciphered, length);
char decoded[length];

Serial.println(enciphered);
base64_decode(decoded, enciphered, length);
bufferSize(enciphered, length);
byte deciphered[length];
AES aesDecryptor(key, iv, AES::AES_MODE_128, AES::CIPHER_DECRYPT);

aesDecryptor.process((uint8_t*)decoded, deciphered, length);
strcpy(output, (char*)deciphered);
}

void setup()
{
Serial.begin(115200);
while (!Serial) {
; //wait
}

char plain_text[] = "Now is the time ABCDABC";

// encrypt
int length = 0;
bufferSize(plain_text, length);
Serial.println(length);
char encrypted[length];
encrypt(plain_text, encrypted, length);

Serial.println(encrypted);

// decrypt

length = strlen(encrypted);
char decrypted[length];
decrypt(encrypted, decrypted, length);

Serial.println(decrypted);
}
void loop()
{
}

Key and IV:
{0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};
or
{ '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' };
Text: "Now is the time ABCDABC";
the encrypted is
1a7OeiH628V7IIoLU6+3n70Dzp6FBQjlGPxSwnuXdzo=
and the AES online tool.
[https://www.devglan.com/online-tools/aes-encryption-decryption]
Key : 0000000000000000
IV  : 0000000000000000
Text: Now is the time ABCDABC
I'm encrypt in web and the result is
1a7OeiH628V7IIoLU6+3n7ILev6IwcZYVNLalS/TBEg=
So I can't decrypt each other. Anyone can help me? Thanks a lot!

A: It looks like this is one of these instances where the author of a crypto library is even more clueless than authors of "online tools" that perform such feat:
   /**
     * Either encrypt or decrypt [in] and store into [out] for [length] bytes, applying padding as needed
     *
     * Note: the length must be a multiple of 16 bytes
     */
    void process(const uint8_t *in, uint8_t *out, int length);

Now it isn't specified which padding is used, nor how it is removed. Furthermore, obviously the input should not always be a multiple of 16, that doesn't make any sense.
However, decryption without padding can be used to recover the plaintext:
4e6f77206973207468652074696d6520414243444142430020000000feefeffe
4e6f77206973207468652074696d652041424344414243090909090909090909
 N o w   i s   t h e   t i m e   A B C D A B C

Here the first one is your encryption. Obviously it doesn't show a correct padding at all. It's a zero byte, a 02 byte and then some zero's followed by feefeffe which terribly looks like a method to detect uninitialized memory or something like it. The online library uses PKCS#7 compatible padding.
The first idea for me when looking at the code is that you were wrong when declaring the array containing the ciphertext:
byte enciphered[length];

obviously that's not correct if the ciphertext size expands the plaintext size due to padding. So you have a possible buffer overrun there. However, as you still get back the original plaintext even for the last block, the library must be in error as well.
Moral of the story: don't use horrible one-person libraries on GitHub. Libraries need to be tested and have a team behind it to be trustworthy enough for crypto.

A: Your encrypted data in both cases is correct.
1a7OeiH628V7IIoLU6+3n70Dzp6FBQjlGPxSwnuXdzo=

Decodes as:
d5 ae ce 7a 21 fa db c5 7b 20 8a 0b 53 af b7 9f

bd 03 ce 9e 85 05 08 e5 18 fc 52 c2 7b 97 77 3a

And
1a7OeiH628V7IIoLU6+3n7ILev6IwcZYVNLalS/TBEg=

Decodes as:
d5 ae ce 7a 21 fa db c5 7b 20 8a 0b 53 af b7 9f

b2 0b 7a fe 88 c1 c6 58 54 d2 da 95 2f d3 04 48

As you can see the first 16 bytes are OK. That can be interpreted as: the Key and IV are the same in both cases.
And as in your case if complete blocks are OK, and only the last block have issues, seems that the problem is in the padding mode.
Your Text: "Now is the time ABCDABC" has 24 bytes (with the null end char), but this encryption algorithm needs multiples of 16 bytes. Therefore, it must be padded up to 32 bytes. It will have 8 padding bytes. But with what value?
I was experimenting same issues with Arduino AESLib.
And I found that versions below 2.0 supports only one padding mode (unfortunately incompatible with online tools), the only option, do it myself.
But in version 2.0.2 they improved it and add support for multiple modes.
Most online tools use as default PKCS7 padding, but Arduino AESLib initialize with Array mode for compatibility reasons.
So I needed to call:
aes.setPadMode(paddingMode::CMS);

before using do_aes_encrypt, do_aes_decrypt functions.
These functions manage all padding, sizing issues according to the configuration.
In your case you case the call to
aesEncryptor.process((uint8_t*)plain_text, enciphered, length);

It doesn't have padding management and it must be done prior to the call.
So what is happening is that the function is using an additional 8 bytes after the end of plain_text[] array as padding with its uninitialized memory value.


text:
Q: Angular unit test child component I am writing unit test for one of my Angular application which consists of multiple components. In one of my component (Component A), it has a child component like below
Component A

    <app-data-grid
      [columnDefs]="columnDefs"
      [defaultColDef]="defaultColumnDefs"
      [overlayNoRowsTemplate]="overlayNoRowsTemplate"
      [hasFloatingFilter]="hasFloatingFilter"
      [frameworkComponents]="frameworkComponents"
      [rowData]="rowData"
      [hasMultipleRows]="rowSelection"
      [hasRowAnimation]="hasRowAnimation"
      [multiSortKey]="multiSortKey"
      (rowDataChanged)="onRowDataChanged()"
      (selectionChanged)="onSelectionChanged()"
      (rowClicked)="gotoDetailView($event)"
      (sortChanged)="onSortChanged($event)"
      (columnResized)="onColumnResized()"
      (gridReady)="OnGridReady($event)"
    >
    </app-data-grid>

      <button
        id="addDevice"
        type="button"
        class="btn btn-brand btn-primary position-relative add-button"
        (click)="gotoAddDevice()"
      >

      </button>

If you see the above HTML in the ComponentA i am having the  component which calls the functions when the column is resized in the Grid which would call the onColumnResized() inside my ComponentA like below
onColumnResized() {
    const updatedColumns: ColumnWidth[] = [];
    this.columnApi.getColumnState().forEach((column) => {
      updatedColumns.push({ field: column.colId, width: column.width });
    });
    this.store.dispatch(new DevicesActions.UpdateColumnWidth(updatedColumns));
  }

My question is how do i spy the onColumnResized() or can i call the function directly like below

    describe('ColumnResized', () => {
        it('call the onColumnResized', () => {
          expect(component.onColumnResized()).toHaveBeenCalled();
        });
      });

I Would like to know whether this is the correct approach as well as can i use spyOn() instead of calling the function directly

A: You should not test if the method is called. You should test if the component behaves correct when the child component is resized.
There is a good library to mock your components: https://www.npmjs.com/package/ng-mocks
Something like that:
let columnApiMock: jasmine.SpyObj<ColumnApi>;

beforeEach(() => {
  TestBed.configureTestingModule({
    ...
    providers: [
      { provide: YourStoreService,
        useValue: jasmine.createSpyObj('YourStoreService', ['dispatch']) },
      { provide: ColumnApi,
        useValue: jasmine.createSpyObj('ColumnApi', ['getColumnState']) },
    ],
    declarations: [
      AppComponentA, // not mocked
      MockComponent(AppDataGrid),
    ],
  });
  columnApiMock = TestBed.inject(ColumnApi) as jasmine.SpyObj<ColumnApi>;
})

...

it('test if columns are stored on resize', () => {
  // expect you have mocked your colum api, prepare columns that should be returned
  columnApiMock.getColumnState.and.returnValue([...]);

  const dataGridMock = ngMocks.find(fixture.debugElement, AppDataGrid);
  // trigger Output from DataGrid
  dataGridMock.columnResized.emit();

  expect(TestBed.inject(YourStoreService).dispatch))
    .toHaveBeenCalledWith(...);
});

This way your tests don't rely on the internal implementation of your component.
You need to know if a method named onColumnResized is called. You have to ensure, that your store is updated with the correct columns when a resize happens...

A: Nidhin, before I provide some answer  let me explain the intention of unit testing for a component.

Unit testing of a component means that you should check the behavior (which includes HTML & ts code) of a component. One important factor which should be kept in mind is that "we should isolate the component(which is being tested) from external dependencies (mostly services) as much as possible"

IMHO, you should only check if the behavior is working when onColumnResized() is called. You should not be worried whether app-data-grid is calling it or not on (columnResized) . In app-data-grid tests, you should test whether columnResized is raised/invoked as per the expectation.

Note: You should test the behavior of both components working together as a part of Integration testing, which means that you test the working of several components together (integrated)

In your case, for below code:
onColumnResized() {
    const updatedColumns: ColumnWidth[] = [];
    this.columnApi.getColumnState().forEach((column) => {
      updatedColumns.push({ field: column.colId, width: column.width });
    });
    this.store.dispatch(new DevicesActions.UpdateColumnWidth(updatedColumns));
 }

you should do below tests:

*

*Make store inside the constructor as public (so that we can put spy on it by accessing it outside the component)

export class MockColumnApi {
  getColumnState() {
    return [
      {colId: 1, column: 2 }
    ];
  }
}

describe('SomeComponent', () => {
  let component: SomeComponent;
  let fixture: ComponentFixture<SomeComponent>;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
         // whatever you need to import
      ],
      declarations: [SomeComponent, GridComponent],
      providers: [
        { provide: ColumnApi, useClass: MockColumnApi },
      ],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SomeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should create dispatch columns on resize call', () => {
    spyOn(component.columnApi, 'getColumnState').and.callThrough();
    spyOn(component.store, 'dispatch').and.callThrough();
    component.onColumnResized();
    expect(component.columnApi.getColumnState).toHaveBeenCalled()
    expect(component.store.dispatch).toHaveBeenCalledWith(
      new DevicesActions.UpdateColumnWidth({colId: 1, column: 2 })
    );
  });
});

OR you can simply override the return type without creating a MockColumnApi:
describe('SomeComponent', () => {
  let component: SomeComponent;
  let fixture: ComponentFixture<SomeComponent>;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
         // whatever you need to import
      ],
      declarations: [SomeComponent, GridComponent],
      providers: [
        { provide: ColumnApi, useClass: MockColumnApi },
      ],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SomeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should create dispatch columns on resize call', () => {
    const sampleData = [
      {colId: 1, column: 2 }
    ];
    spyOn(component.columnApi, 'getColumnState').and.returnValue(sampleData );
    spyOn(component.store, 'dispatch').and.callThrough();
    component.onColumnResized();
    expect(component.columnApi.getColumnState).toHaveBeenCalled()
    expect(component.store.dispatch).toHaveBeenCalledWith(
      new DevicesActions.UpdateColumnWidth(sampleData )
    );
  });
});

You can refer this article of mine where I have combined few topics as a part of tutorial of Unit testing in Angular. I hope it helpes.


text:
Q: How to add a reference to a project in dotnet/cli (rc2)? I have created a Web API dotnet core project and i would like to use an older C# library (.NET Framework 4.5)
My project.json looks like
...
  "frameworks": {
    "netcoreapp1.0": {
       "imports": [
         "net451",
         //"dotnet5.6",
         //"dnxcore50",
         "portable-net45+win8"
         ],
  "dependencies": {
    "LibInternal": {
      "target": "project"
    }
  }
}
...

After adding a using in Startup.cs, i get the error - the type or namespace name "..." could not be found.
What is wrong?


text:
Q: Let $H_1$ be the cyclic subgroup $\langle(1234)\rangle$ of $S_4$. Write down the right cosets of $H$ in $S_4$ We have $H_1 = \{e,(1234),(13)(42),(1432)\}$
As I understand it, "right cosets" are defined as:
$H_1x:x\in S\setminus H$
The answer is given as:
$\{\operatorname{id},(1 2 3 4),(1 3)(2 4),(1 4 3 2)\},$
$\{(1 2),(1 3 4),(1 4 2 3),(2 4 3)\},$
$\{(1 3),(1 4)(2 3),(2 4),(1 2)(3 4)\},$
$\{(1 4),(2 3 4),(1 2 4 3),(1 3 2)\},$
$\{(2 3),(1 2 4),(1 3 4 2),(1 4 3)\},$
$\{(3 4),(1 2 3),(1 3 2 4),(1 4 2)\}$.
What I don't understand is how the first $x$ in each right coset given was chosen. Surely we have to go through all $x$ which is in $S$ but not in $H$?
For instance I calculated the set:
$\{(123),(1324),(1342),(143)\}$ - is this not a right coset?

A: Okay after some trial and error and further reading, I discovered what my problem was:
Firstly, we know that in general $|S_n| = n!$. We have that $|H_1| = 4$ by counting the number of elements in $H_1$. Moreover, we know that $|H_1|$ divides $|S_4|$ by Lagrange's Theorem. Then the index of $H_1$ in $S_4$ is given by $\frac{|S_4|}{|H_1|} =  \text{number of right cosets in $H_1$}$
In this case we then have $\frac{4!}{4} = 6$ cosets.
So we just plug in an element $x\in S_4\setminus H_1$, which generates a right coset. Then we repeat with an element $y\in S_4\setminus(H_1 \cup xH_1)$. We repeat this until we have $6$ cosets and then we know we are done.


text:
Q: Use button caption as variable excel This has to be an obvious thing to do, but I want to use the name of a command button that is pressed in excel as a variable in a macro. The macro would be as simple as setting the value of a cell to the name of the button; So if button captioned "10" is pressed the cells value would be "10", the same macro needs to work for all numeral button captions/names.
Again, sorry if this is obvious!

A: Try this, works with Forms buttons but not ActiveX buttons.
Sub Button1_Click()

    If Not IsError(Application.Caller) Then

        Dim obj2 As Object
        Set obj2 = ActiveSheet.Shapes.Item(Application.Caller)
        Debug.Print obj2.AlternativeText
    End If
End Sub

but your question asked about command buttons (the ActiveX variety) and this is more involved, we need to find the shape and then drill in via OLEFormat and two layers of IDispatch to get a reference to the command button, then we use WithEvents to fire event handler.
Option Explicit

'* Inside Sheet module

Private WithEvents mcmd As MSForms.CommandButton

Private Sub Initialise()
    Dim obj As Object
    Set obj = Me.Shapes.Item("CommandButton1")
    Set mcmd = obj.OLEFormat.Object.Object

End Sub

Private Sub mcmd_Click()

    Debug.Print mcmd.Caption

End Sub

Sadly you need to initialise code like this for every command button I think.


text:
Q: convert .htaccess to web.config on iis please could anyone help me. I have a.htaccess file that worked locally on php application uisng zend frame work. Now my application is hosted on windows with iis6.0. My application doest not load when open it on the browser. i quess there is a way one can convert .htaccess file to web.config file.
this is the re-write case-http://localhost/app
( will be re-written as:  http://localhost/app/auth/login). it is a zend frame work application.All i want to do is to convert this .htaccess to web.config
Can anyone help me? here is my code:
SetEnv APPLICATION_ENV development

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

A: It would be something like:
<configuration>
<system.webServer>
<rewrite>
  <rules>
    <rule name="Imported Rule 1" stopProcessing="true">
      <match url="^.*$" />
      <conditions logicalGrouping="MatchAny">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" />
      </conditions>
      <action type="None" />
    </rule>
    <rule name="Imported Rule 2" stopProcessing="true">
      <match url="^.*$" />
      <action type="Rewrite" url="index.php" />
    </rule>
  </rules>
</rewrite>
</system.webServer>
</configuration>

It looks like your rule just wants to make sure that if the file or directory exists do nothing, otherwise rewrite to index.php.


text:
Q: Unit-Testing an Action with NUnit I'd like to unit-test the following function with NUnit and Rhino Mocks. The function uses the given parameters to create a RestSharp.RestRequest and give the request to the dataAccessApi:
public void CopyToUserSession(string uri, string sourcePath)
{
    RestRequest request = new RestRequest(uri, Method.POST);
    request.AddParameter("source-path", sourcePath);

    dataAccessApi.Request<object>(request, restExecution.Get);
}

This is the testing Class:
public void CopyToUserSession_ValidUriAndParameter_CallDataAccessRequest()
{
    // Arrange
    var dataAccessApi = MockRepository.GenerateMock<IDataAccessApi>();
    var restExecution = MockRepository.GenerateMock<IRestExecution>();
    var sinkNodeResource = new SinkNodeResource(dataAccessApi, restExecution);

    string uri = "http://SomeUri.com";
    string sourcePath = "Some Source Path";

    RestRequest request = new RestRequest(uri, Method.POST);
    request.AddParameter("source-path", sourcePath);

    // Act
    sinkNodeResource.CopyToUserSession(uri, sourcePath);

    // Assert
    dataAccessApi.AssertWasCalled(x => x.Request<object>(request, restExecution.Get));
}

The IDataAccessApi...:
public interface IDataAccessApi
{
    void Request<T>(RestRequest request, Action<T> callbackAction) where T : new();
}

... and the IRestExecution:
public interface IRestExecution
{
    void Get(object o);

    void Put(object o);

    void Post(object o);

    void Delete(object o);
}

The test worked with easier functions to call (like x.Test("Some String")) but does not with the Action new RestExecution().Get - how do i unit-test such calls?
Thank you in advance for your help!
Edit: Changed the Code regarding @rich.okelly comment.
Edit: Added the code for the interfaces

A: Try the following:
// arrange
var dataAccessApi = MockRepository.GenerateMock<IDataAccessApi>();
var restExecution = MockRepository.GenerateMock<IRestExecution>();
var sinkNodeResource = new SinkNodeResource(dataAccessApi, restExecution);
string uri = "http://SomeUri.com";
string sourcePath = "Some Source Path";

// act
sinkNodeResource.CopyToUserSession(uri, sourcePath);

// assert
dataAccessApi.AssertWasCalled(
    x => x.Request<object>(
        Arg<RestRequest>.Matches(
            y => y.Method == Method.POST &&
                 y.Resource == uri &&
                 y.Parameters.Count == 1 &&
                 y.Parameters[0].Value as string == sourcePath
        ),
        Arg<Action<object>>.Is.Equal((Action<object>)restExecution.Get)
    )
);


text:
Q: Kubernetes StatefulSets and livenessProbes Liveness probes are supposed to trigger a restart of failed containers. Do they respect the default stateful set deployment and scaling guarantees. E.g. if the liveness probe fails at the same time for multiple pods within one and the same stateful set, would K8S attempt to restart one container at a time or all in parallel?

A: According to https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/ the liveness probes are a feature implemented in the kubelet:

The kubelet uses liveness probes to know when to restart a container.

This means any decision about scheduling that requires knowledge of multiple pods is not taken into account.
Therefore if all your statefulset's pods have failing liveness probes at the same time they will be rescheduled at about the same time not respecting any deployment-level guarantees.


text:
Q: PHP function like jquery remove() Is there a function in PHP that does the same job as jQuery's remove()?  I have this simple javascript function....
    function remove_trs (){
        $( "tr" ).remove( ".problem_display_work" );
    }

which removes all table ,
's that are class="problem_display_work" but I want to see if this can be done in PHP.
EDIT FOR CLARIFICATION
Ultimately, I'm having some HTML loaded in to a TinyMCE editor.  The function above is called via onclick of a button.  This all works well when the HTML is outside the TinyMCE editor, but it doesn't work when I place the HTML content inside the editor.  Thoughts?
Thanks.

A: You can set your class as a PHP variable in your HTML code and change the class name.
This is an example in the  tag but you can use it in your
 tag
adding and removing css classes on href

A: The code in your TinyMCE is not part of the DOM, it's a string.
But Thanks to JQuery, you can manipulate HTML strings as if they were part of the DOM.
Click the Do Stuff Str Button, to see how the table's content as string gets manipulated.
You need to adapt this example to work with the string from your TinyMCE and write the string back to the editor when you're done.

$(document).ready(function() {

  function remove_trs() {
    $("tr").remove(".problem_display_work");
  }

  function remove_trs_str(str) {
    // pass your HTML string to this function
    $str = $(str);
    $(".problem_display_work", $str).remove();
    return $str;
  }

  $("#do_stuff_dom").click(function() {
    remove_trs();
  });

  $("#do_stuff_str").click(function() {
    var html_str = $("#my_tbl").html(); // string from your TinyMCE
    var $ret = remove_trs_str(html_str);
    console.log($ret.html());
  });

});

      this will be removed

      this will be kept

<button id="do_stuff_dom">Do Stuff DOM</button>
<button id="do_stuff_str">Do Stuff Str</button>

There's really no need to pass the HTML to PHP to do what you want.


text:
Q: laravel 5.2 how to pass variable to route.php from middleware? i have a middleware, i want it to pass $role to the route.php
public function handle($request, Closure $next)
{
    if ($this->auth->check())
    {

        $role= "normal";
        $user_roles = AssignedRoles::join('roles','role_user.role_id','=','roles.id')
        ->where('user_id', $this->auth->user()->id)->select('roles.is_admin', 'roles.is_vendor')->get();
        foreach($user_roles as $item)
        {
            //var_dump($item->is_vendor);
            //die();
            if($item->is_admin==1)
            {
                $role = "admin";
            }
            if($item->is_vendor==1)
            {
                $role = "vendor";
            }
        }
        if($role=="normal"){
            return $this->response->redirectTo('/');
        }
        //$request->attributes->add(['admin' => $admin, 'vendor' => $vendor]);
        $request->attributes->add(['role' => $role]);
        View::share ('role', $role);

        return $next($request);
    }
    return $this->response->redirectTo('/');
}

is there any way to do that?
My route:
Route::group(['prefix' => 'admin', 'middleware' => ['auth']], function() {
    Route::auth();
    Route::pattern('id', '[0-9]+');
    Route::pattern('id2', '[0-9]+');

    #Admin Dashboard
    Route::get('dashboard', 'Admin\DashboardController@index');

    Route::get('vendor/{id}/edit', 'Admin\VendorController@getEdit');
    Route::post('vendor/{id}/edit', 'Admin\VendorController@postEdit');

});

A: You can do something like this:
// In your middleware
$request->offsetSet('role', $role);

Then in the routes.php:
use Illuminate\Http\Request;

Route::get('test', ['middleware' => 'auth', function(Request $request) {
    dd($request->get('role'));
}]);


text:
Q: Beginner: IF statement/PHP/HTML issue I do apologise in advance for my lack of knowledge in PHP and HTML. I have scoured the internet for 3/4 days trying to create what is probably a simple system. I need the user to enter a digit before the next page is loaded. I have an IF statement on my page.
1.php

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <link href="css/style.css" rel="stylesheet" type="text/css" />
    <link href="css/reset.css" rel="stylesheet" type="text/css" />

<form action="2.php" method="post">

Please enter your 4
 digit authorisation code:

<input type="text" name="digits" />
<input type="submit" name="submit" />
</form>

2.php
<?php
  if ($_POST['digits'] === '210392')
  {echo 'https://www.facebook.com/'
 ?>

But I need a form first which the user would input the code '210392' and press submit. Then the if statement can take place. I know how to do a form but dont know how to assign that form a variable name 'digits'. All help is appreciated.

A: A basic form:
<form action="your_file.php" method="post">
  <input type="text" name="digits" />
  <input type="submit" name="submit" />
</form>

Then in your_file.php:
<?php
  if ($_POST['digits'] === '210392') {
  // etc.

$_POST is a superglobal array that has all data POSTed to your script.  digits in this case is an index in that array.  It comes from the name of the input field.

A: You first need to create an input with the very important name attribute which you'll use later.
<form method="post">
    <input type="password" name="mypassword" />
    <button type="submit">Go</button>
</form>

PHP:
//Post method access with $_POST variable:
if ($_POST['mypassword'] == 'my-password') { //Oh, you should probably use SSH and hash the password
    //Hooray!
}

A:     <form action="https://scm-intranet.tees.ac.uk/users/l1071039/bobbin/admin.php" method="post">
      Password : <input type="password" name="pwd" />
      <input type="submit" name="send">
    </form>

    // admin.php
    <?php
    if( isset($_POST['pwd']) ){
        $pwd = $_POST['pwd'];
    }
    ?>

A: Instead of echo, use header.
   <?php
   if ($_POST['digits'] === '210392')
   {
   header (loaction:https://www.facebook.com/);
   }
   ?>

A: <form action="check.php" method="POST">
<input type="text" name="digits" />
<input type="submit" value="click here" />
</form>

//in check.php

if (isset($_POST['digits']) and $_POST['digits'] == 12345){
header("Location: http://google.com");
}
else {
echo " error !!";
}

study html from w3school
http://www.w3schools.com/html/html_forms.asp
and php
http://www.w3schools.com/PhP/php_forms.asp


text:
Q: Core Data array I am using the code below to fetch the objects in an array. In my program, I have an array displayed in a tableview and when a cell is tapped, it leads to another array displayed in a tableview. The user can add cells in both of these tableviews. What is happening is that when I create new rows in my second tableview, go back, and tap the same cell that got me there, I notice that the objects I created are not there (they were reassigned to another cell). I believe that the problem lies in the line: routines = results. What I think is happening, is that when I tap back in my second view, the line routines = results is called again, and because results is by nature unordered, it messes up the order of my previously established routines array.
var routines = [NSManagedObject]()

override func viewWillAppear(animated: Bool) {

    self.navigationItem.leftBarButtonItem = self.editButtonItem()

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext!

    let fetchRequest = NSFetchRequest(entityName: "Routine")

    var error: NSError?

    let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as! [NSManagedObject]?

    if let results = fetchedResults {
        routines = results
    } else {
        println("Could not fetch \(error), \(error!.userInfo)")
    }
}

A: I agree with the comment from Jonathan.  You are just making work for yourself holding onto everything in arrays.  Use the tools that are designed to work with both Core Data and UITableView controllers and you will have a much easier (and more maintainable) time.


text:
Q: line following robot using dsp and image processing I am taking part in a line following robot competition where we use a camera in order to follow line.
My algorithm is:
mean filter
--> Gaussian filter
--> find centroid
--> kalman filter
--> do pid for steering
--> do pid for speed of back motor

and the robot performs 98% perfectly.
My issue is that after all this filtering, sometimes I see some huge error in the reading of the camera when the robot moves, which cause small oscillation of the robot.
How can I eliminate this error?
(this small error in high speed is a big issue)

A: Probably setting up the buffers before image processing can work.
Assume of three buffers (image pages saved continuously from camera)... page1, page2, page3.
Use page1 to process the image... Then get an average image by comparing both page2 and page3, and put this resulting image on page1... then repeated the image processing from page1 again... and so on.


text:
Q: Allow property to be an array or plain type I was trying to be able to pass the property as an array of strings or just a string value.
class GetUsersDTO {
  // @IsArray() | @IsString()
  readonly status;
}

But it's not possible even though it's a common use case. Can we do it with a plain class-validator package?

A: You'll need to make your own custom validator for this. Typescript doesn't reflect generics (yes, a union type is a special generic) and because of that, class-validator won't be able to properly figure out which of the two decorators to use.
import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';

@ValidatorConstraint({ name: 'customText', async: false })
export class IsArrayOrString implements ValidatorConstraintInterface {
  validate(val: string | string[], args: ValidationArguments) {
    const isArray = Array.isArray(val);
    const isString = typeof val === 'string';
    return isArray || isString
  }
}

And now you can use it like
class GetUsersDTO {
  @Validate(IsArrayOrString)
  readonly status: string | string[];
}

My personal word of warning: using multiple allowed inputs to the same endpoint usually brings nothing but trouble and headache. If possible, keep them separate.


text:
Q: Haskell loadMatrixf Where is the OpenGL function for loadMatrixf and what is the type signature?

A: See the Matrix class.  I think you are looking for either newMatrix or the matrix StateVar in those docs.
For example: let mat be a list of 16 floats representing the matrix.  Then you would use it something like this:
import qualified Graphics.Rendering.OpenGL.GL as GL

drawThingWithMatrix :: [GL.GLfloat] -> IO ()
drawThingWithMatrix mat = GL.preservingMatrix $ do  -- instead of push/pop
    newmat <- GL.newMatrix GL.RowMajor mat          -- or ColumnMajor
    GL.currentMatrix GL.$= newmat
    -- draw your thing

That's about right I think. It has been a while.


text:
Q: Why the layout file for an ArrayAdapter has to be set twice? I'm creating an ArrayAdapter for a Spinner view.
Here's my (working) code:
val spinnerAdaptor = ArrayAdapter<String>(this@PlayerDetails, R.layout.support_simple_spinner_dropdown_item, users)
spinnerAdaptor.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item)
choose_user?.adapter = spinnerAdaptor
choose_user.onItemSelectedListener = this@PlayerDetails

When I initialise my spinnerAdaptor I set the layout file for the dropdown in the 2nd parameter. Why is setDropDownViewResource() needed? (it doesn't work when I omit this line).

A: *

*Main List item

*

*Dropdown List item

*Dropdown List item

*Main List item

*Main List item

First layout that you set in the constructor is your main list item layout, the 2nd layout is the dropdown item layout. You may want to set them differently.


text:
Q: How to get a named route from a class in rails? I have a common partial for index where i want to insert some links.
On this links i would like to use the named_routes, like
link_to "Say hi",things_path(:param1=>:hello, :params2=>:there)

but i dont know if things_path is users_path, places_path or reviews_path, because this partial is shared for all controllers. There is any way to get the named route associated to the class or the current controller.
I want something like this
link_to "Say hi", path_of(@current_class)(:param1=>:hello, :params2=>:there)

A: There are several approaches to this. The simplest thing is to rely on polymorphic routing, such as: link_to "Say hi", @my_object. In this case rails will look at the class of @my_object and its current state (new_record?) and use the appropriate route and restful action. Assuming your partial is named _foo.html.erb then this can be as simple as
link_to 'Say hi', foo

... which is pretty awesome. This question has been asked before, here: Polymorphic Routes in Rails - in views but I guess it's hard to find answers without knowing the magic words "polymorphic routing" :-)

A: A path helper like cars_path is ultimately just a shortcut to setting :controller, :action and other params like :id.  If you want to make the controller always equal to the current controller you can just say
link_to "Say hi", :action => "index", :param1=>:hello, :params2=>:there
Because the :controller option is omitted, it will be assumed to be the current controller.


text:
Q: Image attachment as part of DTO or separate upload (ASP.NET MVC 2 & WCF REST) I have an existing ASP.NET MVC 2 client application that consumes a RESTful WCF service application for data persistence. A new requirement has come up to support an image attached/associated to one of my existing domain objects (Product).
Currently, the client application calls the service to obtain a list of Products (in the form of a list of lightweight ProductInfo objects) and displays the list to the user.  When the user clicks an item in the list, the client calls the service to get the specific Product object which supports editing by the user.  When saved, the client posts the updated Product to the service for persistence.
The new requirement calls for me to display the associated image in the list as well as allow the user to set/replace the image when editing the Product.  The current image is also displayed in the Product editor.  Only one image will be associated with each Product and the image will be required.

*

*Is Stream the best way to pass the image data between client and server or should I go with Byte[]?

*For the list, would it be wise to add a new Image property to ProductInfo of type Stream (or Byte[]) or require a separate call to the service to download the image?

*Likewise for editing, do I just treat the image data as any other property and pass it back and forth across the wire using an Image property?

A:
Is Stream the best way to pass the image data between client and server or should I go with Byte[]?

This will depend on the binding you are using but with SOAP even if you choose Stream eventually when the serializer needs to send it over the wire it will be a base64 encoded byte array.

For the list, would it be wise to add a new Image property to ProductInfo of type Stream (or Byte[]) or require a separate call to the service to download the image?

I would go with a separate call to download each image given a product id. This way you won't be downloading images every time you want to view product info without previews which could save bandwidth.
Another possibility is to load all the images at one go from the WCF service and then invoke the controller action that will download them using AJAX. Then embed them in the HTML as base64 data (the way Google does with image previews in the results page)

Likewise for editing, do I just treat the image data as any other property and pass it back and forth across the wire using an Image property?

For editing you could have a service method which will take the byte array and the id of the item you are updating.

A: While I appreciate Darin's response and originally headed down that path, I ended up going with the same approach outlined in Pro ASP.NET MVC 2 Framework.
Chapter 6 describes how an image can be uploaded as part of the edit page for a Product object then displayed using a controller action in another page.  The only difference in my application is that persistence is handled in a different tier via a RESTful web service interface.  However, based on the approach shown in the book, I decided to go with a single DTO that contains properties for the binary image data and string MIME type information.
If I had a different UI or a heavier object to pass around, I would definitely reconsider this approach but for me, this time around, this works great.


text:
Q: JNI Eclipse Plugin Is there any kind of plugin that performs the task of writing a JNI-Wrapper around an existing C++ DLL?
Thanks!
Stefan

A: It isn't an Eclipse plugin, but you could take a look at SWIG.
From the documentation:

The Java extension to SWIG makes it very easy to plumb in existing C/C++ code for access from Java, as SWIG writes the Java Native Interface (JNI) code for you.


text:
Q: Getting JSON data out of Array Variable React I have a jsx file with code
var React = require('react');
var CreateReactClass = require('create-react-class');

var url = "192.168.1.1:8081/json";
let data = [];

fetch(url)
.then(response => response.json())
.then(result => data.push(result));

console.log(data);
console.log(data[1].name);

console.log(data);
returns data but I can't seem to get any specific attributes out from it.
console.log(data[1].name); just returns: TypeError: data[1] is undefined.
on the URL address I have json
[
 {
  "id": "2",
  "name": "led",
  "color": "blue"
 },
 {
  "id": "3",
  "name": "le",
  "color": "red"
  }
]

for some reason the length of my data array is 0 even after pushing json data into it.
How can I get console to log an attribute from data variable like "name":"le".

A: .fetch() is asynchronous. This console.log(data) occurs before the promise is resolved (data.push(result))
fetch(url)
.then(response => response.json())
.then(result => data.push(result))
.then( () => console.log(data))

will log the data.
One possibility is to use ES7' async feature, as explained here.

A: The results of the then calls for data are asynchronous.
That means that your console.log is fired when response and result are not even finished yet.
fetch(url).then(json => {
    console.log(json);
});

A: In your fetch do something like this.
fetch(url)
 .then(response => response.json())
 .then(result => {
    data = [ ...data, ...result ]; // spread the entire array;
    console.log('Result is=', data);
  });

P.S: The entire approach for your coding style is not very good. This is not how you should maintain data, the api result should be in some state variable. So the DOM can update if any changes happen to this data.

A:     var React = require('react');
    var CreateReactClass = require('create-react-class');

    var url = "192.168.1.1:8081/json";
    let data = [];

    fetch(url)
    .then(response => response.json())
    .then(result => data = result);

console.log(data[1].name);


text:
Q: Pagina de agradecimiento con titulo de página anterior WordPress Hola chic@s mi duda es la siguiente.
Tenemos que hacer bastantes páginas de agradecimiento para inscripción a diferentes cursos, mi pregunta es
¿Hay alguna manera de que por código se pueda rastrear el titulo de la página donde vienen y así solo hacer una página en general para todas.

La idea es solo cambiar lo que dice CQI-15 Evaluación..... (es el nombre del curso) por el titulo de la página donde viene.

A: Al inscribirse en el curso podrías pasar un parámetro GET con el ID de la página des del que se realiza la inscripción, por ejemplo http://web.com/gracias?id=12 y en la nueva página de 'Gracias' recuperar el parámetro de la URL $id = $_GET['id']; y llamar el link $link = get_permalink($id); y el título $titulo = get_the_title($id);.


text:
Q: Why does half of this XML get hidden when I try to post "code' in a question? Hello, I tried to post this XML in SO for this question
But it hides half the XML.  Please take a look at this post (if you have edit capabilities) and you will see a lot more XML than what gets shown.
====== start xml ======

  <!-- Rollover at midnight each day -->
  <param name="DatePattern" value="'.'yyyy-MM-dd"/>

  <layout class="org.apache.log4j.PatternLayout">
     <!-- The default pattern: Date Priority [Category] Message\n -->
     <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>

  </layout>

 <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>
 </layout>

====== end xml =====

A: Two issues. One, code block needs an extra blank line before it in the post body before it renders properly. The other issue is that you only have 3 spaces in front of the appenders and some of the comments. You need 4. This causes those to be treated like normal text, which then causes the following lines to get stripped along with them since they don't have the blank line preceding them.
Below is how it should probably properly look, disregarding the actual proper whitespace.

====== start xml ======
<!-- A time/date based rolling appender -->
<appender name="FILE" class="org.jboss.logging.appender.DailyRollingFileAppender">
   <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/>
   <param name="File" value="${jboss.server.log.dir}/server.log"/>
   <param name="Append" value="false"/>

   <!-- Rollover at midnight each day -->
   <param name="DatePattern" value="'.'yyyy-MM-dd"/>

   <layout class="org.apache.log4j.PatternLayout">
      <!-- The default pattern: Date Priority [Category] Message\n -->
      <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>

   </layout>
</appender>

<!-- A size based file rolling appender -->
<appender name="FILE" class="org.jboss.logging.appender.RollingFileAppender">
 <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/>
 <param name="File" value="${jboss.server.log.dir}/server.log"/>
 <param name="Append" value="false"/>
 <param name="MaxFileSize" value="10MB"/>
 <param name="MaxBackupIndex" value="20"/>

 <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>
 </layout>
</appender>

====== end xml =====


text:
Q: Copy first row in grid just want to ask if it is possible to copy the first value of the row in grid?
For example. I have two column. A and B value are. If I put any value in column B at the first row. It should be fill all the remaining row.
**Serial**   **CartNum**   Output **CartNum**
    1             1                    1
    2                                  1
    3                                  1
    4                                  1

Is this possible? I'm using ASP.NET(VB), javascript for this I think?
Here's my grid code.

  <asp:DataGrid runat="server" ID="dgSerial" AutoGenerateColumns="false" ShowFooter="false" ShowHeader="false" GridLines="None" DataKeyField="BaseLineNum" AlternatingItemStyle-CssClass="AlternateGrid">
    <Columns>
      <asp:TemplateColumn>
        <ItemTemplate>

                <asp:CheckBox runat="server" ID="chkSelect"></asp:CheckBox>

                <asp:TextBox Width="120" ID="SerialNum" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "SerialNum")%>' />

                <asp:TextBox Width="120" ID="CartNum" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "CartNum")%>' />

        </ItemTemplate>
      </asp:TemplateColumn>
    </Columns>
  </asp:DataGrid>

Hope to hear positive response.

A: Try this, it will help you

    <input type="text" id="name" onkeyup="copy();" name="name" />
    <input type="text" id="name_1" name="name_1" />
    <input type="text" id="name_2" name="name_2" />
    <input type="text" id="name_3" name="name_3" />
    <input type="text" id="name_4" name="name_4" />

A: You must edit your second row template as above:
<asp:TextBox Width="120" ID="CartNum" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "CartNum")%>'
  onchange="javascript: copy();" CssClass="row2"/>

And then add the Javascript magic:

I'm not able to test this right now, so I'm not sure that it will work fine but I'm sure it will with a few modifications.
Note that the javascript code is always taking the value from the first cell of the column (cells[0]), due in your question that was what you were asking for.


text:
Q: ConfigureRemoteApiForOAuth: invalid grant after 'gcloud auth login' Today my oauth token is expired but I am unable to regenerate it.
I have a command line tool to interact with the data store on Google Cloud Platform to carry out some support tasks.
Here are the lines of the code that is responsible for the connection
from google.appengine.ext.remote_api import remote_api_stub
remote_api_stub.ConfigureRemoteApiForOAuth(app_name, '/_ah/remote_api')

It prints out these error messages:
INFO:oauth2client.client:Attempting refresh to obtain initial access_token
INFO:oauth2client.client:Refreshing access_token
INFO:oauth2client.client:Failed to retrieve access token: {
  "error" : "invalid_grant"
}
INFO:google.appengine.tools.appengine_rpc:Got access token error
Traceback (most recent call last):
  File "/usr/local/google_appengine/google/appengine/tools/appengine_rpc_httplib2.py", line 247, in Send
    url, method=method, body=payload, headers=headers)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/oauth2client/oauth2client/client.py", line 547, in new_request
    self._refresh(request_orig)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/oauth2client/oauth2client/client.py", line 775, in _refresh
    self._do_refresh_request(http_request)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/oauth2client/oauth2client/client.py", line 840, in _do_refresh_request
    raise AccessTokenRefreshError(error_msg)
AccessTokenRefreshError: invalid_grant
Go to the following link in your browser:

    https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fappengine.apis+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&client_id=None&access_type=offline

Enter verification code:

and it follows by a url which it asks me to open in a browser.
When I copy and paste it in chrome, it is all I get

So I tried to run gcloud auth login again. I granted all the access it requested. It seems to work fine.
But when rerun my command line tool, it give the same error message.
So how can I regenerate this 'verification code'?

A: This fixed my problem
https://stackoverflow.com/a/40493992/58129
Run
 gcloud auth application-default login --scopes=https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/userinfo.email


text:
Q: Export fitted data from gnuplot in a datafile I am applying smooth bezier function to smooth a data which I have to plot. Can gnuplot give this smoothened data as well in a datafile as output ?

A: This question is already answered here: How to output smooth cspline curve as a data file


text:
Q: React and firebase setState 'you must specify the "to" property' I tried many hours but can't seem to find what I am doing wrong, I am new to react so I really appreciate your help. I first had an array state of accommodations, then I looped through them with a map function and everything was ok. But after I connected firebase with the project the map function didn't work because firebase was an object so I had to change the map function and assign Object.keys first. Then there is an error that says 'you must specify the "to" property' highlighting me the setState method. I have an image attached to the error. I am so sorry for my poor English, thank you so much for your help
ErrorImage

A: In my case. I used incorrect structure for <Link> component in an other file related to this file.
Wrong structure :
<Link href="...">

Correct structure :
<Link to="...">

after this change, it's ok.


text:
Q: Node.js route inheritance I'm very new to node.js, specifically express.js. I'm working on express.js app to export some rest apis and I found that I have many dup codes that I would like to avoid this issue. I'm seeking a best practice solution. This is my made-up examples:
// app/routes/category.js
exports.create = function (req, res) {
  categoryModel.create(someData, function (error, category) {
    if (Util.isError(error)) {
      res.send(400, error);
    } else {
      res.send(category);
    }
  });
};

// app/routes/product.js
exports.create = function (req, res) {
  productModel.create(someData, function (error, product) {
    if (Util.isError(error)) {
      res.send(400, error);
    } else {
      res.send(product);
    }
  });
};

You can see that both my create routes codes are pretty much the same but just different model (product vs category) my questions are:
1) is there a way to do inheritance in node.js/express.js?
2) is there a way to do interface in node.js/express.js?
3) what is the best way to avoid duplicate code as above samples?
4) I was thinking of it is possible to have parent class and let both category and product classes inherits from parent. I really do not how it should be done in node.js
I read couple of node.js books but I don't see authors mentioned much about how to architect app in correct or at least best practice.
I read about Prototype.js, is it the right path to go?
Any thoughts and helps would be very appreciated!

A: There's no need for inheritance (especially since handlers have to be functions so it's hard for me to see how you can use inheritance here). You can simply create a function generator:
var generate_handler = function(model) {
  return function(req, res) {
    model.create(someData, function (error, obj) {
      if (Util.isError(error)) {
        res.send(400, error);
      } else {
        res.send(obj);
      }
    });
  };
};

and then you do
// app/routes/category.js
exports.create = generate_handler(categoryModel);

// app/routes/product.js
exports.create = generate_handler(productModel);


text:
Q: Search using wildcard character in Bootstrap-table Is it possible in Bootstrap-table to search in the table, using the wildcard character * ?
For example, in this table I want to search the word *blog* in order to filter the records which contain the word blog.


text:
Q: Starting with tabbed metabox I need a tabbed metabox for my plugin.
Actually they are 5 metaboxes each one in a tab.
I found these scripts:
https://speckyboy.com/10-simple-code-snippets-creating-beautiful-tabs/
Which one is best for using in meta boxes?
It's better to have only CSS ? JS must be registered ?
I want to start testing these scripts but would like advice on where to start.
thank you

A: First, you have to create the metabox. Then you have to add tabs to the metabox.
For the first step, to create a metabox, here is a tutorial for you. You can use that as bases for your metabox, and maybe modify it according to your needs.
For the second step, you have to add tabs to your metabox. This question has been asked before in Stack Overflow, and you can follow steps describe in the answer to setup your tabs.
Please remember, WordPress uses the JQuery UI Tabs widget. So you can find examples here and detailed documentation here.
Hope this helps.

A: I've founded the best solution and used redux framework. It really provides what I was looking for.