text:
Q: Finding constants to get a required frequency from a discrete signal processing function I use a simple filter in my programing for many situations. Mathematically I think its called a progression.
The function takes the form.
func (v){
   c = (c + (v - r) * a) * b;
   r = r + c;
   return r;
}

where

*

*$v$ is any number and is the input value, each time step it may be a different.

*$a$ and $b$ are constants within the range $0 < a$ and $0 < b < 1$

*$c$ is the change over the time step, it is static (programing lingo for it remembers its last value). Its initial value is normally $c = 0$

*$r$ is the result, it is static. It initial value is set to $v$ on the first time step.

It can be thought of as a signal processing function. The function has the effect of smoothing out a signal.
The following images show the response of $c$ (green) and $r$ (red) to the input $v$ (blue) over time

As you can see the value of $r$ approaches $v$ over time, the signal is smoothed out.
For some values of $a$,$b$ I get a the following response.

The value of $r$ and $c$ oscillate over time. As long as $b < 1$ the oscillations seem to flatten out.
I am very interested in the period of the oscillations. From experimentation, for the same values of $a$ and $b$ and no matter the input value $v$ the oscillations seem to have a constant period (to within my ability to measure it)
What I would like to do is find what values of $a$,$b$ I can use to get a specific frequency.
My current and ugly solution is a statistical solution, where I sample the frequency of $c$ over many different values of $a$,$b$ and for many different input signals $v$.  I can then select a value for $b$  and use the table to find what value $a$ should be for a required frequency.
The following image show a some of the sampled data and hints to me that there is a formula that will fit this data.

$b$ is on the x axis, $a$ is the colour coded index and the y axies is increasing period going up (high frequencies are down with infinity at $y = 0$)
My solution is not accurate especially at higher frequencies.
Is there a way to compute possible values of $a$ and $b$ given a required period/frequency?
My best attempt is this
$f(b)\ =0.8+\left(1.2-a\right)\frac{\left(1.2-a+\frac{\left(b-0.4\right)}{2}\right)^{2\left(1.2-a\right)}}{\frac{\left(b-0.4\right)}{2}}$
$f(b)$ returns the period. It is just a guess on my part but its close as it has a similar look the the sampled data when I change the value $a$ but I have given up on playing with the constants to find a fit.
It looks like this

Sorry I have no idea what tags this should come under, hope I got it correct.
Any help is appreciated if just to point me in the right direction or tell me it's not possible. Thank you. :)

A: In signal processing terms you've implemented a recursive filter. The difference equations corresponding to your code are
$$\begin{align}c[n]&=b\cdot (c[n-1]+a\cdot(x[n]-y[n]))\\
y[n]&=y[n-1]+c[n]\end{align}\tag{1}$$
where I've followed the convention to use $x[n]$ for the input signal, and $y[n]$ for the output signal.
Such recursions can be solved using the Z-transform. Applying the Z-transform to $(1)$ gives:
$$\begin{align}C(z)&=b\cdot [C(z)z^{-1}+a\cdot(X(z)-Y(z))]\\
Y(z)&=Y(z)z^{-1}+C(z)\end{align}\tag{2}$$
which can be solved for $Y(z)$ in terms of $X(z)$:
$$H(z)=\frac{Y(z)}{X(z)}=\frac{ab}{1+(ab-b-1)z^{-1}+bz^{-2}}\tag{3}$$
The function $H(z)$ is called the system's transfer function. It completely characterizes the system.
The roots of the denominator of $(3)$ determine whether the system's response to a step oscillates or not. If the roots are real-valued there is no oscillation, and if there are complex-conjugated roots there will be oscillations.
Let us define $d=ab-b-1$. Then the roots of the denominator of $(3)$ are
$$z_{\infty}=-\frac{d}{2}\pm\sqrt{\frac{d^2}{4}-b}\tag{4}$$
So there are only oscillations if $b>\frac{d^2}{4}$, i.e., if there are complex roots. The frequency of the oscillations is determined by the angle of the complex roots. Assuming $b>\frac{d^2}{4}$, we have
$$\theta=\arg\{z_{\infty}\}=\begin{cases}\arctan\left(-2\frac{\sqrt{b-\frac{d^2}{4}}}{d}\right),&d<0\\
\arctan\left(-2\frac{\sqrt{b-\frac{d^2}{4}}}{d}\right)+\pi,&d>0\end{cases}\tag{5}$$
The oscillation frequency is simply $f_0=\theta/(2\pi)$.


text:
Q: Magento 2 custom xml schema validation This is a follow up of Magento 2 xml validation:
I understood how to map xsi:noNamespaceSchemaLocation in my IDE so I will get real time validation of my xmls.
But what if I have to create my own config file with it's own validation schema?
What value should I put for xsi:noNamespaceSchemaLocation ?
Right now I have this in class.xml:
<?xml version="1.0"?>
<classes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="class.xsd">
   ....
</classes>

This works nicely, because class.xsd is in the same folder as my class.xml.
But I plan to make my module extensible and actually composed from multiple modules.
Now I use in the additional modules a relative path to the class.xsd file and this seams a bit wrong.
<?xml version="1.0"?>
<classes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../Base/etc/umc/class.xsd">
   ....
</classes>

Obviously I cannot use urn:magento:framework... because my module is not in the framework, and I also cannot use urn:magento:module... because mine is not a core module. Or can I use the latter?
Or should I use a custom urn?
And (last one) if I use a custom urn will this be picked up automatically by the command bin/magento dev:urn-catalog:generate or should I dos something special?

A: It should be urn:magento:module:<Vendor_Module>:<path>
The command will work since it filters out urns that begin with urn:magento
https://github.com/magento/magento2/blob/2.2-develop/app/code/Magento/Developer/Console/Command/XmlCatalogGenerateCommand.php#L118

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does Python support declaring a matrix column-wise? In Python numpy when declaring matrices I use np.array([[row 1], [row 2], . . . [row n]]) form. This is declaring a matrix row-wise. Is their any facility in Python to declare a matrix column-wise? I would expect something like - np.array([[col 1], [col 2], . . . [col n]], parameter = 'column-wise') so that a matrix with n columns is produced.
I know such a thing can be achieved via transposing. But is there a way for np.array([...], parameter = '...') being considered as a row or column based on the parameter value I provide?
***np.array() is just used as a dummy here. Any function with above desired facility will do.

A: At the time of array-creation itself, you could use numpy.transpose() instead of numpy.array(), because numpy.tranpose() takes any "array-like" object as input:
my_array = np.transpose ([[1,2,3],[4,5,6]])
print (my_array)

Output:
[[1 4]
 [2 5]
 [3 6]]

A: In [65]: np.array([[1,2,3],[4,5,6]])
Out[65]:
array([[1, 2, 3],
       [4, 5, 6]])

There's a whole family of concatenate functions, that help you join arrays in various ways.
stack with default axis behaves much like np.array:
In [66]: np.stack([[1,2,3],[4,5,6]], axis=0)
Out[66]:
array([[1, 2, 3],
       [4, 5, 6]])

np.vstack also does this.
But to make columns:
In [67]: np.stack([[1,2,3],[4,5,6]], axis=1)
Out[67]:
array([[1, 4],
       [2, 5],
       [3, 6]])

np.column_stack([[1,2,3],[4,5,6]]) does the same.
transposing is also an option: np.array([[1,2,3],[4,5,6]]).T.
All these '*stack' functions end up using np.concatenate, so it's worth your time to learn to use it directly.  You may need to add dimensions to the inputs.
[66] does (under the covers):
In [72]: np.concatenate((np.array([1,2,3])[:,None], np.array([4,5,6])[:,None]),axis=1)
Out[72]:
array([[1, 4],
       [2, 5],
       [3, 6]])


text:
Q: "Interpolate previous value" of the same table in SQL I faced with a problem where I need to do something that works as interpolate previous value in join, but not from the table I join but from the original one. Let me explain:
Table A:

Item Package Start_date Finish_date
 X   12345   2020-01-01 2020-02-01
 X   6789    2020-02-02 2020-03-02

Table B

Item   Date
 X   2020-01-15
 X   2020-02-15
 X   2020-03-15

I want to know, in which package from table A was my Item at date from Table B. So I do:
select Item, Date, Package
from B
left join A on (B.Item = A.Item and B.Date between StartDate and FinishDate)

and I get:
Item  Date      Package
X   2020-01-15  12345
X   2020-02-15  6789
X   2020-03-15  NULL

but instead of null I'd like to see the last non-empty value of Package, event if the date is out of date range (here it will be 6789).
Does anyone know how to do that?

A: Although you can comfortably use a left join with INTERPOLATE PREVIOUS VALUE here, there might be data constellations where you need the exact complex join predicate, with an equi and a BETWEEN predicate combined, that you are using.
If you need that (I can't come up with cases where you would off the top of my head, so help me there) it would be a simple OLAP, Window, function that is available in Vertica: LAST_VALUE(<_expression_> IGNORE NULLS), which returns the last non-null value in the OLAP window.
But I doubt you need it, so I add both solutions here below.
Repeating your input in an initial WITH clause involving two Common Table Expressions, with your join, it should look like this:
WITH
a(item,package,start_date,finish_date) as (
          SELECT 'X',12345,DATE '2020-01-01',DATE '2020-02-01'
UNION ALL SELECT 'X',6789,DATE '2020-02-02',DATE '2020-03-02'
)
,
b(item,date) AS (
          SELECT 'X',DATE '2020-01-15'
UNION ALL SELECT 'X',DATE '2020-02-15'
UNION ALL SELECT 'X',DATE '2020-03-15'
)
SELECT
  b.item
, b.date
, LAST_VALUE(a.package IGNORE NULLS) OVER(w) AS package
FROM b
LEFT JOIN a
 ON a.item=b.item
AND b.date BETWEEN start_date AND finish_date
WINDOW w AS(PARTITION BY b.item ORDER BY b.date)
ORDER BY 2;
-- out  item |    date    | package
-- out ------+------------+---------
-- out  X    | 2020-01-15 |   12345
-- out  X    | 2020-02-15 |    6789
-- out  X    | 2020-03-15 |    6789

The INTERPOLATE PREVIOUS VALUE left join predicate works, though, also in this data constellation, as you can see here below.
WITH
a(item,package,start_date,finish_date) as (
          SELECT 'X',12345,DATE '2020-01-01',DATE '2020-02-01'
UNION ALL SELECT 'X',6789,DATE '2020-02-02',DATE '2020-03-02'
)
,
b(item,date) AS (
          SELECT 'X',DATE '2020-01-15'
UNION ALL SELECT 'X',DATE '2020-02-15'
UNION ALL SELECT 'X',DATE '2020-03-15'
)
SELECT
  b.item
, b.date
, a.package
FROM b
LEFT JOIN a
 ON a.item=b.item
AND b.date INTERPOLATE PREVIOUS VALUE start_date
ORDER BY 2;
-- out  item |    date    | package
-- out ------+------------+---------
-- out  X    | 2020-01-15 |   12345
-- out  X    | 2020-02-15 |    6789
-- out  X    | 2020-03-15 |    6789

Worth trying which is quicker - the range join predicate or the INTERPOLATE PREVIOUS VALUE predicate.
Worth checking which version is quicker - and you're not always in the comfortable position of having a finish_date to play with ...
Can you try both, and tell us which one was quicker?

A: Use two joins.  One for the match and one for the default:
select b.Item, b.Date,
       coalesce(a.Package, adef.Package) as Package
from B left join
     A
     on B.Item = A.Item and
        B.Date between A.StartDate and A.FinishDate left join
     (select a.*,
             row_number() over (partition by item order by StartDate desc) as seqnum
      from a
     ) adef
     on adef.item = B.item and
        adef.seqnum = 1 and
        a.item is null;

EDIT:
You could actually combine this into one join:
select b.Item, b.Date, a.Package
from B left join
     (select a.*,
             row_number() over (partition by item order by StartDate desc) as seqnum
      from a
     ) a
     on adef.item = B.item and
        B.Date >= A.StartDate and
        (B.Date <= A.FinishDate or
         (B.Date > A.FinishDate and seqnum = 1)
        );


text:
Q: dynamic page caching in rails How to add dynamic caching to time or I should use fragment caching?
I tried to follow RailsCasts but nothing works.
_feed.html.rb
<% cache feed do %>

    <%= render 'shared/time' unless @page_caching %>

<%= time_ago_in_words(feed.posted_at) %>

<%= image_tag feed.profile_pic, :class => 'pic', :size => '15x15' %> @<%= feed.name %>

<%= raw auto_link(feed.content, :username_include_symbol => true, :target => '_blank') %>

<% end %>

_time.html.rb

<%= time_ago_in_words(feed.posted_at) %>

index.js.rb
$('#feeds').append('<%= j render(@feeds) %>');
<% if @feeds.next_page %>
  $('.pagination').replaceWith('<%= j will_paginate(@feeds) %>');
<% else %>
$('.pagination').remove();
<% end %>

$('#time').prepend('<%= j render("shared/time") %>');

feeds_cotroller.rb
  def index
    @page_caching = true
    @feeds = Feed.page(params[:page]).per_page(12)
  end

A: using helpers that changes over time should not be used inside a cache block.  The best solution to this is to use a js plugin that will insert the time string for you.  google for timeago js plugin and you'll get a bunch of useful results.  The first result there is in http://timeago.yarp.com/.  Using that plugin,  your code should look like the following (i've inserted a script which should insert the time string)
<% cache feed do %>

      <%= render 'shared/time' unless @page_caching %>

    <p class="pull-right grey timeago" title="<%= feed.posted_at %>">

        <%= image_tag feed.profile_pic, :class => 'pic', :size => '15x15' %> @<%= feed.name %>

<%= raw auto_link(feed.content, :username_include_symbol => true, :target => '_blank') %>

<% end %>

This is a simple implementation.  You probably want to move the js call to an asset file so you dont have to call it inside the cache.  Anyway, this should give you an idea.


text:
Q: NPE after !=null I'm using an Accessibility Service and I'm facing a very strange NPE.
Inside the onAccessibilityEvent(AccessibilityEvent event) method I have this code.
if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_CLICKED
       && event.getSource() != null) {
            AccessibilityNodeInfo source = event.getSource();

            if (waiting && source.isEditable()) {
                .....

            }else if (!waiting && source.isEditable()) {
               .....
            }

The crash reports I'm receiving say that isEditable() is being performed on a null pointer even though I checked that it's not null. Unfortunately this does not happen on any of my devices. And another strange thing is that the NP is only in the else if, the if is checked without any problems.
This was my previos code
AccessibilityNodeInfo source = event.getSource();
if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_CLICKED
       && source != null) {....

I was advised by a friend to switch to the first code (check then assign), but it still didn't help
Thanks for any help in advance.
Edit: waiting is false most of the time,I think that is way the NPE is mostly thrown from the else if
Edit 2:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.view.accessibility.AccessibilityNodeInfo.isEditable()' on a null object reference
  at  com.dhm47.nativeclipboard.AccesService.onAccessibilityEvent(AccesService.java:184)
  at android.accessibilityservice.AccessibilityService$1.onAccessibilityEvent(AccessibilityService.java:659)
  at android.accessibilityservice.AccessibilityService$IAccessibilityServiceClientWrapper.executeMessage(AccessibilityService.java:752)
  at com.android.internal.os.HandlerCaller$MyHandler.handleMessage(HandlerCaller.java:37)
  at android.os.Handler.dispatchMessage(Handler.java:102)
  at android.os.Looper.loop(Looper.java:135)
  at android.app.ActivityThread.main(ActivityThread.java:5254)
  at java.lang.reflect.Method.invoke(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:372)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

The isEditable() is a part of Android see isEditable()


text:
Q: Connecting DB request to API - Android I would like to do something, I don't know how to do it. But before, let me explain the previous steps:
1st: I have defined a content manager that, when I introduce a specific "id" from a resource, it finds such reosurce and shows it to me. In addition, I have created a POJO for the resource and an interface in which I specifiy my request.
2nd: Now I want to be able to incorporate such resources into a local data base. So, I have defined my entity for such data base (and that entity has the same attributes that the resource (consulted) from the API). Then I have defined the contract for such entity and the repository for that entity (where I have defined my query as "WHERE field "name" = (...)" .
3rd: After that, I have defined a ContentProvider for my DB.
4th: Finally, there is my MainActivity, which acts as a Client to consult my DB through my content provider.
Now, my question is, how and where I have to define the next:
a) When I make a search -based on the attribute name of the resource-, if the content provider doesn't find it in my local DB, then a request is made to the API (and the name specified on my search should fit with the attribute "name"
of the resource in the API).
b)Once the response with the resource is given, my local DB should add that resource as a new entity.
Thanks.
I hope I have explained myself well.


text:
Q: iPad app become inactive after locking screen In my application, I'm downloading and uploading data at some point of time on a separate thread using NSOperation. Both process take approx. 2-3 min. If application remains active then everything works fine. But if the iPad screen is locked (automatically or manually), the app becomes inactive and download/upload get paused and when screen is unlocked after some time process failed with timeout error.
I have "App plays audio" for "Required background modes" in plist file. Do I need to set any other flag for running app while screen is locked?
Please help me what is going wrong.

A: When the screen is locked, your app becomes inactive. Per "Responding to Interruptions" in iOS App Programming Guide:

Pressing the Sleep/Wake button is another type of interruption that causes your app to be deactivated temporarily. When the user presses this button, the system disables touch events, moves the app to the background but sets the value of the app's applicationState property to UIApplicationStateInactive (as opposed to UIApplicationStateBackground), and finally locks the screen.

You can get extra time for background tasks according to "Executing a Finite-Length Task in the Background" in the same guide:

Apps that are transitioning to the background can request an extra amount of time to finish any important last-minute tasks. To request background execution time, call the beginBackgroundTaskWithExpirationHandler: method of the UIApplication class. If your app moves to the background while the task is in progress, or if your app was already in the background, this method delays the suspension of your app. This can be important if your app is performing some important task, such as writing user data to disk or downloading an important file from a network server.

You can refer to the document to implement a finite-length download task in the background.
Other references:

*

*Download data in background with iOS4

*iOS Application Background Downloading


text:
Q: JupyterLab editor ignores indent setting an notebooks When using JupyterLab, the indent setting seems to be ignored on notebook files (.ipynb). Tested with jupyterlab 3.1.1 (installed from pypi).
My user settings of the JupyterLab editor contains the following setting:
{
    "editorConfig": {
        "cursorBlinkRate": 530,
        "fontFamily": null,
        "fontSize": null,
        "lineHeight": null,
        "lineNumbers": true,
        "lineWrap": "on",
        "wordWrapColumn": 80,
        "readOnly": false,
        "tabSize": 4,
        "insertSpaces": false,
        "matchBrackets": true,
        "autoClosingBrackets": false,
        "rulers": [],
        "codeFolding": false
    }
}

I would expect, that the editor inserts a tab character when indenting with the tab-key, but it still inserts 4 spaces.
Jupyther notebook is able to insert tabs. I have the following settings in ~/.jupyter/nbconfig/notebook.json:
{
  "CodeCell": {
    "cm_config": {
      "indentWithTabs": true
    }
  }
}

With this setting, the normal notebook-editor is inserting tabs instead of spaces.
Is it possible, to have JupyterLab using tabs for indent characters on notebooks as well?

A: This editor setting is not affecting notebooks (at least not yet).
To get indentation with tabs (or other number of spaces than 4) in notebooks, you need to go to "Settings"->"Advanced Settings Editor". In the left pane select "Notebook" and insert the following in the user settings pane:
{
    "codeCellConfig": {
        "insertSpaces": false
    },
    "markdownCellConfig": {
        "insertSpaces": false,
    },
    "rawCellConfig": {
        "insertSpaces": false,
    }
}

See https://github.com/jupyterlab/jupyterlab/issues/10751#issuecomment-890181712


text:
Q: Using Java, how do I delete two lines in a text file after reading them?   try {

        OutputStreamWriter writer = new OutputStreamWriter(
              new FileOutputStream("x.txt", true), "UTF-8");
        BufferedWriter fbw = new BufferedWriter(writer);
        fbw.write(newemails + ":" + passwordEntered);
        fbw.newLine();
        fbw.close();
        System.out.println("Poo");
    }catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    }

I am developing a program which creates accounts on a website and saves the details of these accounts into a text file. Then, another application reads this text file and extracts the account details. It is important for the application to not login in using the same account details. Therefore, I would like to make a program which deletes a couple of lines in the text file and then saves it, so that the application can log in using different account details. Above is the code I have for writing the email and the password to a text file.


text:
Q: Adafruit_NeoPixel objects abnormal behavior when used in an array I've been having problems trying to work out how to loop through an array of Adafruit_NeoPixel objects.
But I cant for the life of me get my head aroud what is going wrong. Ive looked up this issue on google and trough both Ardrino and stack over flow ive tryed adapting the code to what ive seen other people have done (for example instead of listing the adafruit_neopixles objects in the array,create the neopixles inside the array) to get it to work and still I have no luck.
so heres an simple example: this script should make the first 6 Leds light up in green blue
#include <Adafruit_NeoPixel.h>

Adafruit_NeoPixel strips[] = {
  Adafruit_NeoPixel(32, 5, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(32, 6, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(32, 7, NEO_GRB + NEO_KHZ800),
};

#define NUMSTRIPS (sizeof(strips)/sizeof(strips[0]))

void setup() {
     //Edit2
         Serial.begin(115200);
     //end Edit2

  for(int i=0; i<NUMSTRIPS; i++)
  {
    strips[i].begin();
    strips[i].setBrightness(255); //adjust brightness here

    /*This is code that ive added in AFTER i made the orgional post to see if it had any difference
    */
        for (int j=0; j<10;j++){
          strips[0].setPixelColor(j, 0,100,0);
      }

     /* End of edited code
     */
    strips[i].show(); // Initialize all pixels to 'off'
  }
  //Edit2
    Serial.println("Loop end");
  //End Edit2

  //strips[0].begin();
  strips[0].setBrightness(255);
  strips[0].setPixelColor(0, 0,100,255);
  strips[0].setPixelColor(1, 0,100,255);
  strips[0].setPixelColor(2, 0,100,255);
  strips[0].setPixelColor(3, 0,100,255);
  strips[0].setPixelColor(4, 0,100,255);
  strips[0].setPixelColor(5, 0,100,255);
  strips[0].show();
}

However that does nothing no led's light up at all. -WHY!?
Yet when I comment out the For loop and un-comment the strips[0].begin it does work.
So why is this? what am I not able to understand?
EDIT: So I tried changing a few things in my code to test if it had any affect
i added in
    for (int j=0; j<10;j++){
          strips[0].setPixelColor(j, 0,100,0);
      }

it worked inside the loop but now anything after the loop no longer works.
EDIT 2: so after using serial i found out that the device is crashing when the loop ends. So why would that be?.
Edit 3:
First I would like to say sorry to ocrdu they tried to edit this but still not quite had the right idea.
Second I want to say that half the problem has been worked out the abnormal behavior was caused by the micro controller crashing when ever the strips were being illiterate through. As for the why that is still what I need help to understand.
So I made it through 1 loop now before it crashes so progress? I took Botje's advice and I used strips[i].numPixels(); instead of using a fixed value
however I decided to do a few more tests to see if I had fixed the problem and well it crashed before test 2 even got to start. Here is the new code.
#include <Adafruit_NeoPixel.h>

Adafruit_NeoPixel strips[] = {
  Adafruit_NeoPixel(32, 5, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(32, 6, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(32, 7, NEO_GRB + NEO_KHZ800),
};

#define NUMSTRIPS (sizeof(strips)/sizeof(strips[0]))

void setup() {
  Serial.begin(115200);

  Serial.println("1st Test Do a loop with out crashing over all the strips");
  for(int i=0; i<NUMSTRIPS; i++)
  {
    strips[i].begin();
    strips[i].setBrightness(255);
    for (int j=0; j<strips[i].numPixels();j++){
          strips[i].setPixelColor(j, 0,100,0);
          Serial.println(j);
      }
    Serial.println("b4 show");
    strips[i].show();
  }
  Serial.println("Loop end");
  Serial.println("If you are reading this then the microcontroller did not crash on 1st Test");

  delay(150);

  Serial.println("2nd Test Do a loop with out crashing over 1 strip");
  for (int k=0; k<strips[0].numPixels();k++)
  {
    strips[0].setPixelColor(k, 0,100,255);
    strips[0].show();
    Serial.println(k);
  }
  Serial.println("Loop end");
  Serial.println("If you are reading this then the microcontroller did not crash the 2nd Test");

  delay(150);

  Serial.println("3rd Test Do a loop changing onley 6 pixles on 1 strip with out crashing");
  for (int l=0; l<=5; l++)
  {
    strips[0].setPixelColor(l, 200,0,0);
    strips[0].show();
    Serial.println(l);
  }
  Serial.println("Loop end");
  Serial.println("If you are reading this then the microcontroller did not crash the 3rd Test");
}

A: So I've fixed this issue by swapping out the adafruit liabery with fastled no more crashing or abnormal behaviour.


text:
Q: How do I reverse a sentence in python? I've been searching for a way to reverse sentences, but I can't seem to find one.  I was hoping to find a way in Python; however, I'm not sure if there is a way to do it.  If anybody knows of a way to do it, I would really appreciate the help.

A: Reversing the string is quite easy:
just add the index to the end of each value:
q = 'qwerty'
k = ''
for i in q:
    k = i+k
print(k)

A: Here's a way off the top of my head, but there may be a more efficient way.
a = "this is a sentence"
b = "".join([a[i] for i in reversed(range(len(a)))])

b should now contain 'ecnetnes a si siht'

A: This would reverse "the quick brown fox" to "xof nworb kciuq eht". Is that what you mean?
str1 = "the quick brown fox"
str2 = ""

for i in range(len(str1)):
    str2 += str1[(len(str1)-i)-1]

print(str2)


text:
Q: Call to undefined method exception in laravel/php I'm getting a row form the table and try to update like this;
{
      $db_dw = \DB::connection('sqlsrvdw');
            $factAlarm= $db_dw->table('ALARM')->where([['AlarmId',$id],['MostRecentFlag',1]])->first();
            print_r($factAlarm);  --->This prints my row

     $this->updateFactAlarm($factAlarm);
-----------------
   }

    private function updateFactAlarm($factAlarm){
        $factAlarm->AlarmActionDescription= request('ackNotes');
        $factAlarm->IsAcknowledged = 1;
        $factAlarm->update();

    }

I get following error
Call to undefined method stdClass::update()

Even if I use save() method I get same error
Call to undefined method stdClass::save()

What is wrong with my approach?

A: update() or save() are methods that can be used on an Eloquent model, and $factAlarm is not one. You should define the Alarm model and use Eloquent to query the table. Also please follow the naming conventions stated in the docs.


text:
Q: use of app file in products folder in xcode 5 I wish to know the usage of .app file that comes in products folder while creating an xcode project for iOS.
app file appears red when run in simulator, but appears when run in device.
I right clicked on this file while running it in device. Now how can I use this app file?
What is the use of this file? Please let me know.

A: What's sometimes useful is to check all assets that get copied into your app bundle. Right-click the file and click 'Show in finder'. Then when you right-click it and 'Show package contents' you can browse all the files that got copied into your target app. If something is missing there you didn't add it to your target.
Other then that, XCode manages the installation of your app file on the device and in the simulator, and when you create an Ad-hoc/Appstore archive so you basically don't need to use it.
The fact that it is red means it doesn't exist (yet). Since it refers to the build product of the device and not simulator it's only created after you have build your project for iOS device.


text:
Q: Equivalent of JEditorPane.modelToView( ) in a JavaFX WebView In Swing, if I'm displaying text in a JEditorPane and I need to get the XY coordinates for a certain index within the text, I can use
Point p = jep.modelToView(idx);

, where jep is the name of my JEditorPane and idx is the int value of the index I'm interested in.
How can I do the same using a WebView in JavaFX?


text:
Q: Spring MVC, force JSON response in plain request I am using Spring 3.0.6 and i have a single controller for uploading files to the server. I am using a script to upload using XmlHttpRequest for browsers that support it while the rest of the browsers submit a (hidden) multipart form. The problem however is that when a form is submitted it sends the following header:
Accept  text/html, application/xhtml+xml, */*

I figure that due to this header the Controller which is marked with @ResponseBody replies with the response been converted to XML instead of JSON. Is there a way to get around this without hacking the form submit request?

A: You can force JSON using @RequestMapping(produces = "application/json"). I don't remember if this is available in 3.0 but it is available in 3.1 and 3.2 for sure.
As others noted, Jackson needs to be on your classpath.

A: Thank you!  I was having exactly the same issue and your post resolved my problem.
On the UI I'm using JQuery with this file upload plugin:
https://github.com/blueimp/jQuery-File-Upload/wiki
Here's my completed method (minus the biz logic):
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
public void  handleUpload( @RequestParam("fileToUpload") CommonsMultipartFile uploadFile, ServletResponse response){

    List<UploadStatus> status = new ArrayList<UploadStatus>();
    UploadStatus uploadStatus = new UploadStatus();
    status.add(uploadStatus);

    if(uploadFile == null || StringUtils.isBlank(uploadFile.getOriginalFilename())){
        uploadStatus.setMessage(new Message(MessageType.important, "File name must be specified."));
    }else{
        uploadStatus.setName(uploadFile.getOriginalFilename());
        uploadStatus.setSize(uploadFile.getSize());
    }
    ObjectMapper mapper = new ObjectMapper();
    try {
        JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8);
        mapper.writeValue(generator, status);
        generator.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

A: If you want a JSON response, you can easily accomplish that by having the Jackson JARs on your classpath.  Spring will auto-magically pick up on them being there and will convert your @ResponseBody to JSON.

A: I made it work by getting rid off @ResponseBody and instead doing manually the conversion (always using Jackson), i.e.
Response r = new Response();
    ObjectMapper mapper = new ObjectMapper();
    JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8);
    try {
        File f = uploadService.getAjaxUploadedFile(request);
        r.setData(f.getName());
    } catch (Exception e) {
        logger.info(e.getMessage());
        r = new Response(new ResponseError(e.getMessage(), ""));
    }
    mapper.writeValue(generator, r);
    generator.flush();

Does anyone know another way? I tried setting up a ContentNegotiatingViewResolver but i don't want to break any other controllers by assigning all hmtl to json. Also, i tried to do it for this method only via a custom viewresolver but when i setup a jsonview and use BeanNameViewResolver although the response is correctly converted to JSON the server throws an
HttpRequestMethodNotSupportedException: exception, with Request method 'POST' not supported and set status to 404.


text:
Q: How to generate random password with PHP? Or is there a software to auto generate random passwords?

A: Just build a string of random a-z, A-Z, 0-9 (or whatever you want) up to the desired length.  Here's an example in PHP:
function generatePassword($length = 8) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $count = mb_strlen($chars);

    for ($i = 0, $result = ''; $i < $length; $i++) {
        $index = rand(0, $count - 1);
        $result .= mb_substr($chars, $index, 1);
    }

    return $result;
}

To optimize, you can define $chars as a static variable or constant in the method (or parent class) if you'll be calling this function many times during a single execution.

A: I want to play the game. The simplest way would be to do:
function rand_passwd( $length = 8, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ) {
    return substr( str_shuffle( $chars ), 0, $length );
}

This is pretty much just a modification of the first answer. Specify the characters you want in the second parameters and the length of the password in the first.

A: This is how I do it.
$pw = "";
for ($i = 0; $i < 13; $i++)
{
    $pw .= chr(rand(33, 126));
}

A: here is a function that generates a password with a minimum length, a minimum number of digits and a minimal number of letters.
function generatePassword() {
$min_length=8;  //Minimum length of the password
$min_numbers=2; //Minimum of numbers AND special characters
$min_letters=2; //Minimum of letters

$password = '';
$numbers=0;
$letters=0;
$length=0;

while ( $length <= $min_length OR $numbers <= $min_numbers OR $letters <= $min_letters) {
    $length+=1;
    $type=rand(1, 3);
    if ($type==1) {
        $password .= chr(rand(33, 64)); //Numbers and special characters
        $numbers+=1;
    }elseif ($type==2) {
        $password .= chr(rand(65, 90)); //A->Z
        $letters+=1;
    }else {
        $password .= chr(rand(97, 122)); //a->z
        $letters+=1;
    }

}
return $password;
}

A: Another, very simple (and secure!) way to do this is the following (I generate all my own passwords that way):
base64_encode(random_bytes(12));

This generates a 16 character password that uses quite a sane range of characters.
However, depending on your requirements (for example if a user needs to type in their password), it may be desirable to remove characters that migth be confused (such as l, I, 1, 0, O, 5, S, and so on). In that case, the above solution is probably a bit too simple.

A: A good password should be a mixture of both uppercase, lowercase, has number, letters, has special characters and its more than 6 characters long. Here is function I use on my apps.
function randomPassword( $length = 8 )
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?";
$length = rand(10, 16);
$password = substr( str_shuffle(sha1(rand() . time()) . $chars ), 0, $length );
 return $password;
}

A: Here's a simple solution. It will contain lowercase letters and numbers.
substr(str_shuffle(strtolower(sha1(rand() . time() . "my salt string"))),0, $PASSWORD_LENGTH);

Here's A stronger solution randomly generates the character codes in the desired character range for a random length within a desired range.
function generateRandomPassword() {
  //Initialize the random password
  $password = '';

  //Initialize a random desired length
  $desired_length = rand(8, 12);

  for($length = 0; $length < $desired_length; $length++) {
    //Append a random ASCII character (including symbols)
    $password .= chr(rand(32, 126));
  }

  return $password;
}

A: Also you can try a function that I wrote and is available form my blog. Advantage of this function is that it gives equal importance to lowercase, uppercase, numbers and special characters. It can be found here
PHP random password generator function

A: I like to shuffle array of random chars
$a = str_split("abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXY0123456789");
shuffle($a);
echo implode($a); //maxlength
echo "\n".substr( implode($a), 0, 10 ); //instead of 10 => any length

//As function:
function getMeRandomPwd($length){
    $a = str_split("abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXY0123456789");
    shuffle($a);
    return substr( implode($a), 0, $length );
}
echo "\n".getMeRandomPwd(8)."\n".getMeRandomPwd(11);
// Outpus something like:
// 3Ai4Xf6R2I8bYGUmKgB9jpqo7ncV5teuQhkOHJCNrTP0sLFd1wxSMlEWvyaD
// 3Ai4Xf6R2I
// JsBKWFDa
// gfxsjr3dX70

If you need the password to be longer, just concatenate charlist a few times :)

A: function generate_password($length = 6) {
    $password = '';
    $chars = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
    for ($i = 0; $i < $length; $i ++) {
        $password .= $chars[array_rand($chars)];
    }
    return $password;
}

A: This function will include half digits and half numbers:
     function generateMixedPassword($length = 8) {
        $base = 'abcdefghijklmnopqrstuvwxyz';
        $baseD = '0123456789';

        $r = array();

        for ($i = 0; $i < $length; $i += 2) {
            $r[] = substr($base, rand(0, strlen($base) - 1), 1);
        }
        for ($i = 0; $i < $length; $i += 2) {
            $r[] = substr($baseD, rand(0, strlen($baseD) - 1), 1);
        }
        shuffle($r);

        return implode('', $r);
    }

Using the same login, it can be extended to also include special characters

A: You could just use PEAR's Text_Password package  - it supports quite a few algorithms for generating them; and frees up your time to go onto something else.

A: Pwgen-php produces save, pronounceable (easier to remember) passwords:
http://code.google.com/p/pwgen-php/
Might that be acceptable?

A: This function will generate more stronger password than most woted solution:
function generatePassword($size=8){
    $p = openssl_random_pseudo_bytes(ceil($size*0.67), $crypto_strong);
    $p = str_replace('=', '', base64_encode($p));
    $p = strtr($p, '+/', '^*');
    return substr($p, 0, $size);
}

Each character of password will be [A-Z] or [a-z] or ^ or *

A: This will help to create random password:
<?php
function generatePassword ($length = 8)
{
  $genpassword = "";
  $possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  $i = 0;
  while ($i < $length) {
    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
    if (!strstr($genpassword, $char)) {
      $genpassword .= $char;
      $i++;
    }
  }
  return $genpassword;
}
?>
<input type="text" value="<?php echo generatePassword(); ?>">

A: use hackzilla/password-generator
it has many options to create different kind of passwords:

*

*ComputerPasswordGenerator()

*HybridPasswordGenerator() -> sjgX-PFjH-zxMz-PRDz-G6mx-wMJ4-ST24

*HumanPasswordGenerator() -> Verkuemmerungen-verlottertet-dreinzuschauen (word list based. in this case a german word list)

*RequirementPasswordGenerator()
ComputerPasswordGenerator
$generator
  ->setOptionValue(ComputerPasswordGenerator::OPTION_UPPER_CASE, true)
  ->setOptionValue(ComputerPasswordGenerator::OPTION_LOWER_CASE, true)
  ->setOptionValue(ComputerPasswordGenerator::OPTION_NUMBERS, true)
  ->setOptionValue(ComputerPasswordGenerator::OPTION_SYMBOLS, false)
;

$password = $generator->generatePassword();

RequirementPasswordGenerator
$generator
  ->setLength(16)
  ->setOptionValue(RequirementPasswordGenerator::OPTION_UPPER_CASE, true)
  ->setOptionValue(RequirementPasswordGenerator::OPTION_LOWER_CASE, true)
  ->setOptionValue(RequirementPasswordGenerator::OPTION_NUMBERS, true)
  ->setOptionValue(RequirementPasswordGenerator::OPTION_SYMBOLS, true)
  ->setMinimumCount(RequirementPasswordGenerator::OPTION_UPPER_CASE, 2)
  ->setMinimumCount(RequirementPasswordGenerator::OPTION_LOWER_CASE, 2)
  ->setMinimumCount(RequirementPasswordGenerator::OPTION_NUMBERS, 2)
  ->setMinimumCount(RequirementPasswordGenerator::OPTION_SYMBOLS, 2)
  ->setMaximumCount(RequirementPasswordGenerator::OPTION_UPPER_CASE, 8)
  ->setMaximumCount(RequirementPasswordGenerator::OPTION_LOWER_CASE, 8)
  ->setMaximumCount(RequirementPasswordGenerator::OPTION_NUMBERS, 8)
  ->setMaximumCount(RequirementPasswordGenerator::OPTION_SYMBOLS, 8)
;

$password = $generator->generatePassword();

A: I use st_split and implode function:
function genarateKey(){
    $limit= 8;
    $chars= 'abcdefghijklmnopqrstuvxwyz1234567890!@#$%^&*()_+=-[]{}\|ABCDEFGHIJKLMNOPQRSTUVXWYZ';
    $chararray= str_split($chars);
    $gen=array();
    for($i=0;$i<$limit;$i++){
        $index=rand(0,strlen($chars)-1);
        $gen[$i]= $chararray[$index];
    }
    return implode($gen); //converts array to string
}

A: Memorable password generator
function password($length)
  {
    $vowel = array(
        'a',
        'e',
        'i',
        'o',
        'u',
    );

    $consonant = array(
        'b',
        'c',
        'd',
        'f',
        'g',
        'h',
        'j',
        'k',
        'l',
        'm',
        'n',
        'p',
        'q',
        'r',
        's',
        't',
        'v',
        'w',
        'x',
        'y',
        'z',
    );

    $result = '';
    for ($i = 0; $i < $length; $i++) {
        if ($i % 2 == 0) {
            $result .= $consonant[rand(0, 15)];
        } else {
            $result .= $vowel[rand(0, 4)];
        }
    }

    return $result;
}

The result:
password(8);//kutekaku
password(11);//rahubabatul

A: I think better way to generate random password is below function, if someone want then you can use these for strong password
public function randPassword($upper = 2, $lower = 3, $numeric = 2, $other = 1) {

        $pass_order = Array();
        $passWord = '';

        //Create contents of the password
        for ($i = 0; $i < $upper; $i++) {
            $pass_order[] = chr(rand(65, 90));
        }
        for ($i = 0; $i < $lower; $i++) {
            $pass_order[] = chr(rand(97, 122));
        }
        for ($i = 0; $i < $numeric; $i++) {
            $pass_order[] = chr(rand(48, 57));
        }
        for ($i = 0; $i < $other; $i++) {
            $pass_order[] = chr(rand(33, 47));
        }

        //using shuffle() to shuffle the order
        shuffle($pass_order);

        //Final password string
        foreach ($pass_order as $char) {
            $passWord .= $char;
        }
        return $passWord;
    }


text:
Q: \qty problem with parentheses Why are the parentheses not showing? (I don't want to remove packages,how can i fix this problem?)

\documentclass[a4paper]{article}
\usepackage{physics}

\makeatletter
\DeclareSymbolFont{cmexlargesymbols}{OMX}{cmex}{m}{n}
\SetSymbolFont{cmexlargesymbols}{bold}{OMX}{cmex}{b}{n}
\DeclareMathDelimiter{(}{\mathopen}{letters}{46}{cmexlargesymbols}{0}
\DeclareMathDelimiter{)}{\mathclose}{letters}{47}{cmexlargesymbols}{1}
\makeatother

\begin{document}

\[e^{\qty(x)}\]

\end{document}

A: You specified the () come from the font in positions 46 and 47 but if you look at the latex sources you will see they are the wrong numbers you get

from
\DeclareMathDelimiter{(}{\mathopen}{letters}{"28}{cmexlargesymbols}{0}
\DeclareMathDelimiter{)}{\mathclose}{letters}{"29}{cmexlargesymbols}{1}

or simpler, by deleting the entire block of code
makeatletter
\DeclareSymbolFont{cmexlargesymbols}{OMX}{cmex}{m}{n}
\SetSymbolFont{cmexlargesymbols}{bold}{OMX}{cmex}{b}{n}
\DeclareMathDelimiter{(}{\mathopen}{letters}{"28}{cmexlargesymbols}{0}
\DeclareMathDelimiter{)}{\mathclose}{letters}{"29}{cmexlargesymbols}{1}
\makeatother

You don't give any indication what you intended this to do, deleting it gives the presumably intended output.

A: Here is the general answer to all your questions. Normally this would probably be deleted, but I ask my fellow TeX.SE users to bear with me in this particular case.

*

*Don't use nonstandard packages like physics (or my own package, semantex, for that matter) unless you know what they are and what they do. They change fundamental things about the way we type LaTeX. If this is not what your want, simply use LaTeX the standard way without trying to change it too much. That way, most things will look nice by default.

*If you think that mathematical symbols such as the equality signs and parentheses do not have rounded enough corners, find a different font.

*If you load mathastext, note that this is about making the math font resemble the text font. Conversely, if you don't want the math font to resemble the text font, don't load mathastext.

*Read what packages do before you load them. In general, start from a clean document that only loads amsmathand add stuff when you need it.

*Re-read the answers to your previous questions before asking an identical one.


text:
Q: How to maintain checkbox selected after navigation through different pages in jsgrid through jquery? Unable to maintain the data or (checkbox selection) after page navigation? or we can say for example:i am on page 1 of JSGRID and i have checked 2 rows using a check box available on that row and I navigate to second page and again come back to first one than the selection lost.

A: Add a field on the data item to track the checkbox state. In itemTemplate restore the value on each rendering.
{
    name: "FieldName",
    align: "center",
    itemTemplate: function(value, item) {
        return $("<input>").attr("type", "checkbox")
                .attr("checked", value || item.Checked)
                .on("change", function() {
                    item.Checked = $(this).is(":checked");
                });
    }
}

Here is the working fiddle http://jsfiddle.net/tabalinas/xo1npabw/
As alternative you can store checkbox state in a separate array like in the demo "Batch Delete" on the demo page.


text:
Q: Скрыть блок при клике Нужно скрыть блок при клике по элементу блока и вне этого элемента, сейчас блок скрывается почему то при первом клике и так и так а на втором клике скрывается только при клике по документу. Вот код :
 $('.in20 .hid').click(function(){
 var check = $(this).siblings('.hid-content').is(':visible')
$('.in20 .in19 .hid-content').each(function(){$(this).hide()})
  if(!check){
    $(this).siblings('.hid-content').show();
  } else {
   $(document).mouseup(e => {
  let ourBlock = $('.hid-content');
  if (!ourBlock.is(e.target) && ourBlock.has(e.target).length === 0)
      ourBlock.hide();
})

 }

 });

       <form method="get" action="" class="in20">
        {foreach $filters as $fid => $filter}

        {if $fid == 'price'}

            {$c = $wa->shop->currency(true)}

[`Price`]

          [`from`] <input type="text" class="min" name="price_min" {if $wa->get('price_min')}value="{(int)$wa->get('price_min')}"{/if} placeholder="{floor($filter.min)}">
           [`to`] <input type="text" class="max" name="price_max"  {if $wa->get('price_max')}value="{(int)$wa->get('price_max')}"{/if} placeholder="{ceil($filter.max)}">{*{$c.sign} *}

        {else}

{$filter.name|escape}

            {$filter.values|asort}
            {foreach $filter.values as $v_id => $v}

                    <input type="checkbox" name="{$filter.code}[]" {if in_array($v_id, (array)$wa->get($filter.code, array()))}checked{/if} value="{$v_id}"> {$v}

            {/foreach}

        {/if}

    {/foreach}


text:
Q: How to describe "A specific food attracts me and makes me feel hungry"? How to describe "A specific food attracts me and makes me feel hungry" ?
As far as I know, appetite may fit this circumstance. However, I do not know how to use it. I may say "I have a strong appetite today.", but I do not know how to describe "A specific food makes me to have a strong appetite now". Verbs, phrases, or adjectives are all welcome.
Thank you very much!!

A: I would say "Craving".
The word crave is used to talk about wanting food a lot.

"I have a bad craving for pickles today."

and

"If you crave potato chips, you may have a salt deficiency."

are both good examples of this.
A more slangy word for "crave" is "Hankering" which means pretty much the exact same thing.

"I have a hankering to eat fried chicken and salsa."

A: You are correct that appetite is a general wanting of food.
In BrE, when one likes a particular food, one usually wants more of it.
The adjective that describes this is moreish:

P1: Those cookies are very moreish
  P2: Be careful of your waistline!

In AmE, one might say something is habit forming: the more you have, the more you want

Reese's Peanut Butter Cups can be habit forming.


text:
Q: How to configure remote debugger for spring cloud data flow Local server I am using the spring cloud dataflow server to create a stream. I want to do a remote debugging on the spring cloud dataflow server.
Below is the command which I am trying but not able to connect on 5005 port.
java -jar spring-cloud-dataflow-server-2.5.3.RELEASE.jar -agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005

A: Please refer to the guides that Sabby pointed for debugging applications and the SCDF/Skipper server in general. Apart from this, what I notice from your question above is you have the debug parameters as java program arguments which is incorrect.
What you actually need is something like this:
java -agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005 -jar spring-cloud-dataflow-server-2.5.3.RELEASE.jar

The debug parameters need to be passed before -jar argument.

A: We have a FAQ describing what property to configure to debug the applications deployed by SCDF.
If you want to debug SCDF itself, you may want to review the Debug Data Flow Server guide from the Microsite. There's also a specific section to debug the Skipper application, as well.


text:
Q: Can't draw RECT on pygame ffs this is the code:
this is the pygame output
I have not been able to create a very simple shape/sprite.

A: The problem is that the code you are using to draw the red rectangle is after the while loop. Your program is stalling in the while loop and never reaches the drawing line.
Try moving:
pygame.draw.rect(stage, red, (x,y,width,height))
pygame.display.update()

to before the while running: statement
or if you want it to draw the rectangle every tick include that statement directly under the while running: statement

A: Indent the lines:
pygame.draw.rect(stage, red, (x,y,width,height))
pygame.display.update()

four spaces to the right. This will put them inside the for loop, and so will redraw the rectangle on every iteration of the loop.


text:
Q: Microsoft HPC 2012 Export Charts and Reports via Powershell I'd like to export some of the standard reports in Microsoft HPC 2012, like for example "job throughput" automatically to pdf and send this report to the users.So sending the mail would not be the problem but i can't find any command that can export this fancy reports :) i already looked up the HPC Powershell commands but none of them seems to fit. Any idea?
Thanks & Best Regards
Bernsi


text:
Q: Customizing the appearance of a file input in an HTML form I've been trying to figure out how to customize the appearance of a file input in an HTML form so that the button will match with the rest of the buttons on my site.  Looking around here I found a solution that I would expect to work, but it's having some strange behavior.
I took my file input and set display:none, and created a new text input and button within the form.
            <form method="post" action="../Entry/Create" enctype="multipart/form-data" onsubmit="return aentryValidate()">
                <input type="text" id="EntryTitle" name="EntryTitle" maxlength="50" />

(50 characters remaining)

                <input type="file" id="ImageFile" name="ImageFile" style="display:none;" />
                <input type="text" id="ImageFileMask" name="ImageFileMask" disabled="true" />
                <button type="button" onclick="HandleFileButtonClick()" id="ImageFileButton" style="margin-left:10px;padding-bottom:0px;height:20px;width:100px;font-size:14px;">browse...</button>

(image to represent your entry, jpg, png, or gif)

                <textarea id="EntryDesc" name="EntryDesc"></textarea>

                <input type="checkbox" id="isPrivate" name="isPrivate" value="true" />
                <input type="hidden" name="isPrivate" value="false" />
                Make my entry private.

                <button id="new-entry-save">save</button>
            </form>

Then my javascript to handle the ImageFileButton button being clicked:
function HandleFileButtonClick() {
    document.getElementById("ImageFile").click();
    document.getElementById("ImageFileMask").value = document.getElementById("ImageFile").value;
}

It appears to work fine.  I click the button, the window pops up for me to select a file.  When I select a file, it appears in the text box.
The weird behavior comes when I hit the save button on the form.  I noticed that it has to be clicked twice to actually submit for some reason now.  And, when it submits it is no longer posting the file.
So I made the file input visible again to see what was happening.  If I use the ImageFileButton button to select a file, the file shows up in the file input.  But when save is clicked, the file input clears and the form doesn't submit.  You then have to click again to submit, and of course now there is no file.
Anybody know what is happening here?

A: No, its not possible. File inputs are generally browser dependant. You might have to use JavaScript replacement or Flash replacement like uploadify.
Article: Input File

Of all form fields, the file upload field is by far the worst when it comes to styling. Explorer Windows offers some (but not many) style possibilities, Mozilla slightly less, and the other browsers none at all. The "Browse" button, especially, is completely inaccessible to CSS manipulation.


text:
Q: ElasticSearch Match Query fuzzines on numbers If I search for tokens with numbers the fuzzines does not work right.
Dokument:
"Nice Photo S61"

Gives me a result on the query
"Nices"
But not as soon I would use
"S6"
I dont get a Result
Here is my query
GET /index1/_search
{
    "query": {
        "match" : {
         "url1" : {
             "query" : "s6",
             "fuzziness": "auto",
             "prefix_length": "3",
              "max_expansions": 6,
              "operator":  "and"
        }
    }
  }
}

Here are my Index Settings:
  PUT /index1/_settings
{
  "settings": {
    "analysis": {
      "analyzer": {
        "product_analyzer": {
          "type": "custom",

          "tokenizer": "punctuation",
          "filter": [
            "lowercase"
          ]
        }
      },
      "tokenizer": {
        "punctuation": {
          "type": "pattern",
          "pattern": "[-_.:~ ]"
        }
      }
      }
  },
  "mappings" : {
    "index1" : {
      "properties" : {
        "url":{
        "type" :"text",
        "analyzer" : "product_analyzer"
        }
        }
      }
    }
  }

A: It's not about numbers.
When setting fuzziness to auto means to auto generate the edit distance base on your term.

AUTO
Generates an edit distance based on the length of the term. Low and
  high distance arguments may be optionally provided AUTO:[low],[high].
  If not specified, the default values are 3 and 6, equivalent to
  AUTO:3,6 that make for lengths:
0..2 Must match exactly
3..5 One edit allowed
>5 Two edits allowed AUTO should generally be the preferred value for fuzziness.

And

prefix_length
The number of initial characters which will not be "fuzzified". This helps to reduce the number of terms which must be examined. Defaults to 0.

So you can change your query to this:
{
    "query": {
        "match" : {
         "url1" : {
             "query" : "S6",
             "fuzziness": "1",
             "prefix_length": "0",
              "max_expansions": 6,
              "operator":  "and"
        }
    }
  }
}

refs:
https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#fuzziness
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-fuzzy-query.html

A: Here are a few considerations.

*

*In your posted examples, your query is trying to match the field url1, but in your mapping you defined the field url. I'll assume it was just a typo in your examples.

*In your query, you're setting a prefix length of 3 characters, but then you search for s6, which obviously doesn't match the length condition.

*In your query, you set the fuzziness value to AUTO, which for strings <= 2 characters means that your term must match exactly (see documentation)


text:
Q: use of \noexpand in tikz/math associative arrays The following does not work in tikz/math :
\documentclass[tikz]{standalone}
\usetikzlibrary{math}
\begin{document}
\tikzmath
{
  let \a = my black string ;
  let \b = my red string ;
  let \c{1} = \a{\noexpand\color{red}\b}\a;
  print{\c{1}};
}
\end{document}

even though it will upon replacing all instances of \c{1} by \c.
Some way to still do that for associative arrays ?
Cheers,

A: It's a followup question. Apparently \edef is used more often and \noexpand gots consumed, exposing \color again. A better way is therefore to use a robust definition made via e-TeX's \protected\def. Package etoolbox provides an interface via \robustify:
\documentclass[tikz]{standalone}
\usetikzlibrary{math}

\usepackage{etoolbox}
\robustify\color

\begin{document}
\tikzmath
{
  let \a = my black string ;
  let \b = my red string ;
  let \c{1} = \a{\noexpand\color{red}\b}\a;
  print{\c{1}};
}
\end{document}


text:
Q: What is the best pattern for managing multiple versions of the same dependency tree in Guice? I would like to instanciate several versions of the same kind of dependency tree/chain which use different implementations for some of the interfaces in that tree/chain. What is the best Guice practice/pattern to use in such case?
Here is a concrete example of my problem.
I have a Writer interface which can potentially be a file writer or a std-out writer, which will be situated at the leaf of my dependency hierarchy. Something like this:
interface Writer { ... }
class FileWriter implements Writer { ... }
class StdOutWriter implements Writer { ... }

Another logger interface is used to add a layer of indirection on the writer. For instance:
interface Logger { ... }

class LoggerImpl{
  @Inject
  public Logger(Writer out){ ... }
  public void log(String message){ out.println(message); }
}

Then there is a client that uses the logger.
class Client{
  @Inject
  public Client(Logger logger){ ... }
  public void do(){ logger.log("my message"); }
}

Now, I would like to use two types of hierarchies in my program:

*

*Client -> LoggerImpl -> FileWriter

*Client -> LoggerImpl -> StdOutWriter

Is there a nice way of wiring this up without using a separate Guice module for 1 and 2?
Ideally I would like to have a ClientFactory class like this:
interface ClientFactory{
  public Client stdOutClient();
  public Client fileClient();
  //or fileClient(File outputFile) for extra points ;)
}

Could anyone come up with a way to wire up this using this factory, or by any other means?
I would also like a solution that would scale to cases where I have a bigger variety of longer dependency trees/chains. Thanks!

A: This is the robot legs problem. The solution is basically to use PrivateModules to bind each dependency tree and expose only the root of that tree. There are several ways you could do this, but here's an example of how you typically might do it (there are a lot of variations on this you can do according to your needs):
public class ClientModule extends PrivateModule {
  private final Writer writer;
  private final Class<? extends Annotation> annotationType;

  public ClientModule(Writer writer, Class<? extends Annotation> annotationType) {
    this.writer = writer;
    this.annotationType = annotationType;
  }

  @Override protected void configure() {
    bind(Writer.class).toInstance(writer);
    bind(Logger.class).to(LoggerImpl.class);
    expose(Client.class).annotatedWith(annotationType);
  }
}

public class ClientFactoryModule extends AbstractModule {
  private final File file;

  public ClientFactoryModule(File file) {
    this.file = file;
  }

  @Override protected void configure() {
    install(new ClientModule(new StdOutWriter(), StdOut.class));
    install(new ClientModule(new FileWriter(file), FileOut.class));
    bind(ClientFactory.class).to(ClientFactoryImpl.class);
  }
}

public class ClientFactoryImpl implements ClientFactory {
  private final Client stdOutClient;
  private final Client fileClient;

  @Inject public ClientFactoryImpl(@StdOut Client stdOutClient,
                                   @FileOut Client fileClient) {
    this.stdOutClient = stdOutClient;
    this.fileClient = fileClient;
  }

  ...
}

Your scenario of a method Client fileClient(File) is quite a bit different though.


text:
Q: Script working fine while it should raise NameError Below is a working minipart of the whole script, only necessary parts. In the steps below I explained how the input works(If you want to run the program) because I'm using a library that detects when the user press 'ENTER'(the library is 'pynput'). Just in case, if it's relevant with this problem. Do the steps in exact order if you want to run the program correctly.
Problematic part is at the end of the script. If you run this script, do below and you'll see this printed in the console: "I'M A PRINT FUNCTION WORKING FINE" just before these lines;
print (list(y))
del list(y)[0]
print (type(y))
which is where my problem starts. It does not raise any error(I expect there should be NameError: name 'y' is not defined), it does not close the PyQt5 window or respond anything while 'y' is not defined anywhere in the whole script. I put there a test button to show that program working fine after this part.
Why it doesn't raise any error while 'y' is not defined anywhere, OR atleast close the main window of PyQt5? It's like it ignores it and keep working, no respond at all.
Am I missing something here or is there something I don't know about how PyQt5 main loop works?
Steps for input if you want to run the program correctly
To input in the first QLineEdit(Next to 'SET' label), for example;
1- Press 'a'
2- Press Enter
3- Press 'b'
4- Press Enter
5- Press Enter
To input in the second QLineEdit(Next to 'TOP' label), for example;
1- Press 'a'
2- Press Enter
3- Press Enter
4- Press 'a'
5- Press Enter
6- Press 'b'
7- Press Enter
8- Press Enter
9- Press Enter
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from pynput.keyboard import Key, Listener
from itertools import combinations

import sys
import re

class Window(QMainWindow):
    def __init__(self):
        super(Window, self).__init__()

        ##BELOW DETECTS WHEN THE USER PRESS ENTER
        self.listener = Listener(on_press=self.on_press)
        self.listener.start()
        self.listener1 = Listener(on_press=self.on_press_top)

        ##CENTERING THE SCREEN
        def center(self):
            qr = QMainWindow.frameGeometry()
            cp = QDesktopWidget().availableGeometry().center()
            qr.moveCenter(cp)
            self.move(qr.topLeft())

        ##JUST GUI
        self.setWindowTitle("Foo")
        self.setFixedSize(950, 710)
        self.setStyleSheet("background-color: rgb(119,136,153)")
        QApplication.setOverrideCursor(Qt.PointingHandCursor)

        ##SET -LINE EDIT
        self.kume_edit = QLineEdit(self)
        self.kume_edit.setText("{")
        self.kume_edit.setStyleSheet("QLineEdit{ background-color: orange; color: blue; font: 11 }")

        fnt = self.kume_edit.font()
        fnt.setPointSize(15)
        self.kume_edit.setFont(fnt)
        self.kume_edit.setGeometry(140, 300, 300, 30)
        ##

        ##SET -LABEL
        self.kume_label = QLabel(self)
        self.kume_label.setText("SET:")
        self.kume_label.setStyleSheet("QLineEdit{ background-color: orange; color: blue; font: 11 }")

        fnt1 = self.kume_label.font()
        fnt1.setPointSize(15)
        self.kume_label.setFont(fnt1)
        self.kume_label.setGeometry(50, 300, 60, 32)
        ##

        ##TOPOLOGY -LINE EDIT
        self.top_edit = QLineEdit(self)
        self.top_edit.setText("{{")
        self.top_edit.setStyleSheet("QLineEdit{ background-color: orange; color: blue; font: 11 }")

        fnt2 = self.top_edit.font()
        fnt2.setPointSize(15)
        self.top_edit.setFont(fnt2)
        self.top_edit.setGeometry(140, 400, 300, 30)
        ##

        ##TOPOLOGY -LABEL
        self.topo_label = QLabel(self)
        self.topo_label.setText("TOP:")
        self.topo_label.setStyleSheet("QLineEdit{ background-color: orange; color: blue; font: 11 }")

        fnt3 = self.topo_label.font()
        fnt3.setPointSize(15)
        self.topo_label.setFont(fnt3)
        self.topo_label.setGeometry(50, 400, 80, 32)
        ##

        ##FUNCTION CHANGES THIS LABEL WHEN THE DESIRED CONDITION OCCURS
        self.top_label = QLabel(self)
        fnt4 = self.top_label.font()
        fnt4.setPointSize(15)
        self.top_label.setFont(fnt4)
        self.top_label.setGeometry(140, 450, 900, 30)
        ##

        ##BUTTON SHOWS THAT THE PROGRAM WORKING FINE
        ##CLICK THIS BUTTON BEFORE AND AFTER YOU RUN
        but = QPushButton(self)
        but.setGeometry(500,400,50,50)
        but.setText("Click Me")
        but.clicked.connect(self.but_test)
        self.count_test = 0
        ##

        self.top_ = 0
        self.kord_ = 300

        self.show()

    def but_test(self):             #########CLICK THIS BUTTON
        self.count_test += 1        #########TO SEE THAT ITS WORKING AFTER 'print(type(y))' PART
        self.top_label.setText("The program working fine {}".format(self.count_test))

    def on_press(self,key): #########THIS DETECTS WHEN THE USER PRESS "ENTER" IN 'SET QLINEEDIT'

        if key == Key.enter:

            if self.kume_edit.text()[-1] == ",":
                self.kume_edit.setText(self.kume_edit.text()[:-1] + "}")
                self.kume_edit.setReadOnly(True)
                self.listener1.start()
                self.listener.stop()

            else:
                self.kume_edit.setText(self.kume_edit.text() + ",")

    def on_press_top(self,key): #########THIS DETECTS WHEN THE USER PRESS "ENTER" IN 'TOPOLOGY QLINEEDIT'

        if key == Key.enter:
            self.top_ += 15

            if self.top_ > 220:
                self.kord_ += 15
                self.top_edit.setGeometry(140, 400, self.kord_, 30)

            if self.top_edit.text()[-1] == "{":
                self.top_edit.setText(self.top_edit.text()[:-2])
                self.top_edit.setText(self.top_edit.text() + "}")
                self.top_edit.setReadOnly(True)

                self.top_edit.setGeometry(140, 400, self.kord_, 30)

                self.topoloji_mi()  #####################HERE THE FUNCTION IS CALLED - ONLY HERE

                self.listener1.stop()

            elif self.top_edit.text()[-1] == ",":
                self.top_edit.setText(self.top_edit.text()[:-1] + "}")
                self.top_edit.setText(self.top_edit.text() + ",")
                self.top_edit.setText(self.top_edit.text() + "{")

            else:
                self.top_edit.setText(self.top_edit.text() + ",")

    def kumetop(self): #############THIS JUST RETURNS TWO LISTS
        reg = r"\{(.*?)\}"
        matches = re.findall(reg, self.top_edit.text()[1:-1])

        top_set = []
        top_set.append(set())
        for x in matches:
            top_set.append(set(x.split(",")))

        kume_set = []
        for x in self.kume_edit.text():
            if x.isalnum():
                kume_set.append(set(x.split(",")))
        return kume_set,top_set

    def topoloji_mi(self): #################PROB FUNCTION #######################################
        kume_set,top_set = self.kumetop() ###TAKING THE LISTS

        for x in combinations(top_set, 2):

            ################WHATS THIS
            print ("IM A PRINT FUNCTION WORKING FINE") ###THIS PRINT WORKS
            print(list(y))
            del list(y)[0]               #######PYCHARM RAISE NO ERROR, WINDOW IS ALSO WORKING
            print (type(y))              ###CLICK THE TEST BUTTON

            if len(z) == len(list(y)) and all([z.count(i) == list(y).count(i) for i in kume_set]):
                self.top_label.setText("BLABLABLA")
                print("IM NOT WORKING")

    def close_application(self):
        sys_exit()

def run():
    app = QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()


text:
Q: A Complex Conditional Formatting in Excel =$H$6:$J$6 IF $I6<$J6? =$H$6:$J$6 +IF($I6 \\< $J6)

I'm finding my first formula isn't working, and was wondering if any might know what help I might need. Essentially, I need three cells to turn different colors if two of the cells are equal, < or >.

A: The problem is the "IF" statement.  The "IF" is actually implied, your formula should be
=$I6 < $J6

and apply to
=$H$6:$J$6

And you'd need two similar rules for greater than and equal comparisons, of course.


text:
Q: How to return Ajax data request by id in octobercms? This has to be pretty straight forward by not sure how.
I am building a front end form with categories and subcategories. The code below displays the categories in select box without any issue
Php block
$this['items'] = Cat::where('parent_id',0)->pluck('cat_title', 'id');

Display

  Category
  <select id="category" class="form-control" data-request="onChangeCat"
 data-request-update="select: '#subcategory'">
    <option selected>Choose...</option>

    {% for key, item in items %}
    <option value={{ key }}> {{ item }}</option>
    {% endfor %}

  </select>

I have an data-request up there with the following Ajax handler to display subcategories in the next select-box. The partial to be rendered is also in place.
   function onChangeCat()
   {
   $this['subs'] = Cat::where('parent_id', '>',0)->pluck('cat_title', 'id');

    }

The question is how do i write the Ajax handler code to only display subcategories by id of the category. The code above just displays all the subcategories.

A: You will need to have a route that take as a parameter selected item on the category select, then that route will filter through sub-categories to have only related sub-categories, the you will send the result back as json using json_encode() take data and create options then add them to the sub-categories select.
The route will be called ones the user change the select category.

A: *

*Give your select a name tag <select name="category">..</select>

*Query the subcategories with the posted data accessible via the post() function : e.g  Cat::where('parent_id', '=', post('category') )->pluck('cat_title', 'id')


text:
Q: Show the latest item firest in Firebase ui Realtime database I use firebase ui realtime database to show data in viewpager2 with RecyclerView adapter and i need to show the latest item firest how can i do that ?
And you can find sample code of that in here
Here simple code of my project


text:
Q: Is there a relationship between the initial length of a pendulum that is released in air, and the amplitudes half-life (defined in post)? If I were to release an underdamped pendulum right now in earth's regular atmosphere, factoring in air resistance, is there a way to plot the motion of the pendulum using a regular function? Also, does the initial pendulum length impact the time taken for the continuous amplitude to reach half of the initial amplitude?
Apologies if this is a basic question,


text:
Q: converting 20+ entry points into 1 or a few using webpack I have a project built in asp.net core and jquery+js libraries for my "front-end". I have about 20 separate HTML pages where each has like a few js scripts imported into it. I have been trying to utilize webpack to make the whole process of knowing which order to include js files easier and more streamlined. I have a vendor.js which is a bundle for all 3rd party libraries that i use like BS, jquery thats included in layout.cshtml. and I also have 20 entry points, one for each distinct HTML page. THis is working fine, but it seems like the point of having webpack is that you can have only 1 or a few entry points, so its easily maintainable.
What should I do to make my current setup to use only one entry point(main.js), if each page has its own set of distinct jquery listeners? Just import * from each js file so that main.js is just croweded with hundreds of event listeners? I have thought about putting the common function in a file and bundle them together into a common.js, and each html page would still needs 1 distinct js file for all the listeners. But the problem here is that if each of the distinct js files with listeners in them arent the entry points, they cant use imports. Is there a good way to handle this problem? Please help, been researching this for a week now.
Here is my current webpack.config.js
const path = require('path');

module.exports = {
  mode: 'development',
  devtool: 'eval-cheap-source-map',
  entry: {
    home_my_taskings: path.resolve(__dirname, 'LabManager/wwwroot/js/home/my_taskings.js'),
    home_all_taskings: path.resolve(__dirname, 'LabManager/wwwroot/js/home/all_taskings.js'),
    home_archived_cases: path.resolve(__dirname, 'LabManager/wwwroot/js/home/archived_cases.js'),
    home_active_cases: path.resolve(__dirname, 'LabManager/wwwroot/js/home/active_cases.js'),
    home_index: path.resolve(__dirname, 'LabManager/wwwroot/js/home/index.js'),
    home_feedback_backlog: path.resolve(__dirname, 'LabManager/wwwroot/js/home/feedback_backlog.js'),
    user_index: path.resolve(__dirname, 'LabManager/wwwroot/js/users/index.js'),
    case_index: path.resolve(__dirname, 'LabManager/wwwroot/js/case/index.js'),
    case_create: path.resolve(__dirname, 'LabManager/wwwroot/js/case/create.js'),
    case_edit: path.resolve(__dirname, 'LabManager/wwwroot/js/case/edit.js'),
    exhibit_index: path.resolve(__dirname, 'LabManager/wwwroot/js/exhibit/index.js'),
    exhibit_create: path.resolve(__dirname, 'LabManager/wwwroot/js/exhibit/create.js'),
    exhibit_edit: path.resolve(__dirname, 'LabManager/wwwroot/js/exhibit/edit.js'),
    tasking_create: path.resolve(__dirname, 'LabManager/wwwroot/js/tasking/create.js'),
    tasking_create_multiple: path.resolve(__dirname, 'LabManager/wwwroot/js/tasking/create_multiple.js'),
    tasking_work: path.resolve(__dirname, 'LabManager/wwwroot/js/tasking/work.js'),
    tasking_edit: path.resolve(__dirname, 'LabManager/wwwroot/js/tasking/edit.js'),
    tasking_details: path.resolve(__dirname, 'LabManager/wwwroot/js/tasking/details.js'),
    vendor: path.resolve(__dirname, 'LabManager/wwwroot/lib/vendor.js'),
  },
  output: {
    path: path.resolve(__dirname, 'LabManager/wwwroot/js/bundle'),
    filename: '[name].js',
  },
};

and for example my case_index.cshtml looks like this
@Scripts{
    <scrpt src="~/js/bundle/case_index.js" asp-append-version="true"></script>
}

A: Answering your specific questions

THis is working fine, but it seems like the point of having webpack is that you can have only 1 or a few entry points, so its easily maintainable.

Given the sheer number of ways that webpack can be configured, it's hard to say that there's some universal "right" way to configure every project. I'd tend to take the approach that if the build isn't broken in some way (maintainability, performance, bugs, etc), then there's really no reason to change it even if it doesn't technically conform to a mythical "ideal".
If you are determined to change it, then take the time to identify the criteria you are using to measure success and be sure to test that your changes are actually making an improvement. It's very possible that the changes you are thinking of making won't actually make much of a difference. "Easily maintainable" is extremely vague. Make sure you know what exactly what you are trying to optimize for.

What should I do to make my current setup to use only one entry point(main.js), if each page has its own set of distinct jquery listeners?

You can use dynamic imports instead of static imports. Then, at runtime, you'd need to load the appropriate modules based on some test, such as the URL or some flag set by the server (for example, a JS variable or function parameter).
However, this will likely result in a significantly more complicated codebase which may defeat your goal of "easily maintainable". Dynamic imports require the use of promises, so you will likely need to wrap a lot of your code in async functions or promise handlers. It may also adversely impact performance if you are unnecessarily loading additional JS files.

I have thought about putting the common function in a file and bundle them together into a common.js, and each html page would still needs 1 distinct js file for all the listeners. But the problem here is that if each of the distinct js files with listeners in them arent the entry points, they cant use imports. Is there a good way to handle this problem?

You can use splitChunks to identify common modules and move them into shared output files that can be loaded by all or a few of your entry files. Instead of having to identify common functions yourself and manually moving them into a common.js file (which is what I think you are suggesting), you can simply move functions into modules and then import them where needed. You can then let Webpack identify which modules are shared and split those modules into common chunks for you.
I'm not sure you are using Webpack to its full potential
Webpack's strength lies in its ability to not just concatenate multiple files together but to do static analysis to figure out which files, and even parts of files, are actually needed and exclude the rest.
When used correctly, you can point webpack toward an entry file and then let webpack figure out the entry file's dependencies and concatenate all of those dependencies together into a single bundle (keeping in mind that 1 bundle ≠ 1 output file, necessarily).
Entry files allow Webpack to optimize the modules that are needed for each page. Rather than loading all modules on every page, Webpack can figure out the bare minimum needed for a particular page, which can dramatically speed up your page (by decreasing the download size and decreasing JS overhead by eliminating modules you don't need).
Webpack can split bundles into multiple output files. Several smaller files are faster to load than a few large files because the browser can download them in parallel. In a multi-page application, you can also take advantage of browser caching by splitting your bundles such that shared modules, like those in your vendors file, can be downloaded once and then shared by multiple pages.
Whether or not you are actually taking advantage of all these capabilities is not apparent from your webpack configuration. I suspect the opposite given that your vendors file appears to be pre-compiled and you seem to think you need to manually create a "common.js" entry file.
Multiple entry files is a good thing, but you should generally try to avoid multiple entry files per window context. While webpack can still work with multiple entry files per window, it is harder to configure correctly. You must carefully mitigate against unintended consequences.
If you do need multiple entry files per page, Webpack recommends specifying when entry file depend on one another and setting optimization.runtimeChunk: 'single' to ensure that entry points are not duplicated or run more than once:
module.exports = {
  entry: {
    home_my_taskings: {
      import: path.resolve(__dirname, 'LabManager/wwwroot/js/home/my_taskings.js'),
      dependOn: 'vendor',
    }
    home_all_taskings: {
      import: path.resolve(__dirname, 'LabManager/wwwroot/js/home/all_taskings.js'),
      dependOn: 'vendor',
    }
    // ...
    vendor: path.resolve(__dirname, 'LabManager/wwwroot/lib/vendor.js'),
  },
  optimization: {
    runtimeChunk: 'single',
  },
};


text:
Q: Error using functions inside of a class. I can't assign a function to a new class method I'm trying to create a new method for my class 'Cloth', the method is called 'max_temp' and, to ease the task, i created the following function (max_temperature) to keep a cleaner code in the init part.
I can't understand why it doesn't calculate the 'max_temp' method tho
class cloth():
    def __init__(self, category, name):
        self.category = category
        self.name = name
        self.max_temp = max_temperature(category)

    def max_temperature(category):
        temps = {
            'sweater' : 24,
            'shirt' : 45}
        return temps[category]

x = cloth('sweater', 'cam_eco')

print(x.max_temp)

>>> print(x.max_temp)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

A: If you define a method inside a class then it needs to be either passed self as the first argument, or define it as a staticmethod or classmethod. Otherwise you need to define it outside the class.
So max_temperature needs to declared as one of:
@staticmethod # or @classmethod (Ill leave looking up the difference to you)
def max_temperature(category):
    ....

or
def max_temperature(self, category):
    ....

or define it outside the class.
If you define it inside the class then you should call it via self (or the class name if its a classmethod):
class cloth: # Note I removed the () from the class
    def __init__(self, category, name):
        self.category = category
        self.name = name
        self.max_temp = self.max_temperature(category)
...

So overall:
class cloth:
    def __init__(self, category, name):
        self.category = category
        self.name = name
        self.max_temp = self.max_temperature(category)

    @staticmethod
    def max_temperature(category): # TODO you should add error handling to this method
        temps = {
            'sweater' : 24,
            'shirt' : 45
        }
        return temps[category]

x = cloth('sweater', 'cam_eco')
print(x.max_temp) # 24

A: The question has been already answered by Austin, but If you are not ok with static concept yet, then your code will look like
    class cloth():
        def __init__(self, category, name):
            self.category = category
            self.name = name
            self.max_temp = self.max_temperature(category)

        def max_temperature(self,category):
            temps = {'sweater' : 24,'shirt' : 45}

            return temps[category]

    x = cloth('sweater', 'cam_eco')

    print(x.max_temp)

A: Have you tried using self.category as the argument in the max_temperature function?
class cloth():
    def __init__(self, category, name):
        self.category = category
        self.name = name
        self.max_temp = max_temperature(category)

    def max_temperature(self, self.category):
        temps = {
            'sweater' : 24,
            'shirt' : 45}
        return temps[category]

x = cloth('sweater', 'cam_eco')

print(x.max_temp)


text: Q: TensorFlow object_detection model to identify person, for the same image, different image sizes have different recognition results,why? I'm using ssd_mobilenet_v1_0.75_depth_coco from the TensorFlow 1 Detection Model(COCO-trained models) to identify people, and am now running into a strange problem. When the input image size is 2160x1080, the recognition result is null, but after scaling the image to 1920x1080, it can recognize the person correctly, does the model have any rule for the input image size? Is this a bug? What should be done about it?


text:
Q: Drawing a chart over a sum of two columns in Dynamics CRM I'd like to draw a line chart based on two columns - let's call the regarded fields cats and dogs. I know I could create a third field called animals and populate it but that seems to me as an ugly workaround.
I'm pretty sure there's no way to achieve that via the GUI so I'm hoping that editing the produced XML will open that possibility. As far I could understand this discussion, it's not possible but since it's old, I'm hoping that it's become possible since then.
Any luck on this one?

A: It's a bit unclear exactly what you are going for with this question.  This is an excellent blog on how to modify your chart's fetchxml to extend the crm chart capabilities (and it may or may not answer your question depending on exactly what you mean by "draw a line based on two columns"): https://crmchartguy.wordpress.com/2015/06/21/compare-this-year-to-last-year-with-a-dynamics-crm-chart/


text:
Q: Convert Long And Lat to X Y coordinate using ArcGis Api For Javascript Hello i'm trying to convert long,lat values to X,Y using ArcGis Api For Javascript
 var i = esri.geometry.lngLatToXY(3.13, 36.742)
 console.log(i); //returns Array [ 348541.32567373366, 4403205.668961807 ]

in what system does this conversion take place?
is there a method to specify the projection system?
note: the conversion is done from decimal degree to meters
i followed this :
https://developers.arcgis.com/javascript/3/jsapi/esri.geometry.webmercatorutils-amd.html

A: This method is used to convert geographic coordinate system longitude/latitude (wkid 4326) to projected coordinate system Web Mercator (wkid 102100).
Default esri map use Web Mercator as projection system. If you need to convert your coordinates to an other coordinate system you need to use the project method of GeometryService :
https://developers.arcgis.com/javascript/3/jsapi/geometryservice-amd.html
Example:
require(["esri/geometry/Point", "esri/tasks/GeometryService", "esri/tasks/ProjectParameters", "esri/SpatialReference", "dojo/domReady!"],
  function(Point, GeometryService, ProjectParameters, SpatialReference) {

    var outSR = "YOUR_OUTPUT_COORDINATE_SYSTEM"; // `wkid {number}`
    var geometryService = new GeometryService("https://utility.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
    var inputpoint = new Point({
      longitude: "YOUR_LONGITUDE_INPUT",
      latitude: "YOUR_LATITUDE_INPUT"
    });

    var projectParams = new ProjectParameters();
    projectParams.geometries = [inputpoint];
    projectParams.outSR = new SpatialReference({ wkid: outSR });

    geometryService.project(projectParams, (result) => {
      let outputpoint = result[0]; // outputpoint first element of result array
      console.log("Result x:", outputpoint.x, "y :", outputpoint.y);
    });
  });

Wkid numbers can be found here:

*

*projected coordinate system: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Projected_coordinate_systems/02r3000000vt000000/

*Geographic coordinate system: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Geographic_coordinate_systems/02r300000105000000/
EDIT
Here is a working example: Plunker


text:
Q: Overriding bundles versus overriding files I'd like to ask what is the difference between overriding a bundle from the vendor and simply overriding its controllers or templates.
It seems to be the same to me, whether I override the bundle and then make my own files, or override the controllers and implement them with my own functionality.

A: http://symfony.com/doc/current/cookbook/bundles/inheritance.html
Not all bundles will allow you to easily override /resources files. Some bundles expose those files in config, others may not do that. For those others, you would need to override the bundle.
Also, I think that you can override dependancy injection files when you override a bundle


text:
Q: Thurston measure of Dehn-Thurston ball center at a multi curve Given a surface of genus $g$ with $n$ singularities, and a decompostion of pair of pant $P=(p_1,...,p_{3g-3+n})$ one can give coordinate (called Dehn-Thurston coordinate) on the space of lamination $\mathcal{ML}$ $$
C_{P}: \lambda \mapsto (i(\lambda,p_i),t(\lambda,p_i))_{i \in [1,...,3g-3+n]}
$$
If one pick a real $\iota >0$, a lamination $\gamma$, we will call Dehn-Thurston ball the set $$
B_{DT}(\gamma,\iota)= \{ \lambda \in \mathcal{ML}, \|C_{P}(\lambda)-C_{P}(\gamma)\|_{\infty} \leq \iota \}
$$
Question: Now given a geometry $X \in \mathcal{T}$ (where $\mathcal{T}$ is the Teichmüller space of the surface) can we compute $$
\mu_{Th}(X) (B_{DT}(\gamma,\iota))
$$
Or if this to complicate, at least give an asymptotics when $\iota \to 0$?

An easy case is when $\gamma = 0$. Then it is well know that for any $A \subset \mathcal{ML}$ measurable $$
\mu(X)(\iota A) = \iota^{6g-6+2n} \mu(X)(A)
$$
So $\mu(X)(B_{DT}(0,\iota))=\iota^{6g-6+2n}\mu(X)(B_{DT}(0,1))$

What we could try is to come back from the definition $$
\mu_{Th}(X) (B_{DT}(\gamma,\iota)) = \underset{M \to \infty}{\lim}\frac{1}{M^{6g-6+2n}} \# \{ \delta \in \Gamma, \delta / M \in B_{DT}(\gamma,\iota)\}
$$
Where $\Gamma$ is the set of the simple closed curves, and try to find a bijection between  $\{ \delta \in \Gamma, \delta / M \in B_{DT}(\gamma,\iota)\}$ and $\{ \delta \in \Gamma, \delta / M \in B_{DT}(0,\iota)\}$ to find the same conclusion as the previous part.


text:
Q: John is calling you or John's calling you Is there a difference between "John is calling" and "John's calling"?
I mean, can I use an apostrophe and an "s" after John's name in the above context, and be understood as "John is calling"?
If both have the same meaning, then can I write "cat's an animal" in place of "cat is an animal"?

A: The meaning is exactly the same.  The 's is just a contraction of is.  The version with the contraction, John's calling, is less formal.

A: the 's is a contraction of the word is. The two sentences are virtually the same.
contraction link

A contraction is a word made by shortening and combining two words.
  Words like can't (can + not), don't (do + not), and I've (I + have)
  are all contractions. People use contractions in both speaking and
  writing.


text:
Q: Is there any better way to get rid of Directory traversal attack? I am trying to prevent Directory traversal attack on my project and I don't understand what is wrong with this
public static final String validateOnDiskFilePath(final String absoluteFolderPath, final String child) {
    String absolutePath = null;
    try {
        String filePath = absoluteFolderPath + File.separator +child;
        absolutePath = new File(absoluteFolderPath, child).getCanonicalPath();
        if (!absolutePath.startsWith(filePath)) {
            throw new SecureStorageException(MessageFormat.format("Invalid path constructed! path ={0}, absolutePath ={1}", filePath, absolutePath));
        }
    }catch(IOException ie){
        throw new SecureStorageException("Failed to get the absolutePath", ie);
    }
    return absolutePath;
}

public static final String validateOnDiskFilePath(final String absoluteFolderPath) {
    String absolutePath = null;
    try {
        absolutePath = new File(absoluteFolderPath).getCanonicalPath();
        if (!absolutePath.startsWith(absoluteFolderPath)) {
            throw new SecureStorageException(MessageFormat.format("Invalid path constructed! path ={0}, absolutePath ={1}", absoluteFolderPath, absolutePath));
        }
    }catch(IOException ie){
        throw new SecureStorageException("Failed to get the absolutePath", ie);
    }
    return absolutePath;
}


text:
Q: How to generate carousel with images fetch from API json I'm trying to generate carousel with images from api json. URL where images are stored is: http://localhost/
First of all I want to check the amount of images occurring in JSON and then display them in carousel. Here's the example of bootstrap carousel code I want to use:

Any help will be appreciated!

A: I just added an image element inside the carousel with the help of javascript. Now you have to work only for an active carousal.

serverInfo = {
  "levelshotsArray": [
    "https://picsum.photos/200",
    "https://picsum.photos/200/300?grayscale", "https://picsum.photos/200"
  ]
}

serverInfo.levelshotsArray.map(res => {
  var imge = document.createElement('img');
  imge.src = res;
  imge.height = 100;
  imge.width = 100;
  imge.alt = "dfs";
  document.getElementById('img').appendChild(imge);
});


text:
Q: Get python ggplot bar axis right? I want to plot the results of throwing a dice in a bar chart using ggplot.
import numpy
import ggplot
import pandas

frame = pandas.DataFrame()

for i in range(6):
    frame.loc[i, 'pips'] = i+1

rand = numpy.random.random_integers(1, 6, 100)

for i in range(len(count)):
    frame.loc[i, 'events'] = numpy.sum(rand == i+1)

frame['propability'] = frame.events / frame.events.sum()

ggplot.ggplot(ggplot.aes(x='pips', weight='events'), frame) + ggplot.geom_bar()

The outcome is
From the examples I expected the plot to

*

*Have more width on each bar

*Not have x=7 with no bar

How do I fix these two things?

A: Use parameters "binwidth", "limits" and "breaks" like this :
 ggplot.ggplot(ggplot.aes(x='pips', weight='events'), frame) +
 ggplot.geom_bar(binwidth=1) +
 ggplot.scale_x_continuous(limits = (1,6), breaks = range(1,7))

Which gives me :


text:
Q: How can the id token be return as part of the custom grant response I am using a custom grant on IdentityServer3 to allow for Windows Authentication to flow through from WinForm and WPF apps.  I based my code on WindowsAuthentication plug in for IdSrv .
What I'm trying to figure out is how can I get the custom grant flow to return the id token.  I'm already getting the access token and the refresh token.
I'm looking to the id token, so I can log the user out, once they are done using the applications.
Thanks
-marc

A: Token endpoint will only give you id_token when exchanging the authorization code obtained by using AuthorizationCode flow client throuh OpenID Connect Authorize endpoint. More info in the spec here http://openid.net/specs/openid-connect-core-1_0.html#TokenRequest


text:
Q: biopython, Import error 'ModuleNotFoundError: No module named 'Bio'' I tried importing the file 'Bio' from the Biopython module to use the seqIO file.
from Bio import SeqIO
with open("uniprot.fa", "rt") as handle:
    for record in SeqIO.parse(handle, "fasta"):
        print(record.id)

Then I changed the path as advised

I'm confused plz help.
PS:I tried uninstalling and installing it again through pip and through zip file and I'm still facing this issue.


text:
Q: Fail in querying specific decimal values from AWS Athena with Simba ODBC driver I observe a strange behaviour when querying decimal values from Athena. Identity tests with local values will work for some numbers, and not with others:
Test 1 with 2.4 -- Works
DBI::dbGetQuery(con, "select CAST(2.4 AS DECIMAL(10,3)) from test") == 2.4

#    _col0
#    [1,] TRUE

Test 2 with 2.3 -- Fails
DBI::dbGetQuery(con, "select CAST(2.3 AS DECIMAL(10,3)) from test") == 2.3

#    _col0
#    [1,] FALSE

Some more tests with this 2.3 value don't explain anything:
result <- DBI::dbGetQuery(con, "select CAST(2.3 AS DECIMAL(10,3)) from test")
typeof(result)
# "double"
typeof(2.3)
# "double"
paste(result)
# "2.3"
paste(2.3)
# "2.3"
result == 2.3
# FALSE
round(result,3) == round(2.3, 3)
# TRUE

Looks like the driver or R would "add" some decimals when retrieving the 2.3 value... but why the heck does it happen for 2.3 and not 2.4 ?
Note : I'm suspecting more the driver itselfbecause the issue occurs only on unix, not on Windows.
Attemps: I tried to play with the SQL Presto data types (DECIMAL / DOUBLE) without success. Also tried to configure the driver encoding by adding 'DriverManagerEncoding = UTF-16' to simba.athenaodbc.ini.
Any help ?
My connection confiuration:
I'm using a DBI connection with Simba ODBC Driver (AWS recommendation), with following features :
con <- DBI::dbConnect(odbc::odbc(),
                   Driver                = "/opt/simba/athenaodbc/lib/64/libathenaodbc_sb64.so",
                   S3OutputLocation      = "s3://xxxxxxxxxxxxxxxxx/",
                   AwsRegion             = "eu-west-1",
                   AuthenticationType    = "IAM Credentials",
                   UID                   = t$AccessKeyId,
                   PWD                   = t$SecretAccessKey,
                   SessionToken          = t$SessionToken,
                   UseResultsetStreaming = FALSE,
                   Workgroup             = 'my-workgroup',
                   Schema                = "my_schema",
                   timeout               = timeout)