text:
Q: Your local changes to the following files would be overwritten by merge Similar questions have been asked here, but I believe this particular one hasn't.
I have a file params.dat that stores some parameter values for my code.
This file is constantly changing, since I change the parameter values often, so I added a  static version of it into my repo at home along with the rest of the code, and then ignored it with:
git update-index --assume-unchanged params.dat

Everything works fine, except when I have to make some change to the static version of the file (which happens no so often). What I do is, first un-ignore it with:
git update-index --no-assume-unchanged params.dat

then make the necessary changes, commit and push them to Github and finally ignore the file again.
This works flawlessly with my main repo, but when I try to git pull from the repo I keep at work, I get:
error: Your local changes to the following files would be overwritten by merge:
    params.dat
Please, commit your changes or stash them before you can merge.
Aborting

I tried, as explained here, to do:
git fetch --all
git reset --hard origin/master

but I get:
error: Entry 'params.dat' not uptodate. Cannot merge.
fatal: Could not reset index file to revision 'origin/master'.

I also tried:
git stash
git merge origin/master
git stash pop

as stated here, but after git stash I get:
No hay cambios locales que guardar

(roughly translates to "No local changes to save")
To make things clear: I am not interested in keeping any changes on the params.dat file on the repo I keep at my work. I just want it to be an exact copy of whatever I pushed last to Github from home.
What is the appropriate way to handle this?

A: "No local changes to save" in this case means git stash doesn't see local changes in params.dat as it is assumed to be unchanged.
Before pulling, you have to make local changes visible, and get rid of them in params.dat file if any:
$ git update-index --no-assume-unchanged params.dat
$ git checkout -- params.dat
$ git pull
$ git update-index --assume-unchanged params.dat

If there are not-commited local changes in other files you are interested in, use stashing to keep them and restore after pulling:
$ git update-index --no-assume-unchanged params.dat
$ git checkout -- params.dat
$ git stash
$ git pull
$ git stash pop
$ git update-index --assume-unchanged params.dat

A: I tried all the aforementioned steps, but it didn't work for me.
After hours online, I found out somewhere that you can just rename that file then do your pull or reset or rebase.
This will pull the remote file for you (recreate the renamed file).
Now you can delete the renamed file and life goes on.


text:
Q: WKHTMLTOPDF breaks saying --margin-bottom invalid argument My application generates a PDF file from a webpage using WKHTMLTOPDF tool. Application written with Symfony2 framework and I am using a Symfony2 process to run the shell command to call WKHTMLTOPDF. My command is like below.
C:\wkhtmltopdf\wkhtmltopdf.exe --lowquality --margin-bottom '0' --margin-left '0' --margin-right '0' --margin-top '0' SOURCE.html SOURCE.pdf

This gives me an error now.
Invalid argument(s) parsed to --margin-bottom
is the error I am getting. I am really confused because for some cases it is working perfectly. Only some cases it is not working.
When I try to run the same command in the CMD, it works. Only symfony process gives error.
I really appreciate if anyone can help me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Any way to get url params in Next.js custom document? I'm working on a multi-language statically built (next export) Next.js site. I can't use next internationalization so I've had to hack together a solution, mostly based on this nextjs-18n-static-page-starter
My page structure looks like this:
pages
 ┣ [lang]
 ┃ ┣ category
 ┃ ┃ ┣ [slug].js
 ┃ ┃ ┗ index.js
 ┃ ┗ index.js
 ┣ _app.js
 ┣ _document.js
 ┗ index.js

I would like to set the html lang attribute in a custom document. Is there any way to dynamically pull this from the url at the document level?
I have this hacky solution going, but it doesn't update when the user changes their language in the app (which does correctly redirect to a new url):
export default class MyDocument extends Document {
  render() {
    const queryLang = this?.props?.__NEXT_DATA__?.query?.lang;
    const lang = ( queryLang === null || queryLang === undefined ) ? DEFAULT_LANG : queryLang;

    return (
      <Html lang={lang}>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

A: Setting it in the app did the trick. Here's the code I ended up with (thanks to @juliomalves for pointing me in the right direction)...
const App = function ({ Component, pageProps }) {
    i18next.changeLanguage(pageProps.language);

    useEffect(() => {
        const lang = ( pageProps.language === null ||
          pageProps.language === undefined )
          ? DEFAULT_LANG
          : pageProps.language;
        document.documentElement.lang = lang;
     }, [pageProps.language]);
    return <Component {...pageProps} />;
 };

A: Since Next.js v10, if you're using the built-in i18n routing, Next will automatically set the lang attribute of the document.
if your language is en-US all you need to do is add the following in you next.config.js file
module.exports = {
  i18n: {
    locales: ["en-US"],
    defaultLocale: "en-US",
  },
  ...
}

From the documentation:

Search Engine Optimization
Since Next.js knows what language the user is visiting it will
automatically add the lang attribute to the <html> tag.
Next.js doesn't know about variants of a page so it's up to you to add
the hreflang meta tags using next/head. You can learn more about
hreflang in the Google Webmasters documentation.


text:
Q: Fonts not rendering correctly until I change the screen resolution to another resolution and back again I've just installed Xubuntu 19.10 on an old Dell Inspiron 545. Unfortunately the fonts are a little fuzzy and the only thing I've found that works is to change the display resolution down and then back up again. This makes the fonts crystal clear.
Adjusting font smoothing etc. makes no difference.


text:
Q: How can I install/run apps that use Rosetta on Lion? Is there a workaround to install/use apps that are using Rosetta on Lion?
I'm still using Zend 5.5 and I don't want to switch to a new IDE right now.

A: You don't need Rosetta to run Zend Studio 5.5.1 on Lion, however, the installer requires Rosetta (which is quite unfortunate).  So long as you have Zend Studio 5.5.1 installed, or migrate it from your Snow Leopard Machine, you can get it running under Java SE 6 by following the instructions here: http://www.s-seven.net/zend_5x_lion

A: At the time of writing Rosetta is not included with Lion, not supported by Lion officially and not available from any other channel (official or unofficial) for use on Lion.
So: no, there is no workaround. Your Rosetta-based applications cease to function if you upgrade to Lion.

A: Until someone creates another emulation layer, you could technically run Snow Leopard inside the virtualization software of your choice. Plenty of tech blogs have the steps for various VM choices.
The Snow Leopard license has words saying you shouldn't do it and you'll have to hack it lightly since the installer won't run unmodified.
Lion however will be "running" the code through rosetta - just not directly.
Don't overlook avoiding the issue altogether for your development work:

*

*keeping an old mac running Snow Leopard and using Screen Sharing to connect  might be much faster than emulation and more "legal" if you don't really need to be self contained.

*keeping Snow Leopard on an external or second partition to boot for your development work.

A: If you still have a copy of your Snow Leopard install disks, install it on another bootable drive or partition.  Boot from that, and run your Rosetta/PPC apps, then reboot into Lion (which can't run PPC apps) when you're done.

A: Spend 60 seconds and tell Apple that they should SELL Rosetta for Lion on the App store.
How would this not be a total win? Fewer people delaying upgrade, enough cash to cover the development and support, more happy customers.
http://Apple.com/feedback/macosx.html

A: I am running lion on a 2008 8 core mac pro.
I used the snow leopard disk to install rosetta as an "optional Install".
Its my understanding that pure ppc code pas will not run in lion; but universal pas with intel code can be installed.
I was able to install final cut studio 2 this way.
The reason I understand this working is because the apps them selves are not ppc but intel or what ever rosetta only had to unlock the ppc installer for me.


text:
Q: Detecting installed MSVC redistributables programmatically is there any way to do it in C++? I'd like to do it like that:
user starts app -> app checks for installed redists -> app tells user to install redistributable X in order to use application and closes

A: Probably your best bet is MsiQueryProductState
Here are two good articles:
How to programmatically obtain the installation state of Visual Studio .NET or Visual Studio 2005
Determining if the VC Runtimes Are Installed  (Delphi code example):
// API call to msi.dll to determine is a MSI installed packed has been installed.
// It does this by checking the state of the installed package.
// Anything other than a return value of INSTALLSTATE_DEFAULT (5) indicates a broken or
// no installation.
function MsiQueryProductState(szProduct: String): Integer; external 'MsiQueryProductStateA@msi.dll stdcall';

// String constants to pass to the routine.
const
   // These constants check for any install of the version specific package
   // regardless the service pack or security update.  There are specific
   // constants for x86, x64 and i64 installations.
   VC2005_ANY_x86        = 'vc2005x86';
   VC2005_ANY_x64        = 'vc2005x64';
   VC2005_ANY_i64        = 'vc2005i64';
   ...
   // All available VC 2005 (version 8.0) installations.
   VC2005_x86            = '{A49F249F-0C91-497F-86DF-B2585E8E76B7}';
   VC2005_x64            = '{6E8E85E8-CE4B-4FF5-91F7-04999C9FAE6A}';
   ...
   // All available VC 2008 (version 9.0) installations.
   VC2008_x86            = '{FF66E9F6-83E7-3A3E-AF14-8DE9A809A6A4}';
   VC2008_x64            = '{350AA351-21FA-3270-8B7A-835434E766AD}';
   ...
function VCRT_IsInstalled(sPackage: String): Integer;
var
   nResult: Integer;

begin
   // Check for the existence of msi.dll.  The poor man's way of checking for the
   // installation of the Windows Installation Engine.
   If FileExists(ExpandConstant('{sys}\msi.dll')) then begin

      // Default return value of -1, which indicated no installation.  This is only
      // necessary for the VC*_ANY_* flags as individual return values are not captured.
      Result := -1;

      // Check for the package passed ia the sPackage parameter.
      case sPackage of
         VC2005_ANY_x86:
            begin
               If (MsiQueryProductState(VC2005_x86) = 5) or
               (MsiQueryProductState(VC2005_SP1_x86) = 5) or
               (MsiQueryProductState(VC2005_SP1_SECUP_x86) = 5) then begin
                  Result := 5;
               end;
            end;
         VC2008_ANY_x86:
            begin
               If (MsiQueryProductState(VC2008_x86) = 5) or
               (MsiQueryProductState(VC2008_SP1_x86) = 5) or
               (MsiQueryProductState(VC2008_SP1_SECUP_x86) = 5) then begin
                  Result := 5;
          ...
         VC2010_ANY_i64:
            begin
               If MsiQueryProductState(VC2010_i64) = 5 then begin
                  Result := 5;
               end;
            end;

         // All speific versions are checked here.  The return value is passed back
         // as the functions return value.
         else
            begin
               Result := MsiQueryProductState(sPackage);
            end;
      end;
   end else begin

      // MSI not installed.  Pass the specific error number for it.
      Result := INSTALLSTATE_MSIABSENT;
   end;
end;

Here is the list of redistributable codes for MSVS 2015:

*

*Distributable Code for Microsoft Visual Studio 2015 RC and Microsoft Visual Studio 2015 SDK RC (Includes Utilities & BuildServer Files)


text:
Q: Is the following a fair betting game? There is this problem I found.
The answer to this brain teaser is different to mine because they used a bit different approach, which changes the solution completely.
I was thinking in terms of a single person playing against the dealer. If that were the case then the set of realizations would be:
$$\Omega_X = \{ 1,1,1, 2,2,2,3,3,3,...,6,6,6\}$$
Then $P[\text{one die is my number}] = 3/18=1/6$
Since the tosses are independent, then $P[\text{two of my numbers show up}] = 1/6 \cdot 1/6 = 1/36$, hence $P[\text{three show up}]=1/6^3$. We are also interested in the complement to the union of these events: $P[(E_1 \cup E_2 \cup E_3)^c] = 1-1/6-1/36-1/216 \approx 80\%$
The game is deemed to be fair if the expected winnings/losses are zero.
Since we know that:
$\mathbb{E}[\cdot] = \sum p_{\omega}X(\omega)$
Then $\mathbb{E}[\text{winnigs}] = 1/6 \cdot (\$1) + 1/36 \cdot (\$3) + 1/216 \cdot (\$5) - (1-1/6-1/36-1/216) \approx -\$0.53$
Thu, unfair (for when one player plays against the dealer). This is correct, right?

A: If $X$ denotes the number of dice showing the chosen face then $X$ takes values in $\{0,1,2,3\}$ with:

*

*$P(X=0)=\frac56\frac56\frac56=\frac{125}{216}$

*$P(X=1)=\frac16\frac56\frac56+\frac56\frac16\frac56+\frac56\frac56\frac16=\frac{75}{216}$

*$P(X=2)=\frac16\frac16\frac56+\frac16\frac56\frac16+\frac56\frac16\frac16=\frac{15}{216}$

*$P(X=3)=\frac16\frac16\frac16=\frac1{216}$

For the expected winning we find:$$(-1)\times\frac{125}{216}+1\times\frac{75}{216}+3\times\frac{15}{216}+5\times\frac1{216}=0$$


text:
Q: Deriving the unitary transformation for phase shifts The transformation of phase translations is linked to the generator of the conjugate variable. For phase changes, this is the number operator. Hence, for a phase translation of $\text{d}\varphi$, the unitary transformation performing this shift is
$$\hat{U} = \exp\left[-i\text{d}\varphi\hat{n}\right].$$
I would like to derive a similar unitary transformation for different variables where the generator is initially unknown. To do so, it would be informative to understand how the above equation is derived. Does anyone know how to derive the form of $\hat{U}$ shown above for phase translations so that a similar approach may be taken for different observables?
NOTE
The above is a phase shifter, not a phase operator.

A: We are trying to find the unitary operator $\hat U$ that shift the phase of the creation operator, i.e.
$$ \hat U(\phi) \hat a \hat U^\dagger(\phi)=e^{-i \phi}\hat a.\quad\quad (1)$$
To do so, the simplest thing is to expand $\hat U(\phi)$ for small phases, $\hat U=\hat 1 -i \phi \hat A$, (the sign is arbitrary) with $\hat A^\dagger=\hat A$ to insure unitarity at lowest order in $\phi$. Expanding $(1)$ to lowest order in $\phi$, one find that $\hat A$ must be such that
$$[\hat A,\hat a]=\hat a,$$
which is solved by $\hat A=\hat a^\dagger \hat a$. One can then reconstruct $\hat U$ directly, since it only involves one operator(this would not be true if $\hat A$ was the sum of two non-commuting operators).


text:
Q: How do I find the IP address of a web site that is sending data by POST method to an asp.net web page? EDIT after Answers AND Comments :
How can i find the IP address of a web site (for example bank web site) that is sending to my web site (asp.net page with c#) some specific and needed data by post method?
For example :
<form id="form1" method="post" action="my web site url"></form>

Imagine that I have a user that wants to buy something from my web site!
He/She opens my web site and choose a product and click pay.  At this time I can get their ip address by the below answers.
By clicking "pay" I transfer some data such as order_id to a bank web site by a POST method.
When the user goes to the bank website and transfers some money, they then want to get back my web site!
At this time,the bank site sends some data such as transaction_id by a POST method to my web site for checking payment.
For some security reasons and to prevent simulation this transaction_id transfers between the bank site and my web site, I want to check bank ip address when getting his POST data (third party ip address).
For example I want to find the ip-address(mean bank) of transaction_id Sender at below code :
string transaction_id = Page.Request.Form["transaction_id"];

However, if I check
string ipaddress = HttpContext.Current.Request.UserHostAddress;

or
Request.ServerVariables("REMOTE_ADDR")

these codes return only that user IP address, not sender of POST data.

A:  Request.ServerVariables("REMOTE_ADDR")

This link might give more details
http://thepcspy.com/read/getting_the_real_ip_of_your_users/

A: If you are using 'Socket', then you could just do something like the example:
s.Connect (lep);

// Using the RemoteEndPoint property.
Console.WriteLine ("I am connected to " + IPAddress.Parse (((IPEndPoint)s.RemoteEndPoint).Address.ToString ()) + "on port number " + ((IPEndPoint)s.RemoteEndPoint).Port.ToString ());

// Using the LocalEndPoint property.
Console.WriteLine ("My local IpAddress is :" + IPAddress.Parse (((IPEndPoint)s.LocalEndPoint).Address.ToString ()) + "I am connected on port number " + ((IPEndPoint)s.LocalEndPoint).Port.ToString ());

A: Can we use the following? Or am I missing something?
string ipaddress = HttpContext.Current.Request.UserHostAddress;


text:
Q: Floating-point: FLT_HAS_SUBNORM is 0 => subnormal value arises => unspecified behavior? If FLT_HAS_SUBNORM is 0 and if during execution of the FP operation (add, mul, div, etc.) a subnormal value arises (or if a subnormal value is given as input to these FP operations), then the FP engine's implementation (i.e. HW implementation [FPU], SW implementation [SW FP library], mixed HW-SW implementation [SW FP library using HW instructions followed by additional SW post-processing]) can:

*

*detect such subnormal values and set them to zeros (i.e. flash-to-zero policy / logic);

*do nothing [special] (leading to unpredictable output result values).

Question: can someone provide a correct argumentation (better if strengthened by references to C / IEEE 754 standards) convincing that the behavior of this case does fall into unspecified behavior category?
Note: ISO/IEC 9899:202x (E) working draft — February 5, 2020 N2479:

3.4.4
unspecified behavior
behavior, that results from the use of an unspecified value, or other behavior upon which this document provides two or more possibilities and imposes no further requirements on which is chosen in any instance

A: Replying to myself.
In this case:

*

*The behavior is not unspecified.

*The behavior is defined by implementation of the FP operation. Hence, the behavior is implementation-defined.

*Since the logic for detecting and processing subnormal numbers is absent (XXX_HAS_SUBNORM is 0), then the output result is indeterminate.

*(extra) This case should be seen as "user error" (and violation of XXX_HAS_SUBNORM is 0).


text:
Q: Reset iPhone and can't get it to unlock So for christmas one year my younger sister got an iPhone 5s. But currently she had to replace the battery and she had to reset her iPhone to do so.
She doesn't remember who set up all her iCloud and Apple ID information, so now we are stuck with a reset iPhone on the activation lock page. Someone please tell me how to fix this or if it even is fixable.

A: You can try to recover your Apple ID here . It's the only one legal way.


text:
Q: How can I efficiently get to the leaves of a binary-search tree? I want to sum all the values in the leaves of a BST. Apparently, I can't get to the leaves without traversing the whole tree. Is this true? Can I get to the leaves without taking O(N) time?

A: You realize that the leaves themselves will be at least 1/2 of O(n) anyway?

A: There is no way to get the leaves of a tree without traversing the whole tree (especially if you want every single leaf), which will unfortunately operate in O(n) time.  Are you sure that a tree is the best way to store your data if you want to access all of these leaves? There are other data structures which will allow more efficient access to your data.

A: To access all leaf nodes of a BST, you will have to traverse all the nodes of BST and that would be of order O(n).
One alternative is to use B+ tree where you can traverse to a leaf node in O(log n) time and after that all leaf nodes can be accessed sequentially to compute the sum. So, in your case it would be O(log n + k), where k is the number of leaf nodes and n is the total number of nodes in the B+ tree.
cheers

A: You will either have to traverse the tree searching for nodes without children, or modify the structure you are using to represent the tree to include a list of the leaf nodes. This will also necessitate modifying your insert and delete methods to maintain the list (for instance, if you remove the last child from a node, it becomes a leaf node). Unless the tree is very large, it's probably nice enough to just go ahead and traverse the tree.


text:
Q: Get NSURLConnection response (from a helper class) inside method of a different class I have a class, "WebAPI", that handles all web API calls, the class uses NSURLConnection through its asynchronous delegate-based calls.
Whenever an object needs to communicate with the web API it will use an instance of WebAPI and call the required method as shown below in the case of signing in I make the folowing call from the AppDelegate:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
     WebAPI *webAPI = [[WebAPI alloc] init];
     [webAPI performLoginWithUserName:@"test1@myserver.com" andPassword:@"password"];
}

The problem is that once the performLoginWithUserName:andPassword call is made, the code progresses on and any/all response is received in the delegate methods that are implemented in WebAPI.m.
This is a real issue because I need to be able to get response codes and any data received within the class method from where the call to the WebAPI, originated . I would like to be able to this :
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
     WebAPI *webAPI = [[WebAPI alloc] init];
     WebAPIResponse * webAPIRespnse = [webAPI performLoginWithUserName:@"test1@myserver.com" andPassword:@"password"];
}

Where WebAPIResponse class is a custom class that will contain the HTTP Status code and any data that is received.
This is achievable if I change WebAPI.m to use NSURLConnection sendSynchronousRequest, but that doesnt enable me to receive all HTTP codes.
What would be the best way to fulfill this requirement?
Thank you for your help.

A: You could use blocks to handle responses.
For example:
WebApi.h
- (void)performLoginWithUsername:(NSString *)userName
                     andPassword:(NSString *)password
                    successBlock:(void(^)(NSData *response))successBlock
                    failureBlock:(void(^)(NSError *error))failureBlock;

WebApi.m
@interface WebAPI()
    @property (nonatomic, copy) void(^authorizationSuccessBlock)(NSData *response);
    @property (nonatomic, copy) void(^authorizationFailureBlock)(NSError *error);
@end

@implementation WebAPI
- (void)performLoginWithUsername:(NSString *)userName
                     andPassword:(NSString *)password
                    successBlock:(void(^)(NSData *response))successBlock
                    failureBlock:(void(^)(NSError *error))failureBlock {
    self.authorizationSuccessBlock = successBlock;
    self.authorizationFailureBlock = failureBlock;
    // NSURLConnection call for authorization here
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if (self.authorizationSuccessBlock != nil) {
        self.authorizationSuccessBlock(data);
        self.authorizationSuccessBlock = nil;
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    if (self.authorizationFailureBlock != nil) {
        self.authorizationFailureBlock(error);
        self.authorizationFailureBlock = nil;
    }
}

AppDelegate.m
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
   WebAPI *webAPI = [[WebAPI alloc] init];
   [webAPI performLoginWithUserName:@"test1@myserver.com" andPassword:@"password" successBlock:^(NSData *response) {
      // Handle result here
   } failureBlock:^(NSError *error) {
      // Handle error here
   }];

}

A: Change your WebAPI class to provide a delegate interface of its own, or to use completion blocks on the request which are called when the asynchronous connection completes.


text:
Q: VSCode extension: Matching brackets inside quotes By default, bracket matching doesn't understand strings and so will match brackets inside of quotes.
Steps to reproduce:

*

*Start the language-configuration-sample extension

*Type the following line in the file,
[ "]" ]

*Move the cursor to the start of the line and hit Ctrl-\

*The open bracket will match with the bracket inside the quotes.
The same behavior happens with anything defined as "brackets" in the config.
I've noticed language extensions like java, python, etc do not have this behavior. How do they get around it? I've looked through their code and haven't seen anything that looks related.


text:
Q: Does TFS 2013 have shelvesets anymore (when using GIT)? I am having trouble finding any way to use shelvesets in Visual Studio 2013 using TFS.  Has that feature been removed, or is it not available when using a GIT repository?

A: This feature does not exist with a git repository. You need to use branches instead. This makes sense as a git branch is at the repository level, so they are functionally equivalent.


text:
Q: Read instance in Haskell I have created a type similar to Maybe
data Defined a = Is a | Undefined
I made the Show instnance
instance Show a => Show (Defined a) where
    show (Is a) = show a
    show Undefined = "?"

So, I try to implement the instance Read
instance Read a => Read (Defined a) where
    readsPrec _ s = case (take 1 s) of
                    "?" -> [(Undefined,tail s)]
                    otherwise -> map (\(a,b) -> (Is a,b)) $ readsPrec 0 s

That's work, but I can't understand why. Why there is no infinite loop here:
otherwise -> map (\(a,b) -> (Is a,b)) $ readsPrec 0 s

readsPrec 0 s try to read the same string such as in input, isn't it? So it have to go to otherwise block yet and form an infinite loop. But the code is really works.

A:
readsPrec 0 s try to read the same string such as in input, isn't it?

Yes it is, but it's not the same readsPrec! Let me add a few type annotations:
{-# LANGUAGE ScopedTypeVariables #-}

instance Read a => Read (Defined a) where
  readsPrec _ = readsDefined

readsDefined :: forall a . Read a => String -> ReadS (Defined a)
readsDefined s = case (take 1 s) of
                    "?" -> [(Undefined,tail s)]
                    otherwise -> map (\(a,b) -> (Is a,b)) $ readsContent s
 where readsContent :: String -> ReadS a
       readsContent = readsPrec 0

Note that I can not replace readsContent with readsDefined here, they're two different functions with incompatible type signature. That's the same situation as in your code, only, there readsDefined and readsContent are both (different) instantiations of the readsPrec method, i.e. they share the same name but still have different implementations.


text:
Q: How to proxy both references of "this" in javascript? Assuming I have the following function that is a callback for a function (in other words, "this" refers to what the callback passed):
afunction("onclick", callbackfunction)
function callbackfunction() {
   console.log(this); // This refers to item clicked
}

Instead of referring to just the item clicked I want to include a reference to the parent object. Normally I would use:
afunction("onclick", $.proxy(callbackfunction, this))

However this makes it such that I can't get the item clicked anymore. Is there a way I could keep both so that I could have access within the callbackfunction both the "proxy" "this" and the item clicked "this"?

A: Why not
var self = this;
afunction("onclick", function(evt){
    var clicked = this;
    anotherfunction(clicked,self);
});

A: Since you can't have two meanings of this, one would need to be passed as an argument.
One possibility using $.proxy would be to pass null as the thisArg value. That will cause the this to not be bound. When the event occurs, the this value will be the expected value set by the caller.
Then you can pass the enclosing this as an argument to be received by the function's first parameter.
afunction("onclick", $.proxy(callbackfunction, null, this));

This functionality of passing null requires jQuery 1.9 or later.
From the $.proxy docs:

As of jQuery 1.9, when the context is null or undefined the the proxied function will be called with the same this object as the proxy was called with. This allows $.proxy() to be used to partially apply the arguments of a function without changing the context.


text:
Q: Excel Popup Blocking Other Spreadsheet Interaction I have two coworkers that utilize an Excel file that has VB forms built into it.
User A has two open excel files on different screens. When they activate the user form for modification, it prevents interaction with either of the excel files while the form is active.
User B also has two open excel files but even with the form open, they are able to manipulate the excel file on the other screen that is not attached to the form.
Why do User A and User B have these differences?
Thanks


text:
Q: Rails - Purpose of using respond_to if templates are available? I have seen some people using code like this
respond_to do |format|
  format.html
  format.js
end

What is the purpose of this if we have template.html and template.js. Either can be rendered without specifying respond_to

A: The format options can take a block so that you can do some custom rendering such as rendering a file or :head response. Have a look at some of the examples here

A: Your snippet doesn't do anything special, but the formatting options allow you to provide additional custom behavior if it is necessary.
For example, if you want to render your @products as a JSON:
 respond_to do |format|
  format.html
  format.js { render :json => @products }
end

This is just one of the many things you can do with the format blocks. For more information, see Ruby on Rails Guides: Layouts and Rendering

A: If you don't specify different behavior for the different formats there is no reason to use respond_to. If you have templates they will automatically be picked up by rails. The respond_to method is useful if you need different behavior per format:
respond_to do |format|
  format.html { render :edit }
  format.json { render :json => '{}' }
end


text:
Q: What does the 'export' command do? I happen to run some commands blindly, in order to get things done.
I started to work with Jenkins recently, and then I had to use this export command to run the Jenkins WAR archive. What does the export command do in general, and why do we need to run this command, while running Jenkins (after the Jenkins home is set)?

A: In simple terms, environment variables are set when you open a new shell session. At any time if you change any of the variable values, the shell has no way of picking that change. That means the changes you made become effective in new shell sessions.
The export command, on the other hand, provides the ability to update the current shell session about the change you made to the exported variable. You don't have to wait until new shell session to use the value of the variable you changed.

A: I guess you're coming from a Windows background. So I'll contrast them (I'm kind of new to Linux too). I found a user's reply to my comment, to be useful in figuring things out.
In Windows, a variable can be permanent or not. The term environment variable includes a variable set in the cmd shell with the SET command, as well as when the variable is set within the Windows GUI, thus set in the registry, and becoming viewable in new cmd windows.
E.g., the documentation for the set command in Windows "Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings."
In Linux, set does not display environment variables. It displays shell variables which it doesn't call/refer to as environment variables. Also, Linux doesn't use set to set variables (apart from positional parameters and shell options, which I explain as a note at the end), only to display them and even then only to display shell variables. Windows uses set for setting and displaying, e.g., set a=5, but Linux doesn't.
In Linux, I guess you could make a script that sets variables on bootup, e.g., /etc/profile or /etc/.bashrc, but otherwise, they're not permanent.  They're stored in RAM.
There is a distinction in Linux between shell variables, and environment variables.  In Linux, shell variables are only in the current shell, and environment variables, are in that shell and all child shells.
You can view shell variables with the set command  (though note that, unlike Windows, variables are not set in Linux with the set command).
set -o posix; set (doing that set -o posix once first, helps not display too much unnecessary stuff). So set displays shell variables.
You can view environment variables with the env command.
Shell variables are set with, e.g., just a = 5.
Environment variables are set with export. Export also sets the shell variable.
Here you see shell variable zzz set with zzz = 5, and see it shows when running set, but it doesn't show as an environment variable.
Here we see yyy set with export, so it's an environment variable. And see it shows under both shell variables and environment variables:
$ zzz=5

$ set | grep zzz
zzz=5

$ env | grep zzz

$ export yyy=5

$ set | grep yyy
yyy=5

$ env | grep yyy
yyy=5

$

Other useful QnAs:

*

*https://unix.stackexchange.com/questions/176001/how-can-i-list-all-shell-variables

*https://askubuntu.com/questions/26318/environment-variable-vs-shell-variable-whats-the-difference
Note: One point which elaborates a bit and is somewhat corrective to what I've written, is that, in Linux bash, 'set' can be used to set "positional parameters" and "shell options/attributes", and technically both of those are variables, though the man pages might not describe them as such.
But still, as mentioned, set won't set shell variables or environment variables). If you do set asdf then it sets $1 to asdf, and if you do echo $1 you see asdf.
If you do set a=5 it won't set the variable a, equal to 5. It will set the positional parameter $1 equal to the string of "a=5". So if you ever saw set a=5 in Linux it's probably a mistake unless somebody actually wanted that string a=5, in $1.
The other thing that Linux's set can set, is shell options/attributes. If you do set -o you see a list of them. And you can do for example set -o verbose, off, to turn verbose on (by the way, the default happens to be off, but that makes no difference to this). Or you can do set +o verbose to turn verbose off. Windows has no such usage for its set command.

A: export in sh and related shells (such as Bash), marks an environment variable to be exported to child-processes, so that the child inherits them.
export is defined in POSIX:

The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands. If the name of a variable is followed by = word, then the value of that variable shall be set to word.


text:
Q: Copy table from one dataset to another in google big query I intend to copy a set of tables from one dataset to another within the same project. I execute the code in Ipython notebook.
I get the list of table names to be copied in the variable "value" using the below code:
list = bq.DataSet('test:TestDataset')

for x in list.tables():
   if(re.match('table1(.*)',x.name.table_id)):
     value = 'test:TestDataset.'+ x.name.table_id

Then i tried using the "bq cp" command to copy table from one dataset to another. But I cannot execute the bq command in the notebook.
!bq cp $value proj1:test1.table1_20162020

Note:
I tried with bigquery command to check whether there is a copy command associated with it but could not find any.

A: I have created following script to copying all the tables from one dataset to another dataset with couple of validation.
from google.cloud import bigquery

client = bigquery.Client()

projectFrom = 'source_project_id'
datasetFrom = 'source_dataset'

projectTo = 'destination_project_id'
datasetTo = 'destination_dataset'

# Creating dataset reference from google bigquery cient
dataset_from = client.dataset(dataset_id=datasetFrom, project=projectFrom)
dataset_to = client.dataset(dataset_id=datasetTo, project=projectTo)

for source_table_ref in client.list_dataset_tables(dataset=dataset_from):
    # Destination table reference
    destination_table_ref = dataset_to.table(source_table_ref.table_id)

    job = client.copy_table(
      source_table_ref,
      destination_table_ref)

    job.result()
    assert job.state == 'DONE'

    dest_table = client.get_table(destination_table_ref)
    source_table = client.get_table(source_table_ref)

    assert dest_table.num_rows > 0 # validation 1
    assert dest_table.num_rows == source_table.num_rows # validation 2

    print ("Source - table: {} row count {}".format(source_table.table_id,source_table.num_rows ))
    print ("Destination - table: {} row count {}".format(dest_table.table_id, dest_table.num_rows))

A: If you are using the BigQuery API with Python, you can run a copy job:
https://cloud.google.com/bigquery/docs/tables#copyingtable
Copying the Python example from the docs:
def copyTable(service):
   try:
    sourceProjectId = raw_input("What is your source project? ")
    sourceDatasetId = raw_input("What is your source dataset? ")
    sourceTableId = raw_input("What is your source table? ")

    targetProjectId = raw_input("What is your target project? ")
    targetDatasetId = raw_input("What is your target dataset? ")
    targetTableId = raw_input("What is your target table? ")

    jobCollection = service.jobs()
    jobData = {
      "projectId": sourceProjectId,
      "configuration": {
          "copy": {
              "sourceTable": {
                  "projectId": sourceProjectId,
                  "datasetId": sourceDatasetId,
                  "tableId": sourceTableId,
              },
              "destinationTable": {
                  "projectId": targetProjectId,
                  "datasetId": targetDatasetId,
                  "tableId": targetTableId,
              },
          "createDisposition": "CREATE_IF_NEEDED",
          "writeDisposition": "WRITE_TRUNCATE"
          }
        }
      }

    insertResponse = jobCollection.insert(projectId=targetProjectId, body=jobData).execute()

    # Ping for status until it is done, with a short pause between calls.
    import time
    while True:
      status = jobCollection.get(projectId=targetProjectId,
                                 jobId=insertResponse['jobReference']['jobId']).execute()
      if 'DONE' == status['status']['state']:
          break
      print 'Waiting for the import to complete...'
      time.sleep(10)

    if 'errors' in status['status']:
      print 'Error loading table: ', pprint.pprint(status)
      return

    print 'Loaded the table:' , pprint.pprint(status)#!!!!!!!!!!

    # Now query and print out the generated results table.
    queryTableData(service, targetProjectId, targetDatasetId, targetTableId)

   except HttpError as err:
    print 'Error in loadTable: ', pprint.pprint(err.resp)

The bq cp command does basically the same, internally (you could call that function too, depending on what bq you are importing).

A: Assume you want to copy most tables, you can first copy the entire BigQuery dataset, then delete some tables you don't want to copy.
The copy dataset UI is similar to copy table. Just click "copy dataset" button from the source dataset, and specify the destination dataset in the pop-up form. You can copy dataset to another project or another region. See screenshots of how to copy dataset below.
Copy dataset button

Copy dataset form

A: Now coping dataset feature available in BigQuery Data Transfer Service. Select transfer service in BigQuery web console and fill the source and destination details and run it on-demand or schedule it on specified time interval.

Or simply run following gcloud command to achieve this
bq mk --transfer_config --project_id=[PROJECT_ID] --data_source=[DATA_SOURCE] --target_dataset=[DATASET] --display_name=[NAME] --params='[PARAMETERS]'

A: I am not sure why it is not working for you, since it works perfectly for me.
projectFrom = 'project1'
datasetFrom = 'dataset1'
tableSearchString = 'test1'

projectTo = 'project2'
datasetTo = 'dataset2'

tables = bq.DataSet(projectFrom + ':' + datasetFrom).tables()

for table in tables:
  if tableSearchString in table.name.table_id:

    tableFrom = projectFrom + ':' + datasetFrom + '.' + table.name.table_id
    tableTo = projectTo + ':' + datasetTo + '.' + table.name.table_id

    !bq cp $tableFrom $tableTo

Try this in your notebook, since it works well for me.
Just wondering, what is the error code that returns from your script?

A: I think it would help you.
    tables = source_dataset.list_tables()
    for table in tables:
        #print table.name
        job_id = str(uuid.uuid4())
        dest_table = dest_dataset.table(table.name)
        source_table = source_dataset.table(table.name)
        if not dest_table.exists():
            job = self.bigquery_client.copy_table(job_id, dest_table, source_table)
            job.create_disposition = (google.cloud.bigquery.job.CreateDisposition.CREATE_IF_NEEDED)
            job.begin()
            job.result()

A: Why not use the CLI:
bq ls src_dataset | grep TABLE | cut -f 3 -d ' ' | xargs -I {} bq cp src_dataset.{} dst_dataset.{}

First, get a list of table names from the source dataset, then copy them to the destination.
If you want to see the commands before executing them put an echo at the beginning:
bq ls src_dataset | grep TABLE | cut -f 3 -d ' ' | xargs -I {} echo bq cp src_dataset.{} dst_dataset.{}


text:
Q: Evento OnDisconnected em SignaIR não funciona direito Galera, desenvolvi um chat de acordo com este link e tudo funcionou numa boa. Mas o evento disconnected não funciona direito.
O que acontece é que, de acordo com o link de referência, esse evento é disparado quando o usuário fecha a página, e assim notificando os usuários online que aquele usuário saiu do chat. Só que esse evento não está sendo chamado.
O que acontece é que se eu fecho a guia(a page) esse evento não é disparado e não avisa a sala que o usuário saiu, e mais, esse nome de usuário fica guardado e eu não consigo entrar no chat com o mesmo nome, mesmo quando fechada a guia e tentando abrir de novo.
Pra que eu consiga colocar o mesmo nome, eu preciso esperar o timeout default pra que todo o cookie do site seja excluído...
Será que alguém poderia me ajudar ?
Lembrando que todas os outros eventos funcionam, só esse que não
Aqui os códigos referentes ao evento:
Na classe que estendo HUB, o método OnDisconnected:
 public override Task OnDisconnected()
    {
        var name = dic.FirstOrDefault(x => x.Value == Context.ConnectionId.ToString());
        string s;
        dic.TryRemove(name.Key, out s);
        return Clients.All.disconnected(name.Key);
    }

- Aqui já um erro. Eu não posso usar o override :

'SignalIRChatMVC.Hubs.MyHub.OnDisconnected()': no suitable method found to override

O evento em javascript
chat.client.disconnected = function (name) {
            //Calls when someone leaves the page
            $('#chats').append('
' + name + ' saiu da sala
');
            $('#onlineList div').remove(":contains('" + name + "')");
            $("#users option").remove(":contains('" + name + "')");
        }

E aqui a div que usa pra fazer as manipulações de usuário online ou offline

Usuários online

A: Excepção
Relativamente à excepção, o método para fazer override do método da classe Hub tem a assinatura
public virtual Task OnDisconnected(bool stopCalled)
{...}

Assim, o seu override ficará:
public override Task OnDisconnected(bool stopCalled)
{...}

O método que menciona foi removido na última versão (veja aqui).
Vida de uma ligação SignalR
Relativamente ao fim da ligação, em SignalR a ligação pode ser terminada das seguintes formas:

*

*O cliente chama o método Stop e uma mensagem é enviada para o servidor a sinalizar o fim da ligação. A ligação é terminada imediatamente.

*A ligação entre o cliente e o servidor cai. O cliente vai tentar voltar a ligar e o servidor vai estar a espera do cliente. Se as tentativas de ligação falharem e o periodo de timeout for excedido, tanto o cliente como o servidor param de tentar.

*Se o cliente parar sem ter oportunidade de informar o servidor que vai desligar através do método Stop, o servidor espera pelo cliente durante um certo tempo. Se ao fim desse tempo a ligação não for restablecida, o servidor abandona a ligação pendente.

*Se o servidor parar, o cliente vai tentar ligar-se ao servidor durante um certo periodo de tempo. Se ao fim desse tempo a ligação não for restablecida, o cliente abandona a ligação pendente.

No seu caso, deveria prever a primeira situação e invocar o método Stop no seu cliente para ter a certeza que os outros utilizadores são informados que o cliente saiu do chat.
Timeouts de ligação
Relativamente aos timeouts, existem 3 distintos que controlam as ligações em SignalR:

*

*ConnectionTimeout: Tempo durante o qual uma ligação permanece aberta. O default são 110 segundos;

*DisconnectTimeout: Tempo esperado depois de uma ligação terminar antes de invocar o evento de desconexão. O default são 30 segundos.

*KeeepAlive: Tempo esperado entre cada pacote enviado numa ligação passiva. O default são 30 segundos. Se colocar este valor a null, não são enviados pacotes de KeepAlive. Se este tempo estiver activo (não nulo) o ConnectionTimeout é ignorado.

Se quiser alterar estes tempos pode fazê-lo da seguinte forma:
[assembly:OwinStartup(typeof (StartupConfig))]

namespace Test
{
    public class StartupConfig
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
            GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(50);
            GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromSeconds(50);
            GlobalHost.Configuration.KeepAlive = TimeSpan.FromSeconds(50);
        }
    }
}


text:
Q: How to I get rid of warning messages fo OCX's for an unverified publisher? I have a classic ASP application with downloads and installs several custom OCX files.
I keep getting a message that reads:
 This web page wants to run the following add-on: 'name.ocx'
 from 'my name (unverified publisher)'

Given that I'm running these web applications in-house and I don't want to go through the hassle of becoming a Verified Publisher for this legacy application; how can stop the messages from popping up on my users Internet Explorer the first time that they are download and installed?
Note: The website for this application is in my Trusted Zone - and I've enabled basically everything in the Active X settings for the Trusted Zone.

A: In the settings for the Trusted Zone; make sure that the "Only allow approved domains to use ActiveX without prompt" option has been set to disabled. Microsoft seems to have reversed the pattern with "what is the most permissive option" for that entry.


text:
Q: Firebase user ID token: when does it change? And how to listen to the updates/refreshes of it? TL;DR
After/at when does FirebaseUser.getIdToken() return a different value? (When does expiration/update happen?) And how do I monitor/listen to its updates?
The Setup
Our Android project needs to setup with a Firebase Project, where provides a bunch of APIs.
Most of APIs require user authentication token. We use Firebase User's ID token as header, like all of common projects:
Firebase.auth.currentUser?.getIdToken(false).addOnSuccessListener {
    it.token?.let { token -> callAPI(token) }
}

fun callAPI(token: String) {
    val header = "Bearer $token"
    // call out API
}

To manage functions, we split them into several parts, including User Repo and API modules. Due to this setup, I'd like to lazy-update the token (using an Interceptor etc.) -- whenever the token updates, updates Interceptor's header set.
However, I got myself lost in the documentation...
What is ID token?
Firebase provides too many kinds of token, which confuses me a lot.
To narrow it down, I'd like to know which token means, or is equal to FirebaseUser.getIdToken().
The most possible answer lays in Firebase Auth User Documentation:

*

*"Current user's access token", which is refreshed when (1) token expires (when...?) (2) user changes password (3) user re-authenticate

*The "refresh token" which appears in the same paragraph.

*"Firebase ID token": It might be the one most obvious same to getIdToken. However the doc only pointed out that these tokens are "signed JWTs" and does not indicate when will it expire/update.

Which of above is equal to FirebaseUser.getIdToken()?
When does ID Token expire/update?
As described above, if "access token" is equal to ID Token, does that mean:

*

*ID token will expire (at when?) and it is a very common situation?

*When user changes password, ID token will also update?

*When user re-authenticate (including login, logout, register?), ID token will also update?

Also another most-resulted one doc in my search is Firebase Admin's Manage User Sessions.

*

*The doc indicates that ID token is short lived and last for an hour -> Does that mean ID token always expire/refresh after around 1 hour?

The doc also tells when does refresh token expire, such as user deleted/disable/email or password changed. However I don't think those situation apply to ID token's expiration...?
How do I monitor/listen to refresh/updates?
All of above questions can actually be ignored. What I care most is -- how do I listen (detects) when the token is updated?
As far as I know, only function I found is
firebaseUser.getIdToken(false)

Which returns a Task, and doesn't really works much like a lifetime-listener.
I found another one function:
Firebase.auth.addIdTokenListener(FirebaseAuth.IdTokenListener { firebaseAuth ->
    // do something with firebaseAuth...?
})

However I don't know how to use it. Should I call firebaseUser.getIdToken inside?
I'm looking forward something like
firebaseUser.addOnIDTokenRefreshListener

but I can't find it. Is there anything I missed?

That's all of my question. Any information/clarification/experience will help me a lot. Thanks.

A: ID tokens in Firebase are short-lived tokens that are valid for an hour after they are minted. About 5 minutes before the current ID token expires, the Firebase SDKs request a new token from the serve and start using that. At this point they also notify any ID token listeners that were registered by calling addIdTokenListener.
When the Firebase SDKs themselves need the ID token to send it with a call to the server, they call getIdToken() and pass the value along. Since most server-side calls are fairly short, the current ID token will be valid long enough for that call to complete, and is also what I'd recommend for most use-cases others may have for getting and passing the ID token. Monitoring the ID token or forcing a refresh are (or at least should be) relatively uncommon in comparison.

A: Time has passed and I finally collected enough info.
Let's talk about Firebase ID Token:

*

*When does it expire/update?

*How do I monitor/listen to its refresh/updates?

*What is it?

When does Firebase ID Token expire/update?
From

*

*Answer of @Frank van Puffelen

*Firebase Doc for Admin: Manage User Sessions

*Reference of Firebase.addIdTokenListener
Firebase ID tokens are short lived, and will be refreshed when:

*

*after 1 hour

*user signs in

*user signs out

*user changes password

*user requires a force-refresh (by executing getIDToken(true))

*other firebase event, like "user changes"
The procedure seems controlled by Firebase system. The time listed above might not cover all the cases.
How do I monitor/listen to refresh/updates?
Due to the propose of Firebase ID token, you are not suggested to "listen to its changes automatically".
It's suggested to get token dynamically, by calling user.getIdToken().
However, if you really want to monitor it, you may use FirebaseAuth.addIdTokenListener. Note that user (as well as IdToken ) might not always exist in this listener:
Firebase.auth.addIdTokenListener(FirebaseAuth.IdTokenListener { auth ->
    Log.v("AUTH", "token Listener: triggers when user is ${auth.currentUser?.uid}")
    auth.currentUser?.run {
        getIdToken(false).addOnSuccessListener {
            Log.v("AUTH", "token Listener: current token is ${it.token}")
        }.addOnFailureListener {
            Log.w("AUTH", "token Listener: failed getting token.", it)
        }
    }
})

Also note that calling getIdToken(true) would ALWAYS refresh ID token.
Bonus: What is ID Token?
Firstly one have to know that, ID token, refresh and access token is NOT invented by Firebase. It's from the Network framework and protocol -- ID token is from Open ID Connect, and others from OAuth 2.0.
I'm not an expert in Network, so I'll just brief explain it from my understanding:

*

*ID Token: always encoded as JWT (JSON Web Token). Provides the identity of user. However it is not very safe as it might be stolen/copied, thus not suggested to be used in API.

*Access Token: no strict format (can also be JWT), but is limited, dynamic token generated (by server) from client request. Have many ways to keep safety, thus suggested to be used in API.

*(and a Refresh Token is sent from server, used by client/server, to refresh the Access Token.)

(I recommend a comparison article of these 2 tokens, very clear and helpful.)
However, there're differences in Firebase. In all articles I found, they all indicate that: when you need an access token in Firebase, you should call FirebaseUser.getIdToken(). And it's dynamic, with refreshing mechanism, and you can refresh it from client.
Considered the definition above, I feel like that in Firebase, Firebase (Auth) ID Token behaves more like Access Token defined in OAuth 2.0, not ID Token defined in Open ID Connect.
That's all I got so far. Hope it helps the future googlers.


text:
Q: Update Hyperlink In Gridview not working Gridview is not working when user click on the link. User is supposed to be directed to another page when clicked on the link and on the second page, there is a text box that will allow user to update.
this is my code for grid view:
 <asp:BoundField DataField = "status" HeaderText = "Status"  HtmlEncode = "true"  ItemStyle-Width="150px" >
       <ItemStyle Width="50px" />
 </asp:BoundField>
 <asp:ButtonField ButtonType="Link" Text="Click"  CommandName="Select"  HeaderText="Details"   />
 <asp:ButtonField HeaderText="Update" Text="update?" CommandName="GridView1_RowUpdated" />

code behind:
 Protected Sub GridView1_RowUpdated(sender As Object, e As GridViewUpdatedEventArgs)
    Dim cr_number As String = GridView1.SelectedRow.Cells(0).Text
    Response.Redirect("upddetail.aspx?id=" + cr_number)
End Sub

A: You are using ButtonField not an actual hyperlink. When user clicks on this there will be a postback to your original page and it will not navigate to another page. Try using HyperLink.

A: since you are set the CommandName as GridView1_RowUpdated you can use GridView1_RowCommand event as below
  Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)

    If e.CommandName = "GridView1_RowUpdated" Then
       Dim index As Integer = Convert.ToInt32(e.CommandArgument)
      Dim cr_number As String = GridView1.Rows(index).Cells(0).Text
      Response.Redirect("upddetail.aspx?id=" + cr_number)
    End If

  End Sub

in your aspx page set onrowcommand as below
 <asp:gridview id="GridView" onrowcommand="GridView1_RowCommand"

instead of all above you can use hyperlinkfield
<asp:hyperlinkfield text="Update?"
            datanavigateurlfields="Id"
            datanavigateurlformatstring="~\upddetail.aspx?id={0}"
            headertext="Update"
            target="_blank" />


text:
Q: Pass simple numpy array to C via SWIG I want to pass numpy array of known size and type via SWIG to C function
# .py
data = numpy.arange( N , dtype=numpy.int32 )
external_c_function( data )

# .i
extern void external_c_function( int32_t* data );

# .c
void external_c_function( int32_t* data)
{
    // ...
}

Unfortunately, I will get an error:
TypeError: in method 'external_c_function', argument 1 of type 'int32_t *'

What is the easiest way to pass numpy array to SWIG?

A: You can use numpy.i. Just have a look at http://www.scipy.org/Cookbook/SWIG_NumPy_examples


text:
Q: django 1.7: allow_empty_file not working in ImageField I can't get my Django form to make an ImageField optional.
If I do this
class TestUploadForm(forms.Form):
    pic_upload=forms.ImageField(allow_empty_file=True)
form2=TestUploadForm(request.POST,request.FILES)
pdb.set_trace()

and then pass a file to it, it is happy:
(Pdb) request.FILES
<MultiValueDict: {u'pic_upload': [<InMemoryUploadedFile: test2.png (image/png)>]}>
(Pdb) form2.is_valid()
True

if I don't pass a file to it, it doesn't validate although allow_empty_file is set to True:
(Pdb) request.FILES
<MultiValueDict: {}>
(Pdb) form2.is_valid()
False

If I put blank=True instead of allow_empty_file=True, I get an error:
__init__() got an unexpected keyword argument 'blank'

So what's wrong?

A: It should be
pic_upload = forms.ImageField(required=False)

blank=True is used in model definition, not forms.

A: You are getting the error when you put blank=True  because it is a form field, not a model field. Use required=False instead.


text:
Q: NetworkManager is APSupported I want to consume a service. I am 100% sure that this service works correctly.
Service call
public void add(User user) {
ConnectionRequest con = new ConnectionRequest();

String url="http://localhost/NY/untitled/web/app_dev.php/user/new"
+ "?Fonctionuser="+user.getUserFunction()
+"&Fullname="+user.getUserName()
+"&Imageproduit="+user.getUserImage()
+"&Latitude="+user.getLatitude()
+"&Longitude="+user.getLongitude()
+"&State="+user.getUserState();
System.out.println(user.getUserState());

con.setUrl(url);
NetworkManager.getInstance().addToQueue(con);
}

Error
Exception in thread "main" java.lang.NullPointerException
at com.codename1.io.NetworkManager.isAPSupported(NetworkManager.java:866)
at com.codename1.io.ConnectionRequest.<init>(ConnectionRequest.java:330)
at Services.UserServices.add(UserServices.java:18)
at Services.Main.main(Main.java:30)

Main method
public static void main(String[] args) {
  User user = new User();
  user.setLatitude(111);
  user.setLongitude(111);
  user.setUserFunction( UserFunction.Client.ordinal());
  user.setUserImage("uezfniez");
  user.setUserState((int)UserState.Hold.ordinal());
  user.setUserName("jamel");
  UserServices userServices = new UserServices();
  userServices.add(user);
}

A: It seems you nedd to write your code in an Action Listener
registerButton.addActionListener(e -> {
        con.setUrl("http://localhost/NY/untitled/web/app_dev.php/user/"
                + "new?Fonctionuser=2&Fullname=jamel&Imageproduit=uezfniez&Latitude=111&Longitude=111&State=2");
        NetworkManager.getInstance().addToQueue(con);
    });

A: I'm guessing that you invoked that code from the constructor or a static initializer which means the implementation of Codename One didn't finish initializing. No code that relies on implementation should be executed before the init(Object) method is invoked.
Action listeners happen well after that point and would thus work well in this case.


text:
Q: How can I transfer objects in buckets between two aws accounts with python? I need to transfer all objects of all buckets, with the same folders and buckets structures, from an aws account to another aws account.
I've been doing it with this code through aws cli, one bucket at a time:
aws s3 sync s3://SOURCE-BUCKET-NAME s3://DESTINATION-BUCKET-NAME --no-verify-ssl

Can I do it with python for all objects of all buckets?

A: The AWS CLI actually is a Python program. It includes multi-threading to copy multiple objects simultaneously, so it will likely be much more efficient than the equivalent Python program you can make yourself.
You can tweak some settings that might help: AWS CLI S3 Configuration — AWS CLI Command Reference
There is no option to copy "all buckets" -- you would still need to sync/copy one bucket at a time.
Another approach would be to use S3 Bucket Replication, where AWS will replicate the buckets for you. This now works on existing objects. See: Replicating existing objects between S3 buckets | AWS Storage Blog
Or, you could use S3 Batch Operations, which can take a manifest (a listing of objects) as input and then copy those objects to a desired destination. See: Performing large-scale batch operations on Amazon S3 objects - Amazon Simple Storage Service

A: aws s3 sync is a high level functionality not available in AWS SDKs such as boto3. You have to implement it yourself on top of boto3 or search though many available code snippets that already implement that, such as python - Sync two buckets through boto3 - Stack Overflow.


text:
Q: How to create a cost matrix? I need to create a cost matrix and a trace like in the image below. I found nothing that seemed up to the task in the matrix package. Is this possible in LaTeX?

A: There are a lot of different packages and therefore a lot of possibilities to do this. Here is one with the matrix library of the TikZ package.
Update 1 : problem on a arrow
The first code reverses an arrow and I haven't figured out why yet. To correct this, the code becomes heavier.

\documentclass[border=5mm,tikz]{standalone}
\usetikzlibrary{matrix,arrows.meta}
\begin{document}
\begin{tikzpicture}[>={Stealth[length=4pt]}]
\matrix (cost)[matrix of nodes,nodes in empty cells]
{ & & B & A & B & A & A & A \\
  & 0 & 1 & 2 & 3 & 4 & 5 & 6\\
A & 1 & 2 & 1 & 2 & 3 & 4 & 5\\
B & 2 & 1 & 2 & 1 & 2 & 3 & 4 \\
A & 3 & 2 & 1 & 2 & 1 & 2 & 3\\
B & 4 & 3 & 2 & 1 & 2 & 3 & 4\\
B & 5 & 4 & 3 & 2 & 3 & 4 & 5\\
B & 6 & 5 & 4 & 3 & 4 & 5 & 6\\
};
\draw (cost-1-8.south east) -| (cost-8-1.south east)-| cycle;
\draw (cost-2-8.south east) -| (cost-8-2.south east);
\foreach \x/\y [remember =\x as \lastx (initially 8),remember=\y as \lasty (initially 8)] in {7/7,6/6}{
 \draw[->,shorten <=-3pt,shorten >=-3pt](cost-\lastx-\lasty)--(cost-\x-\y);
 }

 \draw[<-,shorten <=-3pt,shorten >=-3pt] (cost-6-6)--(cost-5-6);
\foreach \x/\y [remember =\x as \lastx (initially 5),remember=\y as \lasty (initially 6)] in {4/5,3/4,2/3,2/2}{
 \draw[->,shorten <=-3pt,shorten >=-3pt](cost-\lastx-\lasty)--(cost-\x-\y);
 }
\end{tikzpicture}

\end{document}

\documentclass[border=5mm,tikz]{standalone}
\usetikzlibrary{matrix,arrows.meta}
\begin{document}
\begin{tikzpicture}[>={Stealth[length=4pt]}]
\matrix (cost)[matrix of nodes,nodes in empty cells]
{ & & B & A & B & A & A & A \\
  & 0 & 1 & 2 & 3 & 4 & 5 & 6\\
A & 1 & 2 & 1 & 2 & 3 & 4 & 5\\
B & 2 & 1 & 2 & 1 & 2 & 3 & 4 \\
A & 3 & 2 & 1 & 2 & 1 & 2 & 3\\
B & 4 & 3 & 2 & 1 & 2 & 3 & 4\\
B & 5 & 4 & 3 & 2 & 3 & 4 & 5\\
B & 6 & 5 & 4 & 3 & 4 & 5 & 6\\
};
\draw (cost-1-8.south east) -| (cost-8-1.south east)-| cycle;
\draw (cost-2-8.south east) -| (cost-8-2.south east);
\foreach \x/\y [remember =\x as \lastx (initially 8),remember=\y as \lasty (initially 8)] in {7/7,6/6,5/6,4/5,3/4,2/3,2/2}{
 \draw[->,shorten <=-3pt,shorten >=-3pt](cost-\lastx-\lasty)--(cost-\x-\y);
 }

\end{tikzpicture}

\end{document}

A: With nicematrix:
\documentclass{article}
\usepackage{nicematrix}
\usepackage{tikz}
\begin{document}

\renewcommand{\arraystretch}{1.2}

\begin{NiceTabular}{|ccccccc|}[first-row,first-col]
  &   & B & A & B & A & A & A \\
\hline
  & 0 & 1 & 2 & 3 & 4 & 5 & 6\\
A & 1 & 2 & 1 & 2 & 3 & 4 & 5\\
B & 2 & 1 & 2 & 1 & 2 & 3 & 4\\
A & 3 & 2 & 1 & 2 & 1 & 2 & 3\\
B & 4 & 3 & 2 & 1 & 2 & 3 & 4\\
B & 5 & 4 & 3 & 2 & 3 & 4 & 5\\
B & 6 & 5 & 4 & 3 & 4 & 5 & 6\\
\hline
\CodeAfter
\begin{tikzpicture}
\draw (8-|2) |- (2-|8) ;
\begin{scope}[->,shorten < = 1pt, shorten > = 1pt]
\draw (1-2) -- (1-1) ;
\draw (2-3) -- (1-2) ;
\draw (3-4) -- (2-3) ;
\draw (4-5) -- (3-4) ;
\draw (5-5) -- (4-5) ;
\draw (6-6) -- (5-5) ;
\draw (7-7) -- (6-6) ;
\end{scope}
\end{tikzpicture}
\end{NiceTabular}

\end{document}

A: A solution for both images, based  on ordinary tabulars and the help of pstricks for the connections:
\documentclass[table]{article}
\usepackage{array}
\usepackage{tabularx}
\usepackage{xcolor}
\usepackage{pst-node, multido}

\begin{document}

\sffamily\setlength{\extrarowheight}{3pt}
\begin{tabularx}{\linewidth}{XX}
 { \begin{tabular}[t]{c|c|*{6}{c}|}
\multicolumn{3}{c}{}B & A & B & A & A & \multicolumn{1}{c}{A} \\
\cline{2-8}
 & \multicolumn{1}{c}{\rnode{8}{0}} & \rnode{7}{1} & 2 & 3 & 4 & 5 & 6 \\
 \cline{3-8}
 A & 1 & 2 & \rnode{6}{1} & 2 & 3 & 4 & 5 \\[2pt]
 B & 2 & 1 & 2 & \rnode{5}{1} & 2 & 3 & 4 \\[2pt]
 A & 3 & 2 & 1 & 2 & \rnode{4}{1} & 2 & 3 \\[2pt]
 B & 4 & 3 & 2 & 1 & \rnode{3}{2} & 3 & 4 \\[2pt]
 B & 5 & 4 & 3 & 2 & 3 & \rnode{2}{4} & 5 \\[2pt]
 B & 6 & 5 & 4 & 3 & 4 & 5 & \rnode{1}{6} \\
\cline{2-8}
\end{tabular}
\psset{arrows=->, arrowinset=0.12,linejoin=1, nodesep=1pt}
\multido{\is=1+1,\it=2+1}{7}{\ncline{\is}{\it}}}
 &
{\Large Trace\bigskip}\newline
{\setlength{\tabcolsep}{8pt}\begin{tabular}[t]{*{6}{c}}
  A & B & A & B & B & B \\[-1ex]
\pnode{U1} & \pnode{U2} & \pnode{U3} & & \pnode{U4} & \pnode{U5}\\[1em]
 & \pnode{D1} & \pnode{D2} & \pnode{D3} & \pnode{D4} & \pnode{D5}\\
B & A & B & A & A & A
\end{tabular}}
\multido{\i=1+1}{5}{\ncline{D\i}{U\i}}
\end{tabularx}

\end{document}


text:
Q: How do I make the 'tasks' in my web app editable? When I press 'update' nothing happens. As there are more than one instances of the 'tasks', which is circled enter image description here). By the way, I am using sequelize as my backend.
The link to my code is:https://glitch.com/edit/#!/gunna-submit-this

A: If you want to edit or update tasks on your page you could try this tutorial,if you find a way to implement this in your project is going to work ,comes in 2 chapters:
https://medium.com/@diogo.fg.pinheiro/simple-to-do-list-app-with-node-js-and-mongodb-chapter-1-c645c7a27583
https://medium.com/@diogo.fg.pinheiro/simple-to-do-list-app-with-node-js-and-mongodb-chapter-2-3780a1c5b039
In chapter 2 you learn about the delete and edit button.


text:
Q: Length of location sequence (given as a string) in R I have a list of geolocation sequences. Each element of my list is of the form :
> "[[1.2,2.2],[-1.12,3.45],[12.311,-1.34],[-12.32,33.333]]"

I would like to be able to get the length of the sequence (4 in the example above). Could you please help me? I've tried to use regular expressions but I couldn't succeed.
Thank you in advance!

A: As a few folks suggested in the comments, you can count the # of times a specific character appears in your sequences. This assumes the data are well formed and consistent. For example:
library(stringr)
x <- "[[1.2,2.2],[-1.12,3.45],[12.311,-1.34],[-12.32,33.333]]"
str_count(x, "\\[") - 1 #subtract 1 since there are two opening [

yields:
> str_count(x, "\\[") - 1
[1] 4

A: In case you do not want to load a library
str <- "[[1.2,2.2],[-1.12,3.45],[12.311,-1.34],[-12.32,33.333]]"
nchar(str)-nchar(gsub("\\]", "", str))-1

A: You can use:
\[[^[]

And then count the matches.
Demo
In R:
> x <- "[[1.2,2.2],[-1.12,3.45],[12.311,-1.34],[-12.32,33.333]]"
> length(gregexpr("\\[[^\\[]",x)[[1]])
[1] 4


text:
Q: PHP support in Glassfish 4 I have read in some blog comment that newer versions of glassfish has inbuilt PHP support, is this true?
I am using Glassfish 4 and trying to make wordpress work on it. For this I am trying to use quercus from http://quercus.caucho.com/ but things does seems to work right. I have submitted a question for the same Exception: WELD-000071 Managed bean class com.caucho.jms.MemoryQueue must be @Dependent while installing Quercus on Glassfish
If glassfish 4 has inbuilt PHP support then I do not need to use quercus. If its true, please guide me how to set up a PHP website in glassfish

A: GlassFish 4 does not have built-in PHP support, nor are there plans to add PHP support in the future.


text:
Q: How to create a report subscription in SSRS which passes today's date to paramters? I created a report with a StartDate and EndDate parameter. If I want to see the information for a single day, I use the same Date in both parameters. I now want to create a subscription for this report so that it runs everyday. How can I use the current date and pass it to these parameters when the report runs? Thanks!

A: EDIT: This will only work with Enterprise edition.
First, write a query that gets the current date and formats it to match the VALUE in your parameter (for example, is it DD-MM-YYYY, YYYY-MM-DD?). Make sure to name your column something meaningful like "CurrentDate".
select cast(current_timestamp as date) as CurrentDate

Then create a new subscription for your report. Instead of Standard Subscription, choose data driven subscription. Now select your SQL datasource and paste in your query. Press validate to make sure it runs fine. Hit OK.
Now you can go down to your subscription parameters at the very bottom of the page. Set Source of Value to be "Get value from dataset" then pick your "CurrentDate" from the drop down.
That's it, data driven subscription with current date.

A: Step 1: You will have your defaultDates dataset as so. can be query or you can wrap it as a Stored proc.
Select TodaysDate = cast(getdate() as date)

Step 2: then , under default values for both the params you will anchor get value from dataset and point to this dataset, which is defaultDates.
Step 3: test it locally. Make sure to delete .DATA from your working directory to enforce fresh data.
Step 4: build and deploy to whatever test location.


text:
Q: Can I use "Dynamics CRM PHP Connector" library for Microsoft Dynamics CRM? Is "Dynamics CRM PHP Connector" library created to make a connection with Microsoft Dynamics CRM? OR it is just a library to connect to PHP sources?
If it can get connected to Microsoft Dynamics CRM, How? Could you help me in detail? Because the basic help exists but I want a complete documentation.
I don't know the structure of Microsoft Dynamics CRM, so I asked if it can be used by ReST actions or I must use SOAP only? I want to create a form for example in my website, and then when I click submit in my site, I want it to be added to Microsoft Dynamics CRM Database too. So there are two approaches: 1. To use SOAP 2. to use ReST. Can I use ReST or not? I have searched and have found out that in order to send data to database in CRM, I must write bunch of code in PHP. So I decided to use some library like "Dynamics CRM PHP Connector", but its documentation is partial. Can you help me?


text:
Q: How can I unit test my JavaScript code in a way that allows it to be used in a website? I have built a web app and I am trying to build out an automated unit testing suite so that I can more easily refactor the code.
I have javascript code that functions correctly on my website. Simple hypothetical code:
function timesTwo(x){x*=2;return x}

If I were writing my code for NodeJS I would add the tests to confirm that the code is working correctly. Below is an example using Wish and Mocha:
describe('timesTwo()', function() {
  it('multiplies by two', function() {
    var result = timesTwo(5);
    wish(result === 10);
  });
});

This code (including tests) works fine if I run it in node.JS to test it, but now it throws errors in my browser:
require is not defined

describe is not defined

wish is not defined

How can I create an automated test suite for my code in a way that doesn't throw errors in the browser?

A: If I'm not mistaken you're also loading the test code into your browser.
The thing is that require isn't something that's available in your browser. This means that the functions like describe and wish are simply not available since the require didn't include any code.
What you should do is keep the tests separate from your application code and only load the application code into your website. How you do this depends on your build system, template engine, etc


text:
Q: Simple python folders/subfolders import example I have this simple project structure:
    main
        __init__.py
        animal.py (class Animal)
        sub1
            __init__.py
            cat.py (class Cat)
        sub2
            __init__.py
            dog.py (class Dog)

Each __init__.py file is empty.
So,

*

*from dog.py I need to import Animal class

Using this syntax:
from animal import Animal

I got
ImportError: No module named animal

*

*from dog.py I need to import Cat class in sub1.cat module

Using this syntax:
from sub1.cat import Cat

I got
ImportError: No module named sub1.cat

How can I do this?


text:
Q: How do I read a string sent from PHP through a socket to a Qt server application? I am having a really hard time reading character input that is sent through a socket connection to a Qt server application. The data is sent from PHP.
I understand the principles of reading streamdata because I already asked this on stack. I also got it working using a server and client written both in Qt.
The method I use is to append the bytesize of the data i want to send before the actual data. Then when the data comes in, I first read the length parth so that I know exactly how much bytes I have to read in order to have correctly formed data.
it looks like this:
send function:
void Client::sendNewMessage(){
    qDebug() << "sendNewMessage()";

    QString string(messageLineEdit->text());

    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);
    out << quint16(0);
    out  << string;
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));

    tcpSocket->write(block);
}

receive function:
QDataStream in(tcpServerConnection);
in.setVersion(QDataStream::Qt_4_0);
qDebug() << "bytes available = " << tcpServerConnection->bytesAvailable();

if (blockSize == 0) {
    int size = (int) sizeof(quint16);
    qDebug() << "size = " << size;
    if (tcpServerConnection->bytesAvailable() < (int)sizeof(quint16)){
        qDebug() << "less bytes than size...";
        return;
    }
    qDebug() << "bytes available=" << tcpServerConnection->bytesAvailable();
    in >> blockSize;
}

if (tcpServerConnection->bytesAvailable() < blockSize){
    qDebug() << "less bytes available than blocksize, bytes="
                   << tcpServerConnection->bytesAvailable();
    return;
}

QString data;
in >> data;
qDebug() << "data = " << data;

Okay, this all works so I tried doing it with PHP but it failed
this is one of my attempts:
<?php

$addr = gethostbyname("127.0.0.1");

$client = stream_socket_client("tcp://$addr:*****", $errno, $errorMessage);

if ($client === false) {
    throw new UnexpectedValueException("Failed to connect: $errorMessage");
}

$data = 'a';
$datatopost = serialize($data);

fwrite($client, strlen($data));
fwrite($client, base64_encode($data));
echo stream_get_contents($client);
fclose($client);

In Qt I have tried various combinations of quint8, 16, 32, 64, sizeof(char), sizeof(int).
in PHP I have tried serializing the data, encoding it, and also sending it without all that stuff. But i can not get it to work. I must be very close though because the data is actually sent as there are bytes available but I have no idea how to encode/decode correctly for it to work.
After asking various question concerning this topic I do feel that my understanding has gone up a lot but an important piece of information on how to actually do things is still missing for me.
So my question: What is going wrong here and what steps need to be taken to be able to read data from PHP to Qt/C++?
Details are highly apreciated as I really like to know how things work from the inside out.
side-note after sending data from the PHP script, the server sends data back aswel and that works. So the connection is made succesfuly
UPDATE
this is the working php script that actually also receives a reply back:
<?php

if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
    perror("Could not create socket");
}
echo "Socket created n";

//Connect socket to remote server
if(!socket_connect($sock , '127.0.0.1' , *****))
{
    perror("Could not connect");
}
echo "Connection established n";

$message = "aa";
//Send the message to the server
if( ! socket_send ( $sock , $message , strlen($message) , 0))
{
    perror("Could not send data");
}
echo "Message send successfully n";

//Now receive reply from server
if(socket_recv ( $sock , $buf , 500 , MSG_WAITALL ) === FALSE)
{
    perror("Could not receive data");
}
echo $buf;

///Function to print socket error message
function perror($msg)
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("$msg: [$errorcode] $errormsg n");
}

The script reply when executed from browser url:
Socket created nConnection established nMessage send successfully n hello

A: Do you need data serialization for this task at all? Your PHP client and Qt server are probably using different formats for it.
Try to send and receive raw data.
Here is a simple QTcpServer exmaple:
class DataReceiver : public QObject
{
    Q_OBJECT
public:
    explicit DataReceiver(QObject *parent = 0);

public slots:
    void start(quint16 port = 9090);

private slots:
    void newTcpConnection();

private:
    QTcpServer server;
};

DataReceiver::DataReceiver(QObject *parent) :
    QObject(parent)
{
    connect(&server, SIGNAL(newConnection()), this, SLOT(newTcpConnection()));
}

void DataReceiver::start(quint16 port)
{
    bool isOk = server.listen(QHostAddress::Any, port);

    if (isOk && server.isListening())
    {
        qDebug() << "QTcpServer started on port" << port;
    }
    else
    {
        qCritical() << "Failed to start QTcpServer";
    }
}

void DataReceiver::newTcpConnection()
{
    qDebug() << "New incoming connection";

    QTcpSocket *socket = server.nextPendingConnection();

    QByteArray data;

    while (true)
    {
        QByteArray tmp = socket->readAll();
        data += tmp;

        if (tmp.isEmpty() && !socket->waitForReadyRead())
        {
            break;
        }
    }

    socket->deleteLater();

    qDebug("Data received: %s (len = %d)", data.constData(), data.length());
}

Launching server:
#include <QCoreApplication>

#include "data_receiver.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    DataReceiver d;
    d.start();

    return a.exec();
}

You can use a PHP client to send data to it:
<?php

$addr = gethostbyname("127.0.0.1");
$port = 9090;
$data = 'hello from php';

$client = stream_socket_client("tcp://$addr:$port", $errno, $errorMessage);

if ($client === false) {
    throw new UnexpectedValueException("Failed to connect: $errorMessage");
}

fwrite($client, $data);
fclose($client);

Or you can use the nc utility:
echo -n "hello from nc" | nc 127.0.0.1 9090

Here is server output for both cases:
QTcpServer started on port 9090
New incoming connection
Data received: hello from php (len = 14)
New incoming connection
Data received: hello from nc (len = 13)

A: It's not that surprising the PHP code does not integrate. As mentioned you have to be aware that QDataStream implements a custom serialization. And as also mentioned you probably want to use (read|write)RawData, or (read|write)Bytes, if your reading something not previously serialized with QDataStream in general. However, the general idea of the way your trying to write string data from PHP should be compatible with the way Qt encodes strings (length then a series of characters. That is what the manual says anyway..). But there some issues.

*

*QString is 2Byte Unicode.

*PHP Strings are byte arrays of an arbitrary kind of ASCII compatible data - PHP String details.

*There is a few things wrong with this bit:
fwrite($client, strlen($data));
fwrite($client, base64_encode($data));

strlen() returns the number of bytes in the underlying storage (which is the actual byte length for a ASCII string). base64_encode() changes the number of bytes in the string. And your assuming fwrite() is writing a four byte integer. Its type casting and writing a string.

*We are still guessing at how
QString data;
in >> data;

really works.
General advice is, you've got to carefully define external binary APIs.


text:
Q: Unable to load client print control in report view I have developed report using SSRS 2005 and deployed in server.
Server : Windows Server 2008 R2.
SQL : SQL Server 2005
When I click on print button of report it shows Unable to load Client Print Control. It Work in IE8. We are trying in IE11
I have tried following things :
Extracted the files from RSClientPrint.cab from Report server and put it in C:\Windows\Downloaded ProgramFiles and then register the dll. Also I have copied all those files in C:\Windows\System32 and registered the same.
Also installed SQL Server Service Pack Update and ReportViewer Service Pack Update
Still I am getting the same error in Server as well as client machine.
Any help will be appreciated.

A: I bet this is do with Security Settings for downloading/scripting controls etc in Internet Explorer. I'm fairly sure that IE later than v8 changed the defaults.
Do you remember getting a prompt the first time you used the report in IE8?
Try adding your site to the Trusted Sites list.
EDIT
My updated suggestion is to install Microsoft Report Viewer 2015 Runtime.


text:
Q: Blinking LED on MPLAB not Working ? am using MPLAB to program my new microchip board and programming it programming it using pickit3
code:
// Include the necessary device header file
#include <p18f8722.h>

#pragma config OSC = HSPLL, //OSCS = OFF // HS-PLL Enabled, Internal External Osc. Switch Over OFF Disabled
#pragma config PWRT = OFF // Power Up Timer: OFF Disabled
//#pragma config BOR = OFF, BORV = 25 // Brown Out Reset: OFF, Brown Out Voltage: OFF Disabled
#pragma config WDT = OFF, WDTPS = 128 // Watchdog Timer: OFF Disabled, Watchdog Postscaler: 1:128
//#pragma config CCP2MUX = OFF // CCP2 Mux: OFF Disabled (RB3)
//#pragma config STVR = OFF // Stack Overflow Reset: OFF Disabled
#pragma config LVP = OFF // Low Voltage ICSP:OFF Disabled
#pragma config DEBUG = ON // Background Debugger Enable: OFF Disabled
#pragma config CP0 = OFF, CP1 = OFF, CP2 = OFF, CP3 = OFF // Code Protection Block 0-3: OFF Disabled
#pragma config CPB = OFF // Boot Block Code Protection: OFF Disabled
#pragma config CPD = OFF // Data EEPROM Code Protection: OFF Disabled
#pragma config WRT0 = OFF, WRT1 = OFF, WRT2 = OFF, WRT3 = OFF // Write Protection Block 0-3: OFF Disabled
#pragma config WRTB = OFF // Boot Block Write Protection: OFF Disabled
#pragma config WRTC = ON // Configuration Register Write Protection: OFF Disabled
#pragma config WRTD = OFF // Data EEPROM Write Protection: OFF Disabled
#pragma config EBTR0 = OFF, EBTR1 = OFF, EBTR2 = OFF, EBTR3 = OFF // Table Read Protection Block 0-3: OFF Disabled
#pragma config EBTRB = OFF // Boot Block Table Read Protection: OFF Disabled

// Function prototypes
void delay1(void);

// Main code section. Execution starts here.
void main(void){
 // First some setup code for the LED
 // The LED will be driven by port D, bit 0, driving the anode, cathode to ground

 // First we should clear the port D, bit 0 data latch
 LATDbits.LATD0=0;

 // We need to set port D, bit 0 as an output
 // Using TRISDbits instead of TRISD allows isolating a single bit leaving the other bits unchanged
 TRISDbits.TRISD1=0; // 0 = output, 1 = input

 // Set port D, bit 0 to off (driving the LED anode, cathode to ground)
 PORTDbits.RD1=0;

 // LED blinking loop that never ends since '1' never changes
 while(1){
 PORTDbits.RD1=1; // turn the LED on
 delay1(); // call the delay function
 PORTDbits.RD1=0; // turn the LED off
 delay1(); // call the delay function
 }
 // end of main, but we will never get this far (endless loop)
}

// Start of our functions
void delay1(void){
 /*
 It is important to note that all variable declarations need to be placed before any code in
 a function or the build will fail.
 */
 // declare a long integer and set it to zero
 long int loop1=0;

 // count from zero to 30,000 then continue on
 // Lower than 30000 for a faster blink, higher for a slower blink.
 for(loop1=0;loop1<=30000;loop1++){

 }
 // The loop is done and execution has moved past the loop
}

this code didn't do anything , it compiled perfectly on high tech C compiler but it didn't workout as it was expected ,
maybe the problem is in the configuration bit ? any idea how to solve this ?

A: Judging by the controller and port, I am guessing that you are using the PIC18 Explorer board.  If so, please verify that jumper JP1 is in place.  This must be in place when using the onboard LED's.
If it is not this board, then could you be using the wrong port?  For instance, the "low pin count" demo board I received with my pickit has the LED's on port C, not D.

A: Check if that pin also has an analog capability (ANx).
If it's the case, analog is the default setting and you cannot drive the pin. You should set it in digital mode first.


text:
Q: Extraer Descripción de cuenta de twitter (no los twitter ni los nº de twitter) Scrapeando Quiero extraer el texto que da una descripción de una cuenta de Twitter, pero no logro acceder, lo único que he logrado es extraer el número de seguidores, pero no logro saber cómo llegar al texto que describe la cuenta de Twitter.
Me imprime el número de seguidores, pero no logro imprimir la descripción.
Código:
import requests
from bs4 import BeautifulSoup

USER_AGENT = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}

def obtener_resultados(termino_busqueda, numero_resultados, codigo_lenguaje):
    url_google = 'https://www.google.com/search?q={}&num={}&hl={}'.format(termino_busqueda, numero_resultados, codigo_lenguaje)
    respuesta = requests.get(url_google, headers=USER_AGENT)
    respuesta.raise_for_status()
    return termino_busqueda, respuesta.text

def procesar_resultados(html, palabra):
    soup = BeautifulSoup(html, 'html.parser')
    resultados_encontrados = []
    bloque = soup.find_all("div", class_="g")
    for resultado in bloque:
        titulo = resultado.find('h3').string
        resultados_encontrados.append(titulo)
    return resultados_encontrados

def scrap(termino_busqueda, numero_resultados, codigo_lenguaje):
    palabra, html = obtener_resultados(termino_busqueda, numero_resultados, codigo_lenguaje)
    resultados = procesar_resultados(html, palabra)
    return resultados

if __name__ == '__main__':
    palabra = 'Quantika14'
    h5 = (palabra, 1, "es")
h6 = (h5[0])

username=h6
url = 'https://www.twitter.com/'+username
r = requests.get(url)
soup = BeautifulSoup(r.content,'html.parser')

f = soup.find('li', class_="ProfileNav-item--followers")
title = f.find('a')['title']
print (title)

g=soup.find_all('title', limit=1)

h = soup.find('data-testid', {'UserDescription': 'textContent'})

title2 =g
print (title2)
title3=h
print(title3)

Esto es lo que sale cuando hago en el inspector la opción "Copy Selector"
#react-root > div > div > div > main > div > div > div > div.css-1dbjc4n.r-14lw9ot.r-1tlfku8.r-1ljd8xs.r-13l2t4g.r-1phboty.r-1jgb5lz.r-11wrixw.r-61z16t.r-1ye8kvj.r-13qz1uu.r-184en5c > div > div:nth-child(2) > div > div > div:nth-child(2) > div > div > div:nth-child(1) > div > div:nth-child(3) > div > span

y esto lo que sale cuando hago en el inspector copy outherHTML
Damos soluciones a través de nuestras aplicaciones y peritajes informáticos. Encontramos a los autores de crímenes usando nuevas tecnologías.

Con estos datos, en la página de Twitter, no logro extraer la Descripción usando BeautifulSoup, lo máximo que logro es None.

A: Ya tengo la solución, he tenido votos negativos por poca investigación, pero he logrado la respuesta, así que no veo puntuación negativa justificada.
import requests
from bs4 import BeautifulSoup

USER_AGENT = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}

def obtener_resultados(termino_busqueda, numero_resultados, codigo_lenguaje):
    url_google = 'https://www.google.com/search?q={}&num={}&hl={}'.format(termino_busqueda, numero_resultados, codigo_lenguaje)
    respuesta = requests.get(url_google, headers=USER_AGENT)
    respuesta.raise_for_status()
    return termino_busqueda, respuesta.text

def procesar_resultados(html, palabra):
    soup = BeautifulSoup(html, 'html.parser')
    resultados_encontrados = []
    bloque = soup.find_all("div", class_="g")
    for resultado in bloque:
        titulo = resultado.find('h3').string
        resultados_encontrados.append(titulo)
    return resultados_encontrados

def scrap(termino_busqueda, numero_resultados, codigo_lenguaje):
    palabra, html = obtener_resultados(termino_busqueda, numero_resultados, codigo_lenguaje)
    resultados = procesar_resultados(html, palabra)
    return resultados

if __name__ == '__main__':
    palabra = 'Quantika14'
    h5 = (palabra, 1, "es")
h6 = (h5[0])

username=h6
url = 'https://www.twitter.com/'+username
r = requests.get(url)
soup = BeautifulSoup(r.content,'html.parser')

f = soup.find('li', class_="ProfileNav-item--followers")
title = f.find('a')['title']
print (title)

g=soup.find_all('title', limit=1)
h = soup.select('.bio',limit=1)

title2 =g
print (title2)
title3=h
print(title3)

A: la opción mas fiable es usar el Api de Twitter, si bien es cierto tiene mucha información se puede acceder facílmente utilizando la librería pandas.
El siguiente ejemplo lo hicimos en un máster de BigData analizando a detalle palabra a palabra
Partiendo del ejemplo que puedas obtener a través del api la salida de tweets o cargarla dinamicamente prueba con esto
import pandas as pd

df = pd.read_json("salida_tweets.txt", lines=True)

df.head(20)  // muestra primeras 20 lineas
df.columns   // obtiene los nombres de columnas

Resultado:
Index(['contributors', 'coordinates', 'created_at', 'delete', 'entities',
       'extended_entities', 'favorite_count', 'favorited', 'filter_level',
       'geo', 'id', 'id_str', 'in_reply_to_screen_name',
       'in_reply_to_status_id', 'in_reply_to_status_id_str',
       'in_reply_to_user_id', 'in_reply_to_user_id_str', 'lang', 'place',
       'possibly_sensitive', 'retweet_count', 'retweeted', 'retweeted_status',
       'source', 'text', 'timestamp_ms', 'truncated', 'user'],
      dtype='object')

Obtenemos solo la columna texto de los tweets limitando a 30 filas
df["text"].head(30)

y si lo deseas puedes separar palabra a palabra del texto
    import json
    tweets = []

    tw = open("salida_tweets.txt")
for linea in tw:
    tweet_en_bruto = json.loads(linea)
    if 'text' in tweet_en_bruto.keys():
        tweets.append(tweet_en_bruto['text'].lower().split(" "))

Como se puede ver en el código anterior se han aplicado variasf funciones, en cada tweet, hemos escogido sólo la columna 'text' lo hemos descompuesto con split(" "), en palabras para poder ir buscando una a una en el archivo de sentimientos. Posteriormente, hemos forzado a que todos sean minúsculas, ya que si encontramos estas palabras "Hellow" y "hellow", en los tweetsAhora mostramos los Tweets descompuestos en espacios en una lista.
tweets[0:20]

Intentalo y ya me dices lo que sea, espero te sea de utilidad


text:
Q: Is there a way to use QCommandLineParser with an option followed by multiple values? I need to make my app scan for a number of ports given as command line arguments and so far I have this:
    QCommandLineOption portScanOption(QStringList() << "p" << "target-port",
                QCoreApplication::translate("main", "Scan <port> for other instances"),
                QCoreApplication::translate("main", "port"));
    parser.addOption(portScanOption);
    parser.process(app);
    auto ports = parser.values(portScanOption); // do something with the ports

In order for this to work correctly, I need to pass the arguments like this: -p 5000 -p 7000 -p 8000.
I am looking for a way to make this work for the following input: -p 5000 7000 8000, but I haven't been able to find anything, not even in the official documentation. It's something quite trivial, so I expect Qt to have something like this. Do you guys know how it should be done?

A: This is already handled - the syntax you propose doesn't quite fit QCommandLineParser. Either use -p 5000,7000,8000 or -p "5000 7000 8000". All those ports will be the value of the port option, and you can then separate them with split(QRegularExpression("[, ]"), Qt::SkipEmptyParts) (that's QString::split). E.g.:
auto ports = parser.value("target-port")
             .split(QRegularExpression("[, ]"), Qt::SkipEmptyParts);
for (auto &portStr : ports) {
  bool ok = false;
  int port = portStr.toInt(&ok);
  if (!ok) continue;
  // use port value here
}

Alternatively, since the Qt source code is available, you could copy the command line parser source into your project, rename the class, and extend it to support the original syntax you had in mind.


text:
Q: JS, Async (lib), Express. response( ) inside async not working
I tried to call res() after some async stuff finishes, inside Async.waterfall([], cb)
But as it seems, the req/res objects are not available in that scope. I call them from my callback cb.
function (req, res, next) {
var query = req.query;
async.waterfall([
    async.apply(userManager.register, query.username, query.email, query.password)
], function (err, result) {
    if (err)
        console.log(err);
    if (err && err.internal == false)
        return res(err); //TypeError: res is not a function

    console.log(result);
});

The only solution I have in mind is, passing the req/res to my backend, and call it there.
But that would mean that my background code needs to have a req and res object. Moreover it returns something to my server, which is also bad.
Thanks for your help.

A: Your issue is not about scope. It's that res is not a function so you can't call it like res(err).  res is an object with methods.  You can send an error response either like this which will go to the default error handler in Express:
next(err)

Or like this:
res.status(500).send("Internal Error occurred").

which sends a 500 status on the response and then sends whatever content you want to describe the error.
I can't think of any circumstance where you want to pass the res object into your backend.  Your backend should fetch and return data and then your route handler should turn that data or error into a response.


text:
Q: How to edit and update item of array in Angular which file is coming from JSON I am trying to implement an edit which will edit the object and then at update will add the new data and will delete the old data.
I want only the comments$ to edit and update.
I am getting the JSON I am showing I can edit but I am not able to save and to show in UI.
Here is the code which I have tried.
@Injectable({
providedIn: 'root'
})
export class CommentService {
private baseUrl = 'http://localhost:3000/comments';

constructor(private http: HttpClient) { }

getComment(id: number): Observable<any> {
return this.http.get(`${this.baseUrl}/${id}`);
}
update(comment: Comment, id) {
return this.http.put(`${this.baseUrl}/${id}`, comment);

}
}

posts$: Observable<Post[]>;
  comments$: Observable<Comment[]>;
  groupedComments$: Observable<CommentGroup>;
  editableComment = emptyComment();

  constructor(private postsService: PostService,
              private commentsService: CommentService,
              private confirmationDialogService: ConfirmationDialogService) {
    this.posts$ =  this.postsService.getPostsList();
    this.comments$ = this.commentsService.getCommentsList();
    this.getAllData();
  }

  ngOnInit() {

  }
  getAllData() {
    this.groupedComments$ = this.comments$.pipe(
      map(comments => lodash.groupBy(comments, 'postId'))
    );
  }

  isEditable(comment: Comment): boolean {
    return this.editableComment.id === comment.id;
  }
  editComment(comment: Comment) {
    this.editableComment = comment;
    this.getAllData();
  }
  update(itemId, itemName, itemObj) {
      console.log(itemId, itemName, itemObj);
  }
  cancel() {
    this.editableComment = emptyComment();
  }

And here is the HTML

    {{post.title}}
    {{post.body}}
      <ng-container *ngIf="groupedComments$ | async as groupedComments">

      {{comment.name}}
      <textarea class="comment" *ngIf="isEditable(comment)" [(ngModel)]="editableComment.name"></textarea>
      {{comment?.body}}
      <textarea class="comment" *ngIf="isEditable(comment)" [(ngModel)]="editableComment.body"></textarea>

      <td class="comment" *ngIf="comment.email === 'Just@do.it' && comment.body.length < 200">
        {{comment.email}}
        <button  *ngIf="!isEditable(comment)" (click)="deleteComment(comment.id)" class="btn btn-danger">Delete</button>
        <button *ngIf="!isEditable(comment)" (click)="editComment(comment)" class="btn btn-info" style="margin-left: 10px">Edit</button>
        <button *ngIf="isEditable(comment)" (click)="update(comment.id, comment.name, comment)" class="btn btn-info" style="margin-left: 10px">Update</button>
        <button *ngIf="isEditable(comment)" (click)="cancel()" class="btn btn-danger" style="margin-left: 10px">Cancel</button>

      </ng-container>

A: Updated the important part. You need somewhere a function to store your changed comment.
groupedComments$: Subject<CommentGroup> = new ReplaySubject(1);

getAllData() {
  this.commentService.getCommentsList()
    .pipe(map(comments => lodash.groupBy(comments, 'postId')))
    .pipe(take(1)) // this will unsubscribe for you, after one value was emitted
    .subscribe(commentGroup => this.groupedComments$.next(commentGroup));
}

editComment(Comment comment) {
  this.commentService.update(comment);
  getAllData();
}

On HTML you can subscribe on this.groupedComments.


text:
Q: Given a $1$-form $\omega$ on $\Bbb R^n$, is there a connection whose torsion is $T(X,Y)=\omega(X)Y-\omega(Y)X$? Consider $(R^n, g_0 )$, where $g_0$ is the Euclidean metric, and a differential $1$-form $\omega$ on $R^n$. Can this differential form define a connection on  $M=R^n$ such that its torsion is
$$T(X,Y)=\omega(X)Y-\omega(Y)X ?$$
Thanks.

A: Hint In a holonomic basis, the components of the torsion tensor are given by
$$T^c{}_{ab} = \Gamma^c_{ab} - \Gamma^c_{ba} ,$$
where $\Gamma_{ab}^c$ are the Christoffel symbols of the connection. Can you choose the Christoffel symbols so that the identity is satisfied? (One can even choose them so that the connection is metric.)