Create a group in address book for iPhone

Question: I am working in an iPhone application which uses adding contact to the address book. I have been able to add contacts to the address book but the problem I am facing is while adding a contact record to a group that I have created.
The contact is created under all contacts not within the group which have been created. Below is the code I have used
// create address book record
ABAddressBookRef addressBook = ABAddressBookCreate();
// create a person
ABRecordRef person = ABPersonCreate();
// first name of the new person
ABRecordSetValue(person, kABPersonFirstNameProperty, @"FirstName" , nil);
// his last name
ABRecordSetValue(person, kABPersonLastNameProperty, @"LastName", nil);
//add the new person to the record
ABAddressBookAddRecord(addressBook, person, nil);

ABRecordRef group = ABGroupCreate(); //create a group
ABRecordSetValue(group, kABGroupNameProperty,@"My Group", &error); // set group's name
ABGroupAddMember(group, person, &error); // add the person to the group
ABAddressBookAddRecord(addressBook, group, &error); // add the group

//save the record
ABAddressBookSave(addressBook, nil);

// relase the ABRecordRef  variable
CFRelease(person);

Comment: you mean you can not add person to group right?
Comment: yes the person is not added to the group but it is added to the all contacts .
Answer: This is My test , I test it , it works well.
ABAddressBookRef ab = ABAddressBookCreate();
CFErrorRef error;
ABRecordRef group = ABGroupCreate();
ABRecordSetValue(group, kABGroupNameProperty,@"new group", &error);
ABAddressBookAddRecord(ab, group, &error);
ABAddressBookSave(ab, &error);
//Create new person and save to this group
ABRecordRef record = ABPersonCreate();
BOOL isSuccess ;

isSuccess  = ABRecordSetValue(record, kABPersonNicknameProperty,@"GroupMember nick name", &error);
isSuccess = ABRecordSetValue(record, kABPersonMiddleNameProperty, @"Middle name", &error);

ABMutableMultiValueRef copyOfPhones = ABMultiValueCreateMutable(kABPersonPhoneProperty);

CFTypeRef phone= CFSTR("123000222111");

ABMultiValueAddValueAndLabel(copyOfPhones, phone,kABPersonPhoneMobileLabel,NULL);

isSuccess = ABRecordSetValue(record, kABPersonPhoneProperty, copyOfPhones, &error);

isSuccess = ABAddressBookAddRecord(ab, record, &error);
isSuccess = ABAddressBookSave(ab, &error);

ABGroupAddMember(group, record, &error);

NSLog(@"is success %d", isSuccess);

ABAddressBookSave(ab, &error);
CFRelease(group);

Comment: The problem with the above code is that is will create multiple groups with the name "My Group". It won't add the content to an existing group, which is what the original question asked. And where I'm stuck :-)
Answer: You first need to save the Person to the address book before adding it to the group, this means you have to add an
ABAddressBookSave(addressBook, nil);

Before adding the person to the group, in your case it will be just before creating the group.
Comment: As for the person in the address book, you also need to save after adding the group, before adding the person to the group, everything need to be saved in the address book. So create the person, save. Create the group, save. Add the person to the group, save.
Comment: I have tried as you have mentioned but still it doesn't work the contact is saved in the all contacts not within the group
Comment: i tried it liked that also it still didnt work. Do you know any other way around in adding  contacts to the addressbook
Comment: This is the only way I know, but It's weird because I've tried what I said, and It worked, Xcode 4 + iOS SDK 4.3
Comment: A link to a sample I've tried and work, tell me if it works for you: http://cl.ly/67s8
Comment: Thank you very much .. the sample you had provided worked for me . :-)


Failed to set default null value for column

Question: I already have a table, simplified example:
CREATE TABLE t (c INT NOT NULL);

And I need to change column default value to NULL, so I tried:
ALTER TABLE t ALTER COLUMN c SET DEFAULT NULL;

but I got the error "Error Code: 1067. Invalid default value for 'c'".
It looks really strange, because query conforms with official docs.
I even tried to:
ALTER TABLE t ALTER COLUMN c DROP DEFAULT;

and after it to make a 'SET DEFAULT NULL' query, but the same error occurred.
It's interesting, that query like:
ALTER TABLE t ALTER COLUMN c SET DEFAULT 1;

executed without errors.
I know, that it is possible to change column default value to NULL in my case using:
ALTER TABLE t MODIFY COLUMN c INT NULL;

but this query is really slow on big tables (it is much slower, than queries like 'SET DEFAULT 1')
So, how to just change default value to NULL?
I mean, without any overhead caused by 'MODIFY COLUMN' command.
Details: MySQL x64 version 5.7.10, Win8. Tested using MySQL Workbench.
Comment: You have created the table with Not Nullable column 'c', so you can't make it default as NULL. Without modifying the column to Nullable I'm afraid you can never set it to NULL.. Once you make it Nullable, it should be by default NULL when you add any new record without a value in this column.
Answer: By creating column as NOT NULL you have created a CONSTRAINT - declaring that values entered into that column may never be NULL.
A default value of NULL (set to null is value not present during INSERT) would create invalid data.
As sadly nullability constraint is part of the datatype in mysql the only way to make the column nullable will be
 ALTER TABLE t MODIFY COLUMN c INT NULL;


How do I collect daily login statistics

Question: I am trying to add a contest to my website which will be based on how frequently they login into my website. Each user will be assigned one point per day irrespective of how many times the login in a day. A winner will be picked every month, at random, based on the number of times they have logged in. Hence the more times you login, the more odds you have of winning.
Any ideas on what would be the best approach? Would I have to build a module from scratch? Modify a current module? Any help would be appreciated.
Thanks,
G
Answer: I would say use the User Points module along with the User Points Login add-on module to handle to recording of points for users logging in.
Then you can use the Views module to build reports for yourself to see which users have the most points for a given period.
It would also be possible to use the Rules module to automatically email you a report of the winners at the end of every month and then reset all user points to zero (I'm making an assumption that there is a rules action you could use to remove existing user points).
Comment: Userpoints is a bit of a heavier solution however it allows you to assign points for other site interactions. If the "points" will only be seen by you and you only need login stats then tenken's answer of using the Login History module is probably better because it is a more light weight solution.
Answer: I was going to recommend the Login History module to track logins on the site -- then it's just a simple matter of doing some filtering and reporting logic to see how many days a user has a login recorded for.
For instance Views and Views Aggregate could likely help build list of tally's; as @rooby says Rules could then do emailing and other tasks for you.
EDIT
views integration seems to be incomplete on the original module in an issue, but there is a small support module that adds the functionality while the issue is worked on the in parent module: https://www.drupal.org/sandbox/mouhammed/2396263

How do I collect daily login statistics


How to get all props from a component that is being passed as a prop?

Question: I have this component called SpecialComp that is being passed as a prop to MyComp . My question is how to pass all of the props from SpecialComp (color, size, weight) to MyComp so then I can override the attributes set in MyComp? In other words how can I have access to SpecialComp's props inside of MyComp?
<MyComp customcomp ={<SpecialComp color='green' size='20' weight='bold'/>} />

export const MyComp = ({customcomp}) => {
  return (

    {React.cloneElement(customcomp, {color: 'red'})}

  );
}

Comment: Doesn't `customcomp.props` work ??
Comment: use redux or some global variables?
Comment: this app doesn't use Redux and will not be using it either
Comment: Have you checked this out? https://reactjs.org/docs/react-api.html#cloneelement
Answer: You can simply access the props by calling customcomp.props.
<MyComp
    customcomp={<SpecialComp color="green" size="20px" weight="bold" />}
  />

const MyComp = ({ customcomp }) => {

  console.log(customcomp.props);
  //Prints: {color: "green", size: "20px", weight: "bold"}

  return
{React.cloneElement(customcomp, { color: "red" })}
;
};

export default MyComp;

codeSandbox for this here.
Answer: If you don't want to make use of any state management solution. Then you can consider lifting the state (prop) up. See code examples below:
import React from "react";

export const App = () => {
  const [specialProps, setSpecialProps] = useState({
    color: "green",
    size: "20",
    weight: "bold",
  }); // make the properties as state

  return (
    <MyComp
      customComponentStyles={specialProps} // you can pass it here
      customComponent={
        <SpecialComp
          color={specialProps.color} // you can pass it here too
          size={specialProps.size}
          weight={specialProps.weight}
        />
      }
    />
  );
};

export const MyComp = ({ customComponentStyles, customComponent }) => { // access the same prop here as well
  return
{React.cloneElement(customcomp, { color: "red" })}
;
};

Comment: Welcome to SO!
Can you explain your answer?
Refer to [How do I write a good answer](https://stackoverflow.com/help/how-to-answer) guidline to improve your contribution.
Comment: The code, I believe, is self-explanatory with comments. Please let me know if this isn't the case.
Answer: <MyComp customcomp ={<SpecialComp color='green' size='20' weight='bold'/>} />

export const MyComp = ({customcomp}) => {
  return (

    {React.cloneElement(customcomp, {...customcomp.props,color: 'red'})}

  );
}


Editing local jsbin

Question: I have a local version of jsbin that I want to be able to style as the font are much larger than the version online. Does anyone know where I can find these files, if they are available on my computer, so that I can adjust the font size?
Thank you,
Rob
Comment: Try Stylish for FF or Chrome and apply your own style to `pre` and `code`.
Comment: So is there no way to change this for good so each time I start it I won't have to go through this process?
Comment: Yes, with Stylish you can do this. Just go here and try it https://chrome.google.com/webstore/detail/stylish/fjnbnpbmkenffdnngjfgmeleoegfcffe?hl=en
Answer: You can open the web console and put in...
jsbin.settings.font = 12;
...or whatever font size you want! Default is 14.
Check out the docs on CodeMirror; they helped me a lot with this.
http://codemirror.net/doc/manual.html#config

Editing local jsbin


Spring Boot Microsservice using External Authentication Server

Question: I have a Full Stack application, with React on the frontend and Spring Boot on the backend, and I would like to make this application consume the authentication service of another application.
Does anyone have an idea how to do this, or has done something similar please?
My idea is that in React, my front end, I have a login screen directed to the external authentication service, and that the SpringBoot APIs are also secured by the external authentication service
I have a large e-commerce application, with built-in authorization OAuth server.
And these days I'm developing several standalone systems (with springboot and react) to extend my e-commerce capabilities.
I'm trying to get all these independent systems to use my e-commerce authentication service
Answer: Maybe you can try to implement your own AuthenticationProvider, something like
<code>public class ThirdPartyAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication auth) thows AuthenticationException {
        // call third party site with auth.getPrincipal() and auth.getCredentials() (those are username and password)
        // Throw AuthenticationException if response is not 200
        return new UsernamePasswordAuthenticationToken(...);
    }

    @Override
    public boolen supports(Class<?> authCls) {
        return UsernamePasswordAuthenticationToken.class.equals(authCls);
    }
}
</code>
After that you can override the configure(AuthenticationManagerBuilder) method in your SpringSecurityConfig:
<code>@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // authProvider = instance of ThirdPartyAuthenticationProvider
    auth.authenticationProvider(authProvider);
}
</code>
Comment: Thank you very much, this made me much clearer what needs to be done! Sincerely, Fabio


Android how to set run time Id

Question: I want to set run time id and get id.
my code is...
TextView image=new TextView(this);
            LinearLayout.LayoutParams imageParams = new       LinearLayout.LayoutParams(100,100);
            image.setLayoutParams(imageParams);
                image.setBackgroundResource(R.drawable.grey);
            image.setId(1);
   image.setOnclickListner(this);

but When I set image.setId(1) then give the error in android studio.
then how to find image id in under the view..
Comment: what is error you are getting
Comment: error is      Expected resource of type id
Comment: #Destro ur code is absolutly fine ... please check somethings else causing this error
Comment: this error is show only Android studio.. same code is run in eclipse
Comment: try changing id to some bigger number
Comment: View.generateViewId()  use this in image.setid(View.generateViewId());
Comment: thanks  but how to find this id..under the View.. means when the click this image then how to find image id
Comment: just after setid you can  also call getid it will return assigned id
Comment: but  image.setid(View.generateViewId()); is set in when minimum API level is 17 .. but in my project is working API level is 13..
Comment: @Destro What's the need to set resource id dynamically?
Comment: @Bhavik mehta  I am set many imageView ya textView in run time and set clicklistener in all imageView ya TextView when click image ya text then find some  response .
Comment: @Destro why worrying about ids then? you can simply do this by i.e(image.setOnClickListener(new View.OnClickListener) ) as simple as that, make a counter and attach that counter with the image name so no conflict may occur
Comment: @Bhavik Mehta  in my layout at a time 32 image is adding in run time so this code is not possible..your code is valid when adding only one image
Comment: @Destro, Can you explain the work flow if possible?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/71644/discussion-between-destro-and-bhavik-mehta).
Answer: in below API level 17 there is not possible to generate run time ID.. if we generate id then we set Tag like as image.setTag(1) .. for example..
TextView image=new TextView(this);
        LinearLayout.LayoutParams imageParams = new       LinearLayout.LayoutParams(100,100);
        image.setLayoutParams(imageParams);
            image.setBackgroundResource(R.drawable.grey);
        image.setTag(1);
     image.setOnclickListner(this);
}

and get Tag like this
  @Override
public void onClick(View v) {
    Log.e("hello",""+v.getTag());

}

Android how to set run time Id


Saving ArrayList in Fragment onPause Method

Question: I am trying to save an ArrayList with custom objects so that when i move to another fragment and come back to it, it doesnt have to reload the data. So far, i havent been able to achieve this despite making the object Parcelable and saving it in the onSaveInstanceState method.
Answer: You can also hold a reference to this list in your ApplicationContext and get the data this way - so you do not need to serialize/deserialize
Answer: If you don't want to use parcelable objects, you can try this:
<code>1- By using GSON library, create jsonString from your Custom Arraylist.
2- Send this jsonString to Fragment by using Bundle.
3- Recieve jsonString from bundle and parse it to Custom Arraylist by using GSON Library again.
4- You can also save it to SharedPreferences as a String.
</code>
Note: This is not a good method but easy option for you.


Create a form programmatically and display result on template

Question: I'm trying to create a simple page with a form.
With the different filled fields I want to execute different EntityFieldQuery in the HOOK_form_submit. To finish I want to display the result of myEntityFieldQueryunder the form like aView`.
For the moment I created a module with HOOK_menu :
function statistiques_menu() {
    $items = array();

    $items['statistiques'] = array(
        'title' => t('Statistics Page'),
        'description' => t('Homepage for statistics'),
        'page callback' => '_homepage_for_statistics',
        //'page arguments' => array('form_example_form'),
        'access arguments' => array('access content'),
    );

    return $items;
}

A simple form here :
function statistiques_form($form, &$form_state) {
    $form['age'] = array(
        '#title' => t('Age'),
        '#type' => 'textfield',
        '#required' => TRUE,
        '#maxlength' => 3,
        '#size' => 3,
        '#weight' => 0,
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#validate' => array('statistiques_form_validate'),
        '#submit' => array('statistiques_form_submit'),
        '#weight' => 10,
        '#value' => t('Click Here!'),
    );

    return $form;
}

I have two functions statistiques_form_validate and statistiques_form_submit under hook_form
Then i send my form and others vars to my template like this :
function statistiques_theme() {
    return array(
        'statistiques_template' => array(
            'template' => 'statistiques',
            'variables' => array(),
        ),
    );
}

function _homepage_for_statistics(){
    global $user;

    $output = '';
    $vartest = 'my var test to template';

    $output .= theme('statistiques_template', array(
        'vartest' => $vartest,
        'form' => drupal_get_form('statistiques_form'),
    ));

    return $output;
}

My template look like this :
<?php print render($form['age']); ?>
<?php print render($form['submit']); ?>

I tried Example module, but this case isn't on this module. There is some cases which are close to my problem, after submit the form data are sent to flash message.
With my code the form doesn't work, I can't submit the form but I think it's a small problem... my real problem will come when I will need to display the result of my form validation to my template under the form or on another template. How can do that ?
Thanks
Comment: check this link http://drupal.stackexchange.com/questions/141357/how-to-style-a-programmatically-created-page-with-a-template
Answer: I recommend adding the results of the query to the form markup-like:
$form['something'] = array(
  '#theme' => 'statistiques_template',
  '#vartest' => $vartest,
);

is equivalent to theme('statistiques_template', array('vartest' => $vartest)) -- the theme system will remove the # from the variable names if #theme is set.
But, of course, you can add the form to the page build as well, see how comment_reply does it:
  $build['comment_node'] = node_view($node);
  $build['comment_form'] = drupal_get_form("comment_node_{$node->type}_form", (object) $edit);

If coding in Drupal 7, forget direct theme calls, strings and the . operator. Work with render arrays instead. It's also a good preparation for Drupal 8 where concatenating strings leads to double escape bugs.


Remover mais de um item de um array

Question: É possível remover mais de um item de um array de uma vez.
Segue o código:
var teste = [6,4,5];
//meu objectivo é remover os itens 4, 5 por ex

//removendo o item 4
teste.splice(1, 1)

//removendo o item 5
teste.splice(1, 2)

Como podem notar apos eu retirar o primeiro item o array fica 'maluco' pois tem um item a menos ou seja todos índices mudam
Comment: Já tentou `teste.splice(1, 2)`, sem rodar os outros que você já tem? O segundo parâmetro do splice é a quantidade a ser removida. [Mais na MDN](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)
Answer: O primeiro argumento do splice é um índice no array, o segundo é a quantidade de itens a remover a partir dali.
Então fica assim:
var itens = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var indice = 2; // lembre que começa em zero, então esta é a posição do "c"
var quantidade = 3;

var removidos = itens.splice(indice, quantidade);

console.log(itens); // ["a", "b", "f", "g"]
console.log(removidos); // ["c", "d", "e"]

Se não souber a posição dos itens, pode remover itens usando o método filter:
var itens = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

var resultado = itens.filter(function(item) {
  return item !== 'c' &&  item !== 'e';
});

console.log(resultado); // ["a", "b", "d", "f", "g"]

ou assim pra ficar mais fácil:
var itens = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var remover = ['f', 'c'];

var resultado = itens.filter(function(item) {
  return !~remover.indexOf(item);
});

console.log(resultado); // ["a", "b", "d", "e", "g"]

se quiser faça uma função pra usar outras vezes:
function remover(array, rem) {
  return array.filter(function(item) {
    return !~rem.indexOf(item);
  });
}

var original = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var resultado1 = remover(original, ['f', 'c']);
var resultado2 = remover(original, ['a', 'e', 'g']);

console.log(resultado1); // ["a", "b", "d", "e", "g"]
console.log(resultado2); // ["b", "c", "d", "f"]

Comment: Valeu Ezequias, desconhecia essa função 'filter' do array, eu consegui realizar a tarefa usando um for e um while mas não ficou muito bonito, ficou funcional apenas. isso sem duvida vai ajudar bastante nas proximas. Valeu !
Answer: O primeiro parâmetro é a parti de qual indice irá começar a ser removido, e o segundo quantas posições serão removidas. No meu exemplo eu estou dizendo:
Remova 1 elemento a parti da posição 1.
Veja funcionando:

var fruits = [6,4,5];

fruits.splice(1, 1);

console.log(fruits);

Fonte: W3Scholls
Comment: Ola Marconi, obrigado pela resposta mas eu coloquei apenas como exemplo, ou seja nem sempre os itens a serem excluídos estarão por ultimo ou em sequência.

Estou quase conseguindo, assim que terminar posta a resposta. Valeu!

Remover mais de um item de um array


Proof of indexed family set

Question: I am stuck at the following exercise in Velleman's How To Prove it:

Suppose $\{A_i\mid i \in I\}$ is a family of sets. Prove that if $\mathscr P\left(\bigcup_{i\in I}A_i\right) \subseteq \bigcup_{i\in I}\mathscr P(A_i) $, then there is some $i\in I$ such that $\forall j\in I(A_j\subseteq A_i) $. ($\mathscr P$ means powerset.)

I tried expanding this into its logical form and proceed, but its logical form has too many variables and too complicated of a structure that I couldn't get my head around it, so I turned to the solution:
i) Suppose $\mathscr P\left(\bigcup_{i\in I}A_i\right) \subseteq \bigcup_{i\in I}\mathscr P(A_i) $.
ii). Clearly $\bigcup_{i\in I}A_i \subseteq \bigcup_{i\in I}A_i$, so $\bigcup_{i\in I}A_i \in \mathscr P\left(\bigcup_{i\in I}A_i\right)$, and therefore $\bigcup_{i\in I}A_i \in \bigcup_{i\in I}\mathscr P(A_i)$.
I don't see how $\bigcup_{i\in I}A_i \in \mathscr P\left(\bigcup_{i\in I}A_i\right)$ leads to $\bigcup_{i\in I}A_i \in \bigcup_{i\in I}\mathscr P(A_i)$; in fact despite knowing its logical form $\exists i\in I\, \forall y(y\in x \to y\in A_i) $, I don't even know how to explain $\bigcup_{i\in I}\mathscr P(A_i)$ in ordinary language!
But even if I am to ignore this, there are further trouble ahead:
iii. By the definition of union of a family, this means that there is some $i \in I$ such that $\bigcup_{i\in I}A_i \subseteq A_i$.
Does this mean $\exists i\in I \left(\bigcup_{i\in I}A_i \subseteq A_i\right)$? But where is this coming from?! It seems that the subset comes from the definition of powerset, but I don't see how $\bigcup_{i\in I}\mathscr P(A_i)$ will yield this.
iv. Now let $j\in I$ be arbitrary. Then it is not hard to see that $A_j \subseteq \bigcup_{i\in I}A_i$, so $A_j \subseteq A_i$.
For me it is vacuously true that 'it's not hard', because I can't even understand what he was doing in the prior steps.
I am a self-teaching student so I am really grateful for any help on this, thank you so much!
Answer: Let's start with $\bigcup_{i\in I}\mathscr P(A_i)$. For each $i\in I$, $\mathscr{P}(A_i)$ is the family of all subsets of $A_i$. The union of all of these families is the collection of all sets that are subsets of at least one $A_i$. That is,
$$x\in\bigcup_{i\in I}\mathscr{P}(A_i)\quad\text{iff}\quad\exists i\in I\,(x\subseteq A_i)\;.$$
Since $x\subseteq A_i$ if and only if $x\in\mathscr{P}(A_i)$, this is just an application of the fact that if $\{X_i:i\in I\}$ is any indexed family of sets, then
$$x\in\bigcup_{i\in I}X_i\quad\text{iff}\quad\exists i\in I\,(x\in X_i)\;,$$
with $X_i=\mathscr{P}(A_i)$.
Now let's look at $\bigcup_{i\in I}A_i \in \bigcup_{i\in I}\mathscr P(A_i)$. We know that $\bigcup_{i\in I}A_i \in \mathscr P\left(\bigcup_{i\in I}A_i\right)$, and we're assuming that
$$\mathscr P\left(\bigcup_{i\in I}A_i\right) \subseteq \bigcup_{i\in I}\mathscr P(A_i)\;,$$
so in fact we have
$$\bigcup_{i\in I}A_i \in \mathscr P\left(\bigcup_{i\in I}A_i\right)\subseteq\bigcup_{i\in I}\mathscr P(A_i)$$
and hence
$$\bigcup_{i\in I}A_i \in\bigcup_{i\in I}\mathscr P(A_i)\;:$$
that's just an application of the fact that if $x\in y\subseteq z$, then $x\in z$.
Now to avoid notational clutter temporarily let $a=\bigcup_{i\in I}A_i$; we've just seen that $a\in\bigcup_{i\in I}\mathscr{P}(A_i)$. As we saw up at the top, this means that there is some $i\in I$ such that $a\subseteq A_i$. At this point your source slips up a little, expanding $a$ to its original form and writing
$$\bigcup_{i\in I}A_i\subseteq A_i\;.$$
This is incorrect: the $i$ on the lefthand side is an index variable, a dummy variable over which we take the union, while the $i$ on the right is a specific member of $i$ such that $a\in A_i$. We can fix this in a couple of ways. One is to make it more obvious that the $i$ on the right is a specific element of $I$ by changing it to $i_0$: the fact that $a\in\bigcup_{i\in I}\mathscr{P}(A_i)$ means that there is some particular $i_0\in I$ such that $a\subseteq A_{i_0}$, i.e., such that
$$\bigcup_{i\in I}A_i\subseteq A_{i_0}\;.\tag{1}$$
The alternative would have been to change the index variable: it's also true that $a=\bigcup_{j\in I}A_j$, so once we have a specific $i\in I$ such that $a\subseteq A_i$, we can write
$$\bigcup_{j\in I}A_j\subseteq A_i\;.$$
I'll go with the first corrected version, with $(1)$.
Now the conclusion is pretty straightforward. For each $j\in I$ we have $A_j\subseteq\bigcup_{i\in I}A_i$ (by an easy application of the definition of the union); combining this with $(1)$, we get $A_j\subseteq A_{i_0}$. This $i_0\in I$ satisfies the conclusion of the theorem: $\forall j\in I\,(A_j\subseteq A_{i_0})$.
Comment: @Daniel: You're welcome! To answer your question, let $j\in I$, and suppose that $x\in A_j$; in order to show that $A_j\subseteq\bigcup_{i\in I}A_i$, we must show that $x\in\bigcup_{i\in I}A_i$. By definition that will be true if there is an $i\in I$ such that $x\in A_i$, and there is: take $i=j$.
Comment: @Daniel: The statement 'if $x\in\varnothing\subseteq z$, then $x\in z$' is indeed true for the reason that you give — the antecedent is false — but it's a bit different from the statements that are usually described as vacuously true. An asymmetric relation, for instance, is vacuously antisymmetric, but this is because no elements of the underlying set satisfy the antecedent of the implication defining antisymmetry, not because that antecedent is internally contradictory. I'd rather classify this implication with 'If $1=0$, then $2=0$': true for formal reasons, simply because the ...
Comment: ... antecedent is necessarily false, and uninteresting otherwise.
Comment: @Daniel: You're very welcome!
Comment: Thank you so much for your detailed explanation Professor! The details really helped me a lot to understand the proof. But I still don't quite get your last paragraph. For the $\forall j\in I A_j \subseteq\bigcup_{i\in I}\mathscr P(A_i)$, which part did you apply the def. of the union on to derive this?

Sorry about the late reply as I am working full time and didn't get to read it till yesterday
Comment: Thank you so much Professor! Just one final, curious question: you mentioned the theorem if$x\in y \subseteq z, then x\in z$. What if y is an empty set? Since it is automatically false that an empty set has an element, it would render the subset relation false, thus the entire if...then true (since the antecedent/if clause is false). Would that be an instance of vacuous truth?
Comment: Thank you so much Professor for your detailed explanations and patience! :)

Proof of indexed family set


What is needed for an electric woodwind?

Question: My wife is a music teacher. She's a classically trained saxophonist, and has been playing almost all of her life. Recently she saw a video which included an electric woodwind, and she just about went nuts when she saw it ("I want one!").
I took note as a birthday present, and am now trying to find a bit of information about what is necessary for her to use it if I were to get one for her. I understand that she'd need the following:

The horn
A monitor/amp

What else? Does she need a mixer? Does she need to purchase soundfonts?
Specifically I am looking at these 3 models, depending on what she ends up needing:

Akai Pro - EWI USB
Akai Pro - EWI4000S
Yamaha - WX5 Wind MIDI Controller

Any help would really be appreciated.
Comment: I answered some of these on reddit where you posted essentially the same question. However, it occurs to me that if your wife wants to start experimenting, you might want to look at the Pico from eigenlabs. It's a completely different approach but with the Fingerer Agent (part of their software) you can probably make it approachable to someone familiar with the Boehm fingering.
Answer: I have the EWI USB. As mentioned by Meaningful Username, it doesn't have any in-board sounds, so I can't play it stand-alone -- it has to be plugged in to a computer. While it does come with its own softsynth program (based on Garritan's Aria Player), and a decent set of samples, it can also be used as a generic MIDI controller, which is what I usually do. I use it with my DAW (Reaper), which hosts SFZ (a VST soundfont player), and whatever free soundfonts I've happened to find online. I don't know if the ones with in-board synths can be directly reprogrammed (I'd guess not), but I'd be shocked if they couldn't also operate with a computer as above.
When I do play it like that, to control soundfonts, I have to program Reaper to interpret the MIDI signals in a way that makes more sense. For instance, I completely turn off the "Velocity" response, and route the breath signal to control the Expression CC. This allows my to play a note that starts out quietly, and slowly swells in volume. With the velocity response turned on, it would start out with a softer overall volume, and would be unable to swell to full volume. I could probably also set this up in the EWI software directly, but I have a template track set up in Reaper that does it all for me.
One extra thing to note about the playing technique -- and it took me a long time to realize this -- you don't close your mouth all the way around the breath sensor when playing. It lets very little air through, so if you try this for very long, you will end up needing to take a breath while your lungs are still full, which feels a bit like suffocating. Instead, the recommended technique is to "leak" air out the corner of your mouth while playing, in a controlled fashion. Coming from a woodwind background, it feels weird to do it the first couple times, but you get used to it. The sensor is based off of breath pressure, not velocity, so the air doesn't have to be moving very fast. You just time your "leak" rate so that your lungs are sufficiently empty by the time you need to breathe.
One final note: I'm so used to controlling expression via breath, that I've also bought a breath controller for my MIDI keyboard. Yamaha used to make these, but discontinued them for some reason. But there is now a new product being made in Europe. Now I can play my keyboard like a MIDI melodica!
Answer: Although EWIs are MIDI controllers, capable of controlling any MIDI devices, some also have built in sounds and headphone sockets. @Meaningful Username has been more diligent than me and checked out your links (!) - he says the middle one has built in sounds. Therefore, with this, you should be able to get started with just the instrument and headphones. This will allow you to play "silently" and get used to the instrument. When you want to start playing out loud, with other people for instance, you need to get an amplifier and a lead. I reckon a keyboard amp would be best to respond to the pitch range and range of sounds of a MIDI instrument.
Comment: Thank you so much! So, based on the responses, it looks like the 4000s would give her the most flexibility. I could see her having fun with it, but I think she'd also be using it to put together scores for her students (anything that lets her spend less time sitting in front of finale/garageband/musescore for hours), so I think just a straight midi controller would be too limiting. It also sounds like I should be picking up a midi cable and a keyboard amp.
Comment: Does your wife already input music onto her computer using a MIDI keyboard? If not, she may need a MIDI interface, if she wants to use the EWI to input music into Finale etc.
Comment: She had an ancient midi interface somewhere (though she may have given it away since it wasn't getting used). I'll have to take a gander around her studio when she's not here. I know she DOES have a midi/USB cable, so maybe that's a possibility depending on the software. Otherwise, I don't think MIDI interfaces are that crazy expensive.
Comment: The EWI USB (which doesn't have in-board sounds) just uses a USB cable, but looking at the specs for the 4000s, it seems that's not the case, so yes, you would need some way of getting MIDI signals into a computer.
Answer: Have you watched the demo video for the Akai EWI USB? It explains a lot.

There are other videos on YouTube that you can search for.
By the way, the earliest electronic wind instruments got their start in the late 1970s and through the 80s. You can hear them on certain Steely Dan tunes, and even on Michael Jackson's Thriller.
The saxophonist most associated with electronic wind instruments is the jazz musician Michael Brecker.
Comment: Youtube is blocked for a lot of people and videos can get lost. Could you summarize some of the relevant parts of the videos in your answer to keep it useful? Thanks
Comment: You can use the EWI to trigger any VST or AU virtual instrument synthesizer or sample player or soundfont that runs on Windows or Mac OS X. This is because the instrument transmits MIDI data to the host computer.
Answer: You'll need a Controller, a Synthesizer/Sound Module & Speakers/Headphones/Amp.
The Akei EWI4000 is both a Controller and Synthesizer. So it's a cost effective starting point.
The USB EWI is just a Controller and might be useful if you're already bringing a laptop (for the soft-synth) to gigs, but the guy I know who plays one will frequently (about once every 10ish hours) have his synth software freeze up. (Think "Fermata from Hell" until the program is killed.)  Don't know if this can be blamed on his machine or his choice of software...  This may be a decent option in a studio, but I wouldn't take one on stage.
I personally play a WX5 controlling a Yamaha VL70-m with great results, though if I was purchasing today I might go with an EWI4000 & a VL70-m Motif Rack XS with Patchman Music's custom sound banks to get the best of both worlds.
For an amp, I just recently upgraded to a Bose L1 and am very satisfied.

BTW:  Soundfont usually implies a Sample based form of synthesis.  While not a bad choice, it is unfortunately not the best choice for a WindSynth setup.  I believe that the EWI4000 uses FM based Synthesis.  Yamaha's Virtual Acoustic products (like the VL70-m) are very well regarded.  If you must use Sample based synthesis, make sure your sounds include legato versions.

update:
Yamaha has discontinued the VL70-m.  (much sadness)  The folks at Patchman Music seem to like the Motif Rack XS, but even with Patchman's custom sound banks, I dread the day my VL70-m dies....
Comment: @CalebHines, I'd say he experiences 1 event in every 10 hours of play time.  That's probably OK in the studio, but not something I'd want to experience on stage.
Comment: I don't think I've had frequent problems with my EWI USB (or the software I use) freezing up, but I also haven't played it in a live setting. With the complexity of the toolchain I use, the possibility is real enough that I could envision it happening, if "Murphy" were feeling particularly legalistic.
Answer: I'm currently on my second EWI4000 (last one got lifted in my trunk on the road) with hardly a complaint. The EWI really feels solid and well constructed. It has a good heft for being so compact, feels almost like a real instrument.
I also like the built in synth. It really allows for total anywhere playing. I believe it also comes with software for editing and replacing the sounds on the EWIs memory banks. And there are plenty of collections of amazing synth sounds already built up for the device (you might even be able to find the ones Brecker used).
This EWI of mine is currently about four years old, so I'm not sure if they've changed pickups, but it has a 1/4" and headphone jack as well as DC power spot and batteries (which last longer than one would expect).
Answer: AKAI has sadly, stopped making pro-level gear because there is a much bigger market for cheap stuff. The new ones are crap construction compared to the old 3030/3020 stuff. I had an EWI USB, it broke under warranty, and Akai were totally useless about it. I've spoken with other players who have had theirs act up after a year or two aswell, octave rollers sending the wrong signal, sketchy device recognition, etc. I won't buy one again.
The old 3020/3030s are huge, but are professional instruments. Even before it broke, the EWI USB was nowhere near as sensitive or responsive as the 3000 series. Those you can alter the response curve on all the inputs really well, they feel like instruments. Brecker played those ones. I wish they would make a modern controller for 3 times the price of the EWI USB and do it right, I'd be all over it.
If your partner is not a serious wind player, they will probably think the USB version feels fine. If they're a pro or high level (ie could be in music school etc) player, they will definitely notice the difference in latency and responsiveness between a 3000 analog controller and the later digital ones (USB, 4000).
Comment: Hm, that is good feedback, and I appreciate it. My wife is a professional music teacher for both public schools and private, plus she does light playing professionally (she has a MME in classical Sax). I still am thinking it may be worthwhile just to make things easier when she is putting together music for students, so maybe the lower end is the better choice.
Answer: The first and third links are midi controllers, so you'll need something to interpret the midi, like a computer or synthesizer. The middle link has built in sounds, so only headphones is needed in order to produce sound.
Comment: Thank you so much for the help! Do you know if the built in sounds can be overwritten with additional soundfonts? It says there's a built in analog-synth but not whether or not custom sounds can be used.
Comment: You can use any VST or AU virtual instrument synthesizer or sample player or soundfont that runs on Windows or Mac OS X. This is because the instrument transmits MIDI data to the host computer.
Answer: Your wife might also consider a breath controller like this
http://www.tecontrol.se/products/usb-midi-breath-controller
You can see it demoed in the video


Enviar email para todos os registrados

Question: Como posso enviar um email para cada um dos utilizadores registrados na base de dados?
Desta forma só consigo enviar para um utilizador, neste caso é enviado um email para o último user da bd.
<?php
    header("Content-Type: text/html; charset=UTF-8");

    $sql = "SELECT * FROM `user`";
    $query = $mysqli->query( $sql );
    if( $query->num_rows > 0 ) {

         while($row = $query->fetch_assoc()) {
             $email[]=$row['email'];
             $u=$row['username'];
         }

        $to = "$email";
        $subject = "Assunto";
        $txt = "texto exemplo";

        $headers = "From: suporte@localhost" . "\r\n" .
        "CC: suporte@localhost";

        mail($to,$subject,$txt,$headers);

    } else {

    }
?>

Comment: Joga o `mail()` dentro do while então.
Comment: Como vc quer fazer? um email para cada pessoa ou um email para todo mundo?
Comment: um email para cada pessoa @rray
Comment: certíssimo @rray :)
Comment: Opa, só alguns comentários que você deveria se atentar. Quantos e-mails são? Onde a aplicação está hospeda vai suportar o envio? Não existe limites de disparo por hora? Se não ver esses detalhes você pode simplesmente bloquear o envio de e-mail do servidor. Entre outros, como colocar o domínio em black list e por aí vai...
Answer: Tente algo como no exemplo abaixo. Seu problema era que a função mail estava fora do laço, desta forma ela só seria excutada uma unica vez. Dentro do while ela enviará um email para cada registro.
header("Content-Type: text/html; charset=UTF-8");

$sql = "SELECT * FROM `user`";
$query = $mysqli->query( $sql );

if( $query->num_rows > 0 ) {

    $headers = "From: suporte@localhost"."\r\n"."CC: suporte@localhost";

    while($row = $query->fetch_assoc()) {

        mail($row['email'], "Assunto", "texto exemplo", $headers);
    }
}

Recomendo ler e utilizar o PHPMailer

Enviar email para todos os registrados


entity_reference field widget as select instead of autocomplete

Question: Is there a select widget I can use instead of autocomplete for referencing entities? Right now I am using this in my baseFieldDefinitions function:
->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => 60,
      'placeholder' => '',
    ),
  ))

but I need to have a select widget instead. Any ideas?
Answer: I was able to change the widget from the field config page. The key used by drupal was options_select, so I updated the type to:
'type' => 'options_select'

Comment: note that the select widget has different settings (actually none I think), so make sure to update that as well. In general, to figure out what options you have, you can always create a field of the same type in the UI (or make it configurable), then export the created view/form display and convert the YAML type + settings back into PHP for your base field definition.


Uniform Random on $(-\infty,\infty)$

Question: Imagine picking a 1 when any real number is equally likely.  What is the pdf?  Does this idea have a known use?  What is its name?
There could be a use for a uniform random real number.  It could end up always being integrated.  It could be a prior for a number that is completely unknown.
It would be like a delta function, which integrates to a finite number though it doesn't have a well-defined value at zero.  The delta function is greater than any number at zero.   This uniform random on (-inf,inf) would be not well-defined anywhere.  It would be less than any positive number and greater than zero.  What is it?
Comment: @gung All these statements have to taken somewhat metaphorically: after all, a "delta function" is not a function and it is (evocative) nonsense to assert it is "greater than any number at zero." Formally, what's going on is a process of completing a function space. Delta functions arise as limits of absolute continuous probability densities as their essential support shrinks to a point; improper distributions arise as limits of a.c. densities that are rescaled arbitrarily greatly. As such, they "integrate" to unity in almost the same sense a delta function does.
Comment: Look up "improper distribution" or "improper prior."
Comment: It does have some names (it's sometimes used as an improper prior in Bayesian stats).

This is not actually possible as an actual probability distribution; you certainly can't generate from it.
Comment: I think you're wrong that it would "integrate to a finite number". If you had a uniform from $-\infty$ to $\infty$ it wouldn't converge; the area under the curve would be $\infty$.
Comment: Yep, an improper prior is indeed the thing. Like @whuber said, it isn't really a function, but it is a useful idea.  ---- How is it useful?  I don't know a particular case, but I've been trying to apply it to a case comparing a guessed value with a statistic (kind of like hypothesis testing, but somehow Bayesian because it doesn't assume there is an underlying true value I guess).  So far I've been able to get it so I don't have to evaluate it by itself, but rather I can evaluate the integral of it!
Comment: Here's where wikipedia gives this distribution as an example of an improper prior: [link](http://en.wikipedia.org/wiki/Prior_probability#Examples)
Comment: Here's a relevant [draft article](http://arxiv.org/abs/1311.1067) from the arXiv.
Answer: We can also approach the matter as follows: Let $\{X_{n}\}_{n\geq 1}$ be a sequence of real valued random variables following a uniform $U(-n,n)$ distribution. Does the sequence converge in distribution to a random variable?
Convergence in distribution means
$$\lim_{n\rightarrow \infty}F_{X_n}(x) = F_X(x)$$
where the RHS is a distribution function, and the equality to hold for every $x$ for which  $F_X(x)$ is continuous.
Our distribution function is
$$F_{X_n}(x)= \begin{cases}0&\text{if $x<-n$}\\\frac{x+n}{2n}&\text{if $x\in[-n,n]$} \\1&\text{if $x> n$.}\end{cases}$$
The first and the last branch are not defined as $n\rightarrow \infty$, since there is no $x$ lower than "minus infinity", or higher than "plus infinity". Then
$$\lim_{n\rightarrow \infty}F_{X_n}(x) = \lim_{n\rightarrow \infty}\Big (\frac{x}{2n} + \frac 12\Big) = 0+\frac 12$$
The constant function $1/2$ does not satisfy the properties of a distribution function, specifically
$$\lim_{x\rightarrow -\infty}\frac 12 =\frac 12 \neq 0,\;\;\lim_{x\rightarrow \infty}\frac 12 =\frac 12 \neq 1$$
The fundamental entity associated with a random variable is the cumulative distribution function, and not the probability density function. Since the limit of cdfs converges to a function that is not a cdf, the sequence does not converge to a random variable. Of course, as the comments indicated, this does not make it a useless concept, quite the contrary.
ADDENDUM Feb 1, 2014.
I found a nice piece of history related to this question: A.Rényi, in
Rényi, A. (1955). On a new axiomatic theory of probability. Acta Mathematica Hungarica, 6(3), 285-335. motivates his axiomatic formulation of probability in terms of conditional probability by writing (p.285), among other things that

"In the theory of KOLMOGOROV it has, for instance, no sense to speak
  about a probability distribution which is uniform on the whole real axis or
  on the whole plane, further it has no sense to say that we choose an integer
  in such a way that all integers (or all non-negative integers) are equiprobable."

Uniform Random on $(-\infty,\infty)$


Subgroup structure of $\mathbb{Z}_{32}$.

Question: Hello I'm doing Abstract Algebra problems for practice and one of them asks for the subgroup structure of $\mathbb{Z}_{32}$ and the main question I have is what does $\mathbb{Z}_{32}$ mean? I have never seen that notation before. Something tells me it has to do with modulo. Anyway I know it seems like a dumb question and i have googled it but haven't found anything on what it means and my book never mentions it. Thank you for the responses in advance
Answer: It means the additive group of integers modulo $32$. You might have seen it written before as $\mathbb{Z}/32\mathbb{Z}$ or $\mathbb{Z}/32$. It is isomorphic to the cyclic group $C_{32}$ with $32$ elements, or equivalently the group with one generator $x$ subject to the relation $x^{32}=1$, i.e. the group presented by $\langle x \mid x^{32}=1 \rangle$.
Pick whichever of the above you prefer, and you'll end up with something equal or isomorphic to $\mathbb{Z}_{32}$.


Differential forms and their meaning

Question: I have been reading the book "An Introduction to Manifolds" and i have a question. So we know that for a $C^\infty$ function we can get a 1-form by doing its differential. My question is, when we write $dx$ for example in $\mathbb{R}^3$ what is the function that we are doing the differential ?Is it the function $w=x$? is it the projection onto the first coordinate?
Thanks.
Comment: Yes it is the projection $(x,y,z)\mapsto x.$
Answer: Yes, it's the projection $(x,y,z)\mapsto x$.
In a general manifold, any chart $\varphi:U\to\Bbb R^n$ determines a local coordinate system on $U$, and the coordinate maps are $x_i=\pi_i\circ\varphi$.

Differential forms and their meaning


curl not working and cant show the print_r data

Question: //   buat fungsi http request
 function http_request($url){

// persiapan curl
 $ch = curl_init();

//  set url
 curl_setopt($ch, CURLOPT_URL, $url);

// fungsi transfer nilai yg berupa string
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// mematikan ssl verify dan peer verify untuk localhost (ganti valuenya bila sc ini berjalan di hosting
 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

// tampung hasil ke dalam variable output
 $output = curl_exec($ch);

// tutup curl
 curl_close($ch);

//  mengembalikan hasil curl
 return $output;

   }

// panggil fungsi http_request (url / link api)
$data = http_request("https://indonesia-covid-19.mathdro.id/api/provinsi/");
$data = json_decode($data, TRUE);

echo "
";
    print_r($data);
echo "
";

?>

why my curl is not working, what the problem? my machine? or my code?
i already try to restart apache, but the problem still persist, curl enabled btw
update:
im sorry, the last api service is currently down, but i already change it and the problem still persist, the problem is print_r print nothing, sorry if the question is less to understand, I am a beginner here
pls help me, thanks
Comment: _"why my curl is not working, what the problem? my machine? or my code?"_ - Before we can start helping you, you need to give us a proper description of what "not working" means. What actually happens? Wrong result? Error messages? Your computer catches fire? Have you checked the webservers error log? Have you checked what it returns before you do `json_decode()`? _"not working"_ can mean anything.
Comment: I don't know if the URL is the correct one, but when trying it in a browser, it times out.
Comment: sorry, the last api service is down, im already change it to new one, and the problem is print_r print nothing
Comment: Don't you have error log?
Comment: The posted code works perfectly fine when testing it with the updated URL. I get a proper output from `print_r($data)`
Comment: thanks, the problem was resolved yesterday, but I don't know what to do on Stackoverflow after the problem is resolved, the cause of error is I'm running php file directly on browser not via localhost and the current api is down
Answer: It seems like your json_decode($data, TRUE); returns null. Please check that $data is a valid json string before you run this line $data = json_decode($data, TRUE);, otherwise it will return null, and print_r(null) will print nothing
Comment: We should hold off on writing answers until the OP has told us what happens. Right now, we have no clue what their actual issue is.
Comment: i think the url is correct json string, i already update it to new one, you can check it above


Como acessar o nome e o endereço na Classe Cliente, e acessar descrição e preço na Classe Produto em Java, estando na Classe Caixa?

Question: eu tentei usar os seguintes comandos:
// Solicitando o nome do cliente
nome = input.toString();
compra[i].getCliente().setNome(nome);
            // Código do produto a ser comprado, que é o endereço da posição do vetor
            System.out.print("Produto: ");
            codigo = input.nextInt();

            //  compra[i].getProduto().Descricao = ;

Segue meus códigos abaixo:
import java.util.*;

public class Venda {
    int quantProduto = 5;
    int i;
    int numProdutos;
    double total;
    Date data = new Date();
    private Cliente cliente;
    private Produto [] produto;

    public Venda(Date data, Cliente cliente) {
        this.cliente = new Cliente();
        this.data = data;
    }

    public Venda(Date data, Cliente cliente, Produto[] produto) {
        this.data = data;
        this.cliente = new Cliente();
        this.produto = new Produto[quantProduto];

    }

    public double getTotal() {
        return this.total;
    }

    public void adicioneProduto(Produto p) {
        produto[i] = p;
        numProdutos++;
    }

    public Produto getProduto(int i) {
        return this.getProduto(i);
    }

    public int getNumProdutos() {
        return this.numProdutos;
    }

    public String imprimeVenda() {
        return data + " " + cliente + " " + produto[i];
    }
}

public class Cliente {
    private String nome;
    private String endereco;

    public Cliente(String nome) {
        this.nome = nome;
        this.endereco = " ";
    }

    public Cliente() {
        this.nome = "";
        this.endereco = "";
    }

    public String getNome() {

        return this.nome;

    }

    public void setNome(String nome) {

        this.nome = nome;
    }

    public String imprimeCliente() {

        return "Cliente: " + this.nome + "\n Endereco: " + this.endereco;
    }

}

public class Produto {

    private String[] descricao= {"arroz", "feijao", "farinha", "macarrao", "açucar",
                                  "óleo", "vinagre", "azeite", "sal", "xerém"} ;
    private double[] preco = {5.00, 7.00, 4.50, 3.20, 2.50, 7.50, 2.00, 11.00, 1.50, 3.50};
    private int total;

    public Produto(String[] descricao, double[] preco) {
        this.descricao = descricao;
        this.preco = preco;
    }

    public double getTotal() {
        return total;
    }

    public double[] getPreco() {
        return preco;
    }

    public String imprimeProduto(String descricao, double total) {
        return "Produto: "  + this.descricao + " Total:" + this.total;
    }

}

import java.util.*;

public class Caixa {
    int quantProdutos = 5;
    Date data;
    int codigo;
    String nome;
    String iten;
    double preco;
    Venda [] compra;

    Scanner input = new Scanner(System.in);

    public boolean atendimento (String resposta) {

            if (resposta == "S" || resposta == "s") {
                return true;
            }

            else{
                return false;
            }

        }

    public <auxiliar> void Compra() {
        int i = 0;
        String resposta;
        Venda [] compra = new Venda[quantProdutos] ;

        boolean atender = true;

        while (atender == true) {

            System.out.println("Continuar atendendo (S/Sim) (N/Não)?");
            resposta = input.nextLine();

            atender = atendimento(resposta);

            if (atender == true) {

                // Solicitando o nome do cliente
                nome = input.toString();
                compra[i].getCliente().setNome(nome);

                // Código do produto a ser comprado, que é o endereço da posição do vetor
                System.out.print("Produto: ");
                codigo = input.nextInt();

                //  compra[i].getProduto().Descricao = ;

            }

            if (i==quantProdutos) {
                quantProdutos = 2 * quantProdutos;
                Venda [] auxiliar = new auxiliar [quantProdutos];
                this.compra = auxiliar;
            }
            i++;
        }
    }

}

Answer: Ewerton, seu código está um pouco confuso, mas acho que entendi o que você deseja fazer.
Antes de mais nada, você precisa passar os valores para os atributos da sua classe utilizando o construtor. Essa é a forma mais utilizada, pois você terá os valores carregados junto com a instância da classe.
Além disso, a sua classe produto não tem os gets e sets da propriedade descricao, que é a propriedade que você vai utilizar na classe Caixa para recuperar os dados através do índice do vetor.
Então acredito que você poderia fazer algo do tipo:
Classe Produto
public class Produto {

   private String[] descricao;
   private double[] preco;
   private int total;

   public Produto(String[] descricao, double[] preco) {
       this.descricao = descricao;
       this.preco = preco;
   }

   public double getTotal() {
       return total;
   }

   public double[] getPreco() {
       return preco;
   }

   public string[] getDesricao() {
       return this.descricao;
   }

   public String imprimeProduto(String descricao, double total) {
       return "Produto: "  + this.descricao + " Total:" + this.total;
   }

}

Depois de corrigir a classe Produto, dentro da classe Caixa você deve criar uma instância da classe Produto e passar os valores como parâmetros no construtor. Dessa forma:
Classe Caixa
// Suas variáveis
int i = 0;
String resposta;
Venda [] compra = new Venda[quantProdutos] ;

// Crie duas variáveis com os dados que serão passados para o construtor
String[] descricao = {"arroz", "feijao", "farinha", "macarrao", "açucar",
                              "óleo", "vinagre", "azeite", "sal", "xerém"} ;
double[] preco = {5.00, 7.00, 4.50, 3.20, 2.50, 7.50, 2.00, 11.00, 1.50, 3.50};

// Depois crie a instância da classe Produto passando os valores no construtor
Produto produto = new Produto(descricao, preco);

                 //

                //

// Código do produto a ser comprado, que é o endereço da posição do vetor
System.out.print("Produto: ");
codigo = input.nextInt();

//Agora você pode acessar os dados do Produto através da variável codigo:

String descricao = produto.getDescricao()[codigo];
String preco= produto.getPreco()[codigo];

Comment: Oi Jaderson!

Muito obrigado por sua ajuda!
Comment: Deu certo Ewerton? Se consegui te ajudar, marque a pergunta como aceita. Obrigado!
Answer: Você precisa criar uma instância da classe Cliente e da classe Produto e passar elas pra dentro da classe Caixa. Não sei quais são suas necessidades específicas mas umas das formas de se fazer isso é:
Cliente cliente = new Cliente ();
Produto produto = new produto ();

Caixa caixa = new Caixa();
caixa.compra(cliente, produto);

Comment: Oi Jaderson!

Boa noite!

Eu preciso fazer o seguinte:

) Implemente uma classe Loja que cria objetos do tipo Cliente, Produto e Venda e exibe na tela o cliente
que está realizando uma compra, os produtos comprados e o valor total da venda.
c) Nomeie os relacionamentos entre as classes.
d) Adicione uma classe Caixa à sua modelagem de classes. Um caixa contém uma coleção de vendas.
Comment: A classe Caixa deve possuir operações para
incluir um novo produto na venda atualmente aberta.
e) Adicione um construtor sobrecarregado à classe Venda de modo que se possa criar uma venda
passando-se para ela um arranjo de produtos ou a quantidade máxima de produtos da venda.
Comment: Depois que fiz as mudanças necessárias para que haja um compartilhamento dos dados, está dando um erro que não consigo retirar...


Configure IIS to only server certain files to requests originating in the US?

Question: The transfer of encrypted data or encryption systems from the US to foreign nations is tricky business as encryption can be categorized as a munition and can be governed by US export laws.
I plan to be starting a website that will contain multiple encryption algorithms written in Javascript. I do not want these js files to be distributed to anybody with an IP outside of the US as I feel I might be breaking export laws (the servers, at least in the beginning, will be in the US). I know there are plenty of ways to spoof IP to get around this but I feel this is the best kind of restriction I could realistically implement and that it would prove intent not to transmit out of the country (due diligence).
For various reasons I do not want to encrypt anything server side. That is out of the question.
I could write up some server side code to geocode the IP address and either return the JS or not but I'm thinking there might be some configuration setting I can set in IIS. I don't want to rewrite the wheel if something already exists.
Can IIS be configured to restrict access to certain files based on IP address and geocoding? Am I being too paranoid?
Answer: You could use IIS's "IP Address and Domain Restrictions", but your list of IP ranges for either deny list, for outside US, or allow, for inside US, will be rather large and will have to scanned for every request. If you don't expect high traffic, then it might not be an issue.
There is no geoip capabilities out of the box in IIS, you'd have to hit some geolocation service from a HttpModule in your app and may be cache your lookups for some time for the same IP's or IP ranges.
Why not host these js files on Azure Storage or AWS S3 in non-US region? You will not be "exporting" anything from US, just merely referencing them from elsewhere?


PHP - Formulário com validação de campos enviado repetidas vezes

Question: Seguindo sugestão do moderador Sérgio, estou enviando uma nova pergunta, visto que a anterior foi sinalizada como duplicada e a única resposta recebida não resolveu o problema. Mas quero deixar claro que, todas as sugestões dadas em respostas às dúvidas (Formulário inserindo duas vezes no banco e Como evitar o envio de requisições PHP seguidas), foram testadas e não resolveram o meu problema.
As sugestões dadas não funcionaram porque o meu formulário faz validação de campos e com as implementações sugeridas, vários formas de desabilitar o botão Enviar, meu form parou de validar os campos.
Problema: eu tenho um formulário em PHP que envia por e-mail os dados fornecidos pelo usuário via método Post. Neste formulário eu faço a validação de alguns campos (CPF e alguns campos são obrigatórios). Quando o usuário clica em "Enviar" o processo às vezes é lento e, alguns usuários, clica várias vezes no "Enviar" causando o envio do mesmo formulário várias vezes.
<?php
require_once '_js/ValidaCPF.php';

$todos_campos_preenchidos = TRUE;
$msg_email_enviado = FALSE;
$ValidaCPF = TRUE;

if (isset ($_POST['salvar'])) {

$contato = $_POST['contato'];
$email = $_POST['email'];
$cpf = $_POST['cpf'];

if(trim($_POST['contato']) == '') {
    $todos_campos_preenchidos = FALSE;
}elseif (trim($_POST['email']) == '') {
    $todos_campos_preenchidos = FALSE;
}elseif (trim($_POST['cpf']) == '') {
    $todos_campos_preenchidos = FALSE;
}

$ValidaCPF = ValidaCPF($cpf);

If (($todos_campos_preenchidos) && ($ValidaCPF)) {

$para = "email@example.com";
$mailoculto = "firstname.lastname@example.com";

    //Codificações para envio do e-mail
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers .= "Reply-To: $email". "\r\n";
$headers .= "Bcc: $mailoculto";

    //Assunto do e-mail
    $assunto = "Contato";

    //Corpo da mensagem
    $mensagem = "

Assunto:	Envio de contato
";
$mensagem .= "
Contato: 	".$contato."
";
    $mensagem .= "
E-mail: 	".$email."
";
    $mensagem .= "
CPF: 	".$cpf."
";
    $mensagem .= "
Data e hora: 	" . date('d/m/Y - H:i') . "
";
    $mensagem .= "
IP's: 	" . get_ips() . "

";

    //Envio do e-mail
    If (mail($para, $assunto, $mensagem, $headers)){

        //Enviando e-mail de confirmação para o e-mail cadastrado
        $assunto = "Confirmação de Contato";
        $mensagem_confirmacao = "Prezado(a) " . trim($contato) . ",

";
        $mensagem_confirmacao .= "Você está recebendo este e-mail por ter solicita cadastro.

";
        $mensagem_confirmacao .= $mensagem;
        $headers_confirmacao  = 'MIME-Version: 1.0' . "\r\n";
        $headers_confirmacao .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
        $headers_confirmacao .= "Reply-To: firstname.lastname@example.com". "\r\n";

        mail(trim($email), $assunto, $mensagem_confirmacao, $headers_confirmacao);

        $contato = NULL;
        $email = NULL;
    $cpf = NULL;
        $msg_email_enviado = TRUE;
    }
}

}
Chamada do form:
<form method="POST" name="solicitacao" action="">

CPF do empregado:*
<input type="text" name="cpf" class="mask-cpf" size="29"
<?php if ($_SERVER['REQUEST_METHOD'] == "POST") { echo "value=\"" . $cpf . "\""; }?>>

<input type="submit" value="Enviar" name="salvar">

Answer: Para quem quer manter a validação value do botão submit e está utilizando jquery há a seguinte solução.

var formEnviado = false;

$("#form").on("submit", function() {
    if(!formEnviado){
        formEnviado = true;
        return true;
    }else{
        return false;
    }
});

Answer: A forma mais simples, sem mexer muito no código seria só controlar se já foi ou não submetido...
$('input[type=submit]').on('click',function() {
    $(this).attr('disabled','disabled');
});

Fiz em jquery, mas podes transformar em javascript puro..
Comment: Fiz da seguinte forma e não funcionou, porque perdeu a validação.


Detailed proof of why integral over the upper semi-circle in $C$ of $\frac{e^{ix}}{x^2 + a^2}$ goes to $0$ as the radius goes to $\infty$?

Question: This is a follow up question to this question: Computing $\int_{-\infty}^{\infty} \frac{\cos x}{x^{2} + a^{2}}dx$ using residue calculus. For clarity, I'll reproduce the question here: calculate $\int_{-\infty}^\infty \frac{\cos x}{x^2 + a} \ dx$ using the residue theorem. The answer given lets $\gamma$ be the semi-circle centered at $0$ with radius $R$ in the upper half of the complex plane, and we can further let $\gamma_1$ be the arc of $\gamma$, and $\gamma_2$ be the part of $\gamma$ along the real line.
I'm working through the proof, which involves using the fact that $\cos x = \Re(e^{ix})$ to solve the problem of $\cos x$ not being bounded if $x$ is allowed to be imaginary. However, it is stated simply that the integral
$$\int_{\gamma_1}\frac{e^{ix}}{x^2 + a^2}\ dx \to 0\ \ \ \text{ as } \ \ \ R \to 0,$$
which I don't fully understand. I have the following bound on the integral:
$$\left|\int_{\gamma_1}\frac{e^{ix}}{x^2 + a^2}\ dx \right| \le \sup_{s \in \gamma_1}\left|\frac{e^{ix}}{x^2 + a^2}\right| \cdot \text{length}(\gamma_1). $$
But I am having a difficult time getting the RHS to go to $0$ as $R$ goes to $0$. Clearly,
$$|e^{ix}| \le 1,$$
but then we are left with
$$\left|\int_{\gamma_1}\frac{e^{ix}}{x^2 + a^2}\ dx \right| \le \sup_{s \in \gamma_1}\left|\frac{1}{x^2 + a^2}\right| \cdot \pi R. $$
Now, we have $x = z + iy$, where $-R \le z \le R$, and $0 \le y \le R$. But how can I find a lower bound on $|x^2 + a^2|$? I'm having a hard time visualizing what it should be. I've tried expanding out $x^2$, and I have that
$$|x^2+a^2| \ge |z^2 + 2izy + a^2| - |y^2|,$$
but can't get anywhere from there. It feels as if I should eventually get $|x^2 + a^2| \ge R^2+a^2,$ but I can't really prove this.
I know this is probably a very silly question, but I seem to always be misunderstanding the details for proofs in complex analysis, and I want to make sure I understand every piece of this one.
Answer: First a notational issue.  The variable in the integral over $\gamma_1$ should be $z$, not $x$, because $x$ in this context (to prevent ambiguity) needs to represent a real variable.  But on the arc $\gamma_1$, you'll necessarily encounter non-real values.
On $\gamma_1$ you can parameterize using $z = Re^{i\theta}$, where $0 \le \theta \le \pi$.  So actually the integral is:
$$ \int_{\gamma_1} \frac{e^{iz}}{z^2 + a^2} \, dz = \int_0^\pi \frac{e^{iRe^{i\theta}} Rie^{i\theta}}{R^2e^{2i\theta} + a^2} \, d\theta $$
Then with absolute values we get:
\begin{align}
  \left|\int_{\gamma_1} \frac{e^{iz}}{z^2 + a^2} \, dz\right| &= \left|\int_0^\pi \frac{e^{iRe^{i\theta}} Rie^{i\theta}}{R^2e^{2i\theta} + a^2} \, d\theta \right|\\[0.3cm]
    &\le \int_0^\pi \left|\frac{e^{iRe^{i\theta}} Rie^{i\theta}}{R^2e^{2i\theta} + a^2}\right| \, d\theta\\[0.3cm]
    &\le \frac{R\pi}{|R^2 - a^2|}\\[0.3cm]
    &\to 0 \text{ as } R \to +\infty
\end{align}
Where did the $|R^2 -a^2|$ in the denominator come from?  Just focusing on the denominator and using the reverse triangle inequality, we have
\begin{align}
  |R^2e^{2i\theta} + a^2| &= |R^2e^{2i\theta} - (-a^2)|\\
    &\ge \big||R^2e^{2i\theta}| - |-a^2|\big|\\
    &= |R^2 - a^2|
\end{align}
Comment: Well explained.. +1.
Comment: Thank you! The example I am working off of (which is for a different problem) completely skips the parametrization, and so I didn't think to try that - but it works out beautifully. I really appreciate your detailed explanation. As for the notational tip - I will definitely avoid that in the future, but the original problem I linked to used $x$'s, and I didn't want to confuse... in retrospect, it's confusing written this way, as well, so I'll avoid doing that again. Thanks again!
Comment: No problem!  Indeed, I did notice the first answer there was using $x$ where it should've been $z$ but I just wanted to make sure you knew otherwise.  Good luck!


Advice on identifying curve shape using quantreg

Question: I'm using the quantreg package to make a regression model using the 99th percentile of my values in a data set. Based on advice from a previous stackoverflow question I asked, I used the following code structure.
mod <- rq(y ~ log(x), data=df, tau=.99)
pDF <- data.frame(x = seq(1,10000, length=1000) )
pDF <- within(pDF, y <- predict(mod, newdata = pDF) )

which I show plotted on top of my data. I've plotted this using ggplot2, with an alpha value for the points. I think that the tail of my distribution is not being considered sufficiently in my analysis. Perhaps this is due to the fact that there are individual points, that are being ignored by the percentile type measurement.
One of the comments suggested that

The package vignette includes sections on nonlinear quantile regression and also models with smoothing splines etc.

Based on my previous question I assumed a logarithmic relationship, but I'm not sure if that is correct. I thought I could extract all the points at the 99th percentile interval and then examine them separately, but I'm not sure how to do that, or if that is a good approach. I would appreciate any advice on how to improve identifying this relationship.
Comment: If your goal is specifically to estimate the conditional 99th percentile, I'd vote for nonlinear quantile regression (of some sort--I don't know the R packages well), since it doesn't sound like you know the true functional form. I still wasn't clear to me from your previous question what the actual goal is, though, so I would reiterate the comment on your previous question from Spacedman Jan 4 at 17:01
Comment: tau=0.5 in the rq() function.
Comment: Can you update the plot to add the conditional median? this seems to me more like a quantile crossing problem than a data transformation problem...
Comment: @user603 What do you mean by the conditional median? (I searched online but am not sure how to calculate it)
Comment: There are a couple of good questions on the site already talking about transforming data like this, see http://stats.stackexchange.com/q/1444/1036 or http://stats.stackexchange.com/q/298/1036
Comment: Why you are fitting `y ~ log(x)` and then plotting it on `y ~ x`? Wouldn't it make more sense to fit `y ~ x`?
Answer: All models are wrong, but some are useful (George Box).  You are forcing a logrithmic shape to your fitted curve, and honestly it doesn't look that bad.  The fit is poor at the tail because there are less points there; the two parameters you have allowed will fit the bulk of the data. In other words, on a log scale, that tail isn't far enough away from the bulk of your data to provide leverage.  It doesn't have to do with the quantile nature of the regression; OLS would also disregard those points (especially on the log scale).
It's pretty easy to allow for some more non-linearity.  I'm partial to natural splines, but again, all models are wrong:
library(splines)
mod <- rq(y ~ ns(log(x), df=6), data=df, tau=.99)

The quantreg package has some special hooks for monotonic splines if that's of concern to you.


SQL Count Distinct Value Oldest DateTime

Question: I'm working with two datasets and attempting to create a new column in the output with a count of unique values. In my query I have multiple Case When clauses where a unique string of numbers from one of the tables will dictate a unique string/sentence value in the output. In the Else statement, any of these unique string of numbers that exists in the 2nd table that doesn't exist in the 1st table (last column in 2nd table, 1st column in 1st table) will result in a summed count in the output. My issue is that the count should only be for the oldest DateTime instance of distinct user id's. I built an edge case to check if my output was working correctly, and it was outputting a count for a userid if they had multiple instances of the same identifier but different strings. I want the output to only count once per identifier per distinct user based on the oldest DateTime.
Some data may look like this:
1581 | billy | abcd | red dead | company1
1903 | bob   | defg | halo 3   | company2
5849 | lilly | hijk | fortnite | company3
1903 | bob   | hijk | fortnite | company3

Some data may look like this:
d83j | 2012-09-28 | 2012-09-28 09:00:00.00 | abcd | 1010
np50 | 2012-09-28 | 2012-09-28 10:45:00.00 | abcd | 1581
j99p | 2012-09-28 | 2012-09-28 11:00:00.00 | abcd | 1581
rn2n | 2012-09-28 | 2012-09-28 18:30:00.00 | defg | 1903
rn2n | 2012-09-28 | 2012-09-28 15:30:00.00 | defg | 1903
rn2n | 2012-09-28 | 2012-09-28 07:30:00.00 | defg | 6211
44ko | 2012-09-28 | 2012-09-28 18:30:00.00 | hijk | 5849

Here is my query currently:
SELECT
  F.Identifier, F.Videogame, F.Developer,
CASE WHEN S.String='1581' THEN 'Made by billy'
     WHEN S.String='1903' THEN 'Made by bob'
     WHEN S.String='5849' THEN 'Made by lilly'
     ELSE 'worked on by someone else' END AS Final_Name,
     COUNT(distinct S.User_ID) as Count
FROM
  table1 as F
JOIN
  table2 as S
ON
  F.Identifier=S.Identifier
GROUP BY
  F.Identifier, F.Videogame, F.Developer, Final_Name

I've attempted to include having and where clauses around the count and sub-querying the count S.User_ID, but none of what I'm doing is getting me what I'm looking to achieve.
Actual output right now looks like this:
abcd | red dead | company1 | worked on by someone else | 1
abcd | red dead | company1 | Made by billy             | 2
defg | halo 3   | company2 | Made by bob               | 1
defg | halo 3   | company2 | worked on by someone else | 1
hijk | fortnite | company3 | Made by lilly             | 1

Because user_id rn2n had multiple instances all with the same identifier, the output should only return the oldest datetime instance (i.e. the 07:30:00.00 instance.) Current output counts distinct user_id per string which is why rn2n counts once for made by bob and once for made by someone else.
Expected output should be this:
abcd | red dead | company1 | worked on by someone else | 1
abcd | red dead | company1 | Made by billy             | 2
defg | halo 3   | company2 | worked on by someone else | 1
hijk | fortnite | company3 | Made by lilly             | 1

Comment: it is not clear why this line `defg | halo 3   | company2 | Made by bob               | 1` should be eliminated  - please explain the logic using this line
Comment: Since user_id rn2n had 3 instances of the defg identifier, only the oldest datetime (i.e. the 07:30:00) row in table2 should be counted in the output. the abcd identifier in the output can have multiple rows because its coming from different unique user_id's.
Comment: got it. make sense. will answer shortly
Answer: Below is for BigQuery Standard SQL
#standardSQL
SELECT F.Identifier, F.Videogame, F.Developer,
CASE WHEN S.String='1581' THEN 'Made by billy'
     WHEN S.String='1903' THEN 'Made by bob'
     WHEN S.String='5849' THEN 'Made by lilly'
     ELSE 'worked on by someone else' END AS Final_Name,
     COUNT(DISTINCT S.User_ID) AS COUNT
FROM `project.dataset.table1` AS F
JOIN (
  SELECT AS VALUE ARRAY_AGG(t ORDER BY datetime LIMIT 1)[OFFSET(0)]
  FROM `project.dataset.table2` t
  GROUP BY User_ID

) AS S
ON F.Identifier=S.Identifier
GROUP BY F.Identifier, F.Videogame, F.Developer, Final_Name

If to apply to sample data from your question - result will be
Row Identifier  Videogame   Developer   Final_Name                  Count
1   abcd        red dead    company1    worked on by someone else   1
2   abcd        red dead    company1    Made by billy               2
3   defg        halo 3      company2    worked on by someone else   1
4   hijk        fortnite    company3    Made by lilly               1


What factors to consider when inventing a new (lab) instrument?

Question: I have the idea for a new instrument which doesn't work with wind/blowing, hitting, or keystroked, but rather pressure.
What factors should an instrument have? Is there a checklist that I can check the attributes of this instrument against?
Answer: As far as I'm concerned, there are two requirements for musical instruments:

It must generate sound.
That sound must be controllable by a human being (or equivalent).

I actually really like this question, though it is based on some premises that I believe are too easily jumped to. I use a generalized definition of music as "organized sound," therefore, the two criteria above are the only things necessary to satisfy an instrument to be used in making music.
Everything else is up to you, including what degree of control the player has over that sound. People have certainly invented instruments that have an element of random chance to them, and by no means do all instruments need to be pitch- and volume-controllable.
If you wish to refine your criteria to "a musical instrument useful for playing the majority of western music", then the requirements will change, but I'm not sure the answers will be as objective as one can be with this question.
Answer: (Edit: Note that I'm treating the question as "What characteristics would a new instrument ideally have?" rather than "What does my instrument minimally need to count as an instrument?" Both are IMO worth asking, although as I've spent time working with new instruments I notice a lot of them run into the same limitations. Hence my list here: )
You should be able to play it with your eyes closed.
It should be worthwhile becoming a virtuoso on the instrument.
There should be a difference between instrument-building and instrument-playing, and you shouldn't have to be an instrument-builder to be an instrument-player.
It should be able to change timbre, as well as volume and pitch, and changing one of those parameters should subtly change the others (this is more opinion that the others, but in my defense it's a carefully considered one)
If it uses power, it should be able to withstand power failure until the end of a song, and if it ever, ever, ever crashes it should reboot hands-free within one musical phrase (where both 'song' and 'phrase' length are determined by whatever style of music this instrument is used in)
Easy, right?
Comment: That thing about power is a bit paranoid (what synth/organ/guitar amp/PA would fulfill this?), but the first three points are definitely good thoughts.
Comment: @leftaroundabout agreed, but isn't that one of the limitations of the instruments you mention? I've played some beautiful concerts in remote locations with no power. Wouldn't it be great if a new instrument could play in that situation? (Edit also added to clarify how I'm treating this question differently from @NReilingh)
Comment: "Wouldn't it be great?" Perhaps not. Such remote locations are great for music, in part _because_ they prevent you from playing certain kinds of instruments. It makes you having to re-invent your music if you're otherwise used to always having power at hand, and such re-boots can be quite healthy to do. If now every instrument could play without power, the remote locations would perhaps lose some of their charm.


For macOS Cocoa, how do I specify a window or a rectangle on the screen for taking a screenshot?

Question: I have written a macOS app for measuring image files, and I wish to add a feature for capturing screenshots. I wish for it to have a user interface for doing it much like what the macOS app "Preview" has.
To use its screenshot function, one does File > Take Screenshot, and one gets a submenu with these options:

From Selection...
From Window...
From Entire Screen

"From Selection..." lets you select a rectangle on the screen by clicking and dragging.
"From Window..." lets you select an app window.
"From Entire Screen" is what it says.
I can find the code for getting the screenshot as an image object, but I haven't been able to find any code for the user-interface part, the part for selecting a rectangle or a window. Does anyone know how to do that? Or else have some code for doing that.
Answer: The following code should give you a window shot:
@objc func myBtnAction(_ sender:AnyObject ) {
 let windowID : Int = window!.windowNumber
 let windowImage: CGImage? = CGWindowListCreateImage(.null, .optionIncludingWindow, CGWindowID(windowID), [.nominalResolution])
 let bitmapRep = NSBitmapImageRep(cgImage: windowImage!)
 let image = NSImage()
 image.addRepresentation(bitmapRep)
 let pngData = bitmapRep.representation(using: .png, properties:[:])
 // your fileURL here
 let fileURL = URL(fileURLWithPath: "/Users/xxxx/Desktop/WndShot.png")
 do {
   try pngData!.write(to: fileURL)
   print("File saved: \(fileURL.absoluteURL)")
   } catch {
   print(error.localizedDescription)
  }
}

I turned off the SandBox.
Comment: That's for getting the image data from the window, and I was asking about how to select the window in GUI fashion, like what one does in Preview. Also about clicking and dragging to make a selection rectangle.
Comment: Is shift-cmd-4 a possibility?
Comment: I've already implemented getting an image from the clipboard, so that would be a good workaround in the absence of code that does it directly.
Answer: Try invoking the screencapture command-line tool:
screencapture -i -c

This will run the default macOS interface for selecting a region on the screen and store the captured image on the clipboard. Use the -Jwindow to capture a window instead:
screencapture -i -c -Jwindow

Or replace the -i flag with the -S flag to capture the entire screen non-interactively:
screencapture -S -c -Jwindow

Comment: So I would use NSTask to spawn a process that runs it? Since I have already implemented using the clipboard, that might work.
Comment: Yes, you can use NSTask for this.


How plot graph with missing data lines?

Question: I have data recorded in time. But some data lines are missing and gnuplot replace them with long lines in these intervals.
How can i set gnuplot to draw nothing instead of draw lines in these intervals?
PS. I don't have free cells in these lines, I dont have these lines at all.
lines:
column 1  ... col 195
13:30:20.8   0.78061899
13:30:21.8    5.969546498
13:32:19.8   17.21257881
13:32:20.8   6.922475345

Answer: If you don't want to draw a line between two points you must insert an empty line in the data file between the two point entries, so that effectively you have
13:30:20.8   0.78061899
13:30:21.8    5.969546498

13:32:19.8   17.21257881
13:32:20.8   6.922475345

This cannot be done with gnuplot directly, but you can use e.g. awk to do the processing on-the-fly:
set timefmt '%H:%M:%S'
set xdata time
filename = 'data.txt'
plot 'awk ''{split($1,d,":"); t_prev = t; t = (d[1] * 60 + d[2])*60 + d[3]; if (t_prev && (t - t_prev > 10)) print ""; print }'' '.filename with lines

Here, the gap threshold is 10 seconds.
Answer: I suppose your miss data identifier is "NaN", then you can use the following command
plot "data" using 1:($2) with linespoints

instead of
plot "data" using 1:2 with linespoints

The former one will ignore the missing data and treat it as blank line and therefore not draw a connecting line across the gap while the latter one will draw continuous, unbroken line.
Comment: No, this has nothing to do with 'NaN'. Some data points just have a large time gap between them.
Comment: This works for me. The advantage of this over the other answer (insert a blank line) is that technique this can be used when only some values are missing. There's nothing wrong with inserting a blank line, if you have no values, but there's nothing wrong with this answer either and it doesn't deserve the downvote.
Answer: Just for the records: there are later questions about the same/similar issue.
Avoid connection of points when there is empty data
How to remove line between "jumping" values, in gnuplot?
Removing vertical lines due to sudden jumps in gnuplot
However, my solutions there require transparent color, which was not available in at the time of OP's question (gnuplot 4.6.5, Feb 2014). Nevertheless, there is a solution without external tools like awk or changing the data.

First solution for gnuplot 4.6.: Instead of a transparent line you use a white line which, however, will cover the grid lines, although it will be hardly visible.

Second solution for gnuplot 4.6 is using vectors. This really interrupts the line and will work for gnuplot 5.x as well.

Data:
 00:00:00    0.406406
 00:00:44    0.339779
 00:01:28    0.986602
 00:02:13    0.17746
 00:02:57    0.0580277
 00:03:42    0.586614
 00:04:26    0.84247
 00:05:11    0.597502
 00:05:55    0.0394846
 00:06:40    0.369416
 00:13:20    0.527109
 00:13:42    0.371411
 00:14:04    0.851465
 00:14:26    0.980312
 00:14:48    0.431391
 00:15:11    0.545491
 00:15:33    0.708445
 00:15:55    0.861669
 00:16:17    0.277122
 00:16:40    0.787273

Script:
### avoid showing a line across larger time gaps
reset

FILE = "SO26510245.dat"

myFmt = "%H:%M:%S"

tGap = 60    # 60 seconds
set format x "%H:%M"
set timefmt "%H:%M:%S"

set xdata time
set ytics 0.5
set key top center noautotitle
set grid x,y

set multiplot layout 3,1

    plot FILE u 1:2 w l lc rgb "red" ti "data as is"

    myColor(col) = (t0=t1, t1=timecolumn(1), t1-t0>tGap ? 0xffffff : 0x0000ff)
    plot t1=NaN FILE u 1:2:(myColor(1)) w l lc rgb var ti "white line"

    myGap(col) = (t1-t0>tGap ? NaN : y0)
    plot t1=y1=NaN FILE u (t0=t1,t1=timecolumn(1),t0):(y0=y1,y1=$2,myGap(0)):(t1-t0):(y1-y0) \
         w vec lc rgb "web-green" nohead ti "with vectors"

unset multiplot
### end of script

Result: (created with gnuplot 4.6.0, from March 2012)

How plot graph with missing data lines?


Triangulation of the topologist's sine curve

Question: Let $X$ be $\{(x,\sin{\frac{1}{x}})\mid x\in(0,1]\}$ together with the vertical set of accumulation points, the vertical line segment at $0$. This is closed subspace of $\mathbb{R}^2$. Is there a triangulation of this space? If there isn't, how would one go about proving this fact? I saw examples, for example in Hocking and Young, of defining a similar simplicial complex, but they omit discussing an explicit homeomorphism.
To be more concrete, let $Y$ be a complex constructed as a collection of $1$-simplices such that there is an "oscillation" on every interval from $1/(2\pi(n+1))$ to $1/(2\pi n)$, together with a vertical set of accumulation points, the vertical $1$-simplex at $0$. It's topology is made by declaring subsets $A\subset Y$ closed if $A \cap \sigma$ is closed in $\sigma$ for all simplices $\sigma$.
Someone tried to explain to me that in the above example, there can't be a homeomorphism, it went as follows. Vertical segment and the "body" of $Y$ are both closed, and they are complements, so they are both open. So $Y$ is open in this topology as union of two open sets. So we are trying to find a homeomorphism that will take an open set to a closed set, which I guess is a contradiction? I am a bit lost in this argument, I would appreciate if someone could verify this is fine. If it is fine, can we construct some complex that will work? Or how could we generalize this contradiction to "arbitrary" complexes? Thanks!
Comment: Hint: Prove that every simplicial complex is locally path-connected.
Answer: The topologist's sine curve $X$ is connected. Assume it has triangulation $K$. This means that the polytope (geometric carrier)  $\lvert K  \rvert$ is homeomorphic to $X$. But a polytope is connected iff it is pathwise connected. Thus $X$ should be pathwise connected, which is not true.


Need help understanding this example of a distribution

Question: Consider the following example of a distribution (given here):

I tried to draw this. If $p=(a,b,c)$ then
$$ X_p = (1,0,-b), Y_p = (0,1,0)$$
Then the planes in the distribution are planes spanned by $X_p,Y_p$.
We see that the plane spanned by $X_p,Y_p$ is a plane that rotates around the vector $Y_p$ as $p$ moves along the $y$-axis.
Assume we had a surface $S$ that was tangent to all this twirling planes. Without loss of generality, assume the surface is located in $\mathbb R^3$ such that the origin is on the surface.
Then we have a plane, coincidentally parallel to the $xy$-plane, that is tangent to $S$ at $0$. In other words: the $xy$-plane is tangent to $S$.
This is as far as I can follow the explanation given in the text. But everything that follows I do not understand.
For example, only because the $xy$-plane is tangent to $S$ at $0$ it is not clear to me why $S$ would intersect the $x$-axis in a line segment (for example, $S^2$ can be tangent to the $xy$-plane an does not intersect the $x$-axis in a line segment).
But even if this was clear to me and I assume that $S$ intersects this axis in a line segment the rest of the explanation is also not clear to me: travelling along an intersection axis does not seem to contradict that the planes are twisting.

Please could someone explain this to me?
Answer: First, let us establish rigorously that the distribution $\xi$ is not integrable, to do so we will use the so-called Frobenius theorem that I recall below:

Theorem. Let $M$ be a smooth manifold and let $\xi$ be a distribution of $M$, then the two following statements are equivalent:

The distribution $\xi$ is integrable.

For all vector fields $X$ and $Y$ of $M$ such that $X,Y\in\xi$, then $[X,Y]\in\xi$.

Sketch. The proof is essentially a recursive use of the straightening theorem for vector fields around a non-singular point. A full proof can be found in the Chapter $14$ of Introduction to smooth manifolds by J. Lee. $\Box$
Going back to your case, even though $X$ and $Y$ are tangent to $\xi$ (by definition), one has $[X,Y]=\frac{\partial}{\partial z}$ which is a vector field linearly-independent from $X$ and $Y$ and hence does not belong to $\xi$. Whence the result.
Let us now shed some lights on the informal discussion you reproduced.
It helps to notice that $\xi$ is given by the kernel of $\mathrm{d}z+y\mathrm{d}x$, it is then clear that $\xi$ is invariant by translation along the $x$-axis (and the $z$-axis, for that matter). Hence, if $0\in S$ is an integral submanifold of $\xi$, then $\xi_0$ (which is the $xy$-plane ) is tangent to $S$ not only at $0$ but all along the $x$-axis (invariance of $\xi$ along this axis). Therefore, $S$ intersects the $x$-axis on a line segment. The counterexample you mentioned fails to be really one since $S^2$ is no-longer tangent to the $xy$-plane when moving along the $x$-axis from the origin.

The key point is that by invariance of $\xi$ by translation in the direction of the $x$-axis, $S$ keeps being tangent to the $xy$-plane when moving along the $x$-axis from $0$.

From this observation, the conclusion should then be really easy. A smooth surface cannot contain a line segment so that a whole open set of the $xy$-plane is in fact included in $S$. Therefore, you can travel in $S$ in the direction of the $y$-axis without leaving the $xy$-plane and $\xi$ being tangent to $S$ must be contained in $\{z=0\}$, a direct contradiction with $\xi$ twisting along the $y$-axis.
Comment: What about the half cylinder ($z = x^2$) as a counterexample? It is a smooth surface that contains only a line segment of the $xy$-plane. I also don't understand this part of the proof in the question.


Proving the minimum of an expected value is greater than the expected value of a minimum

Question: I am looking to prove that $\min_{a \in \mathbb{R}} E[f(a, X)] \geq E[\min_{a \in \mathbb{R}}f(a, X)]$ where $f: \mathbb{R} \times \mathbb{R} \rightarrow \mathbb{R}$, $f$ is guaranteed to have a minimum, and $X$ is some random variable with an unknown distribution.
This looks similar to Jensen's Inequality for a concave function where $\min_{a \in \mathbb{R}(\cdot)}$ would be the function of interest. If this is the case, I am not sure how to prove that $min_{a \in \mathbb{R}}(\cdot)$ is concave. If there is a simpler way, then it is eluding me and any help is wanted.
Answer: In general, if $X \le Y$ and both have expectations you have $EX \le EY$.
Assuming the relevant expectations exist, for any $a'$ you have $E f(a',X) \ge E \min_a f(a,X)$ and
so $\inf_{a'} E f(a',X) \ge E \min_a f(a,X)$.
Comment: Could you start your second paragraph with "for any $a'$ and $x$ you have  $f(a',x) \ge  \min_a f(a,x)$ and thus $E f(a',X) \ge E \min_a f(a,X)$ ..." ?
Comment: I am not sure what you are asking. There are an infinite number of ways of expressing that sentence.
Comment: Why the downvote?


JS: use grunt + mocha + phantomjs

Question: I used the yeoman webapp-generator to create a fancy website template. It creates a test-folder and scaffolds the whole project incl. one simple unittest. To try the phantomjs functionality I added an additional function:
describe("DOM Test", function () {

    var el = document.createElement("div");
    el.id = "myDiv";
    el.innerHTML = "Hello World!";
    document.body.appendChild(el);
    var myEl = document.getElementById('myDiv');

    it("has the right text", function () {
        (myEl.innerHTML).should.equal("Hello World!");
    });
});

But when I run grunt test I always get this annoying error:
Running "mocha:test" (mocha) task
Testing: test/index.html

Warning: PhantomJS timed out, possibly due to a missing Mocha run() call. Use --force to continue.

Aborted due to warnings.

My mocha-entry within the Gruntfile looks like this (its a slightly modified version of the generated one. I replaced the url by a relative path with wildcard):
mocha: {
      test: {
        src: ['test/**/*.html'],
      }
    },

And the test/index.html looks like this:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Mocha Spec Runner</title>
    <link rel="stylesheet" href="bower_components/mocha/mocha.css">

And I tried the following things (without success):

run bower twice (suggested by this guy)
added grunt.config.set('server.port', 7002) (suggested by this github issue post)
Answer: Go to your test folder and run bower install:
cd test
bower install

Then try again to run grunt test.
You have two bower_components folders, one in root and one in test.

JS: use grunt + mocha + phantomjs


Launch the app on Gear S2

Question: I'm using Tizen Studio to launch the tamplate app BasicUI on my Gear S2.
My error:

When I tried to install from sdb:
The problem is related to the certificates. I did generate my certificate in Certificate Manager with one generate author certificate and the automatic certificate for distributor.
What is to be done?
Answer: Try the following method.
Connection Explorer - right click target(show context menu) - Permit to install applications
And Try install again.

Launch the app on Gear S2


Can you tell me why my webpage displays differently in IE and how to fix it

Question: I've been browsing through all of the CSS related cross-browser questions trying to troubleshoot my IE styling issues with no luck.  Can anyone tell me how to fix my homepage styles so that it displays the same in IE as it currently does in Firefox?  I've used Firebug (probably why it looks good in Firefox) but I can't find any tools for IE that will let me change the stylesheet real time.  I'm just as interested in the process of figuring out this answer as I am in the answer itself so posting the steps you took to figure it out would be beneficial. (want to be able to do this myself next time!!!)
Website is AppQandA.com.  Scroll down to the bottom in IE and notice the footer.  It's not like this on every page.....just the main page and the questions page.
Answer: The problem in IE is with the "border-left: 10px solid #333333;" rule. If I remove this, it works in IE (but obviously breaks in Firefox).
There is a tool a bit like Firebug for Internet Explorer:
http://www.stevefenton.co.uk/Content/Blog/Date/200902/Blog/Something-Like-Firebug-For-Internet-Explorer/
Potential Fixes:
1) Browser-specific styles (yuck) this would be a quick fix to get it working. Put another stylesheet AFTER your main stylesheet to override a style:
<code><!--[if IE]>
    <link rel="stylesheet" type="text/css" href="ie.css" />
<![endif]-->
</code>
And inside, override the rule...
<code>#footer { border-left: none; }
</code>
EDIT: Potential issue spotted
Your problem may be getting caused by incorrect tag nesting. You can avoid these kind of problems by validating your HTML using
http://validator.w3.org
Specifically, there looks to be a missing closing div tag in these amongst a couple of other errors. Fixing these may actually solve your problem without an IE specific hack.
Answer: There is a tool for ie called ie tester that allows you to check how does a site look in all versions of ie. This tool also has a debug bar, does not have as much features as firebug, actually is quite limited but allows you to explore the DOM and styles.
There is also a version of firebug (firebug lite) that u can use on ie, altough you need to create a reference in your webpage to use it, see Firebug Lite
I think the problem with your page if you look with firebug, in the #footer rule you have :
<code>#footer{
  margin:0 auto 15px
}
</code>
Try removing the 15 px and see how u go.