text:
Q: How to create Quarter parameter for SSRS Fetch xml when there is no Year or Quarter field I'm new to SSRS and building an SSRS Quarterly Report using FetchXML for Dynamics365.
I need to create a parameter for Year and Quarter (Jan-Mar, Apr-Jun, Jul-Sep and Oct-Dec).There is no Year and Quarter field in the table, only the Case Received Date field. How should I accomplish this?
Thanks!

A: You can add parameter and 'Specify Values' list in 'Available Values' like below:
Lable     Value
Jan-Mar    1
Apr-Jun    2
Jul-Sep    3
Oct-Dec    4

Then in your query, you can use this value to compare against your date using DATEPART(qq,[Case Received Date])  which returns values 1 through 4 based on quarter.


text:
Q: Match and filter Column in CSV for Desired output I have a backup report in which I have multiple columns. I want to get only those clients who have never been successful in a particular group. If the same client with the same save set gets successful in other groups, then also I should get the client as failed for that particular group in which it is failing.
Get-Content E:\Report\Daily_Failed.csv |
    ConvertFrom-Csv |
    Select-Object -Unique * |
    Group-Object -Property 'Client Name','Save Set Name','Group' |
    Where-Object { $_.Count -eq 1 -and $_.Group.Status -eq 'Failed' } |
    Select-Object -Expand Group |
    Select-Object "Client Name", "Save Set Name", "status", "Group" |
    Export-Csv -NoTypeInformation E:\Report\Final_Failed.csv

Input
Client Name,Save Set Name,Group,Status
SQL01.abc.com,MSSQL, D_CWT_SQL_FULL,Failed
SQL01.abc.com,MSSQL:master,D_CWT_SQL_FULL, Success
SQL01.abc.com,MSSQL:model,D_CWT_SQL_FULL,Failed
SQL01.abc.com,MSSQL:msdb,D_CWT_SQL_FULL,Failed
SQL01.abc.com,MSSQL,SQL_T-Log_15Mins,Success
SQL01.abc.com,MSSQL:master,SQL_T-Log_15Mins,Failed
SQL01.abc.com,MSSQL:model,SQL_T-Log_15Mins,Success
SQL01.abc.com,MSSQL:msdb,SQL_T-Log_15Mins,Success
5001.abc.com,G:\System,CWT_FS,Failed
5001.abc.com,G:\System,CWT_FS,Success
5001.abc.com,H:\System,CWT_FS,Failed

Desired Output
Client Name Save Set Name   Group            Status
SQL01.abc.com   MSSQL       D_CWT_SQL_FULL    Failed
SQL01.abc.com   MSSQL:model D_CWT_SQL_FULL    Failed
SQL01.abc.com   MSSQL:msdb  D_CWT_SQL_FULL    Failed
SQL01.abc.com   MSSQL:masterSQL_T-Log_15Mins  Failed
5001.abc.com    H:\System   CWT_FS            Failed

I want to output for all clients to a particular group which are failing.
  I tried filtering out the column with status and save set but in that, I didn't get the clients which are failed in one group and are successful in other groups.

A: Your logic is faulty, if the sum of Status=Success per group is zero you want to keep it.
Get-Content .\Daily_Failed.csv |
    ConvertFrom-Csv |
    Select-Object -Unique * |
    Group-Object -Property 'Client Name','Save Set Name','Group' |
    Where-Object {0 -eq ($_.Group|Where-Object Status -eq 'Success').Count} |
    Select-Object -Expand Group |
    Select-Object "Client Name", "Save Set Name", "status", "Group"

Just without the export this yields:
Client Name   Save Set Name Status Group
-----------   ------------- ------ -----
SQL01.abc.com MSSQL         Failed D_CWT_SQL_FULL
SQL01.abc.com MSSQL:model   Failed D_CWT_SQL_FULL
SQL01.abc.com MSSQL:msdb    Failed D_CWT_SQL_FULL
SQL01.abc.com MSSQL:master  Failed SQL_T-Log_15Mins
5001.abc.com  H:\System     Failed CWT_FS

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need info on proto.properties file in java I am completely new to java  . I would like to know what the proto.properties file is used for in programming. Any details on this is appreciated.
Regards
David

A: Property files are files that store a property by using 2 parameters, one called the key, which is the variable name, and the other being the value which is what you assign to the key.
Remember that all values saved are Strings
Property files look something like this
# You are reading the ".properties" entry.
! The exclamation mark can also mark text as comments.
# The key and element characters #, !, =, and : are written with
# a preceding backslash to ensure that they are properly loaded.
website = http\://en.wikipedia.org/
language = English
# The backslash below tells the application to continue reading
# the value onto the next line.
message = Welcome to \
          Wikipedia!
# Add spaces to the key
key\ with\ spaces = This is the value that could be looked up with the key "key with spaces"
# Unicode
tab : \u0009

Read more here and here

A: Normally, Java properties file is used to store project configuration data or settings.
See the below example how to write to properties File in Java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

public class App {
  public static void main(String[] args) {

    Properties prop = new Properties();
    OutputStream output = null;

    try {

        output = new FileOutputStream("config.properties");

        // set the properties value
        prop.setProperty("database", "AIXDB");
        prop.setProperty("dbuser", "mukesh");
        prop.setProperty("dbpassword", "password");

        // save properties to project root folder
        prop.store(output, null);

    } catch (IOException io) {
        io.printStackTrace();
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
  }
}

**Output**

config.properties

dbpassword=password
database=AIXDB
dbuser=mukesh

A: Properties are configuration values managed as key/value pairs. In each pair, the key and value are both String values. The key identifies, and is used to retrieve, the value, much as a variable name is used to retrieve the variable's value.
To manage properties, create instances of java.util.Properties. This class provides methods for the following:

*

*Loading key/value pairs into a Properties object from a stream

*Retrieving a value from its key

*Listing the keys and their values

*Saving the properties to a stream

*Properties extends java.util.Hashtable. Some of the methods inherited from Hashtable

For more details please follow Java doc link. Java Doc


text:
Q: FIR Filter for image resampling by non integer factor Hello the title of this questions says it all. I do not find any leads to how one can design a FIR filter for image interpolation to upsample it or downsample it by a non integer factor.
Imagine I want to downscale an image by a 1.5 factor with cubic interpolation, how can I create the FIR filter? And how should I do the convolution with this FIR filter (if it is possible without zero padding)?
Any help or explanation is welcome and MUCH appreciated!

A:
You didn't find anything about this because it's not posible. You need different interpolation (filter) weights at each output point.

– Cris Luengo


text:
Q: How to execute code fully before load xul file? I have a script that I add to my xul file, like:
<?xml version="1.0" encoding="UTF-8"?>

<!-- Bindings -->
<?xml-stylesheet href="chrome://test/content/bindings.css" type="text/css"?>

<mywindow id="myWindowID" width="800" height="600"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

    <script type="application/x-javascript" src="chrome://greenfox/content/jquery-1.4.4.min.js" />

</mywindow>

and on mywindow constructor (at the binding) I use a function of my scrip, called 'print'.
The problem is that sometimes, my script doesn't load really fast before it's used, and I get the message

We are unable to Print or Print
  Preview this page.

..which is related to the Printer usage.
Please note that I'm not trying to use the Printer, I'm trying to use my own print method (in the script that doesn't loaded in time) to simply write on the screen.
So, any idea how can I make the xul file wait till my script is completely loaded?

A: Solved it with a variable "window.scriptsLoaded" and a loop on my class constructor that wait..
-update
also, it didn't work with while(!window.scriptsLoaded), I needed to use:
function loadScripts() {
    if (!window.scriptsLoaded)
        setTimeout(loadScripts, 1)
    else
        loaded();
}

so the window.scriptsLoaded could be updated each time I check it. I don't really understand why.
-update
Actually, use "onload" showed itself a the better solution..


text:
Q: Appcode Reformat Code JavaDoc style comments disagreeably AppCodes 'Reformat Code' feature formats JavaDoc comments in a disagreeable manner.
This is how I like to have the comments:
/**
 * blabla
 * @return blibla array bli
 */

but 'Reformat Code' always reformats it to
/**
* blabla
* @return blibla array bli
*/
- (NSArray *) bla....

Does anyone know how I can tell AppCode to format those comments as I like, or at least how to not touch any existing comments?


text:
Q: Nodemailer SMTP generating ENOTFOUND I'm trying to implement Nodemailer in Firebase and I keep getting ENOTFOUND error as below:
Error: getaddrinfo ENOTFOUND smtpout.secureserver.net smtpout.secureserver.net:587
at errnoException (dns.js:28:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)

code: 'ECONNECTION',
  errno: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'smtpout.secureserver.net',
  host: 'smtpout.secureserver.net',
  port: 587,
  command: 'CONN'
My transporter setup is:
var transporter = nodemailer.createTransport({
        host: 'smtpout.secureserver.net',
        port: 587,
        auth: {
            user: 'uttsgroup@uttsg-demos.com',
            pass: 'somepassword'
        },
        secure:false,
        tls: {rejectUnauthorized: false},
        debug:true
    });

I've tried various options but all were generating the same error result.
Please, assist.
Many Thanks,
Badih


text:
Q: Methods with event handling giving me errors Sorry for bad title but didn't know what else to say.
So I am trying to add a little piece of code into a game I am making so that you can make the player jump by pressing any key or using the mouse.  I pretty much copied the code that makes the player jump by pressing the mouse into the code that makes him jump by keyboard keys ( risky but I like to live on the edge) but it gives me the error:
The method KeyPressed(KeyEvent) from the type new KeyAdapter(){} is never used locally

from this:
        this.addMouseListener(new MouseAdapter(){

        public void mousePressed(MouseEvent arg0) {
            player.jump();
        }

    });

this.addKeyListener(new KeyAdapter(){

    public void KeyPressed(KeyEvent arg0) {
        player.jump();
    }

});
}

I have searched the whole game but found no other things that have the word 'mouse' in them and I am also new to this. I'm sure i'm missing something obvious.


text:
Q: String as an object in pool or as a reference? I'm a little confused on what does string pool actually contain.
When we say String s = "abc", does this mean that during compile time, the string object is put in the string pool or is it the reference that is put?

A: The statement String s = "abc" causes the abc to be created in String constant pool if it is not already present. If it is present, then a reference will be returned . You can find a good tutorial about string constant pool here.
http://www.thejavageek.com/2013/06/19/the-string-constant-pool/

A: Each time you create a String that way, the JVM checks whether this Object is in the String constant pool. If so, a reference to the "pooled" instance will be returned. If it doesn't, a new instance initialized and put in the pool:
          ----------- String s = "Hello";
          |
          ٧
+-------------------+
|      "Hello"      |
+-------------------+
        pool

A: String pool is just a cache for string literal.Whenever we assign string literal to string reference ,literal will be searched in string pool and it will be assigned to reference variable.
In String s="abc" JVM  will search literal "abc" in string pool and will be assign reference of it to reference variable s.
                  ____________
          refers |           |
String s ------->|   abc     |<---- String Pool
                 |___________|

A: The pool you are talking about is in the heap and all the references that exist are present on stack(not heap). When you create a string String s = "abc"; String literal "abc" is placed in the String pool and all further references will point to this literal except the case in which you create a String object using new(separate memory space is allocated on the heap in this case).

A: The string pool refers to a place in memory where Strings are defined. The string pool has references to constants to be reused. The string pool is what allows this to happen:
String a = "a" + "b";
String b = "ab";
if(a == b) {
System.out.println("this will print");
}

a==b will evaluate to true, because the compiler sees both String a and String b as equal to "ab" so this string is stored in the String pool and both String a and String b point to this one reference.

A: "abc" is defined at compile time here and hence would be automatically interned. This string object will hence go to string intern pool. If one already exists there, its reference would be returned.The string intern pool is a part of main java heap since Java 7(and we know heaps are to contain objects).


text:
Q: Integrating boxtal PHP library into a custom WordPress Plugin I need to integrate this PHP library on my WordPress site.
I read that you have to create a plugin or integrate it into the child theme.
So I created a plugin and integrated the PHP library in the plugin folder.
https://ibb.co/vXfJjLj
Here is my plugin
    <?php
/*
Plugin Name: igosen api boxtal
Plugin URI:
Description: Relier marketplace à boxtal
Author: Serge Astrakhan
Version: 1.0
Author URI: https://igosen.fr/
*/

require_once ('/config/autoload.php');
require_once ('/config/config.php');

The require_once request causes a fatal error when activating the plugin.
Can you help me (documentation or example) to be able to correctly load the different elements.
Thank you

A: The / path will try to require the file from your server's root directory. Instead, try something like:
require_once( plugin_dir_path( __FILE__ ) . '/config/autoload.php' );
require_once( plugin_dir_path( __FILE__ ) . 'config/config.php' );

Reference

*

*plugin_dir_path()


text:
Q: Can supremacist Purebloods (like the Malfoys) be seen wearing Muggle clothes in the books? First of all I only mean books, not the movies please.
To begin with, here is related question - it doesn't reflect Draco's case though. I do not ask what he wears under his robes, I ask if he can be seen walking around dressed like a Muggle somewhere in the books.
So here is what I found on Draco wearing school robes:

He pulled the robes over his head and threw them onto the floor at Madam Malkin's feet... And with that, the pair of them strode out of the shop..

So apparently he was trying his new robes on some causal closes. It would do with a jeans a t-shirt I think, but trying on robes on top of other robes doesn't make much sense. Was Draco doing his shopping on the Diagon Alley in Muggle clothing?!
And later on the train:

To his relief, Malfoy seemed to decide that he had imagined the noise; he pulled on his robes like the others...

He pulled his robes on what? There was Pancy in the compartment and seemed like they changed all together. So were they in Muggle clothes, wearing their robes on those as Ron and Harry apparently do? Or did they have to change their common robes to the school ones?
Now I was thinking - do Pure-blood families arrive to the train station in their wizarding clothes? It seems against the Statute of Wizarding Secrecy, does it mean every year all Pure-bloods have to wear Muggle clothes to take their children to the station? Say, Lucius Malfoy?
We see at the and of The Order of the Phoenix that a whole bunch of adults waiting for Harry at the platform are dressed in Muggle clothing:

There was Mad-Eye Moody, looking quite as sinister with his bowler hat pulled low over his magical eye as he would have done without it, his gnarled hands clutching a long staff, his body wrapped in a voluminous travelling cloak. Tonks stood just behind him, her bright bubble-gum-pink hair gleaming in the sunlight filtering through the dirty glass of the station ceiling, wearing heavily patched jeans and a bright purple T-shirt bearing the legend The Weird Sisters. Next to Tonks was Lupin, his face pale, his hair greying, a long and threadbare overcoat covering a shabby jumper and trousers. At the front of the group stood Mr and Mrs Weasley, dressed in their Muggle best, and Fred and George, who were both wearing brand-new jackets in some lurid green, scaly material.

Though it could be they did it only this time because they intended to talk to the Dursleys. Or not? When Harry first meets the Weasleys on the platform he never notices their clothes, only their talk about Muggles and their owl.

Harry swung round. The speaker was a plump woman who was talking to four boys, all with flaming red hair. each of them was pushing a trunk like Harry's in front of him - and they had an owl. Heart hammering, Harry pushed his cart after them.

Does it mean all wizards obliged to dress as a Muggle when going to the platform and the Malfoys every year appear there in Muggle clothes?
Or Muggle wear is not a big deal for the new generation and Draco does occasionally wear Muggle clothing (like, in Diagon Alley) without considering it to be beneath him?

A: There's no mention of Purebloods breaking the dress code for public clothes.

The International Statute of Secrecy laid down clear guidelines on dress for witches and wizards when they are out in public.
When mingling with Muggles, wizards and witches will adopt an entirely Muggle standard of dress, which will conform as closely as possible to the fashion of the day. Clothing must be appropriate to the climate, the geographical region and the occasion. Nothing self-altering or adjusting is to be worn in front of Muggles.- Clothing - Pottemore

Later in the same article it mentions what Muggle haters wear.

Day to day, however, even those who detest Muggles wear a version of Muggle clothing, which is undeniably practical compared with robes. Anti-Muggles will often attempt to demonstrate their superiority by adopting a deliberately flamboyant, out-of-date or dandyish style in public.- Clothing - Pottermore

So, we can assume that the Malfoys did wear Muggle clothes and didn't mind it because it was practical, but dressed flamboyantly or in an out of date style to show their superiority.

A: Well, my question was more about the Malfoys, but other Death Eaters also interested me and here I found a piece of information on Voldemort himself, so I post it as an answer as - well - it is an answer in a way.
Here we see young Tom Riddle visiting Hepzibah as Borgin and Burke's worker and

he was plainly dressed in a black suit...

I think this is an interesting mention as the whole situation is set in the wizarding world and does not suggest any contacts with Muggles. And yet, Voldemort is dressed as a proper muggle.

A: Before we can talk about whether wizards want to dress like Muggles, the question is whether they even know what this means.
There is the scene at the Quiddich Cup:

One of them was a very old wizard who was wearing a long flowery nightgown...
"Just put them on, Archie, there's a good chap, you can't walk around like that, the Muggle on the gate's already getting suspicious –"
"I bought this in a Muggle shop," said the old wizard stubbornly. "Muggles wear them."
"Muggle women wear them, Archie, not the men, they wear these," said the Ministry wizard, and he brandished the pinstriped trousers.

Even the ministry wizard, who seems to know that something is wrong, doesn't seem to know that women (or men) may wear a nightgown, but not in public. It would also be strange to see a woman in a nightgown in public, but the ministry wizard didn't seem to realize that.
That scene might be meant as a joke, but wizards in general are not described as up to date with fashion, and therefor not really able to blend in or behave inconspicuously.

"You're not the first one who's had trouble with money," said Mr. Roberts, scrutinizing Mr. Weasley closely. "I had two try and pay me with great gold coins the size of hubcaps ten minutes ago." ...
At that moment, a wizard in plus-fours appeared out of thin air next to Mr. Roberts's front door.
"Obliviate!" he said sharply, pointing his wand at Mr. Roberts. ...
"Been having a lot of trouble with him. Needs a Memory Charm ten times a day to keep him happy." (GoF)

This shows that many visitors are either unable to behave like Muggles, or they don't care enough despite Ministry orders, and the Ministry doesn't really try to enforce it, it's easier to modify a Muggle's memory, and it's not like anybody cares about the effect of ten obliviations a day. And it' not like the obliviations are without side effects. While Mr Weasley said he will be all right eventually, I doubt anybody bothered to verify that.

Mr Roberts had a strange, dazed look about him, and he waved them off with a vague 'Merry Christmas'.
"He'll be all right," said Mr Weasley quietly, as they marched off onto the moor. "Sometimes, when a person's memory's modified, it makes them a bit disorientated for a while ... and that was a big thing they had to make him forget."

Even Arthur Weasley, who is supposed to be interested in Muggles, doesn't know about currency, as seen earlier, or electricity.

"Really? Ecklectic, you say? With a plug? Gracious, I must see that..."

We also don't see much need for wizards to blend in with Muggles, so why should they try, and if they try, why restrict their effort just to clothes, as their behavior would reveal them anyway?


text:
Q: SQL Query related to average and length i have a question. im currently doing an assignment, and having trouble in one particular request.
the request is:
Find Customers who have purchased more than 2 times. Get the
1. customer information
2. purchase frequency
3. total spending
4. avg basket size.

i already got 1 - 3, but i cant do much about number 4.
the values on product can have several values, separated by commas.
~> (product id: 12,4,5) -> if an order buys more than 1 product
i got to the point where i can separate it with length replace, but im a bit confused on how to show it to the average basket size.
thanks for any help!
SQL Table Image
sql table
**Customer**
Customer ID
Name
AddressCity

**Order**
OrderID
CustomerID
ProductID
Total

**Delivery**
DeliveryID
OrderID
AddressCity

this is my current sql statement
SELECT Customer.*, Order.CustomerID,
    COUNT(Order.CustomerID) AS PurchaseFrequency,
    SUM(Order.Total) AS TotalSpending
    FROM Customer JOIN Order
    ON Customer.CustomerID=Order.CustomerID
    Group By Customer.CustomerID
    Having Count(*) > 1

A: LEN(Order.ProductID) - LEN(REPLACE(Order.ProductID, ',', '')) + 1

Should give you the total amount of products per order.
Just add that to your existing statement.
SELECT Customer.*, Order.CustomerID,
    COUNT(Order.CustomerID) AS PurchaseFrequency,
    SUM(Order.Total) AS TotalSpending,
    AVG(LEN(Order.ProductID) - LEN(REPLACE(Order.ProductID, ',', '')) + 1) as AvgProdQuantityPerOrder
    FROM Customer JOIN Order
    ON Customer.CustomerID=Order.CustomerID
    Group By Customer.CustomerID
    Having Count(*) > 1

EDIT:
The fields used in the SELECT part should also be specified in the GROUP BY part. Your query becomes then something like this:
SELECT Customer.CustomerID, Customer.Name, Customer.AdressCity,
        COUNT(Order.CustomerID) AS PurchaseFrequency,
        SUM(Order.Total) AS TotalSpending,
        AVG(LEN(Order.ProductID) - LEN(REPLACE(Order.ProductID, ',', '')) + 1) as AvgProdQuantityPerOrder
FROM Customer JOIN
        Order  ON Customer.CustomerID=Order.CustomerID
GROUP BY Customer.CustomerID, Customer.Name, Customer.AdressCity
Having Count(*) > 1


text:
Q: Extract subdomains from strings using split in python I have a python function that outputs/prints the following:
['CN=*.something1.net', 'CN=*.something2.net', 'CN=*.something4.net', 'CN=something6.net', 'CN=something8.net', 'CN=intranet.something89.net', 'CN=intranet.something111.net, 'OU=PositiveSSL Multi-Domain, CN=something99.net', 'OU=Domain Control Validated, CN=intranet.something66.net',...etc]

I am trying to extract all the sub-domain names between "CN=" and the single quotation mark, using the split() method in python. I've tried split('CN=', 1)[0]  but i can't get my head around on how to use it
what i want to print out:
['something1.net', 'something2.net', 'something4.net', 'intranet.something111.net', 'intranet.something66.net']

Any help would be gratefully appreciated :-)
Thanks, MJ

A: The last single quote is indicating the end of the string, so it seems you just want everything after CN=. Assuming that's the case, you can just chop off the first three characters:
subdomains = [item[3:] for item in my_list if item.startswith('CN=')]

A: Here is a more readable code that extracts the subdomains in more clean or better way;
@tzaman code didn't really give me subdomains.
myDirtyDomains = ['CN=*.something1.net', 'CN=*.something2.net', 'CN=*.something4.net',\
'CN=something6.net', 'CN=something8.net', 'CN=intranet.something89.net',\
 'CN=intranet.something111.net', 'OU=PositiveSSL Multi-Domain', \
 'CN=something99.net', 'OU=Domain Control Validated', 'CN=intranet.something66.net']

cleanSubDomainsList = []

for item in myDirtyDomains:
    countDots = item.count(".")
    if countDots == 2:
        host = item.partition('CN=')[2]
        subdomain = host.partition('.')[0]
        cleanSubDomainsList.append(subdomain)

print(cleanSubDomainsList)

A: If you just want to strip CN= from each string, you can strip from the left with str.lstrip():
subdomains = [item.lstrip("CN=") for item in my_list]


text:
Q: How to move subquery to WITH statement I have a query:
SELECT *
FROM app_interfaces
WHERE ROWID IN (
    SELECT MAX (ROWID)
    FROM app_interfaces
    WHERE version <= (SELECT MAX (version) AS v FROM app_interfaces)
    GROUP BY id);

I'm not sure if this is the "proper" way to write this query, and I'm trying to use Oracle's WITH clause like so:
WITH latest_version AS (
SELECT MAX(version) AS v FROM app_interfaces )
SELECT *
FROM app_interfaces
WHERE ROWID IN (
    SELECT MAX (ROWID)
    FROM app_interfaces
    WHERE version <= latest_version.v
    GROUP BY id);

Can you tell me A) which technique is more efficient? B) Why the second technique (with with) is incorrect?
[Edit]
The intent of this query is the following:
I have a model where each entry is associated with a 'version' (so one entity in the app_interfaces model may have multiple versions). However, these versions are determined based on a date, so they're not necessarily sequential (I could have 1402, 1403, 1407, etc.).
If I'm looking at version X of my model, I want to see all entries at version X or the next latest version of the entities which don't have that version number.
So if app A has entries for versions 1402, 1403, and 1407; and app B has entries for versions 1402 and 1405, and I query for the latest version (1407), I would expect to get teh 1407 entry for app A and the 1405 entry for app B. Ideally I'd have another query I could use to specify particular entries (instead of the max).

A: No, it isn't.  You need to mention the CTE in a from clause:
WITH latest_version AS (
      SELECT MAX(version) AS v FROM app_interfaces
     )
SELECT *
FROM app_interfaces
WHERE ROWID IN (SELECT MAX(ROWID)
                FROM app_interfaces
                WHERE version <= (SELECT v FROM latest_version)
                GROUP BY id
               );

Unless version can be NULL, the comparison doesn't do anything.  So, your query is equivalent to:
SELECT *
FROM app_interfaces
WHERE ROWID IN (SELECT MAX(ROWID)
                FROM app_interfaces
                GROUP BY id
               );

or
SELECT *
FROM app_interfaces
WHERE ROWID IN (SELECT MAX(ROWID)
                FROM app_interfaces
                WHERE version IS NOT NULL
                GROUP BY id
               );


text:
Q: make glossaries \glslink respect the first-use I would like to have a \glslink-style command, that respects the first use flag of an abbreviation i.e. printing the abbreviation in parantheses if this is the first occurance.
MWE:
\documentclass{article}
\usepackage{hyperref}
\usepackage[acronym,toc]{glossaries}

\makeglossaries

\newacronym{abc}{ABC}{Arbitrary Bull Crap}
\begin{document}

I would need some more \glslink{abc}{Arbitrary Bull Crappings}.
This is some \gls{abc}.

\end{document}

Output should be:
I would need some more Arbitrary Bull Crappings (ABC). This is some ABC.
Output is:
I would need some more Arbitrary Bull Crappings. This is some Arbitrary Bull Crap (ABC).
Unfortunately I could not find a corresponding option in the documentation and fiddling with the inerts of package commands is not my strong suite.
Is there an easy solution for that?

A: I have found a solution, although not the best I guess.
After enough digging in the documentation I found the \ifglsunused{}{}{} command, that executes code depending on the first-use flag of the given gls-entry.
\newcommand{\GlsPara}[2]{%
    \ifglsused{#1}{%
        \glslink{#1}{#2}%
    }{%
        \glslink{#1}{#2 (\acrshort{#1})\xspace}%
        \glsunset{#1}%
    }%
}%

\newcommand{\GlsParaPl}[2]{%
    \ifglsused{#1}{%
        \glslink{#1}{#2}%
    }{%
        \glslink{#1}{#2 (\acrshortpl{#1})\xspace}%
        \glsunset{#1}%
    }%
}%

From that I derived these two commands, that add my short acronym depending on the first-use state and actually sets the first-use flag afterwards, so everything works as expected.
Unfortunately this does not respect your chosen acronym style at all, but instead uses my hardcoded choice of "<long>(<short>)" If someone wants to improve this to work with any custom style -- go ahead :D


text:
Q: Solve $1-x^2=5-2x$ graphically
Solve the following equation graphically: $$1-x^2=5-2x$$

To solve the equation graphically, we must draw the graph for each side, member of the equation, and see where they cross, are equal. The $x$ values of these points are the solutions to the equation. $$y_1=1-x^2$$ and $$y_2=5-2x$$

We see that the graphs don't cross; therefore, we don't have solutions to the given equations.

According to WolframAlpha, this equation has complex roots. We can't see them in the Cartesian coordinate system, right?

A: The equation is the same as $$x^2-2x+4=0$$ which is solved by the quadratic formula, $$ x=\frac {2\pm \sqrt {4-16}}{2}=1\pm i\sqrt 3 $$
Therefore the roots are complex numbers and we do not see them on the plane $\mathbb {R^2}$ where coordinates are real numbers.
Similar situation happened with polynomials such as $$x^2+1$$ and $$x^4+1$$
We simply can not see the complex roots on the real plane.

A: When you plotted your curves, you assumed that the $ x $ coordinate is real
.
But your second degree equation has no real root. its discriminant is negative.
If you want to solve it graphically, you should plot two surfaces :
$$f(z)=1-z^2$$
and
$$g(z)=5-2z.$$

A: We can make the complex roots visible as real roots if we reflect the graph at the apex of the parabola. Here is a nice answer which explains the procedure. I´m going to show how it works graphically in your case
We can transform the equation to $f(x)=0$
$$f(x)=x^2+bx+c=x^2-2x+4=0$$
Now we can transform the function f to get the corresponding real roots.
$$h(x)=-x^2-bx-\frac{b^2}2+c=-x^2+2x-2+4$$
The graphs looks like below.

The real roots of $h(x)$ are $x_1=1-\sqrt{3}, x_2=1+\sqrt{3}$
Therefore the complex roots of $f(x)$ are  $x_1=1-i\cdot \sqrt{3}, x_2=1+i\cdot \sqrt{3}$


text:
Q: Jenkins job workspace directory name change We have an old jenkins v2.138 upgraded to v2.332. with this upgrade, there is a change related with workspace structure.
with v2.138, it was like /jenkins_home/workspace/jobaaa-SFSBDFEXXXXXXXXXXX@script/pom.xml
with v2.332, it is now /jenkins_home/workspace/jobaaa@script/SFSBDFEXXXXXXXXXXX/pom.xml
with this change, our pipeline script fileexist("pom.xml") doesn't work anymore.
If we don't want to change our pipeline script, is there any setting to set back the workspace structure as in v2.138.
Thank you very much for any input!


text:
Q: What's the difference between XHTML and DHTML? Reading about both separatedly, looks like the same, html+xml+javascript.
What's the difference between then? Is there any?

A: XHTML is a w3c standard, a form of HTML that also strictly conforms to XML.
DHTML is a largely deprecated term (it is short for 'Dynamic HTML') which was introduced when the first early static web sites started introducing client side scripting to make the page more 'dynamic'. Nobody really talks in terms of DHTML any more (the term got superseded by 'ajax', and 'web 2.0', and 'web app')

A: No, neither one is HTML + XML + Javascript.
XHTML is HTML (but also XML)
It's just a dialect of HTML that conforms to the syntax rules of XML. Javascript is not part of the XHTML specification (or any HTML specification).
DHTML is HTML + Javascript
It stands for Dynamic HTML, and Javascript adds the dynamic part. The HTML part can also be the dialect XHTML.

A: *

*XHTML is a dialect that is based on the XML language while DHTML is not a dialect or a language but a collection of other technologies

*Both were created to provide additional features and interactivity to HTML

*DHTML still uses HTML at its core and is plagued with HTML related problems

*XHTML is more streamlined and easier to code with because of its conformance to XML

*DHTML is already outdated and has been replaced by other technologies

take a look to this post:
http://www.differencebetween.net/technology/difference-between-dhtml-and-xhtml/

A: DHTML is dynamic HTML, means the contents of html becomes dynamic and changes time to time and did not require developer again after one time creation of language.
XHTML extensive HTML means this is also uses XML , simple is that in XML you can build your own tags and used in your project or file.


text:
Q: Place label along line near both start and end of line in QGIS I would like to place label at both the start and the end of a polyline in QGIS.
At the moment I'm only able to place a labet either at the start or at the end of my polyline.
I guess I should use the generator geometry
line_substring(reverse($geometry),0,1)
line_substring(($geometry),0,1)

How to use those 2 code together?

A: You can create a generated geometry as Point / Multipoint type :
collect_geometries(
    start_point($geometry),
    end_point($geometry)
)

Documentation :

*

*collect_geometries

*start_point

*end_point

A: You can use rule based labeling.
Create a rule labelling the start point. When done, copy/paste it and instruct to label the end point. In both cases, don't set any filter.


text:
Q: CSS Align items in a column depending on content I have the following html code with own css and bootstrap classes:

91.86

    (+61%)

108.15

    (+108%)

329.93

    (+593%)

And CSS:
.table-string {
    width: 100%;
    text-align: end;
}

I need to recieve column like this:

But actually get this:

How to align values without percentages in a column so that they are strictly under each other: hundreds under hundreds, tens under tens, ones under ones? And also value and percentage must be aligned at the end of the field. Thanks for any help

A: As a temporary solution, you can use something like this. Just set the width: 50%; of your
 and  tags.

.table-string {
    width: 50%;
    text-align: end;
}
span.ml-2 {
    width: 50%;
    text-align: left;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

91.86

    (+61%)

108.15

    (+108%)

329.93

    (+593%)

A: You need to divide your row into 2 equal halves and align text depending

91.86

    (+61%)

and this is an example
Let me know if you need anything else

A: Remove d-flex from all the Div's and put d-inline onto all
's and 's instead. With this you most likely do not need the CSS for .table-string so remove that as well.
Eg

91.86

(+61%)

A: Apparently you are using Bootstrap, and if I understood your question, you just need to add two classes to the flex item, flex-column align-items-end, in order to set the direction of flex items and change the alignment on the cross axis:

[…]


text:
Q: Obtain id of current element in view I have a list of items that are organized in an alphabetical order on a page. I would like to create a fixed element at the side of the page that shows, which letter section you are currently scrolling by.
For example, if you are scrolling past items starting with the letter 'D', the fixed div will show 'D'. I have been trying to create this with jQuery, but have been finding it tricky.
Each section has the class 'card-container' and an 'id' corresponding to the current letter.
ie.

  ...

  ...

  ...

...

Any idea how I can accomplish this?
EDIT
So far I have this:

$(window).scroll(function() {
  var winTop = $(this).scrollTop();
  var letters = $('.card-container');

  letters.each(function(section) {
    if($(this).position().top <= winTop) {
      console.log($(this).context.id);
      $('.letter-show h3').text($(this).context.id);
    }
  });
});

So this seems to work, but I feel like it's not very performant. Any suggestions to improve on this?

A: As I said in the comment: There's not much you can do to improve your code - a few millisecond gain at most. Stuff like minimizing the DOM lookups and breaking the loop when the right element is found, dropping jQuery, etc... But I doubt you'd notice a difference even on the slowest machine you can find around.

var letters = $('.card-container');
var letterShow = $('.letter-show h3');
$(window).scroll(function() {
  var winTop = $(this).scrollTop();
  letters.each(function(section) {
    if($(this).position().top <= winTop) {
      letterShow.text($(this).context.id);
    }
  });
});
.card-container {height: 300px;border-top: 1px solid}
.letter-show {position: fixed}

  ...

  ...

  ...

  ...

  ...

A: This is what did the trick:

$(window).scroll(function() {
  var winTop = $(this).scrollTop();
  var letters = $('.card-container');

  letters.each(function(section) {
    if($(this).position().top <= winTop) {
      $('.letter-show h3').text($(this).context.id);
    }
  });
});


text:
Q: When does $f(x) = g(x)$ for all $x$ imply $f=g$ for polynomials $f$ and $g$? Let $R = k[x_1, x_2, \dots, x_n]$ for some field $k$ and $n \in \mathbb{N}$. Suppose I have two polynomials $f, g \in R$ which satisfy $f(x) = g(x) \forall x \in k^n$. Under which conditions can we conclude that $f$ and $g$ are equal not only as functions, but as elements of $R$?
I know that the property I am looking for is equivalent to demanding that the ideal $I := \{ f \in R \vert f(x) = 0 \forall x \in k^n \}$ be the zero ideal.

A: Given a commutative ring $R$, we always have a well-defined ring-homomorphism $\phi\colon R[x]\to R^R$, where $R^R$ is the ring of all functions $R\to R$ with pointwise addition and multiplication, given by mapping $p(x)\in R[x]$ to the function $p\colon R\to R$ that sends $a$ to $p(a)$.
Theorem. Let $R$ be an integral domain. The morphism $\phi$ is one-to-one if and only if $R$ is infinite.
Proof. Let $K$ be the field of quotients of $R$.
Assume first that $R$ is infinite, and that $p\in\ker(\phi)$. Then $p(x)$, viewed as an element of $K[x]$, has at least $|R|$ roots; since $R$ is infinite and $K$ is a field, the Factor Theorem and the fact that $K[x]$ is a UFD yield that $p(x)=0$. Thus, $\phi$ is one-to-one.
Conversely, assume that $R$ is finite. Then $K$ is finite of order $p^r$ for some $k$. By Lagrange's Theorem, we know that for every $a\in K$, if $a\neq 0$ then $a^{p^{r}-1} = 1$. Thus, every element of $K$ is a root of $q(x)=x^{p^r}-x$. In particular, $q\in\ker(\phi)$, but $q\neq 0$. Thus, $\phi$ is not one-to-one. $\Box$
Corollary. Let $n\geq 1$, $k$ be a field, and let $R=k[x_1,\ldots,x_n]$. Now let $\phi\colon R\to k^{k^n}$ be the morphism from $R$ to the ring of all functions from $k^n$ to $k$ (with pointwise addition and multiplication) given by $\phi(p)(a_1,\ldots,a_n) = p(a_1,\ldots,a_n)$. Then $\phi$ is one-to-one if and only if $k$ is infinite.
Proof. If $k$ is finite of order $p^r$, then $p(x_1,\ldots,x_n) = x_1^{p^r}-x_1$ has $\phi(p)(a_1,\ldots,a_n) = 0$ for all $(a_1,\ldots,a_n)\in k^n$, but $p\neq 0$. Thus, $\phi$ is not one-to-one.
Conversely, assume that $k$ is infinite, and let $p(x_1,\ldots,x_n)\neq 0$. If $p$ is constant, then clearly $\phi(p)$ is not the zero function, so it does not lie in $\ker(\phi)$. Thus, we may assume that $p$ has positive degree in at least one of the variables, and without loss of generality say it has  positive degree in $x_1$. That is, we can write $p(x_1,\ldots,x_n)$ as $q(x_1)$, with $q\in S[x_1]$, where $S=k[x_2,\ldots,x_n]$. Say
$$q(x_1) = p_s(x_2,\ldots,x_n)x_1^s + \cdots + p_1(x_2,\ldots,x_n)x_1 + p_0(x_2,\ldots,x_n),$$
where $p_s(x_2,\ldots,x_n)\neq 0$. Arguing inductively, we know that there exist $(a_2,\ldots,a_n)\in k^{n-1}$ such that $p_s(a_2,\ldots,a_n)\neq 0$. In particular, $p(x_1,a_2,\ldots,a_n)$ is a nonzero polynomial in $x_1$ of degree $s\gt 0$.
By the Theorem above, we know that there exists $a_1\in k$ at which this polynomial is not equal to $0$. Thus, there is an $n$-tuple $(a_1,\ldots,a_n)$ such that $p(a_1,\ldots,a_n)\neq 0$, proving that $\phi(p)\neq 0$. Thus, $\ker(\phi) = \{0\}$, proving that $\phi$ is one-to-one. $\Box$

A: If $k$ is finite, then $x_1^{|k|}$ and $x_1$ are polynomials which take equal values.
Now assume $k$ is infinite.
Prove by induction on $n$ that if $k$ is an infinite field and $p\in k[x_1,\dots,x_n]$ has the the property that $p(v)=0$ for all $v\in k^n$ that $p=0.$
For $n=1,$ this is a result that a non-zero polynomial of one variable over a field can only have finitely many roots.
General case: Write $$p=\sum_{j=0}^m p_jx_n^{j}$$ with each $p_j\in k[x_1,\dots,x_{n-1}].$ $p=0$ iff $p_j=0$ for all $j.$ So if $p\neq 0,$ then some $p_j\neq 0.$ Then the by induction, there are values such that $p_j(v_1,\dots,v_{n-1})\neq 0.$
But then $q(x_n)=p(v_1,\dots,v_{n-1},x_n)$ is a non-zero polynomial in one variable, so $q(v_n)$ can't be zero for all $v_n\in k.$ Pick $v_n$ so that $q(v_n)\neq 0.$ Then $p(v_1,\dots,v_n)=q(v_n)\neq 0.$

Note this proves the case that $p_1,p_2\in R$ has $p_1(v)=p_2(v)$ for all $v\in k^n$ since $p=p_1-p_2$ would be a polynomial always zero and thus   the above shows (if $k$ is infinite) that $p_1-p_2=0,$ or $p_1=p_2.$


text:
Q: Razer mouse not detected since update After I installed the latest Mac update (Big Sur 11.5.2) my Razer Basilisk V2 mouse is no longer being detected. The light in the mouse turns white, but the mouse isn't working.
I have reset SRAM and PRAM, which didn't work. I have installed bootcamp, because I have assumed that this is a software error, and it didn't work there as well. The USB device was detected, not as the Razer device it is, but it was detected. The following error was visible:
This device cannot start. (Code 10)

I still think, that this is a software problem and that there is some sort of corrupt information on my system. Unfortunately I do not have a second PC or MacBook to test the Razer mouse itself. Connecting my lightning power cable or my iPhone to the USB-Ports works though!
Is there a way to make my mouse work again? Maybe some sort of software or the possibility to remove corrupt files?

A: Per instructions found on this site:

Boot into recovery mode (Restart your mac and hold ⌘+ R during
startup. (Command + R)
Go to Utility → Terminal
Type /usr/sbin/spctl kext-consent add R2H967U8J8 and press Enter
Type /usr/sbin/spctl kext-consent list and press Enter

Recommend to visit the site listed above to see full details about what is being done here.


text:
Q: Making a program exit during a loop I recently was playing around with Java, and I made a program that runs in a loop. When I tried hitting the X in the corner to close it, nothing happened. I tried adding standard mouselistener code to make it exit, but it won't come through the loop. The program is simply a small square bouncing around the screen:
package mainPackage;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;

import javax.swing.*;

public class MainClass extends JApplet{
    public static boolean isRunning = true;
    public static void startStop(){
        if(isRunning){
            isRunning = false;
        } else {
            isRunning = true;
        }
    }
    /**
     * Eclipse kept yelling at me.
     */
    private static final long serialVersionUID = -3997547128895841169L;
    final static Color bg = Color.white;
    final static Color fg = Color.black;
            /*
     * The direction of the box; 1 is up-right, 2 is down-right, etc.
     */
    public static byte direction = 1;
            /*
             *The X and Y values start somewhat randomly.
             */
    public static short x = (short) (Math.random() * 150);
    public static short y = (short) (Math.random() * 150);
    public void init() {

        }
    public static void moveBall(){
        if(x >= 585){
            if(direction == 1){
                direction = 4;
            } else {
                direction = 3;
            }
        } else if(x <= 0){
            if(direction == 3){
                direction = 2;
            } else {
                direction = 1;
            }
        } else if(y <= 0){
            if(direction == 1){
                direction = 2;
            } else {
                direction = 3;
            }
        } else if(y >= 365){
            if(direction == 3){
                direction = 4;
            } else {
                direction = 1;
            }
        }
        if(direction == 1){
            x++; y--;
        } else if(direction == 2){ x++; y++;
        } else if(direction == 3){ x--; y++;
        } else if(direction == 4){ x--; y--;
        } else { System.out.println(direction); System.exit(5);}
    }
    public void paint(Graphics g){
        Graphics2D g2 = (Graphics2D) g;
        Color color = Color.black;
        Rectangle2D.Double a = new Rectangle2D.Double(250, 250, 10, 10);
        Rectangle2D.Double fill = new Rectangle2D.Double(0, 0, 600, 400);
        g2.setPaint(color);
        g2.fill(fill);
        while(isRunning){
            g2.setPaint(Color.blue);
            g2.fill(a);
            try {
                Thread.sleep(15L);
            } catch (InterruptedException e) {
                System.out.println("Interrupted!");
                e.printStackTrace();
            }
            g2.setPaint(Color.black);
            g2.fill(a);
            a.setRect(x, y, 10, 10);
        }
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        JFrame jframe = new JFrame("Test");
        jframe.setVisible(true);
        jframe.setBounds(250, 250, 600, 400);
        jframe.setResizable(false);
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JApplet applet = new MainClass();
        jframe.getContentPane().add("Center", applet);
        while(isRunning){
            moveBall();
            try {
                Thread.sleep(15L);
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("Interrupted.");
            }
        }
    }
}

[Edit]I forgot to mention that when I exported it into an executable JAR file and then ran it, I had to open Task Manager, which then told me it was not responding, in order to close it.
Is there anyway to re-write this so that it can close?

A: I think you're not listening the close event. Try with this:
class WindowEventHandler extends WindowAdapter {
 public void windowClosing(WindowEvent evt) {
  isRunnig = false;
 }
}

and
jframe.addWindowListener(new WindowEventHandler());

A: Thread.sleep and main loop in Swing EDT are bad idea.
Use javax.swing.Timer.


text:
Q: How to efficiently find the index of a number in an array at which all the previous indexes add up to a given integer N? UPDATE: I realized the question is invalid. Ignore it. I made a mistake in the for loop, it actually takes only ~1 ms to sum all the indexes, not half a second, that lead me to the assumption it can be optimized with binary search, which does not apply here.

Let's say we have:

*

*an integer target = 85

*an array of integers array = [36, 48, 48, 36, 48, 48, 48, 48, 48, 48]
How would we efficiently find the index at which sum(array[0], array[N]) > target ? In this example, the index would be 2 because the sum of indexes exceeds the target at index 2.
Basically, I have a virtual container of elements (it renders only a small subset of elements at all times) all of which have different heights (36, 48, etc) and a scroll event that returns the amount of scrolled pixels (target), so I'm trying to find the element to which the container is scrolled to, in this example the container is scroll 85px down, which means it scrolled pass the element 2.
Example:
let target = 85
let array = [36, 48, 48, 36, 48, 48, 48, 48, 48, 48]

// Finding the element with a bruteforce method:
array[0] > target // false
array[0] + array[1] > target // false
array[0] + array[1] + array[2] > target // true
return 2

For some reason trying to sum all the indexes until we find the target value using a for loop takes half a second per 1000 values.
I'm not sure if there's a well known algorithm for this already, but I figured I have to use a custom derivative form of a binary search to find the index in just a few iterations, for example:
Divide the array in half
Sum all the indexes in the left half
If the target < sum, it means the target is in the left half, so divide it again
If the target > sum, extend the search to the right half
Repeat recursively

I've partially created this recursive algorithm but I'm having difficulties figuring out how to properly handle the condition when the target is in the "right half" of the array, i.e. when target > halfSliceSum:
let target = 85
let array = [36, 48, 48, 36, 48, 48, 48, 48, 48, 48]
console.log(getElementIndexAtTargetPosition(array, target))

function getElementIndexAtTargetPosition(array, target) {
  // TESTS (expected results):
  // ([36, 48, 48, 36, 48, 48, 48, 48, 48, 48], 35) => return 0
  // ([36, 48, 48, 36, 48, 48, 48, 48, 48, 48], 36) => return 0
  // ([36, 48, 48, 36, 48, 48, 48, 48, 48, 48], 37) => return 1
  // ([36, 48, 48, 36, 48, 48, 48, 48, 48, 48], 84) => return 1
  // ([36, 48, 48, 36, 48, 48, 48, 48, 48, 48], 85) => return 2
  // ([36, 48, 48, 36, 48, 48, 48, 48, 48, 48], 456) => return 8

  let halfIndex = Math.round(array.length / 2)
  let halfSlice = array.slice(0, halfIndex)
  let halfSliceSum = halfSlice.reduce((a, b) => a + b, 0)
  if (array.length === 1) {
    return 0
  }
  if (target === halfSliceSum) {
    return halfIndex
  }
  else if (target < halfSliceSum) {
    return getElementIndexAtTargetPosition(halfSlice, target)
  }
  else if (target > halfSliceSum) {
    // Increase search slice by Math.round(halfIndex * 1.5)?
    // ...
  }
}

The target is always within the array, i.e. target <= sum(array[0], array[lastIndex])

A: You must sum up all the individual values until you reach the threshold, there's no other way of doing it when you are just given the array.
However, if you have to do this multiple times it can help to transform the array into one of increasing sums, on which you then can run the binary search (assuming there are no negative summands so it actually is an increasing sequence). You might even drop the original array, as you can still access its values by computing differences.

A: I agree with the answer provided by @bergi. Specially if the array is not in a given sequence or pattern.
The thing that you are proposing is a false sense of optimization. Though it may look like it, You are not doing a "binary" search. You are still doing the "unoptimized" work of adding the full array albeit in two halves.
And in the best case this "binary" approach will end up needing one more iteration than the "linear" approach.
As mentioned already, The most effecient approach is to just keep adding till you reach the condition.
On a side note, this looks like a XY problem, what exactly are you trying to achieve in the first palce?


text:
Q: Change data requirements of an input field based on the value of a select field in a web form I am working on a web form that includes a select drop down with two options: "Cedula" (in English, "Identification") and "Pasaporte" (in English, "Passport").
Here is an image of my web form so far.
Please help me achieve the following goal: when the user selects "Cedula", they are limited to 10 digits, but when they select "Pasaporte, they are not limited to 10 digits.
Here is my code so far:
<?php
if ($_GET['id']) {
    $cliente = $clienteNegocio->recuperar($_GET['id']);
    $txtAction = 'Editar';
}else{
    $cliente = new cliente();
    $txtAction = 'Agregar';
}

?>

<?php echo $txtAction; ?> Cliente

    <form role="form" method="post" id="principal">
        <input type="hidden" name="id" value="<?php echo $cliente->getId();?>" >

            Nombre
            <input type="text" class="form-control" id="nombre" name="nombre" placeholder="Nombre" value="<?php echo $cliente->getNombre();?>" required>

            Apellidos
            <input type="text" class="form-control" id="apellido" name="apellido" placeholder="Apellido" value="<?php echo $cliente->getApellido();?>" required>

            Tipo de Documento
            <select class="form-control" id="tipoDoc" name="tipoDoc">
                <option value="Cedula"  <?php if($cliente->getTipoDoc() == 'Cedula') {echo "selected";} ?>  >Cedula</option>
                <option value="Pasaporte" <?php if($cliente->getTipoDoc() == 'Pasaporte') {echo "selected";} ?> >Pasaporte</option>
            </select>

            Numero de Documento
            <input type="number" class="form-control" id="nroDoc" maxlength=10 oninput="if(this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
             name="nroDoc" placeholder="Numero de Documento" value="<?php echo $cliente ->getNroDoc();?>" required>

A: There you go.
I have written a javascript function to check the length with you select Pasaporte/Cedula.
Secondly, in <input type = "number"/> you cannot set maxLength. Hence you have to set <input type = "text" />. Also, an onKeyPress event to verify the input as number
<?php
if ($_GET['id']) {
    $cliente = $clienteNegocio->recuperar($_GET['id']);
    $txtAction = 'Editar';
}else{
    $cliente = new cliente();
    $txtAction = 'Agregar';
}

?>

<?php echo $txtAction; ?> Cliente

    <form role="form" method="post" id="principal">
        <input type="hidden" name="id" value="<?php echo $cliente->getId();?>" >

            Nombre
            <input type="text" class="form-control" id="nombre" name="nombre" placeholder="Nombre" value="<?php echo $cliente->getNombre();?>" required>

            Apellidos
            <input type="text" class="form-control" id="apellido" name="apellido" placeholder="Apellido" value="<?php echo $cliente->getApellido();?>" required>

            Tipo de Documento
            <select class="form-control" id="tipoDoc" name="tipoDoc" onChange="setMaxLength()">
                <option value="Cedula"  <?php if($cliente->getTipoDoc() == 'Cedula') {echo "selected";} ?>  >Cedula</option>
                <option value="Pasaporte" <?php if($cliente->getTipoDoc() == 'Pasaporte') {echo "selected";} ?> >Pasaporte</option>
            </select>

            Numero de Documento

            <input type="text" class="form-control" id="nroDoc" maxlength=10 onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
             name="nroDoc" placeholder="Numero de Documento" value="<?php echo $cliente ->getNroDoc();?>" required>

    </form>


text:
Q: Can Dark Matter be light and cold at the same time? In most of the papers that I encounter, the mass range for Dark matter is generally taken to be 1-1000 GeV. Is it possible that dark matter is of the order of few MeV? What observation is violated in this case?
To be clear, I emphasize that the DM is cold (kinetic energy << mass) as is required for structure formation.

A: The dark matter you are talking about is "cold dark matter". Cold dark matter is non-relativistic (their kinetic energy is much less than their rest mass energy). The classification refers not to their kinetic energies now (which have been reduced by the expansion of the universe), but their kinetic energies at an epoch that was important for structure formation.
The wikipedia page on cold dark matter suggests that this is about 1 year after the big bang when the particle horizon contains the mass of a typical galaxy. At this epoch temperatures were of order 1 keV, so that would seem to admit the possibility of particles with rest mass energies of $\sim 1$ MeV being described as "cold".
Therefore the reason that cold dark matter candidate particles are expected to have masses $>1$ GeV is down to theoretical ideas. For instance the lightest WIMPS are expected to be of order 100 GeV because they are thought to be the leftovers of an electroweak interaction in supersymmetric models that appear at these energy scales.
On the other hand axions are not expected to be heavy, with masses $<1$ eV. These are still "cold dark matter" candidates however, because they are bosons and could form a condensate with low kinetic energy even at relatively high temperatures. Hence this gives an answer to the title of your question - yes it is possible for light particles to be cold dark matter.
In recent years there has been a move towards looking at/for other particles  such as sterile neutrinos, with masses of maybe keV or tens of keV. However, these are known as warm dark matter and would lead to different observational properties from cold dark matter with regard to their dynamical behaviour and role in structure formation.
As far as I know there would currently be no observational objection to dark matter being made of 1 MeV, non-interacting, particles - they would be cold dark matter.


text:
Q: Is buffered io using stdio.h async? I understand that one of the advantages of using stdio.h FILE over direct read()/write() is the buffering, interrupt handling, etc.  So, as I understand, all the fwrite()s get buffered up until I do an fclose().  So far, so good.  Now, when I do an fclose(), will I block until the data is flushed to disk or will the fclose() return right away after handing the data over to the OS and letting it flush to disk at its leisure?

A: There are buffering at many levels, this depends on the OS and many other things.
Typically there's an internal buffer in the FILE* living in your application that is either flushed out to the file (or whichever device the FILE* is connected to)

*

*when the internal FILE* buffer is full

*when you've written a newline (in case of a line buffered FILE*)

*when you close the FILE*

*when you call fflush()

*the FILE* could also be unbuffered

In the case of an ordinary disk file, most OS have buffering in the kernel, so flushing the
FILE* buffer involves more or less just a copy of memory from the buffer of your application to the OS kernel, and the kernel will take care of writing it to the actual file at its leisure asynchronously, which will cause the fclose() to return "right away".
There could circumstances where the OS first have to do some housekeeping before the data is copied into the OS/kernel buffers, e.g. it might have to flush out data to the physical file to make room for more data, allocate space in the file to ensure there is room and so on, making it not return instantly.
In short, it depends, and you cannot control it. Usually the "best" you can do is use platform dependent APIs that at least allow you to flush the OS buffers to the physical file, such as the posix fsync()/fdatasync() APIs.

A: Your understanding is (at least partially) wrong.
The I/O is buffered, but there are limits to the buffer sizes. When the buffers overflow, they will be flushed. Also, many streams are line-buffered; when you write a line feed, the buffer is flushed. If this were not the case, outputting to a terminal would be pretty impractical with all output appearing when the program terminates.
I don't think the calls are necessarily blocking otherwise, there are functions that try to make sure the underlying media is synced with the writes for instance. This commonly creates issues where you get "too low-level" and need to deal with the complexities of caches and buffers both the software but also in the hardware for e.g. hard drives.


text:
Q: Why this React conditional rendering has issue? Props data is fetched by the parent element.
results a delay to fetch them
I checked for empty or null props and the console log is OK :
import React from 'react'
import styles from '../articles.css'
const TeamNfo = props => {
    const team = props.teamData
    // console.log( team)

    return !team || team.length < 1
        ?
Loading ...

        : <>
            {console.log(team)}
            {/* {
                city: "New Jersey"
                count: 0
                description: "At vero eos et accusamus et ."
                id: 3
                logo: "nets.png"
                name: "Nets"
                poll: "false"
                stats: Array(1)
                    0: {wins: 23, defeats: 12}
            } */}

                <div className={ styles.left }
                    styles= {{
                        background: `url('images/teams/${ team.logo })`
                }}>

                         { props.team.city } { props.team.name }

        </>
}
export default TeamNfo

returns this error message on the screen:
TypeError: Cannot read property 'city' of undefined

Is it still loading the return with undefined props?

A: team is a local variable. Use team.city or props.teamData.city, e.g.:
 { team.city } { team.name }
// or
 { props.teamData.city } { props.teamData.name }


text:
Q: .id_rsa.swp file found in user ssh directory, is that normal? Im a bit of a noob when it comes to using linux OS.  On my local machine I have noticed a new file within the user .ssh directory as the following:-
.id_rsa.swp
is that normal ?
I definitely didn't make myself im sure of that.
Thanks
J

A: Its not normal but its probably benign. You should check the contents of that file and then delete it if its older or the same as your id_rsa file.
.filename.swp is a standard way that VI (and possibly other editors) modify and lock a file -  if you were looking at the id_rsa file in vi and did not properly exit this file would remain, and when you next tried to edit vi it would know/complain about someone else editing it. If the id_rsa file contains what you need it us safe to delete this file.


text:
Q: Connection error to localhost database c# Hi I'm trying to connect to a database using System.Data.SqlClient. I think I have everything correct, but for some reason Visual Studio gives out an error:
EDIT:
It turns out I was dumb and using System.Data.SqlClient when my database is MySql so I changed it to MySql.Data.MySqlClient and changed all the variables methods and everything. I also changed the port that It was using to 3306 cause it's the port I have set for mysql in xampp. Although I still get an error that says:
System.ArgumentException: "Connection option 'server' is duplicated."
Now to answer some more questions, I don't know what is the name of the instance but I never set any so Idk if there is one or not(Sorry I'm not very advanced). I didn't add a password to the connection string cause the only user I have is root without any password. I think I seen some people used something like TrusedConnection=true or something but I don't know if it's the right thing to do here. My MySql version is 15.1. Here is the updated code:
using System;
using MySql.Data.MySqlClient;

namespace ConsoleApp2
{
    class Program
    {
        private static void Main()
        {
            string conn = "Initial Catalog=world.sql;user=root;Server=127.0.0.1,3306";

            MySqlConnection myConnection = new MySqlConnection(conn);
            MySqlDataReader myReader = null;
            string sql = "SELECT * FROM coutry";

            MySqlCommand myCommand = new MySqlCommand(sql, myConnection);

                myConnection.Open();
                myReader = myCommand.ExecuteReader();

                while (myReader.Read())
                {
                    for (int i = 0; i < myReader.FieldCount; i++)
                    {
                        Console.WriteLine(myReader[i].ToString());
                    }

                }
                myConnection.Close();
        }
    }
}

A: Use a connection string format like this: Server=localhost;User=user_name;Database=db_name;Port=3306;Password=password;SSL Mode=None
and apart from that, never use the root account. Just create an account that has a password.
If you apply these things to your code, the error should disappear.

A: use This connection in C#
Data Source=yourIpAddress,yourPort;Initial Catalog=YourdatabaseName;User ID=sqlserverUsername;Password=sqlserverpassword;MultipleActiveResultSets=True;" providerName="System.Data.EntityClient";


text:
Q: Redirecting webpage to a file Suppose a webpage that presents a table, but with an option to download it as an Excel sheet. The option is presented as a button that submits a form (containing the required parameters to create the same report, but for Excel).
<form action="makereport.blah">
<!-- Some parameters -->
<input type="button" value="Export to Excel" onClick="submit();"/>
</form>

The final step remains to direct the browser to the created Excel sheet.
I see three possibilities:

*

*In the "action" page of the form, with the OnLoad event: rewrite in JavaScript the URL to the created file path and reload the page

*In the HTTP header: Redirect to the url of the file (with the Redirect command)

*Using an iframe, where src is the target file
Those seem a bit hackish, but I've used them in the past. How is this normally done?
(As a note, the language I'm using to generate the HTML (and Excel sheet) is an in-house solution. So if PHP has something for that, I would just have to port it).

A: Possibility 4 (the right one): the PHP script this form points to should send a Content-type: application/vnd.ms-excel header then the contents of the Excel file. If it's an actual file on disk, use readfile, otherwise just echo the Excel data straight out. If you want to specify a filename for download, you can also send a Content-Disposition: attachment; filename='filename' header.

A: The script/code that handles the posting of the form (server side) can generate the Excel spreadsheet. Then instead of replying with an HTML response (or some kind of redirect) you can instead return the spreadsheet directly (with the correct HTTP headers that would be sent if the file was loaded directly).
An example in PHP:
<?php

// generate spreadsheet in file
$file = do_something_to_generate_spreadsheet();

// specifies it is an excel spreadsheet response
header('Content-Type: application/vnd.ms-excel');
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename="' . $file . '"'); // filename
header('Content-Length: ' . filesize($file)); // length

readfile($file); // sends file to client

?>

A: Why have a second page at all?  Make makereport.blah the xls file itself instead of another HTML document.

A: you can use DATAURI scheme in new file to insert file in base64 mode. i'll make a script tonight.

A: Using base64 code from webtoolkit.info and disassembling an XML/XLS file i have tried make a script to force to download a file made in the air. I make a windows object and when this will open, then insert XML/XLS code codified with base64. this method is a hack of dataURI. I have not put a name when the file download.
I tried on google chrome.
here an jsfiddle of file.
Thanks for your interest.


text:
Q: Populate React prop object from async function My high level goal here is to be able to read data from text files onto a page I'm creating using React.
I have a utility script file that I'm using to read the file by path:
//reader.js
window.readFile = function(filePath, callback) {
  var request = new XMLHttpRequest();
  request.open("GET", filePath, true);
  request.send(null);
  request.onreadystatechange = function() {
    if (request.readyState === 4 && request.status === 200) {
      var type = request.getResponseHeader('Content-Type');
      if (type.indexOf("text") !== 1) {
        callback(null, request.responseText);
      }
    }
  }
}

I'm calling that function like so in one of my React component files:
//component.js
var data = {};

populateData();

function populateData() {
  data.subject = "FILE TITLE";
  data.title = "FILE SUBJECT";
  window.readFile("../path/to/file", function(error, results){
    if (!error) {
      data.content = results;
    }
    else {
      console.log(error);
    }
  });
}

var Content = React.createClass({
  render: function() {
    return (
      <FileContent { ...data } />
    );
  }
});

I've tested that the function gets ran correctly from this context, but it would appear that due to the async nature of the readFile function, my data object's content field never gets populated with the text from the file. Is there a synchronous way of returning what I need, or how can I solve this asynchronously?

A: Due to the asynchronous nature of the readFile function, you will have to solve this asynchronously. The easiest way to do this would be to add a method to your component that calls the function and then sets the state after it is completed. After it is completed, you can then pass the data to the child component.
For example:
var Content = React.createClass({
  getInitialState() {
    return {
      data: null
    }
  },

  componentDidMount() {
    this.populateData();
  },

  populateData() {
    const data = {};
    data.subject = "FILE TITLE";
    data.title = "FILE SUBJECT";
    window.readFile("../path/to/file", (error, results) => {
      if (!error) {
        data.content = results;
        this.setState({
          data
        });
      }
      else {
        console.log(error);
      }
    });
  },

  render: function() {
    const {data} = this.state;

    if (data === null) {
      // data has not been loaded yet
      // you can add a loading spinner here or some kind of loading component
      return null
    }

    return (
      <FileContent { ...data } />
    );
  }
});


text:
Q: Create function that parses a string into an array PHP I would like to create a php function that parses a string into an array(which I found not easy), the strings varies alot, I am not sure how to do it in a way that will work properly for any string below($text1,...,$textn):
    <?php

    $text1 ='balance_check!en:[ussd]Your balance is $balance $currency;ru:[ussd]Vash balans $balance $currency;';
    //function outputs: $text_array = array ('type'=>'ussd','en'=>'Your balance is', 'ru'=>'Vash balans');

    $text2 = 'voicemail!:[redirect]*44*2*$number';
    //function outputs: $text_array = array('type'=>'redirect');

    $text3='callerid!en:success=[ussd]$callerid is your Caller-ID/error=[ussd]Bad caller-ID number;';
    //function outputs: $text_array = array('type'=>'ussd','en'=>array('success'=>'is your Caller-ID', 'error'=>'Bad caller-ID number'));

    $text4 ='voucher_recharge!en:success=[sms]Your balance is $balance $currency. Voucher recharged successfully';
    //function outputs: $text_array = array('type'=>'sms','en'=>array('success'=>array('Your balance is','Voucher recharged successfully'),),);

//parse into an array
function multiexplode($text) {

        //parse $text into array

        // return  $text_array;
    }

    ?>

A: I'm not pretty sure but you can test it :
EDIT
function transform($string) {
  $string = preg_replace('/\$[a-zA-Z0-9]+/i', '', $string); // remove $words pattern
  $text = end(explode('!',$string,  2)); // get part of string targeted
  preg_match_all('#([a-z]{2})?\:?([a-z]+)?\=?\[([a-zA-Z]+)\]#iU', $text, $matches); // Find all parts needed to build array
  $output = array();
  $text = str_replace($matches[0], '#SPLITME#', $text);

  $sentences = explode( '#SPLITME#', $text);
  foreach ($sentences as $k => $v){
    if(empty($v) || $v == '') unset($sentences[$k]);
  }
  $sentences = array_values($sentences);
  $lang_memory = null;
  foreach ($matches[1] as $key => $lang){
    $output['type'] = $matches[3][0]; // get type
    if(!empty($lang) ){
      if(isset($matches[2][$key]) && !empty($matches[2][$key])){
        // success or error key found
        $output[$lang][$matches[2][$key]] = $sentences[$key];
        $lang_memory = $lang;
      }else{
        $output[$lang] = $sentences[$key]; // no success of error key found
      }
    }else if($lang_memory != null){
      if(isset($matches[2][$key]) && !empty($matches[2][$key])){
        $output[$lang_memory][$matches[2][$key]] = $sentences[$key];
      }
    }
  }

  return $output;
}


text:
Q: Date difference between UIDatepicker and NSDate I have a datepicker and I save the value to .plist file with key UserDate in string format.
The value returns from datepicker is in 2013-02-13 11:17:34 +0000 format.
In order to save it into to .plist file I need to convert datepicker to string 2013-02-14T19:17:34Z
In other View, I want to retrieve back the UserDate from plist and compare with the user current date. I want days and hours different.
I convert and pass 2012-02-12 19:17:34 +0800 as destinationDate to compare with [NSDate new].
I managed to calculate the difference between two date. But the result is not correct.
How to get the correct difference result for two dates between iPhone's date and Datepicker's date? Do I need to use a specific timezone?
Extra info: I live in GMT+8. I set the simulator datepicker to Feb 13 2012, yet the result still say the countdown has 18hours and 4 minutes.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int units = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *components = [calendar components:units fromDate:[NSDate date] toDate:destinationDate options:0];
[datelabel setText:[NSString stringWithFormat:@"%d%c %d%c %d%c %d%c %d%c", [components month], 'm', [components day],
                    'd', [components hour], 'h', [components minute], 'm', [components second], 's']];

NSLog

Edit
Plist file.

save method
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];

// set the variables to the values in the text fields
self.userTitle = myTitle.text;
self.userMessage = myMessage.text;

NSLog(@"METHOD SAVE");

NSLog(@"Datepicker value =  %@", myDate.date );

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSString *mdate = [dateFormatter stringFromDate:myDate.date];
//  [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];

NSLog(@"Converted from date picker, save into plist =  %@", mdate );

self.saveDate = mdate;
//self.userDate = myDate.date;

// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: userTitle, userMessage, saveDate, nil] forKeys:[NSArray arrayWithObjects: @"Title", @"Message", @"UserDate", nil]]; NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];

// check is plistData exists
if(plistData)
{
    // write plistData to our Data.plist file
    [plistData writeToFile:plistPath atomically:YES];

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Your settings have been saved." delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok",nil];
    [alert show];
}
else
{
    NSLog(@"Error in saveData: %@", error);
    //[error release];
}

viewWillAppear
- (void)viewWillAppear:(BOOL)animated {
[self.navigationController setNavigationBarHidden:YES];

[super viewWillAppear:animated];

// Data.plist code
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];

// check to see if Data.plist exists in documents
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
    // if not in documents, get property list from main bundle
    plistPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
}

// read property list into memory as an NSData object
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSString *errorDesc = nil;
NSPropertyListFormat format;
// convert static property liost into dictionary object
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp)
{
    NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
}

NSLog(@"Plist Title: %@", [temp objectForKey:@"Title"]);
NSLog(@"Plist Message: %@", [temp objectForKey:@"Message"]);
NSLog(@"Plist date: %@", [temp objectForKey:@"UserDate"]);

userTitle.text = [NSString localizedStringWithFormat:@"%@", [temp objectForKey:@"Title"]];
userMessage.text = [NSString localizedStringWithFormat:@"%@", [temp objectForKey:@"Message"]];

//http://stackoverflow.com/questions/1070354/how-do-i-get-the-current-date-in-cocoa

NSDate* now = [[NSDate alloc] initWithTimeIntervalSinceNow:3600];
userCoundown.text = [NSString stringWithFormat:@"%@",now];

NSString *uDate = [[NSString alloc] init];
uDate = [temp objectForKey:@"UserDate"];
NSLog(@"Plist date in string - %@", uDate);

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *ddate = [dateFormatter dateFromString:uDate];
[dateFormatter setDateFormat:@"yyyy-MM-dd H:mm:ss Z"];

NSLog(@"Format date from Plist -  %@", [dateFormatter stringFromDate:ddate]);

//NSLog(@"GMT format from Plist - %@", timeStamp);

//http://www.epochconverter.com/#
destinationDate = ddate;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];
}

updatelabel
-(void)updateLabel {

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int units = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *components = [calendar components:units fromDate:[NSDate date] toDate:destinationDate options:0];
[datelabel setText:[NSString stringWithFormat:@"%d%c %d%c %d%c %d%c %d%c", [components month], 'm', [components day],
                    'd', [components hour], 'h', [components minute], 'm', [components second], 's']];
}

A: NSDate keeps time in GMT. If you have time zones you will have to specify them.
The question is not clear so this is not a complete answer but should provide some help with NSDate in a plist.
Here is an example of creating, writing and reading a plist with a NSDate:
NSDictionary *plistDict = [NSDictionary dictionaryWithObjectsAndKeys:
                           userTitle,   @"Title",
                           userMessage, @"Message",
                           saveDate,    @"UserDate",
                           nil];

[plistDict writeToFile:filePath atomically:YES];

NSDictionary *plistDictRead = [NSDictionary dictionaryWithContentsOfFile:filePath];
NSDate *dateRead = [plistDictRead objectForKey:@"UserDate"];

There is no need to convert the NSDate to a string and no need to use NSPropertyListSerialization.

A: Remember to create the NSDate and then output it with a valid timezone and calendar!
Check a similar question I answered in another post:
UIDatePicker return wrong NSDate


text:
Q: How to download an Excel file I want to download an Excel sheet to my specific location not to Download folder.
I tried below code. Then the file is download to the "Download" folder. I need to download this file to a given file path.
string filepath = "D:\";
string strDownloadableFilename = "Test.xlsx"
Using (MemoryStream stream = ExportExcel()){
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", strDownloadableFilename));
  stream.WriteTo(Response.OutPutStream); ;
  Response.End();
}

The file is download to "Download" folder.

A: Well there are two things
first of all what you want to achieve can't be done by downoad option it means we can read file and write in system memory as per our desired location but in that case No download popup will see so you have to decide if you need download popup and no desired location or vice versa.


text:
Q: LAN adapter works every second time I turn my PC on I have a really strange problem and I am desperate for help now, since I could not find any solution on the internet.
Specifications first: I am using a desktop computer and a router. The router gives off wireless for the laptop in the house and my PC is connected directly via a cable coming from the router. My OS is Windows 7 32 bit.
Here is the problem : every time I turn my PC off for more than a few minutes, my internet connection stops.   To fix this, I need to turn the PC off again for like five minutes, then it is all right. So in a way, my computer takes turns of having and not having internet connection. Also, another thing is, I cannot do anything to the LAN adapter settings while this is happening - I can disable it, but when I try to enable it again, it just freezes and does not enable the adapter (also when I restart, I do not need to enable it again, even if it was disabled when I turned the PC off).
I cannot change any driver settings, it just freezes again. When I wait a couple of minutes and turn the PC off again, it is all back to normal and I can change options, enable/disable etc.
I really find no logic in this problem and I want to know if it is a Windows 7 problem before reinstalling or if it is my Network Card that needs replacement.
EDIT: I know it is not a router problem or ISP problem, since the laptop can connect to the internet at the time I cannot. I also switched up the cables and nothing changed, so I think the problem is not there too.

A: I suggest you to start your computer in safe mode, then uninstall the network driver. Further restart your computer in normal mode and install ethernet drivers.
In safe mode if you fail uninstalling your network driver, start the computer in safe mode with command prompt,
you may follow the link that might help you with it
http://social.technet.microsoft.com/wiki/contents/articles/181.how-to-manage-device-drivers-with-command-line.aspx

A: It could be power management settings kicking in at the wrong time.  I've seen this happen before.
Open up Device Manager and double-click your wireless network adapter's properties page.  Then go to the Power Management tab and uncheck "Allow the coputer to turn off this device to save power".  See if that helps.


text:
Q: How to choose SSD persistant disk on Google Container engine? Just checked, while creating the container cluster, we are not able to find option to set SSD persistant disk on Google cloud container engine. How do I set that. Note we are using paid plans on GCE

A: There isn't a way to choose the type of boot disk that is attached to each node, but you can mount SSD PDs into your containers using volumes.


text:
Q: Modelling DC/DC-Converter i want to model a cascaded Buck/Boost-Converter with FAST like mentioned here: https://cbasso.pagesperso-orange.fr/Downloads/PPTs/Chris%20Basso%20APEC%20seminar%202013.pdf.
The goal is to implement a controller, to verify constant Voltage at the Output:
\begin{align}
V_{out}=355V.
\end{align}
The Power will be:
\begin{align}
P = 3.6kW,
\end{align}
so the Resistance at the Output is:
\begin{align}
R_L = 35 \Omega.
\end{align}
The Topology looks like this:

My Question is how to model the the Converter in consideration to the Output-Voltage and the Resistance?
I would think I should model my known Values for the Output-Voltage like this:

or is it easier to model only the Converter Dynamics without these parameters?
edit: another Question is, if i can make an order reduction in case of the Voltage over C1 is equivalent to Uin?


text:
Q: Oracle regular expression I have below string of data,How to get number alone using oracle regular expression last two charcters is always either 'RC' or 'RN'.If number not found return
0.
1AEABCRC

1AEABC1RC

1AEABC1RN

1AEABC2RN

A: select
   nvl(regexp_substr(column_name, '(\d*)(RC|RN)$', 1, 1, null, 1), 0)
from table_name;

A: You can try something like this:
select nvl(regexp_replace(regexp_substr(v, '\d+(RC|RN)$'), '(\d+)(RC|RN)$', '\1'), 0)
from t;

Here is a sqlfiddle demo

A: This seems to work.  Dunno if you want the number as a number or are willing to work with as a char, but:
select nvl(substr(regexp_replace('1AEABCRC','^1[A-Z]+'),1,1),to_char(0,'9')) from dual;
select nvl(substr(regexp_replace('1AEABC1RC','^1[A-Z]+'),1,1),to_char(0,'9')) from dual;
select nvl(substr(regexp_replace('1AEABC1RN','^1[A-Z]+'),1,1),to_char(0,'9')) from dual;
select nvl(substr(regexp_replace('1AEABC2RC','^1[A-Z]+'),1,1),to_char(0,'9')) from dual;

Of course you can replace the string literal with a column name or variable or somesuch.  Won't work if the number goes to two digits, obviously.


text:
Q: How to retrieve uid data using FirebaseRecyclerOptions I can't retrieve data from firebase under uid. When I try to retrieve data without using uid it works perfect but when I try to retrieve data from uid it doesn't work, can anyone help me to find out data.
FirebaseRecyclerOptions<Model> options =
            new FirebaseRecyclerOptions.Builder<Model>()
                    .setQuery(FirebaseDatabase.getInstance().getReference().child("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()), Model.class)
                    .build();

    myAdopter = new MyAdopter(options);
    binding.adminRecycler.setAdapter(myAdopter);

A: Since you're reading a node at a lower level in the tree, the adapter will be populated with the child nodes of that root - typically the properties of the individual user. These children are not longer valid instances of the Model class.
If you want to show a list of a single user, you can use a query like this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid()
Query query = FirebaseDatabase.getInstance().getReference().child("Users").orderByKey().equalTo(uid);
FirebaseRecyclerOptions<Model> options =
            new FirebaseRecyclerOptions.Builder<Model>()
                    .setQuery(query, Model.class)
                    .build();

Now you have query that matches just one child node, and that node is a valid Model object.


text:
Q: Keep getting "member reference base type 'string [1000]' is not a structure or union" error and dont know how to fix it? This program reads an SSN from the user and checks if it matches an SSN in a text file provided. Tried switching the array to a vector and it didnt work. Tried putting the array in the structure function and using info:: but nothing seems to work. I know this is pretty basic but I cant get it, thanks.
#include <iostream>
#include <fstream>
using namespace std;

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

  struct info{
    string SSN;
    string firstName;
    string lastName;
  };

  string list[1000];
  string userSSN;
  char x;
  fstream input(argv[1]);
  int i = 0;
  while(!input.eof()){
    input >> list.x[i] >> list.SSN[i] >> list.firstName[i] >> list.lastName[i];
    i++;
  }
  input.close();

  cout << "Input a SSN:" << endl;
  cin >> userSSN >> endl;
  for(int k = 0; k < i; k++){
    if(userSSN.compare(list.SSN[k]) == 0){
      cout << "Found at location " << k << endl;
    }
  }
}

A: list is just an array of 1000 std::strings.  It looks like you need it to be of type info. Even that won't solve your problems as info has no member named x. After that, to access a member of info in an array would be like
list[i].SSN

not
list.SSN[i]

A: There are so many things wrong with this code that I don't know where to start. Let's see:

*

*Using using namespace std; is almost always a bad idea, and if you have an identifier list, then it's even worse because it conflicts with std::list.

*Using std::string without #include <string> is not guaranteed to work. It may work if you include some other standard header, but don't rely on it.

*Your variable x is unused.

*string list[1000]; should probably be info list[1000];.

*list.SSN[i] et al should probably be changed to list[i].SSN.

*list.x[i] does not make sense at all and can probably be removed. (Or you meant to read into the otherwise unused x to skip parts of the file.)

*You cannot read from std::cin into std::endl. Remove std::endl from that line.

*Using std::string's compare function is pretty strange here, just use ==.

A: The issues in your code were already pointed out in other's answers. I'll show you a "working" example:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using std::string;
using std::vector;
using std::cout;
using std::cin;

struct info {
    char x;       // You were reading that from the file so I added it
    string SSN;
    string firstName;
    string lastName;

    friend std::istream &operator>>( std::istream &is, info &i ) {
        // maybe you should check data input somehow...
        is >> i.x >> i.SSN >> i.firstName >> i.lastName;
        return is;
    }
};

int main(int argc, char* argv[]) {
    // check if a file name has been passed as a parameter
    string file_name;
    if ( argc < 2 ) {
        cout << "Please, enter the input file name:\n";
        cin >> file_name;
    }
    else
        file_name = argv[1];

    std::ifstream input(file_name);
    if ( !input ) {
        std::cerr << "Error. Unable to open file: " << file_name << '\n';
        exit(-1);
    }
    // Just use a vector to store all the structs
    vector<info> my_list;
    info temp_info;
    while( input >> temp_info ) {
        my_list.push_back(temp_info);
    }
    input.close();

    cout << "Input a SSN: ";
    string userSSN;
    cin >> userSSN;
    // That's not cheap. You may want to change the container or sort it
    for ( int k = 0; k < my_list.size(); k++ ) {
        if ( userSSN == my_list[k].SSN ) {
            cout << "Found at location " << k << '\n';
        }
    }

return 0;
}


text:
Q: query by date vs query by time I assume that application code should store time in database always as UTC ( punch me if I am wrong)
Now lets say I want to query everything between 23-mar-2013 to 24-mar-2013 . Should I create a time object and then query something like "23-mar-2013:00:00:00UTC" to "24-mar-2013:24:00:00UTC" or querying just by date is right "23-mar-2013" to "24-mar-2013".
Now the problem comes when I am not in UTC and in a time zone like -7:30  .
Now date queries would go wrong..
So does that mean I should query always with time ?
I am talking in concern to ElasticSearch, Tire, Ruby ( But I think that shouldn't matter)

A: The implementation absolutely does matter.  Querying against one database or another is very different depending on how that database stores date / time values.  I suggest you edit your question and make it specific for the technologies that you are using.  Show some code if you can.
In general though, you are mixing two concepts and you should probably try to separate them mentally.

*

*The moment something happened, an event time, can be measured by a DateTime combined value - represented as either UTC, or as a value that is offset from UTC where the offset is known.  This is often referred to as "Instantaneous Time", "Universal Time", or "Physical Time".

*The values that we give to dates and times when talking about them locally, such as "Today", "Yesterday", or "March 29, 2013".  Even when we have a time, we are talking about a fraction of a day on a calendar.  This is often referred to as "Calendar Time", "Local Time" or "Civil Time".
You can always query and do math with Instantaneous Time.  It's unambiguous.  However, the concept of "Today" is meaningless.  There is no observer to mark the end of one day and the start of the next.  (One could argue that the observer is in London, but that's not true during BST.)
Calendar Time is only suitable for querying or math when you have day-level precision and only one observer.  So it usually makes a poor representation of something meant to be universal, like an event.
Let's go back to your original question.  You said:

I want to query everything between 23-mar-2013 to 24-mar-2013

Right there - you have a problem.  What is the context?  Who's calendar dates are you talking about?  Even though you said March 23, you probably don't mean March 23rd at midnight UTC to March 24th at midnight UTC.  You probably mean some other calendar's midnights.
Keep in mind that not every day is 24 hours in length.  When time zones switch on and off of daylight savings time (or summer time), the days could be 23 hours or 25 hours in length.
So what to do?  First, you need a Time Zone database (like the IANA/Olson/TZ/TZDB/ZoneInfo database for example)  Here is one implemented in Ruby.
Now, you need to to know the local time zone of the user.  That is - the person that is asking the question that you are showing the query results to.  That will involve your own application logic, maybe a selector or picker.  If this is a web app, you might want to look at this map-based timezone picker, or at jsTimeZoneDetect.
You should always store events with instantaneous time.  Let's just say you store events as UTC (although you might use an offset, we'll ignore that for now).
So you need to know for the date range that the user wants, what UTC times do the start and end dates of your query map to?  For example, say we are in India using the Asia/Calcutta time zone.  We would convert 23-mar-2013 00:00 - 24-mar-2013 00:00, to the UTC equivalent 22-mar-2013 18:30 - 23-mar-2013 18:30.
Then you can use those UTC DateTime values to query the database.
When you return the results to your user, you will probably want to convert UTC back to local time so they understand the results they are looking at.
You should also read the many great suggestions in this post.