Como colocar uma fonte externa no meu aplicativo?

Question: Eu estou tentando colocar uma fonte personalizada no meu app, mas estou tendo muitos erros.
Já tentei usar o PixlUI, já tentei diversos códigos diferentes e sempre da erro, ou o aplicativo é executado, porém da crash (app Parou).
Este é o código que estou tentando colocar dentro do MainActivity.java:
TextView tx = (TextView)findViewById(R.id.textView1);
Typeface custom_font = Typeface.createFromAsset(this.getAssets(),
    "fonts/watermelon.ttf");
tx.setTypeface(custom_font);

Este é o código do MainActivity:
@SuppressWarnings("unused")
public class MainActivity extends ActionBarActivity{

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView tx = (TextView)findViewById(R.id.textView1);
    Typeface custom_font = Typeface.createFromAsset(this.getAssets(),
    "fonts/watermelon.ttf");
    tx.setTypeface(custom_font);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();}
                }

public void opensecondactivity(View view) {
    Intent intent = new Intent(this , SecondActivity.class);
    startActivity(intent);
    overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
       }

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent = new Intent(this , AboutActivity.class);
    startActivity(intent);
    overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
          }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
                View rootView = inflater.inflate(R.layout.fragment_main, container, false);
                return rootView;
            }
     }
}

Com esse código o Eclipse não declara nenhum erro, porém quando ele executa a Activity ele da erro e o aplicativo é fechado sozinho. O que fazer?
Só pra constar, a fonte está na pasta "assets/fonts"
Debug:
New_configuration [Android Application]
    DalvikVM [localhost:8612]
        Thread [<1> main] (Suspended (exception RuntimeException))
            <VM does not provide monitor information>
            ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2195
            ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2245
            ActivityThread.access$800(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 135
            ActivityThread$H.handleMessage(Message) line: 1196
            ActivityThread$H(Handler).dispatchMessage(Message) line: 102
            Looper.loop() line: 136
            ActivityThread.main(String[]) line: 5017
            Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
            Method.invoke(Object, Object...) line: 515
            ZygoteInit$MethodAndArgsCaller.run() line: 779
            ZygoteInit.main(String[]) line: 595
            NativeStart.main(String[]) line: not available [native method]
        Thread [<10> Binder_2] (Running)
        Thread [<9> Binder_1] (Running)
        Thread [<11> Timer-0] (Running)

Logcat:
06-14 09:58:59.484: W/ActivityThread(1243): Application com.akzonobel.malote is waiting for the debugger on port 8100...
06-14 09:58:59.494: I/System.out(1243): Sending WAIT chunk
06-14 09:58:59.584: I/dalvikvm(1243): Debugger is active
06-14 09:58:59.694: I/System.out(1243): Debugger has connected
06-14 09:58:59.744: I/System.out(1243): waiting for debugger to settle...
06-14 09:58:59.954: I/System.out(1243): waiting for debugger to settle...
06-14 09:59:00.154: I/System.out(1243): waiting for debugger to settle...
06-14 09:59:00.354: I/System.out(1243): waiting for debugger to settle...
06-14 09:59:00.564: I/System.out(1243): waiting for debugger to settle...
06-14 09:59:00.764: I/System.out(1243): waiting for debugger to settle...
06-14 09:59:00.994: I/System.out(1243): waiting for debugger to settle...
06-14 09:59:01.194: I/System.out(1243): waiting for debugger to settle...
06-14 09:59:01.394: I/System.out(1243): waiting for debugger to settle...
06-14 09:59:01.594: I/System.out(1243): debugger has settled (1348)
06-14 09:59:02.424: D/(1243): HostConnection::get() New Host Connection established 0xb8f54e48, tid 1243
06-14 09:59:02.514: W/EGL_emulation(1243): eglSurfaceAttrib not implemented
06-14 09:59:02.524: D/OpenGLRenderer(1243): Enabling debug mode 0
06-14 09:59:03.054: W/EGL_emulation(1243): eglSurfaceAttrib not implemented
06-14 09:59:06.384: D/AndroidRuntime(1243): Shutting down VM
06-14 09:59:06.384: W/dalvikvm(1243): threadid=1: thread exiting with uncaught exception (group=0xb1aa8ba8)
06-14 09:59:06.484: E/AndroidRuntime(1243): FATAL EXCEPTION: main
06-14 09:59:06.484: E/AndroidRuntime(1243): Process: com.akzonobel.malote, PID: 1243
06-14 09:59:06.484: E/AndroidRuntime(1243): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.akzonobel.malote/com.akzonobel.malote.MainActivity}: java.lang.RuntimeException: native typeface cannot be made
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.os.Handler.dispatchMessage(Handler.java:102)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.os.Looper.loop(Looper.java:136)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.app.ActivityThread.main(ActivityThread.java:5017)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at java.lang.reflect.Method.invokeNative(Native Method)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at java.lang.reflect.Method.invoke(Method.java:515)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at dalvik.system.NativeStart.main(Native Method)
06-14 09:59:06.484: E/AndroidRuntime(1243): Caused by: java.lang.RuntimeException: native typeface cannot be made
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.graphics.Typeface.<init>(Typeface.java:175)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.graphics.Typeface.createFromAsset(Typeface.java:149)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at com.akzonobel.malote.MainActivity.onCreate(MainActivity.java:32)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.app.Activity.performCreate(Activity.java:5231)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-14 09:59:06.484: E/AndroidRuntime(1243):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
06-14 09:59:06.484: E/AndroidRuntime(1243):     ... 11 more
06-14 10:00:38.184: I/Process(1243): Sending signal. PID: 1243 SIG: 9

EDIT - SOLUÇÃO:
Obrigado a todos que me ajudaram! A solução era implementar o código dentro do public View onCreateView. Veja como ficou:
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        TextView txt = (TextView) rootView.findViewById(R.id.TextView1);
        Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/laouib.TTF");
        txt.setTypeface(font);

        return rootView;

Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/54747/discussion-on-question-by-renan-como-colocar-uma-fonte-externa-no-meu-aplicativo)
Answer: Para ler fontes externas, eu coloquei as fontes na raiz da pasta asset e criei um classe "FontChanger" que só tem métodos para mudar as fontes. Todos os métodos são estáticos para que não precise instanciar a classe. A única coisa que passo ao método e o Context.
Implementacao do metodo dentro da classe FontChanger :
public static Typeface setRobotoRegular(Context context)
{
     return Typeface.createFromAsset(context.getAssets(),"roboto_regular.ttf");
}

mudando a fonte de um textView que tenha em minha aplicacao:
meuTextView.setTypeFace(FontChanger.setRobotoRegular(context));

Comment: Testei este código, mas ele fala isso: `context cannot be resolved to a variable`
Comment: Renan ai eu dei o exemplo de uma variável do tipo Contexto que tenho e tem o nome context. se voce esta em um Fragment faca
Context context=getActivity();
Comment: Finalmente consegui! Você me deu a luz! Bastava implementar o código dentro do `public View onCreateView`. =D Obrigado.
Answer: Clique com o botão direito na pasta "res" > New>Android Resource Diretory.
Ponha um nome de sua preferência no diretório e em "Resource type" selecione o tipo "font" e aperte em ok.
Depois disso é só copiar suas fontes para dentro da pasta criada.
Obs.: Antes de copiar as fontes, renomeie e tire todos os caracteres especiais e traços, pois o Android Studio não aceita arquivos com nomes assim.
Exemplo: DS-DIGITAL.TFF >>>>>> dsdigital.tff!
Fonte: https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml


Sigmas Problem ΣΣ i^2

Question: How can i solve this?
$ΣΣ i^2=?$
both are from 1 to 4
And i is the variable
My Answer is 58.am i correct?
Comment: what are the variables of each sum?
Comment: i is the variable
Comment: i is the variable for both?
Comment: also, I believe you can do this short double sum by hand, am I wrong?
Comment: Yes.i is the variable for both.i just need to check the answer
Comment: That doesn't make any sense. What's the context of this expression? There has to be some mistake that leads up to it.
Comment: How did you get the answer 58? I also agree with Erik's answer.
Comment: @MobinaK $i$ cannot be the variable for both of the sums.
Answer: Is this the correct expression?
$$\sum_{i=1}^{4}\sum_{i=1}^{4}i^2$$
If so this is equal to
$$\sum_{i=1}^{4}(1^2+2^2+3^2+4^2) = \sum_{i=1}^{4}30 = 120$$
Comment: You should start one of the sums with $j$ or another letter.
Comment: Ok. I definitely think that the he/she misread the question.
Comment: I agree, I was just trying to stick with the notation Mobina K was using.
Comment: Sticking to **bad** notations is a **bad** idea. Do not use the same variable twice.

Sigmas Problem ΣΣ i^2


Why don't I get a HTTP status code from Firebase Server? Swift - Vapor server

Question: I am writing to Firebase Database from a Vapor server using the Firebase REST API. Why don't I get a Status code in the header received? This would enable me to check if the write was successful or not.

headerReceived items line 83 in
  extensionPutRequestToUsersClaimBookingCleaner are
([Connection: "keep-alive",  Cache-Control: "no-cache",  Server:
  "nginx",  Date: "Sun,  27 Aug 2017 21:47:25 GMT",  Content-Type:
  "application/json;  charset=utf-8",  Content-Length: "1027",
  Strict-Transport-Security:  "max-age=31556926;  includeSubDomains;
  preload",  Access-Control-Allow-Origin: "*"])
Comment: What do you mean? You dont get a status code when inspecting in the network tab of dev tools?
Comment: @Rienk , If I make the request using Postman, it shows status 201. However, when I make the request using the Vapor client, in the header received from Firebase server, I don't get a Status code key: value. There is no key:value with Status: XXXXX received from Firebase in the header of the response. Please see the a copy of the header received from Firebase upon a successful PUT
Comment: Are you using Vapor's `client` to contact your Firebase server?
Comment: @tobygriffin   yes, I do
Answer: The response's status code is returned in the status property rather than the headers property.
guard response.status == .created else {
  // not a 201 response
}

Comment: Could you please advise if the way in which I create my JSON object is correct? I keep getting an error when I send the object to Firebase. https://stackoverflow.com/questions/46100421 . Thank you


Clustering: finding groups of close items within a large collection

Question: I have an array of items (~5000 items, each item is an English word) and a distance function between pairs of items. I want to find groups of items within the array where all the items within a group satisfy a distance criterion (e.g. every pair of items have a distance smaller than 2). The groups should generally be as large as possible, but there's no formal definition or hard requirement for this.
My implementation language is PHP, but I'm looking for general advice regarding algorithms that can handle this efficiently.
Update: I think I can solve this by building a graph where the vertices are the items, and there's an edge between items that satisfy the distance constraint. Once I build the graph I can run an algorithm like Bron–Kerbosch to list all the maximal cliques. I'll update if this works out but feel free to add your thoughts in the meantime.
Comment: Let's call the distance function "Levenshtein"? PHP is about as bad a choice as you can find. It's not good for anything but web apps, seriously.
If you want a more detailed answer, define "group" more precisely. Does DBSCAN work for you?
Answer: How is this function defined? Is it pre-computed? If so you can iterate over the computed function representation and retrieve pairs of words based on your criterion. If not, you have no other option but to compute the function between all pairs of words (This is necessary in your graph approach). Instead of the Bron-Kerbosch algorithm, I would go for a randomization+approximation strategy like,
http://dimacs.rutgers.edu/Workshops/Challenge10/abstracts.html#ovelgonne
http://dl.acm.org/citation.cfm?id=1933306.1934471
It is based on an modularity maximization approach. Modularity is the ratio between number of outgoing edges in a cluster to the number of edges within the cluster. In your case, you will be looking for the clusters with ratio 0, and choose the biggest one of them. This algorithm is really fast and works for most datasets that I have worked with. Though a modularity based method might be overkill for this problem, IMHO I feel this is a nice way to think about the problem + the implementation of this algorithm is available online (C implementation by the authors of the paper).
Answer: What I understand the problem is:
"A-G" stand for the words. "#" stands for the distance between the two words. And you need to find out the pair which the distance <= 2.
<code>  A B C D E F G
A * # # # # # #
B   * # # # # #
C     * # # # #
D       * # # #
E         * # #
F           * #
G             *
</code>
Basically it needs 2-level loop, what we can do is to reduce comparison times, only compare "#" part in matrix above. Here is the code in PHP:
<code>$result = array();
while ( ($word = array_shift($arrWordList)) !== NULL ) {
    foreach ($arrWordList as $otherWord ) {
        if ( calc_dist($word, $otherWord) <= 2 ) {
            $result[] = array($word, $otherWord);
        }
    }
}
</code>
And you can use $result to continue doing something.
Comment: Thanks Troy, but you're solution only gives word pairs, and does not split the array into groups where all pairs of items within a group satisfy a criterion as requested in the question.
Comment: you can just change "echo" statement to the result you want, using another array to record the pairs of word. Am I understood right?
Answer: Given that you want your criteria to apply to all members of a group, you need a clustering algorithm that allows for overlapping groups. That's a pretty complex subject, so the best I can do is direct you to the literature on clustering algorithms, and in particular C-Means Clustering which is designed for overlapping groups.
Comment: If I understand correctly you're only making sure the criterion is valid in relation to the first element in the group, but the requirement is for the criterion to hold between all pairs of elements within the group.
Comment: @hillel - That's basically correct. If `d` is close to `a`, and `f` is close to `d`, then `f` would fall under the group of `a`. Your requirement would entail the possibility of one word being the member of more than one group, which complicates the matter. I'll have to give it some more thought.
Comment: @hillel - I updated my answer with a link that might help. I'm afraid that's the best I can do.


Superharmonic functions, Barriers - Complex Analysis (Conway)

Question: Let $G$ be an open connected subset of the plane $\mathbb{C}$, and let $a \in \partial_{\infty}G$. Suppose $\psi_{r}(z)$ is a function from $G \cap B(a,r)$ to $\mathbb{R}$ with the following properties:

$\psi_{r}$ is superharmonic on $G \cap B(a,r)$ with $\psi_{r} \geq 0$;
$\lim_{z \rightarrow a} \psi_{r}(z) = 0$;
$\lim_{z \rightarrow w} \psi_{r}(z) = 1$ for $w \in G \cap \{w : |w-a| = r\}$.

Define $\hat{\psi_{r}}$ by letting $\hat{\psi_{r}}=\psi_{r}$ on $G \cap B(a,r)$ and $\hat{\psi_{r}}=1$ for $z$ on $G-B(a,r)$.
Show that $\hat{\psi_{r}}$ is superharmonic. (Conway Chapter X Section 4. The Dirichlet Problem.)
Thanks. I just have a presentation to do on Harmonic Functions in two days, and I'd prefer to have all the details under my belt. Just reading Conway and this is the section about barriers. The book says (Verify!), but I've been trying for a while, and even though I managed to prove something similar earlier, I can't seem to do this one.
Comment: I don't see a question here.
Comment: @wordsthatendinGRY sorry, question should be show that psi^_r is superharmonic.
Answer: I'm Dongryul, preparing my presentation on Dirichlet Problem for Complex Function Theory Course, based on the Conway's book, too.
I concerned the same question as you did, and I think that I can answer as follows.
To show that $\hat{\psi}$ is superharmonic, it suffices to prove that $\hat{\psi} - u$ satisfies the minimum principle for any harmonic function $u$ on $G_1 \subseteq G$.
Denote $G^1 = \{z \in G : |z - a| > r\}$ and $G^2 = \{ z \in G : |z-a| < r\}$, and suppose to the contrary that $\hat{\psi} - u$ is non-constant and attains minimum at $z_0 \in G_1$.
If $z_0 \in G^1$, then $$1 - u(z_0) \le \hat{\psi}(z) - u(z) \le 1 - u(z)$$ so $u$ is constant.
If $z_0 \in G^2$, then $\hat{\psi} - u$ is constant on a connected component of $G_1 \cap G^2$ containing $z_0$ since it is superharmonic there. Since $\hat{\psi} - u$ is non-constant, $G^1 \cap G_1 \neq \emptyset$ or there is another connected component, but connectedness of $G_1$ implies $G^1 \cap G_1 \neq \emptyset$ even in this case. Then by continuity we may assume that $|z_0 - a| = r$. Now $$1 - u(z_0) \le \hat{\psi}(z) - u(z) \le 1 - u(z)$$ so $u$ is constant.
Finally if $|z_0 - a| = r$, $$\hat{\psi}(z) - u(z) \ge \hat{\psi}(z_0) - u(z_0) = 1 - u(z_0)$$ and thus $$u(z_0) \ge 1 - \hat{\psi}(z) + u(z) \ge u(z).$$ Since $u$ is harmonic, it means that $u$ is constant.
In either case, $u$ is constant, and the minimum of $\hat{\psi} - u$ is $1 - u(z_0)$. However, $\hat{\psi} - u$ is assumed to be non-constant so $\hat{\psi}(w) < 1$ for some $w \in G_1$ and it contradicts to the minimality.
Therefore, we conclude that $\hat{\psi}$ is superharmonic.
I think that I'm late, but I hope that your presentation was successful.


Is longitudinal data a necessity of mediation paths in structural equation modeling?

Question: Motivating Background Info
I was recently in a grad class and someone was presenting on a structural equation model (SEM) that had a mediation path. If I recall correctly, this was the specific pathway they were speaking about from this paper:

Someone in the class stated that there is no ability to run a path analysis with this data because the data isn't longitudinal. I have never heard this distinction before and because I wasn't aware of this, I didn't question the statement until I got home and wondered if this was indeed correct.
Question
My understanding is that path analysis and SEM are basically just extensions of regression (the paths are literally just regression paths at the end of the day), and this doesn't necessitate longitudinal data, but obviously having this kind of data is ideal. For example, Sewall Wright's original path analysis was done on Guinea pig heredity features, and as far as I recall, he did not use longitudinal data to explain his methods. His original path analysis is shown below:

Using this logic, let's say somebody wanted to investigate whether waking up early (measured in time) predicts coffee consumption (measured in cups), thereafter coffee consumption predicts productivity (measured in minutes). This is simply one regression path followed by another, and I don't think it requires longitudinal data (again, it would be ideal, but I don't know if that's totally necessary). Basically my question is what I've summarized already: does path analysis / SEM with mediation require longitudinal data?
Comment: If your arrows have a causal interpretation then that implies temporal ordering: causes occur before effects so cross-sectional  data won't provide support for an SEM under the circumstance, unless you are making *lots* of assumptions which only longitudinal data can support.
Comment: Using the logic of my time -> coffee -> productivity example, isnt this process in some part temporal? Time waking up always precedes coffee consumption, and coffee consumption usually precedes work (though thats obviously not necessary). A better final variable may be time went to bed since it would always be after the other two variables. In the Sewall Wright case, he only used generational data. So I guess my main idea is that temporal effects should not require hard coding (Time 1 and Time 2 for example), but can instead be left as is if it is assumed the relationship precedes the outcome.
Answer: As you said, mediation is at it's core a regression, so you can run a mediation model with any kind of data. However, typically when we talk about "mediation" we really mean causal inference. Causal inference requires that a host of assumptions be met, and having longitudinal data can be useful for this, though it isn't necessary. This is a nice primer on the limitations of naively applied path models (including mediation) and it discusses how one might do better.
Comment: Thank you for this. I believe the cited paper does a good job of giving me additional insights beyond the longitudinal aspect. Thanks for sharing.


IP testing tool similar to wireshark website

Question: I am looking to implement a tool similar to the one linked below on my personal server/website what are the steps I would need to get started?
http://www.wireshark.org/tools/v46status.html

I understand that I will need two seperate domains for example: (ipv4.mywebsite.com and ipv6.mywebsite.com) from which I will serve the images.  What would be the next step?
Comment: One would need to write a book to explain all of the things you'll need to know to implement this. As asked, this question is **far** too broad. Start working on things, and then come back with specific, well-scoped, well-researched questions and we'll be glad to help.
Comment: You can use existing services that do this like http://www.ipv6test.nl/demosource.php
Answer: Check it using PHP on your server:
function is_ipv6() {
    $ipv4_mapped_ipv6 = strpos($_SERVER['REMOTE_ADDR'], "::ffff:");
    return (strpos($_SERVER['REMOTE_ADDR'], ":") !== FALSE) &&
           ($ipv4_mapped_ipv6 === FALSE || $ipv4_mapped_ipv6 != 0);
}

It's a modified version of: https://stackoverflow.com/a/13677565


how to migrate a multi-value term reference field?

Question: I am setting up a drupal migration where the destination node contains a multi-value taxonomy term_reference field, called 'field_features'. The machine name of the drupal taxonomy vocabulary of the field is called 'voc_features'.
My field mapping for this field is configured like this:
$this->addFieldMapping('field_features:create_term')->defaultValue(true);
$this->addFieldMapping('field_features:ignore_case')->defaultValue(true);

//i don't have tid's in the source, so i leave the source_type for what it is
$this->addUnmigratedDestinations(array('field_features:source_type'));

//i link the drupal vocabulary to the multivalue field.
$this->addFieldMapping('voc_features', 'field_features')->separator('|');

The terms are added in the 'voc_features' vocabulary, but not in the 'field_features' field.
When i add the field mapping like i do with all the other fields:
//my source fields have the same name as my destination fields
$this->addFieldMapping('field_features', 'field_features')->separator('|');

i get the following error:
strtolower() expects parameter 1 to be string, array given File ...\sites\all\modules\migrate\plugins\destinations\fields.inc, line 402
Other single value term_reference fields import just fine.
What am i missing?
Answer: Yes. The migration of term doesn't allow to migrate multi-value. You have to process the source ahead.

Create a new migration and import the data to terms of vocabulary named 'voc_features' at first.
Add a dependence to your current migration using previous migration. Such as $this->dependencies = array('MigrateXXXMigration');.
The field mapping should be like this,$this->addFieldMapping('field_features', 'Features')->arguments(array('source_type' => 'tid'));
In the function prepareRow($row), you should prepare the Features field and put it into your $row variable. $row->Features=array(tid1,tid2,tid3);. The 'tid1','tid2' and 'tid3' should be replace the live tid from your term tables.
Comment: Have you managed to do this with the :ignore_case argument set to true?
Comment: Is there an issue open about this? Having to do this amount of parsing makes migrate framework a lot less useful.
Answer: Looking at the code for migrate module it seems to be a bug in the module.This issue happens when ignorecase is set to true while migrating multivalue fields. You may want to open a new issue in ALB migrate module.
Answer: I'm working on a migration also at the moment.  I agree with Tony that you could write something using prepareRow() that would achieve what you want .   Could you post your full extension class of RcnMigrateMigration, I'll see if I can make any sense of it.
Comment: I managed to get the migrate up and running with a separate migration for the terms first. However i did not use tid as source_type. This wasn't needed. I also didn't use the prepareRow() for this. I just used the 'separator' argument in addFieldMapping().


Erro ao converter BigInt para inteiro utilizando lambda

Question: No banco de dados o tipo está BigInt e no C# estou tentando converter para int e ele consegue converter, mas quando chega na instrução lambda, dá erro.
 long codpro = Int64.Parse(tb_CodigoProduto.Text.Substring(0,14));
 db = (from p in data.Produtos where p.ProCodInt == codpro select p).FirstOrDefault();

Comment: Eu desisto, espero que alguém consiga retirar de você a informação necessária ou consiga te dar uma solução mesmo que você não passe a informação necessária.
Comment: Você está convertendo para `long` não `int` e isto está correto. Sem sabemos o erro que dá fica um pouco complicado ajudar. Quando você faz uma pergunta com um código que dá um erro, você deve postar esse erro, onde exatamente dá, em que circunstâncias, todas as partes relevantes do código e se possível um código que possa reproduzi-lo: http://pt.stackoverflow.com/help/mcve
Comment: "the 'ProCodInt' property on 'Produtos' could not be set to a 'Int64' value.You must this property to a non-null value of 'Int32'"
Comment: Qual é o tipo de `ProCodInt`? Seria um `int`? Ou um `int?`?
Comment: [ProCodInt] [bigint] NOT NULL
Comment: Precisa do tipo de `p.ProCodInt`, talvez seja bom colocar toda a estrutura do tipo de `p`.
Answer: Int64 procod = Int64.Parse(string);

Comment: O que você quer dizer, @BrunoRodrigues? Declarar a variável como `Int64` resolveu o seu problema?
Comment: Eu postei a resposta sobre o que resolveu o meu problema e obrigado pela ajuda a todos! e quem resolveu foi eu mesmo!
Comment: Você pode ter resolvido o problema mas não desta forma. Esta sintaxe sequer existe. O problema provavelmente era outro e foi resolvido de outra forma mesmo. Pelo código apresentado era impossível resolver.


Margin collapsing between tables

Question: I have several tables on a page, and would like to have some space between tables. It is possible that some tables only have empty cells; such tables have a zero-height, in which case I don't want any additional spacing added.
Normally, margin collapsing would do the trick. However, I'm gathering that tables establish a block formatting context (BCF), and that margin collapsing doesn't happen between boxes that establish a BCF.
You can see this running the snippet below: you get a 1em space between "1" and "2", but a 2em space between "2" and "3", while I'd always want to have a 1em space. But how to achieve that?
PS: Some constraints I have to work with: I can't remove the markup for the empty tables or add a class on them. However, I could add a container for each table, such as a
. (I was hoping that doing so and moving the margin-bottom on that container would do the trick, but it doesn't, maybe because if a block establishes a BFC, then its parents do as well.) Finally, I could certainly write JavaScript that adds a class with the margin on non-empty tables, but don't consider this to be an acceptable solution.

table { margin-bottom: 1em }

1

2

3

Comment: one solution that is not supported is to use the `:has()` selector with `:empty` like this `table:has(td:empty) {display:none}` ... but this will probably work in 1 or 2 years
Comment: @TemaniAfif Right. But I'm not sure customers are willing to wait that long. ;)
Answer: Interesting question. Not an easy one. How about something like this: https://codepen.io/MSCAU/pen/jQLWxL? The spacer is grey to show what's going on:
table {
  border-spacing: 0;
}

td {
  border: 1px solid grey;
}

td:empty {
  display: none;
}

td:not(:empty) {
  &:after {
    content: '';
    display: block;
    height: 30px;
    width: 10px;
    background-color: rgba(99,66,33,0.3);
  }
}

You've only got one cell in each table in your example so this works.
Comment: Interesting, but, as you can imagine, the tables I'm dealing with typically have more than one row, with each row again typically having more than one cell.
Comment: Hehe. Yes, it also feels quite hacky but can work with multiple cells and rows by adding `tr:last-child` selector. I have modified the CodePen accordingly.
Comment: I don't mind hacky, if it works :). However, a `tr:last-child td:not(:empty)` would find any empty cell on the last row, so this will add a space if any `td` on the last `tr` is empty, while I want to add a space only if *all* `td` in *all* `tr` are empty. Plus `:empty` here isn't what I want to test on, as the `td` in general contain something, but that "something" might be hidden. So I really want to do what the margin collapsing does, but on blocks that contain a ``.

Margin collapsing between tables


Show 3 different Views displays for same exposed filter block or link Views displays?

Question: So, I have a View which uses exposed filters which has the exposed form style set to block.
In my first view display, I have one page display which shows the content as teaser view for all results. The teaser of the content type is styled with a custom template (node--my-custom-type.tpl.php).
I then made 3 tabs using the "Quicktabs" module and put my view page as one of the tabs, and 2 generic PHP blocks as placeholders for the other 2 tabs.
I setup a Page in "Panels" (Page Admin) so that I can have the block above and the quicktabs content below. I might change the layout later on but for now it works fine.
My 3 tabs are therefore:

List

This the View Page (Teaser view of the content type)

Map

Currently a block placeholder but should be linked to the same View Page results

Other

Currently a block placeholder but should be linked to the same View Page results

Now, I want to know how can I set the Map and Other tabs to be different View displays for my View that are linked to the same exposed form in my first views display?
Furthermore, the Map and Other tabs would need to just get the custom field: field_id and append the values of all the results to an iFRAME - so I really just need to output PHP and nothing else, no fields or anything.
I suppose I could do this via another custom themed display for the content type... e.g. adding another teaser display type named custom-teaser?
However, how would I "link" all the results between the displays using the same exposed filter block?
UPDATE 17/2/13:
So I tried the "Attachment" display, however that just added the field_id to my "List" tab and I don't want the field to appear on that tab.
UPDATE 4/6/13:
I haven't looked into fixing this issue for a while, but getting back to it now.
So I want the end result to be:

A page with exposed filter and 3 tabs that show each different "view display"

Tab 1: Show results as Gallery (custom CSS styling)
Tab 2: Show results on a Map (results have IDs, would need to get the IDs and pass them to the Map as an array or string as a comma separated list)
Tab 3: Show results on another map using different fields

The results should all correspond to the same exposed filter and should be updated when you update the filter. I currently use Quick-Tabs but I can change to something else to make the tab effect.
Answer: You can use only one exposed form of one of the displays. The other exposed forms should be set "as block", so they are not shown (as you will not set them active in the block configuration). As exposed forms work via GET-params, you simply can use the same "Filter identifier" for filters that shall share the same value.
An exposed filter in display2 with identifier type will use the same value as the exposed filter in display1 with the same identifier type.

This way you can control all three displays by only using one exposed form.
Answer: I think the best options for you is to load the first view in a normal way with the exposed filter, and load your other views programmatically with the correct arguments that you can get from the url.
Get parameter from URL:
$count = $_GET['count']
Print view with args :
print views_embed_view('search', 'page_1', array(23,44,100));
Comment: I'm not too sure what you mean, however I know that my main "gallery" view is set to one specific display, so I could make other displays (like teaser, or some custom ones) then in the views tpl file, I can check if($display == $teaser) than set output =+ the_id . ","; - Then this way might work, I would just restyle the other two views to have the results add to the URL of the iFrame for each other display
Comment: I'm using AJAX, I think I'll need to remove the quick-tabs and do the tabbing myself with CSS?


Need help to use array.some() to check if existing cities in arrays are included in array of phrases

Question: I have a list of cities and I have a list of phrases. I need to check if the cities exist in the phrases and based on this return "big city" or "not a big city"
I thought it would be simple with the some() function but I seem to be not clear about how it really works. I've tried with with a single string for a city and an array of cities.. but both don't seem to work..
I have check this question (Checking if elements of an array are included in elements of another array) and maybe the answer is there but there seems to be a use of filter there.. do I have to do that or can I not just use some and get the result?
I'd appreciate some help with some explanation why the below code does not work.. I've lost one day trying to figure it out but I can't seem to.. In my head the result should be 'big city' twice in the code below .. once for 'new york' and once for 'milan'
// COMMON FOR BOTH

const phrases = ['I live in San Francisco','I live in milan in italy', 'I live in Los Angeles', 'I live in New York City']

// WITH AN ARRAY

const cities=['paris',"new york",'milan'];

function checkCities(phrase){

  cities.forEach(city=> phrase.includes(city));

};

const result1 = phrases.some(checkCities) ? "big city" : "not a big city";

console.log('result1',result1); // Output "not a big city"

// WITH JUST A STRING

const city = 'new york';

const result2 = phrases.some(checkCity) ? "big city" : "not a big city";

console.log('result2',result2); // Output "not a big city

function checkCity(phrase){

  phrase.includes(city);

};

Comment: When you say _"I need to check if the cities exist in the phrases"_ do you want to check that all of the strings in `cities` exist in at least one of the strings in `phrases` or do you want to check that at least one city string from the `cities` array is in a string from the `phrases` array?
Comment: Sorry if was not clear.. i'll try and update the question.. but I want to check if, in any of the phrases, if any of the cities exist then return a "a big city".. at least that's what I was trying to achieve with my code.. as I assumed that `some()` returns true if any of the condition returns true.. am I right?.. I am still trying to figure it out in my head how `some()` works..
Answer: Your issue is with your misunderstanding of how the function you pass to .some() should work. The function you pass to .some() will be called by JS multiple times, once for each element in the array that you called the .some() method on - in your case, that is each string in the phrases array. The function should also return a true or false value (or a truthy/falsy value). When you return true from your function, the .some() method stops any further iterations and returns true (indicating you've met the condition you're trying to check), if you return false, the .some() method will continue its loop and check the next element in your array. If the function passed to .some() doesn't return true for any value in your array, then the .some() method returns false after checking all items in your array. You can read abut the details of the .some() method on MDN.
In your code, the function you're passing to .some(), checkCities, does not return anything from it, so it automatically returns a value of undefined every time JS calls it, which to the .some() method is the same as returning false for each element.
As you outlined, you want to "check if, in any (.some()) of the phrases, if any (.some()) of the cities exist then return a "a big city"". We can try and turn this sentence into code (see code comments below):

const phrases = ['I live in San Francisco','I live in milan in italy', 'I live in Los Angeles', 'I live in New York City'];
const cities = ['paris',"new york",'milan'];

// If "any"--------------v   of the phrases...
const result1 = phrases.some(checkCities) ? "big city" : "not a big city";

function checkCities(phrase){
  // If "any"---v of the cities "exist"------------v
  return cities.some(city => phrase.toLowerCase().includes(city.toLowerCase()));
  //                      ^--- arrow function without body `{}`, so the return value is implicit
};

console.log('result1', result1); // Output "not a big city"

Here we're using two .some() methods, one on the outer phrases to iterate through each phrase, and the an inner .some() to check if any of the city strings are in the current phrase. If the inner .some() method returns true (indicating that a city has been found in a phrase), then your outer .some() method will also return true, otherwise, if the inner .some() method is unable to find a city in any phrase, then it will return false for each phrase that is iterated on by the outer loop, which will result in your outer .some() method returning false.
Answer: ...
// WITH JUST A STRING
...
function checkCity(phrase){
  if (phrase.toLowerCase().includes(city.toLowerCase())) return phrase
};

WITH AN ARRAY: you can loop for each city with "JUST STRING" code
Answer: One suggestion : As includes is a case sensitive. Hence, 'new york'.includes('New York') will return false. You can either convert both the strings in lowerCase() to check if it exist or not.
Working Demo :

const phrases = ['I live in San Francisco','I live in milan in italy', 'I live in Los Angeles', 'I live in New York City'];

const city = 'new york';

function checkCities(city) {
  return phrases.some((phrase) => phrase.toLowerCase().indexOf(city.toLowerCase()) > -1);
}

console.log(checkCities(city) ? "big city" : "not a big city");

Note : Above code will work perfectly if you want to search for a single city at a time.


Limit of a complex valued function in polar coords

Question: Let $f(z) = \dfrac{z}{z+\mid z\mid}$. We have to find the limit as $z \to 0$.
In polar coordinates, we have $f = \dfrac{re^{i\theta}}{re^{i\theta} +r}=\dfrac{e^{i\theta}}{e^{i\theta}+1}$
As this form is not dependent on $r$, what can we conclude about the limit as $r \to 0$?
Comment: You can conclude that the limit does not exist. Because you get different values for different $\theta$s
Answer: Putting $\;z=x+iy\;,\;\;x,\,y\in\Bbb R\;$, we have:
$$x=y:\;\implies\lim_{x\to 0}\frac{x(1+i)}{x(1+i)+\sqrt2\,|x|}=\begin{cases}\frac{1+i}{1+i+\sqrt2}\,,&x>0\\{}\\\frac{1+i}{1+i-\sqrt2}\,&x<0\end{cases}$$
and thus the limit doesn't exist.


Forecasting with ARMA-GARCH

Question: I want to forecast a differenced time series of an Index using the combined ARMA-GARCH model (because I want to forecast the mean and not the variance). My model is a ARMA(2,2)-GARCH(1,1) model. So the equations for the first forecast are:
Y(t+1)=Y(t)+Alpha(1)*(Y(t)-Y(t-1))+Alpha(2)*(Y(t-1)-Y(t-2)) - Beta(1)*e(t) - Beta(2)*e(t-1) + e(t+1)

with
e(t+1) = Sigma(t+1)*Z(t+1)  ,   Z(t+1)=N(0,1)

and
Sigma^2 (t+1) = Omega + a(1)*u^2(t) + b(1)*Sigma^2(t)

I tried it with the "rugarch" package and the ugarchforecast method:
GARCHspec <- ugarchspec( variance.model = list(model = "sGARCH", garchOrder = c(1, 1)),mean.model = list(armaOrder = c(2, 2), include.mean = TRUE))

GARCHfit <- ugarchfit(GARCHspec, diffclosingkursu)

ugarchforecast(GARCHfit,n.ahead=250)

The forecast seems to be quite strange
*------------------------------------*
*       GARCH Model Forecast         *
*------------------------------------*
Model: sGARCH
Horizon: 30
Roll Steps: 0
Out of Sample: 0

0-roll forecast [T0=1976-11-23 01:00:00]:
     Series  Sigma
T+1   10.28 0.7802
T+2   10.30 0.8580
T+3   10.32 0.9264
T+4   10.34 0.9876
T+5   10.36 1.0429
T+6   10.38 1.0933
T+7   10.40 1.1395
T+8   10.43 1.1822
T+9   10.45 1.2217
T+10  10.47 1.2585
T+11  10.49 1.2927
T+12  10.51 1.3247
T+13  10.54 1.3547
T+14  10.56 1.3829
T+15  10.58 1.4093
T+16  10.60 1.4343
T+17  10.63 1.4578
T+18  10.65 1.4800
T+19  10.67 1.5010
T+20  10.69 1.5208
T+21  10.71 1.5396
T+22  10.74 1.5574
T+23  10.76 1.5743
T+24  10.78 1.5903
T+25  10.80 1.6056
T+26  10.82 1.6200
T+27  10.85 1.6338
T+28  10.87 1.6469
T+29  10.89 1.6593
T+30  10.91 1.6743

Also, how can it be, that every forecast for the same time series is the same but e(t+1) should be a random variable?
EDIT:
ugarchspec( variance.model = list(model = "sGARCH", garchOrder = c(1, 1)),mean.model = list(armaOrder = c(2, 2), include.mean = TRUE))

*---------------------------------*
*       GARCH Model Spec          *
*---------------------------------*

Conditional Variance Dynamics
------------------------------------
GARCH Model             : sGARCH(1,1)
Variance Targeting      : FALSE

Conditional Mean Dynamics
------------------------------------
Mean Model              : ARFIMA(2,0,2)
Include Mean            : TRUE
GARCH-in-Mean           : FALSE

Conditional Distribution
------------------------------------
Distribution    :  norm
Includes Skew   :  FALSE
Includes Shape  :  FALSE
Includes Lambda :  FALSE

ugarchfit(GARCHspec, closingkursu)

*---------------------------------*
*          GARCH Model Fit        *
*---------------------------------*

Conditional Variance Dynamics
-----------------------------------
GARCH Model     : sGARCH(1,1)
Mean Model      : ARFIMA(2,0,2)
Distribution    : norm

Optimal Parameters
------------------------------------
        Estimate  Std. Error     t value Pr(>|t|)
mu     24.000332    0.774681    30.98091  0.00000
ar1     1.795379    0.000456  3935.65863  0.00000
ar2    -0.795715    0.000360 -2209.69523  0.00000
ma1    -0.891371    0.026093   -34.16102  0.00000
ma2     0.008179    0.024713     0.33094  0.74069
omega   0.152244    0.020684     7.36031  0.00000
alpha1  0.229838    0.023339     9.84798  0.00000
beta1   0.729204    0.023038    31.65283  0.00000

Robust Standard Errors:
        Estimate  Std. Error     t value Pr(>|t|)
mu     24.000332    0.644910    37.21499 0.000000
ar1     1.795379    0.000731  2456.77236 0.000000
ar2    -0.795715    0.000471 -1687.85596 0.000000
ma1    -0.891371    0.035477   -25.12542 0.000000
ma2     0.008179    0.030585     0.26741 0.789156
omega   0.152244    0.040365     3.77172 0.000162
alpha1  0.229838    0.043371     5.29932 0.000000
beta1   0.729204    0.041929    17.39135 0.000000

LogLikelihood : -4427.411

Information Criteria
------------------------------------

Akaike       3.5230
Bayes        3.5415
Shibata      3.5229
Hannan-Quinn 3.5297

Weighted Ljung-Box Test on Standardized Residuals
------------------------------------
                         statistic p-value
Lag[1]                      0.1058  0.7449
Lag[2*(p+q)+(p+q)-1][11]    1.6123  1.0000
Lag[4*(p+q)+(p+q)-1][19]    5.5053  0.9859
d.o.f=4
H0 : No serial correlation

Weighted Ljung-Box Test on Standardized Squared Residuals
------------------------------------
                        statistic p-value
Lag[1]                    0.01876  0.8911
Lag[2*(p+q)+(p+q)-1][5]   4.39776  0.2084
Lag[4*(p+q)+(p+q)-1][9]   6.38265  0.2566
d.o.f=2

Weighted ARCH LM Tests
------------------------------------
            Statistic Shape Scale P-Value
ARCH Lag[3]     1.227 0.500 2.000  0.2681
ARCH Lag[5]     2.548 1.440 1.667  0.3623
ARCH Lag[7]     3.489 2.315 1.543  0.4262

Nyblom stability test
------------------------------------
Joint Statistic:  2.1259
Individual Statistics:
mu     0.01831
ar1    0.34437
ar2    0.33567
ma1    0.06716
ma2    0.02932
omega  0.44909
alpha1 0.79120
beta1  1.02912

Asymptotic Critical Values (10% 5% 1%)
Joint Statistic:         1.89 2.11 2.59
Individual Statistic:    0.35 0.47 0.75

Sign Bias Test
------------------------------------
                   t-value      prob sig
Sign Bias           3.3842 0.0007247 ***
Negative Sign Bias  0.5320 0.5947678
Positive Sign Bias  0.3897 0.6967648
Joint Effect       19.5500 0.0002104 ***

Adjusted Pearson Goodness-of-Fit Test:
------------------------------------
  group statistic p-value(g-1)
1    20     259.6    3.576e-44
2    30     286.2    4.244e-44
3    40     322.5    2.575e-46
4    50     348.2    1.040e-46

Elapsed time : 0.30832

Comment: Could you clarify you question besides the one in the last paragraph? Also, you equation for the conditional variance model is a GARCH(1,2), not GARCH(1,1).
Answer:
The forecast seems to be quite strange

What exactly do you mean? What is the question here?

Also, how can it be, that every forecast for the same time series is the same but e(t+1) should be a random variable?

The best point forecast for the error term e(t+1) under square loss is its estimated conditional mean, which is zero. You do not expect e(t+1) to actually be zero, but zero is your best guess. That is why the point forecast for e(t+1) is zero every time.

My goal is not to find the best guess but to model a time series model (at least that is what my professor said). So is there a way to set e(t+1) equal to a random variable with zero mean and the conditional variance instead of zero?

Your question title says "forecasting", so I answered it as such. Now if you want to model the time series for some other purpose, you can still use the same model as an approximation of the true data generating mechanism. If you want to simulate some paths from your estimated model, you can do that with the functions ugarchsim and/or ugarchpath. They will generate some random errors according to the estimated properties of those errors from the historical data.
Comment: I edited the print out in my question. My goal is not to find the best guess but to model a time series model (at least that is what my professor said). So is there a way to set e(t+1) equal to a random variable with zero mean and the conditional variance instead of zero?
Comment: Sorry for the confussion. I am pretty new to time series analysis and I mix up the different terms. ugarchsim/ugarchpath may be the methods I need. I will try them out and report back.
Comment: @user2968163, how is it going with ARMA-GARCH?
Comment: I am not quite sure if I am using ugarchpath right. The plot looks alright. Here is my Code: GARCHspec<-ugarchspec(variance.model = list(model = "sGARCH", garchOrder = c(1, 1),submodel = NULL, external.regressors = NULL, variance.targeting = FALSE),mean.model = list(armaOrder = c(2, 2), include.mean = TRUE))
Comment: GARCHfit<-ugarchfit(GARCHspec,diffclosingkursu)
GARCHspecfixed<-ugarchspec(variance.model = list(model = "sGARCH", garchOrder = c(1, 1),submodel = NULL, external.regressors = NULL, variance.targeting = FALSE),mean.model = list(armaOrder = c(2, 2), include.mean = TRUE),fixed.pars=list(mu=(-0.031455),ar1=(-0.096911),ar2=0.861134,ma1=0.023537,ma2=(-0.940248),omega=0.162944,alpha1=0.246904,beta1=0.711975))
GARCHforecast<-ugarchpath(GARCHspecfixed,closingkursu,n.sim=1000, n.start=0, m.sim=250)
Comment: @user2968163, So I guess you are doing it right. Do you have any further questions (directly related to your post)? Or is there something I should clarify about my answer?

Forecasting with ARMA-GARCH


Complex integral along an ellipse

Question: I have to evaluate the function $f(z)$ = (1+$e^z$/$z^2$) along the ellipse $cos(t)$+2$i$$sin(t)$ where t goes from 0 to 2$\pi$. I know there's singularity at 0. I am thinking of using a homotopy from this ellipse to a circle but I don't know how to write it down.  If there's a simpler way without using homotopy, please point it out. Any help with this integral is appreciated.
Comment: Hint: Look at the region between the ellipse and the circle. Your function is analytic in that region. Use Cauchy's Theorem.
Answer: You have noted that the only singularity occurs at $z=0$ which is contained in your contour. If you have access to the residue theorem you can use it here. The value of the integral is $2\pi i$ times the coefficient on the $1/z$ term of the Laurent series.
Rewriting your function as
$$
f(z)=\frac{1}{z^2}+\frac{1}{z^2}e^z=1/z^2+\frac{1}{z^2}(1+z+\frac{z^2}{2}+.....)
$$
We see the only term that gives weight to the integral has coefficient 1, so the value is just $2\pi i$.
Comment: @Hades sure thing!

Complex integral along an ellipse


Fitting a function to a sequence of datapoints (quadratic)

Question: I'm looking for a formula for the next term in a sequence (example from an RPG game).
$\begin{matrix}
n & f(n)\\\hline
1 & 29 \\
2 & 33 \\
3 & 37 \\
4 & 41 \\
5 & 46 \\
6 & 50 \\
7 & 55 \\
8 & 60 \\
9 & 65 \\
10 & 70 \\
11 & 75 \\
12 & 81 \\
13 & 86 \\
14 & 92 \\
15 & 98 \\
16 & 104 \\
17 & 111 \\
18 & 117 \\
19 & 124 \\
20 & 131 \\
21 & 137 \\
22 & 145 \\
23 & 152 \\
24 & 159 \\
25 & 167 \\
26 & 175 \\
27 & 183 \\
28 & 191 \\
29 & 199
\end{matrix}$
Who knows value for $f(30)$, $f(31)$, $f(32)$ etc? What is the formula?

Strictly speaking, there's no reason to assume this pattern repeats, although this certainly looks like it's quadratic. It looks like the values in this sequence are just the result of $0.0814n^2+3.6298n+25.44$, rounded.
Jack Crawford

why not line graph you can see on image below
trendline why not - click to view
Comment: There's no reason to not assume that the values are arbitrarily chosen
Comment: It increases almost regularly, difference between two numbers in turn: `4,4,4,5,4,5,5,5,5,5,6,5,6,6,6,7,6,7,7,6,8,7,7,8,8,8,8,8`
Comment: It seems like you've modified your question to add, well, basically a whole extra question to it. I'm kind of confused. Could you perhaps just make this a new, separate question, or at least format this one in a less confusing way? I think it's usually against the *vibe* of stack exchange to edit your question to add a new one after it's already been answered
Comment: Also it looks like you added back some tags that we removed in edit. We removed those tags for good reason, this question is *not* about elementary number theory, or about pattern matching. Pattern matching is a particular thing in computer science, and none of this has to do with number theory.
Comment: If you roll back this question to the previous edit and just post this as a new question (let me know when you have) I'll be more than glad to help you out with it.
Comment: If you're saying that the values yielded by this quadratic (rounded) are not the same as the actual empirical values you observe when you manually go and check the negative values, it's because, as @HagenvonEitzen notes above, there's no reason to assume that these are all generated in some consistent way. If the values you get over the negative range are different to the values you get from the quadratic over the positive range, that's because they must be using a *completely different* function for those values. As we've said, the game developer can do whatever they want with the sequence.
Comment: You probably just have to go and collect some new data and run another regression on it as I described below.
Comment: [formulas](https://math.stackexchange.com/questions/3256147/regresion-formulas-from-an-rpg-game) @Jack Crawford
Answer: Strictly speaking, there's no reason to assume this pattern repeats, although this certainly looks like it's quadratic.
I used Excel to run a quick regression and give me the closest quadratic, and I get this: $f(n) \approx 0.0814n^2 + 3.6298n + 25.44$. It looks like the values in this sequence are just the result of this quadratic, rounded.
Here are the values you had, and here is the value generated by this quadratic for comparison:
$\begin{bmatrix}
n & \textrm{data}& f(n)\\\hline
1 & 29 & 29.1512 \\
2 & 33 & 33.0252 \\
3 & 37 & 37.062 \\
4 & 41 & 41.2616 \\
5 & 46 & 45.624 \\
6 & 50 & 50.1492 \\
7 & 55 & 54.8372 \\
8 & 60 & 59.688 \\
9 & 65 & 64.7016 \\
10 & 70 & 69.878 \\
11 & 75 & 75.2172 \\
12 & 81 & 80.7192 \\
13 & 86 & 86.384 \\
14 & 92 & 92.2116 \\
15 & 98 & 98.202 \\
16 & 104 & 104.3552 \\
17 & 111 & 110.6712 \\
18 & 117 & 117.15 \\
19 & 124 & 123.7916 \\
20 & 131 & 130.596 \\
21 & 137 & 137.5632 \\
22 & 145 & 144.6932 \\
23 & 152 & 151.986 \\
24 & 159 & 159.4416 \\
25 & 167 & 167.06 \\
26 & 175 & 174.8412 \\
27 & 183 & 182.7852 \\
28 & 191 & 190.892 \\
29 & 199 & 199.1616
\end{bmatrix}$
I think that's what you're after.
They just round the result at the end.
If you ever want to do this yourself (it's a very useful little trick, and can fit other kinds of functions to your data, too!), just line the columns of data up next to each other in Excel, select them, make a line graph, and then right click on the line and choose the "add trendline" option. From the trend-line menu, you can play around with the different kinds of functions and see if you can find the one that fits your data the best (as you noted in one of your comments above, there are a few properties about this that should point us in the direction of this being quadratic; a degree-2 polynomial), and then select "display equation on chart" and they will give you the equation for the best-fitting trendline. Good luck with your game!
Comment: Solving $0.0814x^2+3.6298x+25.44 = 19$ and rounding $x$ gives $x = -2$.
Comment: Nice explanation ! Using matrix calculations, you would get the exact coefficients $\frac{439}{5394}$, $\frac{45685}{12586}$ and $\frac{15493}{609}$. And $\to +1$.
Comment: I probably meant that, thank you :) but can you show what it looks like for negative values? I want to match the number 19 (and I mark the topic as solved)
Comment: Sure! You can just use that formula I gave you, as Toby suggested, but here are the values we get for the first few negative inputs, $\begin{matrix} -20 & -14.596 \\
-19 & -14.1408 \\
-18 & -13.5228 \\
-17 & -12.742 \\
-16 & -11.7984 \\
-15 & -10.692 \\
-14 & -9.4228 \\
-13 & -7.9908 \\
-12 & -6.396 \\
-11 & -4.6384 \\
-10 & -2.718 \\
-9 & -0.6348 \\
-8 & 1.6112 \\
-7 & 4.02 \\
-6 & 6.5916 \\
-5 & 9.326 \\
-4 & 12.2232 \\
-3 & 15.2832 \\
-2 & 18.506 \\
-1 & 21.8916 \\\end{matrix}$


Orientable double covers for non-orientable manifolds

Question: If I have two non-orientable connected manifolds such that their orientable double covers are homeomorphic, can anything be said about the manifolds? Are they homeomorphic?
Answer: They are in general not homeomorphic. Here is a counterexample.
Consider the manifold $X = S^2 \times S^2 \times S^2$. We define two free $C_2$ actions on X, where $C_2$ is the cyclic group of order $2$.
The first is $(x,y,z) \sim (-x,y,z)$ and the second is $(x,y,z) \sim (-x,-y,-z)$. You obtain two quotients with are on the one hand $\mathbb{R}P^2\times S^2 \times S^2$ and on the other hand some $6$-manifold $M$.
Since both actions are orientation reversing you see that both quotients are non-orientable. Moreover since $X$ is simply-connected both quotients have $C_2$ as fundamental group. This directly implies that $X$ must be in both cases the orientation double cover (since there is only one connected 2-sheated covering over the quotients).
Now we claim that $M$ and $\mathbb{R}P^2\times S^2 \times S^2$ are not homeomorphic. This you can prove using rational cohomology. For $\mathbb{R}P^2\times S^2\times S^2$ you can do this by Künneth, and for $M$ I at the moment do not know of a better reason than using the Cartan-Leray spectral sequence to show that $H^*(M;\mathbb{Q}) \cong H^*(X;\mathbb{Q})^{C_2}$ where the last means the $C_2$-invariants of the cohomology of $X$ by the induced $C_2$-action. Now you can distinguish the two manifolds by H^2 and H^4.
It would be interesting to explicitly identify the manifold $M$ if this is possible.
Comment: Thank you for answering. I'm working out the details of the counterexample.
Comment: You are welcome. Were you able to check all details?
Answer: Here's a slightly easier example than mland's.
Let $X = S^2\times S^4$  Then $X$ is the universal (orientation) cover of both $\mathbb{R}P^2\times S^4$ and $S^2\times \mathbb{R}P^4$.  By the Kunneth formula, $H_2(\mathbb{R}P^2\times S^4) \cong 0$ while $H_2(S^2\times \mathbb{R}P^4) = \mathbb{Z}$.
Somewhat relatedly, (if you want a lower dimensional example), $T^2\times S^2$ covers both $K\times S^2$ and $T^2\times \mathbb{R}P^2$ where $K$ denotes the Klein bottle.  In this case, the fundamental group of the first is nonabelian while the fundamental group of the second is abelian.
Comment: Does anyone know if $4$ is the lowest possible dimension of a counterexample?


How to change attribute value with pointer

Question: I am trying to change a value within a struct. Unfortunately, the value in "" ==>", flow" doesn't change. I don't understand why.
Can you help me to explain why the pointer doesn't correspond in Slice. May be I must write a slice of pointer ?
Thank you in advance.
package main

import (
    "fmt"
)

type Foo struct {
    value float64
}

var flows []Foo;

func AddFoo(foo Foo) {
    flows = append(flows, foo)
}

func UpdateFoo(stream *Foo) {
    stream.value = 5.00
}

func main() {
    x := Foo{1.00}
    AddFoo(x)
    UpdateFoo(&x)
    fmt.Println(x)

    for _, flow := range flows {
        fmt.Println(" ==>", flow)
        }
}

Comment: Your `x` got added to the `flows`. Then you change x. This does not change the value inside `flows`. It is like `a := 3; b := a; a = 5; fmt.Println(b);` As `b`'s value is a copy of `a`'s value it would be strange if `b`changed. Same with slices. Work your way through the Tour of Go once more.
Comment: Thank you Volker. It's true. Thank you so much for this help.
Answer: In your function AddFoo you are adding a copy of Foo to your slice, then in UpdateFoo you are changing x which is not the same variable as the one in the slice.
Yes, if you'd create a slice of pointers it'd work.
Comment: Thank you for your answer. I tried to create slice of pointers before my question but I had an error on another function. So Excuse me for this question. I am tired


Problemas com a pasta vendor/bin de uma aplicação Laravel

Question: Estou tentando fazer deploy de uma aplicação laravel tanto na AWS(Amazon Web Services) quanto na Heroku, e ambos acusaram erros no phpunit dentro da pasta vendor.
Depois de várias pesquisas(que já me custaram umas 6 horas) finalmente achei o erro  dentro da pasta vendor/bin onde praticamente todos os arquivos estão corrompidos.
Esses são os arquivos corrompidos:

Eles estão com os seguintes erros:
Ex: vendor/bin/dep
    #!/usr/bin/env sh

dir=$(cd "${0%[/\\]*}" > /dev/null; cd "../deployer/deployer/bin" && pwd)

if [ -d /proc/cygdrive ]; then
    case $(which php) in
        $(readlink -n /proc/cygdrive)/*)
            # We are in Cygwin using Windows php, so the path must be translated
            dir=$(cygpath -m "$dir");
            ;;
    esac
fi

"${dir}/dep" "$@"

Ex: vendor/bin/php-parse:
#!/usr/bin/env sh

dir=$(cd "${0%[/\\]*}" > /dev/null; cd "../nikic/php-parser/bin" && pwd)

if [ -d /proc/cygdrive ]; then
    case $(which php) in
        $(readlink -n /proc/cygdrive)/*)
            # We are in Cygwin using Windows php, so the path must be translated
            dir=$(cygpath -m "$dir");
            ;;
    esac
fi

"${dir}/php-parse" "$@"

E algumas outras também.
Alguma ideia de como resolver isso?
Answer: Exclui a pasta vendor, adiciona no .gitignore e na vpn roda o composer install.
Comment: É interessante apagar o composer.lock também.
Comment: Eu fiz exatamente o que você falou, apaguei o vendor, e também o que o CypherPotato disse e apaguei o composer.lock, e ainda dava erro, então li vários tutoriais gringos e percebi que o erro acontecia pois algumas das dependências que estavam no require-dev estavam sendo necessárias no require, então comecei a colocar uma por uma as dependências do require-dev no require conforme davam erro, mas isso levaria muito tempo então copiei e colei tudo, agora estou com outro erro, quando uso o "heroku open", não abre o site, aparece o erro "Não foi possível acessar esse site". Alguma ideia ?
Comment: A propósito, já configurei o Procfile.


Problems with the sample (unkown population)

Question: I realized a large research with Brazilian physics high-school teachers and I wanted that my sample could be representative of the Brazilian physics high-school teachers population. However, nobody in Brazil knows how many teachers there are, in which cities they are or who they are to provide contact.
So, during one year, I contacted teachers, schools, universities, governmental secretaries, labor unions, and event organizers and I reached more than 7000 names of possible teachers.
To build my sample, knowing that a lot of them wouldn't not answer the survey, I invited 33% of this 7000 names to participate of the research. I chose randomly this 33%, but I can't contact many of them and others didn't fit with my population (they are no more teachers, they teach only in Universities and so on). In the end of one year trying to contact this 33%, I got about 300 valid responses.
But now, with all data collected, I'm not sure if my sample could be considered a simple random sampling (SRS) and how I can modify and fix my results to extend them to all population if my sample is not a SRS (or another previously known sampling method). Someone could help me?
Thank you,
Alysson Ramos Artuso
Comment: **Of the six sources for names that you mention**

- Individual teachers
- schools
- universities
- gov secretaries
- labor unions
- event organizers

• How many of the original 7,000 names came from each?
• How many of the 33% sample of names (~2,333) came from each
• How many of the final 300?
Comment: **Focusing on High schools**
• How many high schools did you contact? How did you select them? Did they include private as well as public schools? In what way, if any, would you consider them representative of  high schools which might teach physics?
• How many schools provided any information? Of these, how many had physics programs?
Comment: Hello, Steve. Thank you for your help!
Let's me explain better some points. We don't have an educational census, so nobody knows how many high-schools or teachers there are. My contact with individual teachers, schools, universities and so on ('the sources') was a tried to estimate how many physics high-school teachers are in Brazil and how I can contact them (every high-school has physics, it is a mandatory discipline).
Comment: I didn't count or separate how many 'sources' a contacted or how many names which of them provide to me. I just contacted as many as I could.

In this contact, I just pretend to have a better estimative of how many physics high-school teachers I could consider as my population (About 1,000? About 50,000? I estimate the answer is about 10,000) and how I can contact them. These teachers are in private and public schools. I got about 7,000 names.
Comment: Considering these 7,000 as my population, I send a survey for 2,500 approximately, choosing randomly this 2,500. 343 teachers answered the survey and I'm considering that this is my sample (n = 343). In this sample, 57% teachers teach in public schools, 29% in private and 14% in both - these numbers are probably close to real. 73% are male teachers and 27% are female teachers, but I have no parameter to know if this is close to real or not.
Comment: Brazil is divided in five regions, and, probably, I have, proportionally, less answers from Northeast and more answers from North in comparison with the amount of physics high-school teachers in these regions, but, again, I didn't have way to be sure. For lucky, almost every answer in the survey seems to not change according to the region – only 2 variable (in 11) shows some statistically significant difference according to the region in hypothesis tests and only between two regions (North and South).
Answer: Alysson's sample can't be considered a random population sample, because the list of names doesn't qualify as a valid sampling frame. The best that Alysson can do, I think, is to state that he had a diverse study group, but that he cannot say that it is a random sample.
Any applied sampling text will tell you that the design of a sample starts with one (or more) sampling frames. You can think of a frame as a list of "slots", or "listings".  Each "slot" contains none, one, or more of the target population. A random number selects from among the eligible slots.  In an ideal frame would be in a 1-1 correspondence of slots with member, but this rarely occurs.
For example, slots may contain no members of the target population. Some slots might reference units who are not members of the population. Duplicate listings are also a problem, because then the frame over-represents the multiply-listed units.
Since random numbers draw frame units, the probability of selection is known for every selected unit. This is the hallmark of a "probability sample", also known as a "representative" or "scientific" sample.
In Arturo's case, the ideal frame would be a list of all high school physics teachers. Such a list doesn't exist. Therefore In its place, he gives a list of names collected from different sources. This list might contain all the physics teachers, but there's no way of telling.
I make a stab, knowing little about Brazil, about how a professional sampler there might  design the study. In place of trying to construct a frame of names, the sampler would employ a multi-stage design. The country would be stratified into regions and into principal cities. In each stratum, smaller geographical units, primary sampling units, or "PSUs" , would be listed (this is the initial frame) and a sample of these would be selected with probability proportional population size. Within each PSU, even smaller geographic units (second stage sampling units SSUs) might be listed (another frame!), and a sample of these selected. Finally, an effort would be made to locate every high school in each SSU (another frame) and all, or a sample of physics teachers would be contacted. An effort would be made to interview a sample, or all, teachers in the selected school. Though three-or-four stages of sampling might be necessary, the probabilities of selection would be known at every stage. I would guess that 20-40 PSUs would be sufficient to cover the entire county, with maybe 100 high schools. If recruitment is successful, the sample would yield at least 100 physics teachers.
The main feature of the multistage design is that there is no attempt to list all the physics teachers in the country or all the high schools in the country or even in a PSU. Even if little is known about the population, a valid representative sample can still be drawn. There are examples in the classic book "Sampling Design in Business Research by WE Deming (Wiley, 1960). The virtue of studying a smaller number of high schools is that resources and time be concentrated on achieving contact and gaining cooperation of respondents.


Logging the output of VBoxHeadless

Question: I want to be able to launch a VM in headless mode and log the outputs of its tty to the command line.
Basically I have a situation where the VM will be launched remotely (hence the command line requirement), but every once and a while, the VM's bootup sequence freezes, and right now there's no way for me to debug why the VM is not booting up properly unless I go there manually and view it in a non-headless mode.
The VM itself does not have a GUI, it just boots into TTY mode.
So is there anyway I can get some debugging output from the TTY while it's headless?
One crazy idea would be using non-headless mode and taking screenshots of the window that opens, but there must be a better way!
Answer: You can use the following command to output a PNG file of the current screen, even in headless mode:
<code>vboxmanage controlvm [vmname] screenshotpng screen.png
</code>
Comment: Nice. Quick and simple. But I would still prefer andsens's solution.
Answer: I am trying to get some integration testing for bootstrapped virtualboxes up and running and ran into the exact same problem. After finding out that VRDP is a dead end, because RDP  cannot send text but only bitmaps, I remembered that some cloud providers require grub to output to ttyS0.
What is ttyS0 you ask? It's the serial console of course :-)
Here's how to configure Debian to output to serial console
VirtualBox allows you to redirect the serial port into either a file or a pipe, meaning you should be able to get all the information you desire by simply reading the specified filepath.
Comment: Yup! Works like a charm. When using the socket option ("named pipe") I was able to print the console messages directly to my terminal using `socat` :-)
Here's a more programmatic way of accessing the output: http://goo.gl/ps6dDK

Logging the output of VBoxHeadless


Nested Case statement in sql query

Question: My Query
Declare     @From       DateTime='01 Feb 2013'
Declare     @To         DateTime='28 Feb 2013 23:59:59'

Select
            Case
                  When
                  (
                        Select TOP 1 f1.UpdatedOn
                        From TicketTypeFollowUp As f1 with(nolock)
                        Where f1.UpdatedOn<T.UpdatedOn And f1.Ticket=T.Ticket
                        Order By f1.UpdatedOn Desc
                  )IS Null
                  Then Ticket.TicketRaisedOn

                  Else
                  (
                       Select TOP 1 f1.UpdatedOn
                       From TicketTypeFollowUp As f1 with(nolock)
                       Where f1.UpdatedOn<T.UpdatedOn And f1.Ticket=T.Ticket
                       Order By f1.UpdatedOn Desc
                  ) End [Start Date]

      From dbo.TicketTypeFollowUp T with(nolock)
      --Some Tables Omitted
      Where CAST(TicketRaisedOn As Date)Between ''+Convert(VarChar(19), @From, 100)+''       And ''+Convert(VarChar(19), @To, 100)+''

If the Column [Start Date] has values Greater than @To Then @To Value should print Else [Start Date] Column
How can i write it in the same query ?
What i tried
       Case When(
             Case
                  When
                  (
                        Select TOP 1 f1.UpdatedOn
                        From TicketTypeFollowUp As f1 with(nolock)
                        Where f1.UpdatedOn<T.UpdatedOn And f1.Ticket=T.Ticket
                        Order By f1.UpdatedOn Desc
                  )IS Null
                  Then Ticket.TicketRaisedOn

                  Else
                  (
                       Select TOP 1 f1.UpdatedOn
                       From TicketTypeFollowUp As f1 with(nolock)
                       Where f1.UpdatedOn<T.UpdatedOn And f1.Ticket=T.Ticket
                       Order By f1.UpdatedOn Desc
                  ) End [Start Date]
              )> @To Then @To Else [Start Date] End,

DB : SQL SERVER 2008
Comment: what error you are getting while modifing your query in your way as posted above?
Comment: At the first glance you nested `CASE-END` query looks reasonable.  What's wrong with it? Do you get any errors? Is your result different from what you expected to see?
Answer: It looks to me like you need this:
Declare     @From       DateTime='01 Feb 2013'
Declare     @To         DateTime='28 Feb 2013 23:59:59'

Select CASE WHEN ISNULL(StartDates.[Start Date], Ticket.TicketRaisedOn) > @To THEN @To ELSE ISNULL(StartDates.[Start Date], Ticket.TicketRaisedOn) END AS ResultValue
From dbo.TicketTypeFollowUp T with(nolock)
    --Some Tables Omitted
    OUTER APPLY
    (
        Select TOP 1 f1.UpdatedOn AS [Start Date]
        From TicketTypeFollowUp As f1 with(nolock)
        Where f1.UpdatedOn<T.UpdatedOn And f1.Ticket=T.Ticket
        Order By f1.UpdatedOn Desc
    ) StartDates
Where CAST(TicketRaisedOn As Date)Between ''+Convert(VarChar(19), @From, 100)+''       And ''+Convert(VarChar(19), @To, 100)+''

The OUTER APPLY lets you specify a computed value per row, referencing values from the joined tables above, but after that it's rather like data coming from a JOIN. So you give your APPLY an alias as if it were a table and then access its value as many times as needed above.
As you can see, this dramatically simplifies your query-- APPLY is extremely handy to have in your tool belt.)))
EDIT Added another ISNULL per comment.
Comment: In Outer Apply...Case When Else End Condition Come ? as i have same in My Select query...
Comment: That should be taken care of by ISNULL in the CASE in the outer query, which will use the first value if it isn't NULL, otherwise the second value. On reflection, you may need it in the ELSE block there, too, though. I will edit my answer.

Nested Case statement in sql query


How to take and save photo without Uiimageview (swift4)

Question: The following code is that standard take photo then place it on imagview then save the image on image view to the photo gallery. I want to skip the uiimageview part and just take photo and have it automatically save to the photo gallery.
<code>import UIKit

class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    var imagePicker: UIImagePickerController!
    @IBOutlet weak var imageTake: UIImageView!
    @IBAction func takePhoto(_ sender: AnyObject) {
        imagePicker =  UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .camera
        present(imagePicker, animated: true, completion: nil)
    }

    @IBAction func save(_ sender: AnyObject) {
        UIImageWriteToSavedPhotosAlbum(imageTake.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
    }

    @objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        if let error = error {
            let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "OK", style: .default))
            present(ac, animated: true)
        } else {
            let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "OK", style: .default))
            present(ac, animated: true)
        }
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        imagePicker.dismiss(animated: true, completion: nil)
        imageTake.image = info[UIImagePickerControllerOriginalImage] as? UIImage
    }
}
</code>
Comment: What problem are you having while trying not to use the image view?
Answer: Then you can do the following edit
<code>@IBAction func save(_ sender: AnyObject) {
    /// useless now
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
    if let error = error {
        let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    } else {
        let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    }}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    imagePicker.dismiss(animated: true, completion: nil)
    if let img = info[UIImagePickerControllerOriginalImage] as? UIImage
    {
           UIImageWriteToSavedPhotosAlbum(img, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
}}
</code>


Problem connecting to a Samba server with share mode security

Question: I'm setting up a Samba server on Ubuntu 9.04 Server Edition.
What I'm trying to do is have a share that is readable by everyone, and writable by a select few.
I am able to login from my computer using smbclient //server/security -U brad,
but I am unable to connect using [Places->Connect to Server...] with a username and password.
One thought I came up with is that I'm using lower case letters in the password.
This is a portion of the /etc/samba/smb.conf file that was generated by swat.
/etch/samba/smbd.conf

[global]
  preferred master = Yes
  domain master    = Yes
  wins support     = Yes

  security               = SHARE
  usershare allow guests = Yes
  guest ok               = Yes
  null passwords         = Yes
  guest account          = samba
  map to guest           = Bad User

  unix password sync     = Yes
  lanman auth            = Yes
  client plaintext auth  = Yes
  lanman auth            = Yes
  client NTLMv2 auth     = Yes
  client lanman auth     = Yes
  client plaintext auth  = Yes

[Security]
  comment = Security and Antivirus software
  path                = /share/security
  write list          = brad
  inherit permissions = Yes
  inherit owner       = Yes
  hide special files  = Yes
  hide unreadable     = Yes

/var/log/samba/log.192.168.0.5

# smbclient //server/security -U brad
[2009/05/04 09:45:31,  1] smbd/service.c:make_connection_snum(1111)
  192.168.0.5 (192.168.0.5) connect to service Security initially as user brad (uid=1000, gid=1000) (pid 3129)
[2009/05/04 09:48:49,  1] smbd/service.c:close_cnum(1323)
  192.168.0.5 (192.168.0.5) closed connection to service Security

# smbclient //server/security -U brad
[2009/05/04 09:48:53,  1] smbd/service.c:make_connection_snum(1111)
  192.168.0.5 (192.168.0.5) connect to service Security initially as user brad (uid=1000, gid=1000) (pid 3177)
[2009/05/04 09:48:58,  1] smbd/service.c:close_cnum(1323)
  192.168.0.5 (192.168.0.5) closed connection to service Security

# smbclient //server/security -U brad # giving null password at prompt
[2009/05/04 09:49:45,  1] smbd/service.c:make_connection_snum(1111)
  192.168.0.5 (192.168.0.5) connect to service Security initially as user samba (uid=1024, gid=1024) (pid 3189)
[2009/05/04 09:49:51,  1] smbd/service.c:close_cnum(1323)
  192.168.0.5 (192.168.0.5) closed connection to service Security

# connect with [Places->Connect to Server...] # with username and password
#
#

# connect with [Places->Connect to Server...] # without username
[2009/05/04 09:50:29,  1] smbd/service.c:make_connection_snum(1111)
  192.168.0.5 (192.168.0.5) connect to service Security initially as user samba (uid=1024, gid=1024) (pid 3310)

When I log in using smbclient //server/security -U brad, I can delete a file I put there by other means.
All files and folders are currently owned by the username samba, but I am willing to change the owner if it would help.
I would really prefer to keep it under share mode security.
This is what I ended up doing:
[Security]
  comment  = Security & Antivirus software
  path     = /share/security
  readonly = Yes

[Security$]
  comment   = Security & Antivirus software +rw
  path      = /share/security
  browsable = No
  administrative share = Yes

Answer: I think that you need to re-examine whether share-mode security is what you actually need for this problem. Share mode security means that a password is used to authenticate to a share, not a username/password combination.
If you want to allow multiple users (logging in as themselves) access to modify the files then you need to use user level security.
If you want to allow anybody that knows the magic password to see the share, then share mode security is right for you.
See the Samba Documentation for more information on share level security.
Comment: I only want to make it so that the computer that is logging on will not have write access, without some interaction with the user.
Comment: ... and only for this share. Most, if not all, other shares will have r/w access enabled.
Comment: It's unclear what is not working... If you connect to the share without authenticating can you read or write files to the share?
Answer: The best way to debug this is check /var/log/messages or similar to see what auth errors Samba is generating. If you can post that this is going to be easier.
You can tail -f /var/log/messages and also check /var/log/samba/*
Post your results when you try to connect. You're most likely interested in smbd and nmbd errors, so you can grep for those.


Create/edit group web-service in ELGG

Question: I am looking for the webservice which would create the group. I looked at the available web service in elgg . I can only find the following web services related to the group -
Group

group.join Joining a group
group.leave Leaving a group
group.forum.save_post Posting a new topic to a group
group.forum.delete_post Deleting a topic from a group
group.forum.get_latest_post Get latest post in a group
group.forum.get_reply Get replies on a post
group.forum.save_reply Post a reply
group.forum.delete_reply Delete a reply

Do we have anything for create group web service in elgg.
Answer: Please add following function, and its defination in your webservice file in ELGG/engine/lib/web_services.php
/**
 * The group.save API.
 * This API call lets a user to create group.
 *
 * @param string $name group name
 * @param string $briefdescription short description
 * @param string $description long description
 * @param string $interests tags comma separated
 * @param int $group_guid GUID of group if its edit request
 *
 * @return bool success/fail
 * @access public
 */
function group_save($name, $briefdescription, $description, $interests, $group_guid)
{
   //you can change/pass below parameters from POST
   $_GET['action']='groups/edit';
   $_POST['membership'] = '2';
   $_POST['activity_enable'] = 'yes';
   $_POST['blog_enable'] = 'yes';
   $_POST['forum_enable'] = 'yes';
   $_POST['pages_enable'] = 'yes';

   //include file at location "ELGG/mod/groups/actions/groups/edit.php"
   include_once '../../mod/groups/actions/groups/edit.php';

   //Or you can copy all code from that file and paste it here. And do modification according to your need.

}

Finally, you should expose a function like following:
expose_function(
        "group.save",
        "group_save",
        array(
                        'name' => array ('type' => 'string'),
                        'briefdescription' => array ('type' => 'string'),
                        'description' => array ('type' => 'string'),
                        'interests' => array ('type' => 'string'),
                        'group_guid' => array ('type' => 'int', 'required' => false),
        ),
        'User add/edit group',
        'POST',
        true,
        true
    );

Comment: You can do the same thing via plugin. See why: http://docs.elgg.org/wiki/Dont_Modify_Core
Comment: @PawełSroka I am talking about web-service, so how can I create just single web-service to create group, because rest services are available.
Comment: @PawełSroka I don't mean to change the core, but if I use any web-service plugin then also I can add same function in that plugin file instead `web_services.php` My goal to show create group web-service.
Answer: Paweł Sroka is right. you could make a basic plugin with a manifest.xml and a start.php in it and place your code in the start.php, and it does not matter wether you write a single function in it or hundreds.
for example you can take a look at the following plugin: https://github.com/markharding/elgg-web-services
Comment: I already rviewed all webservice plugins available, and finally I came to know that there are no web-service for create group. Please read my question.

Create/edit group web-service in ELGG


Fitch-Style Proof

Question: Hi I'm having trouble solving a Fitch Style Proof and I was hoping someone would be able to help me.
Premises:

$A \land (B \lor C)$
  $B \to D$
  $C \to E$

Goal: $\neg E \to D$
Thank You
Comment: Do you still need help with this?
Answer: You should be able to transform the following in a formal proof.
Assume $\neg E$.
Prove $B\lor \neg B$ with the intent to use $\lor$-$\text{Elim}$.
If $B$ holds, then use $\to$-$\text{Elim}$ on the premise $B\to D$ to conclude $D$.
Suppose $\neg B$ holds. Use $\land$-$\text{Elim}$ on the first premise to get $B\lor C$. You will want to use $\lor$-$\text{Elim}$ on $B\lor C$. If $B$ holds you can get $D$ in two ways, choose one of them. If $C$ holds, eliminate $\to$ on the premise $C\to E$ to get $E$ and a consequently a contradiction, thus getting $D$ with $\bot$-$\text{Elim}$. Eliminating the disjunction $B\lor C$ gives you $D$.
Eliminating the disjunction $B\lor \neg B$ yields $D$.
Finish off.
You can find the proof hidden in the grey area below.
Comment: **Revision Notes:** You don't need to use LEM ($B\lor\lnot B$) because the first premise entails $B\lor C$ and the second premise *is* $B\to D$. $~$ Since $C\to D$ can be deduced from the third premise under the assumption of $\neg E$ , you may then derive $D$ by or-elimination, and therefore discharge the assumption to deduce $\neg E\to D$.
Comment: @GrahamKemp Thanks.
Answer: Do a proof by contradiction. Assume $\neg E \wedge \neg D$. Then we have from $A \wedge (B \vee C)$ that $B \vee C$. If $B$, then $D$, which contradicts $\neg D$. If $C$ then $E$ which contradicts $\neg E$.
Comment: @GitGud: There is no hard work in this question and I was giving him a strategy instead of a full Fitch proof. Mine does work formally, minus some $\wedge$-Elim's I didn't explicitly mention; there is no "correct" strategy for giving a simple proof like this.
Comment: Please read this [comment](http://math.stackexchange.com/questions/829828/fitch-style-proof#comment1712888_829829) which I gave in another answer. Though I feel like your suggestion may be a bit closer than the other answer, dealing with the details is where the 'hard' work is.
Answer: To begin with: you have $\neg E$, and combine this with $C \to E$, then you have: $\neg C$, but $B \lor C$ must be true, so this yields $B$, and with $B \to D$, apply Modus Ponen: we have: $D$.
Comment: I wasn't gonna say anything, but this came up in the review queue, so now I'm compelled to. I don't think your answer gets the OP closer to solving the problem. It does hint at a way to do it, but not necessarily an easier way. Reiterating: I don't think proving what you suggest is easier than solving the problem in a more standard way.
Comment: That stupid user is me. I had four options while reviewing: *Looks OK* (it didn't look OK, it still doesn't look OK, I think you need to review your natural deduction), *Edit* (It wasn't at all reasonable to transform your answer into something that can actually help the OP), *Skip* and *Delete*. Maybe I could have chosen skip and kept an eye on your answer to see what happens, but it's also perfectly reasonable to delete. You took this personally unnecessarily, I have nothing against you.

Fitch-Style Proof


Clash in Flutter library functions on a platform I'm happy to drop

Question: I'm building a web app with dart/flutter.
I'd like to use file_picker with rich_clipboard but when I try and add the latter I get this message…
flutter pub add rich_clipboard
Because rich_clipboard_windows >=1.0.2 depends on win32 >=2.5.1 <5.0.0 and rich_clipboard_windows <1.0.2 depends on win32 ^2.5.1,
  every version of rich_clipboard_windows requires win32 >=2.5.1 <5.0.0.
And because file_picker >=5.3.2 depends on win32 ^5.0.2, file_picker >=5.3.2 is incompatible with rich_clipboard_windows.
Because rich_clipboard <1.0.0 depends on rich_clipboard_windows ^0.0.1 and rich_clipboard >=1.0.0 depends on rich_clipboard_windows
  ^1.0.0, every version of rich_clipboard requires rich_clipboard_windows ^0.0.1 or ^1.0.0.
Thus, file_picker >=5.3.2 is incompatible with rich_clipboard.
So, because [] depends on both file_picker ^5.3.2 and rich_clipboard any, version solving failed.

I don't need to target win32 - does that enable a solution?
Answer: Try changing file picker veraion to any pubspec.yaml
file_picker : any

Then flutter clean and flutter pub get. If this doesnt work then downgrade file picker to a smaller version
file_picker : 5.2.0

Comment: thanks for this - it'll come in handy if I have other version clashes between libraries. Flutter's error message let me to mistakenly believe it had checked all versions of these libraries rather than fixing file_picker at ^5.3.2
Answer: The error occurs due to incompatible dependencies between the rich_clipboard and file_picker. So not targeting win32 won't fix your problem. You can downgrade file_picker to 5.3.0 until file_picker or rich_clipboard update their dependencies to be compatible with newer versions of win32 package.
In your pubspec.yaml set file_picker as following
file_picker: ^5.3.0

Answer: I couldn't find an alternative to rich_clipboard so I swapped out file_picker for file_selector.
I then did:
flutter clean
flutter upgrade
dart run build_runner build


Calculus Implicit Differentiation &Partial Diff.

Question:
Express v$_x$ in terms of u and y if the equations x =vln(u) and y= uln(v) define u and v as functions of the independent variables x and y, and if v$_x$ exists.

Implicitly differentiating a function gives:
(1) (ln(u)v$_x$) + (v/u)u$_x$ = 1
(2) (u/v)v$_x$ + (ln(v)u$_x$) = 0;
Now I have to solve for v$_x$, which should be no problem, but I think I am tripping over algebra.
Textbook pulls some formula out of thin air and gives answer ln(v)  / (ln(u) ln(v)-1).
Anyone got any idea?
Comment: The problem I am having is with eliminating u$_x$. How do I get rid of that?
Answer: $$
x = v\ln u\\
y = u\ln v.
$$
Taking logs of the first equation we get
$$
\ln x = \ln v  + \ln \ln u.
$$
We can now sub $y$ in and get
$$
\ln x = \frac{y}{u} + \ln \ln u
$$
Take the derivatives with respect to $x$ we find
$$
\frac{1}{x} = -\frac{y}{u^2}u_x +\frac{1}{u\ln u}u_x
$$
We have an equation for $x$ for later.
Taking the derivative of our initial second equation we find
$$
0 = u_x \ln v + \frac{u}{v}v_x \implies \frac{u_x }{u}= -\frac{1}{v\ln v}v_x
$$
So we have
$$
\frac{1}{x} = -\frac{u_x}{u}\left[\frac{y}{u}-\frac{1}{\ln u}\right] = \frac{1}{v\ln v}\left[\frac{y}{u}-\frac{1}{\ln u}\right]v_x = \frac{1}{v\ln u}
$$
Re-arrange we find $v_x$ as
$$
v_x = \frac{\ln v}{\ln u \left[\frac{y}{u}-\frac{1}{\ln u}\right]}
$$
Now you have
$$
\frac{y}{u} =\ln v
$$
Now you are done.
I went the long way just to be simpler (but you can take short cuts).
Comment: Thank you for your help. I thought I needed to derive something for u$_x$, since we had two equations and two variables (v$_x$ and u$_u$). Fortunately your solution worked and I can now solve this!


Return only newest record in database with SQL

Question: How can I return only one (the newest) record in database using SQL?
As example I have records:
dateFrom     dateTo   dateInserted
2017-08-09  2017-08-20 2017-08-10
2017-08-15  2017-08-17 2017-08-15

And my query is to return record that has dateFrom and dateTo between or even 2017-08-09 and 2017-08-20. So now both records will be returned, but is it possible to return only one record, the newest one, that means 2017-08-15  2017-08-17 2017-08-15 in this case?
I know how to sort by date, but then, anyway, both records will be returned only sorted, as example:
Select dateFrom,dateTo
From  temp t1
where date = (select max(date) from temp where t1.name =temp.name)
order by date desc

I need only one record cause asterisk can't work with two results or so...
Comment: use `limit 1` with the `order by ` clause
Answer: Just add LIMIT 1
SELECT dateFrom, dateTo
FROM  temp t1
WHERE date = (SELECT MAX(date) FROM temp WHERE t1.name = temp.name)
ORDER BY date DESC
LIMIT 1

Comment: wow, that was simple... How did I miss that... Thank you very much!


Set User Control's default event

Question: I have a User Control containing a bunch of controls. I want to set the default Event of this User Control to the Click event of one of my buttons.
I know for setting default event to one of the UserControl's events I should add the attribute:
[DefaultEvent("Click")]
public partial class ucPersonSearch : UserControl
...

I'm wondering if it's possible to do something like:
[DefaultEvent("btn1_Click")]
public partial class ucPersonSearch : UserControl
...

I want to fire some methods in the form hosting this User Control at the time btn1 is clikced.
This is really a knit in my project, and you're answer will be valueable.
Comment: ??? I have no idea what you're trying to say.
Answer: You can't expose events of your class members to the outside of the class. How can others subscribe to the Click event of a Button inside your UserControl? Did you try it? It's not possible unless you make the button accessible from the outside, which is not good (everybody can change all the properties).
You have to define a new event, and fire your new event when your desired event (clicking on the button) happens:
[DefaultEvent("MyClick")]
public partial class UCPersonSearch : UserControl
{
    Button btnSearch;
    public event EventHandler MyClick;

    public UCPersonSearch()
    {
        btnSearch = new Button();
        //...

        btnSearch.Click += new EventHandler(btnSearch_Click);
    }

    void btnSearch_Click(object sender, EventArgs e)
    {
        OnMyClick();
    }

    protected virtual void OnMyClick()
    {
        var h = MyClick;
        if (h != null)
            h(this, EventArgs.Empty);
    }
}

Comment: Use `[DefaultEvent(nameof(MyClick))]` instead of hard-coding the name.
Comment: @MahdiTahsildari You're welcom, my compatriot :-)
Comment: Thanks @MD.Unicorn good idea, before reading your answer the idea of making the button public came up, and it worked. Your answer is also good, even better. Good lock.
Comment: @jor Thanks for pointing that out, but the answer war written before C# 6 (2015) where this feature is introduced. :) For historical reasons, and sice the WinForms platform is no longer actively being used, I'll keep the answer that way.

Set User Control's default event