text:
Q: How to display a youtube embed link that is called from database I have an application I want to use for my teaching studio where I create lessons that students can view. the lessons are specific to each student so they are linked via a :user_id (user has_many lessons, lesson belongs_to user). I can bring up specific lessons based on which user it is but the one part I cannot figure out is how to get a video (youtube) link to display correctly.  What I want is to save the link  along with the text for the lesson.  The text and title and all that comes up fine right now, but the video will not display with embed code and throws a routing error in the iframe window.
Here is my code for the _lesson partial. "video_url" is the name of the column in the database.
_lesson.html.erb

    <%= lesson.title %>

    <%= lesson.lesson_notes %>
     <iframe width="490" height="275" src="<%= lesson.video_url %>" frameborder="0"  allowfullscreen>

this is the code in my show view.
show.html.erb
<% if @user.lessons.any? %>

 Lessons (<%= @user.lessons.count %>)

  <%= render @lessons %>

  <%= will_paginate @lessons %>
<% end %>

the error I get is below
  No route matches [GET] "/users/www.youtube.com/embed/CFF0mV24WCY"

I kind of understand what is happening, but not really.  I guess I am unsure why it is looking for that route instead of just embedding the code and then displaying the video. It brings up all the other text and stuff from the lesson so that is working fine.  Is there not an easy way just to display the link so it embeds the video along with it?  I have searched quite a bit but everything I find just deals with embedding the code into the html which I can do, but this needs to change based on the user so has to be pulled out of the database along with the rest of the lesson info.  Any help would be greatly appreciated.

A: src needs to know the protocol, so if you don't include http://, the explorer assumes that the given src is next to your actual path.
A shitty solution could be add the protocol with a raw string:
src="http://<%= lesson.video_url %>"

But a way better solution is adding a filter to check if the protocol is included when you save the field.


text:
Q: AWS Java SDK error: request signature 'not match signature provided' Check your key, etc. But credentials are correct UPDATE: This was my stupid copy/paste error with keys.  Some other interesting aspects to this which i will try to explain shortly...
ORIGINAL QUESTION FOLLOWS:
I was trying to write a Spark program that writes JSON to S3 and ran into this error:
Request signature we calculated does not match the signature you provided. Check your key and signing method.
So I decided to try to get things working the simplest possible way, with the AWS Java SDK, and the sample program described here
With my credentials correctly provided in ~/.aws/credentials the sample
code referenced above worked without modification.
I then decided to break things by moving ~/.aws/credentials aside and rerunning, and of course it errored out. Then I tried fixing by explicitly providing the credentials. You can see the full code
of the slightly modified sample program in the section 'FULL MODIFIED PROGRAM'.
But the essence of what I tried is given immediately below. Note that I am supplying the credentials
via
.withCredentials(provider)

on the s3Client builder.  I also tried running with the line below both commented out and enabled:
//.withClientConfiguration(clientConfiguration)

.
   public static void main(String[] args) throws IOException {
        String bucketName = "cbedford-sqlshackdemocli-test-only";
        String stringObjKeyName = "durango.saturday1";
        String fileObjKeyName = "clean.money.txt";
        String fileName = "/tmp/x";

        ClientConfiguration clientConfiguration = new ClientConfiguration();
        // Solution is update the Signer Version.
        clientConfiguration.setSignerOverride("S3SignerType");

        AWSCredentialsProvider provider = new  AWSCredentialsProvider() {
            @Override
            public AWSCredentials getCredentials() {
                return new AWSCredentials () {
                    @Override
                    public String getAWSAccessKeyId() {
                        // String below copied form ~/.aws/credentials
                        // [default]
                        // aws_access_key_id = somethingsomething
                        return "somethingsomething";
                    }
                    @Override
                    public String getAWSSecretKey() {
                        // String below copied form ~/.aws/credentials
                        // [default]
                        // aws_secret_access_key = somethingsomethingelse
                        return "somethingsomethingelse";
                    }
                };
            }
            @Override
            public void refresh() {
            }
        };

        try {
            //This code expects that you have AWS credentials set up per:
            // https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-credentials.html
            AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                    .withRegion(Regions.US_EAST_1)
                    .withCredentials(provider)
                    //.withClientConfiguration(clientConfiguration)
                    .build();

No matter what I tried, I failed in all my attempts to supply the same credentials as those in my .aws directory via the inline method. If any one can spot my dumb mistake (I know I must be making one!) I would be extremely grateful.
FULL MODIFIED PROGRAM
import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;

import java.io.File;
import java.io.IOException;

public class UploadObject {

    public static void main(String[] args) throws IOException {
        String bucketName = "cbedford-sqlshackdemocli-test-only";
        String stringObjKeyName = "durango.saturday1";
        String fileObjKeyName = "clean.money.txt";
        String fileName = "/tmp/x";

        ClientConfiguration clientConfiguration = new ClientConfiguration();
        // Solution is update the Signer Version.
        clientConfiguration.setSignerOverride("S3SignerType");

        AWSCredentialsProvider provider = new  AWSCredentialsProvider() {
            @Override
            public AWSCredentials getCredentials() {
                return new AWSCredentials () {
                    @Override
                    public String getAWSAccessKeyId() {
                        return "somethingsomething";

                    }
                    @Override
                    public String getAWSSecretKey() {
                        return "somethingsomethingelse";
                    }
                };
            }
            @Override
            public void refresh() {
            }
        };

        try {
            //This code expects that you have AWS credentials set up per:
            // https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-credentials.html
            AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                    .withRegion(Regions.US_EAST_1)
                    .withCredentials(provider)
                    //.withClientConfiguration(clientConfiguration)
                    .build();

            // Upload a text string as a new object.
            s3Client.putObject(bucketName, stringObjKeyName, "Uploaded String Object");

            // Upload a file as a new object with ContentType and title specified.
            PutObjectRequest request = new PutObjectRequest(bucketName, fileObjKeyName, new File(fileName));
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType("plain/text");
            metadata.addUserMetadata("title", "someTitle");
            request.setMetadata(metadata);
            s3Client.putObject(request);
        } catch (AmazonServiceException e) {
            // The call was transmitted successfully, but Amazon S3 couldn't process
            // it, so it returned an error response.
            e.printStackTrace();
        } catch (SdkClientException e) {
            // Amazon S3 couldn't be contacted for a response, or the client
            // couldn't parse the response from Amazon S3.
            e.printStackTrace();
        }
    }
}

A: can be related to v4 signing where you need to route the request to the specific AWS region where the the bucket lives. recent regions (london, frankfurt, ...) are v4 signature only.
why not add the hadoop-aws jar for the exact hadoop versions you have in your lib dir *and the exact aws JARs it was built with, and try to use the s3a connector, to see if it works or, if it doesn't, what errors are provided. Then look at the troubleshooting_s3a doc on the hadoop docs and see what possible causes are.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apache Mod Rewrite does not rewrite file name i have the following problem:
On the download dialog on each browser it displays me only the dot extension filename
like .divx
But i want the full name eg
http://example.com/14558/.divx rewrites to 14558.divx and not onyly .divx
I want see on every browser dialog the number and the extension.
like 14558.divx
How i can solve this problem ??
RewriteRule ^([0-9]+)/.divx$ $1.divx
RewriteRule ^([0-9]+)/.mkv$ $1.mkv
RewriteRule ^([0-9]+)/.avi$ $1.avi

Current Configuration:
RewriteRule ^([0-9]+)/\.(divx|mkv|avi)$ /$1.$2

Rewrite Log:
127.0.0.1 - - [19/Dec/2011:13:07:02 +0100] [video.local/sid#4518f8][rid#ae5c7c8/initial] (3) [perdir F:/media/video_files/] add path info postfix: F:/media/video_files/29 -> F:/media/video_files/29/.mkv
127.0.0.1 - - [19/Dec/2011:13:07:02 +0100] [video.local/sid#4518f8][rid#ae5c7c8/initial] (3) [perdir F:/media/video_files/] strip per-dir prefix: F:/media/video_files/29/.mkv -> 29/.mkv
127.0.0.1 - - [19/Dec/2011:13:07:02 +0100] [video.local/sid#4518f8][rid#ae5c7c8/initial] (3) [perdir F:/media/video_files/] applying pattern '^([0-9]+)/\.(divx|mkv|avi)$' to uri '29/.mkv'
127.0.0.1 - - [19/Dec/2011:13:07:02 +0100] [video.local/sid#4518f8][rid#ae5c7c8/initial] (2) [perdir F:/media/video_files/] rewrite '29/.mkv' -> '/29.mkv'
127.0.0.1 - - [19/Dec/2011:13:07:02 +0100] [video.local/sid#4518f8][rid#ae5c7c8/initial] (1) [perdir F:/media/video_files/] internal redirect with /29.mkv [INTERNAL REDIRECT]
127.0.0.1 - - [19/Dec/2011:13:07:02 +0100] [video.local/sid#4518f8][rid#ae588f8/initial/redir#1] (3) [perdir F:/media/video_files/] strip per-dir prefix: F:/media/video_files/29.mkv -> 29.mkv
127.0.0.1 - - [19/Dec/2011:13:07:02 +0100] [video.local/sid#4518f8][rid#ae588f8/initial/redir#1] (3) [perdir F:/media/video_files/] applying pattern '^([0-9]+)/\.(divx|mkv|avi)$' to uri '29.mkv'
127.0.0.1 - - [19/Dec/2011:13:07:02 +0100] [video.local/sid#4518f8][rid#ae588f8/initial/redir#1] (1) [perdir F:/media/video_files/] pass through F:/media/video_files/29.mkv

A: Your rewriterules seem ok... err well maybe it's the backslash. By the way you could optimize in a nicer way (not tested):
RewriteRule ^([0-9]+)/\.(divx|mkv|avi)$ /$1.$2

But the only way to solve your problem (= show the whole filename) is to make a full redirect to a URL that has the full filename.
So in your case redirect would mean these rules:
RewriteRule ^([0-9]+)/\.(divx|mkv|avi)$ $1.$2 [QSA,R=301,L]

And that implies that the URLs like "14558.divx" and "1526.mkv" have to be valid and return the file.
Two hints:
Please try to use the RewriteLog directive: it helps you to track down such problems:
# Trace:
# (!) file gets big quickly, remove in prod environments:
RewriteLog "/web/logs/mywebsite.rewrite.log"
RewriteLogLevel 9
RewriteEngine On

My favorite tool to check for regexp:
http://www.quanetic.com/Regex (don't forget to choose ereg(POSIX) instead of preg(PCRE)!)


text:
Q: How to invoke another intent within the responseBuilder WITHOUT using .addDelegateDirective or .addElicitSlotDirective I have the following return statement:

return input.responseBuilder
  .speak(speakOutput)
  .addDelegateDirective(previousIntent)
  .getResponse();

I don't want to use Dialog.Delegate (addDelegateDirective) since I need to have access to the ssml output for my repeat intent.
I know you can use addElicitSlotDirective but you need to pass a slotToElicit - which is not what I want. I just need to have a speakOutput and then send the user to another intent. Is there a way to do that?

A: So what you want to do is just pass some data between intents - you can use SessionAttributes in that case.


text:
Q: how to play SIP RTP packets I'm working on windows, trying to make one application in .NET that capture the RTP SIP traffic information, and send it to julius for word detection, example if the person at the line says "one" julius can detect based on the grammar file the word "one", two, three, etc.
Testing with microphone input, julius goes fine, and the detection works like a charm. My problem is that the audio will not come from microphone anymore, because it will come from RTP sip call. So, how can I pass the RTP audio packets from network to julius input? Maybe if I can convert the RTP to audio on the fly and pass it to microphone input so julius can make the detection?

A: The Stereo mix device might help you. This is a tricky device which allows any app to record what you are playing.
Just playback to this device from your app and configure julius to listen on this device (or set this as the default device).
You can find the details about how to enable the stereo mix device here.


text:
Q: Integration (similar to Laplace transform) & limit for large argument I am faced with the following integral, that looks like essentially finding a Laplace transform, and would like to know how to extract the asymptotic behaviour for large argument. The integral in question is, for $n \in \mathbb{Z}^{+}$
$$ \int_{0}^{\infty} ds \left(\frac{1}{s - i n } - \frac{1}{s + in} - \frac{2i}{n} \right) \frac{\textrm{e}^{- s / z}}{s}\,.$$
Here I have removed the small-$s$ divergence from the integrand because I know how to treat it. I would like to get a grip of the functional form of this result for large $z$.
I believe this can be evaluated in terms of the Cosine and Sine exponential integrals, and then one can expand them for large argument; could consider this as the Laplace transform (with argument $1/z$) of the remainder of the integrand and look at its asymptotic form. However, I'd like to analyse the asymptotic behaviour without, necessarily, the need to evaluate the integral exactly or write it in terms of special functions; rather just by looking at the integrand itself...
I wanted to use contour integration, but one can't close the counter in a keyhole because the exponent grows for arguments with large negative real part. The other choice it to return along the imaginary axis, but that's exactly where the poles are.
Any suggestions greatly appreciated.

A: Let
$$g(s) = \frac 1 {s - i n} - \frac 1 {s + i n} - \frac {2 i} n, \\
 f(s) = \frac {g(s)} s e^{-s/z}.$$
We have
$$I = \int_0^\infty f(s) ds =
\left( \int_0^z + \int_z^\infty \right) f(s) ds, \\
\left| \int_z^\infty f(s) ds \right| \leq
\int_z^\infty \frac 4 n \frac {e^{-s/z}} s ds =
\frac 4 n \int_1^\infty \frac {e^{-s}} s ds =
O(1), \\
\int_0^z f(s) ds =
\underbrace {\int_0^z \frac {g(s)} s ds}_{ = I_1} +
 \underbrace {\int_0^z g(s) \frac {e^{-s/z} - 1} s ds}_{= I_2}, \\
|I_2| \leq \int_0^z \frac 4 n \frac {1 - e^{-s/z}} s ds =
\frac 4 n \int_0^1 \frac {1 - e^{-s}} s ds = O(1).$$
It remains to estimate $I_1$, which gives $I = -2 i \ln(z)/n + O(1)$ for $z \to \infty$ and constant $n$.


text:
Q: Bash -- how do I extract the third number In bash how do I extract the fourth element out of a comma-separated list such as
"text",1244,258,8,NA,17,NA,2423

i.e. I want the number 8.
If it's easier, please recommend how I can use something like perl.

A: *

*You can use cut:
 echo '"text",1244,258,8,NA,17,NA,2423' | cut -d, -f4
 8

-d is the option to set the char separator,  and -f to specify which field you are interested in. (you can specify a range)

*Or use awk:
echo '"text",1244,258,8,NA,17,NA,2423' | awk -F, '{print $4}'
8

Btw this is 4th field not 3rd.

A: Perl solution:
perl -aF, -lne 'print $F[3]' input.txt

If the input is really a CSV which could contain quoted commas and newlines, better use the Text::CSV.

A: This isn't the most robust (will break on newlines inside double quotes), but with a CSV parser:
perl -MText::CSV -nE '
    BEGIN {$csv = Text::CSV->new()}
    $csv->parse($_);
    say +($csv->fields())[3];
' <<END

"hello,world",1244,258,8,NA,17,NA,2423
END

8

ruby comes with a CSV parser in the standard library:
ruby -rcsv -ne 'CSV.parse($_) {|f| puts f[3]}'

A: I'm at a loss for why folks are recommending tools external to bash itself -- unless correctly handling cases where the text string contains commas is important, there's no need whatsoever for perl, awk, or any other such tool, and handling this internally to bash will be much more efficient when processing only a single line.
IFS=, read _ _ _ target _ <<<'"text",1244,258,8,NA,17,NA,2423'
echo "$target"

...or, similarly:
IFS=, read -a items <<<'"text",1244,258,8,NA,17,NA,2423'
echo "${items[3]}" # first item is 0

Now, if you need to handle commas and quotes inside the text field, then it's time to pull out a CSV parser. Python includes one in the standard library, so this can be assured to work on all modern systems:
python -c 'import sys, csv; print csv.reader(sys.stdin).__iter__().next()[3]' \
  <<<'"text",1244,258,8,NA,17,NA,2423')


text:
Q: byte[] to image convertion in windows phone 7 application I am doing an application for windows phone 7.
the application is access a image from database(Sql server 2008).
the data is stored in data type 'image'.I want to Display the image.
i use the following code
     public object Convert(object value, Type targetType, object parameter,           System.Globalization.CultureInfo culture)
    {
        byte[] data;
        BitmapImage empImage = new BitmapImage();
        Stream mm;
        data = (byte[])value;
        mm = new MemoryStream(data);
        mm.Position = 0;
        BinaryReader BR = new BinaryReader(mm);
        byte[] image=BR.ReadBytes(data.Length);
        mm = new MemoryStream(image);
        //empImage.SetSource(mm);
        return empImage;
    }

But there is a 'Unspecified' error at commented line (empImage.SetSource(mm);).
Please help Me......

A: BitmapImage.SetSource accepts a Stream (you can leave out the CreateOptions if you don't need to access the bytes immediately afterwards):
public object Convert(object value, Type targetType, object parameter,
       System.Globalization.CultureInfo culture)
{
    byte[] data = (byte[])value;

    using (MemoryStream stream = new MemoryStream(data))
    {
        BitmapImage image = new BitmapImage
        {
            CreateOptions = BitmapCreateOptions.None
        };

        image.SetSource(stream);

        return image;
    }
}

Also, I don't think an IValueConverter is the right place for this sort of code.
And finally, the image database type has been deprecated in favour of varbinary(MAX)


text:
Q: Problems exporting tibble to ODS I have the following code:
library(readODS)
source <- tibble(LANGUAGE = toupper(sprachen),
                 SOURCE = c("Source: SFO  National accounts",
                            "Quelle: BFS Volkswirtschaftliche Gesamtrechnung",
                            "Source: OFS Comptes nationaux",
                            "Fonte: UST Conti nazionali"),

                INFORMATION = c("Information: 058 467 34 86, info.vgr-cn bfs.admin.ch",
                          "Auskunft: 058 467 34 86, info.vgr-cn bfs.admin.ch",
                          "Renseignements: 058 467 34 86, info.vgr-cn fs.admin.ch",
                          "Informazioni: 058 467 34 86, info.vgr-cn bfs.admin.ch"),
                COPYRIGHT = c("SFSO 2020", "BFS 2020", "OFS 2020",
                              "UST 2020"))
)

write_ods(source, "test.ods", sheet = "INFORMATION")

When I look in the sheet the first and the last line show some weird behavior (see picture):
The value for the second column is overwritten by the value for the third column. The fourth column then has a NA.

I removed all tabs and other stuff, but it keeps happening.
Any idea what is wrong here?
Cheers
Renger


text:
Q: Hyper-V File Server Clustering - at my wit's end I am at my wit's end with File Server clustering under Hyper-V. I am hoping that someone might be able to help me figure out this Gordian Knot of a technology that seems to have dead ends (like forcing cluster VMs to use iSCSI drives where normally-attached VHDX drives could suffice) where logic and reason would normally provide a logical solution.
My hardware:
I will be running three servers (in the end), but right now everything is taking place on one server. One of the secondary servers will exist purely as a witness/quorum, and another slightly more powerful one will be acting as an emergency backup (with additional storage, just not redundant) to hold the secondary AD VM and the other halves of a set of clustered VMs: the SQL VM and the file system VM. Please note, these each are the depreciated nodes of a cluster, the main nodes will be on the most powerful first machine.
My heavy lifter is a machine that also contains all of the truly redundant storage on the network. If this gives anyone the heebie-geebies, too bad. It has a 6TB (usable) RAID-10 array, and will (in the end) hold the primary nodes of both aforementioned clusters, but is right now holding all VMs. This is, right now: DC01, DC02, SQL01, SQL02, FS01 & FS02. Eventually, I will be adding additional VMs to handle Exchange, Sharepoint and Lync, but only to this main server (the secondary server won't be able to handle more than three or four VMs, so why burden it? The AD, SQL & FS VMs are the most critical for the business).
If anyone is now saying, "wait, what about a SAN or a NAS for the file servers?", well too bad. What exists on the main machine is what I have to deal with.
I followed these instructions, but I seem to be unable to get things to work. In order to make the file server truly redundant, I cannot trust any one machine to hold the only data store on the network. Therefore, I have created a set of iSCSI drives on the VM-host of the main machine, and attached one to each file server VM. The end result is that I want my FS01 to sit on the heavy lifter, along with its iSCSI "drive", and FS02 will sit on the secondary machine with its own iSCSI "drive" there as well. That is, neither iSCSI drive will end up sitting on the same machine as the other. As such, the clustered FS will utterly duplicate the contents of the iSCSI drives between each other, so that if one physical machine (or the FS VM) goes toes-up, the other has got a full copy of the data on its own iSCSI drive.
My problem occurs when I try to apply the file server role within the failover cluster manager. Actually, it is even before that -- it occurs when adding the disks. Since I have added each disk preferentially to a specific VM (by limiting the initiator by DNS hostname, and by adding two-way CHAP authentication), this forces each VM to be in control of its own iSCSI disk. However, when I try to add the disks to the Disks section of Storage within Failover Cluster Manager, the entire process fails for a random disk of the pair. That is, one will get online, but the other will remain offline because it does not have the correct "owner node". I mean, really -- WTF? Of course it doesn't have the right owner node, both drives are showing the same node name!! I cannot seem to have one drive show up with one node name as owner, and the other drive show up with the other node name as owner. And because both drives are not "online", I cannot create a pool to apply to a cluster role. Talk about getting stuck between a rock and a hard place!
I've got more to add, but my work is closing for the day and I have to wrap things up. I will try to add more tomorrow morning when I get in.
My main objective is to have a file server VM on each machine, the storage on each machine, but a transparent failover in case one physical machine fails. Essentially, a failover FS that doesn't care which machine fails -- the storage contents are replicated equally on each machine. Am I even heading in the right direction?

A: The article you link to sets up one server to act as an iSCSI target that both Hyper-V servers connect to for shared storage (did you not catch that?). Meaning, it acts as the NAS/SAN-like device and provides the shared storage that the other two hosts both connect to for storage. What you are trying to do is completely different.

.. Am I even heading in the right direction?

Frankly, No.
As MDMarra suggest, DFS would be technology I would look at to accomplish this objective.. If you want the same for Exchange, you would setup a DAG for the database and CAS Array for the CAS servers. For SQL 2012, you would be looking at SQL Always On.
These technologies are BUILT specifically for these purposes and all don't rely on Hyper-V. If you want to leverage Hyper-V in all this, I would suggest you look at Hyper-V replica in 2012. It wouldn't necessary provide you automatic failover, but it would create the redundant copy of the data that you seem to think you need.
edit: all these things were brought up in your last question here.
edit2: If you can't live with the limitations of DFS and want to setup a file server cluster either within Hyper-V or not, please read the clustering requirements to do so. In particular, note the storage section that starts off saying: "You must use shared storage.." What you are setting up is not shared storage.

A: The reason you're frustrated is because you're trying to do something that you shouldn't be doing.
You say

If anyone is now saying, "wait, what about a SAN or a NAS for the file servers?", well too bad.`

You're right. Too bad for you.
What you're trying to do cannot work. A cluster disk must be the same disk shared amongst cluster members. You can't make separate disks, replicate the data somehow, and use it as a cluster volume. It doesn't work like that. This is why cluster disks typically live on a SAN and not on local storage.
Instead of clustering, you may be better off with DFS replication and namespaces. It's a slightly different animal than clustering, but if you need to use separate disks, because you don't have proper shared storage, it's the best option available.

Additional clarification:

As such, the clustered FS will utterly duplicate the contents of the iSCSI drives between each other, so that if one physical machine (or the FS VM) goes toes-up, the other has got a full copy of the data on its own iSCSI drive.

This isn't how clustering works. You can't do this.

I cannot seem to have one drive show up with one node name as owner, and the other drive show up with the other node name as owner.

Again - because that's not how it works. If you're trying to add a disk to a cluster, it should be shared amongst all nodes in the cluster. That's how it works. This is the expected outcome of trying to add disks to a cluster that all members cannot see.

My main objective is to have a file server VM on each machine, the storage on each machine, but a transparent failover in case one physical machine fails.

If you want independent storage on each machine, you don't want clustering. You'll be better off with DFS Namespaces and Replication instead. It's not the same as clustering, but you can usually accomplish a similar outcome for simple file services needs.

I strongly urge you to read through the Windows Failover Clustering documentation before you try and do anything else.


text:
Q: How should I create classes in ATL project? I'm writing an ATL project and I wonder how should I create classes here.
Right now I have one class created by Add/Class/ATL Simple Object. I want to divide it to smaller classes but method from this classes should use CComPtr and have CComPtr as an argument. I can't create 'simple' c++ class because I don't have CComPtr there.
Should I create ATL classes by ATL Simple Object Wizard and then use interface for this class to call methods. Like here:
CComPtr<ITestAtlClass> tptr;
tptr.CoCreateInstance(CLSID_TestAtlClass);
tptr->test();

And should I add all public methods by Class View/ITestAtlClass/Add/Add Method?
What about constructors? Do I must initialize my class only by properties (and add them by Class View/ITestAtlClass/Add/Add Property)? And pass every com object by IUnknown interface?
Can somebody tell me how it should be done in ATL project. I will use this smaller classes internally (nobody will create this classes outside my DLL) just to make my code more readable.

A: I don't understand your comment that you can't use CComPtr from a simple C++ class. Can you please clarify?
I see two strategies:

*

*build a clean C++ object model that solves the problem, and then wrap it in a thin facade layer of one or more COM objects

*Use ATL classes throughout, and use CComObject<> and derivatives to instantiate and maintain these without the overhead of CoCreateInstance and the limitations of only using public interfaces.

The first one is usually much nicer, but if you're building a data-heavy object model, the second can be a useful technique.
If you have an ATL COM class called CVehicle, that derives from CComObjectRootEx<> and friends, you can instantiate it like so;
   CComObject<CVehicle>* vehicle = NULL;
   CComObject<CVehicle>::CreateInstance(&vehicle);

   vehicle->AddRef();

   // To get at any of its interfaces, use:
   CComPtr<ICar> car = 0;
   vehicle->QueryInterface(&car);

   // And to delete object, use:
   vehicle->Release();

There's also variations on CComObject<>, e.g. CComObjectStack<> that use different allocation and reference counting strategies.
As you can see, this is pretty messy. If you can explain what you mean by your comment on not being able to use CComPtr, maybe I can expand on that.


text:
Q: reformat string of index field when creating RethinkDB index I am trying to create an index in RethinkDB.
The documents look like this:
{ "pinyin" : "a1 ai3"}

To make searching easier, I would like to preprocess the index entries and remove spaces and numbers, the entry thus should simply be "aai" in this case. What I tried are various variants of the following:
r.index_create('pinyin', lambda doc: doc['pinyin'].replace("1", "")).run()

This is a most simple case to build from, but even here I get an error
Expected 2 arguments but found 3 in:
r.table('collection').index_create('pinyin', lambda var_7:   var_7['pinyin'].replace('1', ''))

It's obvious that I do not understand what's going on.  Can anybody help?  I gather that the lambda expression has to follow python syntax, but since it will be used on the server has to be JavaScript??

A: I do not have experience using rethinkdb. But if you would like to remove all numbers and space from a string value the below snippet might help.
import re
doc = { "pinyin" : "a1 ai3"}
removeIntSpace = lambda doc: re.sub("\d", "x", doc['pinyin'].replace(" ", ""))

print removeIntSpace(doc)
#r.index_create('pinyin', removeIntSpace(doc)).run()

Output:
axaix

A: OK, I figured it out and am posting here for others who might run into the same problem.  This is how the index can be created in the data explorer of the rethinkdb admin console:
r.db("dics").table("collection").indexCreate('pinyin', r.row("pinyin").split("").filter(function(char) { return r.expr(["1", "2", "3", "4", " "]).contains(char).not(); }).reduce(function(a, b) { return a.add(b); }))

A corresponding python version would use an anonymous function with lambda in the filter part.


text:
Q: Get the count of duplicate keys in a hash I have a hash say
test = [ {:a1=>"a", :b1=>"q"},
         {:a1=>"c", :b1=>"z"},
         {:a1=>"a", :b1=>"zcq"} ]

Need to find out count of key with "a" (e.g. :a1=>"a") in a hash. The output should be 2 if i am searching for key as "a".
How to find the count of the selected key.

A: Try this one
test.count { |item| item[:a1] == 'a' }


text:
Q: SVN Pre-commit script execution here is my hook script that should restrict the commit for cpp file with no comments.but it fails to execute ...any ideas
        #!/bin/bash

        REPOS="$1"
        TXN="$2"

        SVNLOOK="/usr/bin/svnlook"
        AWK="/usr/bin/awk"
        GREP="/bin/egrep"
        SED="/bin/sed"

       CHANGED=`$SVNLOOK changed -t "$TXN" "$REPOS" | $GREP "^[U|A|M]" | $AWK '{print
       $2}' | $GREP \\.cpp$`

       for FILE in $CHANGED
       do
        MESSAGE=`$SVNLOOK log -t "$TXN" "$REPOS" "$FILE" | sed 's/ *//g' |$GREP ".\
       {16,\}"`
       if [ $? -ne 0 ]
       then
       echo 1>&2
       echo "***********************************" 1>&2
       echo `echo "$MESSAGE"` 1>&2
       echo "***********************************" 1>&2
       exit 1
       fi
       done

A: Make sure the pre-commit script has the execute permission (chmod +x pre-commit)
Also, make sure that the script is indeed being executed but you don't realize that it is. Note that the echo messages are echoed to the client only when there is an error and you do exit with non-zero error code.

A: First of all:

*

*Only messages to STDERR are printed and only if the exit of the pre-commit script is something other than zero. Otherwise, there's no print out at all.

*Commit messages are for the entire commit. That means you don't check the commit message of every single file. It's the same for them all.

*You can find the commit message by looking at the revision property svn:log. You don't have to look at the message.

Try this completely untested rewrite:
#!/bin/bash

REPOS="$1"
TXN="$2"

SVNLOOK="/usr/bin/svnlook"
AWK="/usr/bin/awk"
GREP="/bin/egrep"
SED="/bin/sed"

if "$SVNLOOK" changed -t $TXN | grep -q "^ *[UAM].*\.cpp$"
then
    MESSAGE=$("$SVNLOOK" pget -t $TXN --revprop "$REPOS" svn:log)
    if [ -z ${MESSAGE:16} ]
    then
        echo "Committing a *.cpp file, but didn't put a comment!" >&2
        exit 1      #CPP, but message too short
    else
    exit 0  #CPP Files but message is long enough
fi
exit 0      #No CPP files

Here are some of the changes:
You had this:
CHANGED=`$SVNLOOK changed -t "$TXN" "$REPOS" | $GREP "^[U|A|M]" | $AWK '{print $2}' | $GREP \\.cpp$`

You push it through a grep, through an awk, and then through another grep. Instead, why not do the entire line at once?
"$SVNLOOK" changed -t $TXN "$REPOS" | $GREP -q "^ *[UAM].*\.cpp$"

*

*The [UAM] means either a U or a M or a A. You don't need the | between each.

*The $GREP -q means do the grep quietly. If you found something, it returns a 0, otherwise, it returns a 1. You can put this directly into your if statement without the [...] testing braces.

*The .*\.cpp$ means I'm looking at the rest of the line and seeing if it ends with .\.cpp No need for the grep|awk|grep pipe.

*There's only a single log message, so all I have to do is check it once. No need for a loop.

*Notice I use the $(...) instead of back ticks. It does the same thing, but is easier to see.

*I use ${MESSAGE:16}. In BASH, this does a 16 character offset of my message. If my message is shorter than 16 characters, then ${MESSAGE:16} is blank. I can then use -z to see if the offset string is empty or not. Saves you the pipe to sed, then grep.

See if this works a bit better. In fact, run this as a regular shell script outside the hook. You can change the -t to a -r and put in various revision numbers. This way, you can verify the script first before trying it as a hook. Then, make sure this is called pre-commit and that you have the permissions set to rwxr-xr-x.
Even better, try my pre-commit hook. It's battle tested, and can do more. It's a Perl script, but it should run in any Perl version greater than 5.8, and you probably already have Perl on your system. You can check the svn:log for length, but my hook script doesn't allow you to specify it based upon what is committed. However, why should you allow any blank commit message anyway -- whether or not a *.cpp file was committed?


text:
Q: jQuery Slide from left to right distorts CSS I have a textbox and a button. On clicking the button, if textbox value is blank, then textbox will be highlighted with red borders. On putting focus on the textbox, a validation message will be displayed (slide in from left to right) , something like this:

But after putting the code for sliding in from left to right the validation message is shown as below:

Below is the snippet for the same.

$(document).ready(function(){
  $.fn.textWidth = function (text, font) {
        if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('').hide().appendTo(document.body);
        $.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
        return $.fn.textWidth.fakeEl.width();
    };
  $('#btnSave').click(function(){
     if (!$('#txtName').val()) {
        $('#txtName').addClass('validationInput');
        $('#txtName').closest('div').addClass('wrap');
    }
    else
      alert("Success");
  });

   $('#txtName').on('blur', function () {
        if ($(this).val() != "" && $(this).val() != null) {
            $(this).removeClass("validationInput");
            $(this).closest('div').removeClass("wrap");
        }
        $(this).parent().parent().siblings().html("");
        $(this).parent().parent().siblings().css("display", "none");
    });

  $('#txtName').on('focus', function () {
        if ($(this).hasClass('validationInput')) {
            var w = $.fn.textWidth("Please enter name", '12px arial') + 50;
            $(this).parent().parent().siblings().html("Please enter name");
            //$(this).parent().parent().siblings().css({ "display": "inline-block", "width": w });
          $(this).parent().parent().siblings().css({ "width": w }).show('slide', {direction: 'left'}, 1000);
        }
    });
});
.wrapTextboxDiv {
    height: 25px;
}
.col-lg-3 {
    width: 25%;
}

.wrap span:first-child {
    display: flex;
    overflow: hidden;
    position: relative;
    width: 100%;
}

.wrap span:first-child .input-holder::after {
    border-color: red;
    border-style: solid;
    border-width: 5px;
    box-shadow: 0 0 0 1px #ffffe0;
    content: "";
    height: 0;
    position: absolute;
    right: -5px;
    top: -5px;
    transform: rotate(45deg);
    width: 0;
}

input.vtooltips[type="text"] {
    display: inline;
    height: 20px;
    position: relative;
}

.vspan {
    background: #dc000c none repeat scroll 0 0;
    border: 1px solid #6d6d6d;
    border-radius: 4px;
    box-shadow: 2px 2px 0 #afb1b1;
    color: #fff;
    display: none;
    font-family: Arial;
    font-size: 12px;
    height: 20px;
    line-height: 15px;
    margin-left: 101%;
    opacity: 1;
    padding-left: 5px;
    padding-right: 5px;
    position: relative;
    text-align: center;
    top: -23px;
    z-index: 1000;
}

.validationInput, .validationInput:focus,  .validationInput:hover {
    background-color: #ffffe0 !important;
    border: 1px solid red !important;
    height: 20px;
}
.mandatoryText {
    background-color: #fafad2 !important;
}
.textbox {
    border: 1.5px solid #f2ca8c;
    border-radius: 4px !important;
    height: 23px !important;
    width:90%;
}

<link href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>

      <input type="text" class="mandatoryText vtooltips form-control textbox" style="width: 100%; vertical-align: top; border-radius: 4px;" maxlength="100" id="txtName" name="tname">

<input type="button" id="btnSave" value="Save"/>

What am I doing wrong? Any help will be appreciated.

A: Remove margin-left and add left:100% in .vspan class.

$(document).ready(function(){
  $.fn.textWidth = function (text, font) {
        if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('').hide().appendTo(document.body);
        $.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
        return $.fn.textWidth.fakeEl.width();
    };
  $('#btnSave').click(function(){
     if (!$('#txtName').val()) {
        $('#txtName').addClass('validationInput');
        $('#txtName').closest('div').addClass('wrap');
    }
    else
      alert("Success");
  });

   $('#txtName').on('blur', function () {
        if ($(this).val() != "" && $(this).val() != null) {
            $(this).removeClass("validationInput");
            $(this).closest('div').removeClass("wrap");
        }
        $(this).parent().parent().siblings().html("");
        $(this).parent().parent().siblings().css("display", "none");
    });

  $('#txtName').on('focus', function () {
        if ($(this).hasClass('validationInput')) {
            var w = $.fn.textWidth("Please enter name", '12px arial') + 50;
            $(this).parent().parent().siblings().html("Please enter name");
            //$(this).parent().parent().siblings().css({ "display": "inline-block", "width": w });
          $(this).parent().parent().siblings().css({ "width": w }).show('slide', {direction: 'left'}, 1000);
        }
    });
});
.wrapTextboxDiv {
  height: 25px;
}
.col-lg-3 {
  width: 25%;
}

.wrap span:first-child {
  display: flex;
  overflow: hidden;
  position: relative;
  width: 100%;
}

.wrap span:first-child .input-holder::after {
  border-color: red;
  border-style: solid;
  border-width: 5px;
  box-shadow: 0 0 0 1px #ffffe0;
  content: "";
  height: 0;
  position: absolute;
  right: -5px;
  top: -5px;
  transform: rotate(45deg);
  width: 0;
}

input.vtooltips[type="text"] {
  display: inline;
  height: 20px;
  position: relative;
}

.vspan {
  background: #dc000c none repeat scroll 0 0;
  border: 1px solid #6d6d6d;
  border-radius: 4px;
  box-shadow: 2px 2px 0 #afb1b1;
  color: #fff;
  display: none;
  font-family: Arial;
  font-size: 12px;
  height: 20px;
  line-height: 15px;
  /* margin-left: 101%;*/ /* Remove this*/
  opacity: 1;
  padding-left: 5px;
  padding-right: 5px;
  position: relative;
  text-align: center;
  top: -23px;
  z-index: 1000;
  left:100%;
}

.validationInput, .validationInput:focus,  .validationInput:hover {
  background-color: #ffffe0 !important;
  border: 1px solid red !important;
  height: 20px;
}
.mandatoryText {
  background-color: #fafad2 !important;
}
.textbox {
  border: 1.5px solid #f2ca8c;
  border-radius: 4px !important;
  height: 23px !important;
  width:90%;
}

<link href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>

      <input type="text" class="mandatoryText vtooltips form-control textbox" style="width: 100%; vertical-align: top; border-radius: 4px;" maxlength="100" id="txtName" name="tname">

<input type="button" id="btnSave" value="Save"/>

A: Simply do this with float:left property , add float to this class .vspan , just try with this snippet

$(document).ready(function(){
  $.fn.textWidth = function (text, font) {
        if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('').hide().appendTo(document.body);
        $.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
        return $.fn.textWidth.fakeEl.width();
    };
  $('#btnSave').click(function(){
     if (!$('#txtName').val()) {
        $('#txtName').addClass('validationInput');
        $('#txtName').closest('div').addClass('wrap');
    }
    else
      alert("Success");
  });

   $('#txtName').on('blur', function () {
        if ($(this).val() != "" && $(this).val() != null) {
            $(this).removeClass("validationInput");
            $(this).closest('div').removeClass("wrap");
        }
        $(this).parent().parent().siblings().html("");
        $(this).parent().parent().siblings().css("display", "none");
    });

  $('#txtName').on('focus', function () {
        if ($(this).hasClass('validationInput')) {
            var w = $.fn.textWidth("Please enter name", '12px arial') + 50;
            $(this).parent().parent().siblings().html("Please enter name");
            //$(this).parent().parent().siblings().css({ "display": "inline-block", "width": w });
          $(this).parent().parent().siblings().css({ "width": w }).show('slide', {direction: 'left'}, 1000);
        }
    });
});
.wrapTextboxDiv {
    height: 25px;
}
.col-lg-3 {
    width: 25%;
}

.wrap span:first-child {
    display: flex;
    overflow: hidden;
    position: relative;
    width: 100%;
}

.wrap span:first-child .input-holder::after {
    border-color: red;
    border-style: solid;
    border-width: 5px;
    box-shadow: 0 0 0 1px #ffffe0;
    content: "";
    height: 0;
    position: absolute;
    right: -5px;
    top: -5px;
    transform: rotate(45deg);
    width: 0;
}

input.vtooltips[type="text"] {
    display: inline;
    height: 20px;
    position: relative;
}

.vspan {
    background: #dc000c none repeat scroll 0 0;
    border: 1px solid #6d6d6d;
    border-radius: 4px;
    box-shadow: 2px 2px 0 #afb1b1;
    color: #fff;
    display: none;
    font-family: Arial;
    font-size: 12px;
    height: 20px;
    line-height: 15px;
    left: 100%;
    opacity: 1;
    padding-left: 5px;
    padding-right: 5px;
    position: relative;
    text-align: center;
    top: -23px;
    z-index: 1000;
 float:left;
}

.validationInput, .validationInput:focus,  .validationInput:hover {
    background-color: #ffffe0 !important;
    border: 1px solid red !important;
    height: 20px;
}
.mandatoryText {
    background-color: #fafad2 !important;
}
.textbox {
    border: 1.5px solid #f2ca8c;
    border-radius: 4px !important;
    height: 23px !important;
    width:90%;
}
<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>
<link href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>

      <input type="text" class="mandatoryText vtooltips form-control textbox" style="width: 100%; vertical-align: top; border-radius: 4px;" maxlength="100" id="txtName" name="tname">

<input type="button" id="btnSave" value="Save"/>


text:
Q: method to validate that amount should be of type integer return type I am getting an amount in an object through the getter method of pojo
but that amount getter method return type is set as string in pojo
as shown below
//setting need to be done in pojo
private String amount;

    public String getAmount() {
        return amount;
    }

let say below that there is object h and I am retrieving it like
h.getAmount()

now I need to develop a validator that will validate the that amount should
be of type integer and if it is not then it will throw the exception
Please advise how can I develop a seprate method that will check whether
the amount is in integer or not and on the basis of it
will return true or false , as like shown below
// Validate the amount is in integer
private boolean isValidAmount (String Amount) {
    boolean valid = false;
//code to check whether the Amount is integer or not, if integer then
//return true else return false
}

I have updated the post as it  throws number format exception , please advise

A: You could just try to parse it, and return true iff the parse succeeds.
try {
    Integer.parseInt(amount);
    return true;
} catch (NumberFormatException e) {
    return false;
}

Edit
I just re-read the question and noticed that it seems the only thing you want to do with this true/false value is to possibly raise an exception if the string couldn't be parsed. In that case, you can get rid of that boolean middleman:
try {
    Integer.parseInt(amount);
} catch (NumberFormatException e) {
    throw new MyWhateverException(amount);
}

A: Why don't you try and use Integer.parseInt(someString);
This will throw a NumberFormatException if it fails.

A: boolean flag = false;
try{
  int amount = Integer.parseInt(amount);
  flag = true;
} catch(NumberFormatException e) {
flag = flase;
}

return flag;

if the amount is in integer format then it will not through any exception
otherwise it will through NumberFormatException.
Get nmore details of parseInt() here.

A: public boolean isValidAmount (Object h){
   try {
       Integer.parseInt(h.amount);
       return true;
    } catch (NumberFormatException e) {
      return false;
    }
}

try this out, may work for u


text:
Q: Closing an open recordset produces a run-time error I have an ADO recordset variable that is declared in the class module of a userform. The recordset is opened in the form's Activate event, and I am trying to close it in the form's Terminate event with code like this:
Private Sub UserForm_Terminate()

If VersionIsReleased Then
    ThisWorkbook.Parent.Quit
Else

    If Not m_rs Is Nothing Then

        If m_rs.State = adStateOpen Then
            m_rs.Close
        End If

        Set m_rs = Nothing
    End If

    Close_CN g_cn
    ThisWorkbook.Application.Visible = True
End If

End Sub

The line m_rs.Close produces a run-time error: "Operation is not allowed in this context.". Any ideas why this happens?

A: That error can occur if the recordset is being edited when you try to close it. Make sure that if you use AddNew or change any Fields().Value that you use Update to save the edits before closing.  You can inspect the EditMode property to see what state the recordset is in.


text:
Q: Merge two DataFrames with the same schema Assume you have two DataFrames
foo = pd.DataFrame([[123,321],[1543,432]], columns=['id','location'])
bar = pd.DataFrame([[123,421],[1543,436]], columns=['location','id'])

which you want to merge into one big table. However, as the schema (columns) are the same, in the resulting table a new column indicating the "type" should be added:
    id   location   type
0   123  321        foo
1   1543 432        foo
0   421  123        bar
1   436  1543       bar

Currently, what I do is
foo['type'] = ['foo'] * foo.shape[0]
bar['type'] = ['bar'] * bar.shape[0]
pd.concat([foo,bar])

Is there some smarter way to do it and in particular, avoid the first two lines?

A: You can add parameter keys to concat - it create MultiIndex:
print (pd.concat([foo,bar], keys=('foo','bar')))
         id  location
foo 0   123       321
    1  1543       432
bar 0   421       123
    1   436      1543

And for MultiIndex to column use:
df = pd.concat([foo,bar], keys=('foo','bar'))
       .reset_index(drop=True, level=1)
       .rename_axis('type')
       .reset_index()
print (df)
  type    id  location
0  foo   123       321
1  foo  1543       432
2  bar   421       123
3  bar   436      1543

Another solution with assign:
df = pd.concat([foo.assign(type='foo'),bar.assign(type='bar')])
print (df)
     id  location type
0   123       321  foo
1  1543       432  foo
0   421       123  bar
1   436      1543  bar

A: Dror below is the timit results on the way you are doing the code and @jezrael 's method.
import pandas as pd
foo = pd.DataFrame([[123,321],[1543,432]], columns=['id','location'])
bar = pd.DataFrame([[123,421],[1543,436]], columns=['location','id'])

def f(foo,bar):
    foo['type'] = ['foo'] * foo.shape[0]
    bar['type'] = ['bar'] * bar.shape[0]
    x = pd.concat([foo,bar])
    return x

%timeit xx = f(foo,bar)

>>>1.14 ms ± 5.56 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

def f2(foo,bar):
    pd.concat([foo,bar], keys=('foo','bar'))
    df = pd.concat([foo,bar], keys=('foo','bar')).reset_index(level=0).rename_axis(None).rename(columns={'level_0':'type'})
    return df
%timeit yy = f2(foo,bar)

>>>3.04 ms ± 18.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

it seems your code is faster.


text:
Q: Arquivo de internalização, como criar? Boa tarde, alguém sabe como criar o arquivo de internalização no Android ?
Quero criar uma strings.xml(en), obrigado.

A: De forma bem sucinta, você só precisa criar um diretório, por exemplo values-en dentro do res. O en significa que é English. Poderia ser fr, Francês, e assim por diante.
Desta forma para cada chave, você faz a tradução.
Exemplo:
res/values
<string name="title_settings">Configurações</string>

res/values-en
<string name="title_settings">Configurations</string>

Leia mais aqui sobre Compatibilidade com diferentes dispositivos.


text:
Q: How to read characters in the detected objects rectangle? I was successful with tensorflow object detection API like an image below.

but now I want to read character inside green box, how to do that?

A: First you need to crop out the bounding boxes of plate(s) and then you can use tesseract. To get the text. A pseudo code for your problem may look like:
import cv2
import pytesseract

original_img = cv2.imread("/path/to/your/img.png")

for plate in detected_plates:
     if plate.confidence > 0.98:
         b_box = plate.bounding_rect  # bounding box in [x, y, w, h]
         img_cropped = original_img[b_box[1]: b_box[1] + b_box[3], b_box[0]: b_box[0] + b_box[2]]
         print(pytesseract.image_to_string(img_cropped))

A: # Load image using OpenCV and
# expand image dimensions to have shape: [1, None, None, 3]
# i.e. a single-column array, where each item in the column has the pixel RGB value
image = cv2.imread(PATH_TO_IMAGE)
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image_expanded = np.expand_dims(image_rgb, axis=0)

# Perform the actual detection by running the model with the image as input
(boxes, scores, classes, num) = sess.run(
    [detection_boxes, detection_scores, detection_classes, num_detections],
    feed_dict={image_tensor: image_expanded})

# Draw the results of the detection (aka 'visulaize the results')

vis_util.visualize_boxes_and_labels_on_image_array(
    image,
    np.squeeze(boxes),
    np.squeeze(classes).astype(np.int32),
    np.squeeze(scores),
    category_index,
    use_normalized_coordinates=True,
    line_thickness=1,
    min_score_thresh=0.60)

# All the results have been drawn on image. Now display the image.
cv2.imshow('Object detector', image)


text:
Q: What is the limit of results that are returned for List-user API call in Microsoft graph API? I could not find any mention of the limit of results that are returned for List user api call in microsoft graph api?

A: It seems the limit results is 1000. We can use $top=1000 to test, it will throw the error: 'Invalid page size specified: '1000'. Must be between 1 and 999 inclusive.'
https://graph.microsoft.com/v1.0/users?$top=1000


text:
Q: The best approach to sum tuple in Haskell i am new in Haskell programming, I got a database which store student data and mark of exam like below
type Student = String
type MarkProject = Float
type MarkMidSem = Float
type MarkFinal = Float

type Database = [(Student, MarkProject, MarkMidSem, MarkFinal)]

exampleBase :: Database
exampleBase = [("Barry", 23, 24, 43),
           ("Wayne", 22, 20, 49),
           ("Ivan", 21, 25, 48),
           ("Alli", 24, 24, 48),
           ("Martial", 22, 25, 49)]

i want to create a function to find a student total marks for exam.
TotalMarks = MarkProject + MarkMidSem + MarkFinal
i had tried couple times to do his function but failed. I also cerate a function to insert student , markProject, markmidsem and markfinal like:
totalMark :: Student -> MarkProject -> MarkMidSem -> MarkFinal -> Float

Can anyone to guide me how to complete the function for totalMarks? Thank in advance.

A: I would make an extra type, for the data tuple, and make Database use that type, after that just create a function that takes the tuple, pattern match it and sum what you need.
type Student = String
type MarkProject = Float
type MarkMidSem = Float
type MarkFinal = Float

type StudentData = (Student, MarkProject, MarkMidSem, MarkFinal)
type Database = [StudentData]

exampleBase :: Database
exampleBase = [("Barry", 23, 24, 43),
           ("Wayne", 22, 20, 49),
           ("Ivan", 21, 25, 48),
           ("Alli", 24, 24, 48),
           ("Martial", 22, 25, 49)]

totalMark::StudentData -> Float
totalMark (n, mp, mms, mf) = mp + mms + mf


text:
Q: MooDialog.Request add Event How can I add a close event to MooDialog.Request?
Update:
There is my code:
window.addEvent('domready', function(){
  $('xyz').addEvent('click', function(e) {
    e.stop();
    var reqDialog = new MooDialog.Request(url,
      {view:'show'},
      {
        size:  {
          width: 460,
          height: 375,
          'zIndex':20
        }
      }
    );
    reqDialog.setRequestOptions({
        onClose: function(){
            alert('closed');
        }
    });
  });
});

A: It's pretty simple:
//Request => new MooDialog.Request(url[, RequestOptions, options]);
var reqD = new MooDialog.Request('URL',null,{
    onClose: function(){
        alert('closed');
    }
});

doc
Edit your code need to be updated this way:
window.addEvent('domready', function(){
  $('xyz').addEvent('click', function(e) {
    e.stop();
    var reqDialog = new MooDialog.Request(url, null, {
        class:'dialogClass',
        autoOpen: false,
        onClose: function(){
            alert('closed');
        }
    });

    reqDialog.open();

    /*
        if you want to add some custom requestOptions, you need to do i.e.:
        reqDialog.setRequestOptions({
           onRequest: function(){
              reqDialog.setContent('loading...');
           }
        }).open();
    */
});

and you need some css to define the style of the dialog by dialogClass:
.dialogClass{
    width:460;
    height:375;
    z-index:20;
}


text:
Q: Pass data to a @section in MVC I know you can't use @RenderSection to pass data but what would be the equivalent to achieve the below?  I'm trying to send back to a partial view that value of item.Enabled
This is the layout page for a drop down DropDown.cshtml:
@foreach (var item in Model.Items){

        @RenderSection("Item", false)//How to pass 'item.IsChecked' back ?
        @item.Key
        @item.Value

}

This partial view that calls the above. I want to use this when specifically creating drop downs with check boxes.
@model DropDownCheckBox
@{
    Layout = "~/Views/Shared/DropDown.cshtml";
}
@section Item{
    <input type="checkbox" @(Model.IsChecked ? "checked=yes" : string.Empty) />
}

A: @RenderSection() is the same concept of @RenderBody()
What you should use in your case is @Html.Partial("ViewName", YourModel) or @Html.RenderPartial("ViewName", YourModel)  instead.


text:
Q: Set first week of the year from the first day of the year until the following monday I want that Oracle treats weeks the following way:
-The week starts on monday
-The first week of the year is from the first day of the year until the following monday
So for 2015 would be
01-jan-2015 (Thursday)  would be 1
02-jan-2015 (Friday)  would be 1
03-jan-2015 (Saturday) would be 1
04-jan-2015 (Sunday) would be 1
05-jan-2015 (Monday) would be 2
06-jan-2015 (Tuesday) would be 2
For 2017 would be
01-jan-2017 (Sunday)  would be 1
02-jan-2017 (Monday)  would be 2
03-jan-2017 (Tuesday) would be 2
04-jan-2017 (Wednesday) would be 2
and so on....
I need the numeration for the year so would go to 1 to 53-54

A: Use the ISO week date standard: 'iw'.
2014-01-01 was Wednesday actually, so:
select
  to_number(to_char(date'2014-01-05', 'iw')) as weeknum,
  to_char(date'2014-01-05', 'Day') as day
from dual;

    WEEKNUM DAY
----------- ---------
          1 Sunday

select
  to_number(to_char(date'2014-01-06', 'iw')) as weeknum,
  to_char(date'2014-01-06', 'Day') as day
from dual;

    WEEKNUM DAY
----------- ---------
          2 Monday

A: A little bit of arithmetics will probably do the trick (assuming d is your date):
select TRUNC((case to_char(d, 'DY')
          when 'MON' then 6
          when 'TUE' then 5
          when 'WED' then 4
          when 'THU' then 3
          when 'FRI' then 2
          when 'SAT' then 1
          when 'SUN' then 0
       end + to_number(to_char(d, 'DDD'))-1) / 7)+1
from v;

*

*The case statement will build an offset according to the day of week

*next I add the day of year

*then I divide the result by 7 for the week number (starting at 0)

*finally, the +1 will start numbering weeks at 1

Please take some time to experiment with it http://sqlfiddle.com/#!4/d41d8/38236 to check if I didn't make a stupid mistake as I didn't have time to test it thoughtfully. Sorry about that...


text:
Q: Get access to parent variables from child class in qt I have two class in Qt. In one I declared some variables and child QFrame class with QPainter. Now, if it's possible, how i can get access to parent variables from child class?
I know that I can pass variables by signals and slots or catch child QPainter events, but i think it would be nice get access directly.

A: It boils down to the visibility of the data in the base class. If the data is public or protected then you have access to it. Otherwise, the data is private and you don't have direct access to it.

A: Not exactly. Simple example:
header parent
class gameWindow : public QWidget
{
    Q_OBJECT

public:
    gameWindow(QWidget *parent = 0);
    int round;

};

class parent
#include "gamewindow.h"

gameWindow::gameWindow(QWidget *parent) :
    QWidget(parent)
{
   round = 0;
}

header child :
class plArea:public QWidget
{
    Q_OBJECT
public:
    plArea(QWidget *parent=0);

};

class child:
#include "plarea.h"

plArea::plArea(QWidget *parent):QWidget (parent)
{
    parent->round = 1;
}

return

'class QWidget' has no member named
  'round'


text:
Q: One freemarker template vs Multiple templates I have a large freemarker template (2000 lines) used to generate a very complex XML document. My problem is that:

*

*Maintaining this thing is hell. Difficult to navigate through the template, find the information you want and change it.

*No clear structure.

*Testing is also difficult. Each time the previous developers compared the whole resulting XML to an "ideal" XML. When you make the slightest change you have to compare the whole XML instead of being able to compare only the part that would be affected.

My obvious idea is to separate this template to a number of smaller ones, each corresponding to a different "logical" section and then include them to a master template. My only concern, one that i haven't found an answer through searching, is weather having many templates (of course they can be cached) included in a master template, adversely affects performance when compared to the single "large" template approach.

A: If you have that #include inside a loop that doesn't do much per cycle and runs for thousand of times, then maybe it can be noticeably slower. Otherwise I wouldn't worry.


text:
Q: MIPS Double Recursion Problem " Can't expand stack segment by 16 bytes to 524288 bytes" I'm trying to implement a double recursion program using MIPS that follows this pseudocode:
procedure DRAGON(order, sign)
    if order = 0 then
        Move forward
    else
        DRAGON(order-1; 1)
        Turn 90sign
        DRAGON(order-1; -1)

This is what I have until now, but when I run it, I get this error:
Can't expand stack segment by 16 bytes to 524288 bytes.
Use -lstack # with # > 524288

I'm new to MIPS so it's really difficult for me to debug this. I suspect that it's probably because I'm making infinite recursive calls, but I'm not sure how to fix this. Could anyone be able to help point out what the problem is?
        .data
# SVG path segment commands
up:     .asciiz "v-5"
right:  .asciiz "h5"
down:   .asciiz "v5"
left:   .asciiz "h-5"

# Print one of the path segment strings by readings its address
# from this array of pointers
        .align 2
dirs:   .word up, right, down, left

# Keep the current direction (0-3) in this single byte value
direction:
        .byte 3

        .text
        # $a0 = order (an unsigned integer)
        # $a1 = sign (either 1 or -1)

        .globl dragon

dragon:
        addiu   $sp, $sp, -16           # allocate space on stack (multiple of 8)
        la      $t0, dirs               # t0: dirs array address
        lbu     $t1, direction          # t1: load current direction byte
        move    $t6, $t1                # t6: copy of current direction byte
        li      $t2, 1                  # t2: load constant 1
        li      $t3, -1                 # t3: load constant -1

        sw      $ra, 0($sp)
        sw      $a0, 4($sp)
        sw      $a1, 8($sp)
        beq     $a0, $0, base

        move    $t4, $a1                # t4: keep current sign (1 or -1)
        addiu   $a0, $a0, -1            # order = order - 1
        move    $a1, $t2                # sign = 1
        jal     dragon                  # dragon(order-1, 1)

        li      $v0, print_int
        move    $a0, $a1
        syscall

        addu    $t5, $t6, $t4
        addiu   $t5, $t5, 4
        div     $t5, $t5, 4
        mfhi    $t6                     # t1: (direction + sign + 4) % 4 -> new direction
        sb      $t6, direction

        move    $a1, $t3
        jal     dragon                  # dragon(order-1, -1)
        j       done

base:                                   # when order = 0
        addu    $t1, $t1, $t1
        addu    $t1, $t1, $t1           # direction * 4
        addu    $t5, $t1, $t0           # base address + offset
        lw      $t5, 0($t5)             # t5: direction from array dirs

        li      $v0, print_string
        move    $a0, $t5
        syscall                         # print direction

done:
        lw      $ra, 0($sp)
        lw      $a0, 4($sp)
        lw      $a1, 8($sp)
        addiu   $sp, $sp, 16
        jr      $ra
#
# Main program
#
        .data
svg_header:
        .asciiz "<svg xmlns=\"http://www.w3.org/2000/svg\">\n"
svg_footer:
        .asciiz "</svg>\n"
path_header:
        .asciiz "<path stroke=\"black\" fill=\"none\" d=\"M225 225"
path_footer:
        .asciiz "\" />\n"

        .text

        .globl main
main:
        move    $s0, $ra

        la      $a0, svg_header
        li      $v0, print_string
        syscall

        la      $a0, path_header
        syscall

        li      $a0, 3   # Order
        li      $a1, 1   # Sign
        jal     dragon

        la      $a0, path_footer
        li      $v0, print_string
        syscall

        la      $a0, svg_footer
        syscall

        li      $v0, 10
        syscall

A: In your recursive fragment, you don't return before the base bits. So after the second jal dragon, your code falls through to the base scenario, which is wrong by any account. By that time, t1 no longer contains the direction variable - it's been multiplied by four. In the base, the code tries to resolve t1 as if it still was the direction and faults.


text:
Q: If condition being ignored in a loop to send emails from sheet This is the sheet I am using.
I am trying to send emails automatically for each employee on the Quota Capacity Recommendation form if Difference in Demand & Production is above 10 or below -10.
When I run the script the emails get sent even if the value is within the acceptable range (-9 to 9).
function checkValue() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Quota Capacity Recommendation");
  var num = sheet.getRange(2, 11).getValue(); //number of employees

  for (var i = 2; i < num; i++) { //loop to get each employee
    var ss = SpreadsheetApp.getActive();
    var sheet = ss.getSheetByName("Quota Capacity Recommendation");
    var dif = sheet.getRange(i, 10).getValue(); //value to check
    var rc = sheet.getRange(i, 9).getValue();
    var name = sheet.getRange(i, 1).getValue();

    if (dif > 10 || dif < -10) //condition
    {
      //GmailApp.sendEmail("user@domain.com",name+ " Quota Recommendation", name+ " has recommended quota change of " +rc);
      GmailApp.sendEmail("otheruser@domain.com", name + " Quota Recommendation", name + " has recommended quota change of " + rc);
      //MailApp.sendEmail("differentuser@domain.com",name+ " Quota Recommendation", name+ " has recommended quota change of " +rc);
    }
  }
}

A: if(dif>10 || dif<10)

if bigger than 10 or less than 10. So that is !=10.

A: It looks that the problem is that the values of column 10 (J) are percentages (the sample value es 20%) instead of integers 20.
You should have to change the value entered to be integers or the script tu use .1 instead or 10.


text:
Q: Split individual characters from a string I'm writing following program to separate characters from a string and assign it to an array.
public class Str {
    public static void main(String[] args) {
        String str = "hello";
        String[] chars = str.split("");
        for (int i = 0; i < chars.length; i++) {
            System.out.println(i + ":" + chars[i]);
        }
    }
}

The output I'm getting is:
0:
1:h
2:e
3:l
4:l
5:o

I'm getting an empty string as the first element of the array. I was expecting the output to be without empty string and the length of chars array to be 5 instead of 6. Why empty char is coming after splitting this String?

A: You can use String#toCharArray() method:
String str = "hello";
char[] arr = str.toCharArray();

As for your question, when you split on an empty string, you will get the first element as empty string, because, your string starts with an empty string, and after every character also, there is an empty string.
So, the first split occurs before the first character.
 h e l l o
^ ^ ^ ^ ^ ^
"Split location"

The trailing empty strings are discarded, as specified in documentation:

Trailing empty strings are therefore not included in the resulting array.

A: Have you tried the toCharArray() method from the String class.
The issue with splitting the String with this "" is that "" matches the first character in the string and therefore you get an empty character.
To verify this claim. You could try str.indexOf(""). This would give you a value 0. If the argument does not occur as a substring, -1 is returned, according to the documentation.

A: Like others have noted, using toCharArray() is the preferred method to do this kind of operation. Since the OP wants to know why the first string is empty when using split(""), it is because empty string is the first match even before the 1st character is parsed. As per documentation, only trailing empty strings are ignored and not the leading empty strings.
In order to work around this problem you can use negative look behind. So, to use split and ignore the first empty string your regex should be:
str.split("(?<!^)")


text:
Q: Variation in SharePoint 2013 I am using Variation in SharePoint 2013. When I hit my root site i.e
www.abc.com
It goes to the
www.abc.com/_layouts/15/start.aspx#/Pages/VariationRoot.aspx
And then goes to the
www.abc.com/en-us
I want to remove this glitch.

A: Minimal Download Strategy, a new feature implemented in SharePoint 2013 to improve the performance. It is activated by default in SharePoint site. It's a technique to use single page "_layouts/15/start.aspx" with URL encoded with following # text.
Minimal Download Strategy will improve the performance of SharePoint site by improving Navigation, Fast Rendering on the client browser. Also reduces the page loading time, because no need to get the duplicate Data from server.
In my case the redirection is happening because of MDS. Disable this by navigating to SharePoint Site Settings Page, Click on Manage Site Features link in Site Actions section -> Deactivate Minimal Download Strategy feature.
http://www.sharepoint2013.me/Blog/Post/386/Remove--_layouts-15-start-aspx---extension-in-SharePoint-URL-address-bar-


text:
Q: Spring 3.1: How do I inject a bean created in a different configuration class I'm just setting up a web application using Spring 3.1 and I'm trying to do this by using java configuration.
I have two configuration classes "AppConfig" (general bean definitions) and "WebConfig" (Spring MVC configuration). How can I reference a bean that has been declared in AppConfig in the WebConfig class?
Below, the validator in the AppConfig configuration class should use the messageSource fromn WebConfig.
AppConfig:
@Configuration
@ComponentScan(basePackages = { "com.example" })
public class AppConfig {

    @Bean
    public Validator validator() {
        final LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setValidationMessageSource(messageSource());
        return validator;
    }

}

WebConfig:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.example.common.web", "com.example.web"  })
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ReloadableResourceBundleMessageSource messageSource() {
        final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages");
        return messageSource;
    }

}

When I want to reference a bean from the same configuration class, I'd just call its setup method, but I obviously cannot do this when the bean is declared in another class.
Your advice will be greatly appreciated!

A: Configurations are beans, too, so you can use @Autowired
public class WebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private Validator validator;

    ...
}

A: There are two ways to do so:
public class WebConfig {
    @Autowired
    AppConfig appconfig;

    ...
}

or, as Aaron Digulla mentioned:
public class WebConfig {
    @Autowired
    Validator validator;

    ...
}

I prefer the first form, with one autowiring you can access the whole configuration, and then you can access its beans, by calling theNewBean.setValidator(appConfig.validator());.

A: I think Aaron Digulla and Amir Pashazadeh are both correct but there is also another annotation since JSR 330 was introduced. You can also use @Inject
@Inject
private Validator validator;

http://docs.spring.io/spring/docs/3.0.x/reference/beans.html#beans-autowired-annotation


text:
Q: How to create an ellipse in svg I'm trying to add an ellipse in a SVG
(original snippet)

    <svg>
      <rect x="0" y="0" width="100" height="100"></rect>
      <circle cx="200" cy="0" r="100"></circle>
      <ellipse cx="400" cy="0" rx="100" ry="50" fill="yellow"></ellipse>
    </svg>

But adding some attributes works:
(working snippet)

    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%">
      <rect x="0" y="0" width="100" height="100"></rect>
      <circle cx="200" cy="0" r="100"></circle>
      <ellipse cx="400" cy="0" rx="100" ry="50" fill="yellow"></ellipse>
    </svg>

Questions:

*

*What are the attributes of xmlns and version for?

*Why is the ellipse NOT showing up in the original snippet (but the rect and the circle show up properly)?

See here for a jsfiddle.

A: If you don't provide a canvas size the <svg> element (same as all replaced elements) defaults to 300px x 150px. Your ellipse is at rx="400" so is outside the canvas. Setting a larger canvas size fixes thing so you can see the ellipse.
version is pointless, xmlns is only required for standalone SVG files, if you're embedding things in an html page as we're doing here with snippets you can omit both.

svg {
  width: 100%;
  height: 100%;
}
<svg>
    <rect x="0" y="0" width="100" height="100"></rect>
    <circle cx="200" cy="0" r="100"></circle>
    <ellipse cx="400" cy="0" rx="100" ry="50" fill="yellow"></ellipse>
</svg>

A: What prevents the ellipse from displaying is the lack of width attribute, as this snippet illustrates:

<svg width="350">
  <rect x="0" y="0" width="100" height="100"></rect>
  <circle cx="200" cy="0" r="100"></circle>
  <ellipse cx="400" cy="0" rx="100" ry="50" fill="yellow"></ellipse>
</svg>

The viewport size defaults to 300x150 thus everything else gets cropped.


text:
Q: Is this usage correct: "The late Professor Emeritus Professor Johannes Kinfu dies"? I saw it as a headline on the Addis Ababa University website. Does late in this instance mean something else?

A: Although not commonly used in this way today, late can mean "former" OxfordDictionaries.com.
However, from what I can gather from AAU, Johannes Kinfu was a living Professor Emeritus when he passed away.
Current usage would make using late to mean "former" tricky, and not worth trying.

A: Sounds like tautology to me. IMHO, the headline should be:
'Professor XYZ dies'
Then, when talking about him: 'The late Professor XYZ ...'


text:
Q: How can I query/retrieve a random object from a parse class using swift? I've looked all over and have found no joy.  I was wondering if someone could help me figure out how to retrieve a random object from a class on parse.com using swift in an iOS app.  By no means am I asking someone to write my code, because then what would I learn, but I was wondering if someone could maybe provide a generic example that I could adapt to my project and future projects.
Let's say the class is called ParseClass, and I will need to populate three variables with data from the object in parse., A, B, C -- two with strings, one as an array of strings.  Let's say there are ... idk ... 50 objects in the parse class, and I need to retrieve them one at a time randomly.
Logically, I get it ... I need to do a count of the objects in the parseclass, then get a random number from that count, and then use that number to retrieve the object somehow (either directly from parse using a skip random query limit 1, or maybe by getting all the objects into an array (whichever is the best/most efficient code).  I just don't know how to format/write the code in swift.  Any one think they could help me (and many others apparently) with some generic code I could adapt to my specific project??
Here is some generic code ... I can start it -- I got a basic idea of how it should be, I just don't know swift well enough to complete the block.
var A  : String!
var B  : [String]!
var C  : String!

    var query : PFQuery = PFQuery(className: "ParseClass")
    query.findObjectsInBackgroundWithBlock {
        (objects : [AnyObject]!, error : NSError!) -> Void in

//now what?
I've seen this in other questions here, but I don't know how to incorporate it.
let randomSkip = arc4random_uniform(count)

query.skip = randomSkip, and query.limit = 1.

Any help on this would be greatly appreciated.
Oh -- just saw this in another thread ... it's basically doing what I need, but in objective C and it looks like with only 2 variables... could someone help me rewrite in swift?  Sorry to be so loquacious ... the burden of a novice.  I promise as I grow more adept, I will help other novices most sympathetically.  :-)
    - (void)randomQuestion:(void (^)(NSString *question, NSArray *answers))completion {
PFQuery *countQuery = [PFQuery queryWithClassName:@"ParseClass"];
[countQuery countObjectsInBackgroundWithBlock:^(int count, NSError *error) {
    NSInteger randomSkip = arc4random_uniform(count);
    PFQuery *query = [PFQuery queryWithClassName:@"ParseClass"];
    query.skip = randomSkip;
    query.limit = 1;
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            if (objects.count) {
                PFObject *ParseClassObject = objects[0];
                NSString *A = ParseClassObject[@"A"];
                NSArray *B = ParseClassObject[@"B"];
                completion(A, B);
            } else {
                NSLog(@"no error, but no ParseClass objects found");
            }
        } else {
            NSLog(@"there was an error %@", error);
            completion(nil, nil);
        }
    }];
}];

}

A: ObjectHolder should be objectHolder, or objects because it's a parameter name.
Your count for arc4random_uniform would be objects.count.
Downloading the objects and randomly accessing them locally will be most efficient if you need to display all of them anyway. Multiple downloads isn't great.
You're going to run into size limits eventually as the download row count is limited. Perhaps you could download pages and treat the items in each page as a separate collection to view randomly...
So, you wouldn't be using skip or limit, you would just be accessing elements in the objects array.
Removing the items from the array after you've used them is easiest. Or you can randomly sort the array so you don't need to remove

A: One way you can do it is to set another key called e.g. questionsNumber and each question will be be in that questionNumbers row. And then query the number from the arc4random_uniform(count) so something like this:
var query = PFQuery(className: "ParseClass")
        let randomNumber = arc4random_uniform(count)
        var randomNumberCast = Int(randomNumber)
        query.whereKey("questionNumber", equalTo: randomNumberCast)
        query.getFirstObjectInBackgroundWithBlock { (object: PFObject!, error: NSError!) -> Void in
            if error == nil {
                let questions = object["questions"] as String //This will equal your question at random.

        }

}


text: Q: Why is the cross-product of two vectors perpendicular to that plane? In my class I have learned that the cross-product of two vectors are perpendicular to those two vectors. Teacher says it has something to do with torque. If it is, then 'if we have to open a door it should be easy to open it by exerting force on top of the hinge', but we know it is not. Is there any scientific reasoning to this question, or is it a standard way of multiplying vectors?


text:
Q: POST Request with Form Data Only Working for Current Year I'm attempting to send form data to get the information on bills for each year. Everything works as expected for 2019 however if I change the form data "ctl00$rilinContent$cbYear" to a prior year it just returns the default search page (which defaults to 2019 as the year) and thus gives no information to collect.
I attempted using "__EVENTTARGET" to change the year but didn't have any success, Thanks for any help you may be able to provide.
Sample Code
import requests

default_data = {'__EVENTTARGET': '',
            '__EVENTARGUMENT': '',
            '__LASTFOCUS': '',
            '__VIEWSTATE': 'PZZDS...', #(long string)
            '__VIEWSTATEGENERATOR': 'B3C16737',
            '__EVENTVALIDATION': 'kp03y...', #(long string)
            'ctl00$rilinContent$cbYear': '',
            'ctl00$rilinContent$txtReport': '',
            'ctl00$rilinContent$cbCommittee': '',
            'ctl00$rilinContent$comm': 'cbxIn',
            'ctl00$rilinContent$cbCategory': '',
            'ctl00$rilinContent$cbSponsor': '',
            'ctl00$rilinContent$cbxPrime': '',
            'ctl00$rilinContent$txtBills': '',
            'ctl00$rilinContent$cbxSortNumeric': '',
            'ctl00$rilinContent$txtBillFrom': '',
            'ctl00$rilinContent$txtBillTo': '',
            'ctl00$rilinContent$cbAction': '',
            'ctl00$rilinContent$cbxLastAction': '',
            'ctl00$rilinContent$cmdReport': 'Enter',
            'ctl00$rilinContent$hfQuery': ''}

url = "http://status.rilin.state.ri.us/"
data = default_data

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

data['ctl00$rilinContent$cbYear'] = '2019'
data['ctl00$rilinContent$cbCategory'] = '307'

r = requests.post(url, data=data, headers=headers).text

# simple test
string = 'Legislative Status Report'
string in r

A: I think the page does an initial update via POST for year then subsequently for marriage. The following can be simplified I'm sure but seems to work
import requests
from bs4 import BeautifulSoup as bs

default_data = {'__EVENTTARGET': '',
            '__EVENTARGUMENT': '',
            '__LASTFOCUS': '',
            '__VIEWSTATE': '',
            '__VIEWSTATEGENERATOR': 'B3C16737',
            '__EVENTVALIDATION': '',
            'ctl00$rilinContent$cbYear': '',
            'ctl00$rilinContent$txtReport': '',
            'ctl00$rilinContent$cbCommittee': '',
            'ctl00$rilinContent$comm': 'cbxIn',
            'ctl00$rilinContent$cbCategory': '',
            'ctl00$rilinContent$cbSponsor': '',
            'ctl00$rilinContent$cbxPrime': '',
            'ctl00$rilinContent$txtBills': '',
            'ctl00$rilinContent$cbxSortNumeric': '',
            'ctl00$rilinContent$txtBillFrom': '',
            'ctl00$rilinContent$txtBillTo': '',
            'ctl00$rilinContent$cbAction': '',
            'ctl00$rilinContent$cbxLastAction': '',
            'ctl00$rilinContent$cmdReport': '', #'Enter'
            'ctl00$rilinContent$hfQuery': ''}

url = "http://status.rilin.state.ri.us/"
data = default_data

headers = {
    'User-Agent': 'Mozilla/5.0',
    'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'Content-Type' : 'application/x-www-form-urlencoded'
}

data['ctl00$rilinContent$cbYear'] = 2017

with requests.Session() as s:
    r = s.get(url)
    soup = bs(r.content, 'lxml')
    vs = soup.select_one('#__VIEWSTATE')['value']
    ev = soup.select_one('#__EVENTVALIDATION')['value']
    data['__VIEWSTATE'] = vs
    data['__EVENTVALIDATION'] = ev
    r = s.post(url, data=data, headers=headers)
    soup = bs(r.content, 'lxml')
    vs = soup.select_one('#__VIEWSTATE')['value']
    ev = soup.select_one('#__EVENTVALIDATION')['value']
    data['ctl00$rilinContent$cbCategory'] = 307
    data['__VIEWSTATE'] = vs
    data['__EVENTVALIDATION'] = ev
    data['ctl00$rilinContent$cmdReport'] = 'Enter'
    r = s.post(url, data=data, headers=headers)
    soup = bs(r.content, 'lxml')
    print(soup)


text:
Q: json-framework "Unknown property attribute" Before I used JSON-framework,https://github.com/stig/json-framework/, it was great. But now I get an error "Unknow property attribute". Even when I run the example provided with the framework I have the same error

A: Upgrade your Xcode to version 4.2 to get the quoted source code compiled successfully.


text:
Q: É possível instalar um serviço do windows a partir de uma DLL? (Delphi) Eu possuo uma dll que possui métodos que deverão ser executados num serviço do windows. Eu fiz uma pesquisa e vi que para instalar um serviço, eu precisaria de um executável. Possuo a versão 2007 do Delphi e Windows 7. Algo como:
rundll32.exe <nomedll>.dll /install


text:
Q: Rails 4 ActiveRecord Module with ActiveSupport So I have a few different models in my Rails 4 app that have image uploads. Rather than adding identical code to each of the models I've created a module that I can include into all of them.
Here it is:
module WithImage
  extend ActiveSupport::Concern

  included do
    attr_accessor :photo

    has_one :medium, as: :imageable

    after_save :find_or_create_medium, if: :photo?

    def photo?
      self.photo.present?
    end

    def find_or_create_medium
      medium = Medium.find_or_initialize_by_imageable_id_and_imageable_type(self.id, self.class.to_s)
      medium.attachment = photo
      medium.save
    end
  end

  def photo_url
    medium.attachment if medium.present?
  end
end

class ActiveRecord::Base
  include WithImage
end

A Medium (singular of media) in this case is a polymorphic model that has paperclip on it. The attr_accessor is a f.file_field :photo that I have on the various forms.
Here's my PurchaseType Model (that uses this mixin):
class PurchaseType < ActiveRecord::Base
  include WithImage

  validates_presence_of :name, :type, :price
end

So here's the thing, the after_save works great here. However, when I go to the console and do PurchaseType.last.photo_url I get the following error:
ActiveRecord::ActiveRecordError: ActiveRecord::Base doesn't belong in a hierarchy descending from ActiveRecord

I haven't the faintest clue what this means or why it is happening. Anyone have any insight?
Thanks!

A: It turns out I was trying to do things I had seen in various examples of modules. It was simple to get it working:
module WithImage
  extend ActiveSupport::Concern

  included do
    attr_accessor :photo

    has_one :medium, as: :imageable

    after_save :find_or_create_medium, if: :photo?

    def photo?
      self.photo.present?
    end

    def find_or_create_medium
      medium = Medium.find_or_initialize_by_imageable_id_and_imageable_type(self.id, self.class.to_s)
      medium.attachment = photo
      medium.save
    end

    def photo_url
      medium.attachment.url if medium.present?
    end
  end
end


text:
Q: Javascript bind click to a href I have code that bind click event to ul li a. I'd like to set global variable id on click. First console.log return 1065, but second got nothing. How can I get global id after click? Here is my code:

var id = 0;

$(function() {
    var clickHandler = ('ontouchstart' in document.documentElement ? "touchstart" : "click");

    $('ul li a').bind(clickHandler, function(e) {
        var item = $(this).parent();
        id = item[0].id;
        console.log(id);
    });

    console.log(id);
});

             Metrics


text:
Q: QGIS layers don't overlay after trying 'enable on the fly' and CRS settings I know there are already many questions about this topic, but none of the answers helped me so far. I have two layers I want to overlay in QGIS. One of them is an Excell file with the coordinates of households in it. I changed it to .csv and projected it in QGIS with 'add deliminate text layer'. The other one are the outlines of the provinces of Dhulikhel municipality, Nepal. I got these from my colleague. I want to project the households in the provinces.
I would like to project these layers in WGS84 UTM zone 45N EPSG 32645.
The first layer is in this projection, the second one isn't, it is in a for me unknown 'Generated CRS'. I tried enable on the fly projection and than the save as option for the second layer. This however did not work. It seems to be something with the spatial reference system units.
I hope someone can help me. These are the properties of my layers:
Households:
General:
Storage type of this layer: Delimited text file
Source for this layer: file:///C:/Documents%20and%20Settings/Administrator/Desktop/GIS/Household_survey_results%20(6).csv?delimiter=,&delimiterType=plain&xField=Longitude&yField=Latitude
Geometry type of the features in this layer: Point
The number of features in this layer: 1681
Editing capabilities of this layer:
Extents:
In layer spatial reference system units : xMin,yMin 85.5281,27.6066 : xMax,yMax 85.5771,27.6372
Layer Spatial Reference System:
+proj=utm +zone=45 +datum=WGS84 +units=m +no_defs

Provinces:
General:
Storage type of this layer: PGeo
Source for this layer: C:/Documents and Settings/Administrator/Desktop/GIS/Dhulikhel_Digital_Data/Administrative.mdb|layername=Ward_line
Geometry type of the features in this layer: Line
The number of features in this layer: 34
Editing capabilities of this layer: Fast Access to Features at ID
Extents:
In layer spatial reference system units : xMin,yMin 353921.13,3054982.59 : xMax,yMax 360199.97,3058637.05
Layer Spatial Reference System:
+proj=tmerc +lat_0=0 +lon_0=87 +k=0.9999 +x_0=500000 +y_0=0 +a=6377299.36559538 +b=6356098.359005156 +units=m +no_defs

A: Looking at the extent given, the first layer is pretty sure in degrees.
So try EPSG:4326 for this one.
The second one looks OK at first sight, but it is rather Kalianpur 1880 mixed with UTM 45N.
This is nearly, but not exact Kalianpur 1975 UTM 45 as used in India.
If you discover offsets of about 200m for all data, you have to apply +towgs84 parameters.


text:
Q: Puppeteer how to check if page is navigated and perform task if not navigated On the login page, I'm trying to figure out whether the google recaptcha appears or not. If it does, I want to run a block of code and otherwise navigate as usual.
await page.goto(
    url
  );
  await page.waitForSelector("#username");
  await page.type("#username", process.env.EMAIL);
  await page.type("#password", process.env.PSWD);
  await  page.$eval("#signIn > div > button", (el) => el.click()) //this line sometimes triggers recaptcha

  {//here wait for navigation and check if google captcha appears}

  //then run the following code:
  await page.solveRecaptchas();
  await Promise.all([
    page.waitForNavigation(),
    page.click("#signIn"),
  ]);

I've tried using page.waitForNavigation but it causes timeout if recaptcha appears. What can I do to run the bottom block of code ONLY if google recaptcha appears?
I also tried conditionally running the block of code on if recaptcha-token is present but I checked the dom and recaptcha element is always present and only prompts image select randomly. Basically I'm available to navigate sometimes without having to perform any captcha and sometimes i'm prompted with image select.
Thanks!

A: Maybe something like this?
const [_, navigation] = await Promise.allSettled([
  element.click(),
  page.waitForNavigation(),
]);

if (navigation.status === 'fulfilled') /* There was navigation. */;
else /* There was timeout, no navigation. */;


text:
Q: How can I get a collection inside a QuerySnapshot On the explore page, I get() the entire users collection to create a user list and search results. Inside each of those user documents is a collection posts that I also need to get to create a GridView of each post. I want to reuse that users collection QuerySnapshot instead of fetching each posts collection again to save money. Is this possible?
Here is my current function:
  void fetchUsers() async {
    final userRef = FirebaseFirestore.instance.collection('users');

    final QuerySnapshot result = await userRef.get();

    final docs = result.docs.asMap();

    docs.forEach((index, value) {
      final profile =
          ProfileObject.fromJson(value.data() as Map<String, dynamic>);

      usersList.add(UserSearchResult(profile, value.id));

/// Below is the code for getting the posts, not working, need ideas

      final QuerySnapshot postsResult = value.get('posts');

      final posts = postsResult.docs.asMap();

      posts.forEach((index, value) {
        final post = Post.fromJson(value.data() as Map<String, dynamic>);

        postsList.add(post);
      });
    });

    print(usersList);
    print(postsList);
  }

Here is the structure of my Firestore:

*

*users

*

*uid (doc)

*

*posts (collection)

*info (fields)

*uid (doc)

*

*posts (collection)

*info (fields)

A: It is not possible to call a collection to get all sub-collections. You should restructure your database to include sub-collection data in document itself. You can use a map or list for that. But remember, calling everything in one go may end up in slow performance and you might end up losing your customers. So the best way is to include the info in every posts' documents. That way, you won't loss your money and user won't feel lag in performance.

A: It is not possible. You fetch a document, then fetch the (sub)collection under it.
Subcollection data are not included in the initial document snapshots because Firestore queries are shallow. There shouldn't be any cost savings that you can do there?
See the similar Q&A:
Firestore: Get subcollection of document found with where


text:
Q: Custom query with querydsl and jpa Is it possible to write custom queries with query dsl?
e.g. (self outer join)
SELECT test1.SURNAME, test2.SURNAME
FROM Test test1
LEFT OUTER JOIN Test test2 ON test1.SUPERVISOR_WARRANT_NUMBER = test2.WARRANT_NUMBER
WHERE test1.SURNAME LIKE '%Your name%';

So I would like to do above with
@Repository
public interface Test <TestModel> , QueryDslPredicateExecutor<TestModel> {
    @Override
    @Query("SELECT test FROM Test") /*do outer self join in Query*/
    Page<TestModel> findAll(Predicate prdct, Pageable pgbl);
}

The exception I get with above code is:
org.springframework.dao.InvalidDataAccessApiUsageException: Parameter with that position [1] did not exist; nested exception is java.lang.IllegalArgumentException: Parameter with that position [1] did not exist

If above is not possible, what would be the best approach in java to write dynamic queries (with various joins) with paging?


text:
Q: Continuous Pull in Ampscript, GTL, or SSJS from a JSON file I am trying to find the best method in a Marketing Cloud email to continuously pull data from a JSON file that updates every 5 seconds so that it is "Live" Data within the email.
Currently I am using Ampscript and SSJS to pull in the data upon send to the individual recipient. This also allows the VAWP link to show the current data upon refresh for a limited time.
EDIT: We would like it to continuously update and show after the email send, similar to a countdown timer, but it is counting up based on the data in the JSON.
JSON Data Example
{
   "Odometers": [
       {
          "LevelId": 28,
          "Value": 57102.82
       },
       {
          "LevelId": 914,
          "Value": 50863.31
       }
   ]
}

Code Snippet Example
%%[
var @response,@value,@progressive,@locale

set @response = HTTPGET("https://URL/filename.json",false,0,@CallStatus)
]%%

%%[
set @locale = "en-US"
set @progressive  = FormatCurrency(@value, @locale)
]%%

The current amount is %%=v(@progressive)=%%

 @response: %%=v(@response)=%%

A: It is not technically possible to replace/update text content in an email after it has been sent. The examples shown e.g. here: How to refer Javascript cloud page in my email in content builder? and or here: Real time dynamic emails all rely on images, that are fetched at open. But the referencing URLs remain the same once the email has been generated and sent.
All of the technologies you mention: SSJS, GTL, Ampscript are processed at sendtime, and content from any external URLs will not be refreshed afterwards.