text:
Q: How do I make a default button in macOS SwfitUI? I've build the following modal dialog in SwiftUI:

But I can't figure out how to make the "Open" button be a default button (i.e. filled with blue in standard macOS HIG). The code for it looks like this:
struct
OpenLocationView : View
{
    @State private var location: String = ""

    var body: some View
    {
        VStack
        {
            HStack
            {
                Text("Location:")
                TextField("https://", text: $location) { self.openLocation() }
            }

            HStack
            {
                Spacer()
                Button("Cancel") { /* dismiss window */ }
                Button("Open") { self.openLocation() }
            }
        }
        .padding()
        .frame(minWidth: 500.0)
    }

    func
    openLocation()
    {
    }
}

I tried appending .buttonStyle(DefaultButtonStyle()), but that had no visible effect.

A: On macOS 11, it is possible to define a keyboard shortcut using the "keyboardShortcut" view modifier.
The standard keyboard shortcuts ".cancelAction" (ESC key) and ".defaultAction" (Enter key) also apply a special coloration to the associated button.
Button("Cancel") { ... } .keyboardShortcut(.cancelAction)
Button("Open") { ... } .keyboardShortcut(.defaultAction)

A: This is currently not possible in SwiftUI, see this question and workaround SwiftUI on Mac - How do I designate a button as being the primary?


text:
Q: Confusion about injective, surjective, bijective As an example, I'm looking at $\sqrt{-x}$ for real $x.$ It's defined on the interval $(-\infty,0]$ and its inverse is defined on the interval $[0,\infty).$
Over which interval is this function injective, surjective and bijective?
If the domain is $(-\infty,0]$ then over this interval, it is injective because every real number in $(\infty,0]$ is mapped to at most one element in $\mathbb{R}$?
I'm confused about where this function is surjective, and if it's bijective at all.
The domain of this function's inverse is $[0,\infty).$ Does that mean the function is invertible over $[0,\infty)$?

A: *

*You're correct that it's injective but your justification is hazy. It is injective because every real in $(-\infty,0]$, the domain, is mapped to a point in the codomain $[0,\infty)$ that is unique to the input (read: no two distinct elements of the domain are mapped to the same element in the codomain). You wrote: "It is mapped to at most one ..." but any function whatsoever will map elements in the domain to exactly one element in the codomain.

*The function has an inverse, so it is indeed invertible. It's not clear what: 'over' should mean. If you have a function $f:X\to X$ that is invertible, it makes sense to say it is invertible over $X$. But the codomain is not equal to the domain, be careful; it is invertible as a function between $(-\infty,0]$ and $[0,\infty)$.

The function surjects onto the given codomain, because if you give me $y\in[0,\infty)$ I can create $x:=-y^2$, such that $\sqrt{-x}=y$.

A: The function $y=\sqrt{-x}$ is defined, as you rightly say, on the domain $\{x\leq0\}$  and takes values in $\{x\geq0\}$ because square roots are always non-negative by convention.
Now note that you can define on $\{x\geq0\}$ the function $x=-y^2$ and observe that the two functions are inverse of each other. Indeed their domains/codomains are interchanged and
$$
-(\sqrt{-x})^2=-x\qquad \sqrt{-(-y^2)}=y.
$$
Thus both functions must be bijective (i.e. injective and surjective) since being invertible and being bijective are equivalent conditions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the justification for these two steps in proof of Baire's theorem? Below is the statement and proof of Baire theorem from the textbook I'm using. I have some difficulties understanding it and I would appreciate if someone can explain it in more details. In particular I can't understand:

*

*Why there exists a relatively compact neighbourhood $U_1 \subseteq U_0$ of point $x'$, such that $\overline{U_1} \subseteq U_0 - A_1$. From local compactness (in Hausdorff space) I understand that there exists a relatively compact neighbourhood $U_1 \subseteq U_0$ of point $x'$, such that $U_1 \subseteq U_0 - A_1$. But why is the closure $\overline{U_1}$ included in $U_0 - A_1$ as well?

*Why is $U_1$ not contained in $A_2$? In other words, how do we know that $U_1$ is an open set?

Theorem (Baire)
Let $A_1, A_2, \ldots$ be a countable family of closed subsets with empty interior in a locally compact Hausdorff space $X$. Then $\bigcup_{i=1}^{\infty} A_i$ also has empty interior in $X$.
Proof:
Let $U_0$ be any open set in $X$. We will show that $U_0$ is not contained in $\bigcup_{i=1}^{\infty} A_i$, in other words, that $U_0 - \bigcup_{i=1}^{\infty} A_i \neq \emptyset$. Because $A_1$ has empty interior, there exists a point $x' \in U_0 - A_1$. Because of local compactness, there exists a relatively compact neighbourhood $U_1 \subseteq U_0$ of point $x'$, such that $\overline{U_1} \subseteq U_0 - A_1$. Similarily, because $U_1$ is not contained in $A_2$, there exists a relatively compact neighbourhood $U_2$, such that $\overline{U_2} \subseteq U_1 - A_2$. If we keep doing the same thing, we get a series of compact sets $\overline{U_1} \supset \overline{U_2} \supset \overline{U_3} \supset \ldots$, such that $\overline{U_i} \cap A_i = \emptyset$, for all $i$. Finally, $\bigcap_i \overline{U_i}$ is nonempty and by construction included in $U_0 - \bigcup_{i = 1}^{\infty} A_i$.

A: A locally compact Hausdorff space is regular and so if $x \in O$ is a situation in such a space, where $O$ is open, we can find an open $O_1$ so that $$x \in O_1 \subseteq \overline{O_1} \subseteq O$$ by regularity.
After that we can find a relatively compact $U$ so that $x \in U \subseteq O_1$ (because relatively compact sets form a base). It then follows that $\overline{U} \subseteq \overline{O_1} \subseteq O$: i.e. the closure of the relatively compact sets sits inside the original open set (and we can forget about the "auxiliary" $O_1$ again).
So the first part about why $U$ exists for $x' \in U_0-A_1$: it's the previous argument (lemma?) applied to the open set $O=U_0-A_1$ (which is open as an "open minus closed" set) and $x=x'$. The resulting $U$ is then called $U_1$ and is the next step in the recursion.
Next, $A_2$ also has empty interior. As $U_1$ is non-empty (as witnessed by $x'$ from before) it cannot be a subset of $A_2$. So $U_1 - A_2$ is open (open - closed again) and non-empty and "the show can continue" (we can proceed with the recursion).
Hope this answers your doubts.


text:
Q: ORACLE (11.2.0.1.0) - Recursive CTE with a date expression The right answer on the following question:

*

*That is a bug that was fixed in 11.2.0.3 or later if I recall correctly. (11.2.0.1 is no longer supported anyway. 11.2.0.4 is the only 11.2 release that is still supported) – @a_horse_with_no_name

*The bug number is 11840579 and it was fixed in 11.2.0.3 and 12.1.0.1
– @a_horse_with_no_name

Question
I have a table
CREATE TABLE test(
  from_date date,
  to_date date
);

INSERT INTO test(from_date,to_date)
--VALUES('20171101','20171115');
VALUES(TO_DATE('20171101','YYYYMMDD'),TO_DATE('20171115','YYYYMMDD'));

The following query in Oracle return only one row (expected 15 rows)
WITH dateCTE(from_date,to_date,d,i) AS(
  SELECT from_date,to_date,from_date AS d,1 AS i
  FROM test

  UNION ALL

  SELECT from_date,to_date,d+INTERVAL '1' DAY,i+1
  FROM dateCTE
  WHERE d<to_date
)
SELECT d,i
FROM dateCTE

SQL Fiddle - http://sqlfiddle.com/#!4/36907/8
For test I changed the condition to i<10
WITH dateCTE(from_date,to_date,d,i) AS(
  SELECT from_date,to_date,from_date AS d,1 AS i
  FROM test

  UNION ALL

  SELECT from_date,to_date,d+INTERVAL '1' DAY,i+1
  FROM dateCTE
  --WHERE d<to_date
  WHERE i<10 -- exit condition
)
SELECT d,i
FROM dateCTE

And get the next result
| D          | I  |
|------------|----|
| 2017-11-01 |  1 |
| 2017-10-31 |  2 |
| 2017-10-30 |  3 |
| 2017-10-29 |  4 |
| 2017-10-28 |  5 |
| 2017-10-27 |  6 |
| 2017-10-26 |  7 |
| 2017-10-25 |  8 |
| 2017-10-24 |  9 |
| 2017-10-23 | 10 |

Why do this recursive query returned bad result in Oracle?
SQL Fiddle - http://sqlfiddle.com/#!4/36907/5
I ran a similar query in SQLServer and I get the right result
WITH dateCTE(from_date,to_date,d,i) AS(
  SELECT from_date,to_date,from_date AS d,1 AS i
  FROM test

  UNION ALL

  SELECT from_date,to_date,DATEADD(DAY,1,d),i+1
  FROM dateCTE
  WHERE d<to_date
)
SELECT d,i
FROM dateCTE

The right result
d           i
2017-11-01  1
2017-11-02  2
2017-11-03  3
2017-11-04  4
2017-11-05  5
2017-11-06  6
2017-11-07  7
2017-11-08  8
2017-11-09  9
2017-11-10  10
2017-11-11  11
2017-11-12  12
2017-11-13  13
2017-11-14  14
2017-11-15  15

Why it doesn't work in Oracle? What alternative variants can you suggest?  Thank you!
Screen shots from a real system:

A: If you want to have a sequential from-date to to-date, Use such this select:
SELECT  DATE '2017-11-01' + LEVEL - 1 AS D, LEVEL AS I
FROM DUAL
CONNECT BY LEVEL <= DATE '2017-11-15' - DATE '2017-11-01' + 1;

A: It's working for me in Oracle 11.2 Enterprise. Your SQL fiddle, however, plainly shows that it doesn't in every Oracle version.
I remember I had similar problems with dates in recursive queries. So there is a bug, that has been fixed in newer versions. It is very likely, your Oracle version has this bug.
A workaround: Get only the integer offsets from the recursive query and add them to the from_date afterwards:
WITH dateCTE(from_date, i, iend) AS
(
  SELECT from_date, 1 AS i, to_date - from_date as iend
  FROM test
  UNION ALL
  SELECT from_date, i + 1, iend
  FROM dateCTE
  WHERE i <= iend
)
, dates as (select i, from_date + i - 1 as d from dateCTE)
SELECT d, i
FROM dates;


text:
Q: Do multiple residents compete for resources (fruit, fossils)? I'm playing on someone else's 3DS where he is the Mayor and I am just a resident. We are both concerned that because we are both gathering fruit, digging up fossils, etc., that it'll lessen what the other person will have to collect. Does anyone know how often fruit, fossils spawn and whether that is increased if there are multiple players on the same cartridge?

A: Well, yes. Fruit respawns after every few days. Fossils pop up every day. If you shake trees and dig up some fossils, there will be less for the mayor to collect...


text:
Q: How to monitor the size of a XElement I am creating an XML document line by line and need to keep an eye on how large this file is becoming. The resulting file will need to be sent via MSMQ which has a message size restriction of 4Mb I think. What I need to do is when the document is getting close to this size, is to stop adding data and to add the document to a list and start creating a new one with the remaining data. I can then return this list of XML documents to the calling function where the documents can be sent via MSMQ. My question is, what would be a good way of continuously monitoring the size of a XElement ?

A: XNode have ToString method
XElement xmlTree = new XElement("Root",
    new XElement("Child1", 1)
);
Console.WriteLine(xmlTree);

You can found size of each element you add.


text:
Q: How did Earth Wind and Fire beat Aku? In episode XII Jack and the gangsters, we learn of the Jewel of Neptune, a powerful item that is guarded by three elemental monsters (that I shall call Earth Wind and Fire).  The reason Aku has not taken the Jewel of Neptune was that he was defeated by E, W, and F (or at least that he was unable to beat them).  How is this possible?  The only things that can harm Aku are Rama's arrows, Odin's Trident, Ra's energy beams and Jack's sword.

A: The best way to answer this in canon is to draw from what we see in Season 5. When Season 5 opens, we find that Jack is without his sword and Aku has a sort of... ennui about the whole thing. He's not even aware that Jack is swordless because he's gotten tired of the fight.
Let's apply that here. From the unofficial transcript (emphasis mine)

Long before you was born or I was born or anybody was born the Neptune Jewel was kept inside this mountain, see? Legend has it, it was placed there by an ancient spirit who gave the jewel special powers to control all the waters of the world, see? Naturally, Aku wanted the jewel's power so evil could control the world, which it should.
  But then, this no-good, goody two-shoes, good-for-nothing got in the way, see? I don't know how she did it, but she beat our boss.
  And she summoned the forces of nature to guard it: Earth.
  Wind.
  And Fire.
  And so Earth, Wind and Fire have guarded the jewel for centuries, see? Making it impossible for Aku to get his hands on it.
And since the big boss himself couldn't close the deal it's been centuries since anybody's even thought about it.

So we know that Aku was not beaten by the three forces, but by whomever created or summoned them. And likely she made it just difficult enough for Aku that he couldn't easily overcome it. As a result, Aku just gave up on it.
In other words, those three never beat Aku, nor were they impossible to defeat (Jack beats them pretty handily), they just made it not worth his time to keep trying. Which is generally what good security systems do.


text:
Q: In the following Swift code why does the program exit while loop when it reaches break? In the following Swift code why does the program exit while loop when it reaches break? Shouldn't it only exit the if and not the while loop.
var cokeLeft = 7
var fantasLeft = 4

while (cokeLeft > 0) {

    println("You have \(cokeLeft) Cokes left.")
    cokeLeft = cokeLeft - 1

    if(cokeLeft <= fantasLeft){
        break
    }
}
println("You stop drinking Cokes.")

A: Breaks generally exit out of the nearest loop. while is a loop. if is not considered to be a loop. Here is the corresponding documentation.
From the IOS Developer Library:

A break statement ends program execution of a loop or a switch
  statement.

Also, from the IOS Developer Library:

Loop statements allow a block of code to be executed repeatedly,
  depending on the conditions specified in the loop. Swift has four loop
  statements: a for statement, a for-in statement, a while statement,
  and a do-while statement.

So, here you can see that "if" is not listed among the loop statements.


text:
Q: Using Transactions or Locking in Entity Framework to ensure proper operation I am fairly new to EF and SQL in general, so I could use some help clarifying this point.
Let's say I have a table "wallet" (and EF code first object Wallet) that has an ID and a balance. I need to do an operation like this:
if(wallet.balance > 100){
    doOtherChecksThatTake10Seconds();
    wallet.balance -= 50;
    context.SaveChanges();
}

As you can see, it checks to see if a condition is valid, then if so it has to do a bunch of other operations first that take a long time (in this exaggerated example we say 10 seconds), then if that passes it subtracts $50 from the wallet and saves the new data.
The issue is, there are other things happening that can change the wallet balance at any time (this is a web application). If this happens:

*

*wallet.balance = 110;

*this operation passes its "if" check because wallet.balance > 110

*while it's doing the "doOtherChecksThatTake10Seconds()", a user transfers $40 out of their wallet

*now wallet.balance = 70

*"doOtherChecksThatTake10Seconds()" finishes, subtracts 50 from wallet.balance, and then saves the context with the new data.

In this case, the check of wallet.balance > 100 is no longer true, but the operation still happened because of the delay. I need to find a way of locking the table and not releasing it until the entire operation is finished, so nothing gets edited during. What is the most effective way to do this?
It should be noted that I have tried putting this operation within a TransactionScope(), I am not sure if that will have the intended effect or not but I did notice it started causing a lot of deadlocks with an entirely different database operation that is running.

A: Use  Optimistic concurrency http://msdn.microsoft.com/en-us/data/jj592904
//Object Property:
public byte[] RowVersion { get; set; }
//Object Configuration:
Property(p => p.RowVersion).IsRowVersion().IsConcurrencyToken();

This Allows dirty read. BUT when you go to update the record the system checks the rowversion hasn't changed in the mean time,  it fails if someone has changed the record in the meantime.
Rowversion is maintained by DB each time a record changes.
Out of the box EF optimistic locking.

A: you can use Transaction Scope.
Import the namespace
using System.Transactions;

and use it like below:
public string InsertBrand()
        {
            try
            {

                using (TransactionScope transaction = new TransactionScope())
                {

                   //Do your operations here
                    transaction.Complete();
                    return "Mobile Brand Added";

                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

A: Another approach could be to use one or many internal queues and consume this queue(s) by one thread only (producer-consumer-pattern). I use this approach in a booking system and it works quite well and is very easy.
In my case I have multiple queues (one for each 'product') that are created and deleted dynamically and multiple consumers, where only one consumer can be assigned to one queue. This allows also to handle higher concurrency. In a high-concurrency scenario with houndredthousands of user you could also use separate servers and queues like msmq to handle this.
There might be a problem with this approach in a ticket system where a lot of users want to have a ticket for a concert or in a shopping system, when a new "Harry Potter" is released but I dont have this scenarios.


text:
Q: Better approach to saving Webpage content to database for caching i want to know which approach is better to saving Webpage content to database for caching?

*

*Using ntext data-type and save content as flat string

*Using ntext, but compress content and then save

*Using varbinary(MAX) to save content (how i can convert flat string to binary? ;-))

*An other approach which you are suggest to me

UPDATE
in more depth i have many table (URLs, Caches, ParsedContents, Words, Hits and etc) which for each url in URLs table i'm sending request and save response into caches table. this is Downloader (URLResolver of Google) section of my engine. then indexer section act was to perform parsing and etc tasks which associated with this. and Compress/Decompress performs only when new content goes to be caching or parsing

A: The better approach would be to use the built-in caching features in ASP.NET. Searching StackOverflow for [asp.net] [caching] is a good start, and after (or before) that, similar searches on both www.asp.net and Google will get you quite far.

In response to your comment, I would probably save the data as a flat string. It might not be the best option performance-wise when it comes to storage, but if you're going to perform searches on the text content, you don't want to have to compress/decompress or convert to/from binary every time, since there is probably no (easy) way to do this inside SQL Server. Just make sure you have all intexes and full-text features you need set up correctly.


text:
Q: Returning a value under if statement for Python 2.7 I am trying to calculate factorial of a number. If the user enters a negative number, I want the loop to rerun. However, when I use the return function under if statement for negative values, it gives me an error of
"SyntaxError: 'return' outside function"

How can I rerun the loop if the user enters a negative number.
# Calculating the Factorial of a Number

number = input ("Please enter a positive number: ")
factorial = 1

if number > 0:
    for n in range (1, number):
        factorial = factorial * (n+1)
        print ("You entered the number of " + str(number) + ". The factorial of that number is " + str (factorial))
else:
    number = input ("You entered a negative number. Please enter a positive number: ")
    return number

A: You do have a return statement outside of a function.

How can I rerun the loop if the user enters a negative number?

Use a while loop:
number = -1
while number < 0:
    try:
        # since factorial applies to integers only
        number = int(input("Please enter a positive number: "))
    except ValueError: # so we don't crash if the user enters a string or a float
        pass
# here number is guaranteed to be a positive integer
factorial = 1
for n in range (1, number):
    factorial = factorial * (n+1)
print 'The factorial of {number} is {factorial}'.format(number=number,
                                                        factorial=factorial)


text:
Q: I am using rocket chat websocket. In those messages when we get the message of "user added" or "removed" I want the user's full name wss://[ABC.DOMAIN.COM]/websocket
I am using websocket of rocket chat.
This is one of the message from the list of messages response the websocket provides.
{
  "_id": "some id",
  "t": "au",
  "rid": "some id",
  "ts": {
    "$date": 1663823165892
  },
  "msg": "7d4e5ab4-34ca-11ed-b29a-7cc2c61d171e",
  "u": {
    "_id": "some id",
    "username": "svc_site_prod",
    "name": "svc_site_prod"
  },
  "groupable": false,
  "_updatedAt": {
    "$date": 1663823165902
  }
}

It uses t = "au" for added user and "ru" for removed user.
The real user added is present in "msg".
But it only shows the username of user who is added or removed.
I want the full name of this user.
I know I can just make another request to find the user's info by api. But what I want is to get the details in this response.
Edit: the headers of request
{
  "msg": "method",
  "method": "loadHistory",
  "id": "1",
  "params": [
    "AyzhtTJiE6YG3cnfA",
    null,
    50,
    null
  ]
}


text:
Q: How to use ion-loading in http get request and response? I'm create Ionic 4 angular app, and i'm use http get and response back.
now i want to ion-loading when request and response.below i'm paste this solution link which is available in ionic 3 but i want in ionic 4 ?
Ionic 3 show loading symbol on http request

A: import Loading Controller
import { LoadingController } from '@ionic/angular';

in the constructor create an object
constructor(
    private loadingController: LoadingController
) {}

Try as follows.
async presentLoading() {
    const loading = await this.loadingController.create({
      message: 'Please wait...',
      translucent: true,
    });
    return await loading.present();
  }

homeData() {
    this.presentLoading();
    this.dataService.getData().subscribe(response => {
        console.log(response);
        this.loadingController.dismiss();
    });
}

See official docs ion-loading

A: Why don't you use spinner dialog instead.


text:
Q: Trouble Accessing Ruby Params on RhoMobile I'm new to Ruby so please excuse my ignorance. I really didn't know how to word this question so this may also be part of the reason I haven't found an answer online.
I'm working with Rho Elements, and I'm trying to pass something from one page to another. I've made some good headway but run into something that I do not understand. I can pass through an ID like so
<input type="hidden" name="id" value="<%= @orderdetails.object %>"/>

I then grab the ID(only doing this right now to make sure I do get the ID)
@id = @params['id']

then redirect to another page
redirect url_for(:action => :newpage, :id => @id).

This is where my problems start. When I debug the application I get past the redirect and enter :newpage
def newpage
    @orderdetails = OrderDetails.find(@params['id'])
    if @orderdetails
      render :action => :newpage, :back => url_for(:action => :index)
    else
      redirect :action => :index
    end
end

Once here I check
@params['id]

and this is what is displayed.
@params {"id"=>"{131113212443313.17}"}
"id"    ""

@params {"id"=>"{131113212443313.17}"} is shown by eclipse and when I break into the variable "id"  "" is shown.
Why can I see the ID that I want to use to grab the orderdetails that was just created but also have the actual variable be empty?
**EDIT: This is the information I'm trying to pass.
@params {"id"=>"131113212443313.17", "next"=>"asleftnext", "orderdetails"=>
{"AsFoundMeterRead"=>"", "AsFoundImage"=>""}}
"id"    "131113212443313.17"
"next"  "asleftnext"
"orderdetails"  {"AsFoundMeterRead"=>"","AsFoundImage"=>""}

A: Use params in the controller, not @params. Also the canonical form of accessing keys is params[:id].

A: Like its say in the previous answer you access the params in the controller in this way
@id = params[:id]

Also if you are using Rails 3 or higher you may want to use the new url way is less verbose so its more easy to read.
newpage_controllername_url(:id => @id)

you can also ask for the path with this method.
If you don't know if you are passing right the params you can display the content using
params.inspect

You can view the content of any object with inspect


text:
Q: How to start java process if it die from script I have bash script to start java process using below command:
#!/bin/bash
java -jar test.jar

I want to make a script so that if the java process of this jar die it will start again from this script. Do i need a do while loop in my script and what condition should i use to check that is java process of this jar is running or not and if die then fire it up again.

A: Use the bash until in a loop until the bash success return code 0 is seen.
#!/bin/bash
until java -jar test.jar
do
   echo "Retrying Command.."
done

A: The following will run until test.jar exits with 0 as exit code
while ! java -jar test.jar; do :; done

Breakdown:
while ! java -jar test.jar; do :; done
#     ^ ^                      ^
#     | |                      while loops needs a body, and `:` will do nothing
#     | The command to run, while will check the exit code and continue if its 0 (true)
#     Flip the exit code, so true becomes false and false becomes true

If you are interested to run until test.jar exits will falsy exit code, you can omit the !:
while java -jar test.jar; do :; done


text:
Q: Using oauth2 by server in behalf of client I am trying to build an application which requires to access user's google apis on their behalf once they give consent.
What I am trying to build?
An azure database is scheduled to put some data on user specified spreadsheets on their google drive.
What is the problem?
I am unable to figure out how to upload data to user specified spreadsheets when the user is offline.
What workflow do I want?

*

*User logs in with Google Account

*User gives consent to web app to access spreadsheets api (just once)

*Thereafter my server should update the sheets as per the schedule without the user's interferance

*User can later check back to see the updated data on their sheets.

I want to know how should I implement to get this mechanism?

A: Request offline access of the user get a refresh token. Store the refresh token and when ever you need to access the users account later use the refresh token to request a new access token.
I recommend looking for a google client library in your chosen language most of them handle this functionality internally.


text:
Q: How to open STDIN in Sublime Text with syntax formatting? I'm getting some JSON from curl and I want to open it using Sublime Text.
I've tried
curl ... | subl --command "Set Syntax: JSON" -

Data is opened, but syntax is not applied. Is my command syntax wrong?

A: Yes. The command subl expects is not the human readable text from the Command Palette, but the actual underlying command and arguments.
To see what these are, you could open the ST console (View menu -> Show Console) and type sublime.log_commands(True) Enter, then switch input focus back to the main file and set the syntax from the command palette. In the console, you'd see the command that was invoked.
Then, you'd end up trying something like (replacing echo[...] with your curl command):
echo '{ "test": 123 }' | subl --command 'set_file_type { "syntax": "Packages/JSON/JSON.sublime-syntax" }' -

...and it still wouldn't work. And you'd notice something odd if you had a non-JSON file focused previously. That file would now be highlighted as if it were JSON.
Why? Because it applies the command before it finishes opening the file (or in this case, opens a tab for the STDIN stream).
Can it be worked around? Yes, generally a separate invocation of subl to execute the command gives Sublime Text enough time to switch the focus to the newly created tab:
echo '{ "test": 123 }' | subl - && subl --command 'set_file_type { "syntax": "Packages/JSON/JSON.sublime-syntax" }'


text:
Q: Kong use Nginx Map module I want to inject a map into my kong deployment on my kubernetes cluster, but it isn´t working.
We are Using Kong Chart version 2.3
To inject configs into the nginx.conf http {} block you need to make an env value in the Kong deployment, for example

*

*env:

*

*name: KONG_NGINX_HTTP_MAP
value:  "$time_local:$msec" $time_local_ms { ~(^\S+)(\s+\S+):\d+.(\d+)$ $1.$3$2 }

In this example i get the error unexpected "}"
If i delete it i always get
[emerg] invalid number of the map parameters in /kong_prefix/nginx-kong.conf:48
-env:

*

*name: KONG_NGINX_HTTP_MAP
value:  "$time_local:$msec" $time_local_ms { ~(^\S+)(\s+\S+):\d+.(\d+)$ $1.$3$2

I tried a hell lot of formating but still didn´t manage to get this or an easy map example running


text:
Q: how to get latest date records of each user in yii Im working workers report display for the last date.
I want to get records of last date reports of single user and need to display total time they spend to complete single project for last date in yii.
My table structure is:
id  worker  project  total_time   date
---------------------------------------------
 1   6        2      1370932128   20-12-2017
 2   9        3      1370931664   20-12-2017
 3   12       5      1370933037   20-12-2017
 4   12       6      1370932128   19-12-2017

Currently my work_report table model query is
$criteria=new CDbCriteria;
$criteria->alias = 'a';
$criteria->select = 'a.*, worker.*, project.*, SUM(a.total_time) as groupbysum, max(a.date) as MaxDate';
$criteria->with = array('worker','project');

$criteria->condition = 'a.date=worker.MaxDate';

$criteria->group = 'a.project, a.worker';
$criteria->order = 'worker.worker_name ASC';

$new_criteria = clone $criteria;
$new_criteria->select = "SUM(a.total_time) as sum";
$new_criteria->group = '';
$new_result = WorkReport::model()->find($new_criteria);

Its not working. it showing me sql error and i dont have an idea to fix this issue.

Column not found: 1054 Unknown column 'worker.MaxDate' in 'where clause'.

A: You can't use alias and aggregation result  in  where condition   but you can use having  for filter result based on aggregated  result ..  eg:
$criteria->having= 'a.date=worker.MaxDate';


text:
Q: php echo quotation marks error I'm having hard time with quotation marks. I have this line of code;
echo "NEXT";

with 3 variables, $bName,$bid, and $next_id[id].
There is something wrong with the quotations I've used. I also tried this;
echo "";

but it's still not working.
Can anyone explain how quoting works in this case please?

A: You don't need to put single quotes around every PHP variable. It should make sense in HTML instead, for example;
echo "NEXT";

You need curly braces ({}) around object and array variables, but it is also useful for normal variables. Also, the array index should be in quotes as it is a string (not required for integer indexes).
Additionally, I changed the ampersand (&) to & as & signifies the start of a special character code (just like &), so although in this case it wouldn't be a problem it is best practice to put the HTML char code in, even in a URL.


text:
Q: Is an HTML list (ul or ol) allowed to be empty for Accessibility? Is an HTML list allowed to have no child list items? Specifically, is this allowed:

The HTML validator on the W3C site does not complain when you test it with an empty list, e.g.
<!DOCTYPE html>

  <title>Test with empty list</title>

So semantically, it's not illegal from a pure HTML perspective. However, the WAI-ARIA Recommendation section on Required Owned Elements suggests that lists must have at least one listitem:

For example, an element with the role list will own at least one
element with the role group or listitem.

However, the WCAG 2 test rule for this very check suggests that the rule is inapplicable, because it does not have explicit role:
**Inapplicable Example 2**

This ul element does not have an explicit semantic role.

Item 1

One automated accessibility testing tool (SiteImprove) is throwing an error for an empty  element, whereas other tools (Lighthouse, WAVE) are not.
I'm trying to get a definite answer on whether an empty list is legal or not.

A: The discrepancy between the different accessibility testing tools' report on your empty
 list is probably down to a different interpretation of whether the
 must own a required element. Based on the WCAG 2 rule for ARIA required owned elements that you referenced, this appears to hinge on the definition of whether the role of an element is implicit or explicit.
When you use the ARIA role attribute, you are assigning an explicit role to an element, such as role="list". The WAI-ARIA recommendations on required owned elements that you referenced state that the owning element contains at least one element with the associated role="listitem" or role="group". If not, then it must have the aria-busy="true" attribute if the owned items will be loaded later. (Note that an element being "owned by" another element in the accessibility tree is different from an element "owning" another element in the DOM tree - see here.)
In your example, a
 element without the ARIA role attribute would have an implicit role of list, but because the list is empty, the implicit role could be ignored by a screen reader and treated as role="presentation". When I tested your code in Firefox, the accessibility tree showed the
 as having a semantic list role, but JAWS and NVDA ignored it. Similarly, when I tried it in Chrome with JAWS and NVDA, both reported that no lists were found on the page.
Technically, there shouldn't be any difference between whether an element's role is implicit or explicit. Explicit roles are designed to help better define the accessibility tree where the DOM layout is not representative of the page information. But this is probably why you're getting different results with different accessibility testing tools.
It's worth pointing out that the WCAG 2 test rule is only a proposed rule and still needs to be approved by the Accessibiligy Guidelines Working Group (AGWG). Based on your comments, the SiteImprove tool is correct in saying that an empty
 list would need the aria-busy="true" attribute assigned to it until the list is populated.


text:
Q: Show a particular column data in form of buttons or links I have a query. I want to show a particular column data from a table in form of links. Suppose 5 rows and there in that column, I want to show 5 buttons or links.
Now I know how to bind in gridview or dropdown. But I'm totally unsure about this.
Any ideas will greatly help me.

A: Hi basically you have two options that you can implement in many ways.

*

*Set the data in the view model in your case create a property that display a collection of items based on the right column

*In the view (ex: wpf) create a data template that display the row according the column


text:
Q: How to get data out of FileReader I need a little help with FileReader API. Is there any way how to get data from FileReader outside it. I have a "class" with method, where image is read with FileReader and I want to put image data to the class local variable (as shown in following code).
I do know that FileReader works asynchronously and my solution is wrong. Is there any way how to make it work? Thank you.
CanvasState.prototype.addImage = function(inputFile) {
    var file = inputFile;
    var reader = new FileReader();
    reader.onload = this.loadImageData;
    reader.readAsDataURL(file);
}

CanvasState.prototype.loadImageData = function(e) {
    this.hasImage = true;
    this.imageData = e.target.result;
}

A: Try this:
CanvasState.prototype.addImage = function(inputFile) {
    var file = inputFile, self = this;
    var reader = new FileReader();
    reader.onload = function(e) {
           self.hasImage = true;
            self.imageData = e.target.result;
       };

    reader.readAsDataURL(file);
}

A: This is an issue with the way this is set in a function. When you do:
    foo.bar();

this inside bar() will be foo. But if you do:
    var bar = foo.bar;
    bar();

this will be the global object.
In your case, the problem is that when you set reader.onload, you are setting it to the function pulled out of the CanvasState prototype. When the reader loads and then calls that function, it is like the example above where the this will be the global object, and not  the same it was inside addImage.
To fix this, you can use the bind() method to create a new function will call loadImageData with the this you expect.
Basically, change:
...
reader.onload = this.loadImageData;
...

to:
...
reader.onload = this.loadImageData.bind(this);
...

Check out JavaScript Function bind for more info and interactive examples.


text:
Q: how to debug a corrupted video file with ffmpeg? for example I downloaded some film, it is somehow encoded with some program, when I try to use ffmpeg to convert it, let's say from mkv to mp4, i get an error that:
[matroska,webm @ 0x1d06640] Read error at pos. 2241497 (0x2233d9)

now how can I know where is the reason that this happens? should just avoid this kind of files, or somehow debug it and see what is the reason behind this error? or maybe skip this error frames, but i dont know how many frames may be like this, what if most of the file is filled with corrupted frames, altough it is playable in the video player


text:
Q: Jquery ui datepicker: disable click on days leaving active change of month I have a Jquery UI Datepicker directly printed in my page (not popup, but directly in the DOM).
I would like to disable click on some (or all) days leaving active only buttons to change month and year displaied. So user can change month viewing other calendars but can't select a specific day.
Is is possibile?

A: You can find the solution here.
var unavailableDates = ["16-7-2013","17-7-2013","18-7-2013"];

function unavailable(date) {
  dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
  if ($.inArray(dmy, unavailableDates) < 0) {
    return [true,"","Book Now"];
  } else {
    return [false,"","Booked Out"];
  }
}

$('.datePicker').datepicker({ beforeShowDay: unavailable });

this is the jsFiddle.

A: You have to know that the click event is bound to the td tags inside the picker's DOM. Considering that, you'll probably have to alter the data-handler or the data-event fields of the cells representing the days, or directly unbind the click event from the table cells. I suggest you take a look into this page of the documentation http://api.jqueryui.com/datepicker/ where they hold an inline picker like the one you suggest you have. Try executing some jquery scripts until you find the one that fits your needs better.


text:
Q: Mod $p$-representation ($p$-torsion points ) of elliptic curve (over number fields) with CM can be irreducible? Let $E/K$ be an elliptic curve with complex multiplication and let $E[p]$ be the group of $p$-torsion points of $E$ where $K$ is a number field and $p$ is a prime number.
My question is: as a $(\mathbb{Z}/p\mathbb{Z})[G_K]$-representation, does there exist a case such that $E[p]$ is irreducible? ($G_K$ denotes the absolute Galois group of $K$.)
remark:

*

*When $E/K$ has no CM, Serre's theorem implies $E[p]$ is irreducible for almost all $p$.

*When $E/K$ has CM over $K$, $E[p]$ can never be absolutely irreducible, at least for the case that $End_K(E)\cong$ full ring of integers of an imaginary quadratic field.

A: Certainly. It will (typically) be irreducible for primes where the curve has supersingular reduction. Indeed, for such primes, the p-torsion as a module over the endomorphism ring $O$ is isomorphic to $O/p \simeq \mathbf{F}_{p^2}$, and the image will (for all but finitely many such primes) will be all of $\mathbf{F}^*_{p^2}$ thought of as a subgroup of $\mathrm{GL}_2(\mathbf{F}_{p})$ via the isomorphism of groups $\mathbf{F}_{p^2} \simeq (\mathbf{F}_{p})^2$ (The image will be the so-called "non-split Cartan). This is certainly always irreducible - for example, reducible subgroups have order dividing the order $p(p-1)^2$ of the Borel.
An alternative way to think about it: reducibility for almost all $p$ implies the existence of $p$ isogenies for almost all $p$. Since the isogeny class of an elliptic curve is finite, this implies that for any infinite set of primes $S$ where p-isogenies exist there will be an endomoprhism of degree $pq$ with distinct primes $p$ and $q$ in $S$. (By pigeonhole principle the two isogenies are both from E to the same E' then take one followed by the dual isogeny of the other.)  But their only exist endomorphisms of E of orders which are norms in $O$ which forces $p$ and $q$ to split in the quadratic field.


text:
Q: how to find unique values with matlab in cell array How do I find unique cells in excel using matlab? i was trying to get all unique strings in some excel field,
so baisicly im trying to do somthing like this:
[~,~,mainraw] = xlsread(mainfilename,1);
unique_expense_types = unique(mainraw(:,2));

it should have goten all the cells into cell array type and then return full strings that are unique, though i receive this output:
ans =

'  "'()-./01245689BEGILMORWY'

please help fixing it


text:
Q: Error while uploading file to PHP and displaying it using fpdf I'm trying to get an image via form and display it in pdf using fpdf, I'm getting an error:

Undefined index: foo in C:\xampp\htdocs\PhpProject1\login.php on line 16

Here is my php code:
$target_dir = "PhpProject1/";

$tf = $target_dir.  basename($_FILES["foo"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($tf,PATHINFO_EXTENSION);
$pdf->Image( "$imageFileType", 50, 108, 110 );

here is my html code:
<input type="file" class="form-control-file" id="foo" aria-describedby="fileHelp" name="foo">


text:
Q: Why azimuth result is wrong for this pyqgis code? In this code I want to obtain azimuth from a single point to each pixel center, but when run it, in raster created azimuth result for each pixel is wrong, what is correct code?
from osgeo import gdal, osr
import numpy as np
import numpy

pntLayer = QgsVectorLayer("E:/Sample_Dataset_Lorestan/Point.shp", "Point", "ogr")
feat = pntLayer.getFeatures().next()
pntxy = feat.geometry().asPoint()

g_NoData_value = -9999

# Open tif file
ds = QgsRasterLayer("E:/Sample_Dataset_Lorestan/subset_a1.tif","subset_a1")
global g_pixelWidth, g_pixelHeight
g_pixelWidth = ds.rasterUnitsPerPixelX()
g_pixelHeight = ds.rasterUnitsPerPixelY()

# extent of the layer
ext = ds.extent()
global g_originX ,g_originY
g_originX ,g_originY = (ext.xMinimum(),ext.yMinimum())
cols = ds.width()
rows = ds.height()

# Get Center pixel x y
def pixel2coord(x, y):

  xp = (g_pixelWidth * x) + g_originX + (g_pixelWidth/2)
  yp = (g_pixelHeight * y) + g_originY + (g_pixelHeight /2)
  return(xp, yp)

# Open tif file
ds = gdal.Open("E:/Sample_Dataset_Lorestan/subset_a1.tif")

band1 = ds.GetRasterBand(1)

driver = ds.GetDriver()
outDs = driver.Create("C:/Temp_NoiseOnePoint/Azimuth_lyr.tif", cols, rows, 1, gdal.GDT_Float32)

outBand = outDs.GetRasterBand(1)
outData = numpy.zeros((rows,cols), numpy.float32)

for i in range(0, rows):
  for j in range(0, cols):
    rspnt = pixel2coord(i, j)
    az = pntxy.azimuth(QgsPoint(rspnt[0], rspnt[1]))
    if az < 0.0:
        azim = 360 + az
    else:
        azim = az

    outData[i,j] = azim

# write the data
outBand.WriteArray(outData, 0, 0)

# flush data to disk, set the NoData value and calculate stats

outBand.SetNoDataValue(g_NoData_value)

# georeference the image and set the projection
outDs.SetGeoTransform(ds.GetGeoTransform())
outDs.SetProjection(ds.GetProjection())
outBand.FlushCache()

#outBand = None
outDs = None

This picture shows point in green and azimuth raster result in grayscale, min value in white color is 0.5622 and max value in black color in 359.251,It seems that north side is incorrect!


text:
Q: Linux Mailx is creating a dead.letter and not sending email I am having issues with sending emails from my Redhat6 linux server. Each type of mailing command sendmail/mailx creates a dead.letter in the users home directory.
Examples of how I am sending things:
mailx -s "backup complete - cron bla" test@example.com

echo "Subject: hello" | sendmail test@example.com

(In a bash script)
page /usr/log/example.log | mailx -s "example - cron example" test@example.com

Dead Letter Message:
Date: Wed, 9 Jan 2019 07:20:32 -0500 From: bob Message-Id:
  <201901091220.x09CKWMG009291@myserver> Subject: hello

A: The file dead.letter is created when the mta fails when it tries to send a mail. Check all the configurations related with the mail server (credentials, mail server...) and also that you can reach the mail server, otherwise you will have that problem.


text:
Q: NodeJS, babel build -> regeneratorRuntime is not defined This morning i got an error with my NodeJS and babel configuration and i have already find the solution but i would like to understand why it happen ?
After building my app with "babel ./src -d ./lib" and then running it with "node lib/index.js" i got this error:

ReferenceError: regeneratorRuntime is not defined

I have found where is the probleme, this is about how i declared a new function:
async function loopIntercom (conversationId, splited) {
  // code..
}

After changing the declaration for this new one:
const loopIntercom = async (conversationId, splited) => {
  // code..
}

Everything working fine, but why is there a problem with the first method ?


text:
Q: Positioning content within a container I want to make a console overlaid on a background image but cannot get positioning to work.  There is a container div with two overlapping child divs, one for a semi-transparent shade and one for text.
What is the proper CSS to fit the children inside the container's content box?
EDIT: the desired result is for the yellow word "content" to be placed inside the content area highlighted in blue in the image, and for the content area to be resized within the browser window with 50px margins (150px on top).  If you run the code, you won't see a blue box - that desired content location is illustrated by hovering over the content box (labeled 384 x 384) in Chrome's debugging window.
The desired result is:

*

*the word "content" appears inside the content area of the container (shown in blue in the image),

*if provided, more content text appears inside the blue content area with none outside that area,

*the content area does not change size regardless of what text is inside it,

*the content area does change size when the viewport is resized, so that it is always 100 px horizontally and 200 px vertically smaller than the viewport,

*The browser window has a gray background.  The area shown in blue in the image should have a transparent reddish background and opaque yellow-green text.  There is no blue in the desired output, the blue just illustrates where the red should be located if the CSS were working properly.  The desired output is a gray page with a red tinted box and opaque yellow text.

Fiddle at: https://jsfiddle.net/dave2/381rnsy5/

body {
  background-color: gray;
}

#container {
  position: absolute;
  padding: 50px;
  padding-top: 150px;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
}

#bg {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background-color: red;
  opacity: 0.25;
  border: 1px solid blue;
  box-sizing: border-box;
}

#text {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  padding: 20px;
  overflow-y: hidden;
  color: greenyellow;
  border: 1px dashed;
  box-sizing: border-box;
}

    background

    content

A: Is this what you're going for?
https://jsfiddle.net/qjLbdtmv/2/
HTML
<!DOCTYPE html>

            background

            content

CSS
body {
  background-color: gray;
}

#container {
  width: 100%;
  height: 100vh;
  position: relative;
  box-sizing: border-box;
}

#bg,
#text {
  position: absolute;
  top: 150px;
  right: 50px;
  bottom: 50px;
  left: 50px;
}

#bg {
  background-color: red;
  opacity: 0.25;
  border: 1px solid blue;
  box-sizing: border-box;
}

#text {
  padding: 20px;
  overflow-y: hidden;
  color: greenyellow;
  border: 1px dashed;
  box-sizing: border-box;
}

The child divs can only be positioned based on their parent, but you need a position set on the parent for that to happen.


text:
Q: Git committing to a new remote? I checked out a branch based off another remote branch by setting it as tracking branch.
git checkout -b bar origin/foo

Now I want bar to go into origin/bar, which is different than foo. I agree I should have
git checkout foo
git pull --all
git checkout -b bar

in the first place. How do I solve that problem?

A: git push -u origin bar:foo

Means "push the bar branch to the origin remote (with the name foo on the remote end) and set up bar to push and pull from origin/foo in the future".


text:
Q: Odd exception thrown in .NET Exception Thrown: "System.ComponentModel.ReflectPropertyDescriptor is not marked as Serializable"
Does this mean I missed marking something as serializable myself, or is this something beyond my control?

A: Can you give more context as to when this happens, and with which serializer? Most serializers have the ability to ignore certain members - NonSerializedAttribute for BinaryFormatter, XmlIgnoreAttribute for XmlSerializer, etc.
Having a PropertyDescriptor instance in your class usually means that your class is acting as a property-bag; in which case you may need to do custom serialization (ISerializable/IXmlSerializable). If the field is there for some other reason, just mark it to be ignored.
This (or similar symptoms) are also very common when you have an event (such as a change notification event / INotifyPropertyChanged) that the UI is hooked into (data binding); in this case, you need to mark the backing field as non-serialized. I don't know about VB, but with C# you can do this with "field-like events" as so:
[field: NonSerialized]
public event EventHandler BarChanged;

A: Do you have a field of this type in your class.  If so, you will have to implement ISerializable yourself -- the automatic implementation requires that all of your fields are marked as Serializable.

A: It is in your control.  Most likely the problem is the same as this:
http://www.codeplex.com/SharedCache/Thread/View.aspx?ThreadId=19759


text:
Q: Passing argument with one single quote in it to a .PS1 script I'm testing a PS script that will be put into win10 right-click context menu, the script simply accepts path info then echo it to my terminal window.
The registry key is as follows:
Computer\HKEY_CLASSES_ROOT\*\shell\MyScript\command
@="powershell.exe -window hidden -command .'\"G:\\path to my script\\MyScript.ps1\"' '%V'"
The script is just $args.
For most regular paths, it just running fine. Now I'm stuck to a situation where the file name contains one single quote, like this one: "D:\John's file.txt".
It throws an error:
The string is missing the terminator: '.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
What should I do to solve this issue?

A: I've found the solution myself.

*

*According to this post  The registry entry has to be modified to: Computer\HKEY_CLASSES_ROOT\*\shell\MyScript\command
@="powershell.exe -window hidden -file \"G:\\path to my script\\MyScript.ps1\" "%V""
Instead of -command, using -file, and the single quotes around %V should be double quotes.
2.To get the full path, you have to join strings separated by space using -join operator like this (if the path contains spaces):
$path = $args -join " "
Powershell v6 user could use the join-string cmdlet instead.


text:
Q: new Task from Task.Continuewith (to run on separate thread) Thanks for your time and assistance in advance.
I am using TPL from WPF application to download files from a remote server.
I have a 'transfer manager' method that runs on the UI thread, from which I create background Tasks to download files individually. I attach continuation tasks on the background tasks to update UI.
Problem is: for first file, the download tasks is starting on a new thread as expected. But for all subsequent downloads, it is using the same thread as UI locking up the application.
I have done my homework, read relevant material on this and hence I am unable to understand this behaviour, determine what I am doing wrong and how to fix it. Any help, tips, pointers, explanation is appreciated.
Thanks.
I am attaching sample code and output window text from debug mode.
private void btnNew_Click(object sender, RoutedEventArgs e)
{
// do some work and prepare transfer state object(my custom object)
...
..
  iTaskFactory = new TaskFactory
          (TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent,
           TaskContinuationOptions.None);

// call transfer manager
this.ManageTransfer(null, iDownloadState);
}

private void ManageTransfer(Task antecedent, TransferState ts)
{
  if(antecedent == null)
  // this is the first invocation of the task from GetNew / Upload methods
  {
    ts.IsActive = true;
    // some code....
  }
  else if(antecedent.IsFaulted)       // check exception on previous task executed
  // if there is a fault, then retry the page again
  {

    // do some error logging....
    //retry transferring the same page again
    pageToTranfer = ts.PagesTransferred + 1;
  }
  else
  // if the page was successfully transferred
  {
    //increment transfer count
    ts.PagesTransferred += 1;

    // update UI.... (as running on UI Thread)

    // if all pages are transferred, then exit method. No further tasks to queue
    if(ts.PagesTransferred == ts.Pages)
    {
      return;
    }

    pageToTranfer = ts.PagesTransferred + 1;
  }

  Task transferTask;     // should run in background thread
                         // **Problem is that afer first execution**,
                         // **this also runs on UI Thread!!**
  Task continuationTask; // should run in UI thread

    localFile = "someName.txt";  //..... work out next file to transfer
    serverFile = "someName.txt"; //..... work out next file to transfer

  time = DateTime.Now.ToString("hh:mm:ss.ffff"); //.ToShortTimeString();
  Debug.WriteLine(time + "starting download :" + pageToTranfer.ToString()
                  + " This is Thread: "
                  + Thread.CurrentThread.ManagedThreadId.ToString());

  transferTask = iTaskFactory.StartNew(() => Download(serverFile, localFile));

  continuationTask = transferTask.ContinueWith((t1Task) => ManageTransfer(t1Task, ts)
                     , TaskScheduler.FromCurrentSynchronizationContext());

}

public bool Download(string aCloudPath, string aLocalPath)
{

  time = DateTime.Now.ToString("hh:mm:ss.ffff"); //.ToShortTimeString();
  Debug.WriteLine(time + " in background for downloading "
                 + aCloudPath + " using thread:"
                 + Thread.CurrentThread.ManagedThreadId.ToString());

  // code to transfer file... no access to UI or any shared variable

  return true;
}

Output Window:

10:37:53.2629 starting download :1 This is Thread: 8
10:37:55.2720 in background for downloading file-01.txt using thread:15
10:37:56.4120 starting download :2 This is Thread: 8
10:38:00.4143 in background for downloading file-02.txt using thread:8
10:38:01.2413 starting download :3 This is Thread: 8
10:38:05.2445 in background for downloading file-03.txt using thread:8
10:38:05.8606 starting download :4 This is Thread: 8
10:38:09.8618 in background for downloading file-04.txt using thread:8

As you can see, first time the download function ran in background as expected. But after that it keeps on running in UI Thread!!
I am expecting ManagerTranfer to run in the same thread and a different Thread to be used for Download function.
I have tried this with simple Tasks (i.e. without TaskFactory) as well, but the behaviour is same. I have set TaskCreationOptions.LongRunning, so TPL should start a new thread regardless!!!

A: The scheduler that you are using is that which runs the tasks in currentSync context, that will in turn run your tasks on the UI thread alongside other tasks that are scheduled on the same scheduler. In order to run your tasks on the seperate thread, you should use another scheduler which implements the taskscheduler class and makes thread accordingly.
A scheduler similar is used in this post, but then again you will have to do a certain level of customization to your scheduler as well, as I can see you are using currentthread as well, which might be not that easy when implementing your own scheduler. On the other hand you can always use some helpful ParallelTaskExtensions and QueuedtaskScheduler provides some useful implementations that can be used in this regard.


text:
Q: Analytic tools in the theory of Galton-Watson processes The questions basically aims at discussing the relative power of using probability generating functions, moment generating functions and characteristic functions as an example for Galton-Watson-processes (GWP).
Within the theory of GWP I see people extensively use the probability generating function $\mathbb E[s^X], x\in [0,1]$ for a random variable $X$.
So far, I have thought that the characteristic function $\mathbb E[e^{itX}]$ is the most powerful tool out of three mentioned above, because it yields all information about the distribution and has nice analytic properties, in particular always exists.
Is there a good reason why the probability generating function is used for GWP?

A: All three are strictly equivalent, of course, hence each is exactly as powerful as the two others, in particular the generating function is always analytic on $[0,1)$. Some natural properties of branching processes are best expressed using generating functions though, for example the probability of extinction $q$ solves $q=f(q)$ where $f(s)=E[s^X]$ for every $s$ in $[0,1]$ and $X$ denotes the number of descendants of each individual.


text:
Q: loop through variable names with for each I have a database of 600 individuals (ind) sampled 12 times during their follow-up.
The acronym of the bacteria (COLI, KPN)was entered each time the sample was positive.
For each sample, there might be 3 bacteria present in the same sample (sample1_1, sample1_2, sample1_3...sample12_1, sample12_2, sample12_3)
I want to sum the number of a specifis bacteria for each individual
for example for coli and kpn (nb_coli, nb_kpn), I tried something:
Database with expected outcome
for (i in 1:12) {
  for (j in 1:3) {
    data_1 <-
      data %>%
      mutate(coli[i] = ifelse(sample[i]_[j] == "COLI", 1, 0))
  } %>%
    mutate(kpn[i] = ifelse(sample[i]_[j] == "KPN", 1, 0))
}

for (i in 1:12) {
  data_clean <- data1 %>%
                    mutate(nb_coli = sum(coli[i]) %>%
                    nb_kpn = sum(kpn[i])

thank you very much!!!!

A: Its good practice to have a data frame with the raw data and another one with the counts. Furthermore, long data helps a lot:
library(tidyverse)
data <-
  tribble(
  ~individual, ~ sample_1_1, ~sample1_2, ~sample12_1, ~sample_12_2,
  "ind1", "COLI", "KPN", "COLI", NA,
  "ind2", "COLI", "KPN", "KPN", NA,
)
data
#> # A tibble: 2 x 5
#>   individual sample_1_1 sample1_2 sample12_1 sample_12_2
#>   <chr>      <chr>      <chr>     <chr>      <lgl>
#> 1 ind1       COLI       KPN       COLI       NA
#> 2 ind2       COLI       KPN       KPN        NA

data %>%
  pivot_longer(starts_with("sample"), names_to = "sample_name", values_to = "sample_value") %>%
  count(individual, sample_value) %>%
  pivot_wider(names_from = sample_value, values_from = n)
#> # A tibble: 2 x 4
#>   individual  COLI   KPN  `NA`
#>   <chr>      <int> <int> <int>
#> 1 ind1           2     1     1
#> 2 ind2           1     2     1

Created on 2021-09-28 by the reprex package (v2.0.1)


text:
Q: Technical Meaning Of "Outside Of" On the web, these sentences could be found:

1a. He made transactions outside of Amazon Payments.
  2a. He made sales outside of Ebay.
  3a. He made wire transfers outside of Bank Of America.

Dictionaries say that "outside of" means "with the exception of". But when I substitute this sense of "outside of" into sentences 1c, 2c, & 3c, I get:

1b. He made transactions with the exception of Amazon Payments.
  2b. He made sales with the exception of Ebay.
  3b. He made wire transfers with the exception of Bank Of America.

, which is awkward. It seems that "outside of" as used in 1a, 2a, 3a means "not through" or "using methods other than". This distorted usage seems popular with banking and other online sales field. Could it be technical jargon?

A: First off, the preposition "outside of" is more common in AE than in BE; you usually use "outside" in BE.
Second, I am at a loss to understand as to what is confusing the OP. The use of this preposition in the sentence is quite clear and self-explanatory. I am sure if he  looks at the following meanings of the preposion, its use in the sentences presented will come across:
Outside (of) = not inside of something, with the exception of, with the exclusion of, not including, excluding, except for, other than.
In light of these senses, the use of the "outside of" completely fits well in the sentences.

A: I explained to the OP in his other question about "outside of" that it is a faintly metaphorical reference to the protection offered by the intermediary to both parties in a financial transaction. Outside of is a spatial expression for being beyond the intermediary's purview and protection. It is not a "technical" term.
If the parties remain within Amazon Payments, they are availing themselves of the system that the payment intermediary has established for the protection of the parties (and for its own enrichment as intermediary).
I think OP does not believe me and is trying to float the question again. So please vote me down if you think the explanation I'm offering is inaccurate, and set OP's mind at rest.
To be "outside of" Amazon Payments means to circumvent the system they have put in place to protect the parties in a financial transaction (for which protection they charge a fee).
We use such spatial terms with figurative meanings a lot in English.

A: I think in this case, "outside of" could be considered a compressed version of "outside of a set [of options] consisting of."
Example:

Set A: {Dog, Cat, Hamster, Bird}
Option 1: Cat
Option 2: Fish

You would say that Option 1 is "in" or "inside of" Set A, while Option 2 is "outside of" Set A.
Now to apply this to one of your examples:

Set "Amazon Payments": {Amazon Payments}
Option 1: Amazon Payments
Option 2: PayPal

This is a set consisting of only one option, Amazon Payments. By selecting Option 2 (PayPal) to make transactions, you would be selecting an option "outside of" Amazon Payments.
I doubt that anyone is visualizing this kind of logic problem as they use the phrase, but the pattern fits. In more literal circumstances, you might say "you can choose any item outside of that display case," or "please pick up all of the marbles outside of the bag." In those cases, there is an actual container for something to be outside of.
I made a simple Venn diagram to show the concept visually. It's oversimplified (the "Sales Made on eBay" side should be much larger than the "Sales Made by Person A" side), but it might help.


text:
Q: boost::interprocess::named_mutex vs CreateMutex I want to switch from CreatMutex to boost::interprocess::named_mutex to limit my application to a single instance. Both methods works when the application runs and ends just fine. However, the lock is not released when the application crashes and using boost::interprocess::named_mutex. I could resolve that issue by using two name_mutex but I don't really understand the issue.
Why is the lock for boost::interprocess::named_mutex not released when the application crashes but it is release with CreatMutex? What's the difference?

boost::interprocess::named_mutex mutex(boost::interprocess::open_or_create, "my_mutex");
boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(mutex, boost::interprocess::try_to_lock);
if(!lock) {
    return 1; //exit
}
//application may crash here.
boost::interprocess::named_mutex::remove("my_mutex");
return 1; //exit

A: Caveat: I've not spent much time with boost::interprocess, so this information is just from a quick inspection of the source. That said, I've used the Windows synchronisation API's a lot, so here goes...

The main difference between the two methods of interprocess synchronisation is how the object exists within the system.
With boost::interprocess::named_mutex, as well as a system-specific mutex, it looks like a synchronisation object is created as a file on the system.  The location of the file is based on Registry entries (see note 1) (at least in Boost 1.54.0)... it's most likely located under the Common Application Data folder (see note 2).  When the aplication crashes, this file is, in your case, not removed.  I'm not sure if this is by design... however in the case of an application crash, it's perhaps best not to mess with the file system, just in case.
Conversely, when you use CreateMutex, an object is created at the kernel mode, which for named mutexes can be accessed by several applications.  You get a handle to the Mutex by specifying the name when you create it, and you lose the handle when you call CloseHandle on it.  The mutex object is destroyed when there are no more handles referencing it.
The important part of this is in the documentation:

The system closes the handle automatically when the process terminates. The mutex object is destroyed when its last handle has been closed.

This basically means that Windows will clean up after your application.
Note that if you don't perform a ReleaseMutex, and your application owns the mutex when it dies, then it's possible/likely that a waiting thread or process would see that the mutex had been abandoned (WaitForSingleObject returns WAIT_ABANDONED), and would gain ownership.
I apologise for not providing a solution, but I hope it answers your question about why the two systems act differently.

*

*Just as an aside, using registry entries to get this information is horrible - it would be safer, and more future-proof, to use SHGetKnownFolderPath. But I digress.

*Depending on your OS version, this could be %ALLUSERSPROFILE%\Application Data\boost.interprocess or ProgramData\boost.interprocess, or somewhere else entirely.

A: What you want is not trivial and the interprocess_mutex definitively the wrong way to do.
What you may could do is remove the mutex on termination, by providing a remover destructor and/or in a catch(...). But this is not guaranteed to work, since it won't be done if you terminate the process directly (from the OS). Also it could accidently remove the mutex while your application starts twice.
One approach is to safe the process-id (for example in a shared memory) on the first time your program starts and remove it when it stops. Everytime you start the application read and check if the id still in process, if not, start the program.


text:
Q: Splitting feature when intersecting with feature of another layer using PyQGIS I have a buffer layer (green polygon) which I want to split to two polygons whenever it crosses a barrier (blue line). I have been trying to use "splitGeometry" method, but I just can't get it to work.
My code so far is this :
while ldbuffprovider.nextFeature(feat):
  while barprovider.nextFeature(feat2):
    if feat.geometry().intersects(feat2.geometry()):
        intersection = feat.geometry().intersection(feat2.geometry())
        result, newGeometries, topoTestPoints=feat.geometry().splitGeometry(intersection.asPolyline(),True)

Which returns 1 for result( error) and an empty list for newGeometries.

A: You can use the reshapeGeometry function of the QgsGeometry object for this, which cuts a polygon along its intersection with a line.
The following will intersect the buffer polygons with the lines, and add the split polygon features to a memory layer (QGIS 2.0 syntax):
# Get the dataProvider objects for the layers called 'line' and 'buffer'
linepr = QgsMapLayerRegistry.instance().mapLayersByName('line')[0].dataProvider()
bufferpr = QgsMapLayerRegistry.instance().mapLayersByName('buffer')[0].dataProvider()

# Create a memory layer to store the result
resultl = QgsVectorLayer("Polygon", "result", "memory")
resultpr = resultl.dataProvider()
QgsMapLayerRegistry.instance().addMapLayer(resultl)

for feature in bufferpr.getFeatures():
  # Save the original geometry
  geometry = QgsGeometry.fromPolygon(feature.geometry().asPolygon())
  for line in linepr.getFeatures():
    # Intersect the polygon with the line. If they intersect, the feature will contain one half of the split
    t = feature.geometry().reshapeGeometry(line.geometry().asPolyline())
    if (t==0):
      # Create a new feature to hold the other half of the split
      diff = QgsFeature()
      # Calculate the difference between the original geometry and the first half of the split
      diff.setGeometry( geometry.difference(feature.geometry()))
      # Add the two halves of the split to the memory layer
      resultpr.addFeatures([feature])
      resultpr.addFeatures([diff])

A: A good approximation with GDAL >= 1.10.0 compiled with SQLite and SpatiaLite consists into wrapping your layers (e.g. poligon.shp and line.shp) in an OGR VRT file (e.g. layers.vrt):
<OGRVRTDataSource>
    <OGRVRTlayer name="buffer_line">
        <SrcDataSource>line.shp</SrcDataSource>
        <SrcSQL dialect="sqlite">SELECT ST_Buffer(geometry,0.000001) from line</SrcSQL>
    </OGRVRTlayer>
    <OGRVRTlayer name="polygon">
        <SrcDataSource>polygon.shp</SrcDataSource>
    </OGRVRTlayer>
</OGRVRTDataSource>

in order to have a very tiny buffer (e.g. 1 micron) around line.shp obtaining the *buffer_line* layer.
Then, we can apply symmetric difference and difference on these geometries using SpatiaLite:
ogr2ogr splitted_polygons.shp layers.vrt -dialect sqlite -sql "SELECT ST_Difference(ST_SymDifference(g1.geometry,g2.geometry),g2.geometry) FROM polygon AS g1, buffer_line AS g2" -explodecollections

Obviously, all this stuff is perfectly executable from a Python script:
os.system("some_command with args")

Hope this helps!

A: The answer of Jake have topological problems with the splitted polygons. I made a solution, hope this can help: https://gist.github.com/RamonLopezEscudero/844c1401f5339143da1b2b5cf7ff27bd

A: You Can use Intersect tool in the Geoprocessing tab in Arcmap.


text:
Q: Custom uitableview cell issue I have a custom UITableViewCell as such:
@implementation CellWithThreeSubtitles

@synthesize title, subTitle1, subTitle2, subTitle3;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.textLabel.backgroundColor = self.backgroundColor;
        self.textLabel.opaque = NO;
        self.textLabel.textColor = [UIColor blackColor];
        self.textLabel.highlightedTextColor = [UIColor whiteColor];
        self.textLabel.font = [UIFont boldSystemFontOfSize:22.0];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    CGRect contentRect = self.contentView.bounds;

    CGRect frame = CGRectMake(35.0, 0, contentRect.size.width, 50.0);
    self.textLabel.frame = frame;

    UILabel *subLabel1 = [[UILabel alloc] init];
    frame = CGRectMake(35.0, 34.0, contentRect.size.width, 25.0);
    subLabel1.font = [UIFont systemFontOfSize:18.0];
    subLabel1.backgroundColor = [UIColor clearColor];
    subLabel1.text = subTitle1;
    subLabel1.opaque = NO;
    subLabel1.frame = frame;
    [self.contentView addSubview:subLabel1];

    UILabel *subLabel2 = [[UILabel alloc] init];
    frame = CGRectMake(35.0, 54.0, contentRect.size.width, 25.0);
    subLabel2.font = [UIFont boldSystemFontOfSize:18.0];
    subLabel2.backgroundColor = [UIColor clearColor];
    subLabel2.text = subTitle2;
    subLabel2.opaque = NO;
    subLabel2.frame = frame;
    [self.contentView addSubview:subLabel2];

    UILabel *subLabel3 = [[UILabel alloc] init];
    frame = CGRectMake(contentRect.size.width-100.0, 54.0, contentRect.size.width, 25.0);
    subLabel3.font = [UIFont systemFontOfSize:18.0];
    subLabel3.backgroundColor = [UIColor clearColor];
    subLabel3.text = subTitle3;
    subLabel3.opaque = NO;
    subLabel3.frame = frame;
    [self.contentView addSubview:subLabel3];

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)dealloc {
    [super dealloc];
    [subTitle4 release];
    [subTitle3 release];
    [subTitle2 release];
    [subTitle1 release];
    [title release];

}

When I implement it in my UITableView like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    int section = [indexPath indexAtPosition:0];
    static NSString *kCustomCellID = @"AppointmentCellID";

    CellWithThreeSubtitles *cell = (CellWithThreeSubtitles *)[tableView dequeueReusableCellWithIdentifier:kCustomCellID];
    if (cell == nil) {
        cell = (CellWithThreeSubtitles *)[[[CellWithThreeSubtitles alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
    }

    switch (section) {
        case 0:
            if ([wineArray count]==0) {
                cell.textLabel.text = @"No wine favorites selected yet";
            }else{
                cell.subTitle1 = [[wineArray objectAtIndex:indexPath.row] objectForKey:@"Varietal"];
                cell.subTitle2 = [NSString stringWithFormat:@"Bin No. %@", [[wineArray objectAtIndex:indexPath.row] objectForKey:@"Bin"]];
                cell.subTitle3 = [NSString stringWithFormat:@"$%@", [[wineArray objectAtIndex:indexPath.row] objectForKey:@"Price"]];
                cell.textLabel.text = [NSString stringWithFormat:@"%@ (%@)", [[wineArray objectAtIndex:indexPath.row] objectForKey:@"Name"], [[wineArray objectAtIndex:indexPath.row] objectForKey:@"Availability"]];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.userInteractionEnabled = NO;

            break;
        case 1:
            if ([dinnerArray count]==0)
                cell.textLabel.text = @"No dinner favorites selected yet";
            else
                cell.textLabel.text = [NSString stringWithFormat:@"%@", [[dinnerArray objectAtIndex:indexPath.row] objectForKey:@"Name"]];

            break;
    }
    return cell;
}

the contents of the cell duplicates on top of itself every time the orientation of the device changes. Is it redrawing the cell every time the device rotates? And if so, How can I keep it from doing so?

A: You should be creating the subviews and adding them to your cell's subviews array in your -initWithStyle:reuseIdentifier: method. You only need to create the subviews once. The -layoutSubviews method is invoked repeatedly by the framework whenever the device orientation changes, to allow you to resize and/or move the subviews (plus make any other minor adjustments) to compensate for differences between the orientations.

A: I suspect layoutSubViews is being called on rotation, and re-drawing new labels on top of your old ones.  If you remove any labels from the table cell at the beginning of layoutSubViews that would probably fix that issue, or you could create them in the init and then just position them in layoutSubViews.


text:
Q: Single index with multiple INCLUDE columns or multiple indices each with single INCLUDE After doing some 'missing index' analysis via the DMV tables (and thanks to this guide), I discovered that I have a few index candidates on a single table.
The output query some something like this:
Total Cost  Table Name  equality_columns  inequality_columns  included_columns
1615619     [TableA]    [ColumnA]         NULL                [ColumnB]
1494475     [TableA]    [ColumnA]         NULL                [ColumnC]

(the *_columns columns are coming directly from sys.dm_db_missing_index_groups)
In this case, would it be OK to create a single index on ColumnA including both ColumnB and ColumnC, or would it be better two have separate indexes on ColumnA, one that includes ColumnB and one that includes ColumnC?
(Using SQLServer 2008 RC2)

A: I think it is better to have one index:  (ColumnA INCLUDE (ColumnB, ColumnC)).
Having two indexes with the same sorting keys in the same order is redundant.  The additional included columns in the index can be used, regardless of the order in which they appear.  Having a second index to include them just adds overhead because of the need to maintain two indexes.

A:
would it be OK to create a single index on ColumnA including both ColumnB and >ColumnC

I would go with this option

would it be better two have separate indexes on ColumnA, one that includes ColumnB and one that includes ColumnC?

creating index with this option is just wastage of space and unnecessary overhead as these columns are in included list  and not in key column list


text:
Q: Which orm you would recommend for a beginner moving from ado.net? Which orm you would recommend for a beginner moving from ado.net?... Thus far used ado.net stored procedures with asp.net and now like to move with an orm.. Any suggestion..

A: NHibernate is nice, but it does require a bit more configuration for the ORM (even though fluent NHhibernate is quite nice).
I have heard that beginners in .NET ORM's have had quite good success with Subsonic: http://www.subsonicproject.com/.

A: NHibernate. The new development branch - much better support for LINQ than the current released versions.

A: At the risk of sounding odd - why not http://msdn.microsoft.com/en-us/library/bb425822.aspx??
Yes, I know - Microsoft has officially said there wouldn't be much more development on it - even though it was bugfixed and enhanced in .NET 4. It's still in .NET 4 - so it'll be around for at least 3-5 years. It's easy to use - much easier than NHibernate - with a visual designer and code generation.
It's simple and easy to understand, and it can give you a great intro to using an ORM.
Once you've learned, internalized, and understood the principles, you can always move on to a more enterprise-ready solution, like NHibernate, or Entity Framework v4.
See Scott Guthrie's excellent blog post series on Using Linq-to-SQL for a great intro, or check out the Nerddinner tutorial which showcases ASP.NET MVC and Linq-to-SQL.

A: NHibernate is currently one of the most popular ORM's, but Microsoft has been busy working on Entity framework. In time this may become the most popular and the best simply because it comes with .Net Framework.

A: I'd second the LINQ2SQL option if you're using SQL Server.
LINQ2SQL:

*

*is easy to learn, with lots of guidance available online;

*has good tooling for design and debugging in Visual Studio; and

*provides adequate performance for all but the most extreme of situations (StackOverflow uses it for data access, for example).

There have been rumours of its demise for a while, but Microsoft's market research seems to show more developer support than for Entity Framework which, whilst arguably more powerful, is also more complex.  LINQ skills are transferable to other ORMs too, with options for LINQ2Entities (for Entity Framework) and, I believe, support from SubSonic also.

A: Entity Framework
Definitely try that out.  Solid support from Microsoft themselves, support for Many-to-Many relationships, eSQL lets you at the lower layers, etc.


text:
Q: Picture memory game This is a memory game by letters. I want to make this  game by pictures, but I can't generate images and write them in the array.

A: You can add style tag as shown in below example,
output += "

";


text:
Q: nodejs net.createServer save scope I have an application listening on port using net.createServer and socket.io on other port.
net.createServer has many clients connected. After receiving command from browser via socket.io I need to coordinate work of two net.createServer clients. So I send command over first socket to first client and I need to proceed further only when it replays. But how do I save my current scope? Any way to keep "this"?
UPDATE1:
Here is a basic example

A: The solution to save "this" scope is to use bind(this) on a function definition
function(arg){...}.bind(this);


text:
Q: Счёт чисел Есть три текстовых поля и одна кнопка.
<INPUT type="text" name="1" value="10">
<INPUT type="text" name="2" value="20">
<INPUT type="text" name="answer" value="">
<INPUT type="button" name="button" onclick="">

У двух из них присвоены значения 10 и 20. Как сделать, чтобы при нажатии на кнопку 'button' складывались значения текстовых полей 1 и 2, и чтобы результат был в третьем текстовом поле 'answer'? Т.е. в данном случае, после нажатия на кнопку, в текстовом поле 'answer' должно быть число 30. Мне желательно, чтобы это было на Javascript.
A: http://jsfiddle.net/41593nc3/
Учебное задание же!
document.addEventListener('DOMContentLoaded',function(){
    var btn=document.getElementsByName('button')[0];
    btn.onclick = function(){
        document.getElementsByName('answer')[0].value = parseInt(document.getElementsByName('1')[0].value) + parseInt(document.getElementsByName('2')[0].value);
    }
});


text:
Q: Is this ADC capable of better performance? I am using ADS1231 to get values from a load cell,i am using the ADC in following configuration.
i am powering the micocontroller and loadcell by 5Volt supply as shown in above image. i am getting the results as expected and everything works fine.
Questions :
load cell that i am using is 2mV/volt type, and it says in the datasheet that the ADC input range is form -19.5 milivolts to +19.5 milivolts. In my case i am supplying the ADC with only 10 mV.
is there any way to increase the range ?
am i using the full potential of ADC capabilities?
Thankyou.

A: In the comments you stated that the problem is noise in the circuit. That is a crucial bit of information that you left out of your original question. If the problem is circuit noise then changing the ADC range isn't going to help.
First, you need to understand the noise. Take an FFT of the noise and see if it has a large component at your local power grid frequency. If so, then you clearly need to clean up your power supplies. You should also try running the whole thing from batteries using only linear regulators to see if that helps.
Make sure that the noise isn't coming from the digital side of your design. The AVDD and DVDD lines should be well isolated. If these two supplies are tied together at some point you may need to add passive LC filtering between them. You haven't told us how you physically constructed the circuit, but the proper routing of power and ground on a PCB is also important.
If the noise is truly random with a Gaussian distribution and its amplitude is greater than 1/2 LSB then you can use oversampling to improve the effective resolution of the measurements. In this case, averaging four measurements will improve the resolution by 1 bit.

A: Eliot Alderson's answer is correct, but let me expand a bit. At 5 volts power supply, your ADC range is (roughly) 40 mV (2 x 19.5, close enough), with a resolution of 24 bits. A 0 to 10 mV input will, then, convert to 1/4 of full scale, or 22 bits. That's about one part in 4 million. This is far, far beyond other sources of error, such as non-linearity of the load cells. Just stop worrying about that part of it. You have resolution and to spare. In rough numbers, 1 lsb will give you 5 milligram resolution (not grams, milligrams) and that is not a realistic goal.
What you also have is noise. From your comment, about 1000 counts of noise. That should be your concern. At a start, put 0.1 uF caps at each ADC input, connected to ground. Of course, you should also get a good capacitance meter and match the two caps as well, since if they are not matched well their different impedances at any frequency will cause problems. But even with not-well-matched caps they will likely help, and the experiment is simple enough that you should give it a try.


text:
Q: Show $f$ is differentiable and $f'$ is continuous.
Let $f:\mathbb{R}\rightarrow\mathbb{R}$ defined by:
  $$f(x) = \left\{ {\begin{array}{*{20}{c}}
   {1,x = 0}  \\
   {\frac{{\sin (x)}}{x},x \ne 0}  \\
\end{array}} \right.$$
Prove $f$ is differentiable and $f'$ is continuous.

My Work:
First, we want to validate that $f$ is continuous.
We know that $\mathop {\lim }\limits_{x \to 0} \frac{{\sin x}}{x} = 1$. Therefore, $f$ is continuous (Is it a rigorous explanation?).
Next, we want to show that $f$ is differentiable.
Indeed, for $x\ne 0$ $f(x)$ is a polynomial and therefore, differentiable.
for $x=0$ (I used L'hospital's rule):
$$\mathop {\lim }\limits_{x \to 0} \frac{{f(x) - f({x_0})}}{{x - {x_0}}} = \mathop {\lim }\limits_{x \to 0} \frac{{\frac{{\sin x}}{x} - 1}}{{x - 0}} = \mathop {\lim }\limits_{x \to 0} \frac{{\sin (x) - x}}{{{x^2}}} \Rightarrow \mathop {\lim }\limits_{x \to 0} \frac{{\cos (x) - 1}}{{2x}} \Rightarrow \mathop {\lim }\limits_{x \to 0} \frac{{ - \sin (x)}}{2} = 0$$
Therefore, $f$ is differentiable.
1) For what I showed so far, is it right? rigorous?
2) How to show $f'$ is continuous?
Thanks in advance.

A: $$f(x) = {1\over x}\sum_{n=0}^\infty {(-1)^n x^{2n+1}\over(2n+1)!}
= \sum_{n=0}^\infty {(-1)^n x^{2n}\over(2n+1)!}.$$
The last is an globally convergent power series and it is therefore infinitely differentiable everywhere.

A: yes it is, for one point, you made need to show continuity on the right side and on the left side (i.e. when x approaches $0$  from $\vert \epsilon\vert$  or from $-\vert \epsilon\vert$ , but your proof does that !
for the differentiability, I think it is much nicer when it is possible to give an explicit value : here you can compute that on ${R}_{-}^{*}$and ${R}_{+}^{*}$ , $f'(x)= \dfrac{x.cos(x) - sin(x)}{x^2}$, which  is worth $\dfrac{x - x^3/2 - x + x^3/6+O(x^4)}{x^2}$ which is equal to $-\frac{x}{3}$+O($x^2$) so from this you can conclude that $f'(x)$ exists and is continuous on ${R}$ .


text:
Q: Starting Chapters on Left page with Koma-script Book I'm using the KOMA-Script Book class and I'm interested in making specific chapters (not all) start on the left. I'm writing a translation and I want the book to open such that the original text (under the chapter header) is on the left, and the translation text is on the right. Right now, it will only open on the right and this puts the translation text on the opposite side of the page so both can't be seen at the same time.
I did a search of the forums already and tried several different solutions, but they didn't work. Some resulted in changing the title page but not whether the chapters started on the left/right.
Any suggestions would be greatly appreciated! Thank you! - J.D.

A: You can use \KOMAoptions{open=left} before that specific chapter and \KOMAoptions{open=right} before the next chapter that should start on a right page:
\documentclass{scrbook}
\usepackage{lipsum}
\begin{document}
\tableofcontents
\chapter{Chapter on right page}
\lipsum
\KOMAoptions{open=left}
\chapter{Chapter on left page}
\lipsum
\KOMAoptions{open=right}
\chapter{Chapter again on right page}
\lipsum
\end{document}

Result:

Or you define an own command \chapterleft:
\documentclass{scrbook}
\usepackage{lipsum}
\let\chapterleft\chapter
\usepackage{xpatch}
\xpretocmd\chapterleft{\KOMAoptions{open=left}}{}{}
\xapptocmd\chapterheadendvskip{\KOMAoptions{open=right}}{}{}
\begin{document}
\tableofcontents
\chapter{Chapter on right page}
\lipsum
\chapterleft{Chapter on left page}
\lipsum
\chapter{Chapter again on right page}
\lipsum
\end{document}


text:
Q: String concatenation inside traversal in Python Kivy This is a syntax issue I think; I am trying to add a dynamic element to my traversal (? Might be the wrong word) which adds the text of a number of buttons to a list. This is basically pseudo-code but it is how I am thinking:
list = [self.root.ids.('button_' + i).text for i in range (5)]

This is to save me having the following:
list = []
list.append(self.root.ids.button_1.text)
list.append(self.root.ids.button_2.text)
list.append(self.root.ids.button_3.text)
list.append(self.root.ids.button_4.text)
list.append(self.root.ids.button_5.text)

Is it possible to do this? The button_# is the bit that should be dynamic. Apologies If any of my terms are incorrect here.

A: To get attributes dynamically, you have to use getattr(obj, 'attr_name').
In your case it could be like this:
getattr(self.root.ids, 'button_%d' % i).text

For additional details see the docs.


text:
Q: Using a recursive macro to write the arguments of a function Is it possible to use a recursive macro to write as many function arguments as required. For example:
void foo( const char (&row1)[3] , const char (&row2)[3] , const char (&row3)[3] )
{
}

void foo( const char (&row1)[3] , const char (&row2)[3] , const char (&row3)[3] , const char (&row4)[3] , const char (&row5)[3] , const char (&row6)[3] )
{
}

I am aware that variadic templates were introduced to solve problems like this but I am limited to C++98 ATM.

A: You can have a look at the boost::preprocessor library which gives you a whole preprocessing toolkit. It provides preprocessor metaprogramming tools including repetition and recursion.
You can see an example in this answer.

A: Macros can't be recursive, since macro expansion won't expand the name of a macro in the process of being expanded.  C++11 did introduce the concept of macros with a variable number of arguments, using __VA_ARGS__, but I don't know too much about it.  (I use very few macros.)

A: Traditionally, the developer would create a set of macros, each with a different number of arguments:
#define foo1(arg1)
#define foo2(arg1, arg2)
#define foo3(arg1, arg2, arg3)
...