text:
Q: Postgres partitioning? My software runs a cronjob every 30 minutes, which pulls data from Google Analytics / Social networks and inserts the results into a Postgres DB.
The data looks like this:
url text NOT NULL,
rangeStart timestamp NOT NULL,
rangeEnd timestamp NOT NULL,
createdAt timestamp DEFAULT now() NOT NULL,
...
(various integer columns)

Since one query returns 10 000+ items, it's obviously not a good idea to store this data in a single table. At this rate, the cronjob will generate about 480 000 records a day and about 14.5 million a month.
I think the solution would be using several tables, for example I could use a specific table to store data generated in a given month: stats_2015_09, stats_2015_10, stats_2015_11 etc.
I know Postgres supports table partitioning. However, I'm new to this concept, so I'm not sure what's the best way to do this. Do I need partitioning in this case, or should I just create these tables manually? Or maybe there is a better solution?
The data will be queried later in various ways, and those queries are expected to run fast.
EDIT:
If I end up with 12-14 tables, each storing 10-20 millions rows, Postgres should be still able to run select statements quickly, right? Inserts don't have to be super fast.

A: Partitioning is a good idea under various circumstances. Two that come to mind are:

*

*Your queries have a WHERE clause that can be readily mapped onto one or a handful of partitions.

*You want a speedy way to delete historical data (dropping a partition is faster than deleting records).

Without knowledge of the types of queries that you want to run, it is difficult to say if partitioning is a good idea.
I think I can say that splitting the data into different tables is a bad idea because it is a maintenance nightmare:

*

*You can't have foreign key references into the table.

*Queries spanning multiple tables are cumbersome, so simple questions are hard to answer.

*Maintaining tables becomes a nightmare (adding/removing a column).

*Permissions have to be carefully maintained, if you have users with different roles.

In any case, the place to start is with Postgres's documentation on partitioning, which is here. I should note that Postgres's implementation is a bit more awkward than in other databases, so you might want to review the documentation for MySQL or SQL Server to get an idea of what it is doing.

A: Firstly, I would like to challenge the premise of your question:

Since one query returns 10 000+ items, it's obviously not a good idea to store this data in a single table.

As far as I know, there is no fundamental reason why the database would not cope fine with a single table of many millions of rows. At the extreme, if you created a table with no indexes, and simply appended rows to it, Postgres could simply carry on writing these rows to disk until you ran out of storage space. (There may be other limits internally, I'm not sure; but if so, they're big.)
The problems only come when you try to do something with that data, and the exact problems - and therefore exact solutions - depend on what you do.
If you want to regularly delete all rows which were inserted more than a fixed timescale ago, you could partition the data on the createdAt column. The DELETE would then become a very efficient DROP TABLE, and all INSERTs would be routed through a trigger to the "current" partition (or could even by-pass it if your import script was aware of the partition naming scheme). SELECTs, however, would probably not be able to specify a range of createAt values in their WHERE clause, and would thus need to query all partitions and combine the results. The more partitions you keep around at a time, the less efficient this would be.
Alternatively, you might examine the workload on the table and see that all queries either already do, or easily can, explicitly state a rangeStart value. In that case, you could partition on rangeStart, and the query planner would be able to eliminate all but one or a few partitions when planning each SELECT query. INSERTs would need to be routed through a trigger to the appropriate table, and maintenance operations (such as deleting old data that is no longer needed) would be much less efficient.
Or perhaps you know that once rangeEnd becomes "too old" you will no longer need the data, and can get both benefits: partition by rangeEnd, ensure all your SELECT queries explicitly mention rangeEnd, and drop partitions containing data you are no longer interested in.
To borrow Linus Torvald's terminology from git, the "plumbing" for partitioning is built into Postgres in the form of table inheritance, as documented here, but there is little in the way of "porcelain" other than examples in the manual. However, there is a very good extension called pg_partman which provides functions for managing partition sets based on either IDs or date ranges; it's well worth reading through the documentation to understand the different modes of operation. In my case, none quite matched, but forking that extension was significantly easier than writing everything from scratch.
Remember that partitioning does not come free, and if there is no obvious candidate for a column to partition by based on the kind of considerations above, you may actually be better off leaving the data in one table, and considering other optimisation strategies. For instance, partial indexes (CREATE INDEX ... WHERE) might be able to handle the most commonly queried subset of rows; perhaps combined with "covering indexes", where Postgres can return the query results directly from the index without reference to the main table structure ("index-only scans").


text:
Q: Unable to decrypt text files with openssl on Ubuntu 18.04 I am unable to decrypt a number of text files I encrypted with openssl on Ubuntu 16.04. I always get this error message:
$ openssl des3 -d < ~/ISRIC/credentials.txt.des3.old > ~/temp/credentials.txt.old.2
enter des-ede3-cbc decryption password:
bad decrypt
139771261990464:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:../crypto/evp/evp_enc.c:536:

I am pretty sure the password is correct. What is the problem?

A: For files which are already encrypted, you can use the md option to force the old md5 password method.
This fixed my issue with files encrypted with 1.0.2 with aes-256-cbc which would not decrypt on 18.04 (openssl 1.1.0+).
My previous decrypt:
cat encfile | openssl enc -d -aes-256-cbc -base64 >plainfile

My new decrypt on 18.04:
cat encfile | openssl enc -md md5 -d -aes-256-cbc -base64 >plainfile

Note:
This will not work with files encrypted on 18.04 (openssl 1.1.0g+) as those will have used the newer SHA password method by default as Luis de Sousa notes.
References:
https://askubuntu.com/a/1067765/873241 (Luis de Sousa's answer)
https://bugzilla.redhat.com/show_bug.cgi?id=1520084
https://github.com/fastlane/fastlane/issues/9542

A: The password based encryption algorithm used in openssl changed from MD5 in version 1.0.2 (shipped with Ubuntu 16.04) to SHA256 in version 1.1.0 (Ubuntu 18.04). For that reason, any files encrypted on Ubuntu 16.04 fail to be decrypted on Ubuntu 18.04. The solution is to install the previous version of openssl, decrypt the files and encryt them back again with the newer version. Step by step:
Start by downloading the older version of openssl (this is the amd64 build, for other builds check packages.ubuntu.com):
wget http://security.ubuntu.com/ubuntu/pool/main/o/openssl/openssl_1.0.2g-1ubuntu13.6_amd64.deb

Now install the package directly with dpkg, this will disable the newer version:
$ sudo dpkg -i openssl_1.0.2g-1ubuntu13.6_amd64.deb

Make sure you got the right version:
$ openssl version
OpenSSL 1.0.2g  1 Mar 2016 (Library: OpenSSL 1.0.2n  7 Dec 2017)

And now decrypt the file:
$ openssl des3 -d < secret.des3 > secret.txt

Then install the latest openssl build, apt is an option:
$ sudo apt install openssl

Making sure it is the latest version:
$ openssl version
OpenSSL 1.1.0g  2 Nov 2017

And then encrypt the file again with the latest version:
$ openssl des3 < secret.txt > secret.des3

Finally remove the .deb file downloaded in the begining:
$ rm openssl_1.0.2g-1ubuntu13.6_amd64.deb

A: The other answer is essentially correct. though other things have changed around these versions (v1.1.0 and v1.1.1) that is good to be aware of.
First the default password hashing digest has changed, going from md5 to sha512
And second the addition the "-pbkdf2" "-iter" which has been needed for a long time. However the default iteration count is far too low, and should be set as high as possible without becoming too annoying. Big enough to take 1/2 second is generally acceptable for both encrypting and decrypting, but makes it very very difficult for brute forced password guessing.
The problem is now we have all these new options and defaults, as well as different digests and cyphers, you need to remember all these options do you can decrypt the encrypted file. That is whatever options was decided on to encrypt must be used to decrypt. However openssl only stores some 'file magic' (EG "Salted__" at the start of the file, and the random "salt" that was used, with the encrypted file. It leaves it up to you to remember everything else!
Aespipe is a old program that got around this by saving some of this information as a extra header to the encrypted data, but it is now becomming dated, and its format does not allow for the new options, or for easy expansion.
As a alternative I have been creating a new script "keepout" as a wrapper around "openssl enc" to save those extra options that is needed to remember how to decrypt that specific file, even as newer options, cyphers, or larger iterations are used when encrypting. Basically it saves the openssl option needed with the data.
https://antofthy.gitlab.io/software/#keepout

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to fetch google plus user info using swift 4 ,while using social integratioin in my app How to fetch google plus user info using swift 4? Social integration is used to login with google plus but i need most of the user profile info to fetch .
i want to get user profile info like email username dob etc from the google plus login .

A: AppDelegate.swift:
Initiate google-framework in AppDelegate.swift:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Initiate gogle sign-in
    GIDSignIn.sharedInstance().clientID = SocialLogin.Google().clientId
    return true
}

handle callback as:
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool {
    print("openUrl scheme: \(url)")
    if let scheme = url.scheme {
        if scheme.hasPrefix("google".lowercased()) {
            return GIDSignIn.sharedInstance().handle(url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplicationOpenURLOptionsKey.annotation])
        }
    }
    return false
}

GoogleLogin.swift:
Add below file GoogleLogin.swift in your project:
import GoogleSignIn

class GoogleLogin: UIViewController {

    static let shared = GoogleLogin()

    var completionBlock: ((GIDGoogleUser?) -> Void)?

    func login(onCompletion: @escaping ((_ dictionary: [String: String]?) -> Void)) {
        completionBlock = onCompletion

        GIDSignIn.sharedInstance().delegate = self
        GIDSignIn.sharedInstance().uiDelegate = self

        GIDSignIn.sharedInstance().signOut()
        GIDSignIn.sharedInstance().signIn()
    }

}

extension GoogleLogin: GIDSignInDelegate {

    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        if error == nil {
            self.completionBlock?(user)
        } else {
            print("Error in didSignInFor: \(error.localizedDescription)")
            self.completionBlock?(nil)
        }
    }

    func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
        print("In didDisconnectWith: \(error.localizedDescription)")
        self.completionBlock?(nil)
    }

}

extension GoogleLogin: GIDSignInUIDelegate {

    func sign(inWillDispatch signIn: GIDSignIn!, error: Error!) {
        //stop your loader here
        //myActivityIndicator.stopAnimating()
    }

    // Present a view that prompts the user to sign in with Google
    func sign(_ signIn: GIDSignIn!, present viewController: UIViewController!) {
        self.present(viewController, animated: true, completion: nil)
    }

    // Dismiss the "Sign in with Google" view
    func sign(_ signIn: GIDSignIn!, dismiss viewController: UIViewController!) {
        self.dismiss(animated: true, completion: nil)
    }

}


text:
Q: Inverse of the following $2\times 2$ Matrix I was asked to find the inverse of the following Matrix $A$:
$$\begin{bmatrix}8&-3\\-4&-7\end{bmatrix}$$
I created a new Matrix, $[A|I]$, where $I$ is the $2\times 2$ identity matrix and row reduced it. I ended up with:
$$\begin{bmatrix}7/68&31/68\\-1/17&-2/17\end{bmatrix}$$
But apparently I'm wrong. Any ideas on how to find the inverse?

A: Formula for the inverse of a $2$ by $2$ matrix is
$$\begin{bmatrix}a & b \\ c & d\end{bmatrix}=\frac{1}{ad-bc}\begin{bmatrix}d & -b \\ -c & a \end{bmatrix}$$

A: Setting up the system $[A\mid I]$ and row reducing gives:
$$\begin{bmatrix}8&-3&|&1&0\\-4&-7&|&0&1\end{bmatrix}\xrightarrow{(1)}\begin{bmatrix}0&-17&|&1&2\\-4&-7&|&0&1\end{bmatrix}\xrightarrow{(2)}\begin{bmatrix}0&1&|&-1/17&-2/17\\1&7/4&|&0&-1/4\end{bmatrix}$$
where the steps are
$$\begin{align}&(1)\qquad R_2+R_1\mapsto R_1\\&(2)\qquad \begin{cases}-\frac{1}{17}R_1\mapsto R_1\\-\frac{1}{4}R_2\mapsto R_2\end{cases}\end{align}$$
I leave the final step to you, as it is fairly straight forward. Maybe you can spot your mistake from these first couple of steps. This method (i.e. row reducing the system $[A\mid I]$) is a very general method for finding the inverse, so it's good to familiarize yourself with it. However, in the trivial $2\times 2$ case, one often uses the formula that Siong Thye Goh gives.


text:
Q: ASP.net main thread block during long running process I have a page from where a user can upload excel sheet and add all data into database. If any user run this page and data upload is in progress other users are not able to access application.
Application is hosted in IIS7.


text:
Q: Headless Install gets stuck at fsck I have been trying all of the tricks I have found to allow fsck to automatically fix errors without any user intervention however it seems that I can still get into this situation which is a major problem.
I've tried the following:

*

*FSCKFIX=YES in /etc/init/rcS

*added fsck.fix=yes fsck.repair=yes to /etc/default/grub (then run update-grub)

Unfortunately this is an embedded install that always get a hard power down.  I am currently able to force this failure mode by setting the clock ahead, doing a soft-reboot, then doing a hard reboot.  It will get stuck everytime when I do this...
It is not clear exactly where the fsck call that is failing is coming from, although I do see the error log in /var/log/upstart/mountall.log.
This is a rather specific failure mode, hopefully someone out there has some nugget of wisdom for me...
Thanks


text:
Q: The normality and  intersection of two sylow group $G$ is of order 1225.
According to the Sylow theorem, we know that $H$ is the only sylow 5-subgroup of $G$ and $K$ is the only sylow 7-subgroup of $G$.
I am trying to prove that they are both normal but looking at the subgroup $gHg^{-1}$ which has the same order of H. What's next shall I look at?
And how can we prove that $H$$\cap$$K$ = {e}?
Could anyone give me a hint? Thanks!

A: Part of the Sylow theorem also says that all p-Sylow subgroups are conjugate.  From this you can get that a unique Sylow p-subgroup is normal, as well as characteristic.  And, these 3 conditions are equivalent for p-Sylows.  For the intersection, as Dylan's comment says, the intersection is a subgroup and must divide the orders of $H$ and $K$.


text:
Q: Clone git repository over ssh with username and password by Java I am trying to clone a git project with Java over ssh. I have username and password of a git-shell user as credentials. I can clone the project in terminal using the following command with no problem. (Of course, it asks for the password first)
git clone user@HOST:/path/Example.git

However when I try the following code using JGIT api
File localPath = new File("TempProject");
Git.cloneRepository()
    .setURI("ssh://HOST/path/example.git")
    .setDirectory(localPath)
    .setCredentialsProvider(new UsernamePasswordCredentialsProvider("***", "***"))
    .call();

I got
Exception in thread "main" org.eclipse.jgit.api.errors.TransportException: ssh://HOST/path/example.git: Auth fail

What should I do? Any ideas? (I am using OSX 10.9.4 and JDK 1.8)

A: For authentication with SSH, JGit uses JSch. JSch provides an SshSessionFactory to create and dispose SSH connections. The quickest way to tell JGit which SSH session factory should be used is to set it globally through SshSessionFactory.setInstance().
JGit provides an abstract JschConfigSessionFactory, whose configure method can be overridden to provide the password:
SshSessionFactory.setInstance( new JschConfigSessionFactory() {
    @Override
    protected void configure( Host host, Session session ) {
      session.setPassword( "password" );
    }
} );
Git.cloneRepository()
  .setURI( "ssh://username@host/path/repo.git" )
  .setDirectory( "/path/to/local/repo" )
  .call();

To set the SshSessionFactory in a more sensible way is slightly more complex. The CloneCommand - like all JGit command classes that may open a connection - inherits from TransportCommand. This class has a setTransportConfigCallback() method that can also be used to specify the SSH session factory for the actual command.
CloneCommand cloneCommand = Git.cloneRepository();
cloneCommand.setTransportConfigCallback( new TransportConfigCallback() {
  @Override
  public void configure( Transport transport ) {
    if( transport instanceof SshTransport ) {
      SshTransport sshTransport = ( SshTransport )transport;
      sshTransport.setSshSessionFactory( ... );
    }
  }
} );


text:
Q: Marking overdue dates on excel (bit more complicated) I have already figured out (thanks to stackoverflow) how to add automatic due dates, and how to mark them using conditional formatting.
I have 3 columns, one 'Status' with options 'Complete, Fail, Pending'. I have another column that automatically updates itself when a row is edited. And a 3rd column, with 15 days added to automatically updated column, which I call due date.
I want to make it so that if due date is passed when someone opens the workbook, the entire row is marked red or something. But I only want to do it for the Pending ones. If a row is marked Fail or Complete, it should not be marked red eventhough last time it was updated was weeks ago. How do i do it :(

A: You could format the overdue cell with a formula such as:
=AND([status cell] = "Pending", [due cell] > TODAY())
Quote below adapted from: https://www.ablebits.com/office-addins-blog/2014/06/17/excel-conditional-formatting-dates/

*

*On the Home tab, click Conditional Formatting menu > New Rule.

*Create    a new formatting rule based on a formula, as explianed in How to    create Excel conditional formatting rules with a
  formula.

*In the    "Format values where this formula is true" box, enter the following formula
=AND([status cell] = "Pending", [due cell] > TODAY())

*Click the Format… button and set up your    custom format by switching between the Font, Border and Fill tabs and    playing
  with different formatting options. When done, click the OK    button
  to preview the rule.


text:
Q: Filling Float buffer in Metal Problem:
I need to fill a MTLBuffer of Floats with a constant value — say 1729.68921. I also need it to be as fast as possible.
Therefore I'm prohibited from filling the buffer on the CPU side (i.e. getting UnsafeMutablePointer<Float> from the MTLBuffer and assigning in serial manner).
My approach
Ideally I'd use MTLBlitCommandEncoder.fill(), however AFAIK it's only capable to fill a buffer with UInt8 values (given that UInt8 is 1 byte long and Float is 4 bytes long, I can't specify arbitrary value of my Float constant).
So far I can see only 2 options left, but both seem to be overkill:

*

*create another buffer B filled with the constant value and copy its contents into my buffer via MTLBlitCommandEncoder

*create a kernel function that'd fill the buffer

Questions
What's the fastest way of filling MTLBuffer of Floats with a
constant value?

A: Using a compute shader that writes to multiple buffer elements from each thread was the fastest approach in my experiments. This is hardware-dependent, so you should test on the full range of devices you expect the app to be deployed on.
I wrote two compute shaders: one that fills 16 contiguous array elements without checking against the array bounds, and one that sets a single array element after checking against the length of the buffer:
kernel void fill_16_unchecked(device float *buffer  [[buffer(0)]],
                              constant float &value [[buffer(1)]],
                              uint index            [[thread_position_in_grid]])
{
    for (int i = 0; i < 16; ++i) {
        buffer[index * 16 + i] = value;
    }
}

kernel void single_fill_checked(device float *buffer         [[buffer(0)]],
                                constant float &value        [[buffer(1)]],
                                constant uint &buffer_length [[buffer(2)]],
                                uint index                   [[thread_position_in_grid]])
{
    if (index < buffer_length) {
        buffer[index] = value;
    }
}

If you know that your buffer count will always be a multiple of the thread execution width multiplied by the number of elements you set in the loop, you can just use the first function. The second function is a fallback for when you might dispatch a grid that would otherwise overrun the buffer.
Once you have two pipelines built from these functions, you can dispatch the work with a pair of compute commands as follows:
NSInteger executionWidth = [unchecked16Pipeline threadExecutionWidth];
id<MTLComputeCommandEncoder> computeEncoder = [commandBuffer computeCommandEncoder];
[computeEncoder setBuffer:buffer offset:0 atIndex:0];
[computeEncoder setBytes:&value length:sizeof(float) atIndex:1];
if (bufferCount / (executionWidth * 16) != 0) {
    [computeEncoder setComputePipelineState:unchecked16Pipeline];
    [computeEncoder dispatchThreadgroups:MTLSizeMake(bufferCount / (executionWidth * 16), 1, 1)
                   threadsPerThreadgroup:MTLSizeMake(executionWidth, 1, 1)];
}
if (bufferCount % (executionWidth * 16) != 0) {
    int remainder = bufferCount % (executionWidth * 16);
    [computeEncoder setComputePipelineState:checkedSinglePipeline];
    [computeEncoder setBytes:&bufferCount length:sizeof(bufferCount) atIndex:2];
    [computeEncoder dispatchThreadgroups:MTLSizeMake((remainder / executionWidth) + 1, 1, 1)
                   threadsPerThreadgroup:MTLSizeMake(executionWidth, 1, 1)];
}
[computeEncoder endEncoding];

Note that doing the work in this manner will not necessarily be faster than the naive approach that just writes one element per thread. In my tests, it was 40% faster on A8, roughly equivalent on A10, and 2-3x slower (!) on A9. Always test with your own workload.


text:
Q: Why didn't Molly Weasley remember the platform number? In the first Harry Potter book, Molly is seen asking her children "what platform number is it again?"

Heart hammering, Harry pushed his trolley after them. They stopped and so did he, just near enough to hear what they were saying.
  'Now, what's the platform number?' said the boys' mother.
  'Nine and three-quarters!' piped a small girl, also red-headed, who was holding her hand. 'Mum, can't I go...'
  'You're not old enough, Ginny, now be quiet. All right, Percy, you go first.'
  (Harry Potter and the Philosopher's Stone, Chapter Six, "The Journey from Platform Nine and Three-Quarters")

Why didn't she remember on her own? She would have been bringing kids there for the past 10 or so years, not to mention her own years at Hogwarts.

A: This is probably for Ginny's benefit. Ginny will be starting at Hogwarts the next year, and Molly is asking a question to which she obviously knows the answer to, to see if Ginny can answer it.
She is basically quizzing Ginny, as parents often do. It would be absurd to think Molly doesn't actually know or remember the correct platform. With brooms, portkeys, Floo networks and Apparation, the Hogwarts train is probably the only train magic-born ever use.
And in the six years that Harry attended Hogwarts, the platform didn't change.

A: There's a strong possibility that she's genuinely trying to work out which platform they're going to be using. In the Pottermore moment on Platform 9 3/4, JKR notes that there were other "fractional platforms" that wizarding trains use to transport witches and wizards to various magical destinations.
It's quite feasible that in other years, the Hogwarts Express set off from a different platforms and she's looking for confirmation which platform they'll be departing from this time;

"In choosing the number of the concealed platform that would take young
  witches and wizards to boarding school, I decided that it would have
  to be a number between those of the Muggle platforms – therefore, it
  was clearly a fraction. This raised the interesting question of how
  many other fractional platforms lay between the whole-numbered
  platforms at King's Cross, and I concluded that were probably quite a
  few.
Although these are never mentioned in the book, I like to think
  that it is possible to take a version of the Orient Express off to
  wizard-only villages in continental Europe (try platform seven and a
  half), and that other platforms may be opened on an as-required-basis,
  for instance for large, one-off events such as Celestina Warbeck
  concerts (see your ticket for details)."

A: What makes you think she didn't remember platform number? Parents (and other teaching figures) frequently ask questions whose answers they know, with the intended goal being for their children to provide the answer; it's a tool that helps the child remember facts.
It's like going to an amusement park and asking your kids "Okay kids, where did we park?" so your children remember where the car is if the family becomes separated.

A: I read about a conspiracy theory: She said it deliberately to attract Harry to his family (Dumbledore warned her about Harry) but conspiracy theories don't deserve attention, although this specific theory is interesting.
In my opinion, this is a REAL question, it's possible that in his epoch, the platform had a different number.

A: The most likely answer is also the simplest (and least interesting).  She probably forgot because she doesn't use it that often.
A number you use only once (or even twice) a year is easy to forget. I can never remember what local voting district (18 or 19?) I am in, for example.  Who remembers their driver's license number?
OK, that's usually a long number, but what about your congressional district number?  How about the street address of your school?  These are all things that we tend to forget, not because they are hard to memorize, but simply because we don't use them that much, and on the annual or semi-annual occasion that we do, we can just look it up (or ask someone else), so it's not really worth trying very hard to remember long term.

A: The way it's described in the books makes it sound like it was just a question for Ginny to answer:

"Now, what's the platform number?" said the boys' mother.
"Nine and three-quarters!" piped a small girl, also red-headed, who was holding her hand. "Mum, can't I go…"

The boys go straight through the barrier, so they must be standing right next to it. It follows that Mrs. Weasley has led them to the right platform, so she does know what it is.
There's no mention of her being flustered or frustrated (or at least, no more than you'd expect with Fred and George for sons) about being unable to find the platform.

ETA: I've seen several comments saying that perhaps this was a movie thing; it isn't. This is what Molly says in the film, which Harry overhears after talking to the station staffer:

…same every year of course, packed with Muggles! Come on: Platform Nine and Three-Quarters this way.

She doesn't seem particularly flustered or concerned, except to keep Ginny close by her side, and to make sure they all get through the barrier safely. There's never any question about what the platform number is.

A: The truth is J.K. Rowling made mistakes in the book and she admitted to that. No one would forget the number as commented above. Even if you use it one time, you also go to Diagon alley one time a year but they do not forget that. The fact she grew up in a wizard family and that was always the way, than would be common knowadge for the wizard world as much as the Minster or Hogwarts.
She purposely put that in there to go with the story or made a simple mistake like the misnumber of Horcrux's. (There was 7, Harry was 8 and the snake was 9 yet 7 were destroy)


text:
Q: Builder pattern where to apply Hi I have a doubt on builder design pattern.From the pluralsight videos I understood that this pattern is used to avoid the complexity of telescopic constructors in mutable classes.
Some other sites explain it as a way to develop or construct complex object by keeping builder as a composition.I am totally confused.Please clarify the same?

A: Complex constructors can be bad for immutable or mutable classes.
One problem with big constructors (or a hierarchy of constructors) is that you can end up with a large constructor used for multiple purposes. For example some parameters might be null if you are creating a brand new object but they must not be null when you call it from somewhere else.
It's painful to figure out how to use these constructors. Even if they have built in validation you still have to check that you are creating it the right way. The builder could have methods that provide hints or force people to create it the right way. For example builder.copy(obj).setName("newObj").build(). This gives a hint about how to copy an object, it might be better than looking through the constructors for the correct one to use.
Another problem is that you must supply all the required constructor args. Even if there are sane defaults, you might be forced to supply something. The builder could contain default values so you only set the parameters you are interested in.
Another problem is that a big constructor might have multiple parameters of the same type in a row. It's asking for someone to bung in the wrong value accidentally. A builder forces you to call a method with a meaningful name.
A builder also has the same advantage as a static factory. It could return an interface instead of the concrete type. This is good because you encourage clients classes to work against the interface.
The linked answer in the comments has more good reasons.


text:
Q: Outer join on a view with calculated columns performs calculation for missing ("outer") records I have a view in MySQL, which has some calculated fields — COALESCE and the like. If I do a left outer join on that view (so records from that view may be missing), then the calculated fields are still calculated for the missing records, instead of showing up as NULL.
Example
I've tested the following example on MySQL versions 5.5.40-36.1-log and 5.5.53-38.5 (because that's what I've got on hand) as well as on SQL Fiddle‡ versions 5.5 and 5.6.
Setup
-- A simple view
CREATE OR REPLACE VIEW foo
AS
      SELECT 1 AS x
UNION SELECT 2
UNION SELECT 3;

-- Another simple view
CREATE OR REPLACE VIEW bar
AS
      SELECT 1 AS y
UNION SELECT 2
UNION SELECT 3;

-- A (contrived) view with a calculated column
CREATE OR REPLACE VIEW baz
AS
SELECT
   f.x,
   b.y,
   SIGN(COALESCE(b.y, 0)) AS z
FROM foo f
LEFT JOIN bar b ON f.x = 2 * b.y;

Query
-- A query that does a left outer join
-- on the view with the calculated column
SELECT *
FROM foo f
LEFT JOIN baz b ON f.x = b.y;

Expected result
I would expect the following result, where we see one row with records from baz and two rows without.
| x | x | y | z |
-----------------
| 1 | 2 | 1 | 1 |
| 2 | - | - | - |
| 3 | - | - | - |

Actual result
But instead I get the following, with indeed one row with records from baz, but two rows where there are no records from baz except for the calculated column, which is calculated for all three rows!
| x | x | y | z |
-----------------
| 1 | 2 | 1 | 1 |
| 2 | - | - | 0 |
| 3 | - | - | 0 |

So z is calculated, even where baz returns no records (as evidenced by the NULLs for x and y).
My actual case involves a join between the view and a table the view is based on. I've replicated this in the example, using views only. I've also tested it without the "self-join"; this makes no difference.
Workaround
What does work for me, is hiding baz in a sub-select, like so.
SELECT *
FROM foo f
LEFT JOIN (
   SELECT *
   FROM baz
) b ON f.x = b.y;

This yields the expected result:
| x | x | y | z |
-----------------
| 1 | 2 | 1 | 1 |
| 2 | - | - | - |
| 3 | - | - | - |

Is this expected behaviour? Why?

‡: worked for me yesterday, can't get it to work today.

A: If the two queries:
SELECT *
FROM foo f
  LEFT JOIN baz b
  ON f.x = b.y;

and
SELECT *
FROM foo f
  LEFT JOIN (SELECT * FROM baz) b
  ON f.x = b.y;

return different results, then it's a bug and the table and view definitions are irrelevant. That should never happen.
Before you go and post a bug report, check your view and queries in the version (5.5.54). Your 5.5.40 is 14 minor versions and about 2.5 years older than the latest 5.5 version.
If the bug still persists, then file a bug report to MySQL with this example. A similar bug has already been reported: Return inconsistent result when using inline SELECT vs VIEW for left join, so if you report I suggest you add your examples there.
MySQL developers have comfirmed that one and suggested a few workarounds (until it is fixed). You can try the suggestion to create the views with ALGORITHM = TEMPTABLE:

There are a few workarounds:
In all version, the query using the view will give correct result if view is created with "CREATE ALGORITHM=TEMPTABLE VIEW ..."
For 5.7/8.0, both queries will give the correct result by setting optimizer_switch='derived_merge=off'
In 8.0 the NO_MERGE hint can be used to get correct behavior in both cases:
  SELECT /*+ NO_MERGE(t2) */ ...

Having said that, the query is more complex than needed. You could have used something simpler (although I don't like having a result with columns identically named):
CREATE VIEW baz2
AS
SELECT
   f2.x AS x
   f1.x AS x,
   CASE WHEN f1.x IS NOT NULL THEN f2.x END AS y,
   SIGN(f1.x) AS z
FROM foo f2                   -- changed:   f2 LEFT JOIN f1
  LEFT JOIN bar f1
  ON f1.x = 2 * f2.x;

and
SELECT * FROM baz2 ;

A: On MySQL 5.7.11 we are getting the expected results.
Seems like a bug in prior versions.
+---+--------+--------+------------+
| x | x      | y      | z          |
+---+--------+--------+------------+
| 1 | 2      | 1      | 1          |
+---+--------+--------+------------+
| 2 | (null) | (null) | (null)     |
+---+--------+--------+------------+
| 3 | (null) | (null) | (null)     |
+---+--------+--------+------------+


text:
Q: How to merge multiple html files (with PHP & JS code in them) into 1 big html file I am trying to create a script that will get multiple HTML files that could have PHP code in them and JavaScript code and make a big HTML/PHP file with that.
E.g home.php, news.php, something.php
Will be combined to form Index.php.
Before anyone ask why I need a file like that: the reason is to create 1 file that uses responsible layout for touch-swipe using parallax.
I've tried file_get_contents() but if the html has a simple <?php echo "hello world";?> it wont output it.
How could I merge multiple HTML files with anything in them (JS, php, etc)?

A: Have you tried a include()?  That should work fine.
From the PHP docs... http://php.net/manual/en/function.include.php

The include statement includes and evaluates the specified file.

A: If you want the unexecuted PHP code, you will require an FTP connection to the PHP files. Using cURL, you'll open an FTP connection and download the file, which will be in its original form with <?php echo "hello world"; ?> and such. This is just like using a normal FTP client in your operating system to retrieve the file, in this case it will be in a variable in your PHP script, then you can execute the contents or do whatever from there.
Of course this method is also dependent on whether the host (server) allows it.


text:
Q: links redirect to dashboard xampp I've moved WordPress from hosts to Xampp local hosts.
I corrected the links inside the database. Although the home page is loaded.
But on every link, I'm redirected to the http: // localhost / dashboard page.
I use WordPress 4.9.6, Xampp 3.2.2 and Windows 8.1 64-bit
my .htaccess file
BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
END WordPress

please guide me, thanks

A: For me, changing the .htaccess file as @Ustav suggested did not resolve the issue. After making that change, while I was no longer redirected to the XAMPP dashboard, I was instead redirected to a 404 page from Apache.
What did resolve the issue for me was simply navigating to Settings > Permalinks in the WP admin, scrolling to the bottom, and clicking "Save Changes", an idea I got from this WP forum page. That immediately fixed it, no changes to .htaccess required.
The remote-to-local transfer instructions I followed can be found on this 1&1 Ionos instruction doc

A: Try this:
Go to htaccess file.
Inside
<IfModule mod_rewrite.c>
...
</IfModule>

Put this code
RewriteRule . FOLDERNAME/index.php [L]


text:
Q: Tomcat H2 deployment I have 2 situations.
hibernate.cfg:
<property name="connection.url">jdbc:log4jdbc:h2:./H2/test</property>
<property name="connection.driver_class">net.sf.log4jdbc.sql.jdbcapi.DriverSpy</property>
<property name="connection.username">user</property>
<property name="connection.password">password</property>
<property name="dialect">org.hibernate.dialect.H2Dialect</property>

*

*H2 db is in my project near my src folder. If I try to test connection from simple class it works. It connects to the db that is in the right place in project folder.

*Now I'm making new configuration to launch tomcat + servlets. All is fine, but tomcat creates new H2 database in his folder: (apache-tomcat-8.0.17\bin\H2\test.mv.db). Is it possible to make tomcat to take (to use) my test.mv.db from my project's folder ?
If I put my test.mv.db manualy from project into tomcat's dir - it is working (I'm not using "sa" with blank password). I don't want to place h2 db into user's folder like jdbc:h2:~/test).
Thank you.

A: *

*You should append the hibernate prefix to all your properties.

*Try giving H2 an absolute path to your database folder:
<property name="hibernate.connection.url">jdbc:h2:file:/your-project-path/test-db</property>

*I don't think the Driver class setting is correct either. It should be:
<property name="hibernate.connection.driver_class" value="org.h2.Driver" />


text:
Q: How to Increase the MaxArrayLength in a WCF web.config - for uploading large files I have dig all around the net for two days about it, and I can't make my asp.net web site to upload files bigger then 16Kb
I'm using fileUploader,wcf, and I have service reference in the client.
when I upload file in 30KB size it asked me to increase the MaxArrayLength.

The maximum array length quota (16384) has been exceeded while reading XML data. This quota may be increased by changing the
  2
   MaxArrayLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader. Line 1, position 205847.

and it's just what I did, but it keeps complaining about this.
if I upload file in 1MB size, I get error 400.

The remote server returned an error: (400) Bad Request

please help
the client app.config:
<bindings>
  <basicHttpBinding>

    <binding name="streamingBinding"
              transferMode="Streamed"/>

    <binding name="BasicHttpBinding_IBLServer" closeTimeout="00:01:00"
      openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
      allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
      maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
      messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
      useDefaultWebProxy="true">
      <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647"
        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <security mode="TransportCredentialOnly">
        <transport clientCredentialType="None" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
<client>

  <endpoint address="http://localhost:8888/BLService.svc" binding="basicHttpBinding"
    bindingConfiguration="BasicHttpBinding_IBLServer" contract="WSRef.IBLServer"
    name="BasicHttpBinding_IBLServer" />
</client>

the WCF web.config:
 <system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior>
      <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
      <serviceMetadata httpGetEnabled="true"/>
      <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
    <behavior name="BLServer.BackEndBehavior">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
      <dataContractSerializer maxItemsInObjectGraph="2147483647" />
      <serviceTimeouts transactionTimeout="05:05:00" />
      <serviceThrottling maxConcurrentCalls="500" maxConcurrentSessions="500"
       maxConcurrentInstances="2147483647" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

<bindings>
  <basicHttpBinding>
    <binding name="streamingBinding"
              transferMode="Streamed"/>

    <binding name="BasicHttpBinding_IBLServer"
       maxBufferPoolSize="2147483647" maxBufferSize="2147483647"
             maxReceivedMessageSize="2147483647">
      <security mode="TransportCredentialOnly">
        <transport clientCredentialType="Windows" />
      </security>
          <readerQuotas
              maxDepth="64"
            maxStringContentLength="2147483647"
             maxArrayLength="2147483647"
             maxBytesPerRead="4096"
             maxNameTableCharCount="16384"/>
    </binding>

  </basicHttpBinding>
</bindings>

<services>
  <service behaviorConfiguration="BLServer.BackEndBehavior" name="WSRef.BackEnd">
       <endpoint address="" binding="basicHttpBinding"
              bindingConfiguration="BasicHttpBinding_IBLServer"
              contract="WSRef.IBLServer" />

  </service>

  <service name="StreamingService.Upload">
    <endpoint address=""
              binding="basicHttpBinding"
              bindingConfiguration="streamingBinding"
              contract="StreamingService.IUpload"/>
  </service>
</services>

files <16 KB are uploaded successfully.
can you please find out what I did wrong?

A: EDIT: Ok, I see you are doing it already... Are you sure yopu are mapping the bindings correctly. Check the first post below, they had a problem with the mapping of the binding.
Check these out:
Maximum array length quota
WCF service The maximum array length quota (16384) has been exceeded
Changing the MaxArrayLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader
How to handle large file uploads via WCF?
Hope this helps.

A: I struggled with the same problem for hours.  Finally, I realized that I was using a config file transform, and my maxArrayLength kept getting overwritten by the transform.  Time for some caffeine.


text: Q: Are there scenarios where the used heap memory reduces without GC i.e. when there is no GC event? I see in my Android app, a decrease in used memory even when GC has not occured. I don't see GC in my logs for that time period. How else is the memory released, if not by GC? Is it by objects that specifically deallocate memory when exiting?


text:
Q: How should I close urllib.urlopen connection in python I have a python code that reads from a URL.
 def submitTest(self,url):
    response = None
    if url is not None:
        wptUrl = WebPageTestConfigUtils.getConfigValue('runTestURL')+"?f=json&url="+url+"&runs=3&video=1&web10=0&fvonly=1&mv=1&private=1&location=us_east_wptdriver:Chrome.DSL"
        with closing(urllib.urlopen(wptUrl)) as response:
            json.load(response)
            return response["data"]["testId"]

I used the context lib docs https://docs.python.org/2/library/contextlib.html to close the python connection. But then I get the following error on executing.
Traceback (most recent call last):
File "webPageTestUtils.py", line 59, in <module>
main()
File "webPageTestUtils.py", line 56, in main
print webPageTestProcessor.submitTest("www.amazon.com")
File "webPageTestUtils.py", line 27, in submitTest
return response["data"]["testId"]
AttributeError: addinfourl instance has no attribute '__getitem__'

What I am doing wrong here . I need a way to close the connection if something bad happens or if I am done with it.

A: What I am doing wrong here?
An error occurred that was not caught.
The error occured because: quote from @Nonnib:

json.load returns the object you need. You are probably looking for:
  response_dict = json.load(response) and then return
  response_dict["data"]["testId"]

Possible solution:
Catch possible errors and return the appropriate result
def submitTest(self,url):
    response = None
    if url is not None:
        wptUrl = WebPageTestConfigUtils.getConfigValue('runTestURL')+"?f=json&url="+url+"&runs=3&video=1&web10=0&fvonly=1&mv=1&private=1&location=us_east_wptdriver:Chrome.DSL"
        with closing(urllib.urlopen(wptUrl)) as response:
            json.load(response)
            try:
                return response["data"]["testId"]
            except AttributeError:
                return "an AttributeError occured" # or return something else, up to you
            except:
                return "an error occured"

This way the with block will always execute normally and close the connection when it's done


text:
Q: Lead acid battery charger I designed the below circuit.
The relay open above 13V and close below 13V.
How can I make relay open above 14V and close below 12V?
Tell me if the circuit have major problem.
Thank you.

A:
tell me if the circuit have major problem.

Simulation for some positions of pot, dependence to BJT beta and Temperature.
There is some "dispersion". Can "work", but not precisely.
Use comparators (as @Syed suggestion) or certainly differential BJT for comparison ... with, obviously, also a "zener" for "reference" (as Autistic suggestion).

This could be better. Pot2 used for "centering" on usable voltages. R9 scales.

For the last point, one can add hysteresis with another resistor.


text:
Q: Server does not receive data from ajax call I have a problem. I'm trying to send content of a textarea with an ajax call, but it doesn't seem to be working, and I don't know why.
There's the method called GetStatus(string statusText) which need to receive the content.
Here's the javascript code:
$("#btnSaveStatus").on("click", function () {
                    var statusText = $(".textareaEdit").val();

                    $.ajax({
                        type: "GET",
                        url: "Default.aspx/GetStatus",
                        data: "{statusText:'" + statusText + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (result) {
//                            $('#littlbioID').text(result.d);
                        }
                    });
                });

Please advise. You should also know that I'm new into web development.

A: *

*You can't have a request body in a GET request, you have to use a POST request for that

*The string you are constrcting is not valid JSON since:

*

*Property names must be strings

*You have no idea what the user will enter in the textarea - it might contain characters with special meaning in JSON

Generate your JSON programatically.
{
  type: "POST",
  url: "Default.aspx/GetStatus",
  data: JSON.stringify({
    statusText: statusText
  }),
  // etc

Obviously, the server side of the process needs to be set up to accept a POST request with a JSON body (instead of the more standard URL Form Encoded format) as well.

A: Try this:
$("#btnSaveStatus").on("click", function () {
                    var statusText = $(".textareaEdit").val();
                    var jsonText = new Object();
                    jsonText.statusText = statusText;

                    $.ajax({
                        type: "POST",
                        url: "Default.aspx/GetStatus",
                        data: JSON.stringify(jsonText);,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (result) {
//                            $('#littlbioID').text(result.d);
                        }
                    });
                });


text: Q: How to make firebase backwards compatible with previous play services versions I have integrated Firebase into the app that I'm making. Problem is, a lot of phones I've tried this on have older play services versions and so the app simply does not work without them updating. Is there a way that I can make my app backwards compatible without having to update? Maybe by decreasing the version? My app uses Firebase auth 11.8.0 to authenticate, Firebase storage and Firebase Realtime database. Also, whats the minimum play services version that I can use without losing functionality?


text:
Q: How can I fetch file from Urban code Deploy workspace I have few files in Urbancode Deploy workspace(downloaded from Artifactory). How can I fetch those files into my Java program where I am using those downloaded files in Java program.
I tried like this:
1) I am calling Java class from urbancode deploy shell, where I am passing the file name,username,password and url as arguments to Java class.
2)In my Java class I created http connection to fetch that file with help of arguments.But its failing.
3)If I could fetch file in above is good for me,or else do I need to make rest call to fetch that file(as i am using rest call to urbancode deploy(UCD) to fetch other properties needed) if so how can I?
4)Another approach, Can I send all the files from urbancode deploy to java program through command line arguments? Is that possible to send entire file from UCD to Java class?

A: I have resolved this problem, as accessing a file into my Java code is simply accessing a file from desktop. As my file is on server agent and my java code is also on same server agenet inside JRE. So I just read the file using "currentdirectory/filename". Then I am able to access.


text:
Q: Closing the xml tag in one line The loop goes through the list
                for file in files:
                    if id == file['param_id']:
                        resources_dict = {'fileNo': str(i), 'startPageNo': str(i), 'endPageNo': str(i),
                                          'format': 'cpk:JPEG'}

                        ET.SubElement(cpf_resources, 'cpf:ContentFile', resources_dict).text = 'cid:{}'.format(str(file['filename']))
                        i = i + 1

then the data is written to the file as follows:
 tree = ET.ElementTree(jobticket)
        filename = '{}\\{}.xml'.format(os.getcwd(), get_af_value(project_data, id, 'filename'))
        tree.write(filename, encoding="UTF-8", xml_declaration=True)

In the end file, the data are displayed as follows:
 <cpf:Resources>
        <cpf:ContentFile endPageNo="1" fileNo="1" format="cpk:JPEG" startPageNo="1">cid:page_0005.jpg
        </cpf:ContentFile>
        <cpf:ContentFile endPageNo="2" fileNo="2" format="cpk:JPEG" startPageNo="2">cid:page_0009.jpg
        </cpf:ContentFile>
    </cpf:Resources>

Is there a way to display the closing of the tag  </cpf:ContentFile>in the same line?
<cpf:ContentFile endPageNo="2" fileNo="2" format="cpk:JPEG" startPageNo="2">cid:page_0009.jpg</cpf:ContentFile>

A: After a few curses I managed to create something like this:
        tree = tree.getroot()
        tree = ET.tostring(tree)
        xmlstr = minidom.parseString(tree).toprettyxml(indent = "   ", encoding='UTF-8')
        with open("filename.xml", "w") as f:
           f.write(xmlstr)

Maybe somebody could use it.


text:
Q: Nested TransactionScope and/or nested connections causing MSDTC escalation I am trying to avoid MSDTC escalation in my application. I am using LINQ with SQL Server Express 2008 R2, and later will be using the full version.
I have written a database wrapper class which creates connections as necessary and disposes of them as quickly as possible. The connection string remains the same across all connections.
Here is a very slimmed-down version of my class:
public class SqlServerDatabaseWrapper {

  public SqlServerDatabaseWrapper(string connectionString) {
    ConnectionString = connectionString;
  }

  public string ConnectionString { get; private set; }

  private static IDbConnection GetOpenConnection() {
    var conn = new SqlConnection(ConnectionString);
    conn.Open();
    return conn;
  }

  // there is also a second method to return a value
  // there is PerformCommandAction for SqlCommand as well
  public void PerformDataContextAction<TContext>(Func<IDbConnection, TContext> creator, Action<TContext> action) where TContext : DataContext {
    PerformConnectionAction(conn => {
      using (var context = creator(conn))
        action(context);
    });
  }

  // there is also a second method to return a value
  public void PerformConnectionAction(Action<IDbConnection> action) {
    using (IDbConnection conn = GetOpenConnection(ConnectionString)) {
      action(conn);
    }
  }
}

Used as follows:
var db = new SqlServerDatabaseWrapper(connectionString);
db.PerformDataContextAction(
  conn => new SomeDataContext(conn),
  context => { /* do something */ }
);

If I put a lock around the content of the PerformConnectionAction method, so only one can run at a time, then everything works but there is a noticeable performance penalty. However, when I remove it, it escalates.
The code that is using the wrapper is using a TransactionScope, and there could be nesting of TransactionScopes and/or calls to either PerformDataContextAction or PerformConnectionAction (which each create a new connection with the same connection string); in pseudo-code (as this might occur across different classes/methods):
var db = new SqlServerDatabaseWrapper(connectionString)
using (TransactionScope tran = new TransactionScope()) {
  db.PerformDataContextAction(
    /* ... */,
    context => {
      using (TransactionScope tran2 = new TransactionScope()) {
        db.PerformConnectionAction(conn => { /* some stuff */ });
        tran2.Complete();
      }
    }
  tran.Complete();
}

Note also that there is use of the static Membership methods which could occur at various points.
I should also add that the connection string is as follows:
Data Source=.\SQLEXPRESS;Initial Catalog=db1;User Id=test1;Password=test1;MultipleActiveResultSets=true;Enlist=false;

The question is, how do I refactor/rewrite my code so that my application can perform well, without MSDTC, and without introducing locks?
Thanks

A: Are you using only one connection to the database inside the transaction scope?
Creating two connections with the same or a different connection string inside a transaction scope will escalate the transaction to a distributed one.
You could store the connection in a thread static variable and close/dispose it when all the work in the transaction is done. Then every thread will have it's own connection.
When you add a lock to your logic you will probably not get an distributed transaction because the connection pool will return you the same connection every time.


text:
Q: How to dynamically add a row in a table when user input (postman-style-reactive-table) How to dynamically add a row when atleast one character in input (like Postman behaves) in header tab.
1) When user enters any single character in td of first row then one row
   should add below. When user deletes  text from first row and when first row's
   td are empty then delete below row.
2) keep track of text enetered in a model for every row input (ie key and
   value);
3) when user enters any single character in a row in any td then checkbox
  should be checked otherwise not.
.ts
    model =  new Model ('','','',..............);
    tableRow = {
    "key":[{
    'name':'key1',
    'keyInput':""
    }],
    "value":[{
    'name':'value1',
    'keyInput':""
    }]
    }

addRow(event){
    if(event.target.length < 2){
     let data = {
           'name':'key' + (this.tableRow.key.length + 1),
           'keyInput':""
           }
         this.tableRow.key.push(data )
       }else{
        this.tableRow.key.pop();
         }
       }

.html

Key
Value

<input type="checkbox">
<input (keyup)="addRow($event)" [(ngModel)]="model.key" type="text">
<input [(ngModel)]="model.value" type="text">

A: Here's a very rudimentary implementation of what you might want.
component:
export class AppComponent {
  title = 'stack-solve';
  //defining row of objects and initializing first row with empty values
  //All values entered on the screen are bound to this array
  rows: any[] = [{
    checked:false,
    key:'',
    value:''
  }];

//This function is called on keyup and checks the checkbox on that row and adds new row if the action was on the last row
checkAndAddRow(i){
    this.rows[i].checked = true;
    if(this.rows.length - 1 == i){//insert new empty row, incase this keyup event was on the last row, you might want to enhance this logic...
      this.rows.push({
        checked:false,
        key:'',
        value:''
      })
    }

  }
}

template:

        Key
        Value

          <input [checked]="row.checked" type="checkbox">
          <input [(ngModel)]="row.key" type="text" name="key" (keyup)="checkAndAddRow(i)">
          <input [(ngModel)]="row.value" type="text" name="value" (keyup)="checkAndAddRow(i)">

app.module:
imports: [
    BrowserModule,
    FormsModule // need to import FormsModule if you don't have already
  ],

A: Your solution is close. The main things that I would modify is to keep track of the key/value/checked state for each row on the row itself, not on some external model. That way each row is self-maintaining and does not have outside side effects that modify other rows (other than the add/remove row, of course).
The other thing I changed is to capture the (input) event, rather than the (keyup) event. This is to allow for better mobile cut/paste and right click cut/paste support. (keyup) will not capture either of those events.
Working Example Here
import {Component} from '@angular/core';

@Component({
  selector: "reactive-table",
  template: `

          Selected
          Key
          value

          <input type="checkbox" [(ngModel)]="row.selected"/>
          <input [value]="row.key" (input)="handleKeyChange($event, row, $index)" />
          <input [(ngModel)]="row.value" />

  `,
  styles: [`

  `]
})
export class ReactiveTableComponent {
  public data;
  constructor() {

  }
  ngOnInit() {
    this.data = {
      rows: [
        {
          selected: false,
          key: "",
          value: "",
          oldKey: ""
        }
      ]
    }
  }
  handleKeyChange(event, row, rowIndex) {
    var newKey = event.target.value;
    if (newKey !== row.oldKey) {
      row.selected = true;
    }
    if (newKey === "" && rowIndex === this.data.rows.length -2) {
      this.data.rows.pop();
      row.selected = false;
    }
    else if (newKey !== "" && row.oldKey === "" && rowIndex === this.data.rows.length -1) {
      this.data.rows.push({
        selected: false,
        key: "",
        value: "",
        oldKey: ""
      });
    }
    row.oldKey = row.key = newKey;
  }
}


text:
Q: Junit failed tests, how to fix this? So I'm tesing using Junit, quite new to it.
I am trying to test methods in a class called SetOfUsers as follows:
 @Test
    public void testFindUserByName() {
        System.out.println("findUserByName");
        String name = "";
        SetOfUsers instance = new SetOfUsers();
        User expResult = null;
        User result = instance.findUserByName(name);
        assertEquals(expResult, result);
        // TODO review the generated test code and remove the default call to fail.

    }

So I wanted to check the name of a user entered in Bob for instance in the name string like this
String name = "Bob";

since I have a user called Bob in  the setOfUsers class.
The output window displays this message
Failed: expected:<null> but was:<Staff name:Bob, Staff pass:abc123>

What can I do to make this a pass?

A: Read about BDD, this is very nice technique for making tests easy to write and understand (read)

Test-driven development is a software development methodology which essentially states that for each unit of software, a software developer must:

*

*define a test set for the unit first;

*then implement the unit;

*finally verify that the implementation of the unit makes the tests succeed.

Well written test should have GivenWhenThen sections

(Given) some context
(When) some action is carried out
(Then) a particular set of observable consequences should obtain

This style is known as SpecificationByExample

Given-When-Then is a style of representing tests - or as its advocates would say - specifying a system's behavior using SpecificationByExample.

Example test
@Test
public void testFindUserByName() {

    // given
    SetOfUsers instance = new SetOfUsers();

    // when
    User result = instance.findUserByName("Bob");

    // then
    assertEquals("Bob", result.getName());

}

Nice to read:

*

*Arrange Act Assert Alternatives

*Maintainable Tests

A: This test is always going to fail because the last line is
fail("The test case is a prototype.");

The reason your test is failing now is because of the line above,
assertEquals(expResult, result);

You are setting your expected result to null and the result you are getting from the name, "", is probably an empty String as well from that error message. You need to have expResult to be the same as what you expect instance.findUserByName("Bob") to return. However, unless you initialize the instance to be set with a User Object the objects will not match, so it might be better to either mock it to return a pre-created User object so they match, or create a User object with the same properties as the one you expect to be returned check the fields of the User Object returned and the User object you created to be sure they match.
If you want to check for what the user for Bob is, change the code to this:
@Test
public void testFindUserByName() {
    System.out.println("findUserByName");
    String name = "Bob";
    SetOfUsers instance = new SetOfUsers();
    User expResult = <Create an object you expect instance.findUserByName("Bob") to return>;
    User result = instance.findUserByName(name);
    //Check fields here.
    assertEquals(expResult.getUserName(), result,getUserName());
    // TODO review the generated test code and remove the default call to fail.

}

A: You can't test for null using assertEquals().
To test for null, use:
assertNull(result);

A: I don't understand the question, but if you want to search for "Bob" why you initialize name=""? The test should be:
@Test
public void testFindUserByName() {
    //Create SetOfUsers
    //Add new User with name Bob
    //FindByUsername("Bob")
    //AssertEqual(User.getName(), "Bob")
}


text:
Q: ¿Dónde me equivoco? Escribe código que lea el fichero file1.txt  y que para cada línea del fichero, meta las palabras en una lista e imprima dicha lista.Se imprimirán tantas listas como líneas en el fichero.
 with open("file11.txt", "w") as eje42:
   j = input("introduzca una lista de palabra: ")
   i = []
   i = j.replace(" ","").split(",")
   for linea in i:
     eje42.write(linea)
 with open("file11.txt", "r") as eje42:
   print(eje42.read())

Pero al parecer lo estoy haciendo mal, ya que tiene estos requisitos

*

*Cuando se habla de palabras, se refiere a las unidades de texto
separadas por espacios
Tener en cuenta que la función readlines() lee caracteres utf-8

A:     with open("file11.txt", "w") as eje42:
        # Leo las palabras
        palabras = input("introduzca una lista de palabras separadas por ',': ")
        # Las separo por el caracter solicitado y creo un arreglo
        lista_de_palabras = palabras.split(",")

        # Recorro el arreglo y escribo cada palabra agregandole el caracter de salto de línea
        for palabra in lista_de_palabras:
            eje42.write(palabra + "\n")
    with open("file11.txt", "r") as eje42:
        #Leo el archivo nuevamente
        print(eje42.read())

    eje42.close()

"""
Al hacer esto
i = j.replace(" ","").split(",")
Primero estás cambiando los espacios por nada, entonces queda todo junto, y al hacer el split por el caracter "," no hay nada para separar.
"""


text:
Q: How to have the algorithmicx comment symbol in algorithm2e? I want to know how can I have the nice ▷
$\triangleright$ comment symbol of algorithmicx in algorithm2e?

A: From the algorithm2e documentation (section 11.4 to define comments, p 35):

\SetKwComment{Comment}{<start>}{<end>} defines a macro \Comment{text comment} which writes text comment between <start> and <end>. Note that <start> or <end> can be empty.
It defines also \Comment*{side comment text} macro which allows to put comment on the same line as the code. This macro can take various option to control its behaviour:

*

*\Comment*[r]{side comment text} put the end of line mark (; by default) and side comment text just after and right justified, then end the line. It is the default.

*\Comment*[l]{side comment text} same thing but side comment text is left justified.

*\Comment*[h]{side comment text} put side comment right after the text. No end of line mark is put, and line is not terminated (is up to you to put \; to end the line).

*\Comment*[f]{side comment text} same as the previous one but with side comment text right justified.

Here's an example of the above:

\documentclass{article}
\usepackage{algorithm2e}
\SetKwComment{Comment}{$\triangleright$\ }{}
\begin{document}

\begin{algorithm}[H]
  \SetAlgoLined
  \KwData{this text}
  \KwResult{how to write algorithm with \LaTeX2e }
  initialization\;
  \While{not at end of this document}{
    read current\;
    \eIf{understand}{
      go to next section \Comment*[r]{Some comment}
      current section becomes this one\;
    }{
      go back to the beginning of current section\;
    }
  }
  \caption{How to write algorithms}
\end{algorithm}

\end{document}

If you wish to reformat the comment font, you can adjust \CommentSty. In algorithm2e this is done via (for example) \SetCommentSty{itshape} to obtain an \itshape or italics comment.

Here is a corresponding example showing the default comment style in algorithmicx, taken directly from the algorithmicx documentation:

\documentclass{article}
\usepackage{algorithm,algpseudocode}
\begin{document}

\begin{algorithm}
  \caption{Euclid's algorithm}\label{euclid}
  \begin{algorithmic}[1]
    \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
      \State $r\gets a\bmod b$
      \While{$r\not=0$}\Comment{We have the answer if r is 0}
        \State $a\gets b$
        \State $b\gets r$
        \State $r\gets a\bmod b$
      \EndWhile\label{euclidendwhile}
      \State \textbf{return} $b$\Comment{The gcd is b}
    \EndProcedure
  \end{algorithmic}
\end{algorithm}

\end{document}


text:
Q: Is there a way to revert Fallout 3 back to a previous version? Building on my previous question about VaultMP.
I am now trying to get VaultMP to work with Fallout 3, but the launcher states that my game version is not supported.
My game version is 1.7.0.3, the latest version of the game. It should also be known that this is a non-Steam version of the game. The game automatically updates to 1.7.0.3 when installed on a new PC from the CD.
Is there a way of rolling back the game a version or two? Like to version 1.6 or 1.5?
Any help would be greatly appreciated!
Thanks for viewing!

A: Alright, after a lot of head scratching, researching dead forums and reading a lot of documentation, I finally reached the conclusion that the game version was not the issue when it came to VaultMP.
It turns out that the Script Extender that came with VaultMP was for Fallout : New Vegas, and not Fallout 3. I needed to replaced New Vegas Script Extender with Fallout Script Extender. After I did that, the mod worked (sort of) and the error stated in the question disappeared.


text:
Q: How do I get back my bookmark folder? I accidentally deleted a folder I need in my bookmarks in Safari. I back up my phone using iCloud. How do I get this folder back on my phone now?

A: On your iOS 9 or iOS 8 device: Go to Settings > iCloud > Storage > Manage Storage, then tap your iPhone listed under Backups to see the date and size of its latest backup. Go to Settings > General > Reset, then tap "Erase all content and settings." In the Setup Assistant, proceed to "Set up your device," tap Restore from a Backup, then sign in to iCloud. Proceed to "Choose backup," then choose from a list of available backups in iCloud.
WARNING: Don't continue to the second, Reset, step if your iPhone does not show any available backup sets from which to restore. If you reset your phone and erase all settings without having a backup with which to work, you'll end up losing all your data rather than just bookmarks. If there is a backup set available, you should be okay to proceed with the restore.
More information here:
https://support.apple.com/kb/ph12521?locale=en_US


text:
Q: fill in a HTML table with all days of month and date table from postgresql (javascript) I don't understand how to use generate_series to populate an HTML table where the 'key' of <tr> is the days of the month depending on the month and year that is selected with an <input type='month'>.
For now (thanks to the answers I got right here), I generated the query that only brings me the days of the month and year when I select it in the select month.
Something like this:
SELECT
    *
FROM (
    SELECT
        folio,
        fecha,
        extract(month FROM fecha) = $3 AS mes,
        EXTRACT(YEAR FROM fecha) = $4 AS anio,
        temperatura
    FROM
        medicion) m
WHERE
    mes = TRUE
    AND anio = TRUE
ORDER BY
    fecha ASC

And got this in the HTML table:

fecha
temperatura

2022-03-04
60

2022-03-07
50

2022-03-09
70

But I need something like this:

fecha
temperatura

2022-03-01
0

2022-03-02
0

2022-03-03
0

2022-03-04
60

2022-03-05
0

2022-03-06
0

2022-03-07
50

2022-03-08
0

2022-03-09
70

2022-03-10
0

with all days and different for each month.

A: Something like this:
SELECT
    t.dt,
    coalesce(temperatura, 0)
FROM
    generate_series('03/01/2022'::timestamp, (('03/01/2022'::timestamp + interval '1 month') - interval '1 day'), '1 day') AS t (dt)
LEFT JOIN
    medicion ON t.dt = medicion.fecha;

This assumes medicion.fecha is a date field. Also you would need to build the start date for the generate_series() from the input values to enter into the function, for instance $3/01/$4


text:
Q: How to set text background color in wxTreeListCtrl Anyone know a way to set the text background colour in a wxWidgets wxTreeListCtrl?

A: Short answer: No. http://trac.wxwidgets.org/ticket/17040#ticket
Long answer: If you really want to be able to do this, you'll need to derive your own class from wxTreeListModel and override wxDataViewModel::GetAttr() to set the item colors. wxTreeListModel is not public, so you'd have to change that in wxWidgets. Alternatively, you could copy the whole wxTreeListModel source to your project, rename it and modify it there. Both are messy, see short answer #1.


text:
Q: ruby round off to two decimal place and keep zero i want to round off a number upto two decimal place in ruby such that
(0.02 * 270187).round(2) is 5403.74  which is correct
but
(0.02 * 278290).round(2) is 5565.8 which is not consistent with previous one
i want to make it look like 5565.80
Please tell me how can i do it in ruby

A: This will do the trick:
> sprintf("%.2f",(0.02 * 270187))
#=> "5403.74"
> sprintf("%.2f",(0.02 * 278290))
#=> "5565.80"
> sprintf("%.2f",(0.02 * 270187)).to_f > 100  # If you plan to Compare something with result
#=> true

OR
> '%.2f' % (0.02 * 270187)
#=> "5403.74"
> '%.2f' % (0.02 * 278290)
#=> "5565.80"

Demo
Note:   The result is always a string, but since you're rounding I assume you're doing it for presentation purposes anyway. sprintf can format any number almost any way you like. If you are planning to compare anything with this result then convert this string to float by adding .to_f at the end. Like this

A: You could do something like
include ActionView::Helpers::NumberHelper

number_with_precision(value, :precision => 2) # value.to_f if you have string

or like this
'%.2f' % your_value

Hope it helps!
Further you can read from here


text:
Q: Creating an array of graphs (time evolving) in Java I'm new to Java and working with graphs. I have a time evolving graph (e.g 5 snapshots of the same graph in different instance of time) and I need to compute some basic network metrics like density, size, centrality, etc on each one of them. I was wondering as to what basic data structures I could use to store and perform computation on each graph. I tried using adjacency matrix, but the node size is too large and dynamic which leads to inefficiency. I came across few libraries notably JgraphT to hold undirected graphs
    UndirectedGraph<String, DefaultEdge> G =
          new SimpleGraph<String, DefaultEdge>(DefaultEdge.class);

But this is for one graph. Is there a way to create an array of these undirected graphs or any other way which I am missing to store time evolving graphs?

A: A few options:
(1) You can create an array (or a List, or a Set, etc.) of graphs just as you can of any other object.  If all the timesteps fit easily into memory (say 100 timesteps of 1000 nodes/edges each) then this should work fine.  Here's an example using JUNG:
List<Graph<V, E>> graphList = new ArrayList<>(); // Java 7 syntax
Graph<V, E> graph = new DirectedSparseGraph<V, E>();
// populate 'graph'
graphList.add(graph);

(2) If the nodes in each graph are all the same (i.e., it's just the edges that are changing), store the nodes once, and store a list of sets of edges, one set for each timestep.
(3) If the whole graph is relatively static, you can store the original graph, and then store deltas (added/removed nodes or edges) for each timestep.  This can be considerably more space-efficient, but requires that you reconstruct steps 1-n in order to see the state at time n+1.
(4) Finally, you can use a single graph, annotate each node/edge with the interval(s) at which it is present, and apply a filter any time you want to apply an algorithm to the graph.


text:
Q: how simulate key press and mouse click by sendinput without setting focus to the application Is there a way to use sendinput for not focused application?
I saw some related posts using HWND, but I do not the knowledge of HWND.
Can you explain some objects and functions related to HWND in order to simulating key press and mouse click without setting focus to the application?


text:
Q: Create a table from a query result with record fields in BiqQuery We have a set of tables with the data about users interactions online and we want to create a table with the scheme similar to GA BigQuery Export Schema (this feature is not yet available in Russia).
I couldn't find the information on how to create a record field in BQ querying existing tables.
On the contrary, it is written that "This type is only available when using JSON source files."
Is there any workaround or this feature expected in a nearer future? Can I submit a feature request?

A: Currently the only way to get nested and repeated records into BigQuery is loading JSON files. Once a query is run, all structure is flattened.
Feature request noted, hopefully BigQuery will support emitting nested records results!


text:
Q: Removing Folders from Linux Tree View? Question: Is there a way to remove the display of certain folders from the linux tree command?
In my case, I'd like to be able to run something like
$ tree . --remove-dir=pictures

which will remove all directories entitled "pictures" from the tree view.

A: man tree:
   -I pattern
          Do not list those files that match the wild-card pattern.


text:
Q: CRM365 data export issue We are using Dynamics CRM source to extract data from Dynamics CRM.
We have simple package importing data to SQL server

By using following query

But we need to get the name values

Is it possible to specify in the Dynamics CRM source whether value or name is returned?


text:
Q: in-place modification of strings within a list? I'm trying to change some elements of a list based on the properties of previous ones.  Because I need to assign an intermediate variable, I don't think this can be done as a list comprehension.  The following code, with comment, is what I'm trying to achieve:
for H in header:
    if "lower" in H.lower():
        pref="lower"
    elif "higher" in H.lower():
        pref="higher"
    if header.count(H) > 1:
        # change H inplace
        H = pref+H

The best solution I've come up with is:
for ii,H in enumerate(header):
    if "lower" in H.lower():
        pref="lower"
    elif "higher" in H.lower():
        pref="higher"
    if header.count(H) > 1:
        header[ii] = pref+H

It doesn't quite work, and feels un-pythonic to me because of the indexing.  Is there a better way to do this?
Concrete example:
header = ['LowerLevel','Term','J','UpperLevel','Term','J']

desired output:
header = ['LowerLevel','LowerTerm','LowerJ','UpperLevel','UpperTerm','UpperJ']

Note that neither of my solutions work: the former never modifies header at all, the latter only returns
header = ['LowerLevel','LowerTerm','LowerJ','UpperLevel','Term','J']
because count is wrong after the modifications.

A: header   = ['LowerLevel','Term','J','UpperLevel','Term','J']
prefixes = ['lower', 'upper']

def prefixed(header):
    prefix = ''

    for h in header:
        for p in prefixes:
            if h.lower().startswith(p):
                prefix, h = h[:len(p)], h[len(p):]
        yield prefix + h

print list(prefixed(header))

I don't really know that this is better than what you had. It's different...
$ ./lower.py
['LowerLevel', 'LowerTerm', 'LowerJ', 'UpperLevel', 'UpperTerm', 'UpperJ']

A: something like this, using generator function:
In [62]: def func(lis):
    pref=""
    for x in lis:
        if "lower" in x.lower():
            pref="Lower"
        elif "upper" in x.lower():
            pref="Upper"
        if header.count(x)>1:
            yield pref+x
        else:
            yield x
   ....:

In [63]: list(func(header))
Out[63]: ['LowerLevel', 'LowerTerm', 'LowerJ', 'UpperLevel', 'UpperTerm', 'UpperJ']

A: This should work for the data you presented.
from collections import defaultdict

def find_dups(seq):
    '''Finds duplicates in a sequence and returns a dict
            of value:occurences'''
    seen = defaultdict(int)
    for curr in seq:
        seen[curr] += 1
    d = dict([(i, seen[i]) for i in seen if seen[i] > 1])
    return d

if __name__ == '__main__':
    header = ['LowerLevel','Term','J','UpperLevel','Term','J']
    d = find_dups(header)
    for i, s in enumerate(header):
        if s in d:
            if d[s] % 2:
                pref = 'Upper'
            else:
                pref = 'Lower'
            header[i] = pref + s
            d[s] -= 1

But it give me the creeps to suggest anything, not knowing but a little about the entire set of data you will be working with.
good luck,
Mike


text:
Q: How to display graphics in javafx ListView I have two TreeViews of dir structures and their files and I want to show an indication of the status of the files(whether the file is unchanged, new, changed, deleted) somewhere in the same window. List views come to mind, and they seem to be capable of working with images somehow, but I don't know how to use them exactly, or whether they are indeed the best way to implement this.
So how do I achieve something like in the picture?(For illustration only, disregard the actual placement and color of the dots.)

A: when you add a new TreeItem, you can pass alot things to the constructors parameter of TreeItem. So if you pass FX containers like HBox it gets simply displayed like the following:
    HBox hbox = new HBox();
    Label label = new Label("file");
    ImageView imageView = new ImageView("path to image");
    hbox.getChildren().add(label);
    hbox.getChildren().add(imageView);
    TreeItem itm = new TreeItem(hbox);
    rootItem.getChildren().add(itm);

i hope this helps.


text:
Q: Equivalent circuit definition Given two (non linear) dc electrical circuits with the same number of nodes. If these two circuits have the same voltage in every node (reference node are selected at the same node)
Can it be concluded that the two circuits are equivalent and why or under what conditions?
Thankyou in advance

A: No, they would not be equivalent.
Suppose you have a circuit in steady state, and somewhere in there it has a diode. It will have a current Id and a voltage drop Vd. You could replace it with a resistor with R=Vd/Id, and nothing would change in terms of the current node voltages and currents.
Is it an equivalent circuit? Of course not, because once the conditions change (e.g. different excitation, or time passes and a comparator changes state, etc.), the diode will behave differently (non-linearly) compared to a simple resistor.
A snapshot in time of the node voltages in a circuit is not enough to characterize it, or even to determine that it is equivalent to another circuit that happens to have the same node voltages.


text:
Q: JDBC Connection Pool I have wriiten my connection pooling by extending connection and driver class. It is working fine but the problem is I want to now impose a upper limit and if te upper limit is reached then I want to store the request in the queue and return when any connections are free. How can I do this.
Thanks in advance for replys

A: This is a bad, bad design.
Your pool should not require you to extend anything.  It should not be concerned with requests, either.  Just check connections in and out.  Have another component manage a queue of requests and collaborate with your pool to get connections.
Connection pools have been done.  The easiest one to maintain is the one that's written by someone else.


text:
Q: How do I get a list of EC2 instances for a given role? I'm launching an EC2 instance with an IAM role. Assuming that I don't store the instance ID when I launch it, how can I use the Amazon API to find which instance I assigned the role to?
I tried using DescribeInstances, but that doesn't seem to have a property for the role.

A: Instead of looking for 'roles', look for 'iamInstanceProfile' elements when using the DescribeInstances API call. You can either get all instance profiles and then filter the results by this value, or you can specify it as a search filter using the 'iam-instance-profile.arn' element, with a wildcard for everything but the role name, like this: '*/RoleName'


text:
Q: Check for split keyboard As many of you know iOS 5 introduced a slick split keyboard for thumb-typing. Unfortunately, I have some UI that is dependent on the normal full-screen keyboard layout. One of my view controllers presents the user with a text entry sheet, and if they click into a textField that would be covered by the keyboard, it slides up along with the keyboard. This action is unnecessary with the split keyboard.
Is there a way to check which keyboard layout is in use before it pops up?
Thanks!

A: This is the solution which works with iPad split keyboards (originally from the blog linked in Zeeshan's comment)
[[NSNotificationCenter defaultCenter]
  addObserverForName:UIKeyboardDidChangeFrameNotification
  object:nil
  queue:[NSOperationQueue mainQueue]
  usingBlock:^(NSNotification * notification)
 {
     CGRect keyboardEndFrame =
     [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

     CGRect screenRect = [[UIScreen mainScreen] bounds];

     if (CGRectIntersectsRect(keyboardEndFrame, screenRect))
     {
         // Keyboard is visible
     }
     else
     {
         // Keyboard is hidden
     }
}];

A: UIKeyboardFrameChangedByUserInteraction key does not return 1 all the time when keyboard splits.
Below is the full user info dictionary key values on UIKeyboardDidShowNotification / UIKeyboardDidHideNotification.
2012-07-11 11:52:44.701 Project[3856:707] keyboardDidShow: {
    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {1024, 352}}";
    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {512, 944}";
    UIKeyboardCenterEndUserInfoKey = "NSPoint: {512, 592}";
    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{-352, 0}, {352, 1024}}";
    UIKeyboardFrameChangedByUserInteraction = 0;
    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 0}, {352, 1024}}";
}

2012-07-11 11:52:45.675 Project[3856:707] keyboardDidHide: {
    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {1024, 352}}";
    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {512, 592}";
    UIKeyboardCenterEndUserInfoKey = "NSPoint: {512, 944}";
    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 0}, {352, 1024}}";
    UIKeyboardFrameChangedByUserInteraction = 0;
    UIKeyboardFrameEndUserInfoKey = "NSRect: {{-352, 0}, {352, 1024}}";
}

Instead you can use UIKeyboardCenterBeginUserInfoKey or UIKeyboardCenterEndUserInfoKey keys to get notified when keyboard splits.
Hope this helps!

A: When the keyboard is docked, UIKeyboardWillShowNotification will be raised. If the keyboard is split or undocked, no keyboard notifications are raised.
If a keyboard is docked, UIKeyboardWillShowNotification will be raised, and the following will be true:
[[[notification userInfo] valueForKey:@"UIKeyboardFrameChangedByUserInteraction"] intValue] == 1

If a keyboard is undocked, UIKeyboardWillHideNotification will be raised, and the above statement will also be true.
Using this information has been adequate for me to code my user interface.
Note: this might be a violation of Apple's guidelines, I'm not sure.

A: The notifications that are posted when the keyboard appears or changes its position (UIKeyboardWillShowNotification, UIKeyboardWillChangeFrameNotification) contain a userInfo dictionary with the frame of the keyboard (UIKeyboardFrameEndUserInfoKey) that allows you to position your UI elements correctly, depending on the actual size and location of the keyboard.


text:
Q: Accidentally deleted all Visual Studio 2012 Win32 files. I need advice So, I have Visual Studio 2012, and I found that there was no windows form application. No problem, I found that I could download the files and follow the instructions, to get the windows form application option. But...something was wrong. There was no win32 project wizard anymore, no windows application, no console application, nothing. I knew I must have deleted them by accident in the VCnet folder, so I retrieved some of the files in the recycle bin. I did some guess and check and thankfully, I got my console application and windows application back. I know this sounds stupid, but I'm only 10 and everyone makes mistakes. So uhh...I need the files for DLL and class library. I can't find my own files in the recycle bin. Can anyone help?

A: Windows Installer has repair functionality. Go to Control Panel -> Programs & Features, select Visual Studio 2012 and click Repair.
On Windows XP, it's Control Panel -> Add/Remove Programs.

A: Can you try the deveng.exe /resetsettings.
Otherwise try a repair of the install using Add/Remove Programs:

*

*Start button

*Type AppWiz.cpl

*Enter

*Choose Visual Studio 2012 and click Repair.

Failing that best to re-install Visual Studio 2012, starting off on the right foot will provide some guarantee the problem will NOT reoccur.
In future best not to delete any of Visual Studio's files.

A: If it is .exe or system files, try using system restore , which will restore your files to earlier date.


text:
Q: DEM raster data to another raster with different resolution and extent I have two raster datasets:
One fine resolution DGM and another one, with different resolution, in which I want to have the mean elevation from the DEM (if possible the mean of the cells from the DGM which intersects it)
The raster have different resolution and different extend.

How can I get the data from my DEM to my other raster

A: You can use Zonal Statistics as Table or Zonal Statistics depending upon your intended output. These tools perform an internal resampling if the spatial resolution does not match.

If the resolutions are different, an internal resampling is applied to
  make them match before the zonal operation is performed.


text:
Q: How to get the first name from the list I have a values file like:
secrets:
  file.tst |
    {
      content ....
    }

And I would like to get file.tst name in the yaml template. I already tried with:
{{ .Values.secrets.secrets |trimSuffix "-" }}

But it doesn't work.

A: With that values.yaml layout, .Values.secrets is itself a dictionary, with string keys and string values.  Helm includes many functions that can operate on details of these.  In particular, you can call keys to get the keys of a dictionary as a list, and first to get the first item out of a list.
firstFilename: "{{ .Values.secrets | keys | first }}"

You can also use the built-in range function to iterate over either the map itself or the list of keys.
hashes:
{{- $filename, $contents := range .Values.secrets }}
  {{ $filename }}: "{{ sha256sum $contents }}"
{{- end }}


text:
Q: A problem when adding a photo using a URL in a div class I am a newbie with HTML and CSS and here is my problem.
I want to use a URL to display an image, and when I used this code (from a tutorial), it's absolutely perfect.

But I want to use a div class to put it into the div, and here is my code:

But when I ran it, it did not display the image as I wanted.
I thought that when I put the URL into the div, it must display the image as the code above?
Could you please help me with this problem?

A: An Img tag "push" your parent to have room to display the image you want to display.
If you use CSS background image, then, the browser do not take care of the size of your image. So you div is actually 0px height and 0px width. So you see nothing, but your background is correctly applied.
Try this:

or this:

Hello
text making room
to see the
background image

and you will see your image.

A: Your div contains nothing so its size is zero. You can set a height to it:

.main_product-img {
  height:200px;
  width:200px;
  background-size: contain;
}

But I think using the tag in your case is a better solution.

A: You forgot your ' in your URL. Also, you have to defy the width and height of the background in order for your image to know what areas to cover. In this example, I added width: 100vw and height: 100vh;

.main_product-img {
  width: 100vw;
  height: 100vh;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

A: Your div needs to have some height and some width. You can get this height and width by setting it manually or by setting some content in to the div.

Here is example CSS for this div. I'm not saying that you should use this but you can test it with this CSS.
.main_product-img {
    width: 50%;
    height: 50vh;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}

A: The thing is that your code does not have a width & height.
Add the width: ; and height: ; in your style="" attribute.
Example:

div {
  background-image: url('https://www.cnet.com/a/img/A7dqrTMGYMYoYMzmC1cvYA--how=/940x0/2018/09/20/62c32a15-d2f7-45ae-9caf-7a94a16c4b94/burningmandoodle.jpg');
  width: 1920px;
  height: 1920px;
}

Plus, you need to give your quotes (single or double) before the URL
And if you do not want your background to not repeat then add this to your style attribute: background-repeat: no-repeat;


text:
Q: How to simplify expressions containing complex exponentials in Sympy In a project I'm working on I'm dealing with expressions containing complex exponentials such as the one below, which I aim to simplify as much as possible:
from sympy import Rational, exp, I, pi, pretty, cos, sin

E = Rational(1,20) + (Rational(1,4) + exp(2*I*pi/5)/4)*exp(-4*I*pi/5)/5 + exp(-2*I*pi/5)/20 + (exp(4*I*pi/5)/4 + exp(2*I*pi/5)/4)*exp(2*I*pi/5)/5 + (exp(-2*I*pi/5)/4 + exp(-4*I*pi/5)/4)*exp(4*I*pi/5)/5 + (exp(-4*I*pi/5)/4 + exp(4*I*pi/5)/4)*exp(-2*I*pi/5)/5

print(pretty(E))

     ⎛     2⋅ⅈ⋅π⎞                       ⎛ 4⋅ⅈ⋅π    2⋅ⅈ⋅π⎞          ⎛ -2⋅ⅈ⋅π     -4⋅ⅈ⋅π ⎞          ⎛ -4⋅ⅈ⋅π     4⋅ⅈ⋅π⎞
     ⎜     ─────⎟  -4⋅ⅈ⋅π               ⎜ ─────    ─────⎟  2⋅ⅈ⋅π   ⎜ ───────    ───────⎟  4⋅ⅈ⋅π   ⎜ ───────    ─────⎟  -2⋅ⅈ⋅π
     ⎜       5  ⎟  ───────    -2⋅ⅈ⋅π    ⎜   5        5  ⎟  ─────   ⎜    5          5   ⎟  ─────   ⎜    5         5  ⎟  ───────
     ⎜1   ℯ     ⎟     5       ───────   ⎜ℯ        ℯ     ⎟    5     ⎜ℯ          ℯ       ⎟    5     ⎜ℯ          ℯ     ⎟     5
     ⎜─ + ──────⎟⋅ℯ              5      ⎜────── + ──────⎟⋅ℯ        ⎜──────── + ────────⎟⋅ℯ        ⎜──────── + ──────⎟⋅ℯ
1    ⎝4     4   ⎠            ℯ          ⎝  4        4   ⎠          ⎝   4          4    ⎠          ⎝   4         4   ⎠
── + ───────────────────── + ──────── + ──────────────────────── + ──────────────────────────── + ────────────────────────────
20             5                20                 5                            5                              5

I managed to simplify it a bit (mostly by trial-and-error using different functions described on https://docs.sympy.org/latest/modules/simplify/simplify.html):
E.rewrite(cos).expand().simplify()
-sqrt(-10 - 2*sqrt(5))/64 - sqrt(-10 + 2*sqrt(5))/64 + sqrt(-50 + 10*sqrt(5))/320 + 3*sqrt(-50 - 10*sqrt(5))/320

print(pretty(_))
    ____________     ____________     _____________       _____________
  ╲╱ -10 - 2⋅√5    ╲╱ -10 + 2⋅√5    ╲╱ -50 + 10⋅√5    3⋅╲╱ -50 - 10⋅√5
- ────────────── - ────────────── + ─────────────── + ─────────────────
        64               64               320                320

However, the resulting expression can still be simplified further, and in fact vanishes altogether — the question is how to do/show this in Sympy. I've tried using sqrtdenest to "denest" the square roots, but so far no luck.
Likewise, another expression rather similar to the first one simplifies to
print(pretty(-cos(pi/7)/7 - sin(pi/14)/7 + Rational(1,14) + sin(3*pi/14)/7))

     ⎛π⎞      ⎛π ⎞           ⎛3⋅π⎞
  cos⎜─⎟   sin⎜──⎟        sin⎜───⎟
     ⎝7⎠      ⎝14⎠   1       ⎝ 14⎠
- ────── - ─────── + ── + ────────
    7         7      14      7

Again, this expression vanishes, though I'm not getting to that point in Sympy. Any directions on how to proceed would be most welcome.

A: Firstly the simplest check for situations like this is to use approximate numerical evaluation:
In [2]: E.evalf()
Out[2]: -0.e-130 - 0.e-132⋅ⅈ

That strongly suggests that the result is zero.
This is used internally by the nsimplify function:
In [3]: nsimplify(E)
Out[3]: 0

Another way to verify that the expression is zero without approximation is to compute its minimal polynomial:
In [4]: minpoly(E)
Out[4]: x

E must be a root of that polynomial and it only has one root (zero):
In [5]: roots(_)
Out[5]: {0: 1}

This expression does seem to be particularly awkward for normal manipulation so many possible ways to simplify it don't seem to work. This one does though:
In [25]: E.expand().rewrite(cos)
Out[25]: 0

I think that the main difficulty for most methods of simplification is the automatic evaluation of trig functions:
In [34]: exp(2*I*pi/5).rewrite(cos)
Out[34]:
                 ________
  1   √5        ╱ √5   5
- ─ + ── + ⅈ⋅  ╱  ── + ─
  4   4      ╲╱   8    8

If we use symbols in place of numbers then we can prevent that:
In [65]: En = E.subs(exp(2*I*pi/5), exp(n*I*pi/5))

In [66]: En.rewrite(cos).simplify().subs(n, 2)
Out[66]: 0


text:
Q: Help with Google Code Issue Tracker API Long story short: I'm trying to post comments and create issues onto Google Code via an Android App called Abugadro.
I followed a very similar piece of code here:
Google Spreadsheet API update \ edit with protocol
When trying to post a comment onto the API, I've gotten various errors like 403 and 501 depending on the headers I use.
Anyway, Code talks, so here's my piece:
HttpPost postRequest = new HttpPost("http://code.google.com/feeds/issues/p/"+projName+"/issues/"+issueId+"/comments/full");

postRequest.addHeader("Content-Type","application/atom+xml;charset=UTF-8");
postRequest.setHeader("Authorization", "GoogleLogin auth=" + auth);
postRequest.addHeader("User-Agent", "abugadro-v"+getResources().getString(R.string.version));
postRequest.addHeader("Accept-Encoding","gzip");
postRequest.addHeader("GData-Version", "1.0");
//postRequest.addHeader("If-Match", "*");//Not entirely sure if I should use this or not

HttpEntity se = new StringEntity(xml,"UTF-8"); //Contains the comment info
postRequest.setEntity(se);

The IssueTrackerAPI is very vague on what sort of headers I should be using to post correctly.
http://code.google.com/p/support/wiki/IssueTrackerAPI#Modifying_an_issue_or_creating_issue_comments
P.S. I know there's a gdata-java-client but there's no sane way to use that api on android without dragging ~2mb of jars.
I really appreciate your help, this issue has been driving me insane beyond comprehension.
Thanks again.

A: The best Android library for Google API's is the google-api-java-client, which supports Android. gdata-java-client doesn't support Android.
google-api-java-client supports the Issue Tracker API, but there is no sample for it yet.  Please make a request for a sample.  Meanwhile, you can take a look some of the other examples written for Android like picasa-atom-android-sample or calendar-v2-atom-android-sample.