text:
Q: Manifest V3 extension: background's ServiceWorker does not unload after sending message to popup With manifest V3, the background's Service Worker will unload (being inactive) after idling for 30 seconds. When I send a runtime message from popup to background without any further actions, after 30 seconds, the background's Service Worker is unloaded like usual. But when I send a runtime message from background to popup, it is not unloaded when idling anymore until it is forcefully unloaded by 5 minutes.
After it is forcefully unloaded by 5 minutes cap, when the popup is triggered again, message is not successfully passed anymore.
Here are the test codes (no special permissions):
manifest.json
{
    "manifest_version": 3,
    "name": "Test sw-pp msg",
    "version": "1.0.0",
    "action": {
        "default_popup": "popup.html"
    },
    "background": {
        "service_worker": "background.js"
    },
    "permissions": [
        "activeTab"
    ],
    "host_permissions": [
        "http://*/*",
        "https://*/*"
    ]
}

popup.js
const lblStatus = document.getElementById('lblStatus');

// send test message from popup to background -> OK
chrome.runtime.sendMessage('to-background', (res) => {
    if (chrome.runtime.lastError) {
        lblStatus.textContent = 'Error';
    } else {
        lblStatus.textContent = 'OK';
    }
});

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    if (msg == 'to-popup') {
        lblStatus.textContent = 'Message from background to popup';
        sendResponse(1);
    }
});

popup.html
<!DOCTYPE html>

    <meta charset="UTF-8">

background.js
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
  if (msg == 'to-background') {
    console.log('Message from popup to background');
    sendResponse(1);

    /* Test sending message from background to popup
    - The first time the message is sent, the background's service worker may still be unloaded like usual
    - The second,... time the message is sent, the background's service worker is not unloaded anymore.
    - Without below code, the background's service worker is unloaded like usual
    */
    setTimeout(() => {
      chrome.runtime.sendMessage('to-popup', (res) => {
        if (chrome.runtime.lastError) {
          console.log('ERR');
        } else {
          console.log('OK');
        }
      });
    }, 2000);
  }
});

So I wonder what is the correct way to send message from background to popup (or options,...) in Manifest V3 extension?


text:
Q: Android Widget: OnClickPendingIntent won't Work Why doesn't recieve get called when I click on Button wid??
Code:
public class Widget extends AppWidgetProvider {
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        for (int i = 0; i < appWidgetIds.length; i++) {
            int appWidgetId = appWidgetIds[i];

            Intent intent = new Intent(context, Widget.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
            views.setOnClickPendingIntent(R.id.wid, pendingIntent);
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }

     @Override
        public void onReceive(Context context, Intent intent) {
            super.onReceive(context, intent);
            Log.d("ARH","CLICKK");
        }

Becuase I need a button to manual refresh the widget but it seems that Log.d("ARH","CLICKK"); only gets called when i add the Widget.
Thanks!

A: You using a PendingIntent to call an Activity but your Widget class is not an activity.
If you want to update to your widget, then you need to use getBroadcast that sends an APPWIDGET_UPDATE action.

redpajama_set_name: RedPajamaStackExchange


text:
Q: OpenDDS IDL Sequence type I am trying to publish video frames using the following IDL:
typedef sequence<octet> Pixels;
module message {
   @topic
   struct Image {
      int width;
      int height;
      int bytesPerPixel;
      Pixels  data;
};

I would also like to send 2 image data sequences (say, raw and filtered). Instead of declaring "Pixels data2", can sequence container by declared as arrays? The typedef sequence<octet> Pixels[2] gives errors.

A: Okay, so I gave this IDL to opendds_idl:
typedef sequence<octet> Pixels[2];
module message {
  @topic
  struct Image {
    unsigned short width;
    unsigned short height;
    unsigned short bytesPerPixel;
    Pixels data;
  };
};

and it accepted it:
opendds_idl --syntax-only test.idl
processing test.idl

However I decided to try to build a library with it in case the generated code was wrong, which seems to be true.
testTypeSupportImpl.cpp: In function 'bool OpenDDS::DCPS::gen_skip_over(OpenDDS::DCPS::Serializer&, Pixels_forany*)':
testTypeSupportImpl.cpp:83:41: error: 'sequence' does not name a type; did you mean 'servent'?
     if (!gen_skip_over(ser, static_cast<sequence*>(0))) return false;

With other errors following. It seems we don't support trying to typedef an array and sequence at the same time. Replacing the typedef with two works:
typedef sequence<octet> PixelSeq;
typedef PixelSeq Pixels[2];


text:
Q: Guide in determining the Database information from this connection string Somebody has sent me a visual studio web application solution that uses Entity Framework. I don't have much experience in Entity Framework and I'm trying to know what sort of datasource/database is he using in the application.
Here's the connection string:
<add name="newdatabaseEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=MySql.Data.MySqlClient;provider connection string="server=localhost;user id=User;password=User;database=newdatabase"" providerName="System.Data.EntityClient" />

I can understand that the database is hosted on his local server, but what other helpful information can i come up with concerning the datasource from this connection string?


text:
Q: Call controller function only once, Two div with same controller I am working on angularjs. I have two divs sharing same controller. My controller code is.
var app=angular.module('categoryPageApp', []);
app.controller('NgProducts', function($scope,UpdateService) {

   $scope.orderby=5;
   $scope.pageNumber=1;
   $scope.loadProducts=function($scope){
             //here goes ajax call
     };

 });

My two divs with same controller are

As we can see, Now two times all variables will be declared and also update fucntion will be called.
I dont want this to happen as single time http call will do the work. Is there any workaround for this.
Also I want to build pager for my products using angular js . Any help would be appreciated.

A: do this:

A: You can try to store some flag after loading the products, something like this:
app.controller('NgProducts', function($scope,UpdateService) {
   if (!$scope.productsAreLoaded)
     $scope.orderby=5;
     $scope.pageNumber=1;
     $scope.loadProducts=function($scope){
        //here goes ajax call
        $scope.productsAreLoaded = true;
     };

});


text:
Q: Change js file code I just ran a website through the wc3 validator and found some errors that I need to fix.
Now, I'm quite new to magento so slightly confused where to find certain bits of the code.
I need to find this code in the head and change the img tag in the </noscipt> :

I know you probably can't tell me where to find it, but maybe some suggestions on where I could possibly look?

A: It could be in page/html/head.phtml in your template, or it could be inserted via the admin.

System > Configuration > Design > Head


text:
Q: Symfony2 generate CRUD with NetBeans IDE 8.0 I am using NetBeans IDE 8.0 and just start learn symfony2. I try to generate CRUD but I get message
The CRUD generator expects the entity object has a primary key field named"id" with a getId() method.

but when  check in my entity file I see
    private $userid;

    public function getUserid()
       {
              return $this->userid;
       }

Any one can share it to me, how to fix it?
I am don't know what my problem! I am looking to see your reply soon!

A: You need to add mapping metadata to your field $userid (if it is your primary key). If you use annotations for mapping you need to add * @ORM\Id in the annotation block above $userid field.
See more here: http://doctrine-orm.readthedocs.org/en/latest/reference/basic-mapping.html#identifiers-primary-keys

A: When creating an entity, the entity should have attribute $id, getId() and setId($id) methods and correct mapping information, it could be for example like this:
/**
 *
 * @ORM\Table(name="your_entity")
 * @ORM\Entity
 */
class YourEntity {
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    public function setId($id){
        $this->id = $id;
    }

    public function getId(){
        return $this->id;
    }
}

If you want to rename your column name from id to for example user_id you change it by setting Column annotation name attribute, like this:
/**
 * @var integer
 *
 * @ORM\Column(name="user_id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
 private $id;


text:
Q: NLog: is it possible to change source name from code? Is it possible to change the source name thru code? My solution has several modules and I want to separate them when viewing the logs.
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <targets>
    <target xsi:type="EventLog" name="eventlog" layout="${message}" log="Application" source="MyAwesomeSolution"/>
  </targets>
  <rules>
    <logger name="*" minlevel="Info" writeTo="eventLog" />
  </rules>
</nlog>

Also, how do I log objects as xml? e.g. if I do this -  logger.Info("Results - {0}", person); I want to view the person object as XML in my event log. Is it possible?

A: Initalize your Logger object with
private static Logger logger = LogManager.GetCurrentClassLogger();

then you can add
${callsite} to your layout in config file
e.g.
<targets>
    <target xsi:type="EventLog" name="eventlog" layout="${callsite}:${message}" log="Application" source="MyAwesomeSolution"/>
</targets>

More info @ ${callsite} is here.


text:
Q: Self elevating cmd or powershell script? I have a script which I have to run frequently, but the exact moment is user-driven so I cannot use a scheduled task etc.
This script has to run with Admin-privileges (my account already has admin rights) so I cannot simply launch the script.
Is there anye way to "self-elevate" this script?
very simple example:
ECHO "I would like to have admin rights to recycle the app-pool"
pause

A: There is no way of self-elevation. But you are quite close to the solution. Create a task with the scheduler and then trigger it with another bat file like this:
SCHTASKS /U "user name" /P "password" /TN "Yourtaskname"

Or you can give a normal user the rights to run a task and skip /U "user name" /P "password".


text:
Q: Rotate two parrarel lines some radius - maintain the distance between is it possible to rotate two parrarel lines with distance between them by some radius?
To better imagine, let say that these two lines are the only two lines that are visible from a rectangle at specific distance from the circle center, and these two lines are on the sides of the rectangle (bottom is side to the center, top is the side out of the circle), so the rotation is done by moving the rectangle over the edge of the circle, perserving the distance from the circle center.
If there would be lines going throught the centre of the circle, the math is quite simple. But these two lines are going near the circle center, but there is a little distance from the center to the left and right.
My approach was to try calculate the line that is in the middle of these two lines and therefore is going throught the circle center.But than I stuck with calculation, how should these two lines move according this calculated "helping" line.
[Edited: Added image]

A: You haven't told how you actually draw you shapes, but something like the XAML below should do what you want. The two Lines are drawn in a common Canvas parent which is rotated by a RotateTransform that has its center at the center of the circle.
<Canvas>
    <Path Stroke="Black">
        <Path.Data>
            <EllipseGeometry Center="200,200" RadiusX="100" RadiusY="100"/>
        </Path.Data>
    </Path>
    <Canvas>
        <Line X1="190" Y1="50" X2="190" Y2="150" Stroke="Black"/>
        <Line X1="210" Y1="50" X2="210" Y2="150" Stroke="Black"/>
        <Canvas.RenderTransform>
            <RotateTransform CenterX="200" CenterY="200"/>
        </Canvas.RenderTransform>
        <Canvas.Triggers>
            <EventTrigger RoutedEvent="Loaded">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation
                            Storyboard.TargetProperty="RenderTransform.Angle"
                            To="360" Duration="0:0:2" RepeatBehavior="Forever"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Canvas.Triggers>
    </Canvas>
</Canvas>


text:
Q: Pullback of line bundles and divisors Let $X$ and $Y$ be smooth projective surfaces over an alg. closed field. Let $f:X\longrightarrow Y$ be a finite morphism of degree 2. Let $C$ be a smooth curve which maps to a smooth $C'$ under $f$. Is it obvious that $\mathcal{O}_X(C)=f^*\mathcal{O}_Y(C')$?
Conversely if $L'$ is a line bundle on $Y$, and if $C\in |f^*L'|$, then is $f(C)\in |L'|$?

A: a) No, it is not true that $\mathcal{O}_X(C)=f^*\mathcal{O}_Y(C')$.
For example take $X=\mathbb P^2_{x:y:z}, Y=\mathbb P^2_{u:v:w}, C=V(x)$ and let $$f(x:y:z)=(u:v:w)=(x^2:yz:z^2)$$ so that $C'= V(u)$.
Then $\mathcal O_X(C)=\mathcal O_{\mathbb P^2}(1)$, whereas $f^*(\mathcal O_Y(C'))=f^*(\mathcal O_{\mathbb P^2}(1))=\mathcal O_{\mathbb P^2}(2)$
b) The same set-up also gives a negative answer to your second question:
Take for $L'$ the line bundle $\mathcal O_{\mathbb P^2}(1)$. Then $f^*(L')=\mathcal O_{\mathbb P^2}(2)$ and you may take for $C$ the conic $z^2=xy$.
Its image  $f(C)$ is the curve $C'$ given by $ w^3=uv^2$ which nor all thy Piety nor Wit will lure to $|L'|$ .


text:
Q: Project Hamster notifications missing on upgrade to 12.04 I have upgraded from an almost default 11.10 install to 12.04. All went well and I can login, logout, etc. without any problem.
One very interesting thing about the Project Hamster notifications, though. I have set Hamster to remind after every 27 mins. I do not get these notifications. However, if there is no activity set, I see the notification.
In 11.10, I used to get both the notifications.
What is wrong? How do I set it right?
By the way, the notifications work quite well in Unity. But in Gnome, the problem continues.

A: Update: the notifications are now back in git master.
Follow the instructions here for how to install (it's pretty straight forward).
Also when looking for hamster answers i can recommend always checking with the buglist ;)
https://github.com/projecthamster/hamster/issues?sort=created&state=open


text:
Q: Product review "Submit" button not working I installed Yotpo reviews extension and disabled the Magento's default review block from Configuration> Advanced> Disable Modules Output> Mage_Reviews.
Soon after installing it I found a free extension that could help in generating Google Rich Snippets, so I installed it and and installed the other block. I also Enabled the Mage_Reviews block from both the views in Configuration> Current Configuration Scope. Both means from default as well as from Website view.
Later I found that the reviews form button is not working. I mean there is no problem with the form but the Submit button isn't working. Clicking on it does nothing! It's like an empty button with no function command. May I know what is the issue? Can anyone please help me in solving this?
Here is the Code that I'm getting after using "Inspect element" feature in Chrome.

A: It's working fine now. It was a problem related to a block.


text:
Q: When is a proper scoring rule a better estimate of generalization in a classification setting? A typical approach to solving a classification problem is to identify a class of candidate models, and then perform model selection using some procedure like cross validation. Typically one selects the model with the highest accuracy, or some related function that encodes problem specific information, like $\text{F}_\beta$.
Assuming the end goal is to produce an accurate classifier (where the definition of accuracy is again, problem dependent), in what situations is it better to perform model selection using a proper scoring rule as opposed to something improper, like accuracy, precision, recall, etc? Furthermore, let's ignore issues of model complexity and assume a priori we consider all the models equally likely.
Previously I would have said never. We know, in a formal sense, classification is an easier problem than regression [1], [2] and we can derive tighter bounds for the former than the later ($*$). Furthermore, there are cases when trying to accurately match probabilities can result in incorrect decision boundaries or overfitting. However, based on the conversation here and the voting pattern of the community in regards to such issues, I've been questioning this view.

*

*Devroye, Luc. A probabilistic theory of pattern recognition. Vol. 31. springer, 1996., Section 6.7

*Kearns, Michael J., and Robert E. Schapire. Efficient distribution-free learning of probabilistic concepts. Foundations of Computer Science, 1990. Proceedings., 31st Annual Symposium on. IEEE, 1990.

$(*)$ This statement might be a little sloppy. I specifically mean that given labeled data of the form $S = \{(x_1, y_1), \ldots, (x_n, y_n)\}$ with $x_i \in \mathcal{X}$ and $y_i \in \{1, \ldots, K\}$, it seems to be easier to estimate a decision boundary than accurately estimate conditional probabilities.

A: Think of this as a comparison between the $t$-test/Wilcoxon test and the Mood median test.  The median test uses optimum classification (above or below the median for a continuous variable) so that it only loses $\frac{1}{\pi}$ of the information in the sample.  Dichotomization at a point different from the median will lose much more information.  Using an improper scoring rule such as proportion classified "correctly" is at most $\frac{2}{\pi}$ or about $\frac{2}{3}$ efficient.  This results in selection of the wrong features and finding a model that is bogus.


text:
Q: Series Formula is correct but output is incorrect I used one formula for series, in which whenever there is any value in a particular cell then the adjacent cell will show the serial number, if empty then the serial number column will also be empty.
The Formula I used is:"=IF(B3:B="","",ROW()-2)" ( "-2" because there are 2 rows which have headings)
Then I used "=Match143^143,B3:B)" to get the last cell value.
I used the above 2 formulas for 2 sheets, it worked fine for a few days but now as the datasets increased it is showing a total count -2. Suppose the total count is 100 but is showing 98.
I used this formula ( "=IF(B3:B="","",ROW())" ) as well to check but it is also showing a difference of 2.
Thank you in advance

A: try:
=INDEX(IF(B3:B="",,COUNTIFS(B3:B, "<>", ROW(B3:B), "<="&ROW(B3:B))))

to make it faster use:
=INDEX(LAMBDA(x, IF(x="",,COUNTIFS(x, "<>", ROW(x), "<="&ROW(x))))
 (B3:INDEX(B:B, MAX(ROW(B:B)*(B:B<>"")))))

or:
=INDEX(LAMBDA(z, IF(z="",,SCAN(, z<>"", LAMBDA(x, y, x+y))))
 (B3:INDEX(B:B, MAX(ROW(B:B)*(B:B<>"")))))


text:
Q: Harmonize display names for automatic URL rewrites A couple of years ago, Stack Exchange switched to HTTPS-only and all internal links were rewritten by (non-bumping) edits by the Community user, like this one here.

I just noticed that on Stack Overflow (and perhaps on some other sites as well), all those edits are attributed to a deleted (or rather non-existing) user "URL Rewriter Bot" instead (example):

On the question page itself, the edit is attributed to the Community user:

For consistency's sake, should/could this be fixed?


text:
Q: BundlerMinifier Visual Studio 2022 We are trying to install the NuGet Package for the BundlerMinifier in VS2022, but we get no context menu or nothing to allow us to minify or bundle or anything else for that matter.
Is this a known issue.
Thanks

A: I had the same issue which is also described on the Github page of the package:
https://github.com/madskristensen/BundlerMinifier/issues/585
The solution for me was to install it from VS marketplace:
https://marketplace.visualstudio.com/items?itemName=Failwyn.BundlerMinifier64
And now I can bundle again even in VS2022


text:
Q: Differents between SDA and DDA in JavaCard? I have an applet (you can take a look at it there JavaCard applet is not working with RSA encryption).
Applet generates RSA public and private keys in constructor and with APDU command encrypt some byte array.
Applet generates public and private keys with KeyBuilder.LENGTH_RSA_2048 in docs provided with cards sad that JavaCard supports 2048 bits key length only in DDA.
So question is what is DDA and SDA. Differences between them? And main question is: how to install (or run?) applet in this mode?
What I found out:
Update 1: SDA -- Static Data Authentication
DDA -- Dynamic Data Authentication

A: So question is:

what is DDA and SDA. Differences between them?

SDA - SDA ensures the authenticity of ICC data. After SDA it is sure that the data from the ICC is real and hasn't changed by anyone.
But SDA doesn't assure the uniqueness of ICC data. You can see the diagram of SDA is like,

Here you can see two RSA Pair is using during SDA,
(1) - IssuerRSA
(2) - CA_RSA
this diagram is very descriptive and clear to understand the flow of SDA. Also you can check EMV BOOK 2 for more description about SDA. while DDA flow is like ,

here you can see 3 RSA Pair is using in DDA,
1 - IssuerRSA
2-  CA_RSA
3 - ICC RSA ( new RSA key which is unique in all card, Each card generate this RSA pair during personalization of card so this RSA Pair will be different for each card)
SDA guarantees that data on cards is valid because we trust a high level certification authority which signs the data. But an attacker can record a card session and build for example a new virtuel card because same data is used here for all session.
But in DDA flow - we can say it is checking SDA + giving random data to card by Terminal to sign and here this part makes cloning of card impossible because each session use different random number so recording a card session will not work in next card session.
hope it helps and more can you read from SDA and DDA , Gemalto

A: DDA implies Cipher.ALG_RSA_NOPAD algorithm (which is sometimes referred to as raw RSA or CKM_RSA_X_509) -- as @Hai-Binh LE noted, have a look into the EMV Book 2 (probably Annex B2).
You are instantiating a Cipher.ALG_RSA_PKCS1 which is not used for DDA, thus might be unsupported by the card.
You could verify this by inspecting the thrown CryptoException for CryptoException.NO_SUCH_ALGORITHM reason code.


text:
Q: How can I accelerate simple matlab code by GPU device I have encountered some problems while I was simulating simple code on Matlab GPU computing.
first case, I compared fft2 computation time of CPU with GPU
By CPU:
A=rand(2000);
tic
for K=1:200
   yy=fft2(A);
end
toc

By GPU:
A=gpuArray(A);
tic
for K=1:200
   yy=fft2(A);
end
toc

It took 5.984209 sec by CPU and 0.036392 sec by GPU. It seem to be a reasonable result.
At second case, I tried simple calculation.
By CPU:
D=rand(1,2000);
E=rand(1,2000);
tic
for K=1:2000
  pp=sqrt(D(K)^2+E(K)^2)/E(K);
end
toc

By GPU:
F=gpuArray(D);
G=gpuArray(E);
tic
for K=1:2000
  qq=sqrt(F(K)^2+G(K)^2)/G(K);
end
toc

It took 0.002940 sec by CPU and 2.699595 sec by GPU. It's a very strange result!
Why is this happening? I know that it can be faster by using 'arrayfun' for gpuArray inputs.
Is there no way to calculate 'for loop' by using GPU except for arrayfun?
I know that one GPU has a few thousands cores.  In that case, is it possible to use 'parfor loop' by using one GPU?
For non built in function, it is difficult to fit all conditions suitable for 'arrayfun'.
So, I think it is natural to using 'for loop' in a self-function. However, from the results above, 'for loop' makes the total process slow for gpuArray inputs.(It is slower than a CPU result)
So, I think all of general codes cannot be converted into 'GPU form' by using full advantage of GPU computing. Is that right?

A: As you have discovered, a FOR loop over scalar elements of gpuArray data performs terribly badly, and is almost always a bad idea. In general, you need to use either vectorised operations or arrayfun to get good performance. If that doesn't give you enough flexibility or performance, you can always use the CUDAKernel interface or the GPU MEX interface.


text:
Q: How to avoid code bloat when using pthreads in C? When writing threaded code in C, I first have to create some struct which includes all the arguments and a wrapper function. This leads to lots of code bloat and is not easy to read. See:
struct some_function_args {
  int arg1;
  int arg2;
  int arg3;
};

void some_function_wrapper(struct some_function_args* args) {
  some_function(args->arg1, args->arg2, args->arg3);
}

int main() {
  struct my_args;
  my_args.arg1 = 1;
  my_args.arg2 = 2;
  my_args.arg3 = 3;

  pthread_create(..., some_function_wrapper, &my_args);
  pthread_join(...);
}

Is there some kind of macro or library (maybe using varargs) which automatically creates the needed structs and wrapper functions for me, like this? Or is this not possible at all in C?
int main() {
  MY_THREAD thread = IN_THREAD {
    some_function(1, 2, 3);
  }

  JOIN_THREAD(thread);
}

A:
EDIT: I released some code. See threadify.h.

With the following macros you can do things like this:
char a = 'A';
int  b = 23;
char[] c = "Example";

pthread_t thread;

// THREAD3 because it takes 3 arguments of variable type.
THREAD3(thread, a, b, c, {
  printf("test: %c %d %s\n", a, b, c);
});

JOIN(thread);

It's possible in GCC, because GCC has two non-standard extensions:

*

*nested functions

*The typeof() operator

There are some drawbacks in this huge mess of macros:

*

*You cannot pass rvalues (because it's not possible to create pointers to them)

*You need to use the appropriate THREAD0, THREAD1, ... macro depending on the number of arguments (not sure if it's possible to work around this using variadic macros).
#include <stdio.h>
#include <pthread.h>

// Nested definition to work around preprocessor prescan
#define __CAT(arg1, arg2) arg1 ## arg2
#define CAT(arg1, arg2) __CAT(arg1, arg2)

// Use the current line number to create a unique name for objects
#define NAME(arg1) CAT(arg1, __LINE__)

// Creates a thread without any arguments
#define THREAD0(thread, code) \
void NAME(__pthread_wrapper)(void) {\
  do {code;} while(0); \
}; \
pthread_create(&thread, NULL, (void*)NAME(__pthread_wrapper), NULL);

// Creates a thread with one argument by creating a struct
// and passing all values via this struct.
#define THREAD1(thread, arg1, code) \
typedef struct { \
  typeof(arg1)* NAME(__pthread_arg1); \
} NAME(__pthread_struct); \
  void NAME(__pthread_wrapper)(NAME(__pthread_struct)* data) {\
  do {code;} while(0); \
}; \
NAME(__pthread_struct) NAME(__data); \
NAME(__data).NAME(__pthread_arg1) = &arg1; \
pthread_create(&thread, NULL, (void*)NAME(__pthread_wrapper), &NAME(__data));

#define THREAD2(thread, arg1, arg2, code) \
typedef struct { \
  typeof(arg1)* NAME(__pthread_arg1); \
  typeof(arg2)* NAME(__pthread_arg2); \
} NAME(__pthread_struct); \
  void NAME(__pthread_wrapper)(NAME(__pthread_struct)* data) {\
  do {code;} while(0); \
}; \
NAME(__pthread_struct) NAME(__data); \
NAME(__data).NAME(__pthread_arg1) = &arg1; \
NAME(__data).NAME(__pthread_arg2) = &arg2; \
pthread_create(&thread, NULL, (void*)NAME(__pthread_wrapper), &NAME(__data));

#define THREAD3(thread, arg1, arg2, arg3, code) \
typedef struct { \
  typeof(arg1)* NAME(__pthread_arg1); \
  typeof(arg2)* NAME(__pthread_arg2); \
  typeof(arg3)* NAME(__pthread_arg3); \
} NAME(__pthread_struct); \
  void NAME(__pthread_wrapper)(NAME(__pthread_struct)* data) {\
  do {code;} while(0); \
}; \
NAME(__pthread_struct) NAME(__data); \
NAME(__data).NAME(__pthread_arg1) = &arg1; \
NAME(__data).NAME(__pthread_arg2) = &arg2; \
NAME(__data).NAME(__pthread_arg3) = &arg3; \
pthread_create(&thread, NULL, (void*)NAME(__pthread_wrapper), &NAME(__data));

/* THREAD4, THREAD5, ... */

#define JOIN(thread) pthread_join(thread, NULL);

A: 'When writing threaded code in C, I first have to create some struct which includes all the arguments and a wrapper function. This leads to lots of code bloat and is not easy to read'.   Sure.  That's what you pay for making your app, (assuming it's not stupid), either X times faster or X times easier to implement becasue it's easier described as independent functionality.   You want something for nothing?


text:
Q: CRON - execute on days 1-5 during weeks 25 - 36 Is there any way to schedule execution of CRON:

*

*only during weeks 25 - 36 during the year

*and only on Mon - Frid (not weekends)

This is because of summer holidays when people place a lot of orders on our products. It is pretty tedious to change CRON settings every week. I understand that @weekly cannot be combined with star-settings, so something like following is not valid markup:
* * 1,2,3,4,5 * * @weekly php /app/cmd import >> /logs/cron-offers.log

A: You should be able to do this in this way:
# m h  dom mon dow   command
* * * * 1-5 /bin/bash -c "if [ `date +%W` -lt 15 ] && [ `date +%W` -gt 11 ]; then php /app/cmd import >> /logs/cron-offers.log; fi"

Put your correct number of week in the first and second "[]".

A: Cron is all things considered a very basic scheduler and the syntax does not easily allow an administrator to formulate slightly more uncommon schedules. Stock cron does not have a weeknumber available, so you have to be creative.
According to ncal -w 2018 weeks 25-36 is:
    May               June              July              August          September
Mo     7 14 21 28        4 11 18 25        2  9 16 23 30     6 13 20 27       3
Tu  1  8 15 22 29        5 12 19 26        3 10 17 24 31     7 14 21 28       4
We  2  9 16 23 30        6 13 20 27        4 11 18 25     1  8 15 22 29       5
Th  3 10 17 24 31        7 14 21 28        5 12 19 26     2  9 16 23 30       6
Fr  4 11 18 25        1  8 15 22 29        6 13 20 27     3 10 17 24 31       7
Sa  5 12 19 26        2  9 16 23 30        7 14 21 28     4 11 18 25      1   8
Su  6 13 20 27        3 10 17 24        1  8 15 22 29     5 12 19 26      2   9
   18 19 20 21 22    22 23 24 25 26    26 27 28 29 30 31 31 32 33 34 35  35  36

One approach is to create multiple batches that combined create the schedule you want. For instance first  simply select the weekdays of the last two weeks of June and then all week days of July and August in a second job and the first days of september as a third:
# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |

* * 18,19,20,21,22,25,26,26,28,29 jun * php /app/cmd import >> /logs/cron-offers.log
* * * jul,aug mon,tue,wed,thu,fri       php /app/cmd import >> /logs/cron-offers.log
* * 3-7 9 *                             php /app/cmd import >> /logs/cron-offers.log

Another option is to simply run your batch daily and use the more powerful syntax of a proper programming/scripting language  to let the batch process itself (i.e. your PHP code) determine if it should execute or exit immediately.


text:
Q: How to use jQuery to select a dropdown option? I was wondering if it's possible to get jQuery to select an <option>, say the 4th item, in a dropdown box?
<select>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
</select>

I want the user to click a link, then have the <select> box change its value, as if the user has selected it by clicking on the <option>.

A:  Try with the below codes. All should work.
    $('select').val(2);
    $('select').prop('selectedIndex', 1);
    $('select>option[value="5"]').prop('selected', true);
    $('select>option:eq(3)').attr('selected', 'selected');
    $("select option:contains(COMMERCIAL)").attr('selected', true);

A: HTML select elements have a selectedIndex property that can be written to in order to select a particular option:
$('select').prop('selectedIndex', 3); // select 4th option

Using plain JavaScript this can be achieved by:
// use first select element
var el = document.getElementsByTagName('select')[0];
// assuming el is not null, select 4th option
el.selectedIndex = 3;

A: I would do it this way
 $("#idElement").val('optionValue').trigger('change');

A: I prefer nth-child() to eq() as it uses 1-based indexing rather than 0-based, which is slightly easier on my brain.
//selects the 2nd option
$('select>option:nth-child(2)').attr('selected', true);

A:  $('select>option:eq(3)').attr('selected', 'selected');

One caveat here is if you have javascript watching for select/option's change event you need to add .trigger('change') so the code become.
 $('select>option:eq(3)').attr('selected', 'selected').trigger('change');

because only calling .attr('selected', 'selected') does not trigger the event

A: With '' element usually we use 'value' attribute. It will make it easier to set then:
$('select').val('option-value');

A: Try this:
$('#mySelectElement option')[0].selected = true;

Regards!

A: The easiest way is val(value) function:
$('select').val(2);

And to get the selected value you give no arguments:
$('select').val();

Also, you if you have <option value="valueToSelect">...</option>, you can do:
$('select').val("valueToSelect");

DEMO

A: if your options have a value, you can do this:
$('select').val("the-value-of-the-option-you-want-to-select");

'select' would be the id of your select or a class selector. or if there is just one select, you can use the tag as it is in the example.

A: answer with id:
$('#selectBoxId').find('option:eq(0)').attr('selected', true);

A: How about
$('select>option:eq(3)').attr('selected', true);

Example:

$('select>option:eq(3)').attr('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>

for modern versions of jquery you should use the .prop() instead of .attr()
$('select>option:eq(3)').prop('selected', true);

Example:

$('select>option:eq(3)').prop('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>

A: The solution:
$("#element-id").val('the value of the option');

A: Use the following code if you want to select an option with a specific value:
$('select>option[value="' + value + '"]').prop('selected', true);

A: This works for me:
$selectedindex=4

If you want to randomise options, you could always do something like this:
$0selectedindex=Math.floor((Math.random()*($0.length-1)+1)

Whilst the 2nd lies outside scope of your questions, it serves to illustrate how 1st could be applied / amended as req.


text:
Q: From javascript object to array I want to store an object in an array, but the object comes with (somekind of) name...
I wrote now the following code:
class Entry {
  constructor() {
    this.id = "";
    this.txt = "";
  }
}

let array = [
    {
    "id": "1",
    "txt": "Cat"
    },
    {
    "id": "2",
    "txt": "Dog"
    },
    {
    "id": "3",
    "txt": "Tiger"
    },
    {
    "id": "4",
    "txt": "Bear"
    }
]
let old = array.filter(e => e.txt != "");
console.log(old);
let pusher = array.push(new Entry());
newer = pusher.filter(e => e.txt != "");
console.log(newer);

If I console.log(array) in Chrome, then I get this:
(5) [{…}, {…}, {…}, {…}, Entry]
0: {id: "", txt: ""}
1: {id: "", txt: ""}
2: {id: "", txt: ""}
3: {id: "", txt: ""}
4: Entry {id: "", txt: ""}
length: 5
__proto__: Array(0)

Why do I get the word Entry? It stays in the array, not only as view in the console.

A: Very first you're trying to add the instance of Entry class in an array that why it returns wrong output.
you can hack this problem using create the normal object
create Entry object in below way
var Entry = { id:0,txt:""}

now you can used this object and set the new values and push into the array
Entry.id = 10
Entry.txt = "stack"
array.push(Entry);


text:
Q: Fractal image compression and image compression in Office and similar programs I have read that fractal image compression can be capable of reconstructing images, and then reconstruct them in any scale.
I have seen that programs like Word (97, 2000) can include images which seem to be as small or smaller than the original one, if "special paste" is used, and that the image can be resized.
Is it possible that Word 97/2000 (and other programs, like modern web browsers) use fractal image compression to achieve what I described?
Does it have something to do with fractal compression at all, or is there some similar method?

A: Microsoft has been known to use Fractal compression, but this is not what is going on in Word. It is possible to scale up an image using many different interpolation methods. Bi-linear, and bi-cubic interpolation are the most common. Word appears, to my eye, to be using bi-cubic interpolation. Vector quantization can also be used to scale up images. It is important to realize that no new detail is gained by enlarging an image this way. Fractal decompression is interesting in that it generates detail, but this detail isn't, in fact, real, simply a convenient byproduct of that particular interpolation method.


text:
Q: Java vs JavaFx vs Android SDK in Intellij Idea How should I choose among these buttons: Java vs JavaFx vs Android SDK in Intellij Idea start up? What are the difference among them? Can you guys explain to me? And if I intend to build an Android application, can I select the Java button? Pictures are shown as below...
How to choose?

A: If you want to create a Android projet, you need to use the Android button. This will setup all the requirements for the Android project to run on a mobile device.
The Java button creates a simple Java project unrelated to the Android framework.
JavaFX is a library to make desktop GUI. Pressing this button will setup a generate some template files ready to program with JavaFX.

A: As your image points out, you are about to create a new project. If you intend to create an Android project, then just click on the Android button, the IDE will create a basic project structure for you.


text:
Q: Creating multiple tables dynamically on ascx page asp.net I am trying to create multiple tables based on SurveyCount(ViewState variable) and populate them on ascx page itself rather than using code behind to populate the data. The number of tables being displayed are correct but I am not able to populate the table cells using foreach loop. The table cell doesn't identify the c variable.
<% if(SurveyCount > 0)
    {%>

    <% foreach(SurveyAvailabilities c in this.lstSurveyAvailabilities){%>

      <asp:Table id="Table2" runat ="server" GridLines="Both" HorizontalAlign="Center">
         <asp:TableHeaderRow    ForeColor="Snow" BackColor ="#8f001a"  Font-Bold="true" >
                    <asp:TableHeaderCell>Year</asp:TableHeaderCell>
                    <asp:TableHeaderCell>Language</asp:TableHeaderCell>
                    <asp:TableHeaderCell>Grade</asp:TableHeaderCell>
                    <asp:TableHeaderCell>Subject</asp:TableHeaderCell>
          </asp:TableHeaderRow>

          <asp:TableRow>
                <asp:TableCell Text="0" />
                <asp:TableCell Text="1" />
                <asp:TableCell><%= c.Grade%></asp:TableCell>
                <asp:TableCell><%= c.Subject%></asp:TableCell>
          </asp:TableRow>

        </asp:Table>
<textarea><%= c.Grade%></textarea>
    <br>
     <% } %>
 <% } %>

The text area identifies the element correctly but not the table cells. I do not want to use Gridview or Repeaters. How can I loop through the list and populate table cells?

A:
rather than using code behind to populate the data.

Well, the instant you start placing "<% and some c# code? You ARE in effect using code behind and server side code - that code becomes part of the code behind page. So, little consolation to say that you "trying" to avoid code behind, but then turn around and start writing some code behind for the web page anyway, right???
Now, I do kind of wish we had a lighter weight version of gridview. And often listview is better (since it follows a standard html table quite a bit closer).
So, at the end of the day? Seems to me, to save code, time, efforts, and quite much save world poverty here?
I think if you want some repeating tables? Well, then there is this thing called a REPEATer - (right in the name!!!).
given you have a repeater control, and you can then drop in a GV inside?
It becomes REALLY but REALLY hard to make a case to attempt a different road unless you have a FANTASTIC reason and case for doing so. (and you not done so).
Unless some huge compelling case exists, then it seems to be a simple approach is the best approach, and will also save all that time as a bonus.
I mean, this simple markup - we can have 2 or 15 tables.
        <asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
            <ItemTemplate>

            <asp:Label id="MyHeader" runat="server" Text='<%# Eval("TableGroup") %>' Font-Size="X-Large" >
            </asp:Label>

             <asp:GridView ID="GTable" runat="server"
                 class="table table-responsive-sm table-bordered table-hover" Width="20%">
             </asp:GridView>

            </ItemTemplate>
        </asp:Repeater>

I mean, golly, already less markup then you posted.
And code behind to load the repeater - say a source of tables - or even a list ?
Say this:
        DataTable TblList = new DataTable();
        TblList.Columns.Add("TableGroup");

        for (int i = 1;i<=3;i++)
        {
            DataRow OneRow = TblList.NewRow();
            OneRow["TableGroup"] = "Table " + i;
            TblList.Rows.Add(OneRow);
        }

        Repeater1.DataSource = TblList;
        Repeater1.DataBind();

The above will give us 3 tables!!! - not a lot of code.
For each set, we use Item data bound. Say this:
    protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        // each new group/thing, lets fill the grid/table
        GridView gV = (GridView)e.Item.FindControl("GTable");
        DataTable TestTable = new DataTable();
        TestTable.Columns.Add("Name");
        TestTable.Columns.Add("Age");

        int TableGroup = e.Item.ItemIndex + 1;
        // add 3 rows
        for (int i = 1; i <= 3; i++)
        {
            DataRow OneRow = TestTable.NewRow();
            OneRow["Name"] = "Group " + TableGroup + " Name " + i;
            OneRow["Age"] = i * 15;
            TestTable.Rows.Add(OneRow);
        }
        gV.DataSource = TestTable;
        gV.DataBind();
    }

And now we get this:

I mean, the above was done quite much in LESS time then it took me to write this post.
You have to ask how long you live, how many days you have, and what each day is worth to you? The above is now done, and in fact I am going to get a pizza.
You? Your still here trying to write and cobble up some code.
So, try the above simple idea - it oh so easy, and then you have spare time to go out for pizza.


text:
Q: Evaluation of Expressions inside printf in C I know that multiple expressions are evaluated from right to left.
Ex:
int i = 0;
printf("%d %d %d", i, i++, i++); // Prints 2 1 0

But when it comes to each expression to be evaluated, i'm not getting if it is from right to left or vice versa.
int main()
{
    int a = 1, b = 1, d = 1;
    printf("%d", a + ++a); // Result = 4
}

Considering evaluation from left to right, the preceding code should be evaluated as 1 + 2 = 3
int main()
{
    int a = 1, b = 1, d = 1;
    printf("%d", ++a + a); // Result = 4
}

And this should Evaluate as 2 + 2 = 4
But in both the cases the answer is 4.
Can anyone explain how these expressions are evaluated?

A:
I know that multiple expressions are evaluated from right to left.

No. The order of evaluation of function parameters is unspecified behavior. Meaning you can't know the order, it may differ from system to system or even from function call to function call. You should never write programs that rely on this order of evaluation.
In addition, there is no sequence point between the evaluation of function parameters, so code like printf("%d", ++a + a); also invokes undefined behavior, see Why are these constructs (using ++) undefined behavior?.
Please note that operator precedence and operator associativity only guarantees the order in which an expression is parsed! This is not related to the order of evaluation of the operands. (With a few special exceptions such as || && , ?: operators.)


text:
Q: add single variable to a sum google spreadsheet i have a simple p&l but i'd like to see the impact if one of the variables changes
eg
in A1 - i have sale unit price - i would like to apply that to a column of figures
if i do the normal =SUM(a1*E1) - thats ok but if i copy the sum down the column i get =SUM(A2*E2), =SUM(A3*E3) etc - i need A1 to be fixed ie: =SUM(A!*E2),=SUM(A!*E3) etc
(i could obviously copy the A1 cell down the column but everytime i want to see the changes i'd have to change all the cell contents everytime rather than just once)

A: Try a formula like the following:
=SUM(A$1*E1)

Example:


text:
Q: SQL Statement does not insert the required value to table column I'm inserting some values to a table using a sql statement. All the values get inserted, except the 'qty' column. When I do an echo for sql statement, it shows the value has been assigned to the sql statement. Table column data type is INT. Can anyone help me to spot the problem?
$it_code = $_POST['id'];

//Prompt user to enter required qty
echo '<script>';
echo 'var qty = prompt("Enter Qty", "");';
echo '</script>';

//Get the item details from item table
$sqlString = "Select * from items where it_code='".$it_code."'";
$objItem = new Allfunctions;
$result = $objItem->retriveData($sqlString);

//Get the selected qty from java script to php variable
$qty = "<script>document.writeln(qty);</script>";
$user_id =$_SESSION['user_id'];

//Insert to orders table
$sqlStringInsert = "INSERT INTO orders(user_id,it_code,qty,status,tr_timestamp) VALUES ('$user_id','$it_code','$qty','PENDING',CURRENT_TIMESTAMP())";
echo $sqlStringInsert;
$objItem->addToTable($sqlStringInsert,'Succsessfully added.','Error adding'); // This is a custom built method to insert data in to a table by taking the sql statement as the parameter

Following is the sql statement generated,

Following is the table data. Qty is always 0 eventhood the sql statement had a value at qty column.

A: Obligatory warning
The code as you have shown it should not be used in production as it is vulnerable to SQL-injection attacks. Preventing this is well covered on this site in other answers.
Answer
The issue is that the value of $qty you are injecting into your SQL is the string "<script>document.writeln(qty);</script>".  You just can't see it because you are likely echoing it out to the browser to test it.
Wrap your echoing of the SQL statement in a call to htmlentities() (docs) to see what's actually happening.
Depending on the version and settings, MySQL is very forgiving of bad data being injected to a column.  In this case, it sees a string of text being inserted to a numeric column, and just truncates it to 0.  See this in action here:
CREATE TABLE Foo (
  Id INT,
  Qty INT
 );

INSERT INTO Foo(Id, Qty) VALUES (1, 'a string of text');

SELECT * FROM Foo; -- returns a row (1, 0)

https://www.db-fiddle.com/f/dEoaYGEyXEjs6ocVBwyyyr/1


text:
Q: TPS9264x Synchronous Buck Controllers for Precision Dimming LED Drivers I have some questions about TI's TPS92641.
Please see below:
1.) Does anybody know the principle of Chopper OTA? there are no too much information in the datasheet.

2.) What's Quasi-hysteretic control? I google it but I couldn't find paper told this control theory.

A: For the offset compensation, Ccomp is integrating the current out of the gm amp.  There's a clock and switches on the input and output of the amplifier that switch the polarity of BOTH the input and output, presumably with a 50% duty cycle.
Therefore, any offset in the amplifier increases the voltage on Ccomp during 1/2 clock cycle and decreases it during the other, averaging to zero.
The buck is a constant on-time converter where the on time is set based on Vin and Vout.  At the start of each switching cycle the buck switch turns on for a fixed period of time.  If the output voltage rises above the regulation point the switch stays off until it falls below the setpoint.  Then the cycle repeats.  This has the advantage that during transients the switching frequency can increase for very good transient response.  In steady-state with fixed input voltage the switching frequency will be close to constant.


text:
Q: If widowed aunt remarries, is her husband "uncle"? My mother's brother's wife Louise has always been Aunt Lou to me; her husband, my Uncle Bob, died young, but we still called her Aunt Lou.
After many years she has now re-married. Is her second husband my Uncle Jim or not?

A: It's a matter of culture and how close you interact with him. Technically, I dont think he is your uncle anymore. He is a new guy in a separate family and doesn't have to do anything with being your uncle. But if you are still in close contact with your aunt and want to stay with her in good terms, why not. I'd call him uncle. And there's nothing wrong with it. I have seen people calling strangers uncles just because they know their father.


text:
Q: Redux isn't holding the data after callback fucntion?     import axios from 'axios';
    export const DO_LOGIN = 'do_login';
    export function doLogin(values, callback){
        console.log(values);
        const request = axios.post(`http://localhost:80/auth/signIn`, values)
        return{
            type: DO_LOGIN,
            payload: request
        }
    }

after calling my function doLogin it is executing the request and callback as specified and working good after that the request isn't holding my data anymore and showing it as undefined where I look at in my console?

A: I am unsure what you are trying, but I would recommend to additionally use redux-thunk middleware, to do that:
const doLogin = values => dispatch => axios.post(…)
  //not sure if one needs that for axios,
  //but for fetch that is required
  .then(res => res.json())
  .then(json => dispatch({
    type: DO_LOGIN,
    payload: json
   }));

That way the action dispatch is actually refered until the request is finished and the resulting data is dispatched to the store.
That way you also handle errors like so:
 const doLogin = values => dispatch => … //as above
   //…
   .catch(error => dispatch({
     type: DO_LOGIN_ERROR,
     error: true,
     payload: error
    }))

Additionally you can dispatch more actions so indicate the start of the request like so:
const doLogin = values => dispatch => {
  dispatch({
    type: DO_LOGIN_START
  });

  return axios.post(…)
    .then(res => res.json())
    .then(json => dispatch({
       type: DO_LOGIN_SUCCESS,
       payload: json
     }))
    .catch(err => dispatch(/*as above*/))
}

Please note that the action creator returns the promise, so in other places, where you trigger the action you can do:
doLogin({…}).then(data => callBack());

If you follow that way, it is much easier to in cooperate with redux-form, if you are using that for your forms, what I would recommend to use, too.
You should be aware, that the within the response object, its data is exposed as stream. That means, you cannot read the data twice. Once res.json() or res.body() is called, the data of the response is »consumed« and cannot be accessed from the response object again.


text:
Q: Making a fetch call in React.js this is my first stack overflow post so I hope I explain this well enough. I am having trouble with a fetch request to my api. It is returning the correct data. However, I believe the issue is with the promise being returned is asynchronous as  well as the function calling the fetch. handleSubmitLogin is a call back function from my Login component.
handleSubmitLogin = (loginInformation) => {
    var userInfo = this.getUser(loginInformation);
    this.setState({loggedIn:true, currentUser:userInfo})
}

getUser(loginInformation) {
fetch('http://localhost:3001/api/getUser', {
  body: JSON.stringify(loginInformation),
  cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
  credentials: 'same-origin', // include, *omit
  headers: {
    'content-type': 'application/json'
  },
  method: 'POST', // *GET, PUT, DELETE, etc.
  mode: 'no cors', // no-cors, *same-origin
})
.then( (res) => {
  var userInfo = res.json();
  console.log(userInfo)
  return userInfo
})

}

Essentially, I know it is trying to setState withough having the userInfo because the promise is pending. I tried running the setState inside the .then instead but this caused React to refresh the page for some reason.
Any help would be appreciated, and if you need to see more code let me know! Thanks!


text:
Q: any number following ### regular expression I am having string like below
###method:song:2###

also string like below
###method:song:2######method:movie:4###

Number 2 and 4 is not static its dynamic 0-9 any number come.
i need to replace the string like below

Can any one please help me to fix this.
I tried below for starting ### change
str = str.replace(new RegExp('###method', 'gi'),'
###method');

http://jsfiddle.net/Ayt9S/417/

A: str = str.replace(/(###method:(song|movie):\d###)/, '
$1
');

A: str.replace(/(###method:.+?:\d###)/gi, '
$1
')

A: Use a capture group
match ###, anything but # more than one time, and ###

var str = '###method:song:2######method:movie:4###'
console.log(str.replace(/(###[^#]+###)/g,"
$1
")) // keep #
console.log(str.replace(/###([^#]+)###/g,"
$1
")) // ignore #


text:
Q: Is it gramatically correct to omit the preposition "on" when talking about events occuring on a certain day? I'm taking this online course on technical writing. It suggests that you can omit "on" from

The meeting happened on Monday

to turn it to

The meeting happened Monday

The second one seems wrong to me, and I haven't seen it being commonly used either.


text:
Q: How Can I test jQuery validation error msgs with cucumber? I googled around and I found this:
https://gist.github.com/1056822
However, once I put it into my project I got this:
Unable to find xpath <XPath::Union:0x106cfc928 @expressions=[

<XPath::Expression::Where:0x106d026c0 @left=#<XPath::Expression::Where:0x106d02bc0 @left=

<XPath::Expression::Descendant:0x106d1e960 @left=., @expressions=[

<XPath::Expression::Literal:0x106d02d50 @expression=:input>,

<XPath::Expression::Literal:0x106d02d28 @expression=:textarea>..... and it goes on

Can anyone tell me how jQuery validation is supposed to be test with cucumber?
Thanks

A: Try just looking for the error messages...I believe the syntax is
Then I should see "<your error message text>"

A: As jaydel said, you can just use Then I should see "whatever".
If you want to use XPath, try checking out W3School's XPath page: http://www.w3schools.com/xpath/xpath_syntax.asp
You should only really be using XPath if you want to dig deep in to the DOM and do very specific stuff that simply doing I should see doesn't support.
You can also try looking up Capybara's rdoc (http://rdoc.info/github/jnicklas/capybara/master/frames) if you want to write something custom.


text:
Q: why this CMake don´t compile? I'm stuck in a CMake project that isn't compiled. I isolated the problem in a simple test project. It is composed from a file teste (main) and a lib that is in libs/ subdirectory. The teste is very simple: the main calls a function that is in lib.
The compiler is generating .c.o compiled files instead of .o files.  CMake generates the Makefile but when I run make it compiles ok but on link phase it gives me:
make
Consolidate compiler generated dependencies of target testecompila
[ 50%] Linking C executable bin/testecompila
/usr/bin/ld: CMakeFiles/testecompila.dir/teste.c.o: na função "main":   <=== .c.o file
teste.c:(.text+0x19): referência não definida para "testeint" <=== the libs fct I call in main
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/testecompila.dir/build.make:97: bin/testecompila] Erro 1
make[1]: *** [CMakeFiles/Makefile2:83: CMakeFiles/testecompila.dir/all] Erro 2
make: *** [Makefile:91: all] Erro 2

Directory tree:
.    ===> testcompila dir
├── libs
│   ├── bin
│   │    └── Makefile       ==>>> Generated from CMake
│   ├── include
│   │   └── testelib.h
│   └── src
│       ├── CMakeLists.txt
│       └── testelib.c
└── src
    ├── bin
    │    └── Makefile       ==>>> Generated from CMake
    ├── CMakeLists.txt
    └── teste.c

test.c:
#include "stdio.h"
#include "testelib.h"

int main(int argc, char** argv)
{
  return testeint();
}

testelib.h:
int testeint();

testelib.c:
#include "testelib.h"

int testeint()
{
  int C = 0;
  C++;
  return C;
}

teste.c:
#include "stdio.h"
#include "testelib.h"

int main(int argc, char** argv)
{
  return testeint();
}

CMakeLists from ./src
####################
#      Global      #
####################

cmake_minimum_required(VERSION 3.12)
#set(CMAKE_CXX_STANDARD 17)

#####################
#      Project      #
#####################

# Project variables
set(LOCAL_PROJECT_NAME        "testecompila")
set(LOCAL_PROJECT_VERSION     "0.0.1")
set(LOCAL_PROJECT_DESCRIPTION "Teste compilação")

# Source files (relative to "src" directory)

set(SOURCES
    teste.c
   )

# Compiler definitions
set(DEFINES
)

# Compiler options
set(OPTIONS
)

# Project setup
project(${LOCAL_PROJECT_NAME}
        VERSION ${LOCAL_PROJECT_VERSION}
        DESCRIPTION ${LOCAL_PROJECT_DESCRIPTION}
        LANGUAGES C)

add_executable(${LOCAL_PROJECT_NAME} teste.c)

list(TRANSFORM HEADERS PREPEND "../include/")
list(TRANSFORM SOURCES PREPEND "../src/")

INCLUDE_DIRECTORIES(../libs/include/)

message ("======>" ${LOCAL_PROJECT_NAME})

set_target_properties(${LOCAL_PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "bin")
set_target_properties(testecompila PROPERTIES LINKER_LANGUAGE C)

target_include_directories(testecompila PUBLIC ${PROJECT_BINARY_DIR})

####################
#   Dependencies   #
####################

CMakeLists.txt from ./libs/src
cmake_minimum_required(VERSION 3.23)

project(libteste)

add_library(libteste STATIC testelib.c)

SET_SOURCE_FILES_PROPERTIES(testelib.c PROPERTIES LANGUAGE C)

INCLUDE_DIRECTORIES(/usr/include )

set(CMAKE_EXE_LINKER_FLAGS --verbose)

I am on a VM Oracle VirtualBox runing Ubuntu.

A: You need to tell testecompila that is uses libteste. Try something like target_link_libraries(${LOCAL_PROJECT_NAME} PUBLIC libtests).


text:
Q: Rails Autocomplete (depending on the choice) I have this:
# _form.html.erb
f.text_field :c,  data: {autocomplete_source: @correlations.all.map { |x| x.name }}<br>
f.text_field :n,  data: {autocomplete_source: @customers.all.map { |x| x.note}}

// Coffee script
$('#launch_c').autocomplete source: $('#launch_c').data('autocomplete-source')
$('#launch_n').autocomplete source: $('#launch_n').data('autocomplete-source')

I need that the variable @customers depending on the choice of correlation...
Can anyone help me?

A: If I understand you correctly, this isn't trivial to do. Basically you'll need something like this:

*

*Store all Customers in nested JSON on the page, so that Jquery can easily look up all the Customers for a given Correlation. (If there are more than a hundredish Customers or Correlations, you may want an AJAX call instead of pre-loading all the possible records into the page.)

*Jquery code that detects when a Correlation is selected, fetches the Customers array for that Correlation, and re-initializes the Customer autocomplete widget with the relevant data. See the Jquery Autocomplete API documentation for more detail on how to detect change events etc.

The result might look something like this Jquery code:
$('#launch_c').autocomplete({
  source: $('#launch_c').data('autocomplete-source'),
  change: function(event, ui){
    var correlation_name = ui.item.value;
    var data = $('#launch_n').data('autocomplete-source')[correlation_name];
    $('#launch_n').autocomplete({ source: data });
  }
});

And it would require #launch_n to have a data-autocomplete-source nested JSON something like this:
{
  "correlation1_name": ["customer1_name", "customer2_name", "customer3_name"],
  "correlation2_name": ["customer4_name", "customer5_name", "customer6_name"],
  "correlation3_name": ["customer7_name", "customer8_name", "customer9_name"],
  // etc.
}


text:
Q: Segmentation fault with Lucene and MMapDirectory we are using NIOFSDirectory instead of MMapDirectory in an intensive test load for indexing.  But we are still getting a SIGSEV with MMapDirectory.  Is there anything else I should be looking for? This is a Linux 64 bit machine. Head of the stack trace follows:
Please let me know what more info would be helpful.
Thanks...

A fatal error has been detected by the Java Runtime Environment:
SIGSEGV (0xb) at pc=0x00002aaaab285ea7, pid=2408, tid=1128642880
JRE version: 6.0_25-b06
  Java VM: Java HotSpot(TM) 64-Bit Server VM (20.0-b11 mixed mode linux-amd64 compressed >oops)
  Problematic frame:
  J  org.apache.lucene.store.MMapDirectory$MMapIndexInput.readByte()B

A: You are most likely closing your IndexReader while other threads are still using it?
Lucene tries to catch this mis-use but it's detection is best-effort only.
You could also try calling MMapDirectory.setUseUnmap(false) to turn off unmapping; this should prevent the SIGSEGV.


text:
Q: Can you delete Microsoft.Web/certificates? I'm creating LetsEncrypt SSL certificates for each of our Web App Services, then binding it to the Web App and subsequently trying to delete the previous one from our Azure resources. I notice Remove-AzureRmWebAppSSLBinding has a -DeleteCertificate flag after unbinding an SSL certificate, but I'd prefer not to unbind/delete until a new certificate has been obtained an bound.
Is there any other way that I can remove the certificates from Azure?

A: I found that I can delete any resource by ID using Remove-AzureRmResource.
Remove-AzureRmResource -ResourceId $resourceId -Force

This solves my problem for now!


text:
Q: How can I binding combo's selectionIndex and Integer in Eclipse RCP application (SWT)? For binding String and Combo I can use this code:
IObservableValue comboTypeObserveTextObserveWidget = SWTObservables.observeText(comboType);
IObservableValue typeObserveValue = PojoObservables.observeValue(router.getParameters(), "type.data");
bindingContext.bindValue(comboTypeObserveTextObserveWidget, typeObserveValue, updateStrategy, null);

Where "type.data" is String.
But I want to bind combos's selectionIndex with Integer value. How can I do that?

A: You can use org.eclipse.jface.databinding.swt.SWTObservables.observeSingleSelectionIndex(Control) for this purpose...
package test123;

import java.beans.PropertyChangeListener;

import org.eclipse.core.databinding.AggregateValidationStatus;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.beans.BeansObservables;
import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.databinding.swt.ISWTObservableValue;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

public class Test123 extends Shell {

    private static class Pojo<T> {
        private T data;

        public T getData() {
            return data;
        }

        public void setData(T data) {
            this.data = data;
        }

        public void addPropertyChangeListener(PropertyChangeListener l) {
        }

        public void removePropertyChangeListener(PropertyChangeListener l) {
        }
    }

    /**
     * Launch the application.
     *
     * @param args
     */
    public static void main(String args[]) {
        try {
            final Display display = Display.getDefault();
            Realm.runWithDefault(SWTObservables.getRealm(display),
                    new Runnable() {

                        @Override
                        public void run() {
                            Test123 shell = new Test123(display);
                            shell.open();
                            shell.layout();
                            while (!shell.isDisposed()) {
                                if (!display.readAndDispatch()) {
                                    display.sleep();
                                }
                            }

                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Create the shell.
     *
     * @param display
     */
    public Test123(Display display) {
        super(display, SWT.SHELL_TRIM);
        setLayout(new GridLayout(1, false));

        Combo combo = new Combo(this, SWT.READ_ONLY);
        combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1,
                1));
        combo.setItems(new String[] { "Test 1", "Test 2", "Test 3" });
        createContents();
        final Pojo<Integer> pojo = new Pojo<Integer>();
        ISWTObservableValue swtObs = SWTObservables
                .observeSingleSelectionIndex(combo);

        Label lblNewLabel = new Label(this, SWT.NONE);
        lblNewLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
                false, 1, 1));
        IObservableValue modelObs = BeansObservables.observeValue(pojo, "data");
        final DataBindingContext dataBindingContext = new DataBindingContext();
        dataBindingContext.bindValue(swtObs, modelObs, new UpdateValueStrategy(
                UpdateValueStrategy.POLICY_CONVERT)
                .setAfterConvertValidator(new IValidator() {
                    @Override
                    public IStatus validate(Object value) {
                        if ((Integer) value == 1) {
                            return ValidationStatus
                                    .error("Test 2 is not allowed");
                        }
                        return ValidationStatus.ok();
                    }
                }), null);
        addDisposeListener(new DisposeListener() {
            @Override
            public void widgetDisposed(DisposeEvent e) {
                // this is neccessary since POLICY_CONVERT does not
                // automatically set the value to the model.
                dataBindingContext.updateModels();
                System.out.println(pojo.getData());
            }
        });
        ISWTObservableValue valiObs = SWTObservables.observeText(lblNewLabel);
        dataBindingContext.bindValue(valiObs, new AggregateValidationStatus(
                dataBindingContext.getBindings(),
                AggregateValidationStatus.MAX_SEVERITY));

    }

    /**
     * Create contents of the shell.
     */
    protected void createContents() {
        setText("SWT Application");
        setSize(450, 300);

    }

    @Override
    protected void checkSubclass() {
        // Disable the check that prevents subclassing of SWT components
    }
}


text:
Q: OpenGL multi-GPU support When we create the OpenGL context on PC, is there any way to choose which physical device or how many devices are used? Do the latest OpenGL (4.5) APIs support multi-GPU architecture? If I have two identical graphics cards (for example, two Nvidia GeForce cards), how do I properly program the OpenGL APIs in order to get benefits from the fact that I have two cards? How do I transfer the OpenGL program from a single GPU version to a multi-GPU version with minimal efforts?

A: OpenGL drivers expose multiple GPUs (in Crossfire/SLI configurations) as if they were a single GPU. Behind the scenes, the driver will (theoretically) figure out how to dispatch rendering calls efficiently between the two GPUs. There are several methods for doing so, and you have zero control over which mechanism a driver picks.
If you want more direct control over which GPU is associated with which GL context, you have to use vendor-specific extensions. AMD has WGL_AMD_gpu_association, while NVIDIA has WGL_NV_gpu_affinity.


text:
Q: Send pub/sub message from Google Tag Manager server side I'm in a project and I ran out of ideas... I have an instance of google tag manager server side running, and I want to send data to my cloud function. I've manage to do it through HTTP request but I would like to use cloud function triggered by pub/sub and how to do it? I need to send a pub/sub message from GTM server. Does anyone did it? Is There any kind of integration that I'm not aware?
Any input on that matter is much appreciated!


text:
Q: QField does not open Raster.gpkg? Qfield cannot load GeoPackage raster data exported with Qgis 3.8.0.  Download vector data from the gpkg file.  The test with a single raster file in a GeoPackage also failed.

A: For some reason qfield does not understand relative path in .gpkg rasters. My workaround was to create exactly same path of qfield project in my Linux machine (/sdcard/Android/data...). Might it be same case for you?

A: If you drag and drop the geopackage raster from a file browser into QGIS (and not open it from internally), this helps to store the path as a relative path inside the QGIS project file.


text:
Q: Protect the font format in macros I define a macro (\chit) that uses one font (sc), and the macro is used in another macro that textbf in the implementation - \textbf{Q\thequestion: #1?}.
\documentclass[12pt]{article}
\usepackage{xspace}

\newcounter{question}

\newcommand{\chit}{\textsc{Chitx}\xspace}
\newcommand\Que[1]{%
    \leavevmode\par
    \stepcounter{question}
    \noindent
    \textbf{Q\thequestion: #1?}\par}

\newcommand\Ans[1]{%
     \leavevmode\par\noindent
    {\textbf{A\thequestion:} #1\par}}

\begin{document}

\Que{What is \chit}? % <-- Wrong font
What is \chit? % <-- Correct font

\end{document}

As a result, the output does not show the font type that I expected.
How to protect the font type that I specified in the \chit macro?

EDIT1
For the Q&A macro, I copied it from Q&A Template in LaTeX

A: You get the warning
LaTeX Font Warning: Font shape `OT1/cmr/bx/sc' undefined
(Font)              using `OT1/cmr/bx/n' instead on input line 19.

which means that there is no boldface small caps font in the Computer Modern font family.
On the other hand, the European Modern font family does have it.
\documentclass[12pt]{article}
\usepackage[T1]{fontenc}
\usepackage{xspace}

\newcounter{question}

\newcommand{\chit}{\textsc{Chitx}\xspace}
\newcommand\Que[1]{%
    \leavevmode\par
    \stepcounter{question}%
    \noindent
    \textbf{Q\thequestion: #1?}\par}

\newcommand\Ans[1]{%
     \leavevmode\par\noindent
    {\textbf{A\thequestion:} #1\par}}

\begin{document}

\Que{What is \chit}? % <-- Wrong font
What is \chit? % <-- Correct font

\end{document}

I'm not sure what \leavevmode\par is for; if your aim is to have some space before the question, it's the wrong tool:
\newcommand\Que[1]{%
    \par\addvspace{\bigskipamount}% <--- or whatever
    \noindent\stepcounter{question}
    \textbf{Q\thequestion: #1?}\par
}

Full code:
\documentclass[12pt]{article}
\usepackage[T1]{fontenc}

\newcounter{question}

\newcommand{\chit}{\textsc{Chitx}}
\newcommand\Que[1]{%
  \par\addvspace{\bigskipamount}% <---- fix it
  \noindent\stepcounter{question}%
  \textbf{Q\thequestion: #1?}\par
}

\newcommand\Ans[1]{%
  \par\noindent
  \textbf{A\thequestion:}~#1\par
}

\begin{document}

Some text before the question. What is \chit?

\Que{What is \chit}
\Ans{I don't know}

\end{document}


text:
Q: Get hard-coded values from component into plugin in Joomla 3.x I have a custom component, in fact several. Each will have raw and hard-coded html at the beginning and end of their /view/default.php
I have a system plugin that needs to get this html and in some cases change it to something else, that can be managed in the back end. As a content plugin this works fine on all com_content articles, but it is ignored by components, my understanding is system plugins can do this but i can't get the data into the plugin and return it
example of component text ($text1, $text2 are defined at the top of the document)
  JPluginHelper::importPlugin( 'system' );
  JPluginHelper::importPlugin('plgSystemMyplugin');
  $dispatcher =& JDispatcher::getInstance();
  $data = array($text1, $text2);   // any number of arguments you want
  $data = $dispatcher->trigger('onBeforeRender', $data);

title

     <?php  var_dump($data);  ?>

my plugin:
      jimport( 'joomla.plugin.plugin' );

   class plgSystemMyplugin extends JPlugin {
function onBeforeRender() {

    if (JFactory::getDocument()->getType() != 'html') {
            return;
    }
    else {
    $document=JFactory::getDocument();
    $document->addCustomTag('');
    $document=JResponse::getBody();

    $bob=JResponse::getBody();

        $db = &JFactory::getDbo();
        $db->setQuery('SELECT 1, 2 FROM #__table');
        $results = $db->loadRowList();
        $numrows=count($results);

                if($numrows >0) {
                                foreach($results as $regexes) {
                                $document  = str_replace($regexes[0],$regexes[1],$document);
                                }
                                return $document;
                }
                else  {
                    $document = 'error with plugin';
                }
    JResponse::setBody($document);
    return $document;
    }
   }
   }

at the moment $data returns an array with a key 1 and value (string) of "" (blank/empty).
but not the data from the database I am expecting.
in simple terms I have {sometext} in my file and my database and it should return
my other text

can you help?
thanks

A: Ok. Well looking at this deeper there is a couple of issues that jump out. The biggest being that you save getBody into a variable named $bob but then switch everywhere to using $document which is the object form above, not the content.
Also, you had a return $document hanging out in the middle of the code that prevented you from seeing that you were going to set $document as the new body. Probably should be more like below:
    $bob=JResponse::getBody();

    $db = &JFactory::getDbo();
    $db->setQuery('SELECT 1, 2 FROM #__table');
    $results = $db->loadRowList();
    $numrows=count($results);

    if($numrows >0) {
        foreach($results as $regexes) {
            $bob  = str_replace($regexes[0],$regexes[1],$bob);
        }
    }
    else  {
        $bob = 'error with plugin';
    }
    JResponse::setBody($bob);
    return $document;
}

Original Thoughts:
Two thoughts to get you started. I'm not sure that this will actually fully answer the question, but should get you moving in the right direction.
First, you should not have to trigger the system plugin. They are system plugins, so the system will take care of that for you. If you wanted to use content plugins in your component (which you can definitely do!) then you would have to trigger them like your first set of code. In this case, don't bother with the entire dispatch section.
Second, your plugin looks set up to grab the body from the JDocument correctly, so that should work.
The likely issue is that the entire system plugin is just not being triggered. Make sure that it is installed and everything is named correctly. It has to be at plugins/system/myplugin/myplugin.php based on this name and make sure that the xml file with this also references myplugin as the plugin name. If not, the system won't find the class but likely won't throw an error. It will just skip it. This gives me trouble every time.
To do some checking just to make sure it gets called, I usually throw an echo or var_dump near the top of the file and just inside the function. Confirm that the function is at least getting called first and you should be most of the way to getting this to work.


text:
Q: Can you login to a different aws OU with master account I know i can create roles and switch between them and I've done a bit a research and it seems the answer is no but I just wanted to make sure.
So i was hoping that when a account joins my organisation, there would be some way for me to use my master account to login to the new OU, e.g. without me having to login and create new roles / users etc. Is this possible?

A: In order to access the new account from your existing "master" account, the new account that joins your org needs to have a role which allows cross-account access from your master account.
Its worth noting that many organizations automate the creation of accounts, and then use CloudFormation to configure the account (which you could use to create a cross account role for you to use to access the new account). You can learn more about this in the AWS tutorial here.


text:
Q: Creating a copy of attribute value of NSManagedObject I need to create a copy/save/duplicate  of listID attribute of NSManagedObject list. The scenario is first delete list from local store and then i send request to server for deleting list objects using their id but when i delete objects from local store there i cannot then access object ids. Following is the code
List *list = (List*)[self.fetchedResultsController objectAtIndexPath:indexPath];

NSString *listID = [list.listID stringValue];
[listsToDelete addObject:listID];

[context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];

i tried to store object id string value in an array for later use but no avail because if at later i access listToDelete it is nil. Why do i need to do to achieve this?

A: Based on the limited code you have shown, a few things come to mind:
1) Did you initialize your listsToDelete? I imagine that is an NSMutableArray type. You need to initialize it properly.
IE. NSMutableArray* listsToDelete = [[NSMutableArray alloc] init];
2) Have you tried logging the value of list.listID prior to adding it into your array? Maybe the value was nil to begin with?


text:
Q: AngularJS unexpected routing I have .NET Core Single Page application with AngularJS routing and this app have some links ("Main page", "Additional info", "Contacts", etc) at the layout. When user click to "Additional info" by link, it's displayed "/app/additionalInfo" page, but when user copy-paste this url to address field, my application opens "/app/additionalInfo" firstly, but then browser make redirect to "Main page".
Can anybody explain me, how to find reason of this strange behaviour and how to fix it?


text:
Q: How to make a good validation on laravel? I have data, they look like this:
 {
   sender_name : "Real fake sender name",
   recipient_name : "Real fake recipient name",
   goods: [
     {
        "no" : 1
        "name":"Pen",
        "unit": "1",
        "qty":"50",
        "price":"50",
        "amount":"2500",
        "vat_percent":"5",
        "vat_sum": "125",
        "total_sum": "2625"
     }
   ]
 }

I need to validate "goods" using extend validator. Here is his code:
Validator::extend('invoiceGoods' , function($attribute, $value, $parameters, $validator) {

  $rulesForGoods = [
      'no'          => 'integer|required',
      'name'        => 'string|max:64|required',
      'unit'        => 'required|integer',
      'qty'         => 'required|string',
      'price'       => 'required|numeric',
      'amount'      => 'required|numeric',
      'vat_percent' => 'nullable|numeric',
      'vat_sum'     => 'nullable|numeric',
      'total_sum'   => 'required|numeric'
  ];

  foreach ($value as $good) {
      $validator = Validator::make($good , $rulesForGoods);
      if ($validator->fails()) {
          return false;
      }
  }

  return true;

});

This is the main code.
$validator = Validator::make($data , [
   'goods' => 'invoiceGoods',
   'sender_name' => 'string',
   'recipient_name' => 'string',
]);

if ($validator->fails()) {
  return response()->json([
    'success' => false,
    'message' => 'Validation error.',
    'data'    => $validator->errors()
  ]);
}

If the goods validation error occurs, I get this answer:

But I would like to display errors like this: the wrong unit in the goods with no 1.
I know that the third argument can be passed an array with custom messages, but how to return it from the extended validator if it should return true or false?

A: https://laravel.com/docs/5.8/validation#custom-error-messages
$messages = [
'Validation.invoice_goods' => 'Errror message!',];

$validator = Validator::make($input, $rules, $messages);


text:
Q: What is the difference between a macrostate and multiplicity? The entropy of a system of an ideal gas depends on the external parameters $U, V, N$.
I always thought entropy is defined by a certain macrostate, which is a set of given external conditions like fixed $U,V,N$. This is one defined macrostate. The macrostate is the framework for a certain amount of accessible microstates.
But now I read that there is not only a single macrostate of a system, but that there can be various macrostates. The multiplicity of a macrostate is the probability of a certain macrostate to occur. So if there are various macrostates that can occur (regardless of how unlikely) what does that mean for our external parameters? How can there be different macrostates with different $U, V, N$?
Or is it just misleading that the multiplicity of indistinguishable particles is also called a macrostate, although there is only one "real" macrostate (defined by the external parameters)?

A:
"But now i read that there is not only a single macrostate of a system,
but that there can be various macrostates."

This is not in conflict with your previous understanding that a fixed U,V,N defines a macrostate. I think you just misinterpreted the statement. If a particular set of values for U,V,N denotes a particular macrostate, that means that if you change any of the values, you have another, different macrostate. The above statement just says that there are different macrostates (that U,V,N can take different values; i.e. the system can be found in different macrostates).

"The multipicity of a macrostate is the probability of a certain
macrostate to occur."

No reason to assume that all macrostates will occur with equal probability. A macrostate is an abstraction that ignores the particular microscopic configuration of particles (microstate), meaning that there can be a number of microstates that all manifest as the same macrostate. That's where the multiplicity comes from.
In other words, it's not talking about a multiplicity of macrostates that are somehow equivalent. It's a multiplicity of microstates that give rise to the same macrostate. Some macrostates can be "manifested" by many different microstates, while others by only a small number of them - which then ties into the probability (greater if there are more ways for the same (macro-)thing to  occur).

"So if there are various macrostates that can occur (regardless of how
unlikely) what does that mean for our external parameters?"

It means that the values of the parameters have a probability distribution.

A:
So if there are various macrostates that can occur (regardless of how unlikely) what does that mean for our external parameters? How can there be different macrostates with different U, V, N?

It means that the quantities which define the macrostate of the system (in this case, $U,V,$ and $N$) are not being held fixed.

*

*If your system is in thermal contact with a heat bath, then $U$ is not fixed because heat can flow between the system and its environment.

*If the system can expand or contract, then $V$ can change.

*If the system is in contact with a particle reservoir (e.g. a semi-permeable membrane), then $N$ is not fixed because particles can flow in and out.

Consider a system with fixed $U,V,$ and $N$.  The values of $(U,V,N)$ define a macrostate of the system.  The number of microstates which correspond to this macrostate, also called the multiplicity, is $\Omega(U,V,N)$; since all microstates are equally likely, the probability that the system is in any particular microstate is simply $\frac{1}{\Omega(U,V,N)}$. The collection of all such microstates and the associated uniform probability distribution is called the microcanonical ensemble.
Now consider a system with fixed $V$ and $N$ but which is in contact with a heat bath at temperature $T$.  The system can exchange energy with the heat bath, which means that its total energy is not fixed; in principle, it could have any value of $U$.  The probability that a system is in a particular microstate now depends on the total energy $U$ of that microstate.
Explicitly, the probability that the system occupies a microstate with energy $U$ is given by $P(\mu) = e^{-U/kT}/Z(T)$, where
$$Z(T) = \sum_{\text{Microstates}}e^{-U_i/kT}$$ is called the partition function of the system.  This set of possible microstates (along with this probability distribution) is called the canonical ensemble.

A: Multiplicity tells how many microstates have a macrostate. E.g. how many possible multiparticle configurations have a glass of 293K water on surface pressure. Entropy is the logarithm of multiplicity. (multiplied by k)


text:
Q: How to generate Charts in SubReport in ReportViewer C# I'm currently developing a WPF Application and I use ReportViewer that contains one chart but I need to display another chart in my report. I create a subreport and call it in my main report. But if I insert a chart in subreport doesn't works!
The Subreport1 could not be found at the specified location. Please verify that the subreport has been published and that the name is correct.
If I use a table or textbox it works but not if a charts.
This is my code Behind:
private void showReport(object sender, RoutedEventArgs e)
        {

            RVInfoGrafico.Reset();
            RVInfoGrafico.LocalReport.DataSources.Clear();
            RVInfoGrafico.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(MSubreportProcessingEventHandler);

            DataTable dt = GetData2();
            ReportDataSource rds = new ReportDataSource("DataSet1", dt);

            RVInfoGrafico.LocalReport.DataSources.Add(rds);
            RVInfoGrafico.LocalReport.ReportEmbeddedResource = "Project.Info.rdlc";
            RVInfoGrafico.ProcessingMode = ProcessingMode.Local;
            RVInfoGrafico.RefreshReport();

        }
        void MSubreportProcessingEventHandler(object sender, SubreportProcessingEventArgs e)
        {
            DataTable dt9 = GetData4();
            e.DataSources.Add(new ReportDataSource("DataSet1",dt9));
        }

A: The error states it can't find Subreport1. Maybe try providing it directly using LoadSubreportDefinition("Subreport1", xxx)?
Something like this:
var asm = Assembly.GetExecutingAssembly();
var stream = asm.GetManifestResourceStream("RVInfoGrafico.Reports.Subreport.rdlc"); // Change to your path or get a stream of it some other way
RVInfoGrafico.LocalReport.LoadSubreportDefinition("Subreport1", stream);

FYI - In a project I've done this in, the .rdlc files' Build Action in VisualStudio was set to "Embedded Resource".


text:
Q: application logs (Payara 4.1.1) don't show up when configuring cluster with 2 instances (locale + remote) I 've done a cluster with Payara Server composed by two instances, one is local ad resides onto a debian VM and the other one ,remote, resides also onto another debian VM. I deployed a test application and when I was looking to logs just wasn't able to find them. More precisely, I ment just one time almost randomly seem they appear and then nothing more. They show up into Admin Server-->View Logs File --> instance 1(local) -->log file --> server.log.
Below test application
package clusterTest;

import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class MySession implements Serializable {

    private String val;
    private static final Logger LOG = Logger.getLogger(MySession.class.getName());

    public String getVal() {
        LOG.log(Level.INFO, "getVal{0}", val);
        System.out.println("getVal");
        return val;
    }

    public void setVal(String val) {
        LOG.log(Level.INFO, "setVal{0}", val);
        System.out.println("setVal");
        this.val = val;
    }

}

image of the log file

A: Payara Server creates a separate directory for each instance, so that it does not mix with the working directory of the domain admin server.
In short, if your domain name is domain1, you should be able to find logs for your local instance in PAYARA_INSTALL/glassfish/nodes/localhost-domain1/instance1/logs/server.log.
Payara Server, as well as GlassFish, creates instances and places them under nodes. Nodes represent the location of the instances - in your case you most probably have a local node and a node for the second remote instance. Their configuration is part of the domain.xml, but before  instances are first started, Payara Server generates another separate directory with config and runtime data like logs, in a directory inside the glassfish/nodes directory, which is in the same directory as domains directory.
The files for remote instance should exist inside the remote Payara Server installation in a similar location.

A: As @nakag has already said here at https://stackoverflow.com/a/31783809/2946593, using the loopback address in /ect/hosts stop showing logs into cluster's instance.
So just comment out this row :
127.0.1.1      "name_of_server"
in each node of the cluster solved the problem.


text:
Q: Make hyperref expand section titles when \label is executed? MWE:
\documentclass{article}

\usepackage{hyperref}

\begin{document}

\newcommand*{\ordinal}{First}
\section{\ordinal{} Section}
\label{sec:first}

\renewcommand*{\ordinal}{Second}
\section{\ordinal{} Section}
\label{sec:second}

I want this to say ``First Section'': \nameref{sec:first}

\end{document}

I end up with \newlabel{sec:first}{{1}{1}{\ordinal {} Section}{section.1}{}} in the .aux file, whereas I wanted \ordinal{} to be expanded immediately when the \label command is executed.  Is there any sane way to make hyperref expand the section title when writing out the \newlabel command?


text:
Q: TSQL error in .Net but not in SSMS Having just built a c# application to run SQL scripts, I've run into a few issues with error handling.
We have a stored procedure in our database which modifies the default constraint for tables (by dropping any existing one and then creating the new one), and it runs fine when we call it from SSMS.  However, when we call the same stored procedure from the .Net SqlClient, it gives an error.  The error I get in the SqlException has the message:
System.Data.SqlClient.SqlException: Column already has a DEFAULT bound to it.
Could not create constraint. See previous errors.

This shouldn't happen, since we never see the message in SSMS unless we don't run the drop statement first.  If the Drop Constraint statement is commented out, we see the same message.
Why would the constraint not get dropped when we call the stored procedure from in .Net?
For reference, the relevant code inside the stored procedure is:
  SELECT @strSQL = 'ALTER TABLE [' + @strTableName + '] DROP CONSTRAINT  [' + @strConstraintName + ']'
  EXEC sp_executesql @strSQL

  SELECT @strSQL = 'ALTER TABLE [' + @strTableName + '] ADD CONSTRAINT DF_' + @strTableName + '_' + @strColumnName + ' DEFAULT (' + @strDefaultValue + ') FOR ' + @strColumnName
  EXEC sp_executesql @strSQL

EDIT: I considered trapping for errors, and ignoring non-fatal errors such as this.  However, unfortunately this specific error is a Level 16 error, and errors such as updating a non-existent table are only Level 15.  So I can't let this error pass by filtering on the Error Class of the exception.
EDIT 2: Should have mentioned, the @strConstraintName is determined automatically based on the table name and column name:
SELECT
        @strConstraintName = vdc.CONSTRAINT_NAME
  FROM
        dbo.vw_DEFAULT_CONSTRAINT vdc
  WHERE
        vdc.TABLE_NAME = @strTableName
        AND vdc.COLUMN_NAME = @strColumnName

Resolution
So, it turns out that the vw_DEFAULT_CONSTRAINT that was determining the name of the default constraint was badly written.
It was filtering based on the value of USER_ID() for some reason (the view was written before I started) which wasn't necessary. Removing this restriction from the view returned the correct constraint name.
@ErikE's answer provided a good push in the correct direction. Saving the variable values into a temporary table allowed me to see that the 2 methods weren't actually working the same, which led me to investigate the view further. Kudos to @ErikE for this, which is why I selected his as the correct answer.
I do find it strange though that the value of USER_ID() was not the same, since the connections were identical.

A: If running an SP-statement trace in SQL Profiler doesn't reveal a difference, can you log the @SQL variable contents being executed to a table and review them afterward? I'm really quite confused that they are truly identical.
Is it possible that the drop default constraint is failing due to a name problem? I think you answered this but it would be a plausible answer.
Did you know that dynamic SQL is executed with the permissions of the caller, not the SP owner, unless you take special measures (such as EXECUTE AS)? Could this be the issue?
Try commenting out the create default from the SP, running it from .Net, and seeing if the default was really dropped by the first statement. Or put a WAITFOR DELAY '5:00' in between them so you can check mid-run.

A: Try tu use SQL Server Profiler and compare the query from the ADO.NET to your query from the SSMS.

A: Try profiling the execution of the query and extracting the SET statements the SqlClient executes on connection. For example this is what I had profiled in the past when debugging performance differences of a query executed by the SqlClient versus running it in SSMS:
set quoted_identifier on
set arithabort off
set numeric_roundabort off
set ansi_warnings on
set ansi_padding on
set ansi_nulls on
set concat_null_yields_null on
set cursor_close_on_commit off
set implicit_transactions off
set language us_english
set dateformat mdy
set datefirst 7
set transaction isolation level read committed

Run these SET statements into SSMS and then try executing your query there again to see if you can replicate the behaviour. Whilst I don't believe this will surface your issue it is at least a good exercise to ensure your session configuration in SSMS is the same as if the query were being executed by the SqlClient