text:
Q: Understanding the law of identity in logic In logic, the 'law of identity' classically says: 'Every thing that exists' has a specific nature. More abstractly,  For all $x, x=x$. In a mathematical perspective, "For all $x$" is sensible to me when $x$ is contained in a universal set $U$ which is already been defined in a 'context'.
What does it mean by "For all $x$" or 'every thing that exists' or 'every being that exists' mathematically or logically? Is it a primitive notion? Also, what about 'existence'?, Some body argue that mathematically 'existence' is purely contextual.

A: In logic, there is a (in)famous 'proof' of the existence of God:
$ 1.\ \forall x \ x=x$ (your 'Law of Identity')
$2. \ god = god$ (Universal Elimination on $1$)
$3. \ \exists x \ x=god$ (Existential Introduction on $2$)
So there you go: there is something that is God: God exists!
OK, we all understand that this is of course not a proof of God's existence at all. So what is going on?
Well, 'existence' in mathematics and logic is merely existence-in-some-logically-possible-world.
For example, '$2$' exists in the world of natural numbers, but '$\pi$' does not.  '$\pi$' does exist in the world of real numbers. In the former world, there does not exist any number between $1$ and $2$, but in the latter world such numbers do exist.
So, it is all about the world or 'domain' that you specify. Once you specify a certain domain, then anything from that domain exists in that domain. That sounds rather trivial and uninteresting, but note that it actually can lead to some interesting results. For example, mathematicians typically specify a domain by laying out certain axioms. The Peano axioms, for example, specify the domain of the natural numbers and some basic operations therein. With these axioms, you can then prove things that are not immediately obvious, such as 'there exist perfect numbers' or 'there does not exist a greatest prime number'.
So this is what you read or heard when you say that 'existence is purely contextual': logical and mathematical existence is merely existence relative to some imagined world or domain.  I could, for example, simply define a world in which unicorns exist, and bam: unicorns exist! ... though not necessarily in the world that you and I inhabit.
Of course, most mathematicians and logicians do aim for their work to be applicable to the world we live in, and therefore most logical and mathematical principles are defined as such. Indeed, logic and math 'works' quite well in our world.  But again, it would be a mistake to say that just because something logically or mathematically exist, it therefore exists in our world.
Finally, let's go back to the 'proof' of God's existence I started out with.
Line 1 seems unproblematic: yes, everything 'has a specific nature': nothing can be different from what its nature, i.e. nothing can be different from what it is: $\neg \exists x \ x \neq x$ or, what is logically the same thing: $\forall x \ x=x$
Line 2 is more tricky. Suddenly I introduce 'god'. Where does that come from?  Well, pleas note that in logic, 'god' is a well-defined constant symbol and, as such, we can certainly use it in logic statements and proofs. However, whenever we do use a constant symbol, we also need to provide an interpretation for that symbol: an object from our domain that that symbol refers to or denotes. So, I must have in mind some object in my domain that 'god' refers to.
This could of course be our very notion of God ... but once I do that, I am committing myself to talking about a world where such a God exist. But again, that may not be our world at all: it is simply some world that I contemplate. Moreover, I could also say that my use of 'god' refers to the number $42$, in which case it is not referring to our typical notion of God at all. In sum, whatever the 'god' in this proof refers to may not be something that we typically understand as God, let alone that it exists in the world we currently inhabit.
With that understanding, we now get line $3$: yes, in whatever world I am contemplating, there exists something that is identical to the object in that very world that I specified as being referred to as 'god': namely that very same object that is being referred to with 'god'!
So everything makes perfect sense logically and mathematically, but we have learned nothing about the nature of our world.

A: It refers to all $x$ in some particular universe. The statement $\forall x, x= x$ can be interpreted to mean that, for all $x$ that exist in the universe, $x = x$. Depending on the context, a logician may be discussing one of many different universes.
Unfortunately, I'm not qualified to answer questions about the meaning of existence.

A: (Submitted after a previous answer was accepted)
(1) In mathematical proofs, each quantifier is usually explicitly restricted to some domain (e.g. to the elements of a particular set). These domains may be empty. Different quantifiers can be restricted to different domains even within the same statement.
(2) In a statement of the form  $x=x$ (by reflexivity), the $x$ would usually be a free variable or constant that was previously introduced by either an axiom, premise or existential specification. The free variable or constant $x$ would usually not appear for the first time as $x=x$.


text:
Q: PTC thermistor simulation in Proteus I want to simulate PTC thermistor in Proteus, but I need this informations.

*

*Thermal Contact Res. (°C/W)

*Thermal Res. to Ambient (°C/W)

*Time constant (s)

full datasheet:
http://www.farnell.com/datasheets/2050662.pdf?_ga=2.261979140.845161386.1546173081-1474740581.1524733191
How can I reach variable values in 1,2 and 3 from datasheet?

A: The time constant is variable.
1s if  It/Int= 5,
6s if It/Int=2.5 and
35s if It/Int=1.3 which is the
From external self heating hot air it appears to be >>35s, which is the lowest trip ratio given for 5mm and all sizes.
It is a self heating PTC not a temperature measuring sensor.
The time constant is a function of the Trip current It over the non-trip rated current Int. or It/Int
The Dissip. Factor (DF) for the 5mmD part is 7.3 (mW/K) therefore the Rja= 1/DF = 137 ('C/W)
The voltage derating is 100% from  75'C to 175'C therefore the trip temp is 175'C with a 100'C swing .  But if the Pd were known to be 0.75W at trip temp, the Rca would be 100'C/W/0.75W = 133 ('C/W) but we do not know this Pd. as it is not exactly constant

I want to ask 2 more questions. 1)If R=11 ohm in 25 °C and Iolmax =1500 (max overload current),then How can i calculate lolmax in 50 °C ?What is the formula? 2)If R=11 ohm in 25 °C,then how can i calculate R in 50 °C and in other temperatures? What is the formula?

You have to know how to create a formula from the curves given in your datasheet on pages 2 and 5. Now since these are not specified as a formula, you need a really good reason to do this and a better understanding of uncertainty and errors in this calculation.
If you see the curves on these pages, you may be surprised to learn that the
PTC actually has an NTC curve below 85'C
and then it flattens out and turns upwards to PTC.

The slope from 25'C to 75'C = k (Log R)/T   where k is the negative NTC coefficient which is never given.  So why do you need it when you have the curves on p 2,5?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rules for number of predictor variables in complex survey data I know there is the event per variable ratio of 10 to 1 for a regression analysis, where you should have ten event for every predictor in your model.
I was wondering what the rules are for a complex survey design. Is it still the same, or are they new or additional sets of rules for the number of predictors in an analysis.

A: The correct calculation of required sample sizes for complex surveys is a good few chapters of a book so I won't try to recreate it here other than to say that you are indeed correct that you need to include your survey design parameters (strata, weights, etc) in the calculation of your sample size.
The 10 to 1 rule is a more of a rule of thumb that seems to have persisted even though the support for it is mixed at best. I would suggest taking a look at Holtman et al. and then finding a good survey analysis book that is used in 3rd year or postgrad statistics subjects like Complex Surveys by Lumley.


text:
Q: Check if image exists or not on remote URL I tried to check either image exist or not on the remote URL. I tried different methods to check.
checkRemoteUrl('https://example.org/image.jpg');

function checkRemoteUrl($url){
    //Curl
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POST, 1 );
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);
    var_dump($result);
    //File Exist
    $result = file_exists($url);
    var_dump($result);

    //Fopen
    $result = fopen($url, 'r');
    var_dump($result);

    //File Get Content
    $result = file_get_contents($url);
    var_dump($result);

    //Get image Size
    $result = getimagesize($url);
    var_dump($result);

    //Get Header
    $result = get_headers($url);
    var_dump($result);
}

The response of the following function
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)

If I hit the image URL on the browser it shows the image, but unable to get any response from any of the methods. All the methods are working fine on a different server with the same URL. allow_url_fopen and allow_url_include are enabled on the server. What could be the issue?

A: you can check with the curl
$ch = curl_init("http://www.fooo.com/image.jpg");

curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$response_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

$response_status >= 404 -> not found,
$response_status = 200 ->  file is exists

All http status code

# 1xx: Information
Code | Message | Description
--- | --- | ---
100 | Continue | The server has received the request headers, and the client should proceed to send the request body
101 | Switching Protocols    | The requester has asked the server to switch protocols
103 | Checkpoint | Used in the resumable requests proposal to resume aborted PUT or POST requests

# 2xx: Successful
Code | Message | Description
--- | --- | ---
200 | OK | The request is OK (this is the standard response for successful HTTP requests)
201 | Created   | The request has been fulfilled, and a new resource is created
202 | Accepted | The request has been accepted for processing, but the processing has not been completed
203 | Non-Authoritative Information | The request has been successfully processed, but is returning information that may be from another source
204 | No Content | The request has been successfully processed, but is not returning any content
205 | Reset Content | The request has been successfully processed, but is not returning any content, and requires that the requester reset the document view
206 | Partial Content | The server is delivering only part of the resource due to a range header sent by the client

# 3xx: Redirection
Code | Message | Description
--- | --- | ---
300 | Multiple Choices | A link list. The user can select a link and go to that location. Maximum five addresses
301 | Moved Permanently  | The requested page has moved to a new URL
302 | Found | The requested page has moved temporarily to a new URL
303 | See Other  | The requested page can be found under a different URL
304 | Not Modified | Indicates the requested page has not been modified since last requested
306 | Switch Proxy | No longer used
307 | Temporary Redirect | The requested page has moved temporarily to a new URL
308 | Resume Incomplete | Used in the resumable requests proposal to resume aborted PUT or POST requests

# 4xx: Client Error
Code | Message | Description
--- | --- | ---
400 | Bad Request | The request cannot be fulfilled due to bad syntax
401 | Unauthorized | The request was a legal request, but the server is refusing to respond to it. For use when authentication is possible but has failed or not yet been provided
402 | Payment Required | Reserved for future use
403 | Forbidden | The request was a legal request, but the server is refusing to respond to it
404 | Not Found | The requested page could not be found but may be available again in the future
405 | Method Not Allowed | A request was made of a page using a request method not supported by that page
406 | Not Acceptable | The server can only generate a response that is not accepted by the client
407 | Proxy Authentication Required | The client must first authenticate itself with the proxy
408 | Request Timeout | The server timed out waiting for the request
409 | Conflict | The request could not be completed because of a conflict in the request
410 | Gone | The requested page is no longer available
411 | Length Required | The "Content-Length" is not defined. The server will not accept the request without it
412 | Precondition Failed | The precondition given in the request evaluated to false by the server
413 | Request Entity Too Large | The server will not accept the request, because the request entity is too large
414 | Request-URI Too Long | The server will not accept the request, because the URL is too long. Occurs when you convert a POST request to a GET request with a long query information
415 | Unsupported Media Type | The server will not accept the request, because the media type is not supported
416 | Requested Range Not Satisfiable | The client has asked for a portion of the file, but the server cannot supply that portion
417 | Expectation Failed | The server cannot meet the requirements of the Expect request-header field

# 5xx: Server Error
Code | Message | Description
--- | --- | ---
500 | Internal Server Error | A generic error message, given when no more specific message is suitable
501 | Not Implemented | The server either does not recognize the request method, or it lacks the ability to fulfill the request
502 | Bad Gateway | The server was acting as a gateway or proxy and received an invalid response from the upstream server
503 | Service Unavailable | The server is currently unavailable (overloaded or down)
504 | Gateway Timeout | The server was acting as a gateway or proxy and did not receive a timely response from the upstream server
505 | HTTP Version Not Supported | The server does not support the HTTP protocol version used in the request
511 | Network Authentication Required | The client needs to authenticate to gain network access

A: <?php

$ch = curl_init("https://cdn.sstatic.net/Img/unified/sprites.svg");
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$response_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response_status == 200) {
    // file exists
} else {
    // file doesn't exist
}
?>


text:
Q: plugin for different writers Does anybody know a way for having different writers with seperate logins? I would like to host a bunch of coaches/trainers with each having their own page they can modify. The plugin I'm using now is WP Customer area, but all the coaches are able to access each others pages. S there another way? Thanks for your help!

A: If I've understood you correctly, you want each coach/trainer to be able to publish a page that any site visitor can read, but not to be able to edit each others pages.
If you just set each of these users to the Author role, then that should work.


text:
Q: How to check if a service is running in chef? In a recipe file, i need to check if a service is already running. If it is, I need to stop it.
I have
service "apache" do
    supports :status => true
    action :stop
end

Any help will be appreciated.

A: Chef is declarative. So the code you've written does exactly what you've described.

A: service "apache" do
  supports :status => true, :restart => true, :start => true
  action [ :start ]
end

If the service is already running, it wont do any thing. but if stopped, it will start the service


text:
Q: Find items in list where word exist and ignor special chars I have list of MyItems:
My item
{
   string name;
   int age;
}

List<MyItem> list = new List<MyItem>();
list.Add(new Test("name", 2));
list.Add(new Test("ŚćĄa", 4));
list.Add(new Test("May NĄmĄa bb" , 7));
list.Add(new Test("May maa cc" , 7));

for now with :
var NewList = list.Where(m => m.name.ToLower().Contains(textToSearch.ToLower())).ToList();

I can ignore lower and upper case, but how to ignore special chars like ĄĆŚ ,
for that when I set textToSearch = "aa";
 I  get item two, three and four.
But when I set textToSearch = "ĄA"; I'd like to get only item two and four

A: try this:
list.Where(m =>
    CultureInfo.InvariantCulture.CompareInfo.IndexOf(
        m.name,
        textToSearch,
        CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase) > -1
).ToList();

two, three and four will be listed.


text:
Q: PrimeFaces 4.0 Tree ActionListener I am using Primefaces 4.0 with JSF 2.0
i have a tree and i want to perform specific action on the child node not on the parent node, my code is like:
<h:form id="form">
        <p:tree id="tree" value="#{treeBean.embargoRoot}" var="node" animate="true" >
            <p:treeNode id="treeNode">
            <p:commandButton value="#{node}" action="#{xmlReader.getRead()}"  id="treeNode"/>
        </p:treeNode>
        </p:tree>
    </h:form>'

Tree Class
    public TreeClass(){
            root = new DefaultTreeNode("", null);
        TreeNode p1 = new DefaultTreeNode("Parent 1", root);
        TreeNode p2 = new DefaultTreeNode("Parent 2", root);
        TreeNode c1= new DefaultTreeNode("Child 1", p1);
        TreeNode c2= new DefaultTreeNode("Child 2", p1);

            TreeNode c3= new DefaultTreeNode("Child 1", p2);
        TreeNode c4= new DefaultTreeNode("child 2", p2);
}

my aim is to perform specific task on child click only
Thanks in Advance

A: You can use the selection option for "p:tree"
<h:form id="form">
    <p:tree id="tree" value="#{treeBean.embargoRoot}" selectionMode="single"
     selection="#{treeBean.selectedNode}"var="node" animate="true" >
        <p:treeNode id="treeNode">
            <p:commandButton value="#{node}" action="#{xmlReader.getRead()}"  id="treeNode"/>
        </p:treeNode>
    </p:tree>
</h:form>

Depending on what you need to do here is an ajax update on event:
<p:ajax event="select" update=":form:objects"/>
<p:ajax event="unselect" update=":form:objects"/>

It is also possible to execute bean operations with getter/setters but not recommended.


text:
Q: json string to object with array var test = {'abc':76,'data':'[6435,3310,56.06875]'}

how do I convert above json string to an object say:
class item
{
    public string abc {Get;set;}
    public float[] data {get;set}
}

I tried
JsonConvert.DeserializeObject<item>(test);
but get this error:
{"Error converting value \"[6435,3310]\" to type 'System.Single[]'. Path 'data', line 1, position 117."}

A: There are a few problems with the json string (i am assuming you are using C#). First of the values of the data property are actually a string (given the quotes). Which is why you are getting the error.
What you could do is create a property to hold the string and then another property to parse the float values after parsed. This is done by using a few JSON.Net attributes of JsonProperty and JsonIgnore. These attributes tell the serializer what the property name is in the json string and which properties to ignore.
class Foo
{
    string dataString;
    float[] data = null;

    [JsonProperty("abc")]
    public string Abc { get; set; }

    [JsonProperty("data")]
    public string DataString
    {
        get { return dataString; }
        set
        {
            data = null;
            dataString = value;
        }
    }

    [JsonIgnore]
    public float[] Data
    {
        get
        {
            if (data != null)
                return data;

            return data = dataString != null ? JsonConvert.DeserializeObject<float[]>(DataString) : null;
        }
        set
        {
            DataString = value == null ? null : JsonConvert.SerializeObject(value);
        }
    }
}

This looks like alot of code however uses backing fields to allow you to change both the Data field and the DataString field while maintaining a working serializer.
This is then simply called using
var i = JsonConvert.DeserializeObject<Foo>(test);

A: This might do the trick for you
string jsn = @"{'abc':76,'data':'[6435,3310,56.06875]'}";
jsn = jsn.Replace("'[", "[");
jsn = jsn.Replace("]'", "]");
var ser = JsonConvert.DeserializeObject<ClsResult>(jsn);

I have used replace because 'data':'[6435,3310,56.06875]' is making the array of data to string. So better we make it like 'data':[6435,3310,56.06875] and then you class would look like
public class ClsResult
{
    [JsonProperty("abc")]
    public int abc { get; set; }

    [JsonProperty("data")]
    public IList<double> data { get; set; }
}


text:
Q: Simple line matching using Regex I have this string stream:
"do=whoposted&t=1934067" rel=nofollow>61	5,286

 [MULTI] Cool Topic Name

m3no

Today 08:04 AM
by karetsos <A "

The lines I am interested are similar to this:
Cool Topic Name

From here all I am trying to extract are:
Thread id: 1911046 (could be from either location in the string)
Thread name: "Cool Topic Name"
Thread link: "http://url.com/forum/f80/cool-topic-name-1911046/"

Currently I use this:
Regex pattern = new Regex ( "([^\\x00]*?)\\s+id=thread_title_(\\S+)" );

MatchCollection matches = pattern.Matches ( doc.ToString ( ) );

foreach ( Match match in matches )
{
    int id = Convert.ToInt32 ( match.Groups [ 1 ].Value );

    string name = match.Groups [ 3 ].Value;
    string link = match.Groups [ 2 ].Value;

    ...
}

I would appreciate if someone can help me fix the pattern to match it. This used to work but it returns 0 matches.

A: Michael Papile's answer works.  Remove the forward slashes (/) from the beginning and end of the pattern that you showed in your last comment.  Forward slashes are pattern delimiters in Ruby - we don't use them in .NET:
var rg = new Regex(@"<A(?:[^<]*)thread_title_(\d+) href=""([^""]*)"">([^<]*)");

(In an verbatim string (@"...") you only need to escape double quotes by doubling them up.
Edit: corrected pattern added by Richard to use the latest version from comments.  The original pattern did not match the elements properly, but this variation should.  Interestingly, the pattern works whether or not you add the extraneous \ before the quotes, but Richard is correct that it is not needed.
Edit (again): You're right, this pattern is not working on the actual page.  Of the three answers, only ridgrunner's returns 24 matches.

A: Assuming there will be any number of attributes and the href attribute always comes after the id, and the attributes may or may not have their values within quotes, then this one should do the trick:
Regex pattern = new Regex(
    @"]+?             # Lazily consume up to id attribute
    id\s*=\s*['""]?thread_title_([^>\s'""]+)['""]?  # $1: id
    [^>]+?             # Lazily consume up to href attribute
    href\s*=\s*['""]?([^>\s'""]+)['""]?             # $2: href
    [^>]*              # Consume up to end of open tag
    >                  # End start tag
    (.*?)                                           # $3: name
                # Closing tag",
    RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

Edit: Fixed the expression which consumed the end portion of the start tag. (Was [^>]+)

A: I do not program in c# but here is a regex that works in ruby (I guess you guys have \\ to indicate character classes?)
/([^<]*)/

EDIT
try this one:
thread_title_(\d+) href=\"([^\"]*)\"\>(.*?)<\/A>  it matches 2 of them in that pastie thing you did.  If you have to match complicated things in HTML, regexes are not good, you should use a XML/HTML parser

A: This should do it...
]+thread_title_(?<id>\d+)[^>]+href="(?<link>[^"]*)">(?<name>[^<]*)

Some of the other suggestions were a little too greedy and were matching more than one link at a time with your sample text.
One other thing to point out is the (?<link> notation, which is a named group.  It matches the same way as a regular group.  But you can then access these groups in C# by their name, or their index.
You can see this in action here...
http://regexhero.net/tester/?id=7855af6f-7774-4a7c-afa2-81c3e24cf496
By the way, use the .NET button at the top of Regex Hero to generate C#, and then the quotes will be properly escaped for you.


text:
Q: I cant figure out the diffrence between following two syntaxes while($rowForStateList  =   @mysql_fetch_array($resForStateList))

{
    $sid[$i]    =   $rowForStateList['state_auto_id'];

    $sname[$i]  =   $rowForStateList['state_name'];

    $spid[$i]   =   $rowForStateList['country_auto_id'];

    $i++;
}

AND
while($rowForStateList  =   mysql_fetch_array($resForStateList))

{
    $sid[$i]    =   $rowForStateList['state_auto_id'];

    $sname[$i]  =   $rowForStateList['state_name'];

    $spid[$i]   =   $rowForStateList['country_auto_id'];

    $i++;
}

A: The difference is that @mysql_fetch_array in first code sample fetches the array suppressing any errors, while mysql_fetch_array do the same but not suppressing errors. Actually, the second one is more correct way.
The evil of using @ is in that it comlicates debugging a lot. With this suppression, in case of error you'll end up with empty arrays, so it will look just like query used to get $resForStateList have returned empty result. But, you actually might have broken query, refused database connection and whatever else. And with @ you will never know that something goes wrong.
So, don't use @. Instead, use error handling functions. And the best way is to check if something could cause error, e.g. mysql_query returns false in case of any error, so you might want to check it like
$result = nysql_query("qwerty");
if (!$result){
    echo mysql_error();
}

A: The difference is that the former will mask any errors that occur in mysql_fetch_array(), making debugging more difficult.

A: The @ in the first version basically means "If this function triggers an error, just hide it, don't log or display it".
Don't ever use the @ error suppression operator!  Not only does it make for a debugging nightmare, but it also harms application performance.  Use error_reporting, log_errors and display_errors to set proper error message behaviour instead.

A: Don't use the @ operator in this case. mysql_fetch_array will only throw an error if the resource is not valid. You should have checked this before, after you got this resource.

A: The difference is the error reporting.
If you set a @ before mysql_fetch_array, any errors will be ignored.
see php errorcontrol

A: the only difference is that the @ in front of the mysql_fetch_array in the first code will supress any error from being displayed on the screen.

A: the first one suppresses errors: http://davidwalsh.name/suppress-php-errors-warnings

A: They are identical. The first mysql_fetch_array() will not produce error messages due to the suppression operator @.

A: The first one will silently ignore any error. The second one will display any error or exceptions thrown the mysql_fetch_array (for example, connection problem). The magic comes from the @ sign.

A: @mysql_fetch_array($resForStateList))
doesn't show up any message in case of an error.
That's all.

A: The @ is an operator thet suppresses errors. Your statement will not throw errors when the @ is added. You can read more here: http://thesmithfam.org/blog/2006/05/07/php-the-operator/

A: When you prepend '@' to an expression, any error messages that might be generated will be ignored (ie. no error output will be generated). Anyway if the track_errors feature is enabled, any error message generated by the expression will be saved (and overwritten on each error) in the variable $php_errormsg.
Check PHP Error Control for more details.
Actually, I prefer to use expression widthout '@' and handle all exceptions with a function that log all message in a file with error_log(). Something like:
function error_handler($errno, $errstr, $errfile=null, $errline=null, $errcontext=null) {
    error_log($errstr, 3, 'debug.log');
}

set_error_handler('error_handler', ERROR_REPORTING);


text:
Q: React Native - How to change bubble style I'm trying to change the background color of the chat bubble from react native.
It seemed so simple here: https://github.com/FaridSafi/react-native-gifted-chat/issues/493
And that's exactly the code I added, but then I got
You likely forgot to export your component from the file it's defined in.
Check the render method of `Message`.

Which lead me to try a bunch of different things that didn't work. And I know it must be super simple, but I know next to nothing about React Native :/
Do you know why this is happening? Thanks in advance!

A: Do you have imported Bubble?
import { GiftedChat, Bubble } from 'react-native-gifted-chat';

Do you have set your renderBubble function as props of GiftedChat as below?
<GiftedChat
            messages={this.state.messages}
            onSend={this.onSend}
            renderBubble={this.renderBubble}
            user={this.state.currentUser}
            showUserAvatar={true}
 />

A: If you want to display different color for two users this will work. It also accepts other text styles.
import { GiftedChat, Bubble, Time} from 'react-native-gifted-chat';

 <GiftedChat
    messages={messages}
    onSend={newMessage => onSend(newMessage)}
    renderBubble={props => {
      return (
        <Bubble
          {...props}

          textStyle={{
            right: {
              color: 'white',
              fontFamily: "CerebriSans-Book"
            },
            left: {
              color: '#24204F',
              fontFamily: "CerebriSans-Book"
            },
          }}
          wrapperStyle={{
            left: {
              backgroundColor: '#E6F5F3',
            },
            right: {
              backgroundColor: "#3A13C3",
            },
          }}
        />
      );
    }}
    user={{
        _id: 1,
    }}
/>


text:
Q: stateful session bean pool size am going through enterprise session bean material.i have doubts regarding below oints :-
1) lets say we mentioned the pool size as 50 for some statful session bean. Different 50 clients use them .
so now all the 50 beans maintain some state. At what point of time will these states be removed so that
if 51th clien ask for bean it does not get any previous spoilt state.?
2) lets say we mentioned the pool size as 50 for some stateless session bean and all are in use at some
point of time. If 51th client comes and ask for a bean, will that wait till some bean become free
or create new bean instance?

A: Stateful session beans are not normally pooled. It's possible, but their state makes them less ideal to pool as the client expects a fresh bean when obtaining a reference.
For stateless beans, yes the 51st client will have to wait. This is normally a good thing since it automatically moderates the resource consumption of your system. Depending on the resources you have, your workload and the amount of work being to in a single call to a ssb, you might want to tune the size of your pool.

A: As bkail states the pooling semantics of @Stateless beans are vendor-specific.  That said in EJB 3.1 we added the @AccessTimeout annotation which can be used on the bean class or methods of a @Stateless, @Stateful or @Singleton bean.
@AccessTimeout
In a general sense this annotation portably specifies up to how long a caller will wait if a wait condition occurs with concurrent access.  Specific to each bean type, wait conditions will occur when:

*

*@Singleton - an @Lock(WRITE) method is being invoked and container-managed concurrency is being used.  All methods are @Lock(WRITE) by default.

*@Stateful - any method of the instance is being invoked and a second invocation occurs.  OR the @Stateful bean is in a transaction and the caller is invoking it from outside that transaction.

*@Stateless - no instances are available in the pool. As noted, however, pooling sematics, if any, are not covered by the spec.  If the vendor's pooling semantics do involve a wait condition, the @AccessTimeout should apply.

Usage
The @AccessTimeout is simply a convenience wrapper around the long and TimeUnit tuples commonly used in the java.util.concurrent API.
import java.util.concurrent.TimeUnit;
@Target({METHOD, TYPE})
@Retention(RUNTIME)
public @interface AccessTimeout {
    long value();
    TimeUnit unit() default TimeUnit.MILLISECONDS;
}

When explicitly set on a bean class or method, it has three possible meanings:

*

*@AccessTimeout(-1) - Never timeout, wait as long as it takes.  Potentially forever.

*@AccessTimeout(0) - Never wait. Immediately throw ConcurrentAccessException if a wait condition would have occurred.

*@AccessTimout(30, TimeUnit.SECONDS) - Wait up to 30 seconds if a wait condition occurs.  After that, throw ConcurrentAccessTimeoutExcpetion
No standard default
Note that the value attribute has no default.  This was intentional and intended to communicate that if @AccessTimeout is not explicitly used, the behavior you get is vendor-specific.
Some vendors will wait for a preconfigured time and throw javax.ejb.ConcurrentAccessException, some vendors will throw it immediately.  When we were defining this annotation it became clear that all of us vendors were doing things a bit differently and enforcing a default would cause problems for existing apps.
On a similar note, prior to EJB 3.0 there was no default transaction attribute and it was different for every vendor.  Thank goodness EJB 3.0 was different enough that we could finally say, "For EJB 3.0 beans the default is REQUIRED."


text:
Q: Calling Q Promise on the basis of conditional logic Below is my condition
if abc is true
    call async func1, func2
else
    call async func1

function test(): Q.Promise<boolean> {
    if(abc)
       Q.all([func1,func2])
    else
       Q.all([func1])
    //if failed throw reject reason all the way in the chain
}

*

*As shown, it can be done using if and else clause, is there a better way to call promise conditionally?

*How to throw back error from any one of the promises?

A: I would put promises in array and append new one depending on condition:
function test(): Q.Promise<Boolean[]> {
    const promises = [func1()]
    if (abc) promises.push(func2())
    return Q.all(promises)
}

I corrected type signature a little, because Q.all resolves with array of values (Boolean in your case) from each underlying promises. You also need to call func1 and func2. And finally, don't forget to return from test function.

A: You are actually pretty close already:
function test() {
    if(abc)
       return Q.all([func1(),func2()])
    else
       return func1();
}
test().then(() => {
    // do whatever
}).catch(err => console.log(err));

Make sure you always return the promises as they don't get chained otherwise.


text:
Q: How to re-assign new data to ng-repeat in angularjs I have two ng-repeat sections in my HTML as below:
<md-card ng-repeat="location in global.locations | limitTo: 1 ">

    <md-select  name="location_id" ng-model="location" ng-change="getSingleLocations(location)">
        <md-option ng-repeat="location in global.locations" ng-value="location.slug">
   {{ location.location_name }}
        </md-option>
    </md-select>
</md-card>

When I change inner repeat then outer repeat content should be change as per the selected one.

A: I think without a plunkr you won't get a solution. But in the code here I see a few problems, first of all, first ng-repeat uses location as the iteration item name, and second one uses exactly the same name - this is wrong, the second should use its own name.
Second issue - the ng-model of the second ng-repeat uses again the same variable name - this will contain the selected value so it has to be a different object - I would call it selectedLocation.
Third thing which I don't really get is why you need the first ng-repeat - the nice part about angularjs is data binding, and once you have the ng-model populated by angular, you can use that one for the md-card something like this:
<md-card>
    <md-card-title>
      <md-card-title-text>
        {{selectedLocation.slug}}
      </md-card-title-text>
    </md-card-title>
    <md-select ng-model="selectedLocation">
        <md-option ng-repeat="location in global.locations track by $index" value="{{location.slug}}">
   {{ location.location_name }}
        </md-option>
    </md-select>
</md-card>


text:
Q: Opening .cdr in inkscape on Mac OS X Mavericks I am trying to open a .cdr file which I got from thingiverse (a RaspBerry Pi case).
I've installed Uniconverter using the steps in the answer by the user lauhub provided here: How to install Uniconvertor (command-line app) on Mac OS 10.7.2 (Lion)?
But when I try to open the .cdr file I get this error:

UniConvertor failed:
Traceback (most recent call last):   File
  "/Library/Frameworks/Python.framework/Versions/Current/bin/uniconvertor",
  line 13, in
      uniconv_run()   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/uniconvertor/init.py",
  line 100, in uniconv_run
      saver(doc, output_file)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sk1libs/filters/init.py",
  line 212, in call
      module.save(document, file, filename, options)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sk1libs/filters/export/svgsaver.py",
  line 339, in save
      saver.Save()   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sk1libs/filters/export/svgsaver.py",
  line 295, in Save
      left, bottom, right, top = self.document.PageRect() AttributeError: 'NoneType' object has no attribute 'PageRect'

Does anyone know what I did wrong?

A: If you are referring to a .cdr file as a CorelDRAW Image File then perhaps you will be able to open it with Adobe Illustrator, or Inkscape, a free application that lets you primarily edit vector graphics. Give that a shot and let me know how that works out for you.


text:
Q: awk :: use case insensitive to find common words in 2 files I have two files called 1.txt and 2.txt.
In 1.txt we can find these words:
apple
orange
butter
flower

In 2.txt we can find these words:
dog
cat
Butter
tower

I can use the command
awk 'NR==FNR{a[$0];next} ($0 in a)' 1.txt 2.txt
to find the common lines in the two files but the word Butter or butter is not returned because it has a capital letter in one of the two files.
How to return butter or Butter?
I just want to find the common lines.

A: easier with grep
$ grep -iwFf file1 file2
Butter

or with awk
$ awk 'NR==FNR{a[tolower($0)]; next} tolower($0) in a' file1 file2
Butter


text:
Q: Getting NullPointerException in onpostexecute method Problem is in onpostexecute method
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        contactListView = getListView();
        contactListView.setOnItemClickListener(viewContactListener);

        String[] from = new String[]{"name"};
        int[] to = new int[]{R.id.contactTextView};
        @SuppressWarnings("deprecation")
        CursorAdapter contactAdapter = new SimpleCursorAdapter(AddressBook.this,
                R.layout.contact_list_item, null, from, to);
        setListAdapter(contactAdapter);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        new GetContactsTask().execute((Object[])null);
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        Cursor cursor = contactAdapter.getCursor();
        if(cursor != null)
            cursor.deactivate();
        contactAdapter.changeCursor(null);
        super.onStop();
    }

    private class GetContactsTask extends AsyncTask<Object, Object, Cursor>{
        DatabaseConnector databaseConnector = DatabaseConnector(AddressBook.this);

        @Override
        protected Cursor doInBackground(Object... params) {
            // TODO Auto-generated method stub
            databaseConnector.open();

            return databaseConnector.getAllContacts();
        }

        @Override
        protected void onPostExecute(Cursor result) {
            contactAdapter.changeCursor(result);
            databaseConnector.close();
        }
    }

A: I see that you are declaring contactAdapter on onCreate. Do you have another contactAdapter as  class member? My guess is yes, but since you are declaring one at method level (onCreate) your  class member will never be set.


text:
Q: Jquery - How to condense function How would I condense this function? Any help would be much appreciated. Thanks.
$(document).ready(function () {
    $(".GoogleAppsProducts li.ProductIcon1").click(function () {
        $(".TabContent2").hide("slow");
        $("this").show("slow");
        $(".Gmail").show("slow").css("visibility", "visible");
    });
    $("input[id$='GoBackButton0']").click(function () {
        $(".TabContent2").show("slow");
        $("this").hide("slow");
        $(".Gmail").hide("slow").css("visibility", "visible");
        return false;
    });
    $(".GoogleAppsProducts li.ProductIcon2").click(function () {
        $(".TabContent2").hide("slow");
        $("this").show("slow");
        $(".GoogleCalendar").show("slow").css("visibility", "visible");
    });
    $("input[id$='GoBackButton1']").click(function () {
        $(".TabContent2").show("slow");
        $("this").hide("slow");
        $(".GoogleCalendar").hide("slow").css("visibility", "visible");
        return false;
    });
    $(".GoogleAppsProducts li.ProductIcon3").click(function () {
        $(".TabContent2").hide("slow");
        $("this").show("slow");
        $(".GoogleDocs").show("slow").css("visibility", "visible");
    });
    $("input[id$='GoBackButton2']").click(function () {
        $(".TabContent2").show("slow");
        $("this").hide("slow");
        $(".GoogleDocs").hide("slow").css("visibility", "visible");
        return false;
    });
    $(".GoogleAppsProducts li.ProductIcon4").click(function () {
        $(".TabContent2").hide("slow");
        $("this").show("slow");
        $(".GoogleCloud").show("slow").css("visibility", "visible");
    });
    $("input[id$='GoBackButton3']").click(function () {
        $(".TabContent2").show("slow");
        $("this").hide("slow");
        $(".GoogleCloud").hide("slow").css("visibility", "visible");
        return false;
    });
    $(".GoogleAppsProducts li.ProductIcon5").click(function () {
        $(".TabContent2").hide("slow");
        $("this").show("slow");
        $(".GoogleGroups").show("slow").css("visibility", "visible");
    });
    $("input[id$='GoBackButton4']").click(function () {
        $(".TabContent2").show("slow");
        $("this").hide("slow");
        $(".GoogleGroups").hide("slow").css("visibility", "visible");
        return false;
    });
    $(".GoogleAppsProducts li.ProductIcon6").click(function () {
        $(".TabContent2").hide("slow");
        $("this").show("slow");
        $(".GoogleSites").show("slow").css("visibility", "visible");
    });
    $("input[id$='GoBackButton5']").click(function () {
        $(".TabContent2").show("slow");
        $("this").hide("slow");
        $(".GoogleSites").hide("slow").css("visibility", "visible");
        return false;
    });
    $(".GoogleAppsProducts li.ProductIcon7").click(function () {
        $(".TabContent2").hide("slow");
        $("this").show("slow");
        $(".GoogleVideo").show("slow").css("visibility", "visible");
    });
    $("input[id$='GoBackButton6']").click(function () {
        $(".TabContent2").show("slow");
        $("this").hide("slow");
        $(".GoogleVideo").hide("slow").css("visibility", "visible");
        return false;
    });
    $(".GoogleAppsProducts li.ProductIcon8").click(function () {
        $(".TabContent2").hide("slow");
        $("this").show("slow");
        $(".GoogleMoreGoogleApps").show("slow").css("visibility", "visible");
    });
    $("input[id$='GoBackButton7']").click(function () {
        $(".TabContent2").show("slow");
        $("this").hide("slow");
        $(".GoogleMoreGoogleApps").hide("slow").css("visibility", "visible");
        return false;
    });
    $(".GoogleAppsProducts li.ProductIcon9").click(function () {
        $(".TabContent2").hide("slow");
        $("this").show("slow");
        $(".GoogleAppsMrkt").show("slow").css("visibility", "visible");
    });
    $("input[id$='GoBackButton8']").click(function () {
        $(".TabContent2").show("slow");
        $("this").hide("slow");
        $(".GoogleAppsMrkt").hide("slow").css("visibility", "visible");
        return false;
    });
    $(".GoogleAppsProducts li.ProductIcon10").click(function () {
        $(".TabContent2").hide("slow");
        $("this").show("slow");
        $(".GoogleChrome").show("slow").css("visibility", "visible");
    });
    $("input[id$='GoBackButton9']").click(function () {
        $(".TabContent2").show("slow");
        $("this").hide("slow");
        $(".GoogleChrome").hide("slow").css("visibility", "visible");
        return false;
    });
})

A: var links = [
    ['.GoogleAppsProducts li.ProductIcon1', '.Gmail'],
    ['.GoogleAppsProducts li.ProductIcon2', '.GoogleCalendar'],
    ...
];

for(var i=0, l=links.length; i<l; i++){
    with({i:i}){
        $(links[i][0]).click(function () {
            $(".TabContent2").hide("slow");
            $(this).show("slow");
            $(links[i][1]).show("slow").css("visibility", "visible");
        });
    }
}

And yes, I know I'm going to get flamed over the with, use a closure if you so desire.
If you can, add a common class to all of the .Gmail links, and compress the above code to:
var links = [
    ['.gmail-link', '.Gmail'],
    ...
]

A: You can put all repetitive tasks into a function.
     $(document).ready(function () {
        $(".GoogleAppsProducts li.ProductIcon1").click(function () {doMyStuff();});
        $("input[id$='GoBackButton0']").click(function () {
           doMyStuff();
           return false;
        });
        $(".GoogleAppsProducts li.ProductIcon2").click(function () { doMyStuff();});
        $("input[id$='GoBackButton1']").click(function () {
            doMyStuff();
            return false;
        });
        $(".GoogleAppsProducts li.ProductIcon3").click(function () {doMyStuff();});
        $("input[id$='GoBackButton2']").click(function () {
            doMyStuff(); return false;
         });

    function doMyStuff(){
     $(".TabContent2").show("slow");
     $("this").hide("slow");
     $(".GoogleDocs").hide("slow").css("visibility", "visible");
    }

A: try this:
var google = ['Gmail', 'GoogleCalendar', 'GoogleDocs', 'GoogleCloud', 'GoogleGroup', 'GoogleSites', 'GoogleVideo', 'GoogleMoreGoogleApps', 'GoogleAppsMrkt', 'GoogleChrome']
for (i = 1; i <= 10; i++) { (function() {
        $(".GoogleAppsProducts li.ProductIcon" + i + "").click(function() {
            $(".TabContent2").hide("slow");
            $(this).show("slow");
            $('.' + google[i] + '').show("slow").css("visibility", "visible");
        });
    })(i)
}
for (i = 0; i <= 9; i++) { (function() {
        $('input[id$="GoBackButton' + i + '"]').click(function() {
            $(".TabContent2").show("slow");
            $(this).hide("slow");
            $('.' + google[i] + '').hide("slow").css("visibility", "visible");
            return false;
        });
    })(i)
}


text:
Q: A simple sort script on Google Sheets is not working I have a "leaderboard"/"scoreboard", across four sheets, that I need to have auto sorting whenever updated by first Total Score (column 2) and then Total Kills (column 3). These columns are the same across all four sheets.
I've used a very simple script in the past when the scoreboard was limited to one sheet, but I have since expanded it to have Top Ten, Top Four, and Top Two on separate sheets within the same document.
The problem I'm running into: When the script updates one sheet, the other ones seem to flat out stop working entirely; in other words, the script breaks.
Can I please get some advice? I've tried several scripts already from this site, and the basic one I see some success with (but then the script seemingly breaks?) is below.
  function sortOnEdit(e) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("MAIN EVENT");
  sheet.sort(3, false).sort(2, false);
}

function sortOnEdit(e) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TOP TEN");
  sheet.sort(3, false).sort(2, false);
}

function sortOnEdit(e) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TOP FOUR");
  sheet.sort(3, false).sort(2, false);
}

function sortOnEdit(e) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TOP TWO");
  sheet.sort(3, false).sort(2, false);
}

Ideally, when functioning, the sheets will literally just sort themselves by the Total Score column, with Total Kills being the "tiebreaker" for sorting.
I've included a copy of my sheet if anybody could help:
https://docs.google.com/spreadsheets/d/1a6XGv09TPt5Vnxqfcd1Xba3TGMis5OelGxlvzNDl5CY/edit?usp=sharing

A: try something like this instead of your scripts:
function onEdit(event){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = event.source.getActiveSheet().getName()
  var editedCell = event.range.getSheet().getActiveCell();
if(sheet=="Sheet1"){
  var columnToSortBy = 2;
  var tableRange = "A3:C10"; //range to be sorted
  if(editedCell.getColumn() == columnToSortBy){
    var range = ss.getActiveSheet().getRange(tableRange);
    range.sort( { column : columnToSortBy, ascending: true } );
  }}
  else if(sheet=="Sheet2"){
    var columnToSortBy = 7;
    var tableRange = "A3:C10"; //range to be sorted
  if(editedCell.getColumn() == columnToSortBy){
     var range = ss.getActiveSheet().getRange(tableRange);
    range.sort( { column : columnToSortBy, ascending: true } );
  }
  else{return}
}}

A: try this:
function sortOnEdit(e) {
  var sh=e.range.getSheet();
  var name=sh.getName();
  var incl=['MAIN EVENT','TOP TEN','TOP FOUR','TOP TWO'];
  if(incl.indexOf(name)==-1) return;
  sh.sort(3,false).sort(2,false);
}


text:
Q: where is the save file located? Question is about KOPP +1 Edition, not KOPP.
Where are the save files located? -- this one didn't help. I bought KOPP+1 for my Android 2.3 device. Played it for a bit, made 3 save files. I just upgraded to an Android 4.2.2 device. I moved KOPP+1 over to the SD card and put the SD card in the new phone. When I open KOPP it can't find the save games. I've searched for files using the file browser named "knights" and not found any files. But searching for "seesmic" did find files, so I know that's working.
How can I find my old save file and get it working on my new phone?

A: If game is using private storage you will want to check:
/data/data/br.com.beholdstudios.knightspp/
or
/sdcard/Android/data/br.com.beholdstudios.knightspp/


text:
Q: Make a custom search bar in glossary in magento There is an error says

Fatal error: Call to a member function addAttributeToSelect() on null

<?php
if ($this->getRequest()->isPost('btn-save')) {
    $search = $this->getRequest()->getPost();
    $searchKey = '';
  if($search) {
      $searchKey = $search['gsearch'];
  }

    $collection = Mage::getResourceModel('glossary/word_collection');
  $words ->addAttributeToSelect('name');
  $words ->addAttributeToFilter(array(array('name' => $searchKey, 'eq' => true)));
  echo $words->getSelect();
}
?>

A: Try this:
<?php
if ($this->getRequest()->isPost('btn-save')) {
    $search = $this->getRequest()->getPost();
    $searchKey = '';
  if(isset($search['gsearch'])) {
      $searchKey = $search['gsearch'];
  }

    $words = Mage::getResourceModel('glossary/word_collection');
    $words->addFieldToFilter("name", array("eq" => $searchKey)));
    echo $words->getSelect();
}
?>

OR
<?php
if ($this->getRequest()->isPost('btn-save')) {
    $search = $this->getRequest()->getPost();
    $searchKey = '';
  if(isset($search['gsearch'])) {
      $searchKey = $search['gsearch'];
  }

    $words = Mage::getResourceModel('glossary/word_collection');
    $words->addFieldToFilter("name", array("like" => $searchKey)));
    echo $words->getSelect();
}
?>

A: Use addFieldToSelect incase of addAttributeToSelect
addFieldToSelect used for flat model
addAttributeToSelect user for EAV model

A: The way I understand you want below code change as I mentioned
<?php
if ($this->getRequest()->isPost('btn-save')) {
$search = $this->getRequest()->getPost();
$searchKey = '';
 if($search) {
  $searchKey = $search['gsearch'];
 }

 $collection = Mage::getResourceModel('glossary/word_collection');
 $collection ->addFieldToSelect('name');
 $collection ->addFieldToFilter(array(array('name' => $searchKey, 'eq' => true)));
 echo $collection->getSelect();
}
?>

A: You have used variable is $words
that should be $collection
your code look like below:
$collection = Mage::getResourceModel('glossary/word_collection');
  $collection->addAttributeToSelect('name');
  $collection->addAttributeToFilter(array(array('name' => $searchKey, 'eq' => true)));
  echo $collection->getSelect();


text:
Q: Does $\inf_{B \in \Lambda} \varphi(B) = \varphi\left( \inf_{B \in \Lambda} \right)$ if $\varphi$ is Borel measurable and each $B \in \Lambda$ is Borel I have been reading the book Modern Real Analysis by Ziemer and have come to an exercise I am having trouble with in the chapter on measure theory. The exercise goes :

Let $\varphi$ be a Caratheodory measure. For each set $A \subset X$ define :
\begin{equation}
\psi(A) = \inf\left\{ \varphi(B) \; : \; B \supset A \text{ , } B \text{ is a Borel set } \right\}
\end{equation}
Prove that $\psi$ is an outer measure on $X$.

Here is a definition that appears in the chapter :
Definition 4.1 :
A function $\varphi$ defined for every subset $A$ of an arbitrary set $X$ is called an
outer measure on $X$ if the following conditions are satisfied :
(i.) $\varphi(\emptyset) = 0$
(ii.) $0 \leq \varphi(A) \leq \infty$ whenever $A \subset X$
(iii.) $\varphi(A_{1}) \leq \varphi(A_{2})$ whenever $A_{1} \subset A_{2}$
(iv.) $\varphi\left( \bigcup_{i=1}^{\infty} A_{i} \right) \leq \sum_{i=1}^{\infty} \varphi(A_{i})$ for every countable collection of sets $\{A_{i}\}$ in $X$
Here is my solution so far :
Let $\mathcal{B}$ be the set of Borel sets and :
\begin{equation}
\ell(A) := \{ B \in \mathcal{B} \; \mid \; B \supset A \}
\end{equation}
We see :
\begin{equation}
\psi(A) = \inf_{B \in \ell(A)} \varphi(B)
\end{equation}
First prove :
\begin{equation}
\psi(\emptyset) = 0
\end{equation}
We see :
\begin{equation}
\ell(\emptyset) = \mathcal{B}
\end{equation}
and we know :
\begin{equation}
\emptyset \in \mathcal{B} \text{ and } \emptyset \subset B \; \forall B \in \mathcal{B}
\end{equation}
So :
\begin{align}
\psi(\emptyset)
 & = \inf_{B \in \ell(A)} \varphi(B)\\
 & = \varphi(\emptyset) = 0 \; \checkmark
\end{align}
Now show :
\begin{equation}
\psi(A) \in [0,\infty] \; \forall A \subset X
\end{equation}
We see :
\begin{align}
\varphi(B) \geq 0 \; \forall B \in \mathcal{B}
 & \Rightarrow \inf_{B \in \mathcal{B}} \varphi(B) = 0 \\
 & \Rightarrow \inf_{B \in \ell(A) \subset \mathcal{B}} \varphi(B) \geq 0 \; \forall A \subset X\\
 & \Rightarrow \psi(A) \geq 0 \; \forall A \subset X \; \checkmark
\end{align}
I think we can just assume that $\psi(A) \leq \infty \; \forall A \subset X$ since $\mathbb{R} \cup \{\infty\}$ is the
co-domain of $\varphi$. So :
\begin{equation}
\psi(A) \in [0,\infty] \; \forall A \subset X \; \checkmark
\end{equation}
Now show :
\begin{equation}
A_{1} \subset A_{2} \subset X \Rightarrow \psi(A_{1}) \leq \psi(A_{2})
\end{equation}
We see :
\begin{align}
A_{1} \subset A_{2}
 & \Rightarrow \ell(A_{2}) \subset \ell(A_{1})\\
 & \Rightarrow \inf_{B \in \ell(A_{2})} B \geq \inf_{B \in \ell(A_{1})} B\\
 & \Rightarrow \psi(A_{2}) \geq \psi(A_{1})\\
 & \Rightarrow \psi(A_{1}) \leq \psi(A_{2}) \; \checkmark
\end{align}
Now show :
\begin{equation} \tag{1}\label{1}
\psi\left( \bigcup_{i=1}^{\infty} A_{i} \right) \leq \sum_{i=1}^{\infty} \psi(A_{i})
\end{equation}
where $A_{i} \subset X \; \forall i \in \mathbb{N}$.
Define :
\begin{equation}
W = \left\{ \{B_{i}\}_{i=1}^{\infty} \subset \mathcal{B} \; \mid \; B_{i} \in \ell(A_{i}) \; \forall i \in \mathbb{N} \right\}
\end{equation}
Let $\alpha \in W$ s.t. $\alpha = \{B_{i}\}_{i=1}^{\infty}$. Define :
\begin{equation}
f(\alpha) = \sum_{i=1}^{\infty} \varphi(B_{i})
\end{equation}
and :
\begin{equation}
g(\alpha) = \varphi\left( \bigcup_{i=1}^{\infty} B_{i} \right)
\end{equation}
We know since $\mathcal{B}$ is a $\sigma$-algebra :
\begin{equation}
\bigcup_{i=1}^{\infty} B_{i} \in \mathcal{B}
\end{equation}
and by definition 4.1 (iv) :
\begin{equation} \tag{2}\label{2}
g(\alpha) \leq f(\alpha) \; \forall \alpha \in W
\end{equation}
Also :
\begin{align}
B_{i} \supset A_{i} \; \forall i \in \mathbb{N}
 & \Rightarrow \bigcup_{i=1}^{\infty} B_{i} \supset \bigcup_{i=1}^{\infty} A_{i}\\
 & \Rightarrow \bigcup_{i=1}^{\infty} B_{i} \in \ell\left( \bigcup_{i=1}^{\infty} A_{i} \right)
\end{align}
So :
\begin{equation} \tag{3}\label{3}
\psi\left( \bigcup_{i=1}^{\infty} A_{i} \right) = \inf_{B \in \ell\left( \bigcup_{i=1}^{\infty} A_{i} \right)} \varphi(B) \leq g(\alpha) \; \forall \alpha \in W
\end{equation}
and :
\begin{equation} \tag{4}\label{4}
\sum_{i=1}^{\infty} \psi(A_{i}) = \sum_{i=1}^{\infty} \inf_{B \in \ell(A_{i})} \varphi(B) \leq f(\alpha) \; \forall \alpha \in W
\end{equation}
So :
\begin{equation}
\ref{2} \text{ and } \ref{3}  \Rightarrow \psi\left( \bigcup_{i=1}^{\infty} A_{i} \right) \leq f(\alpha) \; \forall \alpha \in W
\end{equation}
Now define a partial order relation $\prec$ on $W$. Let $\alpha,\beta \in W$ s.t. $\alpha = \{B_{i}\}_{i=1}^{\infty}$ and $\beta = \{E_{i}\}_{i=1}^{\infty}$.
We define :
\begin{equation}
\alpha \prec \beta \Leftrightarrow B_{i} \subset E_{i} \; \forall i \in \mathbb{N}
\end{equation}
We see :
\begin{align}
\alpha \prec \alpha \; \forall \alpha \in W \; \text{(reflexive)}\\
\alpha \prec \beta \text{ and } \beta \prec \alpha \Rightarrow \alpha = \beta \; \text{(antisymmetric)}\\
\alpha \prec \beta \text{ and } \beta \prec \gamma \Rightarrow \alpha \prec \gamma \; \text{(transitive)}
\end{align}
So $\prec$ is a valid order relation.
Clearly due to definition 4.1 (iii) :
\begin{equation}
\alpha \prec \beta \Rightarrow f(\alpha) \leq f(\beta)
\end{equation}
We see :
\begin{equation}
\sum_{i=1}^{\infty} \inf_{B \in \ell(A_{i})} \varphi(B) = f\left( \inf(W) \right) \Rightarrow \psi\left( \bigcup_{i=1}^{\infty} A_{i} \right) \leq \sum_{i=1}^{\infty} \psi(A_{i})
\end{equation}
So we can prove :
\begin{equation}
\sum_{i=1}^{\infty} \inf_{B \in \ell(A_{i})} \varphi(B) = f\left( \inf(W) \right)
\end{equation}
First prove :
\begin{equation}
\color{red}{\inf_{B \in \ell(A_{i})} \varphi(B) = \varphi\left( \inf_{B \in \ell(A_{i})} B \right)}
\end{equation}
(... NEED TO FINISH THIS PART ...)
So :
\begin{equation}
\inf_{B \in \ell(A_{i})} \varphi(B) = \varphi\left( \inf_{B \in \ell(A_{i})} B \right) \; \checkmark
\end{equation}
So we can prove :
\begin{equation} \tag{5}\label{5}
\sum_{i=1}^{\infty} \varphi\left( \inf_{B \in \ell(A_{i})} B \right) = f\left( \inf(W) \right)
\end{equation}
Now let $\alpha = \inf(W)$ with $\alpha = \{ D_{i} \}_{i=1}^{\infty}$. We see :
\begin{equation}
\inf_{B \in \ell(A_{i})} B = D_{i} \; \forall i \in \mathbb{N}
\end{equation}
So \ref{5} is true. This means :
\begin{equation}
\psi\left( \bigcup_{i=1}^{\infty} A_{i} \right) \leq \sum_{i=1}^{\infty} \psi(A_{i}) \; \checkmark
\end{equation}
I'm not sure if the answer needs to be this long, but I think that I may be missing something here. The part that I need assistance with is proving :
\begin{equation}
\color{red}{\inf_{B \in \ell(A_{i})} \varphi(B) = \varphi\left( \inf_{B \in \ell(A_{i})} B \right)}
\end{equation}
Is this a true statement ? Is there a way to prove that it is true ?

A: I think you're making things overly complicated. Let $\{A_k\}$ be a sequence of subsets of $X$. If $\psi(A_k) = \infty$ for some $k$ then subadditivity is automatic. Otherwise, if $\psi(A_k) < \infty$ for each $k$, then for a fixed $\epsilon > 0$ you can by definition find a set $B_k \in \cal B$ for which $A_k \subset B_k$ and $$\varphi(B_k) \le \psi(A_k) + \frac \epsilon{2^k}.$$
Since $\bigcup_k A_k \subset \bigcup_k B_k$ and $\bigcup_k B_k \in \cal B$, you have by definition $$\psi \left( \bigcup_k A_k \right) \le \varphi \left( \bigcup_k B_k \right).$$ Since $\varphi$ is a measure it is countably subadditive and you get
$$\varphi \left( \bigcup_k B_k \right) \le \sum_k \varphi(B_k) \le \sum_k \left( \psi(A_k) + \frac \epsilon{2^k} \right) = \epsilon + \sum_k \psi(A_k).$$ Now let $\epsilon \to 0^+$ to reach the conclusion.


text:
Q: What's the difference between a Permutation and a Perturbation? I frequently come across the terms Permutation and Perturbation within the field of explainable AI.
I understand that both terms refer to methods that make changes to a sample's features. However, I'm not certain of the difference between the two.
From mathematics, a permutation is a rearrangement of elements in a set. This makes me think permutation methods draw their changes from other samples in the dataset.
From physics, a perturbation is a minor change to a model that disturbs its usual output. This makes me think perturbation methods can make any change to the sample regardless of what values are held in other samples.
If that's true then permutation methods would be special cases of perturbation methods. Have I got this right, or is there more to the distinction?
Example situation
To avoid confusion, consider the example of a single sample, which is part of a highly localised dataset.
The high locality of the dataset implies there are many other samples nearby. Permutation will therefore produce samples close to the single sample. Similarly, perturbing the single sample will produce multiple samples close to the dataset. In this situation it's possible the two methods would produce overlapping samples, the only difference being the permutation samples are more restricted than the perturbation samples.
In the above example, wouldn't that make permutation a special case of perturbation?
Related

*

*What is perturbation in Machine Learning?

*Permutation Feature Importance

A: There may be a deeper connection between the two, I'll speak from a perspective of graduate level applied math/physics.

If that's true then permutation methods would be special cases of perturbation methods. Have I got this right, or is there more to the distinction?

No, I don't think so.  Permutations are mappings from a finite set onto itself.  In that way, a permutation can be like a function.
In english, to perturb something is "to an influence tending to alter its normal or regular state or path" or maybe "to unsettle something". This aligns fairly closely to applications in physics/applied math where we take a dynamical system and perturb the solution to understand the dynamics near fixed points.  At least in physics, perturbations can be conceived as functions I suppose, but its more to understand  how some other function or system behaves near some point of interest.


text:
Q: Correlation between scale and ordinal variables? I am currently writing my thesis, and one of my research questions involves testing a correlation between two variables from my questionnaire.
One of the variables is a number between 1.0 and 5.0, representing a person's personality score, and the other variable is the participants choice out of 3 options. To simplify things for the sake of this explanation, option 1 would be "evil", option 2 would be "moderate" and option 3 would be "good". I would like to find out if there is a correlation between a person's personality score and the choice they made (e.g. will people with a higher p score choose option 3 more?)
Unfortunately I was never good at statistics, so could anyone tell me how I can find the answer to this? Currently I'm messing around in SPSS, but I don't really know what I'm doing...
Kind regards
Edit: Would an ANOVA-test be a solution to this problem?
Edit2: This is a scatter plot of the data:

A: Maybe you have data something like my fake data for 200 'subjects' graphed below, where x has 200 scores
between 1 and 5, and y shows Option chosen. [Simulation and graph from R.]
stripchart(x ~ y, pch="|", ylim=c(.6,3.4))

If you're just interested in correlation, I'd suggest Spearman
correlation between numerical scores x and ordinal categorical options y.
Spearman correlation is based on ranks, and ordinal options can be ranked.
cor(x,y, method="s")
[1] 0.62997

A Kruskal-Wallis test shows highly significant differences in scores for the three options.
kruskal.test(x ~ y)

        Kruskal-Wallis rank sum test

data:  x by y
Kruskal-Wallis chi-squared = 79.208, df = 2, p-value < 2.2e-16

Ad hoc 2-sample Wilcoxon rank sum tests show significant differences
in scores between Options 1 & 2 and between Options 2 & 3.
wilcox.test(x[y==1],x[y==2])$p.val
[1] 4.815738e-08
wilcox.test(x[y==2],x[y==3])$p.val
[1] 4.225357e-10

Depending on your objectives, you should also consider ordinal regressions as suggested by @kjetilbhalvorsen.

Note: In case you want to the individual values for x and y here
is the code I used to simulate them:
set.seed(2020)
x1 = round(4*rbeta(50, 1,3)+1, 2)
x2 = round(4*rbeta(100,2,2)+1 ,2)
x3 = round(4*rbeta(50, 3,1)+1, 2)
x = c(x1,x2,x3)
y = rep(1:3, c(50,100,50))

Addendum, Changing data to integers: Based on discussion in Comments.
set.seed(2020)
x1 = round(4*rbeta(50, 1,3)+1)
x2 = round(4*rbeta(100,2,2)+1)
x3 = round(4*rbeta(50, 3,1)+1)
x = c(x1,x2,x3)
y = rep(1:3, c(50,100,50))
cor(x,y, method="s")
[1] 0.6035967
kruskal.test(x~y)

        Kruskal-Wallis rank sum test

data:  x by y
Kruskal-Wallis chi-squared = 73.012, df = 2,
  p-value < 2.2e-16

TAB = rbind(c(tabulate(x1),0),tabulate(x2),tabulate(x3))
TAB
     [,1] [,2] [,3] [,4] [,5]
[1,]   14   24    9    3    0
[2,]    8   26   39   23    4
[3,]    1    3    8   17   21

Chi-squared test rejects null hypothesis that
HH and Choice (both treated as nominal, not ordinal, variables) are independent. Unlike
Spearman correlation the chi-squared says
nothing about the direction of the association.
chisq.test(TAB)

        Pearson's Chi-squared test

data:  TAB
X-squared = 98.331, df = 8, p-value < 2.2e-16

Table may be the best data display, but here is a marginally satisfactory version of a stripchart, using jitter (small random displacements) to
minimize overplotting).
stripchart(x~y, method="jitter", pch="-")

After rounding HH scores to integers, everything
works fine for my fake data. Choose the tests
that you believe best match your data and
objectives. (Inappropriate to try everything and just report what happens to show significance.)


text:
Q: Meu componente dentro do meu modal está renderizando duas vezes Possuo um componente pai que abre um modal baseado no valor desta variável:
const [openFullScreenModal, setOpenFullScreenModal] = useState(false)

Possuo um botão neste componente que seta o vaor desta variável para true:
setOpenFullScreenModal(true)

No meu template, eu possuo um modal que abre quando o valor dessa variável é true:
{ openFullScreenModal === true ?
    <ModalFullScreen
        FormComponent={UsersFormPermissionsGroupPermissions}
        title="Permissões do grupo"
        onCloseModal={setOpenFullScreenModal}
        open={openFullScreenModal}
    />
    :
    <> </>
}

Este é meu ModalFullScreen component:
const ModalFullScreen = (props) => {

    const { title, FormComponent, open, onCloseModal } = props
    const classes = modalFullScreenStyles()

    const handleClose = () => {
        onCloseModal(false)
    }

    return (

            <Dialog fullScreen open={open} onClose={handleClose}>
                <AppBar className={classes.appBar}>
                    <Toolbar>
                        <Typography variant="h6" className={classes.title}>
                            {title}
                        </Typography>
                        <IconButton edge="start" color="inherit" onClick={handleClose} aria-label="fechar">
                            <Typography variant="h6" className={classes.title}>
                                Cancelar
                            </Typography>
                        </IconButton>
                    </Toolbar>
                </AppBar>

                <FormComponent></FormComponent>

            </Dialog>

    )

No meu UsersFormPermissionsGroupPermissions componente eu uso um useEffect() para buscar dados de uma api:
useEffect(() => {
    console.log('mounted again')
    dispatch(groupPermissionsActions.getPermissionsGroupById(idGroupCompany))
})

Eu percebi que minha api estava sendo chamada duas vezes, então coloquei esse console.log() e confirmei que meu componente está sendo re-renderizado duas vezes quando eu clico no botão do meu componente pai para abrir esse modal, meu modal abre e o componente que eu estou passando para o modal é renderizado duas vezes.
Porque isso está acontecendo?

A: Vou deixar um exemplo mesmo assim, com o useEffect para renderizar o componente e após isso atualizar uma variável local de estado para carregar as informações não gerando assim renderização desnecessárias, exemplo:

function Modal({onClose}) {
  const [data, setData] = React.useState({});
  const loadData = () => {
    fetch('https://viacep.com.br/ws/01001000/json/')
      .then(response => response.json())
      .then(response => setData(response));
  }
  React.useEffect(() => {
    loadData();
  }, []);
  return (

Modal

      <button onClick={onClose}>Close</button>

Data

        { data && (
{data.cep}
) }
        { data && (
{data.localidade}
) }
        { data && (
{data.logradouro}
) }

  )
}

function Pai() {
  const [open, setOpen] = React.useState(false);
  const onClose = () => {
    setOpen(false);
  }
  const onOpen = () => {
    setOpen(true);
  }

  return (

      {open && <Modal onClose={onClose}/>}
      {!open && (<button onClick={onOpen}>Open</button>)}

  );
}
ReactDOM.render( <Pai/> , document.getElementById('root'));


text:
Q: excludeFromIndexes: [] does not work. entity properties are still indexed I have a transaction where I am saving an entity and I have an array excludesFromIndexes.when the entity is saved it shows the properties as indexed even though I added excludefromindexes.
  function test(user,pass,array,callback){
        let transaction = ds.transaction();
        let key = ds.key('questions')
        transaction.run()
        .then(()=>
            transaction.save(
                {key: key,
                data:{
                    'user':user,
                    'pass':pass
                },
                excludeFromIndexes:['user','pass']}))
        .then(()=> transaction.commit())
        .then(function(apiResponse){
            callback({response:'successful'});
        })
        .catch(function(err){
                transaction.rollback()
                callback({'error':err});
            })
      }

A: Different version of Google Datastore libraries are using different syntax and may ignore excludefromindexes completely.
Updating to the latest version is recommended.


text:
Q: Why is my event emitter not working on angular? Why is my EventEmitter not working?
Calling the function sendInstruction() the EventEmitter doesn't work, but testing in ngOnInit the event reaches on parent component, what is happening?
child component.ts
@Output() updateInstruction = new EventEmitter<boolean>();

sendInstruction() {
    this.objDetails = this.titleDetails.DetalhesTitulo
    const send: SendInstruction = {
      ...
    }
    this.service.sendInstruction(send, this.objDetails.NN_ABC).subscribe({
      next: () => {
        this.emitInstruction(true)
      },
      error: () =>
        ...,
    });
  }

  emitInstruction(emit){
    this.updateInstruction.emit(emit)
  }

child component.html
<button class="abc-button select medium col-top" mat-raised-button color="primary" [disabled]="!hasInstruction || formInstructions.invalid"
        (click)="sendInstruction()">
            Send Instruction
</button>

parent component.ts
getDetailsUpdate(update) {
    console.log(update);
}

parent component.html
<abc-instruction-billet (updateInstruction)="getDetailsUpdate($event)"></abc-instruction-billet>

A: You need to subscribe to your observable like this.
this.service.sendInstruction(send, this.objDetails.NN_ABC).subscribe(()=> {
    this.emitInstruction(true)
},error => {
    ....,
});


text:
Q: Show that $f(z)$ can be extended to all of $\mathbb{C}$ as an entire function. Let $f(z)$ be analytic in the unit disc $D$. Suppose there is a constant $M$ such that $$\left|f^{(n)}(0)\right| \leq M^n$$ for all n sufficiently large. Show that $f(z)$ can be extended to all of $\mathbb{C}$ as an entire function.
My idea is to construct a function $g(z)$ whose restriction to $D$ is $f(z)$, and prove that its Taylor series has infinite radius of convergence, which means it is an entire function. But I do not know how to do that.
Do you have any idea?
Any help would be highly appreciated!
Thank you in advance!

A: Let $m$ such that $|f^{(n)}(0)|\leq M^n$ for all $n\geq m$. Put $f(z)=\sum a_kz^k$ for all $z\in D$.
Because $f^{(k)}(0)=k!a_k$, we have $|a_k|\leq \frac{M^k}{k!}$ for all $k\geq  m$.
Let $z\in K,\text{ a compact set on } \mathbb{C}$ and let $r>0: |z|\leq r $ for all $z\in K$. $
|\sum a_kz^k|\leq |\sum_{k=0}^{m-1} a_kz^k| + |\sum_{k=m}^{\infty} a_kz^k|$ but $ |\sum_{k=m}^{\infty} a_kz^k|=|z^m|| |\sum_{k=0}^{\infty} a_{m+k}z^k|\leq |z^m|(\sum_{k=0}^{\infty} |a_{m+k}z^k|)\leq  |z^m|(\sum_{k=0}^{\infty} \frac{M^{m+k}}{k!}|z^k|)\leq  r^mM^me^{Mr}$.
Because $f$ converges on all compacts $K$,$f$ is holomorphic on $\mathbb{C}$.


text:
Q: Safari lost half my extensions and passwords after a system crash The crash was logged into console
and it caused logout from my system.
After I've logged in again Safari lost most of my passwords and extensions.
I've already looked at this and it didn't help.
I'm using iCloud Keychain and I've checked on my phone - the passwords are still there. I also looked into ~/Library/Safari/Extensions/ and all my extensions are still there, just not visible in safari preferences.
I've tried using Time Machine on ~/Library/Safari/ but it also didn't work.
I have to say that this is very annoying since it happened to me at least 3 times in past 2 years.
1) What can I do to restore all my iCloud passwords?
2) What can I do to restore all my Safari extensions without installing them again one-by-one?
3) What can I do to stop this from occurring again?
I guess 3) is too much to ask for, but I need at least a reliable procedure that can restore everything to the state it was before.
I'm also not the only person affected by this problem - my cousin turned to 1-Password exactly because of this behaviour.

A: As you may have noticed from my question, I was very determined to find a solution and finally I found one. If you have a Time Machine setup then you're lucky. All you need to do is to restore those 4 folders (remember to select all the contents from the backup) to the time before the crash.
~/Library/Safari/Extensions/
~/Library/Keychains
/Library/Keychains
/System/Library/Keychains
(Probably not all are needed, but this worked for me)
Restart and open safari to check that everything is on place. Re-enable Keychain if it was disabled (mine was enabled, but turned to disabled in this process). Enjoy.


text:
Q: what is the difference between any[] and [] in typescript So the first example here works,
protected createGroups(sortedItems: Array<TbpeItem>): any[] {
    let groups: any[] = [];
    return groups;

}

but the second one gives a typescript error:
    type any[] not assignable to type []
protected createGroups(sortedItems: Array<TbpeItem>): [] {
    let groups: any[] = [];
    return groups;

}

A: any[] is an array where the item is of type any. [] is the empty tuple. Tuples are represented in typescript as arrays where the type of each position is known (ex [boolean, number] is a tuple where the first item is a boolean and the second is a number). When checking compatibility for tuples the size has to be the same, so this means nothing but [] is assignable to the empty tuple type. Read more about tuples here


text:
Q: Trying to reduce run time of GAS code that copies sheets from multiple spreadsheets into a merged master version OK, so my main question here is if I can reduce the time it takes for this script below to run--it takes on average 8 minutes, 5-6 of which is just from copying sheets into another spreadsheet and pasting their original display values over them.
The purpose of this is to have vendor sheets from four different spreadsheets totaled in alphabetical order for sending as-is or for printing. I already researched trying do use PDFs instead, but have not been able to find a way to be able to print in a specific order with the resources I have--which do not include Adobe premium or access to printers for something like powershell scripts, which I do not know anyway. (Printing a folder of files does not actually print in sequential order, unfortunately, so generating PDFs of each sheet does not give me an option to print in alphabetical order.)
So, my workaround is to get an array of the four source spreadsheets, loop through those with another loop that goes through each sheet, and for each sheet make a copy to the merge spreadsheet, and then get and paste over each sheet with the display values as there would otherwise be issues with formulas not referencing. Then it calls other functions to rename the sheets without "Copy of " on them and then to place them in alphabetical order. For ongoing use, it starts by deleting all the old sheets except for an Index sheet from the merged spreadsheet.
Is there any way to reduce the number of calls? I looked into while loops, but it's different in that a lot of the "data" I'm moving is actual entire sheets, and I need their formatting as well. I considered just inserting the same number of sheets as I would be copying, and then repeating copying the same format which they all have, but that hits into an issue with the names--there can sometimes be duplicate named sheets between the source spreadsheets which have to be allowed in, and copying in just makes additional ones have a number at the end. That is fine, but I cannot set the names of the sheets before they are in the merged spreadsheet due to this, unless I can somehow check for duplicate sheet names and add "1", "2", etc, to them to allow them in.
Is the time running this just inevitable for this process, or can I speed it up?
//https://stackoverflow.com/questions/58834873/copy-google-sheet-values-to-another-google-spreadsheet-and-create-new-sheet-with?rq=1
//https://stackoverflow.com/questions/36758479/google-apps-script-to-iterate-through-a-list-of-spreadsheet-ids-and-copy-range

//Global variables. Runs from the merging spreadsheet, and the IDs of the four source Vendor spreadsheets
var mergeSpreadsheet = SpreadsheetApp.getActive();
var indexSheet = "Index";  //global for alphabetzing script
var monthly732 = '1TLH8HencpyH-4pDkQ1LetTErRxqYjh4gYC0XDdQxSVM'
var monthly827 = '19UfhUAvpFi0UJBF-rQoc4LWcL20-79nRltbSL-Wpj0A'
var quarterly732 = '1BRhoO_GcEoBmV_SoaV2xkw9BjgasAX3CorKxgWuEd2I'
var quarterly827 = '1JaAQtRIiCaQjO_A5S0p-VjHk8LUXExmqOYo75LxWf58'

//main function
function mergeTest2(){

deleteAllSheets();  //calls function at end of script to delete old sheets from merged spreadsheet

//Array of source spreadsheets for looping through
 var idList = [monthly732, monthly827, quarterly732, quarterly827];

 for (var i = 0; i < idList.length; i++){

//get sheets from each source spreadsheet
  var allsheets = SpreadsheetApp.openById(idList[i]).getSheets();

//For each spreadsheet, iterate through sheets except for Index and Template
// Stop iteration execution if the condition is meet.
  for(var s in allsheets){
    var sheet = allsheets[s];
    if(
       (sheet.getName() == "Index") ||
       (sheet.getName() == "Template") ||
       (sheet.getName() == "Totals")
      ) continue;

//For each sheet, copyTo merged spreadsheet, get original's display values and paste them on the copy
//Using copyTo to get format of sheet, and allow for duplicate sheet names added

var mergeSheet = sheet.copyTo(mergeSpreadsheet);

//Getting display values to override formulas to avoid REF errors
var sValues = sheet.getDataRange().getDisplayValues();
  mergeSheet.getRange(1,1,sValues.length,sValues[0].length).setValues(sValues);

  } //allsheets, end of for-loop for sheets within a spreadsheet

} //end for-loop of array of spreadsheets

//Get numbers of sheets from each spreadsheet for comparing to make sure all applicable ones were copied
//formulas set in Index page for comparing applicable sheets from sources (Vendors only) to make sure they equal merged Vendor sheets at the end
 var index_sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(indexSheet);
    index_sheet.getRange("C2").setValue(SpreadsheetApp.openById(monthly732).getNumSheets());
    index_sheet.getRange("D2").setValue(SpreadsheetApp.openById(monthly827).getNumSheets());
    index_sheet.getRange("E2").setValue(SpreadsheetApp.openById(quarterly732).getNumSheets());
    index_sheet.getRange("F2").setValue(SpreadsheetApp.openById(quarterly827).getNumSheets());
    index_sheet.getRange("B2").setValue(mergeSpreadsheet.getNumSheets());

//Loggers used for testing, replace with getNumSheets above in final
    Logger.log(SpreadsheetApp.openById(monthly732).getNumSheets());
    Logger.log(SpreadsheetApp.openById(monthly827).getNumSheets());
    Logger.log(SpreadsheetApp.openById(quarterly732).getNumSheets());
    Logger.log(SpreadsheetApp.openById(quarterly827).getNumSheets());
    Logger.log(mergeSpreadsheet.getNumSheets());

slicerOfNames(); //call slicer function below for removing "Copy of " from sheet names.

sortSheetsByName(); //call function to put sheets in alphabetical order

} //end mergeTest2 main function

//Function to get sheet names except for Index, or that all have "Copy of " in name, and slice(8)
function slicerOfNames(){
  mergeSpreadsheet.getSheets().forEach(function(sheet) {
    var sheetName = sheet.getSheetName();
    if (sheetName.indexOf("Copy of ") == -1) {
      Logger.log(sheetName);
    } else {
      sheet.setName(sheetName.slice(8));

    } //end if/else
  }) //end function(sheet)
} //end slicer function

//Function for alphabetical ordering of sheets within merged spreadsheet

function sortSheetsByName() {
  var aSheets = new Array();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var allsheets = ss.getSheets();
  for (var s in allsheets)
  {
    var ss = SpreadsheetApp.getActive();

    var sheet = allsheets[s];
    if(
       (sheet.getName() == indexSheet)
      ) continue;
    aSheets.push(ss.getSheets()[s].getName());
  }
  if(aSheets.length)
  {
    ss.getSheetByName(indexSheet).activate()
    ss.moveActiveSheet(1)
    aSheets.sort();
    for (var i = 0; i < aSheets.length; i++)
    {
      var theSheet = ss.getSheetByName(aSheets[i]);
      if(theSheet.getIndex() != i + 2){
        ss.setActiveSheet(theSheet);
        ss.moveActiveSheet(i + 2);
       } //end if statement
    } //end for-loop
  } // end if(aSheets.length)
 }//end alphabetization function

//Function to delete old sheets from merged spreadsheet at the beginning of the script
function deleteAllSheets() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
    var result = SpreadsheetApp.getUi().alert("This will delete all sheets except the Index, are you sure?", SpreadsheetApp.getUi().ButtonSet.OK_CANCEL);
  if(result === SpreadsheetApp.getUi().Button.OK) {
    var sheets = ss.getSheets();
    for (i = 0; i < sheets.length; i++) {
    switch(sheets[i].getSheetName()) {
    case "Index":
    break;
    default:
    ss.deleteSheet(sheets[i]);}}

  } else {
    SpreadsheetApp.getActive().toast("Sheets not deleted");
  }

} //end delete sheets function

A: In your code, it looks you set values of disjoint ranges five separate times, which is very expensive. You could combine these into one line like combined_range.setValues(2D_array). If you are worried about overwriting any existing data, use combined_range.getValues(), and then manipulate the returned 2D array using Apps Script prior to setting.
Following a similar philosophy, logging can be made much more efficient as well; in general, consider implementing a hash map to store and organize the results of  frequent spreadsheet calls. Alternatively, variables can also otherwise be used to condense, hasten, and improve overall readability.


text:
Q: functional programming javascript chain filter operation defaults Is there a way to filter an array and if it returns no objects default to the default option in a single chain?
e.g.
[1,2,3]
    .filter(isDivisibleByTen)
    // otherwise return whatever

I could write it like so
const result [1,2,3].filter(isDivisibleByTen)
result ? result [0]

A: Here's what I think you are looking for in one line, but if a result is false, filter() will return nothing. In Demo 1 filter() is used. In Demo 2 map() is used with a return of an arbitrary value of "default" as the alternate return.

Demo 1

console.log([1, 21, 30].filter(a => a % 10 === 0));

Demo 2

console.log([1,21,30].map(a => a % 10 === 0 ? a : 'default'));

A: You could try reduce(). This allows you to pass an initial value (the default return value) and then add values to the return array if they pass the test. So if no values pass the test, the function will return the default value.

console.log([1,21,30].reduce((t, v) => { return v % 10 === 0 ? (t = 'default' ? [v] : t.concat(v)) : t; }, 'default'))

    console.log([1,21,35].reduce((t, v) => { return v % 10 === 0 ? (t = 'default' ? [v] : t.concat(v)) : t; }, 'default'))

A: Solution 1. Without side effects.
Maybe reduce is the only Array method that provides the array and can return an arbitrary value so you can use it:
[1,2,3]
    .filter(isDivisibleByTen)
    .reduce((_1, _2, _3, array) => array, 'defaultValue');

This solution is a bit processor-time-wasting (loops over the array without a benefit), but it can be combined with any chain easily.
Solution 2. The elegant one.
You can add a custom method to the Array prototype to make it available in a chain:
Array.prototype.filledOrDefault = function(defaultValue) {
    return this.length ? this : defaultValue;
}

[1,2,3]
    .filter(isDivisibleByTen)
    .filledOrDefault('defaultValue');

This solution is not recommended because it modifies a global value (Array) which is used by other scripts on a page.

A: I'll add a more verbose option here. This solution makes use of 3 pure functions, and then combines it in a pipeline. This is pretty typical of functional programming, and has the side benefit of being able to test the functions in isolation to make sure they do exactly what you want.
(As a sidebar other languages such as elixir make the chaining more syntactically pleasing, but I digress)

const defaultValue = "foobar";

const isDivisibleBy10 = n => n % 10 === 0;

const enforceDefault = numbers => numbers.length ? numbers : [defaultValue];

const unpackSingleton = numbers => numbers.length === 1 ? numbers[0] : numbers;

const pipeline = numbers =>
  unpackSingleton(
    enforceDefault(
      numbers.filter(isDivisibleBy10)
    )
  )

console.log(pipeline([2])); // no matches so returns default
console.log(pipeline([20])) // one match so returns the item

console.log(pipeline([1, 20, 10, 3])) // general case


text:
Q: Is there a way to create cascading dropdown without using list? I want to know is there a way to create a cascading dropdown menu in sharepoint without using a list.

A: You can supply the drop down values as part of the drop down properties and then use rules to populate the related drop downs. I gather it will be a fairly comprehensive rule set as you will have to check on each item select and populate the corresponding drop down values.

A: You can bind your dropdown to any other data source (XML file, database, table, embedded default values), through receive data connection. And if you have done dropdowns you should have seen this option after clicking  Get choices from external data source > Add > Next
There is no difference in procedure between sharepoint lists and other data sources ...


text:
Q: Load text from local .txt file into html textarea using JavaScript I have a <textarea> element and a button that calls a loadFile() JavaScript function. I want this function to allow me to load the text from a .txt file on my local machine into the textarea. Any help with this would be greatly appreciated!

A: You can use the File and FileReader objects to read local files.
You can use an input element with type="file" to allow the user to select a file.
<input id="myFile" type="file"/>
<textarea id="myTextArea" rows="4" columns="20"></textArea>

After the user has selected a file, you can get the File object from the input element. For example...
var file = document.getElementById("myFile").files[0];

You can then use a FileReader object to read the file into the text area. For example...
var reader = new FileReader();
reader.onload = function (e) {
    var textArea = document.getElementById("myTextArea");
    textArea.value = e.target.result;
};
reader.readAsText(file);

A: I found a old topic about this:
How do I load the contents of a text file into a javascript variable?
Have you read the last answer already? This works with a div instead of a textbox, but you could adapt the code a bit.
In the last piece of the last commenters post you could change this line:
document.getElementById("id01").innerHTML = out;

to:
document.getElementById("textbox01").innerHTML = out;

And in your HTML:
<textarea name="textbox01">Enter text here...</textarea>

Result:
function loadFile() {
    var xmlhttp = new XMLHttpRequest();
    var url = "file.txt";

    xmlhttp.onreadystatechange = function() {

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var myArr = JSON.parse(xmlhttp.responseText);
            myFunction(myArr);

            console.log("xmlhttp Request Asepted");
        }

    }

        xmlhttp.open("GET", url, true);
        xmlhttp.send();

        function myFunction(arr) {
            var out = "";
            var i;
            var row = 0;

        for(i = 0; i < arr.length; i++) {
           // console.log( arr[1].data); change data to what every you have in  your file
           // out +=  arr[i].data + '<br>' + arr[i].data2 ;
            document.getElementById("textbox01").innerHTML = out;

        }

    }
}


text:
Q: New version of Matlab (R2017a), won't open video files (.avi) that my old version (R2014a) can run fine I'm using VideoReader as follows:

video_object=VideoReader('filename.avi');

This runs totally fine on R2014a, but the same code, for the same video files and on the same operating system, returns the following error in R2017a:
Error using VideoReader/init (line 619)
The file does not appear to have any video data.
Error in VideoReader (line 172)
            obj.init(fileName);
The video files I'm trying to open are encoded with the codec 'Microsoft video 1'. A random other video file, namely 'rhinos.avi', seems to open just fine.
This is on Mac (Sierra).
It seems a very strange problem to me. Is it maybe possible that certain video codecs were removed form the new version of Matlab? I've been unable to find information about this. Maybe other have had the same problem? Is it possible to install codecs manually?
Thank you in advance!


text:
Q: Unable to open 'osteram.tcc' and 'ios_base.h' when debugging in VS code I'm on Manjaro, and I have followed the VS code guide to install C++ on Linux and it have successfully build and ran a hello world app and other apps that I have build, but the problem I have discovered is that whenever I'm debugging and hit "Step into" cout or cin I get the following error message:
Unable to open 'ios_base.h': Unable to read file '/build/gcc/src/gcc-build/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/ios_base.h' (Error: Unable to resolve non-existing file '/build/gcc/src/gcc-build/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/ios_base.h').
Unable to open 'ostream.tcc': Unable to read file '/build/gcc/src/gcc-build/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/ostream.tcc' (Error: Unable to resolve non-existing file '/build/gcc/src/gcc-build/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/ostream.tcc').
and when I click on Create File, the following message shows up:
Unable to write file '/build/gcc/src/gcc-build/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/ostream.tcc' (NoPermissions (FileSystemError): Error: EACCES: permission denied, mkdir '/build')
Unable to write file '/build/gcc/src/gcc-build/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/ios_base.h' (NoPermissions (FileSystemError): Error: EACCES: permission denied, mkdir '/build')
I have searched for the ios_base file and ostream file and found them in /usr/include/c++/11.1.0/, and I know I can run cout and cin operation with no problem it's just trying to step into them causes the error.
Here is also my Task.json file because I have saw some post talk about it.
    "version": "2.0.0",
    "tasks": [
      {
        "type": "shell",
        "label": "g++ build active file",
        "command": "/usr/bin/g++",
        "args": ["-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}"],
        "options": {
          "cwd": "/usr/bin"
        },
        "problemMatcher": ["$gcc"],
        "group": {
          "kind": "build",
          "isDefault": true
        }
      }
    ]
  }```


text:
Q: not able to save one shipping address and one billing address in Django In My Customer app i am not able to save billing and shipping address Boolean Field correctly in admin models.I will explain it with screen shot
First Step:
I can Add Multiple Address in Admin for one customer, So here i have address A and address B
When i Check on Billing address form address A and Shipping address from address B it is saved successfully condition 1 screen shot
def check_billing_shipping(self):
   if self.billing_address:

       temp = Address.objects.filter(billing_address=True, customer=self.customer)
       for key in temp:
           if key.billing_address:
               key.billing_address = False

               key.save()

   if self.shipping_address:
       temp = Address.objects.filter(shipping_address=True, customer=self.customer)
       for key in temp:
           if (key.shipping_address):
               key.shipping_address = False

               key.save()

 super(Address, self).save()

def save(self, *args, **kwargs):
    super(Address, self).save(*args, **kwargs)

    self.check_billing_shipping()

Same way if interchanged it i.e When i Check on Shipping address form address A and Billing address from address B and then save  it discards all checked from Address A
after save screen shot
we want to user to select one shipping and one billing address for one customer . Also if u don't get a question please ask again i will explain it in better way I have inline customer and address class in admin.py

A: I Found Out the solutions
i just added new class and ChainedForeignkey to customer address,
and inline it in admin.py so i have to seprate drop downs for shipping and
billing address
ScreenShot
in case someone has same problem