text:
Q: want to additional dropdown menu with Jquery - cant make it work properly using clone() I'm new to coding so please be gently - here goes:
I'm having a bit of a problem and was hoping someone could help.
I have a dynamic drop down menu for people to choose subjects and I would like to repeat this selection drop down to allow people to add more subjects. I can clone #subjselect and prepend it to #another but then if they click 'Add another' it will insert 2 copies of the dropdown box (and increase exponentially from there). I'm pretty sure this is to do with the clone, but I can't work out how to just add one at a time. Here is the code:
HTML:
            Primary  Subject

    <select id="subject">
    <option value="">Subject</option>
    <option value="math">Math</option>
    <option value="science">Science</option>
    <option value="languages">Languages</option>
    <option value="humanities">Humanities</option>
    <option value="econ">Economics/Finance</option>
    <option value="gmat">GMAT</option>
    <option value="sat">SAT</option>
    </select>

    <select id="topic">
    <option value="">Topic</option>
    </select>

Add Another Subject

JQuery:
function Repeat(obj){
    var currentDiv = $(obj).prev('div');
    var dropDown = currentDiv.find('select');
    dropDown.clone().prependTo('#another');
    }

A: Looking at your html markup, I think it should be prev('div') rather then parent('div'). Since the link is outside the div .select here:
function Repeat(obj) {
    var currentDiv = $(obj).prev('div');
    var dropDown = currentDiv.find('select');
    dropDown.clone().prependTo('#another');
}


text:
Q: Initialize my form with redux-form I am facing trouble with initializing my form with redux-form and the 'initialValues' props. I read a lot posts (for instance here) and I don't manage to get it work...
I see that my initialValues is properly set but my fields are not updated with it... Maybe the issue is in my renderBasicField function but I don't know how to fix this.
Otherwise it could also be something like the prop is not populated yet when the component is rendered... But I don't know what to do to make it work as I must rely on mapStateToProps to feed it.
I saw a lot of post about this kind of issues and unfortunately for me I already set up the enableReinitialize property to true :)
Here is my code :
// My component
class ProfileForm extends React.Component {

  render () {
    console.log(this.props);
    const { handleSubmit } = this.props;
    const messageClassname = this.props.errorMessage !== undefined ? stylesShared.errorMessage : this.props.confirmationMessage !== undefined ? stylesShared.confirmationMessage : '';
    return (

            <form onSubmit={handleSubmit(this.props.onSubmitProfileUpdate)}>

Votre profil

                {this.props.errorMessage &&
                {this.props.errorMessage}
                }
                {this.props.confirmationMessage &&
                {this.props.confirmationMessage}
                }

                <Field name='firstname' type='text' label='Prénom' component={renderBasicField} />

                <Field name='lastname' type='text' label='Nom' component={renderBasicField} />

                <Field name='email' type='email' label='Email' addon='@' component={renderBasicField} />

                <Field name='telephone' type='text' label='Téléphone' component={renderBasicField} />

                <Field name='ranking' className='input-row form-group form-control' options={this.getTennisRankingsOptions()} type='select' component={renderSelectField} />

                <Field name='city' type='text' label='Ville' component={renderBasicField} />

                <button className='btn btn-info btn-lg center-block' type='submit'>Mettre à jour</button>

            </form>

    );
  }
}

const reduxFormDecorator = reduxForm({
  form: 'profile',
  enableReinitialize: true,
  validate: validateProfileForm
});

const mapStateToProps = (state) => {
  return {
    initialValues: state.userConnection.loadProfile.user
  };
};

const reduxConnector = connect(
  mapStateToProps,
  null
);

export default reduxConnector(reduxFormDecorator(ProfileForm));

And the code to render my field :
// My renderFunction
export const renderBasicField = ({input, meta: {touched, error}, label, type='text', id, addon, styleClasses, handleChange, controlledAsyncValue}) => {
  const inputStyles = getInputStyles(input.value, touched, error);
  if (controlledAsyncValue !== input.value) {
    input.value = controlledAsyncValue;
    input.onChange(input.value);
  }
  return (

    {displayInputLabel(inputStyles.input.idInput, label)}

      {addon && {addon}}
      <input
        {...input}
        className={classNames(styles.basicInputField, styleClasses)}
        id={id}
        value={input.disabled ? '' : input.value}
        onChange={getOnChangeAction(input.onChange, handleChange)}
        placeholder={label}
        type={type}
        aria-describedby={inputStyles.input.ariaDescribedBy}
      />

    {touched && error &&
    displayErrorMessage(error)}

);
};

I am wondering if I am ignoring the initialValue with my custom renderBasicField function but in that case, I would I retrieve this value to set my input ?
Thanks a lot for your help ! :)

A: Try to switch connect and form decorator. It should helps.
export default reduxFormDecorator(reduxConnector(ProfileForm));

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL Query with 2 or more Filters I just want to ask if it is possible to have 2 filters in one mysql query?
Can you show some examples?

A: Try like this
SELECT *
FROM Table1
WHERE Cond1 = "value1" AND Cond2 = "value2"

Or:
SELECT *
FROM Table1
WHERE Cond1 = "value1" OR Cond2 = "value2"

MySql Where Clause


text:
Q: can anyone tell me whats wrong in my code of binary search tree insertion i am trying to insert elements in binary search tree , without recursion (but this code is just inserting the root element and no other elements ) .i don't know whats wrong , this code should work , but its not , i am not good with reccursion and every code on internet was with recursion for inserting elements in the binary search tree. can anyone tell me , whats wrong and how should i correct it??
here is the code
<#include<bits/stdc++.h>
using namespace std;
struct node
{
  int data;
  node *left;
  node *right;
}*root=NULL;
void insert(int data)
{   node* temp=new node;

  node *ptr=root;
  temp->data=data;
  temp->left=NULL;
  temp->right=NULL;
  if(ptr==NULL)
    {
      root=temp;

    }
  else
    {
      while(ptr!=NULL)
        {
          if(data<=(ptr->data))
            {ptr=ptr->left;}
          else{
            ptr=ptr->right;
          }
        }//while loop ends here so that i get the ptr to be

      ptr=temp;
    }
}
void disp(node* ptr)
{
  if(ptr==NULL)
    return ;
  disp(ptr->left);
  cout<<ptr->data<<endl;
  disp(ptr->right);
}

int main()
{
  insert(10);
  insert(11);
  insert(23);
  disp(root);

}

A: You never write in you tree, only in local var ptr. In your code, you should insert temp when you find a NULL child.
void insert(int data)
{
  node* temp=new node;
  node *ptr=root;
  temp->data=data;
  temp->left=NULL;
  temp->right=NULL;
  if(ptr==NULL)
    {
      root=temp;
    }
  else
    {
      while(1)
        {
          if(data<=(ptr->data)) {
            if(ptr->left) ptr=ptr->left;
            else {ptr->left=temp; break;}
          }
          else{
            if(ptr->right) ptr=ptr->right;
            else {ptr->right=temp; break;}
          }
        }//while loop ends here so that i get the ptr to be
    }
}


text:
Q: Call web service from SQL CLR? I have a SQL Server 2012 stored procedure that returns a table. I have to modify that SP to add an additional value to the returned table. Unfortunately, that added value comes from a call to a web-service. From my research, I gather the main ways to do this are using the OLE Automation procedures (sp_OA...) in SQL, or a SQLCLR stored procedure. Given the security context in which the sp_OA... procedures run, the single return value is a VARCHAR(10) registration key, and calls to the service are few (ten to twenty per hour), I'm guessing the SQLCLR method is the way to go. Also, the web-service is hosted on our intranet, and not accessible to the outside world.
Is there a better way to accomplish what I need? Better meaning more performant, better security, easier to code and maintain

A: Please do not use the sp_OA* OLE Automation procedures. They do not appear to be officially deprecated, but SQLCLR replaces both the OLE Automation procedures as well as Extended Stored Procedures.
Yes, this can be done easily enough in SQLCLR. You can find examples on using WCF (as shown in @CodeCaster's answer) or using HttpWebRequest / HttpWebResponse (I have more info in this answer: How to invoke webservice from SQL Server stored procedure ). Also, please be aware that sometimes you will need to also add the Serialization Assembly: Using Webservices and Xml Serialization in CLR Integration
Coding and Maintenance
Web Services provide a nice API, but if you change the structure you will have to recompile and redeploy at least some part of this. Assuming the information being exchanged is simple enough, I tend to think that treating this as a standard web request adds a lot of flexibility. You can create a generic web request function (scalar or TVF) that takes in the parameters and URI and constructs the properly formatted XML request and sends it to the URI. It then gets the response and merely returns the XML. So you shift a little bit of the responsibility since you now need to parse the XML response rather than getting a nice object. But, XML is easy to parse in SQL Server, and you can re-use this function in any number of places. And, if the remote service is ever updated, updating a Stored Procedure to change the query string that is passed to the Web Service and/or change the parsing of the XML response is a simple ALTER PROCEDURE and should be easy to test. No need to recompile / redeploy the SQLCLR Assembly.
Security
Regardless of how "pure" of a web service call you want, the main thing, security wise, is to NOT be lazy and turn TRUSTWORTHY ON (as also shown in the linked page from @CodeCaster's answer, and unfortunately most other examples here on the interwebs). The proper way to make this secure is to do the following:

*

*Sign your Assembly

*In the [master] database, create an Asymmetric Key from the DLL of your Assembly.

*Also, in [master], create a Login from that Asymmetric Key

*Grant your new Login the EXTERNAL ACCESS ASSEMBLY permission

*Create your Assembly with a PERMISSION_SET of EXTERNAL_ACCESS, not UNSAFE
For more details on:

*

*using SQLCLR in general, please visit: SQLCLR Info

*using Module Signing, please visit: Module Signing Info

*not using TRUSTWORTHY ON, please read: PLEASE, Please, please Stop Using Impersonation, TRUSTWORTHY, and Cross-DB Ownership Chaining

A: You can definitely call a WCF service using SQL CLR.
If you don't want that, you could write a Windows Service in C# that watches or polls the table for changes. Depending on how you implement this service, the reaction to a new record would be near immediate. Read also How to notify a windows service(c#) of a DB Table Change(sql 2005)?.
Then you can perform the service call from C#, perform the required work and store the result in the column.
When you require more information, for example extra variables obtained during the exchange, you could introduce a new table for storing that, and the actual result you're interested in. Then join that table from the table in your question.


text:
Q: Seagull testing with SCTP I'm having an issue with SCTP requests in Seagull.
Here's the important part:
  <define entity="transport"
    name="sctp-trans-layer"
    file="libtrans_extsctp.so"
    init-args="type=tcp">
  </define>

  <define entity="channel"
    name="channel-1"
    protocol="diameter-v1"
    transport="sctp-trans-layer"
    open-args="mode=client;dest=127.0.0.1:3868;source=172.17.0.1:5005">
  </define>

I tried couple of different things (including changing the "type=sctp", file="libtrans_ip.so"). I get the following error:
ERROR: Kernel SCTP seems to be available! You cannout use sctplib and kernel SCTP simultaneously!
I tried to find sctplib in my packages to remove it but the only thing I found was libsctp-dev and libsctp1. Removing them didn't change a thing.
Any suggestions?


text:
Q: Communication from embedded Custom LWC to parent FlexCard We have a requirement in which we embed a custom LWC into a Vlocity FlexCard. We can communicate from Parent FlexCard to embedded child custom LWC. But couldn't figure out how to communicate back from embedded child custom LWC to the parent FlexCard. Is there any reference for this , something similar to sending a custom event from a child LWC to parent LWC

A: The Pubsub Component enables data sharing between components. You need to import pubsub component in your LWC from the Vlocity namespace. The namespace will vary based on your package.
import { LightningElement} from 'lwc';
import pubsub from 'vlocity_ins/pubsub';//importing pubsub component

export default class ChildLWC extends LightningElement{
    //Variable to store our message
    text;

    connectedCallback() {
        //Initializing message in connected callback
        this.text = '';
    }

    //On click handler for Send to Parent button
    handleClick(){
        //Publishing showtext event to ParentFlexCard channel
        pubsub.fire("ParentFlexCard", "showtext", {text: this.text});
    }

    //On change handler for text input
    handleChange(event){
        this.text = event.target.value;
    }
}

Following is the syntax for the fire method :

pubsub.fire("Channel_Name", "Event_Name", payload);

In order to subscribe to the events published by components, your Flexcard will need an event listener. In Design View, click on Setup tab and scroll to EVENT LISTENER option. Click on Add New.

Select Event Type as Pubsub and Event Name as showtext. Channel Name is the name of your Flexcard(ParentFlexCard) by default.

Now you need to define the action to be taken once "showtext" event is received. Select Action Type as Card, Type as Set Values. Click on Add New to add a new Key Value pair. For example, if you want to update "Message" key in your Data JSON, set Key as Message and Value as {action.text}. Here "text" is a key in the message object sent from child LWC. Click Save.


text:
Q: Composer: Can only install one of: minishlink/web-push[v4.0.0, dev-master] I'm trying install web-push (https://github.com/web-push-libs/web-push-php) in Ubuntu 14 but with a execute composer require minishlink/web-push I get the next error:
Problem 1:
 - Can only install one of: minishlink/web-psuh[v4.0.0, dev-master].
 - Can only install one of: minishlink/web-psuh[v4.0.1, dev-master].
 - Can only install one of: minishlink/web-psuh[v4.0.2, dev-master].
 - Installation request for minishlink/web-push dev-master -> Satisfiable by minishlink/web-push[dev-master].
 - Installation request for minishlink/web-push ^4.0 -> satisfiable by minishlink/web-push[v4.0.0, v4.0.1, v4.0.2].

Composer.json
    {
  "name": "minishlink/web-push",
  "type": "library",
  "description": "Web Push library for PHP",
  "keywords": ["push", "notifications", "web", "WebPush", "Push API"],
  "homepage": "https://github.com/web-push-libs/web-push-php",
  "license": "MIT",
  "authors": [
    {
      "name": "Louis Lagrange",
      "email": "lagrange.louis@gmail.com",
      "homepage": "https://github.com/Minishlink"
    }
  ],
  "require": {
    "minishlink/web-push": "^4.0"
  },
  "require-dev": {
    "phpunit/phpunit": "^7.0"
  }
}


text:
Q: mysql concat regexp word boundary and quote Here is my query
SELECT producer FROM producers WHERE producer REGEXP CONCAT('[[:<:]]', 'dell\'', '[[:>:]]')

I replaced mysql like with this to use word boundary from another example here. But now I am having a problem with escaped apostrophe, it doesn't find the dell' in the database even if there is a match.

A: select count(*) from (select 'dell\'' as c) t where c regexp '[[:<:]]dell\'';        -- -> 1
select count(*) from (select 'dell\'' as c) t where c regexp '[[:<:]]dell\'[[:>:]]'; -- -> 0

So it's the trailing boundary requirement which fails. Which makes sense. Quoting from the docs:

These markers stand for word boundaries. They match the beginning and
  end of words, respectively. A word is a sequence of word characters
  that is not preceded by or followed by word characters. A word
  character is an alphanumeric character in the alnum class or an
  underscore (_).

As ' is not a word character, it cannot be the end of a word, hence [[:>:]] can't match.

A: I created UDF and it solve the issue just give a call to a function you can set prefix, suffix and value depend upon your condition.
DROP FUNCTION IF EXISTS pp$$
CREATE  FUNCTION  pp(Slist varchar(100)) RETURNS char(100) CHARSET latin1
BEGIN
    Declare sregex varchar(100);
    SET slist  = 'G';
    return Concat('[[:<:]]',Slist,'[[:>:]]');
END;


text:
Q: Link to controller index with certain id fails in rails I want to make a back link that will link to the controller index.
<%= link_to 'Back', employee_personals_path%>

It works.
But in index i want to send user id also.
 <%= link_to 'Back', {  :action => "index", :user_id => @user_id},
   {:class=>"btn btn-success"}%>

This works.
Now i want to implement sending user_id by first method
<%= link_to 'Back', employee_personals_path, :user_id => @user_id%>

But it does not works. How can i make it work?

A: You need to pass a parameter to your employee_personals_path function (not to link_to):
<%= link_to 'Back', employee_personals_path(:user_id => @user_id) %>


text:
Q: prime faces jsf pages will not render on linux tomcat but will render on eclipse test env My first time posting so if i break the protocalls I apologise
I have created a project that runs Primefaces with Spring using Eclipse and a tomcat 6 server on windows the application runs perfectly fine, when the application is moved to the "live" server which is a linux box the screens will not display
All the libraries are copied over as they should be, when I try access the url on the linux box with the jsf extention(login.jsf) i recive a 404 error, when i try using the .xhtml extention (login.xhtml) i recive an xml view of the code
my web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <welcome-file-list>
    <welcome-file></welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>myApp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>WEB-INF/applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
  </servlet>
  <context-param>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>server</param-value>
  </context-param>
  <context-param>
    <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
    <param-value>.xhtml</param-value>
  </context-param>
  <context-param>
    <param-name>com.sun.faces.expressionFactory</param-name>
    <param-value>com.sun.el.ExpressionFactoryImpl</param-value>
  </context-param>
  <context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
  </context-param>
  <context-param>
    <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
    <param-value>true</param-value>
  </context-param>
  <servlet-mapping>
    <servlet-name>myApp</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>log4jtLocation</param-name>
    <param-value>/WEB-INF/log4j.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
  <listener>
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
   </listener-class>
  </listener>
  <listener>
    <listener-class>
          org.springframework.web.context.request.RequestContextListener
       </listener-class>
  </listener>
</web-app>

my login.xhtml
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <ui:composition xmlns="http://www.w3.org/1999/xhtml"
          xmlns:h="http://java.sun.com/jsf/html"
          xmlns:f="http://java.sun.com/jsf/core"
          xmlns:ui="http://java.sun.com/jsf/facelets"
          xmlns:p="http://primefaces.org/ui"
          template = "template/template.xhtml">
    <h:head>

    </h:head>
    <ui:define name="body">
    <h:form id="form">

    <p:growl id="growl" showDetail="true" />

          <p:panel>
                <p:panelGrid columns="2">
                        <h:outputLabel value="Username:"/>
                        <p:inputText value = "#{loginUI.username}"/>

                        <h:outputLabel value="Password"/>
                        <p:password value = "#{loginUI.password}"/>

                </p:panelGrid>
                <p:commandButton value="Login" actionListener="#{loginUI.login}" update="growl"/>

          </p:panel>
    </h:form>
    </ui:define>
    </ui:composition>
    [/code]

my faces config file
 <?xml version="1.0" encoding="UTF-8"?>

    <faces-config
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd"
        version="2.1">

         <application>
      <el-resolver>
              org.springframework.web.jsf.el.SpringBeanFacesELResolver
      </el-resolver>
       </application>

    </faces-config>

when i start the tomcat there are no errors in the log
thanks in advance

A: in servlet
<servlet-name>Faces Servlet</servlet-name>

set
<load-on-startup>1</load-on-startup>

and in servlet
<servlet-name>myApp</servlet-name>

set
<load-on-startup>2</load-on-startup>


text:
Q: How to use MySql to get High Speed Performance? I am currently working on MySql database, on which we handle a very big amount of data. Many times we match and delete duplicate or inappropriate data from database, but it takes very long time to execute (sometimes 2 or 3 days).
I want to know about, if there is any method with which we can improve the speed of query execution and get result fast.
Please Suggest.
For Example:
There are two tables, First table has 1 Million records and second table also has 1 Million.
We are matching both tables and deleting data from second table if Match.
That's it.

A: Its kind of a huge question "How to delete faster".
Without any specific description I can advise you to use UNIQUE in your tables to prevent duplication.
If you want an advice about some other DB, then maybe you could switch to some type of no-sql database like Redis, which is incredibly fast, but you need to understand how and where to use it to get most profit from it.
Do you have indexes on the tables you're deleting from?
Do you use any kind sharding?
What engine is used in your tables?
What Mysql version do you use?
Did you try "EXPLAINing" your delete query?
"As of MySQL 5.6.3, EXPLAIN provides information about SELECT, DELETE, INSERT, REPLACE, and UPDATE statements. Before MySQL 5.6.3, EXPLAIN provides information only about SELECT statements."
EDIT
After you added your example of deleting while comparing 2 tables:
I'd still suggest using "explain" and telling us if you use indexes or not.
But anyway instead of straight up "DELETE FROM ..." you could insert into temp table and renaming it afterwards. Like so:
CREATE TABLE tmp LIKE yourtable;
INSERT INTO tmp SELECT <your required data from 2 tables>;
RENAME yourtable TO deleteme, tmp TO yourtable;
DROP TABLE deleteme;

Altough I dont like such workarounds and I'd probably refactor your architecture first.


text:
Q: Task to build react files with Azure Devops from Azure Repos I have created a pipeline to build a folder with react files.
Unfortunately I am unable to perform the "npm run build" coomand.
I tried creating a custom npm task and i put inside it the command "npm run build" but it does not accept it.
Here is the image of my CI pipeline.
Any hint on how to achieve the build task?
here is the yaml that gets generated by the npm custom task :


text:
Q: resolve a cell value inside single-quoted table name selection I have sheets like january february march, which have a known arrangement of values. I also have the month names written out in row 6 in my master table (i.e. A6=january, B6=february) etc. I would like the corresponding cell in row 7 to contain the value from cell E2 in the table named above it, as just like ='january'!E2. However, it does not seem that I can do something like =A6!E2 to resolve the table name dynamically.
Is there a way to escape the single quotes or something, so that dynamic values can be used to select a table?
Thanks!

A: Please try, in A7:
=indirect(A6&"!E2")

INDIRECT


text:
Q: "universe" in set theory and category theory In all applications of the theory of sets, all sets under investigation take place in the context of the universal set $U$. What exactly is the purpose of the universal set in set theory? $U$ is infinite, why do we need to mention this infinite context in regards to set theory?
In category theory is there such a notion of a universe? Would it be the category of categories? I have a feeling that the answer has to do with Russell's paradox, but if you could elaborate that'd be great, I'm a beginner.
Also, is there such a thing as "outside" of a universe?

A: It is convenient to know that if you have a bunch of sets and then do something with these sets (e.g., take their cartesian product), then the object you will get will still be manageable. In other words, we want to know that we can perform lots of convenient operations with sets we like and still remain in the same 'universe' of sets we like. Russele's Paradox demonstrates clearly that this is nothing trivial.
In set theory the universe of sets, or set of discourse, is used in two different ways. Naively, it just specifies a set where all the elements come from when you write $\forall$ or $\exists$. For instance, when talking about real numbers it is usually assumed the set of discourse is $\mathbb R$. In axiomatic set theory one specifies some axioms of set theory and then consideres models of the axioms. A model of the axiom is itself a set whose elements are the sets that the model defines. So, 'set' here is used in two totally different ways. The universe is the set $M$ which is the model of the axioms of set theory. The elements of $M$ are all of the sets that the model allows. The set $M$ itself is, typically, not an element on $M$, thus is not a set in the model.
In category theory it is convenient to know that given a bunch of categories we can perform lots of constructions with them, like forming categories of functors. This means that the underlying set theory we employ should be strong enough to allow for lots of 'big' constructions. Grothendieck introduced the notion of a tower of universes of sets to manage these constructions. This is required since typical categories are big in the sense that their objects do not form a set of the same magnitude as the hom-sets do. For instance, for any two groups $G,H$ the hom-set of all group homomorphisms $\psi:G\to H$ is indeed a set (even if the groups are very big). So, when we define the category $Grp$, each hom-set is just a set, but the class of all groups does not form a set. There is thus a hierarchy, using Grothendieck universes, of sizes for categories and various constructions may transcend the size of the categories it operates on, or it may not, depending on the constructions.
On that note, the category $Cat$ usually refers to the category of all small categories, meaning all categories whose objects form a set (in a fixed level of the tower of universes which is ambient and assumed fixed). Thus, the category $Cat$ itself is not a small category (avoiding such silly paradoxes as the category of all categories containing itself as an object). Instead, $Cat$ is a larger category than any of the categories it contains (which makes sense). $Cat$ is still a manageable object using universes, however, the category $CAT$ of all categories is huge and presents many more difficulties if one really needs to deal with it.
To see the importance of size issues in category theory, recall that a category is called small complete if it has all set-indexed limits, and that a category is a poset if between any two of its objects there is at most one morphism. There are plenty of small complete categories (e.g., $Set$, $Grp$) which are clearly not posets. Interestingly, if one looks at complete categories (i.e., those having all limits, with no size restriction), then any such category must be a poset.

A: What is true is that most mathematical discussion takes places in the context of some set, which is called "the universe of discourse."  You can't have a "universal set;"  Russel's paradox dispatches that notion.

A: In "real" set theory, there is usually no universal set. The reason is that we care about the collection of all sets, and in modern set theory this is not a set. It's a collection which we can define, and we can discuss meaningfully, but it's not a set.
On the other hand, in almost any mathematical application, in particular in logic where we have structures for a language and models of a theory, the universe of discourse is a set. So what we do is we work with respect to that set, rather than the whole universe of set theory.
In category theory there is a problem with the category of categories, and that's the same issue which makes the set of all sets problematic. But there are ways to overcome this issue.
The term universe in category theory, often mean some set theoretical universe which we can see as a set from the point of view of a larger universe, then we can work inside that universe and outside that universe. This allows us to talk about categories whose objects and morphisms are members of that universe, and categories which are too large with respect to the first universe, but are small enough with respect to the second universe.

A: This is an interesting question and, even though it was asked a year ago, will give my answer.
Actually, the question sounds to be about many notions with the same or close name:

*

*Universal set with two meanings: (a) a set, about the subsets of which we discuss, like in case of a Boolean algebra of sets, (b) a set, about the elements of which we discuss, like in the book Elementary "Set Theory with a Universal Set" by Holmes Randall (1998)

*Universe of discourse of a theory $T$ - a collection, which together with some relationships and operations form a model of a theory. In particular, $T$ can be one of many axiomatic set theories. Thus, the notion of "universe" is not used only in set theory.

*Universe as a special kind of set - a set which contains the elements of its elements, and has other properties like it was described by Ittay Weiss above.

Each of these notions manifest differently "in applications". The "rule of thumb" to distinguish between "set" and "universe" is that a universe is a special kind of set.

A: Universe of discourse:
When I started getting into database logic, I often came across the expression "universe of discourse". When I tried to understand what exactly it is really, most answers I found referred to it as "a set". Well it didn't help much to me understanding one concept by naming it another.
So after studying the subject thoroughly, here's what i found :
The universe of discourse is at its core really is a set (wait...what?...but..), but before we dive right into it let's take a step back for a second: the term "universe of discourse generally refers to a collection of objects being discussed in a specific discourse. The concept universe of discourse is generally attributed to De morgan (1846) but the name was used for the first time by George boole (1854). ( boole's definition ).
So now after we know that a universe is a "collection" so to speak,  let's take it up a notch.
To understand best what the universe" is we can bring an example from predicate logic.  In predicate logic we have propositions which  are the "sentences" in the predicate.
For instance, x lives in y is a proposition without values (predicate). But now that we know that a universe is a collection we're able to assign those parameters a range of values that will make the propositions in the predicate a statements in the objects of the universe. This method is called "quantifying" a predicate.  a real life example would be Suppose P(x) is the sentence "x has fur" and the universe of
discourse for x is the set of all animals. In this example P(x) is a true statement if
x is a cat. It is false, though, if x is an alligator}).
So really  a universe is a collection of objects that defines a range of the values.  We can use it  to resolve predicates.
But there's still one more important thing to know.
And that  being a "set".  Now I know that this can get a little confusing, especially because a set in natural language is a very general broad term, so what is a "set" in logic?.
A set is any collection of objects or symbols. The objects in a set will be called element or a number of the set. Sets are usually described using "{}" and inside these curly brackets a list of the elements or a description of the elements of the set. If a is an element of a set A, we use the notation a ∈ A and often say "a in A" instead of "a an element of A". The notation a ∉ A indicates that a is not an element of A and is often read as "a is not in A".
So to summarize a universe is a collection  of sets of interest (discourse).
A set is a subset of the larger set-universe.
Enjoy!


text:
Q: MailingCountry contact field in before insert trigger I have to populate a Contact field programmatically according to the MailingCountry field in the before insert trigger so the contact is created properly. But I noticed that the field MailingCountry on Contact is populated in a weird way in the before trigger context; here's a sample trigger to reproduce the behaviour
trigger TR01_Contact on Contact (before insert, before update, after delete) {
    if(Trigger.IsBefore && Trigger.IsInsert)
    {
        for(Contact c : Trigger.new)
        {
            system.debug(JSON.serialize(c));
            system.debug(JSON.serialize(c.MailingCountry));
        }
    }
}

the output of this trigger is
contacts [{"attributes": {
"type": "Contact"
},
"Show_on_Account_Plan__c": false,
"IsDeleted": false,
"AccountId": "0011800000cLvVmAAK",
"Email": "nb@m.it",
"IsEmailBounced": false,
"DoNotCall": false,
"FirstName": "test",
"HasOptedOutOfEmail": false,
"HasOptedOutOfFax": false,
"SNPCAPIQ__Is_DB_USA_Data__c": false,
"CurrencyIsoCode": "USD",
"Salutation": "Mr.",
"pi__Needs_Score_Synced__c": false,
"OwnerId": "005f4000001LmWJAA0",
"MailingCountryCode": "IT",
"RecordTypeId": "012180000000YrGAAU",
"pi__pardot_hard_bounced__c": false,
"Contact_Summary_Ref__c": "a0318000008OUc8AAG",
"LastName": "test",
"Status__c": "Active",
"Prospecting_Stage__c": "New Contact",
"Opt_in__c": false

and
null

also MailingCountryCode is populated and if I go to the record page after the insertion I can see that MailingCountry is correctly displayed as "Italy"
I need a way to read MailingCountry or a way to retrieve the MailingCountry from the MailingCountryCode. Thanks!

A: If you have enabeled 'State and Country/Territory Picklists' in your org use the below code to get country details.
Please don't add inside for loop.
Schema.DescribeFieldResult fieldResult = User.Countrycode.getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
Map<String,String> countryMap = new Map<String,String>();
for( Schema.PicklistEntry f : ple){
    System.debug(f.getLabel() +'::'+ f.getValue());
    countryMap.put(f.getValue(), f.getLabel());
}

You will get country code from c.MailingCountryCode.
Use countryMap.get(c.MailingCountryCode) to get country name.
Else you may need to used Custom Metadata Type or Custom Setting to store country code and label accordingly and access this whenever as needed.


text:
Q: Why GCC compiles and links two files even if 'extern' is not used? Following are the two separate codes written in two separate files Test1.c and Test2.c. I am not using extern keyword in any file.
//Test1.c
#include <stdio.h>

int a = 1;
int main()
{
    printf("test1 - a val = %d\n",a);
    fn();
    printf("After Return : %d",a);
}

//Test2.c
#include <stdio.h>

int a;
int fn()
{
    printf("test2 - a val = %d\n",a);
    a++;
}

I compiled this code using gcc:
gcc Test1.c Test2.c

It generates the following output:
test1 - a val = 1
test2 - a val = 1

I tried printing address of variable a in both codes. The address is also same.
Now I have following questions:

*

*Does gcc automatically compile and link even if extern is not used?? Here apparently gcc internally does that as I am compiling these two files together.

*Is this behaviour with/without extern keyword is compiler-dependent?

A: This code is undefined behaviour with no diagnostic required.  Test1.c and Test2.c both define an object a with external linkage, which violates C11 6.9/5:

If an identifier declared with external linkage is used in an expression (other than as part of the operand of a sizeof or _Alignof operator whose result is an integer constant), somewhere in the entire program there shall be exactly one external definition for the identifier; otherwise, there shall be no more than one.

Note: "external definition" means a definition at file scope. (C11 6.9/4, 6.9/5).  Some other comments/answers confuse "external definition" with "definition of object with external linkage", or "definition with extern keyword".   static int x = 5; at file scope is an external definition.

As mentioned by Jonathan Leffler in comments, this particular result may be an intentional GCC extension. From C11 Annex J.5.11 "Common extensions" :

There may be more than one external definition for the identifier of an object, with or without the explicit use of the keyword extern; if the definitions disagree, or more than one is initialized, the behavior is undefined.

If gcc implements this extension then it would explain the behaviour you observed.  Presumably "more than one is initialized" in that quote does not count the implicit initializer generated for a tentative definition.


text:
Q: How to use a precomputed distance matrix in Scikit KMeans? I'm new to scikit.
I can't find an example using a precomputed distance matrix in Scikit KMeans.
Could anybody shed a light now this, better with an example?

A: Scikit-learn does not allow you to pass in a custom (precomputed) distance matrix. It can precompute Euclidean distance matrix to speed-up the process, but there's no way to use your own one without hacking the source.


text:
Q: How many ways are there to seat 7 people around a round table, if we regard two arrangements that differ by a rotation as the same? I have to use Burnside's Lemma for this.
What I was thinking is that the group that acts on the set of possible seating arrangements was the rotation group $R_7$.
For the total combinations we have $7!$ since we have 7 persons.
The identity fixes every arrangement so $\mathrm{Fix}(e) = 7!$
Since every person is distinct, every other element of the action does not fix the arrangement, since you would need the heptagon of people to be composed of the same person (like the problems about colored beads on necklaces), therefore $\mathrm{Fix}(r^k) = 0$ where $r \in R_7 \setminus \{e\} $
This covers all the elements of $R_7$, so we end up with
$$\frac{7!}{7} = 6!$$
 possible seating arrangements that don't differ by some rotation.

A: For cicular permutation suppose to fix an element in a circle, then you can permute the others and thus we obtain $(n-1)!$ arrangements.

A: I know nothing about the theorem you mention, but just as if you cut a necklace at a point and count the permutations and then consider the repetitions. Since for "any" given four people in a row, say
$$\color{red}{A}BCD,$$
you can also find $\color{red}BCD\color{blue}{A}$, $\color{red}{C}D\color{blue}{AB},$ $\color{red}{D}\color{blue}{ABC}$, so you have to divide it by
$$(\textrm{number of people}),$$
in short
$$\frac{(\textrm{number of people})!}{\textrm{number of people}}$$


text:
Q: Install php 7 on mac with Homebrew Hi just got a new fresh mac and I want to use the last version of php7.
So I have instal php 7.1 with homebrew successfully. But the php -v command show that I have the 5.6 version witch is the default version installed on mac.
How can I target the new version of php installed with homebrew.
I have followed this tutorial to do it : https://developerjack.com/blog/2016/installing-php71-with-homebrew/

A: You need to set your PATH environment variable to have /usr/local/bin at the start because that is where homebrew puts your installed binaries:
export PATH=/usr/local/bin:$PATH

Put that in your login profile too, so it works on future logins.
You may also need to rehash with:
hash -r

which causes your shell to forget where commands are, so it has to search afresh.


text:
Q: Define a relation for "is contained in" Here is my question (should help with my understanding of this new topic):
Consider two words $x, y $ and say that the word $x$ is contained in the word $y$ if it only uses characters from $y$. Only the characters used in the word are relevant, not their order or frequency.
a) I need to define a relation for "is contained in"
This is what I have attempted (note: I don't claim this is at all accurate - just to show that I have actually tried the question before asking)

*

*Question is saying $x$ is a subset of $y$, therefore $ x \subseteq y$.

*With this I have: $x \subseteq y \iff \forall_{a,b} : (a,b \in x \Rightarrow a,b \in y)$

*$_ax_b \Rightarrow$ $_a y _b$

b) Explain how/what property of a relation is satisfied (is it reflexive, symmetric, transitive or functional)

*

*I was under the impression 'implies' $\Rightarrow$ is transitive. But I'm not sure.

I hope I can pass on the favor and contribute to someone's question soon.
Thanks!

A: Note, $x$ and $y$ being words (or strings of characters) do not quite work the same way as sets.
We have the word "apple" and the word "pale" have the same letters appearing but are technically unequal as words.
One could however reword the relation in terms of sets.
For a word $x$, let the set $X$ be the set $X=\{\text{letters appearing in the word}~x\}$
Similarly for the word $y$ and related set $Y$, as well as the word $z$ and related set $Z$.
We have then the nice intuitive rewording as $x\mathcal{R} y \Leftrightarrow X\subseteq Y$.
We ask which of the special properties of relations are satisfied.

*

*Reflexive:  Is it true that for every word $x$, that $x\mathcal{R} x$?

*

*Yes since $X\subseteq X$ is true for every set $X$, in particular when $X$ is the set of letters for a word $x$.  Since $X\subseteq X$ this implies $x\mathcal{R} x$.

*Symmetric: Is it true that for every word $x$ and word $y$ such that $x\mathcal{R} y$ that you must necessarily also have $y\mathcal{R} x$?

*

*No since it is possible that $X\subsetneq Y$ at which point $Y\not\subseteq X$.  For example, $x$ being the word "top" and $y$ being the word "option".  $y$ has letters appearing in the word which are not letters of $x$, in particular the letters i and n.

*Transitive: Is it true that for every words $x,y,z$ such that $x\mathcal{R} y$ and $y\mathcal{R} z$ that it must follow that $x\mathcal{R} z$?

*

*Yes since $x\mathcal{R} y$ and $y\mathcal{R}z$ implies that $X\subseteq Y$ and $Y\subseteq Z$.  It is known or easily shown that this implies that $X\subseteq Z$ thus implying that $x\mathcal{R} z$.

*Functional: (I rarely see it referred to as such, so this might be the incorrect property.  Let me know if intended something else)  Is it true that for every words $x,y,z$ such that $x\mathcal{R} y$ and $x\mathcal{R}z$ that $y=z$?

*

*No since even with examples with equal related sets, the words themselves could be different.  For example $x=$"top", $y=$"opt, and $z=$"pot".  We have that all three of these are related, but none of them are equal.


text:
Q: Paste as values without Name ranges being copies I want to copy sheet from another file and paste it as values without name ranges being copies from the other file. Following is the code I am using. It is working fine but it also copies name ranges from the other file, which I don't want.
DataFile_1.Sheets(summary_sheet).Copy After:=ThisWorkbook.Sheets("Previous Data->")
        ActiveSheet.Cells.Copy
        ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues
        Application.CutCopyMode = False

Thanks!

A: Try this method instead so it won't copy the named ranges:
'Adjust the Range to fit into your own data
ThisWorkbook.Sheets("Previous Data->").range("A1:P100").value = DataFile_1.Sheets(summary_sheet).range("A1:P100").value


text:
Q: Slow Adobe Flash Pro CS6 I'm trying to make a .swf flash for a game suggestion. I know how Flash works and all, I used it a ton on my other computer, it's just I got a new computer and this one is weird. When I first turn it on it works really, really fast. Than after I use for for 2-5 min I greatly see it got slower. When I turn it on it's at 10/10. After 2 min it's at 8/10 than after 10 min it's 2/10.
I'm running Adobe Flash Pro CS6

*

*Windows 7 x64

*Intel Core i3 540 @ 3.07 3.06 GHz

*12 GB RAM
Does anyone know how to fix this?

A: I am guessing it is probably what you are working on, your history, and probably you undo list. Try changing them to a lower rate. Try lightening your project and its quality as long as you are working on its fundamental features, because you can add details later. Try reducing the size of your history and undo list to a lower capacity and number. (Meaning that you wouldn't be able to do a lot of undos).
Also You might want to make sure that this is the appropriate edition of Adobe Flash Pro CS for your system. (Like it might be better if you tried the X64 edition).


text:
Q: Publish image on facebook user's wall with php Is there a way to send image to a facebook user's wall? To publish texts I use this code:
$arpost = array(
            'message' => $text,
            'access_token' => $token
        );

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($arpost));
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        $result = curl_exec($ch);

        curl_close($ch);

For future generations: http://developers.facebook.com/docs/reference/api/post/ <- param is called picture, so you do it like this:
$args = array(
        'message' => $text,
        'picture' => $link2picture
    );

    $this->_facebook->api('/me/feed/', 'post', $args);

A: Here is a link to doing it in Java... perhaps you can use it for some ideas.
Android - Upload photo to Facebook with Facebook Android SDK
Check the facebook php sdk too. It should be there.
https://github.com/facebook/php-sdk/


text:
Q: How do I calculate the odds of a given set of dice results occurring before another given set? Dice odds seem simple at first glance, but I've never taken a Calculus based statistics course or game theory, and I think I may need to in order to solve some of the things I'm trying to solve. I can hammer out the odds in some of the more straight-forward scenarios, but when it comes to calculating the odds of a series of dice events with variable conditions... I get lost in the numbers. I've tried different, seemingly legit methods... only to return vastly different figures each time.
Casino craps tables have a great variety of bets and hedge bets you can make. Some of the bets you make can sit on the table for half an hour or more, through dozens and dozens of dice throws, waiting on a resolution. It's technically possible (in theory not fact) that some of these bets could go on forever without being resolved. I would really like a decent approach to calculating these odds myself... hopefully by presenting a particular scenario, I can pick up enough tid-bits from your answers to piece together the methodology:

*

*We're throwing two six-sided dice at a time.

*Each side of each dice has equal probability on any given throw.

*There exists a tracking list with the numbers: 2, 3, 4, 5, 6, 8, 9, 10, 11, 12. (Note: 7 is not in this list.)

*When the dice are thrown and their total is a number other than 7, the number is crossed off the tracking list and the dice are rolled again.

*When the dice are thrown and their total is a number that's already been crossed off the tracking list, the dice are rolled again.

*At any point if the dice are thrown and their total is 7, the series is resolved as a loss.

*At any point if all ten numbers are crossed off the tracking list, the series is resolved as a win.

What's the probability of crossing all ten numbers off the list (winning) before throwing a 7 (losing)?
This is the"All or Nothing at All" bonus bet newly popular at many casinos. It pays 175 to 1. There are also "All Small" and "All Tall" bonus bets that pay 34 to 1 for throwing 2 thru 6 or 8 thru 12 respectively before throwing the 7. There's also a "Fire Bet" I'd like to break apart, but the rules are quite different. It will require a new post if I can't cull some new insights from the answers here... Please bear in mind, I'm wanting to know how to calculate conditional dice probability (where instantaneous probability shifts depending on your progression from throw to throw), not just know the odds in this particular case. I've taken mathematics courses up through CalcIII, so I can understand discussions involving limits and summation. Again, I've never takes statistics, probability, or game theory. Sorry for the long post, I know I talk too much....

A: You can compute the probability exactly if you really want (see below), but it's probably not worth it. Instead, you can estimate it to your heart's content by simulation – just run the game many many times, and see how often do you win.
In order to compute the probability exactly, the first step is to find an economical way to describe the state of the game. Naively, there are $2^{10} = 1024$ possible states, but we can reduce it to $3^5 = 243$ by grouping the numbers into pairs: $(2,12),(3,11),(4,10),(5,9),(6,8)$. The state identifies how many numbers in each pair are crossed.
Now form a $243\times 243$ transition matrix $A$ in which $A_{st}$ is the probability to move from state $s$ to state $t$. The probabilities out of state $s$ don't sum to $1$ since it's possible to lose the game. We assume that once at the winning state $W$, the next move always loses.
Let $v_I$ be the indicator vector of the initial state, and $v_W$ the indicator vector of the winning state. The probability to win in exactly $n$ moves is $v'_I A^n v_W$, and so the winning probability is
$$ \sum_{n=0}^\infty v'_I A^n v_W = v'_I \sum_{n=0}^\infty A^n v_W = v'_I (I-A)^{-1} v_W. $$
You can write a program that computes the matrix $A$ (with rational entries), and then use a linear algebra package that supports rational numbers to calculate the exact probability. It could turn out the the exact probability is a very complicated number – with very large numerator and denominator, but the computer can probably deal with it given enough time.
Update: The exact winning probability is
$$ \frac{126538525259}{24067258815600} \approx 0.00525770409619644.$$
This number agrees with the simulation results by both myself and Michael.
Note that the matrix in question is triangular, so the computation is pretty fast. We can interpret the matrix $I - A$ in the following way: $(I-A)_{ss}$ is the probability of losing while at state $s$, and $(I-A)_{st}$ is minus the probability of moving from $s$ to $t$; we assume that after reaching the winning state, we immediately lose.

A: Seems like a version of the (difficult) coupon collector problem with unequal probabilities.  You might want to simulate it.  Here are some exact results on simplified versions of the problem:
1) Suppose all 11 choices $\{2, \ldots, 12\}$ have equal probability.  The probability of getting all non-7 numbers before seeing "7" is then the probability that 7 is the last number to be seen.  Since all 11 numbers have an equal chance of being the "last to be seen," this probability is $1/11$.  It can also be calculated as:
$$ \left(\frac{10}{11}\right)\left(\frac{9}{10}\right)\left(\frac{8}{9}\right)\cdots \left(\frac{1}{2}\right) = \frac{1}{11} $$
2) Suppose the chance of getting $7$ is $1/6$ (which it really is), but pretend all 10 other numbers have equal probability of $(5/6)\frac{1}{10}$. The probability of getting 7 last is:
$$ \left(\frac{5}{6}\right)\left(\frac{(5/6)(9/10)}{1/6+(5/6)(9/10)}\right)\left(\frac{(5/6)(8/10)}{1/6+(5/6)(8/10)}\right)\left(\frac{(5/6)(7/10)}{1/6+(5/6)(7/10)}\right)\cdots\left(\frac{(5/6)(1/10)}{1/6+(5/6)(1/10)}\right) $$
This simplifies to:
$$   \left(\frac{5}{6}\right)\left(\frac{1}{\frac{2}{9}+1}\right)\left(\frac{1}{\frac{2}{8}+1}\right)\left(\frac{1}{\frac{2}{7}+1}\right)\cdots\left(\frac{1}{\frac{2}{1}+1}\right) = \frac{1}{66}   $$
3) The true answer:  The true answer would be less than $1/66$ since pretending all 10 other numbers have equal probabilities of $(5/6)(1/10)$ makes it more likely to see everything else before seeing 7.

As another variation, you can exactly compute the expected number of distinct numbers rolled before seeing "7."  The answer is $\approx 3.161472$, whereas winning the game requires you to see all 10 before seeing "7."  Here is the computation:
Define $X$ as the amount of distinct numbers seen before seeing "7."  So $X \in \{0, 1, 2, \ldots, 10\}$. Imagine an infinite sequence of dice rolls. For each $i \in \{1, 2, 3, \ldots\}$, define $I_i$ as an indicator function that is $1$ if "7" has not occured in rolls $\{1, \ldots, i\}$ and if roll $i$ adds a distinct new number seen.  Then $X = \sum_{i=1}^{\infty} I_i$,
so:
$$ E[X] = \sum_{i=1}^{\infty} E[I_i] =\sum_{i=1}^{\infty} Pr[I_i=1]=\sum_{i=1}^{\infty} (5/6)^{i}\sum_{j\neq 7} p_j(1-p_j)^{i-1} $$
where we define $p_j$ as the conditional probability that a given roll is $j$, given that it is not 7. So $p_1 = \frac{1/36}{5/6}$, $p_2=\frac{2/36}{5/6}$, $p_3=\frac{3/36}{5/6}$, and so on, with $p_1=p_{12}$, $p_2=p_{11}$, and so on.
Thus:
\begin{align}
E[X] &= \sum_{i=1}^{\infty} (5/6)^{i}\left(2\sum_{j=2}^6p_j(1-p_j)^{i-1}\right)\\
&=\sum_{j=2}^6 \frac{p_j}{1-p_j}\sum_{i=1}^{\infty} [(5/6)(1-p_j)]^i\\
&=\sum_{j=2}^6 \frac{p_j}{1-p_j}\left(\frac{(5/6)(1-p_j)}{1-(5/6)(1-p_j)}\right)\\
&=\sum_{j=2}^6 \frac{p_j(5/6)}{1-(5/6)(1-p_j)}\\
&\approx 3.161472
\end{align}

I wrote a C program to simulate over $10^8$ independent experiments. The simulation shows the average number of distinct numbers seen before 7 is $\approx 3.161488$ (very good match to the above exact answer), and a success probability of $\theta \approx 0.005252$, $1/\theta = 190.384$.  So, assuming my simulation for successes had no bugs, the answer is that about 1 out of every 190 times you will get a success (where a success is defined as getting all other numbers before 7).

A: You can do this exactly in a straightforward fashion using the inclusion-exclusion principle to compute 1 minus the probability of getting a 7 before at least one of the other numbers. You can find a real easy-to-follow write up of how to get the probability of numbers before other numbers using inclusion-exclusion in the last answer here which also describes how to get the average number of rolls.  Doing it for all the numbers is tedious, but that's what computers are for.  That page also links to my own explanation and an R script on another site which computes the terms with the help of a combn function.  The probability you want is 1 minus the last probability computed by that R script which to 15 places is $0.00525770409617443$.
We will be computing 1 minus the probability of a 7 occurring before one or more of the other numbers. To compute this probability, first sum the probabilities of a 7 occurring before each of the 10 numbers. This over counts the cases where we get it before more than just 1 number. So we then subtract the sum of the probabilities that it can occur before each combination of 2 of the other numbers. Then we add back the probability that it can occur before each combination of 3 other numbers, and so on.  That's inclusion-exclusion.
Mathematically we have:
$$
\text{P(roll all $a_n$ for $n \neq N$ before $a_N$) = }1-\sum_{j=1}^{|S|-1}\sum_{k=1}^{|S|-1 \choose j}(-1)^{j+1}\frac{S_N}{S_N+\sum_{i=1}^jC_{i,k}}
$$
where
$$
S = \{S_n: S_n=36P(a_n)\}
$$
gives the set of numbers of ways to roll $a_n$ out of 36, and $C$ is a matrix whose columns are the combinations of size $j$ from $S$ excluding $S_N$. That is
$$
C = \mathrm{Combn}((S - \{S_N\},j)).
$$
For example, if we want the probability of rolling all the numbers before a 7, then we would have $S=\{1,1,2,2,3,3,4,4,5,5,6\}$ with $S_N = 6$ since $P(7) = 6/36$, and $a_N = 7$.
The following R script implements this for the probability of rolling all numbers before a 7:

S = c(1,1,2,2,3,3,4,4,5,5,6)  # Wynn bet
# S = c(1,2,3,4,5,6)          # All tall or all small
N = length(S)
p = 0
for (j in 1:(N-1)) {
  C = combn(S[1:(N-1)],j)
  for (k in 1:choose(N-1,j)) {
    p = p + (-1)^(j+1) * S[N]/(S[N] + sum(C[1:j,k]))
  }
}
1-p

Output:

> 1-p
[1] 0.00525770409617443

You can do this for the all small or all tall bet by simply uncommenting the line that replaces S with $\{1,2,3,4,5,6\}$.  This gives to 15 digits $0.0263539092486457$.


text:
Q: Charge 48V battery bank with 12V I have a 48V battery bank made up of 4 deep cycle 12V batteries in series. My charger only has 12V and 24V options.
I've considered using relays to put the batteries in parallel and charging at 12V. I'm assuming there has to be a better way. Ideally, one that allows all 4 batteries to remain in series.
Is there a common method to do this?
What effect would charging one 12V battery have on the other three in series?

A: The common solution, unfortunately, is to use a 48V charger.
I can think of two potential problems with charging the batteries in circuit. First, you want the batteries to have the same charge since they are in series. If you charge them one at a time, while there is a load on the bank, they may become out of sync, some charged, some less charged. If you remove the load while charging, this would not be much of a problem, I guess, but charging them in series would still be better in terms of keeping them synced up.
Second, there could be some kind of grounding issue. Does your charger ground the battery negative terminal to earth ground? Does it have an isolation voltage rating? Does your 48V bank, or the inverter connect 48V ground to earth? Just to be explicit, imagine this. Your charger negative is earth grounded. When you charge the bottom battery, no problem. When you charge the next battery up, you would actually be shorting battery 1 + directly to battery 1 - by way of earth ground. That would be bad.
Good luck!

A: In my opinion, the better way to charge those batteries is to use individual 12V chargers for each battery so that they all charge at the same time.  However, you MUST ensure that each charger's output is completely floating with respect to earth ground.  Most charges DO have floating outputs but some have the negative lead connected to the AM Mains earth terminal.  You have to check.
Obviously, all 4 chargers should be identical.
The reason I suggest charging the batteries individually is you lessen the chance of one or more of the batteries of becoming either under-charged or over-charged.
It's probably also less expensive than purchasing a dedicated 48V charger - good-quality 12V chargers often go on sale at decent prices.

A: Charging the 12 volt batteries individually would be a Bad Thing, as you want alll the batteries in the 48 volt bank to be in the same state of charge.
Ideally, you should use a 48 volt charger, but I think it would be acceptable to use two 24 volt chargers, one on each half of the bank.
Note that many marine or RV chargers claim to charge two or more battery banks - however their outputs all have a common ground, so cannot be used in your situation.

A: I have a 48v bank made up of 24 2v 500Ah cells. for simplicity and faster recovery after a power failure, I use 4 Noco Genius 12v smart chargers. if you have access to the individual cells then you can use a hydrometer and check the charge state per cell and if you have a difficult cell then you can deal with it.
It is very important that whatever chargers you use have floating leads. This is because if as others have stated, charger 1 has a negitiv lead to ground connection and you add charger 2 to battery 2 the charger 2 negitive lead being also grounded is now also attached to the positve lead of battery 1. this creates a circuit through the ground and shorts out battery 1.
Bank chargers in general share the same sources so are not good for series banks. There are some with the proper protection built in but are still not effective due to the low charge rates. eg 12v 4battery bank charger food for series applications with 24A capacity. take the total capacity an divide by number of batteries: 6A ea. a 240Ah bank will take approx 48hrs to completely recharge. this adds the extra time for absorbtion and top-up.
now if using 4 individual 24A chargers it will take 12hrs to recharge.
Using smart 5 or more stage chargers will ensure that the batteries are always in sync and always fully charged with the least amount of fluid loss. Just make sure you do not load split these batteries as that will cause issues with bank availability. load splitting is taking a 12 or 24v load and tapping the bank for it. this of setts the bank by that load current and will cause uneven discharge rates and thus can (and usually does) damage that battery. this is easily seen as the 36v bank trying to push current through a dead 12v battery. it tries to charg that battery as it supplys the load and this boils the dead battery.
in summary: use good quality smart chargers that have floating leads and make sure you have at least 10% of your banks Ah rating in charger capacity. Using 4 individual chargers does not add together for capacity. use on chargers capacity as total charging capacity. and dont mix and match chargers. use 4 of the exact same chargers. that way all specs and calcs are the same.

A: Listen they are batteries and yes you need to be very careful not to cross wire as this will short the battery. However you can charge 48v with a 12v charger it will just take a lot longer also the slower you charge your battery the more life you will get out of it charging at a high rate does damage battery faster less life on battery. I have a scooter that i wired in a series battery bank I use a 12v charger to charge battery which is 36v it takes about 10-12 hours to charge but it does ive had the scooter for 3 years and the batteries run and charge great fluid is still pretty much full I could take the batteries back now and they wouldnt even know they were used. Be careful buy the correct charger if you want a faster charge time but if you have a weekend event planned well plug it in on thursday everybody wants to be more tech savy than the next a pos is pos neg is neg a wire is a wire blah blah. Oh no make sure your series 1-9 dv data base port control model synth connects to the switch 5 route mega ac computer mother media hdmi yeah yeah get a charger read instructions everything you buy tells you how to use. Stick to that and everything will work stop trying to rig things or hope there is a secret way to do it and get the tools for the job.

A: can charge 4 nos 12v battery in 24v charging system but the battery capacity (AH) must same,otherwise charging time varries also  low capacity (AH) Battery will charge Early.You must check the chager capacity minimum 24v/10A ,you didnot mentioned battry capacity & Chager capacity.But 12v/80AH or 13 Plate Battery ,4 Nos can charge in this charger. Please very careful connect TWO Battery Series so this is one set also connect another set ,so each set have one end +ve Terminal & other end have -ve Terminal then connect Two Sets as Parallel ,switch on charger select 24v & set current rate .dont use in invertor & Ups. Indian.


text:
Q: enviar $_FILE de un formulario a otra pagina con target _blank Tengo un formulario con un input file para subir imágenes, no utilizo ajax ni nada porque salta a otra pagina para hacer un preview y no se porque en la variable $_FILE llega vacío. el resto de campos llegan correctamente.
Aquí el código:
extracto de preview.php
<form method="post" name='contactform' id='contactform' action="guardarpdf.php" target="_blank">
    <input type="file"  name="logon" id="logon" accept=".jpg,.png">
</form

y el extracto de guardarpdf.php
if (!empty($_FILES['logon'])){//Nunca llega a entrar aqui y/o hago echo y no saca nada
    echo "logon";
    $image = basename($_FILES['logon']['name']);
    $image_temp = $_FILES['logon']['tmp_name'];
    list($base,$extension) = explode('.',$image);
    $newname = implode('.', [$base, time(), $extension]);
    $ruta = "uploads";
    $ruta = $ruta."/".$newname;
    move_uploaded_file($image_temp,$ruta);
    ?>
    <img src="uploads/<?php echo $newname; ?>" style="width: 100%;">
    <?php
    $logo=$newname;
}
?>

A: Coloca el atributo enctype
<form method="post" name='contactform' id='contactform' action="guardarpdf.php" target="_blank" enctype= "multipart/form-data">
    <input type="file"  name="logon" id="logon" accept=".jpg,.png">
</form>


text:
Q: Android Gestures to Replace Physical Arrow Keys I'm starting from scratch and I don't even know where to look.. or even what to call this.. so any help would be appreciated.
I am working with the Snake example that Google supplies and I want it to work on Android devices without physical keys. How would I be able to use touch gestures (up/left/right/down) to make the snake turn and whatnot.
Again, I don't even know where to start looking.. I'm still slowly learning my way through programming for Android.
Thanks!

A: You could implement View.OnTouchListener. I think this page is the one you're looking for.
I would modify it so that touching the top part of the screen sent the snake up, the left side sent it left, etc.


text:
Q: SWIFT: Tapping a UIButton really fast results in incorrect vote count I've created a simple song list app below.

It works as follows:
1. Users can add songs to the list (using the '+' icon)
2. Uses can click to the vote button to increase or decrease their vote by one. It works similar to the 'LIKE' button on Facebook.
As you can see, some of the vote counts are negative numbers.  The reason for this is because during QA, I clicked the 'Vote' button extremely fast and it causes the vote count to go haywire. I do not see this as being a scenario that would occur a lot, but does anyone have a creative way to prevent this from happening? Any solutions would be appreciated. Thanks.
I can add my code if it's required, but I am hoping that there is a simple solution to this that I haven't found as yet.
UPDATE: Added code for the Table View Controller and the Table View Cell -
Table View Cell (with UIButton Action for 'vote'):
@IBAction func voteButton(sender: UIButton) {

    var query = PFQuery(className:"UserVotes")

    //query the database to check if the user actually like the song in the paticular row that's clicked
    query.whereKey("username", equalTo: (PFUser.currentUser()?.username)!)
    query.whereKey("song", equalTo: songID!)
    query.whereKey("vote", equalTo: true)

    query.findObjectsInBackgroundWithBlock {
        (object: [PFObject]?, error: NSError?) -> Void in

        if error == nil {

            //this is the case where a TRUE value is found. LIKE is ON
            if object!.count > 0 {

                if let object = object! as? [PFObject] {

                    for object in object {

                        if self.delegate != nil && self.rowValue != nil {

                            //decrease the count by 1
                            self.voteCount = self.voteCount! - 1
                            self.votes.text = "\(self.voteCount!)"

                            self.voteButtonOn = true
                            self.delegate!.voteButtonTurnOffFromCellRow(self.rowValue!)
                            print(self.voteButtonOn)
                        }

                    }
                }

            //this is the case where a TRUE value is NOT found, LIKE is OFF.
            } else if object?.count == 0 {

                if self.delegate != nil && self.rowValue != nil {

                    //increase the count by 1
                    self.voteCount = self.voteCount! + 1
                    self.votes.text = "\(self.voteCount!)"

                    self.voteButtonOn = false
                    self.delegate!.voteButtonTurnOnFromCellRow(self.rowValue!)
                    print(self.voteButtonOn)

                }
            }

        } else {
            // Log details of the failure
            print("Error: \(error!) \(error!.userInfo)")
        }
    }
}

Table View Controller:
import UIKit
import Parse

protocol VoteProtocol {
    func voteButtonTurnOnFromCellRow(row: Int)
    func voteButtonTurnOffFromCellRow(row: Int)
}

class MusicPlaylistTableViewController: UITableViewController, VoteProtocol {

var usernames = [String]()
var songs = [String]()
var songVotes = [Int]()

//Function to display an alert
func displayAlert(title: String, message: String) {

    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)

}

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.separatorColor = UIColor.grayColor()

    let query = PFQuery(className:"PlaylistData")
    query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in

        if error == nil {

            if let objects = objects! as? [PFObject] {

                self.usernames.removeAll()
                self.songs.removeAll()

                for object in objects {

                    let username = object["username"] as? String
                    self.usernames.append(username!)

                    let track = object["song"] as? String
                    self.songs.append(track!)

                    let votes = object["numVotes"] as? Int
                    self.songVotes.append(votes!)
                }

                self.tableView.reloadData()
            }

        } else {

            print(error)
        }
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1

}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return usernames.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("CellTrack", forIndexPath: indexPath) as! TrackTableViewCell

    cell.username.text = usernames[indexPath.row]
    cell.songTitle.text = songs[indexPath.row]

    var voteCount: Int = songVotes[indexPath.row]
    var voteCountString = String(voteCount)
    cell.votes.text = voteCountString

    cell.delegate = self
    cell.rowValue = indexPath.row
    cell.songID = songs[indexPath.row]
    cell.voteCount = songVotes[indexPath.row]

    cell.selectionStyle = UITableViewCellSelectionStyle.None
    return cell
}

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {

}

//If the LIKE button is OFF perform this. This means that a record in the database has NOT been found with a value of TRUE.
func voteButtonTurnOnFromCellRow(var row: Int) {

    // At this point, the value needs to be changed to TRUE, and the vote count needs to be increased by 1.
    //note: does not take into account scenario where there are duplicate records (slight case)
    let query = PFQuery(className:"UserVotes")
    query.whereKey("username", equalTo: (PFUser.currentUser()?.username)!)
    query.whereKey("song", equalTo: songs[row])
    query.whereKey("vote", equalTo: false)

    query.findObjectsInBackgroundWithBlock { (object: [PFObject]?, error: NSError?) -> Void in

        if error == nil {

            //this is the case where a FALSE value is found. LIKE is OFF
            if object!.count > 0 {

                if let object = object! as? [PFObject] {

                    for object in object {

                        object["vote"] = true
                        object.saveInBackground()

                        let query = PFQuery(className:"PlaylistData")
                        query.whereKey("song", equalTo: self.songs[row])

                        query.findObjectsInBackgroundWithBlock { (object: [PFObject]?, error: NSError?) -> Void in

                            if error == nil {

                                if let object = object! as? [PFObject] {

                                    for object in object {

                                        var voteCount:Int = object["numVotes"] as! Int
                                        voteCount = voteCount + 1
                                        object["numVotes"] = voteCount
                                        object.saveInBackground()
                                    }

                                }

                            }
                        }
                    }
                }

            //this is the case where a TRUE value is NOT found, LIKE is OFF (first time user vote)
            } else if object?.count == 0 {

                //add row to table
                let addUserVote = PFObject(className: "UserVotes")

                addUserVote["song"] = self.songs[row]
                addUserVote["username"] = PFUser.currentUser()?.username
                addUserVote["vote"] = true

                addUserVote.saveInBackgroundWithBlock {
                    (success: Bool, error: NSError?) -> Void in

                    if (success) {

                        if let error = error {
                            if let errorString = error.userInfo["error"] as? String {

                                self.displayAlert("Error", message: errorString)

                            }

                        } else {

                            let query = PFQuery(className:"PlaylistData")
                            query.whereKey("song", equalTo: self.songs[row])

                            query.findObjectsInBackgroundWithBlock { (object: [PFObject]?, error: NSError?) -> Void in

                                if error == nil {

                                    if let object = object! as? [PFObject] {

                                        for object in object {

                                            var voteCount:Int = object["numVotes"] as! Int
                                            voteCount = voteCount + 1
                                            object["numVotes"] = voteCount
                                            object.saveInBackground()
                                        }

                                    }

                                }
                            }

                        }

                    } else {

                        // There was a problem, check error.description

                    }
                }

            }

        } else {
            // Log details of the failure
            print("Error: \(error!) \(error!.userInfo)")
        }

    }

}

//If the LIKE button is ON perform this. This means that a record in the database has been found with a value of TRUE.
func voteButtonTurnOffFromCellRow(var row: Int) {

    // At this point, the value needs to be changed to FALSE, and the vote count needs to be decreased by 1.

    //note: does not take into account scenario where there are duplicate records (slight case)
    let query = PFQuery(className:"UserVotes")
    query.whereKey("username", equalTo: (PFUser.currentUser()?.username)!)
    query.whereKey("song", equalTo: songs[row])
    query.whereKey("vote", equalTo: true)

    query.findObjectsInBackgroundWithBlock { (object: [PFObject]?, error: NSError?) -> Void in

        if error == nil {

            if let object = object! as? [PFObject] {

                for object in object {

                    object["vote"] = false
                    object.saveInBackground()

                    let query = PFQuery(className:"PlaylistData")
                    query.whereKey("song", equalTo: self.songs[row])

                    query.findObjectsInBackgroundWithBlock { (object: [PFObject]?, error: NSError?) -> Void in

                        if error == nil {

                            if let object = object! as? [PFObject] {

                                for object in object {

                                    var voteCount:Int = object["numVotes"] as! Int
                                    voteCount = voteCount - 1
                                    object["numVotes"] = voteCount
                                    object.saveInBackground()
                                }

                            }

                        }
                    }

                }

            } else {

                print(error)
            }
        }

    }

}

}

A: In your button action toggle button userInteractionEnabled property to NO at the beginning and to YES at the end of the method. This may help you


text:
Q: Pgfplot - add the mean to a histogram (bar plot) I have a number of data files in the format count: frequency of count
1:  3691
2:  1492
3:  651
4:  922
5:  818
6:  1475
7:  335
8:  286
9:  165
10:     152
11:     208
12:     197
13:     137
14:     159
15:     87
16:     84
17:     40
18:     20
19:     37
20:     16
21:     38
22:     25
23:     17
24:     9
25:     18
26:     21
27:     4
28:     6
29:     3
30:     1
31:     5
33:     1
34:     1
35:     4
36:     3
37:     1
38:     2
39:     8
40:     3
42:     1
44:     1
46:     1
47:     12
52:     2
58:     1
83:     1
88:     1

I want to plot this as a histogram of counts (which I can do) with an average count (which I can't do).This is what is have so far:
\documentclass[]{standalone}

\usepackage{tikz}
\usepackage{pgfplots}

\begin{document}

\maketitle

\begin{tikzpicture}
    \begin{axis}[
        xtick distance=10
    ]
        \addplot[ybar interval] table [x, y, col sep=colon] {results/data.txt};

        % this line is sort of what I want but I want the 7 to be calculated automatically as the average count
        %\draw[] (axis cs:7, \pgfkeysvalueof{/pgfplots/ymin}) -- (axis cs:7, \pgfkeysvalueof{/pgfplots/ymax});

    \end{axis}
\end{tikzpicture}

\end{document}

I found this example but the data format was different so I wasn't sure how to adapt it for my situation.
This is an example of what I'm after:
Can anyone tell me how to automatically calculate the average count and add it to my plot?

A: I don't know how you want to calculate the average, so here is an example of how to calculate averages from a table.
Be aware, that at no time any value is allowed to exceed 16383.9999. Otherwise you'll get a dimension too large error. To prevent this, you can divide a value by some constant while suming up and later multiply the average with it.
The code:
Edit: table and macro names for results are now passed as parameters.
\documentclass[]{article}
\usepackage{pgfplots}

\pgfplotstableread[col sep=colon]{pgfplots-histo-average.dat}\datatable

% old code, table and macros for results fixed
%\newcommand*{\GetAverage}{%
%    \pgfmathsetmacro\dtcsum{0}%
%    \pgfmathsetmacro\dtfsum{0}%
%    \pgfmathsetmacro\dtcfsum{0}%
%    \pgfmathsetmacro\dtcnt{0}%
%    \pgfplotstableforeachcolumnelement{[index]0}\of\datatable\as\cellValue{%
%        \pgfplotstablegetelem{\pgfplotstablerow}{[index]1}\of\datatable
%        \pgfmathsetmacro{\dtfreq}{\pgfplotsretval}
%        % now: \cellValue = count; \dtfreq = frequency
%        % calculate sums
%        \pgfmathsetmacro{\dtcsum}{\dtcsum + \cellValue}%
%        \pgfmathsetmacro{\dtfsum}{\dtfsum + \dtfreq}%
%        % dividing \cellValue by 100 prevents dimension to large error
%        \pgfmathsetmacro{\dtcfsum}{\dtcfsum + (\cellValue / 100 * \dtfreq)}%
%        \pgfmathsetmacro{\dtcnt}{\dtcnt + 1}%
%    }
%    % calculate the averages
%    \pgfmathsetmacro{\dtcavg}{\dtcsum / \dtcnt}%
%    \pgfmathsetmacro{\dtfavg}{\dtfsum / \dtcnt}%
%    \pgfmathsetmacro{\dtcfavg}{\dtcfsum / \dtcnt * 100}%
%}
%\GetAverage

% new code, table and macros for results as parameters
\newcommand*{\GetAverage}[4]{%
    \pgfmathsetmacro\dtcsum{0}%
    \pgfmathsetmacro\dtfsum{0}%
    \pgfmathsetmacro\dtcfsum{0}%
    \pgfmathsetmacro\dtcnt{0}%
    \pgfplotstableforeachcolumnelement{[index]0}\of#1\as\cellValue{%
        \pgfplotstablegetelem{\pgfplotstablerow}{[index]1}\of#1
        \pgfmathsetmacro{\dtfreq}{\pgfplotsretval}
        % now: \cellValue = count; \dtfreq = frequency
        % calculate sums
        \pgfmathsetmacro{\dtcsum}{\dtcsum + \cellValue}%
        \pgfmathsetmacro{\dtfsum}{\dtfsum + \dtfreq}%
        % dividing \cellValue by 100 prevents dimension to large error
        \pgfmathsetmacro{\dtcfsum}{\dtcfsum + (\cellValue / 100 * \dtfreq)}%
        \pgfmathsetmacro{\dtcnt}{\dtcnt + 1}%
    }
    % calculate the averages
    \pgfmathsetmacro{#2}{\dtcsum / \dtcnt}%
    \pgfmathsetmacro{#3}{\dtfsum / \dtcnt}%
    \pgfmathsetmacro{#4}{\dtcfsum / \dtcnt * 100}%
}
\GetAverage{\datatable}{\dtcavg}{\dtfavg}{\dtcfavg}

\begin{document}
\begin{tikzpicture}
    \begin{axis}[
        xtick distance=10
    ]
        \addplot[ybar interval] table [x, y] {\datatable};

        % this line is sort of what I want but I want the 7 to be calculated automatically as the average count
        \draw[blue] (axis cs:\dtcavg, \pgfkeysvalueof{/pgfplots/ymin}) --
                    (axis cs:\dtcavg, \pgfkeysvalueof{/pgfplots/ymax});

    \end{axis}
\end{tikzpicture}

Average of column count is: \dtcavg

Average of column frequency is: \dtfavg

Average of count $\cdot$ frequency is: \dtcfavg
\end{document}


text:
Q: How to keep a PHP socket client connection open until socket_closed() by user I have a button "connect" !
when i press that button i want to open a php socket connection to a ip:port and the connection should stay open to send and receive data messages until the users click;s disconnect. how can i do that? i have the following code:
if (isset($_POST['cmd_connect'])) {
    // select in baza de date nodes pentru randul selectat de user
    $selectOption = $_POST['cmb_select_node'];
    $sqlquery = mysql_query("SELECT * FROM `nodes` WHERE node_mac='{$selectOption}'");
    if ($sqlquery === FALSE) {
        die(mysql_error());
    }
    while ($row = mysql_fetch_array($sqlquery)) {
        $host = $row['node_ip'];
        $port = 11000;
    };
    // don't timeout!
    set_time_limit(0);
        // Creaza si se connecteaza la socket internet IP

        $socket=socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        $s_connect=socket_connect($socket, $host, $port);
        $timeout= array('sec'=>30,'usec'=>500000);
        socket_set_option($socket, SOL_SOCKET , SO_KEEPALIVE, 1);
        socket_set_option($socket, SOL_SOCKET , SO_RCVTIMEO,$timeout);

        // Conditie creare si connectare socket
       if (! $socket) {
           ?> <script>alert('Could not create the socket to client');</script>
            <?php
        }
             elseif($s_connect) {
             ?> <script>alert('Your Are now connected');</script>
            <?php
        }

    }

?>

thanks


text:
Q: Data driven(D3.js) vertical grouped bar chart with tooltip, clickable legends and brush facilities I want to build a chart using D3.js using vertical bar chart on provided data and selected filters.

*

*Vertical grouped bar chart

*Legends

*Tooltip

*Brush and zoom

*Drill down

I have already added the filter for legends and tooltip, but facing issues while adding bursh. As i am new to D3, not sure what is the right way to integrate brush.
<!DOCTYPE html>
<meta charset="utf-8">
<head>
    <script src="https://d3js.org/d3.v3.min.js"></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.7.1/d3-tip.min.js'></script>
</head>
<style>
    g.axis path, g.axis line {
        fill: none;
        stroke: black;
        shape-rendering: crispEdges;
    }

    g.brush rect.extent {
        fill-opacity: 0.2;
    }

    .resize path {
        fill-opacity: 0.2;
    }

    .n {
      opacity: .8;
      font-size: 10px;
      margin-left: 4px;
      font-family: sans-serif;
      color: white;
      padding: 6px;
      background-color: #3C3176;
    }
</style>
<body>

    <style>

        .axis .domain {
          display: none;
        }

        </style>
        <svg width="960" height="500"></svg>
        <script src="https://d3js.org/d3.v4.min.js"></script>
        <script>

        var svg = d3.select("svg"),
            margin = {top: 20, right: 20, bottom: 30, left: 40},
            width = +svg.attr("width") - margin.left - margin.right,
            height = +svg.attr("height") - margin.top - margin.bottom,
            g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        // The scale spacing the groups:
        var x0 = d3.scaleBand()
            .rangeRound([0, width])
            .paddingInner(0.1);

        // The scale for spacing each group's bar:
        var x1 = d3.scaleBand()
            .padding(0.05);

        var y = d3.scaleLinear()
            .rangeRound([height, 0]);

        var z = d3.scaleOrdinal()
            .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

        d3.csv("data.csv", function(d, i, columns) {
          for (var i = 1, n = columns.length; i < n; ++i) d[columns[i]] = +d[columns[i]];
          return d;
        }, function(error, data) {
          if (error) throw error;

          var keys = data.columns.slice(1);

          const tip = d3.tip().html(d=> d.value);

          svg.call(tip);

          x0.domain(data.map(function(d) { return d.State; }));
          x1.domain(keys).rangeRound([0, x0.bandwidth()]);
          y.domain([0, d3.max(data, function(d) { return d3.max(keys, function(key) { return d[key]; }); })]).nice();

         g.append("g")
            .selectAll("g")
            .data(data)
            .enter().append("g")
            .attr("class","bar")
            .attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; })
            .selectAll("rect")
            .data(function(d) { return keys.map(function(key) { return {key: key, value: d[key]}; }); })
            .enter().append("rect")
              .attr("x", function(d) { return x1(d.key); })
              .attr("y", function(d) { return y(d.value); })
              .attr("width", x1.bandwidth())
              .attr("height", function(d) { return height - y(d.value); })
              .attr("fill", function(d) { return z(d.key); })
              .on('mouseover', tip.show)
              .on('mouseout', tip.hide);

          g.append("g")
              .attr("class", "axis")
              .attr("transform", "translate(0," + height + ")")
              .call(d3.axisBottom(x0));

          g.append("g")
              .attr("class", "y axis")
              .call(d3.axisLeft(y).ticks(null, "s"))
            .append("text")
              .attr("x", 2)
              .attr("y", y(y.ticks().pop()) + 0.5)
              .attr("dy", "0.32em")
              .attr("fill", "#000")
              .attr("font-weight", "bold")
              .attr("text-anchor", "start")
              .text("Population");

         // Initialize brush component
          d3.brushX()
          .handleSize(10)
          .extent([10, 0], [g.width, g.height]);

          // Append brush component
         svg.append("g")
          .attr("class", "brush")
          .call(d3.brush);

          var legend = g.append("g")
              .attr("font-family", "sans-serif")
              .attr("font-size", 10)
              .attr("text-anchor", "end")
            .selectAll("g")
            .data(keys.slice().reverse())
            .enter().append("g")
              .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

          legend.append("rect")
              .attr("x", width - 17)
              .attr("width", 15)
              .attr("height", 15)
              .attr("fill", z)
              .attr("stroke", z)
              .attr("stroke-width",2)
              .on("click",function(d) { update(d) });

          legend.append("text")
              .attr("x", width - 24)
              .attr("y", 9.5)
              .attr("dy", "0.32em")
              .text(function(d) { return d; });

          var filtered = [];

          ////
          //// Update and transition on click:
          ////

          function update(d) {

            //
            // Update the array to filter the chart by:
            //

            // add the clicked key if not included:
            if (filtered.indexOf(d) == -1) {
             filtered.push(d);
              // if all bars are un-checked, reset:
              if(filtered.length == keys.length) filtered = [];
            }
            // otherwise remove it:
            else {
              filtered.splice(filtered.indexOf(d), 1);
            }

            //
            // Update the scales for each group(/states)'s items:
            //
            var newKeys = [];
            keys.forEach(function(d) {
              if (filtered.indexOf(d) == -1 ) {
                newKeys.push(d);
              }
            })
            x1.domain(newKeys).rangeRound([0, x0.bandwidth()]);
            y.domain([0, d3.max(data, function(d) { return d3.max(keys, function(key) { if (filtered.indexOf(key) == -1) return d[key]; }); })]).nice();

            // update the y axis:
                    svg.select(".y")
                    .transition()
                    .call(d3.axisLeft(y).ticks(null, "s"))
                    .duration(500);

            //
            // Filter out the bands that need to be hidden:
            //
            var bars = svg.selectAll(".bar").selectAll("rect")
              .data(function(d) { return keys.map(function(key) { return {key: key, value: d[key]}; }); })

           bars.filter(function(d) {
                 return filtered.indexOf(d.key) > -1;
              })
              .transition()
              .attr("x", function(d) {
                return (+d3.select(this).attr("x")) + (+d3.select(this).attr("width"))/2;
              })
              .attr("height",0)
              .attr("width",0)
              .attr("y", function(d) { return height; })
              .duration(500);

            //
            // Adjust the remaining bars:
            //
            bars.filter(function(d) {
                return filtered.indexOf(d.key) == -1;
              })
              .transition()
              .attr("x", function(d) { return x1(d.key); })
              .attr("y", function(d) { return y(d.value); })
              .attr("height", function(d) { return height - y(d.value); })
              .attr("width", x1.bandwidth())
              .attr("fill", function(d) { return z(d.key); })
              .duration(500);

            // update legend:
            legend.selectAll("rect")
              .transition()
              .attr("fill",function(d) {
                if (filtered.length) {
                  if (filtered.indexOf(d) == -1) {
                    return z(d);
                  }
                   else {
                    return "white";
                  }
                }
                else {
                 return z(d);
                }
              })
              .duration(100);

          }

        });

        </script>

State,Under 5 Years,5 to 13 Years,14 to 17 Years,18 to 24 Years,25 to 44 Years,45 to 64 Years,65 Years and Over
CA,2704659,4499890,2159981,3853788,10604510,8819342,4114496
TX,2027307,3277946,1420518,2454721,7017731,5656528,2472223
NY,1208495,2141490,1058031,1999120,5355235,5120254,2607672
FL,1140516,1938695,925060,1607297,4782119,4746856,3187797
IL,894368,1558919,725973,1311479,3596343,3239173,1575308
PA,737462,1345341,679201,1203944,3157759,3414001,1910571


text:
Q: How can I cross lines of a listA.txt and listB.txt and return an output.txt with each line of listB.txt where they match in Python and grep? So, I have two lists with emails and I want to cross that information.
The "listA.txt" list will be used as a basis for checking the "listB.txt" list, where there are not only emails but also texts. Then an "output.txt" file will be generated, where there will be the WHOLE line where that email listed in "listA.txt" appears in "listB.txt".
Example:
listA.txt

arthur@gmail.com
guinevere@outlook.com
lancelot@yahoo.com
gawaine@gmail.com

listB.txt

arthur@gmail.com Arthur Smith
guinevere@outlook.comtest
lance@gmail.com
gawaine@gmail.com Ocean Bvd
arth@hotmail.com

output.txt

arthur@gmail.com Arthur Smith
guinevere@outlook.comtest
gawaine@gmail.com Ocean Bvd

Note that I need each line of "listA.txt" as a pattern to check not only the lines of "listB.txt" that contain ALL the whole line of "listA.txt", but also return ALL the whole line of "listB.txt" where those emails appear at "output.txt". I don't want partial results as has already happened with another algorithms where "lancelot@yahoo.com" was split (splitlines) and matched with "lance@gmail.com".
I searched for more than a week, including here on the stackoverflow, but I didn't get any solution and I have no idea what to do, could you help me? I've tried grep, regex and etc. but no success too.
My try:
with open('emails4.txt', 'r', encoding="latin-1") as k:
keywords = k.read().splitlines()
results = []

with open('emails5.txt', encoding="latin-1") as f, open('output.txt', 'w',
encoding="latin-1") as o:
keywords2 = f.read().splitlines()
for line in keywords2:
if any(line in key for key in keywords):
o.write(line + "\n")

Thanks in advance.

A: A = [
    "arthur@gmail.com",
    "guinevere@outlook.com",
    "lancelot@yahoo.com",
    "gawaine@gmail.com",
]

B = [
    "arthur@gmail.com Arthur Smith",
    "guinevere@outlook.comtest",
    "lance@gmail.com",
    "gawaine@gmail.com Ocean Bvd",
    "arth@hotmail.com",
]

# oneliner
output = [b for b in B if any(b.startswith(a) for a in A)]
print(output)

# "longer" solution
output = []
for b in B:
    for a in A:
        if b.startswith(a):
            output.append(b)
            break
print(output)

The complexity is quadratic - len(A)*len(B)
EDIT: solution with files:
with open("listA.txt") as f: listA = f.read().splitlines()
with open("listB.txt") as f: listB = f.read().splitlines()
output = [b for b in listB if any(b.startswith(a) for a in listA)]
with open("output.txt","w") as f: f.writelines(l+"\n" for l in output)


text:
Q: formatting  to 12 hour format with no seconds/milliseconds I'm trying to format some times for display.
  <input ng-change="changeTimeBehaviours()" ng-model="booking.time" type="time" >

How can I add formatting to this to be h:mma format ? (eg 2:30PM)
I used
var _time = new Date().toLocaleTimeString(navigator.language,{hour:'2-digit', minute: '2-digit'});

and it did the job but i cant use that with the type='time' because it expects a date time object not a string.
I'm using
{{booking.time | date:"h:mma"}}

in a template in another section and it works perfectly.
~Edit
I was using ionic serve to test the app, and it was giving me this as the time
11:59:18.046 PM
when I closed the quit the serve and refreshed the page, chrome had the time flag exactly how I wanted it to be,
11:59 PM
so I've come to the conclusion that its something to do with how ionic or cordova builds the type="time"
~Edit2
Seems to be a localisation issue as it works correctly on ios also.

A: You are using angularjs expression

{{booking.time | date:"h:mma"}}

Which will filter your data only at UI side. So change logic in your controller similar to this

var sdf = new SimpleDateFormat("HH:mm");
var _time = sdf.format(new Date());


text:
Q: Is the function $f(x)=\frac{1}{\sqrt{x}}$ Lebesgue integrable on $[0,1]$ ? Justify Is the function $f(x)=\frac{1}{\sqrt{x}}$ Lebesgue integrable on $[0,1]$ ? Justify.
From intuition I believe it is Lebesgue integrable, since it is Riemann integrable. $$\int_0^1\frac{1}{\sqrt{x}}=\int_0^1 x^{-\frac{1}{2}}=2x^{\frac{1}{2}}\vert_0^1=2$$Also by then fact that the points of discontinuities is countable i.e$( x=o)$.
Is there any formal way to show this results preferably by constructing simple function approximation of $f(x)$?
Any help? thank you


text:
Q: does cocoapods build settings override all project target settings? Hello im new to cocoapods and I just had a question, do all the cocoapods build settings override the build settings I have set for my project target ? (specifcally enable bitcode)

A: Not all cocoapods build settings override the build settings you have set for your project target.
Some build setting in your project target can be inherited so it's like allowance to setup your project target build settings from other place. When you run pod install cocoapods does magic that creates a workspace containing your project and Pods.xcodeproject. To support relationship between them cocoapods injects some changes into your project target.