text:
Q: What is the basis of gauge theory? I'm learning about gauge concepts. I've always had the idea that by looking at a phenomenon from different viewpoints, that symmetries could be derived – in fact, that was what an equal sign signified.  In other words, the underlying phenomenon remained constant, only the viewpoints changed, and therefore could be equated.  But it seems that gauge theory is the opposite – identical observable quantities are seen, although the configurations of the underlying fields change. Is this right, or am I completely off-track?

A: You are basically right. A gauge theory is a field theory that leaves the equations of motion invariant under local (important distinction pointed out by @joshphysics) transformations of the coordinates. It gives physicists the ability to introduce arbitrary degrees of freedom to play with and simplify problems, as long as the physical quantities remain the same.
For example in Electrodynamics you can redefine the potential as long as the gradient stays the same. The electric field $E(r)$ (our physical quantity) is given by: $$E = -\nabla\phi$$
But $\phi$ can be transformed by adding a constant term $k$ which will give: $$\phi' \rightarrow \phi + k$$
Substituting this into the previous equation we get: $$E = -\nabla(\phi + k) = -\nabla \phi$$ which corresonds to the same physical quantity as above (in this case the electric field).
This is just an example. Another example, which probably makes the usefulness of this theory clearer, is the gravitational potential $V = mgh$. We can choose the origin to be anywhere since we are only interested in the potential energy difference, and this simplifies the calculations a lot (you don't have to care about the origin, only the distance between the points you are investigating).
In Quantum Field Theory, gauge transformations lead to conserved quantities via Noether's Theorem which says that for every continuous symmetry there exists a conserved quantity.
A group of independent gauge transformations gives rise to gauge fields. Each generator of the gauge group corresponds to a gauge field that describes gauge bosons.

A: Another take on gauge theories, to add to ACuriousMind's answer: as well as adding degrees of freedom which allow greater wriggle room to bring a broader class of solution techniques to bear, a gauge theory is a way for a theorist to encode experimentally observed symmetries into the a candidate theory. You might, for example, know from the experimental literature that a certain kind of interaction conserves some experimentally measured continuous quantities, let's call them "blooblehood", "twangleness" and "thargledom" to emphasise the idea's generalness (I fancy these were studied by the Thargoids under their leader theoretical physicist Gort). One way of making a candidate theory conserve blooblehood, twangleness and thargledom in its descriptions of the interaction is to make it a theory described by a Lagrangian and then to set that Lagrangian up so that it is invariant with respect to a Lie group $\mathfrak{G}$ of transformations on its co-ordinates. Noether's theorem then tells you that there will be one conserved quantity for each basis member of the Lie group's Lie algebra $\mathfrak{g}$. This Lie group is then the structure (gauge) group for the fibre bundle formed with $\Sigma$ as the base space (in ACuriousMind's notation and the "gauged" fields are the fibres, as in ACuriousMind's answer. So we postulate a Lagrangian that has a symmetry group of dimension 3 for $\mathfrak{G}$.
Other answers wherein I talk about similar things are here and here. The latter answer has what I hold to be excellent references for nonspecialists, and were how I began to feel I understand such things (albeit still fairly dimly).
Of course, this is not the only way things can be conserved, so conserved quantites don't prove the description has to be a gauge theory. It's just a suck and see kind of approach that makes an analogy with the first gauge theory (Maxwell's electrodynamics) and other kinds physical theories: you hope you can make some falsifiable foretelling with your Lagrangian so an experimentalist can see whether you're on the right track. What's good about a gauge theory is that conservation holds throughout smooth transformations that pass through a smooth path in spacetime, so we're not talking about jumping discontinuously from one point to one displaced a nonzero distance away and our theory stays "local": Richard Feynman talks about this nonuniqueness of a conservative theory when he derives Poynting's theorem in his second volume: see the beginning of Chapter 27 of Vol II
As an aside, a most interesting and highly unusual use for gauge theories is in the field of anholonomic control theory of dynamical systems. A most excellent framework for thinking about the way a falling cat flips over whilst conserving angular momentum is the following: The cat can be described by a manifold $\Sigma$ (to use ACuriousMind's notation) called the "space of cat shapes" and the cat can deform his or her shape to move smoothly between points of the manifold. These shapes are described in a co-ordinate frame that is fixed with respect to axes mounted on the tumbling (i.e. falling and rotating) cat. In the language of fibre bundles, the space of shapes is the base space $\Sigma$, the fibre is the space $SO(3)$ (or $SO(2)\cong U(1)$) of the cat's orientations in space. The bundle's topology is defined by the "parallel transport" notion or connexion one gets by computing the shift in cat orientation that arises, owing to the conservation of angular momentum, from the cat's following of a piecewise $C^1$ path through the space of shapes. The structure (gauge) group is some connected Lie subgroup of $SO(3)$ acting on the fibre $SO(3)$ itself.
I say more about the falling cat in my article:
"Of Cats and their Most Wonderful Righting Reflex" at my website Wet Savanna Animals.
Richard Montgomery's seminal work is:
Richard Montgomery, "Gauge Theory of the Falling Cat", in M.J. Enos, "Dynamics and Control of Mechanical Systems", American Mathematical Society, pp. 193–218, 1993
I wrote my article in the course of reading and understanding Montgomery's ideas. So you MAY find my article gentler, but different kinds of technical exposition work better for different mindsets.

A: PhotonicBoom has already provided a nice overview of the basic idea behind gauge theories, let me lay it on a bit thicker with the abstraction:
A gauge theory is a theory that has a local gauge symmetry induced by a gauge group $G$, which is required to be a Lie group. Now what do we mean by that?
Let $\Sigma$ be our spacetime (of arbitrary dimension and signature). Suppose we know that there should be some field $A_\mu : \Sigma \rightarrow \mathfrak{g}$ on $\Sigma$ ($\mathfrak{g}$ is the Lie algebra of $G$, you can think of the (vector) potential of classical electrodynamics (henceforth referred to as ED) for this. But, whenever we look, we can look only locally at this field, so we have some open sets $U_\alpha$ with $\alpha$ some index covering $\Sigma$, and on each of these $U_\alpha$, we have some $(A_\alpha)_\mu$ (e.g. as solution to the Maxwell equations). We get a global definition for the field if we require
$$ A_\alpha = g_{\alpha\beta}A_\beta g_{\alpha\beta}^{-1} + \mathrm{i}g_{\alpha\beta}\mathrm{d}g_{\alpha\beta}^{-1} \; \text{with} \; g_{\alpha\beta} : U_\alpha \cap U_\beta \rightarrow G \text{ a smooth function}$$
for all pairs of sets $U_\alpha,U_\beta$ that have non-zero intersection. This may look very strange, but consider the case of ED, where $G = \mathrm{U}(1)$: There, for $f : \mathbb{R}^4 \rightarrow \mathbb{R}$, we can write such functions as $g(x) = \mathrm{e}^{\mathrm{i}f(x)}$. Everything commutes, and the above formula reduces to
$$A_\alpha = A_\beta - \mathrm{d}f$$
which is precisely the gauge freedom we have in classical ED! So, in this sense, the ugly looking equation above is the generalization of the familiar case to general, non-abelian symmetry groups $G$. In fact, the above data (the sets $U_\alpha$ and the transition functions $g_{\alpha\beta}$) define what is called a $G$-principal bundle. Now, on this $G$-principal bundle, let's call it $P$, you can define the notion of a gauge transformation $g : P \rightarrow G$, and the transformation of $A$ under this will again be $A \mapsto gAg^{-1} + g\mathrm{d}g^{-1}$ (ignoring annoying factors of $\mathrm{i}$). What does this have to do with our intuitive idea of gauge? Well, $P$ locally looks like $U_\alpha \times G$, where letting a group element $h \in G$ act on a point $(x,k)$ just means $(x,k)h := (x,kh)$, and doing the gauge trafo is just $(x,k) \mapsto (x,kg(x,k))$. So all the trafo does is switching the group elements above a point $x \in \Sigma$ around, or, in other words, chooses a new point in what looks like $\{x\} \times G$ to be the group identity. This is (in a vague sense) the generalization of the freedom of setting the "zero" for some potential that PhotonicBoom talked about.
Now, having this weird symmetry going on is alright, but how do we get things that do not change under gauge transformation? Right now, $A$ is changing, the points in $P$ are switching around, isn't something supposed to be gauge invariant here?
Define the covariant derivative w.r.t. to the connection $A$ as
$$ \mathrm{d}_A f := \mathrm{d}f + A \wedge f$$
(every covariant derivative of a field transforming in a representation of $G$ will also transform in that representation, but I've already written a wall of text here, so I'll not go into matter fields, the buzzword is associated vector bundles) and define the curvature or field strength
$$ F := \mathrm{d}_A A = \mathrm{d}A + A \wedge A$$
It can now, by direct computation, be shown that $F$ transforms as $F \mapsto gFg^{-1}$. In ED, everything commutes, and you have already a gauge invariant quantity (since $gFg^{-1} = F$ there), which is good, since the field strength should, as a physical quantity , not change under gauge transformation! For general $G$, which can in all cases of interest be written as matrix groups, just take the trace. $\mathrm{tr}(gFg^{-1}) = \mathrm{tr}(F)$ is invariant, since the trace is invariant under cyclic permutations.
And, we're done! The action for this pure Yang-Mills theory is
$$ S[A] := \frac{1}{4e^2}\int_\Sigma \mathrm{Tr}(F \wedge \star F)$$
with $e$ some coupling constant. I'm not quite certain if that's refining your intuition as you may have hoped, but that's how it is (provided I've not made some major technical blunder somewhere, pointers of course appreciated).


text:
Q: Incompatible types in assignment. C This part of my code:
    char MAC_ADRESSES[MAX_LINES][100];
    for(j=i+1; j<=countlines; j++)
        {
            if((MAC_ADRESSES[j])==(MAC_ADRESSES[i]))
            {
                MAC_ADRESSES[j] = NULL;
            }

At the point where I want to change the string with a NULL I have a compiler error about incompatible types assignment. Do not understand why..

A: Presumably MAC_ADRESSES is not an array of pointers.  NULL is a pointer (normally (void *)0 in C), so you can't assign it to a non-pointer variable.
Edit:  Since your definition is char MAC_ADRESSES[MAX_LINES][100], you have a 2D array, not an array of pointers.  You can't store NULL in this array.  You can wipe out a string by putting a null character in the first byte, though:
            MAC_ADRESSES[j][0] = '\0';

Note that you can't test strings for equality using ==, either.  You should be using strcmp.

A: Instead of NULL use '\0'
NULL is macros defined as
#define NULL (void *)0
or
#define NULL 0 , hence the
warning: assignment makes integer from pointer without a cast
As per your edited question use:
MAC_ADRESSES[j][0] = '\0';

A: I think you need this
for(j=i+1; j<=countlines; j++)
    {
        if(strcmp(MAC_ADRESSES[j],MAC_ADRESSES[i]) == 0)
        {
            MAC_ADRESSES[j][0] = 0;
        }
    }

Given that
char MAC_ADRESSES[MAX_LINES][100]

As I guess you are trying to remove duplicates
BTW MAC_ADDRESS[j] is an array - not a pointer! Hence == operator will not make any sense

A: NULL is defined something like below
#define NULL (void*)0

So you can't assign void* type to char[][].(both are incompatible types)
If you want to invalidate use '\0' or 0;
MAC_ADRESSES[j][0] = '\0';

      (or)

MAC_ADRESSES[j][0] = 0;

(Note: Also you should use strcmp / stricmp / strcasecmp to compare the c string & == is not allowed on array bases)

A: if MAC_ADRESSES isn't a pointer array then MAC_ADRESSES[j] = NULL; is wrong because NULL is a pointer and MAC_ADRESSES is not

redpajama_set_name: RedPajamaStackExchange


text:
Q: "/" Get Removed from the URL When onclick Event I change current url of the webpage using window.history.replaceState() without refreshing the page. so that I can append to current url YouTube VideoID when ever user clicks on the video which are listed on this page and plays the same video in the same page.
Let us assume sample urls are -
Default Video page
http://www.domain.com/video/
After User clicks on video URL changes to removing the last /
http://www.domain.com/video#Se1y2R5QRKU
I want url to remain with /
http://www.domain.com/video/#wckLzQDTm6s
Here is the script I am using but I am not sure what is remove last / from the url
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var match = URL.match(regExp);
if (match && match[7].length == 11) {
    //console.log(match[7]);
    currentURL = document.URL;
    // alert(currentURL.slice(0, currentURL.lastIndexOf('#')));
    console.log(currentURL.slice(0, currentURL.indexOf('#')));
    var sliceURL = currentURL.slice(0, currentURL.indexOf('#'));
    var newURL = sliceURL + '#' + match[7];
    window.history.replaceState(null, "Video Gallery", newURL);
    return match[7];
} else {
    //alert("Could not extract video ID.");
}

A: Because your currentURL initially does not contain the #, the indexOf will return -1 and the result is that the last character (your slash) will be removed. You should explicitly check whether the hash is inside the currentURL before slicing it:
var hashIndex = currentURL.indexOf('#');
var sliceURL = (hashIndex != -1) ? currentURL.slice(0, hashIndex) : currentURL;


text:
Q: Auto Click on hyperlink I would like to a HTML code with the following functions if you guys can help , please.
Once the page loads, after 1 second to auto click on a hyperlinked text , how do I do this ? For the new website to be opened in the same window.
I have this code but this one is sending me to a new window and the pop up is blocking - not good
<!DOCTYPE html>

GOOGLE

Thanks

A: Instead of using  you should try just setting the variable window.location.href. So your code should look something like this:

https://www.w3schools.com/howto/howto_js_redirect_webpage.asp

A: Let me preface this by saying this is extremely questionable when it comes to web design, and generally regarded as a shady or bad practice. That said:
$(window).on('load', function(){
     window.location = 'http://example.com'
});
OR (vanilla JS)
window.onload = function(){ window.location = 'http://example.com' };
Again, be careful with this. If you want to do something like this, you need a pretty good reason why.
Possible duplicates:
Redirect from an HTML page
HTML redirect on page load


text:
Q: how to extract the contents of the array? I'm writing an application on flutter and I'm a bit stuck at the moment of extracting the contents of firebase classes. How do I extract the contents of the PhoneNumber variable from "user"? I will need the extracted number to send to the server
This is the output of the debugPrint('user: $user'):
user: FirebaseUser({uid: hGLEDW6OT5ZMhWra9L4p6bB4Pw92, isAnonymous: false, phoneNumber: +79644054946, providerData: [{uid: hGLEDW6OT5ZMhWra9L4p6bB4Pw92, phoneNumber: +79644054946, providerId: firebase}], providerId: firebase, creationTimestamp: 1557420327980, lastSignInTimestamp: 1558848790729, isEmailVerified: false}

void _signInWithPhoneNumber() async {
    final AuthCredential credential = PhoneAuthProvider.getCredential(
      verificationId: _verificationId,
      smsCode: _smsController.text,
    );
    final FirebaseUser user = await _auth.signInWithCredential(credential);
    final FirebaseUser currentUser = await _auth.currentUser();
    assert(user.uid == currentUser.uid);
    debugPrint('user: $user');
    setState(() {

      if (user != null) {

           Navigator.pushNamed(context, '/amenities');
      } else {
        _message = 'Вход не выполнен';
      }
    });
}

I need to extract PhoneNumber from "user" to send to server in Json

A: I'm pretty sure you can grab the phone number with just user.phoneNumber


text:
Q: Redshift: 500310 Invalid Operation I am using talend to insert data into a table on Amazon Redshift. The java code is producing by talend but today() function is not supported by Amazon Redshift.
I am trying to load a table from Salesforce and put it in Redshift using talend. When I am running the job from talend I have following error:
Exception in component tRedshiftOutput_1
java.sql.SQLException: [Amazon](500310) Invalid operation: function today() does not exist;
    at com.amazon.redshift.client.messages.inbound.ErrorResponse.toErrorException(ErrorResponse.java:1830)
    at com.amazon.redshift.client.PGMessagingContext.handleErrorResponse(PGMessagingContext.java:804)
    at com.amazon.redshift.client.PGMessagingContext.handleMessage(PGMessagingContext.java:642)
    at com.amazon.jdbc.communications.InboundMessagesPipeline.getNextMessageOfClass(InboundMessagesPipeline.java:312)
    at com.amazon.redshift.client.PGMessagingContext.doMoveToNextClass(PGMessagingContext.java:1062)
    at com.amazon.redshift.client.PGMessagingContext.getErrorResponse(PGMessagingContext.java:1030)
    at com.amazon.redshift.client.PGClient.handleErrorsScenario3(PGClient.java:2481)
    at com.amazon.redshift.client.PGClient.handleErrors(PGClient.java:2346)
    at com.amazon.redshift.client.PGClient.directExecute(PGClient.java:1098)
    at com.amazon.redshift.client.PGClient.directExecuteExtraMetadata(PGClient.java:1167)
[FATAL]: dw.create_invoice_0_1.create_invoice - tRedshiftOutput_1 [Amazon](500310) Invalid operation: function today() does not exist;
    at com.amazon.redshift.dataengine.PGQueryExecutor.execute(PGQueryExecutor.java:210)
    at com.amazon.jdbc.common.SStatement.executeNoParams(Unknown Source)
    at com.amazon.jdbc.common.SStatement.execute(Unknown Source)
    at dw.create_invoice_0_1.create_invoice.tSalesforceInput_1Process(create_invoice.java:4691)
    at dw.create_invoice_0_1.create_invoice.tSalesforceConnection_1Process(create_invoice.java:694)
    at dw.create_invoice_0_1.create_invoice.runJobInTOS(create_invoice.java:8761)
Caused by: com.amazon.support.exceptions.ErrorException: [Amazon](500310) Invalid operation: function today() does not exist

It seems that Amazon Redshift does not support today() function.
I  want to know how can I deal with that problem?

A: You can use the CURRENT_DATE function instead. You can find out more at the Redshift Date and Time functions documentation: https://docs.aws.amazon.com/redshift/latest/dg/Date_functions_header.html


text:
Q: GoogleTest and Memory Leaks I'm surprised that Google C++ Testing Framework does not explicitly support checking for memory leaks. There is, however, a workaround for Microsoft Visual C++, but what about Linux?
If memory management is crucial for me, is it better to use another C++ unit-testing framework?

A: If memory management is crucial for me, is it better to use another C++ unit-testing framework?
i don't know about c++ unit-testing, but i used Dr. memory, it works on linux windows and mac
if you have the symbols it even tells you in what line the memory leak happened! really usefull :Dmore info
http://drmemory.org/

A: Even if this thread is very old. I was searching for this lately.
I now came up with a simple solution (inspired by https://stackoverflow.com/a/19315100/8633816)
Just write the following header:
#include "gtest/gtest.h"
#include <crtdbg.h>

class MemoryLeakDetector {
public:
    MemoryLeakDetector() {
        _CrtMemCheckpoint(&memState_);
    }

    ~MemoryLeakDetector() {
        _CrtMemState stateNow, stateDiff;
        _CrtMemCheckpoint(&stateNow);
        int diffResult = _CrtMemDifference(&stateDiff, &memState_, &stateNow);
        if (diffResult)
            reportFailure(stateDiff.lSizes[1]);
    }
private:
    void reportFailure(unsigned int unfreedBytes) {
        FAIL() << "Memory leak of " << unfreedBytes << " byte(s) detected.";
    }
    _CrtMemState memState_;
};

Then just add a local MemoryLeakDetector to your Test:
TEST(TestCase, Test) {
    // Do memory leak detection for this test
    MemoryLeakDetector leakDetector;

    //Your test code
}

Example:
A test like:
TEST(MEMORY, FORCE_LEAK) {
    MemoryLeakDetector leakDetector;

    int* dummy = new int;
}

Produces the output:

I am sure there are better tools out there, but this is a very easy and simple solution.

A:
"I'm surprised that Google C++ Testing Framework does not explicitly support checking for memory leaks."

It's not (and never was) purposed to do so.
You can actually do some certifying, e.g. using google mock and setting up expected calls (for e.g. destructors). But using a tool specialized upon this aspect, will certainly do better, than everything you're able to write yourself.

"is it better to use another C++ unit-testing framework?"

So why bothering looking for different unit testing frameworks (that won't support such feature either, at least there's none I know of).
There are tools like valgrind you can use, and run your UnitTester executable under their control to detect memory leaks.
Note:
The above advice to do this with the UnitTester executable, won't be able to catch all of the possible memory leaks from the final executable produced with your code, but just help to find bugs/flaws with the actually tested code.

A: Not sure whether this worked in 2015, but since 2018 or so we use GoogleTest with CLang's sanitizers, including LeakSanitizer, AddressSanitizer and UndefinedBehavior sanitizer.
Just build tests with sanitizers enabled, example for the CMake-based project:
  add_compile_options(-fsanitize=leak,address,undefined -fno-omit-frame-pointer -fno-common -O1)
  link_libraries(-fsanitize=leak,address,undefined)

A: Memory leaks are a result of incorrect use of system interfaces, The unit test should check if those interfaces are being used correctly in your unit under test, not what the implementation specific results of any of those interfaces is. It should check that the memory allocation and deallocation interfaces used directly by your unit are being used as designed.  Testing the system specific results would be a part of component or integration testing.  In the unit test, the memory management interfaces are external to the unit under test and thus should be stubbed out with a test implementation.


text:
Q: Jquery create effect after load I have this function:
 $(".delete").live('click', function() {
  var commentContainer = $(this).parent();
        var id = $(this).attr("id");
        var string = 'id='+ id ;
    $.ajax({
       url: "<?php echo site_url('messages/delete') ?>",
       type: "POST",
       data: string,
       cache: false,
       success: function(){
          commentContainer.slideUp('600', function() {$(this).remove();
             $('.messages').fadeOut('2000', function(){$(this).remove();
                $('#messages').load("<?php echo site_url('messages/show') ?>", function(){
                    $(this).slideDown('2000');
                    deleteConfirmSetup(qst); // Add function call here
                });
            });
        });
    }
  });
  return false;
});

It is working up to a load. It is loading data, but there is no slideDown - data is suddenly presented. How to fix this?

A: You need to modify the following line in your code. Hide the element first the next method will apply the sliding effect and make it show as well.
    $('#messages').load("<?php echo site_url('messages/show') ?>", function(){
         $(this).hide().slideDown('2000'); //modify this
         deleteConfirmSetup(qst); // Add function call here
    });

A: This line:
$(this).slideDown('2000');
should possibly be commentContainer.slideDown('2000');
I'm simply guessing using your ID names though if you could possibly clarify?


text:
Q: How to run golang tests after automatic compile from dev_appserver I am running dev_appserver.py and so it auto builds as I save go files (I need to run this and not goapp because of log_level I need).
When there is a successful build I would like the tests for the project (goapp test) to run automatically. How can I do this?

A: You could use something like https://github.com/nf/watch in a separate terminal window. It'll re-run tests in parallel to dev_appserver.py.
Install: go get github.com/nf/watch
Run from your app's directory: watch goapp test

A: With AppEngine, I use the entr app like so:
$ find ./*.go | entr goapp test


text:
Q: My processor supports 64-bit hardware, but It is for Windows. How to understand If I can run 64-bit Ubuntu? I checked my processor and It supports 64-bit hardware as you can see down below.
Image
But Securable talks about Windows. I want to download Ubuntu. Can I still go for it?
Thanks much.

A: Press and hold the Windows Key and the Pause key.
In the System window, next to System type it lists 32-bit Operating System for a 32-bit version of Windows, and 64-bit Operating System if you're running the 64-bit version.
If you have a 64-bit then you should be able to install Ubuntu x64 version.


text:
Q: Error in calculating Timezone of Brasilia function(startDate, lastDate){

var midDate = newDate(startDate.getFullYear(),startDate.getMonth(),Math.ceil((lastDate.getDate() + startDate.getDate()) / 2));

var startDateOffset = startDate.getTimezoneOffset();
var lastDateOffset = lastDate.getTimezoneOffset();
var midDateOffset = midDate.getTimezoneOffset();

var finalDate = new Date();
if(startDateOffset == midDateOffset){

  if((lastDate.getDate() - midDate.getDate()) > 1){
    alert("loop");
  finalDate = this.getDaylightChangeDate(midDate, lastDate);
  }
 }

I am getting start date as 20 oct , end date as 22nd and mid date again as 20th oct . This is happening only for the location Brasilia , also startDateOffset & midDateOffset is 180 as output.. which is throwing the code in infinite loop as mid date is equal to start date always. Please suggest some other method in javascript to calculate the mid date

A: There is nothing wrong with your code. The mid date between 2012-10-20T00:00 and 2012-10-21T23:00 is 2012-10-20T23:30. Of course your code can't expect the dates to differ if the input dates are no more than 2 days apart. What would even happen if you passed in the same date as start and end?
If those dates were recorded in different time zones, you always should use UTC to calculate differences.


text:
Q: Networked macs, .app installer help Im pretty new to macs and i know no one who can figure this out, I have a folder which has an .app client in it and a .app installer in it and a bunch of other files. I use software called filewave to send that folder out to various macs i have here. I need to make something like a script i can run at startup or just once to run the installer .app in silent mode. Or would it be possible to package up the folder with all this in and make it into a .PKG installer? any thoughts anyone i'm new to all that is mac and sorry if things sounds like i'm talking about windows.

A: Apple's software installation is a bit of a deep subject.

*

*You could use a unix packaging system and script it with shell/bash/python/perl - whatever code base and language you prefer. Optionally ssh and AppleScript would allow you to automate running the code.

*You could use a developer account and Apple's tools to build a proper install image with receipts and code signing so that your app is allowed on Macs with GateKeeper

*You could use Homebrew (again a unix based tool) which has easy casks

*You could use AutoPkg - an excellent tool for exactly what you ask - networked framework for installing software.

Since there are so many products you could make and package for OS X, it's hard to pick just a best solution for you.

A: You could invest ($100US) in the app Composer from JAMF.

Creating packages that are tailored to end-user configurations enables
  IT administrators to save their organizations time and resources.
  Packages are standards-compatible and available for deployment with
  Apple Remote Desktop, the Casper Suite, or any other patch management
  system. Better yet, the software arrives pre-configured and ready for
  end users to get started immediately.

I used it a few years ago when managing ~ 120 Macs. Simply put, it watches your development Mac when you install software and creates a .PKG from all the new & modified files|folders which result. When the .PKG installer is run, the files|folders are installed in the correct places. I used Composer in conjunction with Apple Remote Desktop, which can push a .PKG onto a Mac and install it silently.
If you are dealing with more than a Handful of Macs, this may be a (not inexpensive) way to go.
Presently, the Mac admins where I work use opensource munki:

Munki is a set of tools that, used together with a webserver-based
  repository of packages and package metadata, can be used by OS X
  administrators to manage software installs (and in many cases
  removals) on OS X client machines.
Munki can install software packaged in the Apple package format, and
  also supports Adobe CS3/CS4/CS5/CS6 Enterprise Deployment "packages",
  and drag-and-drop disk images as installer sources.
Additionally, Munki can be configured to install Apple Software
  Updates, either from Apple's server, or yours.
Munki is currently in use at organizations all over the world,
  managing software for tens of thousands of Macs.


text:
Q: How to pass a parameter with *slashes* in the url? What I want to do is to pass the dates inside the parameter of a function, then process the input. Here's the function for it
@HR.route('/confirm_sickLeave/<date>/<user>', methods=['GET', 'POST'])
def confirm_sickLeave(user,date):
    u = User.query.filter_by(username=user.username).first()
    print u
    us = UserStatistics.filter_by(userId=u.id).first()
    temp = us.slDates
    dates = temp.keys()
    for a in dates:
        if a == date:
            temp['date'] = True
            flash('Date Confirmed.')
            return redirect(url_for('.approval_of_leaves'))

    return redirect(url_for('.approval_of_leaves'))

Now, my problem was I can't pass the values in my function. The reason was my input dates had slashes (/) in it. Let me show you:
HTML:
{% for u in all_users %}
## Returns all the dates applied by the user (it's in dict format)
{% set user_info = u.return_sickLeaves(u.username) %}
{% for us in user_info %}

             {{ u.username }}
             {{ us|e }}
        {% if us.value|e == True %}
        Confirmed
        {% else %}
        Pending..
        {% endif %}
        Confirm
            Deny

        {% endfor %}

{% endfor %}

Now, when I try to click confirm button, the response that I get is Error 404 not found. The url of the 404 error is: http://localhost:5000/confirm_sickLeave/02/01/2015%3B02/02/2015/seer
Is there any alternatives I can do? Thank you for you contribution. :)

A: Slashes carry meaning in a URL path, so the default converter for a path section explicitly excludes slashes.
You have two options:

*

*Explicitly match the separate parts of the date and re-constitute:
@HR.route('/confirm_sickLeave/<year>/<month>/<day>/<user>', methods=['GET', 'POST'])
def confirm_sickLeave(user, year, month, day):
    date = '/'.join([year, month, day])

*Format your dates to use a different separator, like a -.
You can match slashes in paths, with the path converter (so /confirm_sickLeave/<path:date>/<user>), but that means you now match an arbitrary number of slashes in the path, making validation harder.


text:
Q: How to reject and HTTP Posts based on content length without parsing the request stream in C#? Some third party is posting data to our webpage via HTTP Post. I want to set a limit say 1 Kb for HTTP posts, if it is above 1 Kb I need to reject the HTTP post. I don't want to read the whole request stream to find out the content length. Is there anyway I can validate without reading the entire request stream?

A: It depends whether the content length is in the headers or not. If it is, you can just fetch that (e.g. HttpRequest.ContentLength). However, they don't have to specify that.
Otherwise, you could just read the first 1K and 1 extra byte:
 byte[] data = new byte[1025];
 int length = 0;
 using (var stream =  request.GetBufferlessInputSream())
 {
     while (length < validData.Length)
     {
         int bytesRead = stream.Read(data, length, data.Length - length);
         if (bytesRead == 0)
         {
             break;
         }
         length += bytesRead;
     }
 }
 if (length > 1024)
 {
     // Client sent more than 1024 bytes of data!
 }
 // Otherwise, use the first "length" bytes of data

Note that data has a size of 1025 so that we try to read one more byte than we're allowing the client to send.
If the client has sent more than 1K, we'll still read the first 1K - but we'll only read a single unnecessary byte. We won't keep reading forever.


text:
Q: In-App Purchase: "Restore Purchases" button on user-bound purchase I'm currently implementing In-App Purchases in my Swift app. The product is a non-consumable one which activates a kind of Premium version for the user. Usually, with non-consumable purchases, you have to put a "Restore Purchases" button in your app (mandatory). However, my problem with this is: The app, and therefore the purchase, is user-bound. So every user of the app has to register an account with us. As soon as an user purchases the IAP, the user account gets flagged as Premium internally on our server. Once he logs out and logs into another account for example, the purchase gets "deactivated" as during the login process the app gets info from the server whether the user is Premium or not.
So basically, if I'd put a "Restore Purchase" button in my app it would either be kind of useless as the purchase gets activated anyways as soon as the user logs in, or the button would make it possible for someone to purchase the Premium version once and then activate it on an unlimited number of other accounts, too, simply by logging into them and "restoring purchases".
So, question is: Is this button mandatory in my case? I've seen other apps, especially subscription-based ones do this, too.

A: If you don't implement restore button for your in-app purchase implementation, Apple will reject your app.
Their idea is if any iTunes user has paid for some content, he should be able to access the content on any device.
How you are using the receipt and allowing the user that's up to you.


text:
Q: How to mock Firebase auth providers such as FacebookAuthProvider? I am trying to mock react-native-firebase's firebase.auth object so that it will return a credential to the code under test so that I can test my method.
I have the following code under test:
public async FacebookSignIn(): Promise<void> {
    try {
      const result = await LoginManager.logInWithReadPermissions(['public_profile', 'email']);

      if (result.isCancelled) {
        throw new Error('User cancelled request');

      }

      const data = await AccessToken.getCurrentAccessToken();

      if (!data) {
        throw new Error('Something went wrong obtaining the users access token');
      }

      const credential = firebase.auth.FacebookAuthProvider.credential(data.accessToken);
      await firebase.auth().signInWithCredential(credential);
    }
    catch (error) {
      console.error(error);
    }
  }

I want to ensure that at the end of the function, my CUT calls signInWithCredential so I have a test case like so; func is a global :
jest.fn()
describe('FacebookSignIn', () => {
    it('should sign in user with facebook credentials', async () => {
      await service.FacebookSignIn();
      expect(func).toHaveBeenCalled();
    })
  })

However with the following mock I get the error TypeError: Cannot read property 'credential' of undefined:
jest.mock('react-native-firebase', () => {
  return {
    auth: () => {
      return {
        currentUser: null,
        signOut: func,
        signInAnonymously: func,
        signInWithEmailAndPassword: func,
        signInWithCredential: func,
        FacebookAuthProvider: jest.fn(() => {
          return {
            credential: jest.fn(() => {
              return {
                provider: 'dummy',
                token: '1234',
                secret: '5678'
              }
            })
          }
        })
      }
    }
  }
});

I've looked at the type for firebase.auth and it can return this:
type AuthModule = {
    (): RNFirebase.auth.Auth;
    nativeModuleExists: boolean;
} & RNFirebase.auth.AuthStatics

which to me looks like it is mocking the signIn methods correctly, but the AuthStatics methods aren't being mocked. AuthStatics is defined as follows:
interface AuthStatics {
        EmailAuthProvider: EmailAuthProvider;
        PhoneAuthProvider: AuthProvider;
        GoogleAuthProvider: AuthProvider;
        GithubAuthProvider: AuthProvider;
        OAuthProvider: AuthProvider;
        TwitterAuthProvider: AuthProvider;
        FacebookAuthProvider: AuthProvider;
        PhoneAuthState: {
          CODE_SENT: string;
          AUTO_VERIFY_TIMEOUT: string;
          AUTO_VERIFIED: string;
          ERROR: string;
        };
      }

How can I mock the FacebookAuthProvider property and avoid it being undefined for credential?

A: Although your question is a bit older, I stumbled across the same challenge and I could solve it like so:
Create default mock of the auth module in your project root
// file: __mocks__/@react-native-firebase/auth/index.js

const auth = jest.fn().mockReturnValue({
  onUserChanged: jest.fn().mockReturnValue(() => {}),
  createUserWithEmailAndPassword: jest.fn(),
  signInWithCredential: jest.fn(),
  // more functions from the module you want to use in your tests
});

auth.FacebookAuthProvider = {
  credential: jest.fn(),
};

export default auth;

Then, in your test file
describe('auth', () => {
  let authMock: jest.Mocked<ReturnType<typeof firebaseAuth>>;
  let facebookAuthProviderMock: jest.Mocked<FirebaseAuthTypes.AuthProvider>;

  beforeEach(() => {
    authMock = firebaseAuth() as jest.Mocked<ReturnType<typeof firebaseAuth>>;
    facebookAuthProviderMock = firebaseAuth.FaceAuthProviderMock as jest.Mocked<FirebaseAuthTypes.AuthProvider>;
  });

  it('your test', () => {
  // given
    authMock.signInWithCredential.mockResolvedValue({});
    facebookAuthProviderMock.credential.mockReturnValue({});

  // ...

  // then
  expect(authMock.signInWithCredential).toHaveBeenCalledWith({});
  })
})


text:
Q: How to detect circle and area of that circle in python?
*

*I need help developing a circle detection algorithm. Does anyone know any algorithms that can be implemented in python and open cv? I'm having trouble getting this done

*https://i.stack.imgur.com/zo1zl.jpg


text:
Q: rsync --delete option not deleting in destination if deleted in source i r-synced my itunes folder to my external USB hard drive (obviously no rsync server on the usb drive)
went perfect, however if i delete folder/file in source than perform rsync it does NOT delete from destination, if i add a folder/file it gets added to destination (as expected)
it must notice the deletion because in "stats" it will say 5348 files to be considered then i delete 1 and it says 5347 files to be considered...but does not delete on destination!
i have tried several diff paths configurations, and even diff delete options...but i cannot get to to delete
here is my script
rsync -avhP --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r --delete --stats --exclude-from '/Users/iTunes/backup/exclude.txt' /Users/iTunes/Desktop/ /Volumes/itunes_BACK/
please advise
thanks
jeoe

A: See if there are any I/O errors listed in the output. (Maybe you will want to redirect the output to a file so you can grep through it for errors). I know that as a safety feature, rsync disables the deleting after it is finished if there were any I/O errors.
It would be helpful to see the output of running the command, but I understand if you feel you can't post that...


text:
Q: Unable to see X-Ray traces from AWS Batch job I am running a batch job that starts an EC2 instance and runs a Java application, and I am trying to generate X-Ray trace for the job. I am unable to see any traces after the job is completed.
In my docker entrypoint I install X-Ray daemon and start it
curl https://s3.us-west-2.amazonaws.com/aws-xray-assets.us-west-2/xray-daemon/aws-xray-daemon-3.x.rpm -o /tmp/xray.rpm
yum install -v -y /tmp/xray.rpm
xray -o -n us-west-2 &

My Java code is instrumented as such
try {
    Segment segment = AWSXRay.beginSegment("load-data-segment");
    logger.info("Segment started traceID={}, segment", segment.getTraceId(), segment.prettySerialize());
    Subsegment subSegment = AWSXRay.beginSubsegment("load-data-sub-segment");
    logger.info("started subSegment traceId={}, {}", subSegment.getTraceId(), subSegment.prettySerialize());
    subSegment.putAnnotation("job_id", "load-data-job");
    ...
} finally {
    logger.info("Ending subsegment {}, {}", subSegment.getTraceId(), subSegment.prettySerialize());
    AWSXRay.endSubsegment();
    logger.info("Ending segment {}, {}", segment.getTraceId(), segment.prettySerialize());
    AWSXRay.endSegment();
}

And I can see from CloudWatch log that the daemon is installed and started, and the segments are created and eventually terminated normally.
...
EVENTS  1667282262329   Running X-Ray: xray -o -n us-west-2 &   1667282258652
EVENTS  1667282262329   Getting Secret: dev-shared-kc-local.yml 1667282258654
EVENTS  1667282262329   2022-11-01T05:57:38Z [Info] Initializing AWS X-Ray daemon 3.3.5 1667282258658
EVENTS  1667282262329   2022-11-01T05:57:38Z [Info] Using buffer memory limit of 321 MB 1667282258658
EVENTS  1667282262329   2022-11-01T05:57:38Z [Info] 5136 segment buffers allocated  1667282258658
EVENTS  1667282262329   2022-11-01T05:57:38Z [Info] Using region: us-west-2 1667282258679
EVENTS  1667282262329   2022-11-01T05:57:38Z [Info] HTTP Proxy server using X-Ray Endpoint : https://xray.us-west-2.amazonaws.com   1667282258679
EVENTS  1667282262329   2022-11-01T05:57:38Z [Info] Starting proxy http server on 127.0.0.1:2000    1667282258679
...
VENTS  1667282262329   2022-11-01 05:57:41,933 [main] [default] INFO  - Segment started traceID=1-6360b555-5161dc6ff45fcca197606de8, segment   1667282261934
EVENTS  1667282262329   2022-11-01 05:57:41,941 [main] [default] INFO  - started subSegment traceId=null, { 1667282261941
EVENTS  1667282262329     "name" : "load-data-sub-segment", 1667282261941
EVENTS  1667282262329     "id" : "348f5fd5734d2002",    1667282261941
EVENTS  1667282262329     "start_time" : 1.667282261934E9,  1667282261941
EVENTS  1667282262329     "in_progress" : true  1667282261941
EVENTS  1667282262329   }   1667282261941
...
...
EVENTS  1667282596467   2022-11-01 06:03:16,334 [main] [default] INFO  - Ending subsegment null, {  1667282596334
...
EVENTS  1667282596467   2022-11-01 06:03:16,336 [main] [default] INFO  - Ending segment 1-6360b555-5161dc6ff45fcca197606de8

However I am completely unable to find any tracing from X-Ray console. I use the queries like annotation.job_id, but nothing shows up. I think I have all the necessary polices added to my role (AWSXRayDaemonWriteAccess), but I am suspecting if I didn't set it up properly. Where and how can I start debugging this? I feel like completely at wits' end. Thank you for any suggestions!


text:
Q: Why is my session still alive I am using spring with redis backed sessions.
If I access the site, I see that sessions is added to database.
Then I run flushdb on the database.
Then I try and access the site, and sessions is still alive (I have the same session id.)  The redis keys are different, but the session id's are the same.
Is the session being stored somewhere else not in redis?  Is this expected?
Using windows 64 bit redis 2.8.2400.
some pom dependencies.
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
        <version>1.6.2.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
        <version>2.2</version>
    </dependency>

    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.8.0</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-data-redis</artifactId>
        <version>1.0.2.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>4.0.3.RELEASE</version>
    </dependency>
 <!--  -->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>4.0.3.RELEASE</version>
    </dependency>

Relavent Beans
<beans:bean id="RedisHttpSessionConfiguration"
    class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration" />
<beans:bean
    class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
    p:port="6379" />

some web.xml
<listener>
        <listener-class>com.mysite.listeners.sessionStarted</listener-class>
    </listener>

<filter>
        <filter-name>springSessionRepositoryFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSessionRepositoryFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Controller function for closing session
RequestMapping(value = "/closeSession", method = RequestMethod.GET)
    public String closeSession(HttpSession session, HttpServletRequest request) {
        logger.info("Closeing Session (greri002 for testing).");
        session.invalidate();
        //request.logout();
        SecurityContextHolder.getContext().setAuthentication(null);
        return "OK";
    }

A: Spring security is managing your sessions storing the data in redis.  You only need to bring in something like redis if you're planning on being able to share session data between nodes.
Spring's SecurityContext where security info in stored.
https://docs.spring.io/spring-security/site/docs/current/apidocs/org/springframework/security/core/context/SecurityContext.html
Assuming you're using a server that supports 3.0 Servlets you just need to call logout() on a HttpServletRequest object.  A spring MVC sample -
@RequestMapping(value="/me/logout", method=RequestMethod.GET)
public @ResponseBody String logout(HttpServletRequest request) throws ServletException {
    request.logout();
    return "OK";
}

http://docs.spring.io/spring-security/site/docs/3.2.1.CI-SNAPSHOT/reference/htmlsingle/#servletapi-logout
If you don't have access to HttpServletRequest you can do
SecurityContextHolder.getContext().setAuthentication(null);

Also make sure you have logout for the http config config'ed correctly.  he's mine
    <sec:logout logout-url="/logout"
                delete-cookies="JSESSIONID,jsessionid"
                invalidate-session="true"
                success-handler-ref="myLogoutFilter"/>


text:
Q: Objects are not valid as a React child when trying to pass a PDF document to backend using Express API in reactJS I am trying to pass a rendered PDF document in my website to the backend in order for me to save it locally in a folder in my backend project directory.
but when I do so I get this error Objects are not valid as a React child in my backend server logs.
I am unsure how to achieve what I require. I need to save the generated PDF file in my website to my backend server in the project directory.
here is my code:
Frontend:
const downloadPDF = () => {
    Axios.post("http://localhost:3001/api/pdf", {
        PDF: <MyDocument/>
    }).then((res) => {
        alert(res)
        console.log(res);
    })
}

// Create Document Component

  const MyDocument = () => (
    <Document>
      <Page size="A4" orientation="landscape" style={styles.page}>
          <View style={styles.sectionHead}>
              <Image style={styles.image} src={logo}/>
              <Text style={styles.freightCode}>{freightType}</Text>
              <View style={styles.headDate}>
              </View>
          </View>

          {/*The body section of the pdf*/}
          <View style={styles.sectionInfo}>
              <View style={styles.sectionInfo1}>
              <Text style={styles.sectionInfoHeader}>COLLECTION:</Text>
              <Text style={styles.sectionInfoText}>{collname}</Text>
              <Text style={styles.sectionInfoText}>{collcompany}</Text>
              <Text style={styles.sectionInfoText}>{colladdress}</Text>
              <Text style={styles.sectionInfoText}>{collphone}</Text>
              <Text style={styles.sectionInfoText}>{collemail}</Text>
              </View>
              <View style={styles.sectionInfo2}>
              <Text style={styles.countryBlock}>{collcountry}</Text>
              <Text style={styles.locationBlock}>{collcity}</Text>
              </View>
          </View>
          {/*The body section of the pdf*/}
          <View style={styles.sectionCodeLocation}>
          <Text style={styles.collDelCode}>{collcountrycode} - {freightType} - {delcountrycode}</Text>
          </View>
          <View style={styles.sectionInfo}>
              <View style={styles.sectionInfo1}>
              <Text>DELIVERY:</Text>
              <Text style={styles.sectionInfoText}>{delname}</Text>
              <Text style={styles.sectionInfoText}>{delcompany}</Text>
              <Text style={styles.sectionInfoText}>{deladdress}</Text>
              <Text style={styles.sectionInfoText}>{delphone}</Text>
              <Text style={styles.sectionInfoText}>{delemail}</Text>
              </View>
              <View style={styles.sectionInfo2}>
              <Text style={styles.countryBlock}>{delcountry}</Text>
              <Text style={styles.locationBlock}>{delcity}</Text>

              </View>
          </View>
          {/*The product section of the pdf*/}
          <View style={styles.sectionDetail}>
              <View style={styles.sectionInfo1}>
              <Text style={styles.weightCode}>Weight: {rangeval}</Text>
              <Text style={styles.weightCode}>Content: {shipContent}</Text>
              </View>
              <View style={styles.sectionInfo2}>
              <Text style={styles.weightCode}>Pieces: {pieces}</Text>
              <Text style={styles.weightCode}>Value: {shipValue} BHD</Text>
              </View>
          </View>
          {/*The product section of the pdf*/}

          <View style={styles.sectionAWB}>
              <Image style={styles.barcode} src={barcode}/>
          </View>
          <View style={styles.sectionFooter}>
          <Text>*Frieght WAYBILL*</Text>
          <Text></Text>
          </View>
          {/*The product section of the pdf*
          <View style={styles.sectionDetail}>
          <Text>*Freight DOC*</Text>
          <Text>2021-08-15</Text>
          </View>*/}
      </Page>
    </Document>
  );

   <button className={'mt-2 btn-orange btn-orange-md getRateBtn rounded'} onClick={downloadPDF} name="pdf">Complete</button>

backend:
//Save PDF API
app.post("/api/pdf", (req, res) => {
    const pdf = req.body.PDF
    ReactPDF.render(pdf, `${__dirname}/example.pdf`);
});

what am I doing wrong?

A: One or more of the text tags contain objects as opposed to strings or floats which they should contain. So check all the ... in <Text>{...}</Text> to find the object which is not valid between html tags (react child).


text:
Q: How to run imwheel at startup/login to allow scrolling while moving the mouse Tl;dr:
Moving the mouse while rotating the scroll wheel prevents the scrolling from actually happening in most applications. imwheel helps, but how do I run it on startup or login so that it actually works?
In detail:
I have a Windows 10 host and an Ubuntu 20.04 guest. The guest was originally installed in VMware, but I exported it (via an OVF) to VirtualBox too, for testing. In VMware Player I am using the "not optimized for gaming" mouse setting.
I have two physical mouses attached. One is the normal mouse that controls the host OS ("Host-Mouse"). The other is passed through to the guest OS ("Guest-Mouse"). The following table shows the combinations of movement and wheeling of both mouses and what the guest OS is doing:

Red means it doesn't work and it's a problem, orange means it doesn't work but it's acceptable (for me).
The problem does not occur in FireFox (so far it's the only exception I found), but in "Text Editor", "Settings", "Files" and - most problematic for me - "Qt Creator" the cursor moves but the window is not scrolled.
I found imwheel, which fixes the problem, but I cannot figure out the arcane rituals necessary to run it at startup or login such that it actually works.
Why is this so long?:
This was gonna be about the mouse wheel problem itself, but right at the end I found imwheel. I already wasted hours testing and writing all of this down, so while I cut it down, I don't want to let it all go to waste.
What I tried:
I've seen others with the same problem and no (good/applicable) solution:
https://communities.vmware.com/t5/VMware-Workstation-Pro/Mouse-scrolling-in-VM-guest-doesn-t-work-when-mouse-is-moving/td-p/2731610
Added those settings, no change.
https://communities.vmware.com/t5/Horizon-Desktops-and-Apps/Mouse-wheel-does-not-work/td-p/2835340
Was already on, disabled and re-enabled it, no change.
https://askubuntu.com/questions/1080542/mouse-scroll-doesnt-work-while-moving-pointer-on-vmware-workstation-with-ubuntu
Tried EN-US keyboard layout, no change.
Tried the commands suggested by Arwez, no change.
https://unix.stackexchange.com/questions/446314/scrolling-impossible-while-moving-mouse-fedora-28-vm-guest-on-win10/498564#498564
Tried xev | grep -n -e "ButtonPress" -e "ButtonRelease", I see activity from the mouse wheel while moving.
xinput showed "Virtual core XTEST pointer" (ID 4) and "Logitech M325" (ID 12) for both VMware and VirtualBox, and then some other slave pointers that differ between the two. I tried disabling each one individually with e.g. xinput disable 4:
Disabling "Virtual core XTEST pointer" errors out with "BadAccess".
In all other cases something was not working, but it never worked in the intended way.
Workaround:
scroll wheel not working when mouse is moving
Using "optimized for games" mouse in VMware and disabling mouse-integration in VirtualBox works, but it's not a great solution since that makes switching between guest and host extremely annoying.
VMware:

VirtualBox:

imwheel:
Taken from this answer: Inconsistent and erratic mouse wheel in Linux while moving the mouse pointer
Running imwheel while already in a console, either as root or as a normal user, fixes the issue.
But none of the ways I tried to have it run automatically work:
init.d:
I considered adding a file to /etc/init.d that simply runs imwheel, but I could not find a sensible explanation of how to create such a file or what the contents that I found in existing files mean (particularly parts of the comment header).
systemd:
Taken from this tutorial: https://linuxconfig.org/how-to-run-script-on-startup-on-ubuntu-20-04-focal-fossa-server-desktop
I created the file /etc/systemd/system/imwheel.service with the following content:
[Unit]
After=display-manager.service
[Service]
ExecStart=/usr/bin/imwheel > /home/user/Desktop/imwheel.txt 2>&1
[Install]
WantedBy=default.target

And ran these commands and rebooted:
chmod 664 /etc/systemd/system/imwheel.service
systemctl daemon-reload
systemctl enable imwheel.service

The imwheel.txt file was not created.
crontab -e:
I added these two lines to crontab and rebooted:
@reboot /usr/bin/imwheel > /home/user/Desktop/imwheel.txt 2>&1
@reboot echo "a" > /home/user/Desktop/echo.txt

The two files are created, echo.txt contains "a", but imwheel.txt contains the following:
INFO: imwheel started (pid=741)
Could not open display, check shell DISPLAY variable, and export or setenv it!

This happens with both root and the normal user.
Startup Applications:
Taken from this answer: https://askubuntu.com/questions/101197/how-can-i-make-an-application-start-up-when-i-login/101200#101200
I hit the windows key, searched for "startup applications", clicked on the only result, added a new entry with the command /usr/bin/imwheel > /home/user/Desktop/imwheel.txt 2>&1.
The imwheel.txt file was not created.

A: Ok, this is actually not as easy as it should be. Creating a systemctl user unit is the right approach but you will need to find the right dependencies to wait for - imwheel will work only if the X display and session are ready. Here's the imwheel.service definition I am using in Manjaro 5.15 + KDE that works reliably to start imwheel once I log into my session:
[Unit]
Description=IMWheel
After=plasma-kwin_x11.service
PartOf=graphical-session.target
[Service]
Type=simple
Environment=XAUTHORITY=%h/.Xauthority
Environment=DISPLAY=:0
ExecStart=/usr/bin/imwheel -kill -d
ExecStop=/usr/bin/pkill imwheel
RemainAfterExit=yes
Restart=on-failure
Slice=session.slice
[Install]
WantedBy=graphical-session.target

In order to customize this script to your environment, run systemctl --user status and identify your window manager or something similar, look up its definition file which likely will be in /usr/lib/systemd/user and adapt the service definition above. Will most likely require you to change After=, Slice=, PartOf= and WantedBy= based on your environment.


text:
Q: Set a single error message for a Email field in Zend I am facing an small issue regarding the Email Validation in my Zend Form.
My Code for the Email field is as
$emailId = new Zend_Form_Element_Text('email');
$emailId->setLabel("Email Adresse")
         ->addFilter('StripTags')
         ->addFilter('StringTrim')
         ->addValidator(new Validator_EmailValidator())
         ->addValidator('NotEmpty')
         ->addValidator(
                        'NotEmpty',
                        TRUE,
                        array('messages' => array(
                              'isEmpty' => 'Please enter your email id.'
                              )
                           )
                        );

Currently it is showing the Email Error Messages as :

What I want is to set a single error message in the place of all these errors and that is as :
"'abcd@shdsjah' is not a valid Email Id."
Since I am new to the Zend Framework, I don't have much idea about it, although I tried some code but they are useless.
Please help.....
Thanks In Advance....

A: When I was new to zend-framework, I faced this problem and got solution by using setErrors() method as:
//this will immediately call the method markAsError() which will show the error always
$emailId->setErrors(array('Please enter a valid Email Id.'));

You can also try :
//this will clearErrorMessages() and after that set the error messages
$emailId->setErrorMessages(array("Please enter a valid Email Id."));

Write this code after your code.
I hope it will be helpful to you......

A: Pass true as second argument of addValidator (breakChainOnFailure). The validation will stop at the first failure and you will have only have one error message.

A: I see that you are passing your own Custom Validator.
->addValidator(new Validator_EmailValidator())

You don't need to do that. Just use :
 $validator =  new Zend_Validate_EmailAddress()

Then just set that validator on the form item, and then set the messages against that validator.
So
 $emailId->setValidator( $validator );

Now just set the Messages against the Validator, using the setMessages method.
These are all of the potential messages that you can change:
    const INVALID            = 'emailAddressInvalid';
    const INVALID_FORMAT     = 'emailAddressInvalidFormat';
    const INVALID_HOSTNAME   = 'emailAddressInvalidHostname';
    const INVALID_MX_RECORD  = 'emailAddressInvalidMxRecord';
    const INVALID_SEGMENT    = 'emailAddressInvalidSegment';
    const DOT_ATOM           = 'emailAddressDotAtom';
    const QUOTED_STRING      = 'emailAddressQuotedString';
    const INVALID_LOCAL_PART = 'emailAddressInvalidLocalPart';
    const LENGTH_EXCEEDED    = 'emailAddressLengthExceeded';

Message Defaults
protected $_messageTemplates = array(
        self::INVALID            => "Invalid type given. String expected",
        self::INVALID_FORMAT     => "'%value%' is no valid email address in the basic format local-part@hostname",
        self::INVALID_HOSTNAME   => "'%hostname%' is no valid hostname for email address '%value%'",
        self::INVALID_MX_RECORD  => "'%hostname%' does not appear to have a valid MX record for the email address '%value%'",
        self::INVALID_SEGMENT    => "'%hostname%' is not in a routable network segment. The email address '%value%' should not be resolved from public network",
        self::DOT_ATOM           => "'%localPart%' can not be matched against dot-atom format",
        self::QUOTED_STRING      => "'%localPart%' can not be matched against quoted-string format",
        self::INVALID_LOCAL_PART => "'%localPart%' is no valid local part for email address '%value%'",
        self::LENGTH_EXCEEDED    => "'%value%' exceeds the allowed length",
    );

Now just change the messages to whatever you want. You will need to update every message.
 $validator->setMessages(array(
    Zend_Validate_EmailAddress::INVALID            => "Invalid type given, value should be a string",
    Zend_Validate_EmailAddress::INVALID_FORMAT     => "'%value%' is no valid email address in the basic format local-part@hostname",
    Zend_Validate_EmailAddress::INVALID_HOSTNAME   => "'%hostname%' is no valid hostname for email address '%value%'",
    Zend_Validate_EmailAddress::INVALID_MX_RECORD  => "'%hostname%' does not appear to have a valid MX record for the email address '%value%'",
    Zend_Validate_EmailAddress::INVALID_SEGMENT    => "'%hostname%' is not in a routable network segment. The email address '%value%' should not be resolved from public network.",
    Zend_Validate_EmailAddress::DOT_ATOM           => "'%localPart%' can not be matched against dot-atom format",
    Zend_Validate_EmailAddress::QUOTED_STRING      => "'%localPart%' can not be matched against quoted-string format",
    Zend_Validate_EmailAddress::INVALID_LOCAL_PART => "'%localPart%' is no valid local part for email address '%value%'",
    Zend_Validate_EmailAddress::LENGTH_EXCEEDED    => "'%value%' exceeds the allowed length",
  ));


text:
Q: Quantization Aware Training for Tensorflow Keras model I want to quantization-aware train with my keras model. I have tried like below. I'm using tensorflow 1.14.0
train_graph = tf.Graph()
train_sess = tf.compat.v1.Session(graph=train_graph)
tf.compat.v1.keras.backend.set_session(train_sess)

with train_graph.as_default():
    tf.keras.backend.set_learning_phase(1)
    model = my_keras_model()

    tf.contrib.quantize.create_training_graph(input_graph = train_graph, quant_delay=5)
    train_sess.run(tf.global_variables_initializer())

    model.compile(...)
    model.fit_generator(...)

    saver = tf.compat.v1.train.Saver()
    saver.save(train_sess, checkpoint_path)

It works without errors.
However, size of saved model(h5 and ckpt) is completely same as the model without quantization.
Is it the right way? How I can check whether it is quantized well?
Or, is there better way to quantize?

A: When you finish the quantization-aware-training and save your model to disk, it is actually not already quantized. In other words, it is "prepared" for quantization, but the weights are still float32. You have to further convert your model to TFLite for it to actually be quantized.  You can do so with the following piece of code:
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]

quantized_tflite_model = converter.convert()

This will quantize your model with int8 weights and uint8 activations.
Have a look at the official example for further reference.


text:
Q: Python ArangoDB I'm not able anymore to change my database on arangodb.
If I try to create a collection I get the error:

Collection error: cannot create collection: invalid database directory

If I try to delete a collection I get the error:

Couldn't delete collection.

Besides that some of the collections are now corrupted.
I've been working with this db for 2 months and I'm only getting these errors now.
Thanks.

A: If anyone gets the same error anytime in life, it was just a temporary error due to server overload.


text:
Q: How to simulate desktop click at (x,y) position with python? I'm trying to click somewhere on the desktop, I'm using python with win32 api, I'm using python 32 bit but my computer is a 64 bit computer. I believe the lParam variable isn't holding the value I'm expecting, and I'm still a bit confused about this variable itself, lets say I import it from wintypes can anyone tell me how to use it? Why does my function below not work?
I have a function as following, this doesn't seem to work:
def clickDesktop(x=0, y=0):

    # Get handle to desktop window
    desktop = win32gui.GetDesktopWindow()

    # Create variable lParam that contains the x-coordinate in  the low-order word while
    # the high-order word contains the y coordinate.
    lParam = y << 16 | x

    # Click at x, y in the desktop window
    win32gui.PostMessage(desktop, win32con.WM_LBUTTONDOWN, MK_LBUTTON, lParam)
    win32gui.PostMessage(desktop, win32con.WM_LBUTTONUP, 0, lParam)

A: The following code works with Python33 on Windows 7.
I used ctypes.
The LPARAM parameter for WM_LBUTTONDBLCLK combines x and y in a single 32 bits value.
When I run that code, it opens the "My Computer" Icon, located at the upper left corner of my Desktop (my TaskBar is also on the left, hence the high value of 110 for x).
from ctypes import windll

WM_LBUTTONDBLCLK = 0x0203
MK_LBUTTON = 0x0001

if __name__=='__main__':
    hProgman = windll.User32.FindWindowW( "Progman", 0 )
    if hProgman != 0:
        hFolder = windll.User32.FindWindowExW( hProgman, 0, "SHELLDLL_DefView", 0 )
        if hFolder != 0:
            hListView = windll.User32.FindWindowExW( hFolder, 0, "SysListView32", 0 )
            if hListView != 0:
                windll.User32.PostMessageW( hListView, WM_LBUTTONDBLCLK, MK_LBUTTON,
                                            110 + (65536*32) )

EDIT
the WM_LBUTTON* messages are normally posted by Windows to the window under the pointer. The desktop window has child windows, and that's those child windows which are "under the pointer". If you want to use the PostMessage API, you need to know to what window you will  post the message.
If you don't want to bother with windows hierarchy, the just use SendInput. Window will then do the work for you and finally post the mouse message to the correct handle.

A: It may be easier to install pywinauto and use ClickInput in combination with find_windows and Rectangle
Links to implementation:

*

*https://code.google.com/p/pywinauto/source/browse/pywinauto/controls/HwndWrapper.py?name=0.4.2#1465

*https://code.google.com/p/pywinauto/source/browse/pywinauto/findwindows.py?name=0.4.2#81

*https://code.google.com/p/pywinauto/source/browse/pywinauto/handleprops.py?name=0.4.2#135


text:
Q: Is it possible to run a python command within a shell script? I'm learning some basic scripting and I thought I would try my hand at "automating" a small task at work and make things a littler easier for users not so comfortable working inside their terminal.
    echo "Activating the Bin"
    Source=source
    BinActivate=/opt/ia3/bin/activate
    SourceBinActivate=$Source $BinActivate
    if [ pwd == pwd ]
            then
            pwd #Log current directory to console
            sleep 2s
            eval $SourceBinActivate # Run source /opt/ia3/bin/activate
    else
            echo "Error, aborting process";  pwd #exit
    fi

When my script runs the eval, my terminal returns an error: /opt/ia3/bin/activate: Permission Denied.
Is it even possible to run a command like this in my terminal?
Do I need to run this as a specific user? Where should I look to research how to run commands as a user in my terminal?
Any direction or insight is much appreciated!

A: Your question doesn't really have anything to do with executing Python code. There's no Python here. Your code is failing on this line:
SourceBinActivate=$Source $BinActivate

It's not doing what you think it's doing. You think it's assigning the variable SourceBinActivate to the value of expanding the two variables Source and BinActivate. However, what it's really doing is temporarily assigning SourceBinActivate to the value of Source and then executing the value of BinActivate. (The value of SourceBinActivate would be reverted to its previous value once the command finished.) Since that value isn't an executable file, your shell reports "permission denied."
To assign a variable to hold a multi-token value, you need to quote the value:
SourceBinActivate="$Source $BinActivate"

A: If it's python code shouldn't be print instead of print ? Assuming your sample code is the "name.py" file. If your sample is indeed in a "name.py" file, try something like python path/.../name.py, and the call that from a "name.sh" file.
Edit: looking again at your code, it's not python at all. If python is the code you want to run, start with something small, something like:
print "Test" # print (string) in python 3.
The line above inside a .sh, then  do ./python_code.sh
Finally adapt your sample code to the python syntax.


text:
Q: android image rotating, imports error Hi to all.
I'm having a problem with the imports. It's showing me errors on the imports and if I remove them the JpegImageMetadata, Sanselan, ImageReadException, TiffImageMetadata, ExifTagConstants can't be resolved to a type.
I'm using Android 2.3.3 and also tried Android 3.2, still had the same problem. Here are the imports:
import org.apache.sanselan.ImageReadException;
import org.apache.sanselan.Sanselan;
import org.apache.sanselan.formats.jpeg.JpegImageMetadata;
import org.apache.sanselan.formats.tiff.TiffImageMetadata;
import org.apache.sanselan.formats.tiff.constants.ExifTagConstants;

And this is the other part of the code that is showing the error (I can post the whole code if needed):
private int degreeRotated(String filePath) {
        try {
            JpegImageMetadata meta = ((JpegImageMetadata) Sanselan.getMetadata(new File(filePath)));
            TiffImageMetadata data = null;
            if (meta != null) {
                data = meta.getExif();
            }
            int orientation = 0;
            if (data != null) {
                orientation = data.findField(ExifTagConstants.EXIF_TAG_ORIENTATION).getIntValue();
            } else {
                String[] projection = { Images.ImageColumns.ORIENTATION };
                Cursor c = getContentResolver().query(Uri.fromFile(new File(filePath)), projection, null, null, null);

                if (c != null && c.moveToFirst()) {
                    orientation = c.getInt(0);
                }
            }
            switch (orientation) {
                case 6:
                    return 90;
                case 8:
                    return 270;
                default:
                    return 0;

            }
            /*
             * } catch (JpegProcessingException e1) { e1.printStackTrace(); }
             * catch (MetadataException e) { e.printStackTrace(); }
             */} catch (ImageReadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return 0;
    }

And this is the error log:
Description   Resource   Path   Location   Type
ImageReadException cannot be resolved to a type   Viewer.java   /Main/src/com/owleyes/moustache   line 687   Java Problem
ExifTagConstants cannot be resolved to a variable   Viewer.java   /Main/src/com/owleyes/moustache   line 666   Java Problem
TiffImageMetadata cannot be resolved to a type   Viewer.java   /Main/src/com/owleyes/moustache   line 660   Java Problem
Sanselan cannot be resolved   Viewer.java   /Main/src/com/owleyes/moustache   line 659   Java Problem
JpegImageMetadata cannot be resolved to a type   Viewer.java   /Main/src/com/owleyes/moustache   line 659   Java Problem
JpegImageMetadata cannot be resolved to a type   Viewer.java   /Main/src/com/owleyes/moustache   line 659   Java Problem
The import org.apache.sanselan cannot be resolved   Viewer.java   /Main/src/com/owleyes/moustache   line 11   Java Problem
The import org.apache.sanselan cannot be resolved   Viewer.java   /Main/src/com/owleyes/moustache   line 10   Java Problem
The import org.apache.sanselan cannot be resolved   Viewer.java   /Main/src/com/owleyes/moustache   line 9   Java Problem
The import org.apache.sanselan cannot be resolved   Viewer.java   /Main/src/com/owleyes/moustache   line 8   Java Problem
The import org.apache.sanselan cannot be resolved   Viewer.java   /Main/src/com/owleyes/moustache   line 7   Java Problem

A: Clearly you don't have the needed library: Apache Sanselan.
Download the binaries here: http://commons.apache.org/imaging/download_sanselan.cgi, and extract the archive. Put the sanselan-{version}.jar in your project's libs directory. Recompile, and the errors should be gone.
Remember - Android doesn't have Sanselan library included out of the box.


text:
Q: Statistical problem involving a coin Two friends flip a coin $100$ times, and $58$ it is head. One says the coin is rigged, the other says it is not, and that it happened by chance. The problem asks to verify the hypothesis $p=1/2$ versus $p \neq1/2$, and who should I believe. He then asks to do the same in a situation with $1000$ throws and $580$ heads.
I know I am supposed to use De Moivre-Laplace approximation, but in the result it says that in the first case the coin is not rigged starting from level $0.011$ approximately, while in the other case you have to refute the hypothesis. What does that level mean, in fact? And how do I find that number?
The approach I want to take is define 100 Bernoulli variables $X_i$ and take their mean $Y$. I know that the expected value is 50 (under the hypothesis $p=1/2$), so I think you should do something like $P\{|Y-50|<8\}>1- \alpha$. That is, find $\alpha$ manipulating the inequality to use De Moivre-Laplace. But in fact I don't know if this is the correct approach, I am used to unilateral tests, but not to these...

A: This is equivalent to proportion hypothesis testing which is the same as frequentist approach.
Hypothesis framework:
$H_0 : p = .5$
$H_1 : p \ne 0.5$
Use the z-statistic and find the p-value.  That p-value is the level above which the null hypothesis ( the coin is not rigged) is rejected.
z -statistic =$ \dfrac{\hat p - p_0}{\sqrt{\frac{p_0(1-p_0)}{n}}}$
$\hat p =\frac{58}{100} =0.58$  and $p_0 = \frac{50}{100} =0.5$
$p - value = 2*$(1-Normsdist(z-statistic))
Do the same for the other experiment involved with 1000 flips and you will see that the z-statistic is large and one would have to reject the null hypothesis that the coin in not rigged.


text:
Q: Correct way to represent documents containing multiple sentences in gensim file-based training I am trying to use gensim's file-based training (example from documentation below):
from multiprocessing import cpu_count
from gensim.utils import save_as_line_sentence
from gensim.test.utils import get_tmpfile
from gensim.models import Word2Vec, Doc2Vec, FastText
 # Convert any corpus to the needed format: 1 document per line, words delimited by " "
corpus = api.load("text8")
corpus_fname = get_tmpfile("text8-file-sentence.txt")
save_as_line_sentence(corpus, corpus_fname)
 # Choose num of cores that you want to use (let's use all, models scale linearly now!)
num_cores = cpu_count()
 # Train models using all cores
w2v_model = Word2Vec(corpus_file=corpus_fname, workers=num_cores)
d2v_model = Doc2Vec(corpus_file=corpus_fname, workers=num_cores)
ft_model = FastText(corpus_file=corpus_fname, workers=num_cores)

However, my actual corpus contains many documents, each containing many sentences.
For example, let's assume my corpus is the plays of Shakespeare - Each play is a document, each document has many many sentences, and I would like to learn embeddings for each play, but the word embeddings only from within the same sentence.
Since the file-based training is meant to be one document per line, I assume that I should put one play per line. However, the documentation for file-based-training doesn't have an example of any documents with multiple sentences.
Is there a way to peek inside the model to see the documents and word context pairs that have been found before they are trained?
What is the correct way to build this file, maintaining sentence boundaries?
Thank you

A: These algorithm implementations don't have any real understanding of, or dependence on, actual sentences. They just take texts – runs of word-tokens.
Often the texts provided to Word2Vec will be multiple sentences. Sometimes punctuation like sentence-ending periods are even retained as pseudo-words. (And when the sentences were really consecutive with each other in the source data, the overlapping word-context windows, between sentences, may even be a benefit.)
So you don't have to worry about "maintaining sentence boundaries". Any texts you provide that are sensible units of words that really co-occur will work about as well. (Especially in Word2Vec and FastText, even changing your breaks between texts to be sentences, or paragraphs, or sections, or documents is unlikely to have very much effect on the final word-vectors – it's just changing a subset of the training contexts, and probably not in any way that significantly changes which words influence which other words.)
There is, however, another implementation limit in gensim that you should watch out for: each training text can only be 10,000 tokens long, and if you supply larger texts, the extra tokens will be silently ignored.
So, be sure to use texts that are 10k tokens or shorter – even if you have to arbitrarily split longer ones. (Per above, any such arbitrary extra break in the token grouping is unlikely to have a noticeable effect on results.)
However, this presents a special problem using Doc2Vec in corpus_file mode, because in that mode, you don't get to specify your preferred tags for a text. (A text's tag, in this mode, is essentially just the line-number.)
In the original sequence corpus mode, the workaround for this 10k token limit was just to break up larger docs into multiple docs - but use the same repeated tags for all sub-documents from an original document. (This very closely approximates how a doc of any size would affect training.)
If you have documents with more than 10k tokens, I'd recommend either not using corpus_file mode, or figuring some way to use logical sub-documents of less than 10k tokens, then perhaps modeling your larger docs as the set of their sub-documents, or otherwise adjusting your downstream tasks to work on the same sub-document units.


text:
Q: How can I prevent other apps from stealing the focus? I have a fullscreen window with the Topmost property set to true. Whenever an application changes its WindowState property, my window is automatically minimized even though it has the active focus. For example, the code below exemplifies the problem. 3 seconds after the window is deactivated, it changes from Minimized to Normal, minimizing the other fullscreen application.
// Topmost = false
private void Form1_Deactivate(object sender, EventArgs e)
{
    System.Threading.Thread.Sleep(3000);
    this.WindowState = FormWindowState.Normal;
}

Is there a way to preserve the fullscreen window's WindowState property in such a case? I want the user to choose to minimize the fullscreen app, so I want to stop other programs from stealing the focus.

A: You may want to investigate  "Kiosk Mode".

A: Perhaps this is what you want: Windows Form in Full Screen "Kiosk Mode".
Otherwise I'll second Henk's recomendation.

A: If this is a kiosk application and you are the only program running on the computer then fine. Otherwise this is a really bad idea and that's why there is not a documented way of doing it.
As Raymund Chen says this kind of question should be followed with the thought experiment "what if two programs did this?":
http://blogs.msdn.com/oldnewthing/archive/2005/06/07/426294.aspx


text:
Q: How to get all documents(including data) in String array from a collection in Firestore? I want to get all itemName of all documents in a String array,
further I want to perform searching on that array, how could I achieve my task? Please help me. Thanx.
https://i.stack.imgur.com/ge5x2.png

A:
I want to get all itemName of all documents in a string array

To get all item names within all documents, you need to create a reference and use a get() call, like in the following lines of code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference offersDataRef = rootRef.collection("MartWayDB").document("Offers")
    .collection("OffersData");
offersDataRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            String[] array = new String[task.getResult().size()];
            int count = 0;
            for (QueryDocumentSnapshot document : task.getResult()) {
                String itemName = document.getString("itemName");
                array[count] = itemName;
                Log.d(TAG, itemName);
                count++;
            }

            //Do what you need to do with your array
        }
    }
});


text:
Q: ATmega48 maximum AREF voltage The application that I want to use it for is 5V. However it could potentially have a future iteration where the reference voltage could be as high as 15V.
The plan is to run the ATmega48 at 3.3V.
I have been researching for what the maximum AREF reference voltage could be and it appears that it is 5.5VDC or so. Am I understanding this correctly? I would prefer to not have to use voltage dividers so that my voltage levels are exact and I do not lose precision in resistor tolerances. Am I over thinking this? The reason why I am worried about this is that I am looking at the input voltage and output voltage of mosfet transistors and knowing the Rdson value of the resistor then calculating the current flowing through the transistor.
If this is the case, then I will plan on just using voltage dividers on my pcb so that I can switch out resistor values to be able to use AREF values from 15V to 5V and not need a pcb change.
What AREF voltage input level should I design to?

A: On page 323, the datasheet clearly states that Vref must not be more than AVcc, and that AVcc must be Vcc +/- 0.3 volts.
If your Vcc is 5 volts, the maximum Vref is also 5 volts.
It is very rare for any IC to accept input voltages outside its power supplies.

A: The reference voltage limits for normal operation are described in the datasheet table 29-15. It should be between AVcc and 1.0V.

Damage may occur if the reference input exceeds Vcc (which in turn must be within +/-0.3V of AVcc) +0.5V at any time, even briefly- that's in the 'Absolute Maximum' ratings, and it may not operate properly if the reference is too low.
So with Vcc = AVcc = 3.3V you should keep the Vref between 1.0 and 3.3V, and you'll probably get better results if Vref is towards the higher end of that range.
Generally you will need a buffer rather than just a voltage divider for Vref since it can draw significant current. You can add op-amp buffers for both the input and the reference and use two voltage dividers.
As others have said, measuring voltage drop across Rds(on) is not a very good idea. It is very variable from unit-to-unit and can increase ~50% as the MOSFET heats up. There are so-called Sense-FETs that are essentially a small MOSFET in parallel with a larger MOSFET such that the current divides between the MOSFETs. That allows one to measure an analog of the current through the main FET without a sense resistor. In most cases, the resistor or some other current measuring device may be a better solution though.

A: If you are relying on the \$R_{DS(on)}\$ parameter to be accurate, then your accuracy problem is not going to be in the divider resistors!
You should definitely keep AREF at or below your supply voltage. Any more than that and the ESD diode in the chip will forward conduct, then burn out.
You should definitely use a voltage divider on your sampled signal to reduce the voltage to be under your AREF voltage, which is below your VCC/AVCC voltage.

A: Besides the voltage measurement issue, there is a huge accuracy issue in using the MOSFET Rdson for measuring current. Rdson varies quite significantly (especially for Silicon FETs) with temperature and current. There is also good variation from individual part to part. If accuracy is important (and you seem worried about that since you talk about resistor tolerance issues), you will face issues due to the reasons mentioned. Consider looking into a series (shunt) resistor or a hall-effect device for current measurement.


text:
Q: STM32F103R6 (Cortex-M3) trouble with rising edge detection I'm using Proteus 8.6 for simulation of STM32F103R6 microcontroller with ports C0 connected to a LED and port C1 connected to a button. I'm trying to capture the rising edge of the button so that it switches the LED on every third click. I'm getting a weird behavior because it switches the LED on the 2nd click(rising) and it turns the LED off on the click after that(falling). I've tried 3 other configurations, using pull down input mode, but capturing the falling edge and using pull up input mode and capturing both rising and falling edges with button connected to the ground. Only configuration that gives me weird behavior is when the button is connected to power and I'm using pull down input mode while capturing the rising edge. Here's my code:
    #include <stdint.h>

#define RCC_APB2ENR (*((uint32_t *) (0x40021000 + 0x18)))
#define GPIOC_CRL (*((uint32_t *) (0x40011000 + 0x00)))
#define GPIOC_ODR (*((uint32_t *) (0x40011000 + 0x0C)))
#define GPIOC_IDR (*((uint32_t *) (0x40011000 + 0x08)))
#define AFIO_EXTICR1 (*((uint32_t *) (0x40010000 + 0x08)))

#define IOPCEN (0x01 << 4)
#define AFIOEN (0x01 << 0)

#define MODE_OUT_2MHZ 0x02
#define CNF_GP_OUT_PUSH_PULL 0x00

#define MODE_IN 0x00
#define CNF_GP_IN_PULL 0x08

#define EXTI_PORT_C 0x02

void init_GPIOC()
{
    RCC_APB2ENR |= IOPCEN | AFIOEN;

    GPIOC_CRL |= MODE_OUT_2MHZ << (4 * 0) | CNF_GP_OUT_PUSH_PULL << (2 + 4 * 0);
    GPIOC_ODR = 0x0;

    GPIOC_CRL |= MODE_IN << (4 * 1) | CNF_GP_IN_PULL << (2 + 4 * 1);
    //GPIOC_ODR |= 0x01 << 1;

    AFIO_EXTICR1 |= EXTI_PORT_C << (4 * 1);
}

#define EXTI_IMR (*((uint32_t *) (0x40010400 + 0x00)))
#define EXTI_RTSR (*((uint32_t *) (0x40010400 + 0x08)))
#define EXTI_FTSR (*((uint32_t *) (0x40010400 + 0x0C)))
#define EXTI_PR (*((uint32_t *) (0x40010400 + 0x14)))

#define MR_NOT_MASKED 0x01
#define TR_ENABLED 0x01
#define TF_ENABLED 0x01

void init_EXTI()
{

    EXTI_IMR |= MR_NOT_MASKED << 1;
    EXTI_RTSR |= TR_ENABLED << 1;
    //EXTI_FTSR |= TF_ENABLED << 1;
}

#define NVIC_ISER0 (*((uint32_t *) (0xE000E100 + 0x00)))

#define SETENA 0x01

void init_NVIC()
{

    NVIC_ISER0 = SETENA << 7;
}

int counter = 3;

void process_button_click()
{

        if(--counter == 0)
        {
            // Stanje diode menjamo na svaki treci pritisak dugmeta
            GPIOC_ODR ^= 0x01;
            counter = 3;

        }

}

void exti_1_handler()
{

    if((EXTI_PR & 0x02) != 0)
    {
        EXTI_PR = 0x02;

        process_button_click();

    }
}

int main()
{
    init_GPIOC();
    init_EXTI();
    init_NVIC();

    while (1)
    {

    }

}

A: In general, using noisy pushbuttons directly with interrupts may not be a good idea. What may happen in this case is that it thinks first edge already is pending when you enable interrupts. And due to noise, both falling and rising edge interrupts get latched as pending. Perhaps most important is to know that if no interrupts has happened, button state has not changed. When interrupt has happened, button state has glitched but if you wait for some time without new intetrupts you can believe that it has stabilized. You may want to disable further interrupts for the stabilization period. And a timer can be useful for determining time or actually executing the button callback in timer interrupt if further interrupts do not restart it. It all depends on if you want to just use pushbuttons, or use pushbutton to simulate interrupt signals.


text:
Q: C# HttpGet IHttpActionResult returns empty array Hope everybody is having a good day.
I am using an API to read from a DB and then testing this API with Postman.
I have a c# class that looks like this:
{

    public class ResultValidSubscriptions
    {
        int ID;
        string Integration;
        string Domain;
        int Month;
        int Year;
        int UserCount;
        string AppVersion;
        bool IsCorrect;

        public ResultValidSubscriptions(int iD, string integration, string domain, int month, int year, int userCount, string appVersion, bool isCorrect)
        {
            ID = iD;
            Integration = integration;
            Domain = domain;
            Month = month;
            Year = year;
            UserCount = userCount;
            AppVersion = appVersion;
            IsCorrect = isCorrect;
        }
    }
}

So I retrieve a list of these objects  from the database and adding them to a list. I then use this method to return it to the caller(postman in this case).
  [HttpGet]
        public IHttpActionResult GetAllValidSubscriptions(int TargetYear, int TargetMonth)
        {
            try
            {
                arrayListSubscriptions = service.getAllValidSubscriptions(TargetYear, TargetMonth);
                string json = JsonConvert.SerializeObject(arrayListSubscriptions);
                var deserialized = JsonConvert.DeserializeObject<List<ResultValidSubscriptions>>(json);

                return Ok(deserialized);
            }

When I insert breakpoints I can see that arrayListSubscriptions contains the correct items. 5x ResultValidSubscriptions in this case. As you can see below the empty array also contains 5 items.
The problem is when I return either arrayListSubscriptions , Json, or deserialized all I get is an empty array.

When I change
return Ok(deserialized);

to

return Ok("hi");

It works fine and I see hi in postman. So my arraylist seems to be full, my method seems to be working. But somehow somewhere the array is getting cleared? I think the conversion to JSON is doing this, but I thought this would be solved by deserializing it with the class name.
Anybody that can help me with this? Much appreciated.

A: Problem was the fields in my object class were private.
Changed to:

 public class ResultValidSubscriptions
    {
        public int ID;
        public string Integration;
        public string Domain;
        public int Month;
        public int Year;
        public int UserCount;
        public string AppVersion;
        public bool IsCorrect;

        public ResultValidSubscriptions(int iD, string integration, string domain, int month, int year, int userCount, string appVersion, bool isCorrect)
        {
            ID = iD;
            Integration = integration;
            Domain = domain;
            Month = month;
            Year = year;
            UserCount = userCount;
            AppVersion = appVersion;
            IsCorrect = isCorrect;
        }
    }

And it works! Sorry for the stupid oversight and thanks for the help!


text:
Q: Should I store uploaded filename in database? I have a database table with an autoincrement ID as primary key.
For each record of this table, I can have up to 3 files, which can be publicly available so random filename generation is not mandatory, and these files are optional.
I think I have 2 possible solutions:

*

*Store a random generated filename in 3 nullable varchar column and store all the files in the same place:

*

*columns: a | b | c

*uploads/f6se54fse654.jpg

*Don't store the filenames, but place them in specific folders and name them the same than the primary key value:

*

*uploads/a/1.jpg

*uploads/b/1.jpg

*uploads/c/1.jpg

With this last solution, I know that uploads/a/1.jpg belongs to record with ID 1, and is a file of type a. But I have to check if the file exists because the files are optional.
Do you think there is a good practice in all that? Or maybe there is a better approach?

A: If the files you are talking about are intended to be displayed or downloaded by users (whether for visitors or for authenticated users, filtered by roles (ACL) or not), it is important to ensure (IMHO) that the user will not be able to guess other information other than the content of the concerned resource which has been sent to him. There is no perfect solution that can be applied to all cases without exception, so let's take an example to give you more explanations.
In order to enhance the security and total opacity of sensitive data, for example for the specific case of uploads/users/7/invoices/3.pdf, I think it would be wise to ensure that absolutely no one can guess the number of files that are potentially associated with the user or any other entity (because otherwise, in this example, we could imagine that there potentially are other accessible files - 1.pdf and 2.pdf). By design, we generally want to give access to files in a well defined and specific cases and context. However, this may not be the case for an image file which is intended to be seen by everyone (a profile photo, for example). That's why the context matters in some way.
If you choose to keep the auto-incremented identifiers as names to refer to your files, this can also give information about the size of the data stored in your database (/uploads/invoices/128.pdf informs that you may already have 127 invoices on your server) and potentially motivate unscrupulous people to try to reach resources that should never be fetched out of the defined context. This case may be less obvious if you choose to use some kind of unique generated identifiers (GUID).
I recommend that you read this article concerning the generation of (G)/(U)UIDs (a 128-bit hexadecimal numbers) to be stored in your database for each uploaded or created file. If you use MySQL in its latest version it is even possible to host this identifier in a binary (16) type which offers an automatic conversion to UUID, I let you read this interesting topic associated with what I refer about. It will probably output this as /uploads/invoices/b0016303-8e4f-487a-8c30-5dddf1ebf7e9.pdf which is a lot better as long as you ensure that the generated identifier is unique hash.
It does not seem useful to me here to talk about performance issues because today there are many methods for caching files or path and urls, which avoid having to make requests each time in a lot of cases where a resource is called (often ordered by their popularity rank in bigdata cases).
Last, but not least, many web and mobile platform applications (I think of Slack, Discord, Facebook, Twitter...) which store a lot of media files every day which are often associated with accounts users, both public and confidential files and information, generate a unique hash for each of them.
Twitter is using its own unique identifier string (64-bits BIGINT) generator called Twitter Snowflake which you might be interesting to read too. It is based on the UNIX epoch value which is, by definition, unique at each millisecond tick.
There isn't a global and perfect solution which can be applied for everything but I hope that this will help you as you may want to take a deeper look in this and find the "best solution" for each context and entity you'll store and link files.


text:
Q: 1.2 GHz Cloverleaf Antenna tolerance I'm working on building my own Cloverleaf antennas, to work at 1.2 GHz, for the video system on my Quadcopter. At this frequency, what kind of tolerance am I looking at in terms of the length of the wire and the various geometric angles before I lose the advantage of this type of antenna? The calculator I used to find the length spit out a number in millimeters with, like, 8 decimal points after it, but after converting to inches, using a tape measure to measure it out, and trying to do the whole shebang in my dorm room bathroom (no hate on this please, it's fireproof I swear!), I only have about 1/8" - 1/16" accuracy. Is this enough?

A: IANARFEng... but
Wavelength of 1.2GHz in air is 25cm.
Often tolerances of λ/10 are acceptable (which is about an inch), so I'd think 1/8" would be OK.


text:
Q: java.lang.NoClassDefFoundError: org/apache/beam/sdk/runners/PipelineRunner after migrating to dataflow 2.x Getting runtime error:
"java.lang.NoClassDefFoundError: org/apache/beam/sdk/runners/PipelineRunner"

even though I have below in my pom.xml
<dependency>
        <groupId>com.google.cloud.dataflow</groupId>
        <artifactId>google-cloud-dataflow-java-sdk-all</artifactId>
        <version>[2.1.0, 2.99)</version>
    </dependency>

All compile time errors have been resolved after moving to 2.X, started getting runtime error.
mvn compile on this project also reports success. Just when I attempt to run the  pipeline from eclipse get this error.

A: I added below to my pom.xml and deleted any all run profiles in pom.xml and error was resolved.
<dependency>
      <groupId>org.apache.beam</groupId>
      <artifactId>beam-runners-google-cloud-dataflow-java</artifactId>
      <version>[2.1.0, 2.99)</version>
    </dependency>