Easiest way to make body of text wrap around image

Question: I would like to have a body text wrap around the the image below. Here is an example:
http://www.fareham.ac.uk/events/2011/06/creative-arts-summer-exhibition
And here's an excerpt of the code:

        Fri 24 Jun 2011

    Don't miss your chance to see the incredible artwork produced by this year's Creative Arts students at Fareham College.

    The exhibition will be held on the College campus, featuring work from our Art, Graphic Design, Photography, Fashion and Media students.

    This event runs on weekdays from 10am–4pm on 24th June–1th July 2011 in both the A-Block and the Function Room at Fareham College.

    We look forward to seeing you.

How can I get the  with the text in to wrap around the  with image in?
Thank you.
Answer: Put the field before the text and apply a float class to the field.
.field-field-event-image {
float: left;
}

Comment: The order of the elements needs to change as the image needs to come before the text in order to allow it to float around it. Otherwise the image will still just sit under the text.
Comment: How do I configure Drupal to 'put field before the text'?
Comment: You already have the date before the text.
Comment: I don't know why I didn't think of this sooner, but I changed the order of page elements here: `/admin/content/node-type/event/fields`, which allowed me to float the image using CSS as above. For what it's worth, that same can be achieved with the Panels module. Thanks.
Answer: I would overriding the node template for this content type.
This can be achieved by copying the node.tpl.php file and renaming it to something like
node-event.tpl.php (change event to the machine readable name of the content type)
You can then output the fields manually in whatever order you need them along with your markup.
I find the easiest way of working out the variable names is by installed the Content Templates module which lets you see the variables going to that node template.
Hope this helps.
Comment: This is helpful, thanks thatboyjim - I shall install contemplate module and have a crack!


403 on creating a node via rest api

Question: I have an issue with creating a node via rest API. I have the correct permissions setup but it seems like a glitch somewhere in the permissions. An admin can create a content but no other role can.
{content_type}: Can create new content permission is checked.
Getting access denied error along with the username in the logs.
Config:

Client:
return api({
    method: 'post',
    url: 'node?_format=hal_json',
    data: JSON.stringify(_node),
    headers: {
        'Content-Type': 'application/hal+json',
        'X-CSRF-Token': _xscrf_token,
    },
});

Answer: Url should be /entity/node?_format=hal_json
Comment: What difference does this make in terms of user roles? 'An admin can create a content but no other role can' - that's my issue.
Answer: Make sure you check the correct permissions for the roles you want in the "RESTful Web Services" section on the /admin/people/permissions page.
Comment: The permissions are right. There is an issue with Drupal. If the role is given "Administer content" permission, the issue resolves. But that shouldn't be the case.

403 on creating a node via rest api


Cannot use fields as product attributes if they are within a field collection

Question: I am building a commerce marketplace, and have several field that I am reusing on multiple product types. It's getting tedious adding them over and over, so I'd like to include them in a field collection.
The issue is that fields within a field collection cannot be marked as (and I'm paraphrasing) "should be used as a product attribute." I'm assuming this is because the fields do not know that they will be used on a commerce product, so the option isn't available.
Does anybody know of a way to implement this functionality? I'm open to coding, I just don't know what I'd work on.
Answer: By default Drupal Commerce supports list type fields (list, term reference - list, etc.) as Product attributes, not sure but may be because pre-defined list of values.
It would be difficult to get the field collection as your product attribute, because attributes make the product Unique and using the field collection won't give you much feasibility to use every field value to differentiate between product. Instead you can re-use fields in every product type and get it working easily.
If you still would like to give field collection module a try, you can check Drupal Commerce module in detail for attributes implementation or refer Commerce Attributes Date module which allows date field to be used as Product Attributes (Drupal Commerce doesn't support Date type field as attribute by default).
Comment: The fields that I was trying to include were Lists/Term References, so they worked as attributes on their own. That's why I was hoping they would work inside the field collection field. I didn't solve this question, but I did find Field Tools (https://www.drupal.org/project/field_tools) which let's you clone a field from one bundle into any other bundle, which essentially solves my issue of adding/maintaining many instances of each field.
Comment: Great. So you just need to export and import.
Answer: I wasn't able to answer the questions above, but I was able to solve my problem using Field Tools, which let's you clone fields to and from any bundles, as well as apply mass edits to all instances of a single field.


Variable's value doesn't change in remote process

Question: So, I have an activity and a service. Service's doing a lot of work that hangs my main application's thread, so I decided to run this service in a remote process (:remote in Manifest). Though everything was working while the service was working in the main process, in the remote process something odd happens.
On the end of onCreate method in my service I set SERVICE_RUNNING variable's value to true. Log.d one line above confirms, that its value really is true. But when I call the static method isRunning() (which returns SERVICE_RUNTIME's value) from my activity, it returns false. Here's my code:
Service:
public class PlayService extends Service {
    private static Boolean RUNNING = false;

    @Override
    public void onCreate() {
        super.onCreate();
        SERVICE_RUNNING = true;
        Log.d("ctw", "onCreate() " + SERVICE_RUNNING); // "onCreate() true" in logcat
    }

    public static Boolean isRunning()
    {
        Log.d("ctw", "isRunning() " + SERVICE_RUNNING);
        return SERVICE_RUNNING;
    }
}

Activity:
if(PlayService.isRunning())
{
    // executes when service is running and PlayService is not a remote process
} else {
    // executes always when PlayService is a remote process
}

Thanks in advance!
Answer: You said that you have separate processes. So each process has it's own PlayService class loaded and own instance of RUNNING flag. You cant share data via static vars between different processes.
Run service in separate thread, not process.
If you are really want different processes than use AIDL to communicate with service.
Comment: Well, so I'll just use AsyncTask in the PlayService class. Thanks for pointing it out!
Comment: You also can use [IntentService](http://developer.android.com/reference/android/app/IntentService.html) which handles all requests consequently on a single worker thread


Finding the expectation value of a random variable counting the occurrences of certain events

Question: Let there be $M$ (distinguishable) boxes and $N$ balls, which we uniformly distribute among the boxes. For $k \leq N$, let $g_k: \Omega \rightarrow \mathbb{Z}$ be the function counting the number of boxes yielding exactly $k$ balls. Note that I am a bit reluctant to specify $\Omega$ (Distinguish the boxes or not?) as it seems key to me to find a clever way to sort the events in it.
What would be the expectation value of $g_k$ then?
Answer: In real life probability the balls and boxes will be distinguishable to get equally probable events (though perhaps not in sub-atomic physics).
You can calculate $E[g_k]$ using the binomial distribution and linearity of expectation: take the probability of the first box having $k$ out of $N$ balls and multiply by the number of boxes.
So $\displaystyle E[g_k] = {N \choose k} \frac{(M-1)^{N-k}}{M^{N-1}}.$
Answer: We assume that for each of the $N$ balls, we choose a box uniformly and independently. For any box $i$, let $X_i=1$ if Box $i$ has exactly $k$ balls, and let $X_i=0$ otherwise. Then the number $Y$ of boxes with exactly $k$ balls is $\sum_1^M X_i$. By the linearity of expectation, we have
$$E(Y)=\sum E(X_i)=ME(X_1).$$
It remains to find $E(X_1)$. Since $X_1$ is a  Bernoulli random variable, $E(X_1)=\Pr(X_1=1)$. But
$$\Pr(X_1=1)=\binom{N}{k}\left(\frac{1}{M}\right)^k\left(\frac{M-1}{M}\right)^{N-k}.$$
Remark: The distribution of $Y$ would be quite unpleasant to get at. The method of Indicator Random Variables bypasses finding the distribution.
Answer: Hint:
For every box $i$ let $B_{k,i}$ take value $1$ if it contains $k$
balls and $0$ otherwise. Then $g_{k}=\sum_{i=1}^{M}B_{k,i}$ and
consequently $\mathbb{E}g_{k}=\sum_{i=1}^{M}\mathbb{E}B_{k,i}=Mp_k$
where $p_k$ denotes the probability that a specified box contains $k$
balls.
For finding $p_k$ have a look at the answer of André.


How to debug a custom activity designer?

Question: I have a custom workflow activity for which I've written a designer. Unfortunately, when I drag my activity from the toolbox onto the workflow designer surface, I get an error ("Could not generate view for ..."). I suspect that some code in my designer (which is running inside of Visual Studio) is at fault.
How can I debug the code in the designer? Since it normally runs inside of VS, I'm not sure how to proceed.
Answer: You can start a second copy of VS2010 and attach the debugger to that instance to debug your designer.


What does ADE20k (the scene segmentation benchmark) stand for?

Question: ADE20k is a scene segmentation dataset created by MIT. It is a common benchmark for localization tasks in computer vision research. I cannot find anywhere what the name stands for!
This information isn't presented on their website their  github or their paper. Please answer if you know.
Answer: 20K is a reference to there being roughly 20,000 images in the dataset (although the number of images seems to have been increased after the initial release).
According to a zhihu post from the first author, ADE are the first 3 letters of the name Adela Barriuso, who single handedly annotated the entire dataset. I came across a quite interesting "Notes on image annotation" written by Adela.
Image of the annotation process.


Creating json array in C# by fetching data from csv

Question: I want to create the below json using C#. All the data is pulled from a csv file.
{
    "car":[
        {
            "manufacturer": "Nissan",
            "fuelType": "petrol",
            "mileage": 20
        },
        {
            "manufacturer": "Nissan",
            "fuelType": "diesel",
            "mileage": 20

        },
        {
            "manufacturer": "Tesla",
            "fuelType": "electric",
            "mileage": 240
        },
        {
            "manufacturer": "Honda",
            "fuelType": "hybrid",
            "mileage": 100
        }
    ]
}

Below is the C# code that i have written and also the output that I get when I run the code. I want the car to be an array of objects, instead I am getting an array of with car object containing an array of single car. I am new to C# and json.
namespace createJSONfromCSV
{
    class Program
    {
        static void Main(string[] args)
        {
            string Path = @"C:\Files\CarDetails.csv";
            List<string> csvData = new List<string>();
            List<carDetails> carlist = new List<carDetails>();

            StreamReader reader = null;

            if (File.Exists(Path))
            {
                reader = new StreamReader(File.OpenRead(Path));
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    csvData.Add(line);
                }

                foreach(var item in csvData)
                {
                    if(item != csvData[0])
                    {
                        string[] fields = item.Split(',');
                        carlist.Add(new carDetails()
                        {
                            cars = new List<car>()
                            {
                                new car()
                                {
                                    manufacturer = fields[0],
                                    fuelType = fields[1],
                                    mileage = Convert.ToInt32(fields[2])
                                }
                            }
                        });
                    }
                }
                var carDetailsjson = JsonConvert.SerializeObject(carlist, Formatting.Indented);
                Console.WriteLine(carDetailsjson);
            }
            else
            {
                Console.WriteLine("File does not exist...");
            }
        }
    }
}

class carDetails
    {
        public List<car> cars { get; set; }
    }

    class car
    {
        public string manufacturer {get; set;}
        public string fuelType { get; set; }
        public int mileage { get; set; }
    }

The output I am getting is as below:
[
    {
      "cars": [
        {
          "manufacturer": "Nissan",
          "fuelType": "Petrol",
          "mileage": 20
        }
      ]
    },
    {
      "cars": [
        {
          "manufacturer": "Nissan",
          "fuelType": "Diesel",
          "mileage": 60
        }
      ]
    },
    {
      "cars": [
        {
          "manufacturer": "Tesla",
          "fuelType": "Electric",
          "mileage": 240
        }
      ]
    },
    {
      "cars": [
        {
          "manufacturer": "Honda",
          "fuelType": "Hybrid",
          "mileage": 100
        }
      ]
    }
  ]

Comment: Make one list of car. Not a list for every line.
Answer: Instead of carDetails object which has only a List property, you should add Car object to the list in foreach condition. So your code should be like;
            List<car> carlist = new List<car>();
  carlist.Add(new car()
                                                         {
                                    manufacturer = fields[0],
                                    fuelType = fields[1],
                                    mileage = Convert.ToInt32(fields[2])
                                });

Answer: Just build up a single cars list. In the foreach you just add car objects to the list:
var cars = new List<car>();

foreach(var item in csvData)
{
     if(item != csvData[0])
     {
           string[] fields = item.Split(',');

           cars.Add(new car()
           {
                manufacturer = fields[0],
                fuelType = fields[1],
                mileage = Convert.ToInt32(fields[2])
           });
     }
}

var carDetailsjson = JsonConvert.SerializeObject(new carDetails() { cars = cars }, Formatting.Indented);


haproxy url_dec does not work with url_reg

Question: I would like to use haproxy (1.7.5-2 2017/05/17, debian stretch stock) as a first line of defense against some possible attacks (e.g. SQL injection). The idea is that I create an acl in the frontend that detects unwanted patterns using regexps and then use an always-failing dummy backend in that case. Something like this:
acl sql_injection url_reg -i -f /etc/haproxy/sqlinject.patterns
use_backend bad_request if sql_injection

The problem is, that if the url is url-encoded, then e.g. foo.com/?select
foo from bar would be transmitted as foo.com/?select%20
foo%20from%20bar, which really needs a different regexp, and thus a matching regexp would bee unnecessarily broad. Hence come url_dec:
acl sql_injection url_reg,url_dec -i -f /etc/haproxy/sqlinject.patterns

However, this does not seems to work, as it does not seem to match anything. Even if I put .* into the pattern file, I get no matches.
There is no syntactical error in the configuration, as haproxy -c returns no warnings or errors. How could I match the urldecoded query string?
Comment: It seems like the fact that this does **not** throw a configurarion error or warning might be a bug, because it doesn't seem logical to me (but I could be wrong).  Consistent with your original style, I would suggest that you try `acl sql_injection url,url_dec -m reg -i -f /etc/haproxy/sqlinject.patterns` or (the way I probably would have written it from scratch without seeing how you are doing it) `acl sql_injection url,url_dec,lower,map_reg(/etc/haproxy/sqlinject.patterns)` (with your regexes written for lower case).
Comment: I actually have a nagging sense that there is still something not right about my approaches, either, but can't put my finger in what it might be.
Answer: The variant suggested by @michael-sqlbot seems to be working:
acl sql_injection url,url_dec -m reg -i -f /etc/haproxy/sqlinject.patterns

Thus, the above seems to be a haproxy error, either in configuration verification or interpretation.


TypeError when converting dictionary to JSON array

Question: How do I take a python dictionary where the keys and values are Strings and convert it into a JSON String.
This is what I have right now:
import json

def create_simple_meeting(subject, startDate, endDate, location, body):
    info = dict()
    if(subject != ""):
        info["subject"] = subject
    if(startDate != ""):
        info["startDate"] = startDate
    if(endDate != ""):
        info["endDate"] = endDate
    if(body != ""):
        info["body"] = body
    if(location != ""):
        info["location"] = location
    print(json.dumps(dict))

create_simple_meeting("This is the subject of our meeting.","2014-05-29 11:00:00","2014-05-29 12:00:00", "Boca Raton", "We should definitely meet up, man")

And it gives me this error
  File "/Users/bens/Documents/workspace/Copy of ws1 for py java playing/opias/robot/libs/playing.py", line 15, in create_simple_meeting
    print(json.dumps(dict))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <type 'dict'> is not JSON serializable

Answer: You are trying to serialise the type object, dict, instead of info. Dump the right variable:
print(json.dumps(info))


Como deixar um background responsivo em c#?

Question: Como relacionar o background_image ao tamanho da janela?
Exemplo:
    Define minha imagem de fundo, mas ao alterar o tamanho da janela(minimizando) a imagem fica "incompleta", e não segue as bordas agindo tanto que independente.
Comment: Você está programando para web ou desktop?
Comment: Para o Desktop usando WinForms
Answer: No Form tem uma propriedade BackgroundImageLayout veja qual se adéqua a sua situação. Imagino que sera Stretch


Using OLS to estimate an ARMA(1,1)

Question: Is it possible to obtain a consistent OLS estimator of an AR-parameter, given that the true process is an ARMA(1,1)? - It is purely a theoretical question regarding whether the AR-parameter is consistently estimated in the presence of moving average processes.
Comment: Possible duplicate of https://stats.stackexchange.com/q/251805/127281.
Comment: @lucasfariaslf It is not a duplicate. Here, the OP already understand that with OLS we can only estimate the AR-parameter, and wonders whether the estimator will be consistent or not.
Comment: @AlecosPapadopoulos Got it, thanks for explaining!
Answer: For the ARMA (1,1) model
$$y_t = \rho y_{t-1} + v_t + \theta v_{t-1}$$
with $v_t$ white noise, the OLS estimator is
$$\hat \rho = \frac {\sum y_ty_{t-1}}{\sum y_{t-1}^2} = \rho + \frac {\sum v_ty_{t-1} +\sum \theta v_{t-1}y_{t-1}}{\sum y_{t-1}^2}$$
We have that $(1/T)\sum v_ty_{t-1} \to_p 0$, and we are left to consider
$$(1/T)\sum \theta v_{t-1}y_{t-1} = (1/T)\sum \theta v_{t-1}[\rho y_{t-2} + v_{t-1} + \theta v_{t-2}] $$
Discarding terms that go to zero in probability asymptotically
$$\text{plim}(\hat \rho-\rho) = \theta\cdot\frac { \text{plim}(1/T)\sum v^2_{t-1}}{\text{plim}(1/T)\sum y_{t-1}^2} \neq 0$$
So it is not consistent.
After a bit of calculations we have
$$\frac { \text{plim}(1/T)\sum v^2_{t-1}}{\text{plim}(1/T)\sum y_{t-1}^2} \to \frac {1-\rho^2}{1+\theta^2+2\rho \theta}$$
so
$$\text{plim}(\hat \rho-\rho) = \frac {\theta(1-\rho^2)}{1+\theta^2+2\rho \theta}$$
Comment: Alecos, shouldn't it be $$y_{t-1}^2$$ in the denominator and not $$y_{t}^2$$ But the statement of the OLS estimator to be inconsistent when estimating the AR parameter still stands I suppose?
Comment: @user162158 Yes, thank you for spotting this, corrected. The conclusion stands, since the process is stationary so unconditional moments do not depend on the index.

Using OLS to estimate an ARMA(1,1)


Can't open PDF file located in server in WebView on android device

Question: I would like to open a PDF file that located in the server (Here)
in a specific place in my application.
I saw a couple of example how to do it with a webview, but no one works for me.
This is part of my code that should preview the pdf inside a WebView :
<code>     WebView webView = (WebView) findViewById(R.id.webView1);
     webView.getSettings().setSaveFormData(true);
     webView.getSettings().setJavaScriptEnabled(true);
     webView.loadUrl("http://mes.mes-ltd.com/itay.pdf");
</code>
The solution is just a Blank webview.
Thanks for help!
Answer: You can't open a PDF directly in the WebView, it just doesn't support this. You'll need to do something like the solution outlined here.
Comment: I did this, But if i want to show the pdf file not in a new intent? and only in a part of the screen. what should i do?
Comment: @user2235615 - you'd probably need to embed some sort of pdf viewer in your app then. See https://code.google.com/p/apv/ for example.


Need assistance getting around runtime error of Hackerrank problem

Question: I am trying to figure out why my for loop at the very end is producing a runtime error. It seems all fine to me and I'm at a loss of figuring a way around it.
<code>import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int n = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        int[] arr = new int[n];

        String[] arrItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < n; i++) {
            int arrItem = Integer.parseInt(arrItems[i]);
            arr[i] = arrItem;
        }

        scanner.close();
        for(int i = n; i >= 0; --i)
        {
            System.out.print(arr[i] + " ");
        }
    }
}
</code>
Comment: What error? Please post the full stacktrace
Comment: yes please post the relevant error log
Answer: Your bottom-most for loop starts from n when it should start from n-1
<code>    for(int i = n; i >= 0; --i) // should be for(int i = n-1; i >= 0; --i)
    {
        System.out.print(arr[i] + " ");
    }
</code>
which is possibly one of the errors in your code.
Comment: @NiVeR , isn't the --i in the for loop executed after the body in the loop is executed? In that case --i or i-- makes no difference. Check here : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html. It says that "The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value."
Comment: yea i just tried that and it solved the runtime error lol, thanks! im trying to figure out why thats the case


Let $A,B,X$ be subgroups of $G$ and $A \subset X \subset AB$. Prove that $A(B \cap X)=X$

Question: Let $A,B,X$ be subgroups of $G$ and $A \subset  X \subset AB$. Prove that $A(B \cap X)=X$
I am not sure how to do this.
Comment: Are you sure that is $\;B\cup X\;$ and **not** $\;\color{red}{B\cap X}\;$ ?
Comment: Or is it $A(B \cup X) = AB?$
Comment: i have edited it
Answer: Hint (almost proof):
According to Dedekind's Unimodular Law (which you should prove if you haven't studied yet)
$$A(B\cap X)=A(X\cap B)=X\cap AB=X$$
Be sure you can justify/prove each step above.
Comment: @ZZS14, I've changed the link to an easier one. In this new one they talk about modules but it is the same for groups in general, and the $\;+\;$ sign there is just the multiplication operation in the group, so you can change it freely.
Comment: @ZZS14, just prove the double implication: $\;t\in A(X\cap B)\implies t\in X\cap AB\;$ , and the other way around.
Comment: why is it necessary to change the order from B $\cap$ X to X $\cap$ B?
Comment: It is not, @ZZS14 : I just did it to take the order you wrote and *then* to use the order in which DUL usually appears.
Comment: oh okay, we have never studied this dedekind's unimodular law, i don't really understand the link either.
Comment: Well, then just prove the middle (the second) equality, @ZZS14. It's easy and it is the modular law.
Comment: would it be A(X $\cap$ B) = AX $\cap$ AB = X $\cap$ AB since A,X are subgroups?
Comment: No @ZZS14, the unimodular law says it is as it is written, and it is easily provable. Try it.
Comment: is it some form of dimW+dimU=dim(U+W)+dim(U∩W)? i have studied this in algebra.
I really don't understand


Por que devemos escalar/padronizar valores das variáveis e como reverter essa transformação?

Question: Ao trabalhar com algoritmos de previsão que usam multivariáveis me deparei com a função scale do R, que cujo objetivo é escalar/padronizar os valores das variáveis.
Não tenho dificuldades na utilização da função scale, mas minha dúvida é especificamente conceitual.
Por que devo escalar os valores das minhas variáveis? Qual é o objetivo? Isso faz diferença por exemplo, na acurácia do modelo de previsão do meu algoritmo? E como posso reverter a transformação?
Comment: Veja [este post](https://stats.stackexchange.com/questions/29781/when-conducting-multiple-regression-when-should-you-center-your-predictor-varia) do [Cross Validated](https://stats.stackexchange.com/). Mas esqueça uma das razões dadas, a da estabilidade numérica, hoje em dia isso já não é bem verdade, os computadores estão muito melhores. Isso foi dito no [R-Help](https://email@example.com/msg249829.html) há algum tempo atrás.
Comment: Obrigado pelas referências @Rui Barradas.
Answer: Devo escalonar minhas entradas? A reposta é: depende.
A verdade é que escalonar seus dados não irá piorar o resultado, então, na dúvida, escalone.
Casos em que se deve escalonar

Se o modelo se baseia na distância entre os pontos, como algoritmos de clusterização (k-meas) ou redução de dimensionalidade (PCA), então é necessário escalonar/normalizar suas entradas. Veja o exemplo:

Partindo dos dados:
    Ano  Preco
0  2000   2000
1  2010   3000
2  1970   2500

A matriz de distância euclidiana é:
       0       1       2
0 [[   0.   1000.05  500.9 ]
1  [1000.05    0.    501.6 ]
2  [ 500.9   501.6     0.  ]]

Observamos que a distância absoluta do preco dita qual será a distância, pois seu valor absoluto é muito maior que o ano. Porém, quando normalizamos entre [0, 1], o resultado muda drasticamente:
   Ano_norm  Preco_norm
0      0.75         0.0
1      1.00         1.0
2      0.00         0.5

A nova matriz de distância euclidiana é:
      0    1    2
0 [[0.   1.03 0.9 ]
1  [1.03 0.   1.12]
2  [0.9  1.12 0.  ]]

Outro exemplo, referente ao PCA, é este aqui.

Para algoritmos como Redes Neurais (veja esta referência), que utilizam o gradiente descendente e funções de ativação, escalonar as entradas permite:

Que features só positivas possuam uma parte negativa e outra positiva, o que facilita o treinamento.
Evita que alguma conta retorne valores como Not a Number durante o treinamento.
Se as entradas estiverem em escalas diferentes, os pesos conectados aos inputs serão atualizados em ritmos diferentes (alguns mais rápidos que outros). Isto prejudica o aprendizado.

E ainda normalizar as saídas é importante por conta da função de ativação da última camada.
Neste caso, para voltar a escala original da saída, basta guardar os valores utilizados para normalizar e fazer a conta inversa. Ex:
Para normalizar:
X_norm = (X - X_min)/(X_max - X_min)

Para voltar a escala original:
X = X_norm * (X_max - X_min) + X_min

Casos em que não é necessário escalonar

Algoritmos de corte, como Árvore de decisão e Random Forest.

Outros casos
Para alguns algoritmos como regressão linear, escalonar não é obrigatório e não melhora a acurácia. Escalonar ou não as entradas mudará apenas os coeficientes encontrados. Porém, como as entradas possuem magnitudes diferentes (como no exemplo acima de ano e preço), os coeficientes encontrados só poderão ser comparados se as entradas forem escalonadas. Ou seja, se quiser interpretabilidade, escalone as entradas.
Comment: Como o ARIMA só utiliza a própria variável temporal como entrada, a escala das entradas é a mesma, por isso não há necessidade de escaloná-las. Inclusive, a escala da saída é a mesma das entradas.
Comment: O ARIMA é uma regressão linear que tem como entrada um (ou mais) histórico(s). Por isso escalonar as entradas não irá melhorar o resultado.
Comment: Obrigado pela resposta @AlexCiuffa, me esclareceu muitas dúvidas. Se me permite gostaria de perguntar mais uma coisa e se puder responder ficaria muito grato. Você mencionou que em Regressão Linear escalonar não melhora na acurácia, mas e se eu usar o ARIMA seria o mesmo caso?
Comment: Entendi. Mesmo que eu inclua multivariáveis no modelo do ARIMA também não tem necessidade? Eu fiz alguns testes e não vi diferença, não sei quanto a interpretabilidade se muda algo.
Comment: Entendi. Muito obrigado pelo esclarecimento.


USPS API - After creating labels retrieving Tracking Number C#

Question: I have been able to successfully use the USPS API to create a shipping label.  The XML returned gives me a Delivery Confirmation Number, but it does not return the tracking number.  The tracking number is what I really need.  I've used (https://www.usps.com/business/web-tools-apis/delivery-confirmation-domestic-shipping-label-api.pdf) as my base for how to successfully create the label, but no place does it mention how to get the tracking number.
The tracking number is in the label that can be created from the base64 code that they send you in the XML output.  So to try to get around my problem I tried to save the label as an image file and use an OCR reader (both MODI & Tesseract) to read the tracking number.  That did not work.  All I received was gibberish.
So then I tried to save the output as a PDF instead and use iTextSharp to read the PDF.  The result was it did not read anything from the file.
So now I'm at a brick wall.  I cannot find any API documentation from USPS that would allow me to use the Delivery Confirmation Number to retrieve the tracking number.  I also cannot find an OCR that will read the tracking number from the output files from the base64 encoding.
Is there anyone out there that might have a solution to this problem?  Thanks in advance.
Answer: I am also looking for the tracking number. I successfully create the PDF and there is a barcode number but no tracking number.
Below is my code and it works fine.
      $devurl = "https://secure.shippingapis.com/ShippingAPI.dll";
       $xml = rawurlencode('<DelivConfirmCertifyV4.0Request USERID="your User id">
        <Option>1</Option>
        <ImageParameters>
            <LabelSequence>
              <PackageNumber>1</PackageNumber>
              <TotalPackages>99</TotalPackages>
            </LabelSequence>
        </ImageParameters>
        <FromName>Joe Smith</FromName>
        <FromFirm>ABC Corp.</FromFirm>
        <FromAddress1>Apt. 3C</FromAddress1>
        <FromAddress2>6406 Ivy Lane</FromAddress2>
        <FromCity>Greenbelt</FromCity>
        <FromState>MD</FromState>
        <FromZip5>20770</FromZip5>
        <FromZip4>1234</FromZip4>
        <ToName>Tom XofY</ToName>
        <ToFirm>XYZ Corp.</ToFirm>
        <ToAddress1>Suite 4D</ToAddress1>
        <ToAddress2>8 Wildwood Drive</ToAddress2>
        <ToCity>Old Lyme</ToCity>
        <ToState>CT</ToState>
        <ToZip5>06371</ToZip5>
        <ToZip4></ToZip4>
        <WeightInOunces>2</WeightInOunces>
        <ServiceType>Priority</ServiceType>
        <InsuredAmount></InsuredAmount>
        <SeparateReceiptPage></SeparateReceiptPage>
        <POZipCode></POZipCode>
        <ImageType>PDF</ImageType>
        <LabelDate></LabelDate>
        <CustomerRefNo></CustomerRefNo>
        <AddressServiceRequested></AddressServiceRequested>
        <SenderName> Imtiyaz</SenderName>
        <SenderEMail>firstname.lastname@example.com</SenderEMail>
        <RecipientName></RecipientName>
        <RecipientEMail></RecipientEMail>
        <Container>Variable</Container>
        <Size>Regular</Size>
        <CommercialPrice>True</CommercialPrice>
        <Content>
            <ContentType>LIVES</ContentType>
            <ContentDescription>Bees</ContentDescription>
        </Content>
    </DelivConfirmCertifyV4.0Request>');

    $service = 'DelivConfirmCertifyV4';
    $request = $devurl . "?API=" . $service . "&xml=" . $xml;
    $response = SendRequest($request);
    //print_r($response);
    $xml = new SimpleXMLElement($response);
    $myfile = fopen("trackingcreate.pdf", "w") or die("Unable to open file!");
    fwrite($myfile, base64_decode($xml->DeliveryConfirmationLabel));
    $json =json_encode($xml);
    $resarray  = json_decode($json);
    echo "
DeliveryConfirmationNumber :  ".$resarray->DeliveryConfirmationNumber;
    echo  "

ToName :   ".$resarray->ToName;
    echo "

ToFirm :   ".$resarray->ToFirm;
    echo "

ToAddress1 :  ".$resarray->ToAddress1;
    echo "

ToCity :   ".$resarray->ToCity;
    echo "

Postnet :   ".$resarray->Postnet;
    echo "

RDC :   ".$resarray->RDC;
    echo "

InsuranceFee :   ".$resarray->InsuranceFee;
    echo  "

Postage :   ".$resarray->Postage;
    echo "

CarrierRoute :   ". $resarray->CarrierRoute;

    function SendRequest($request){
    $session = curl_init();
    curl_setopt($session, CURLOPT_URL, $request);
    curl_setopt($session, CURLOPT_HTTPGET, 1);
    curl_setopt($session, CURLOPT_HEADER, false);
    curl_setopt($session, CURLOPT_SSL_VERIFYPEER , false );
    curl_setopt($session, CURLOPT_SSL_VERIFYHOST , false );
    curl_setopt($session, CURLOPT_HTTPHEADER, array('Accept: application/xml', 'Content-Type: application/xml'));
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($session);
    curl_close($session);
    return $response;
 }

Note the API shown (DelivConfirmCertifyV4.0Request) is for test only.  To make this production code, make these two changes:

Change the beginning and end XML tag from DelivConfirmCertifyV4.0Request to DeliveryConfirmationV4.0Request
Change
$service = 'DelivConfirmCertifyV4';
to
$service = 'DeliveryConfirmationV4';
Comment: Just copy and paste it in any file example my folder/filename.php
run the code and you will get pdf file (trackingcreate.pdf)  inside myfolder
Answer: It turns out that the delivery confirmation number that is returned via the XML can be used as the tracking number.  It's just that there was a little bit of lag time before the API created Delivery Confirmation Number appeared on the USPS website.


How do I check if a query table exists in Excel VBA?

Question: I want to check if QueryTables(1) exists, and if so, delete it.  I already know what code to use to delete it:
ActiveSheet.QueryTables(1).Delete

but I'm not sure how to check first that it exists, so that I don't get an error when it tries to delete a query table that doesn't exist.
UPDATE:
I tried using
If Not ActiveSheet.QueryTables(1) Is Nothing Then ...

And got a run-time error '9': Subscript out of range.
I get this same error when using the actual name of the query table I'm searching for (called "MonitorData").
Comment: @JacobH you don't `=` compare to `Nothing` - you use the `Is` operator instead, i.e. `If Not {object-expression} Is Nothing Then`
Comment: Maybe `If Not ActiveSheet.QueryTables(1) = Nothing Then... `
Comment: I tried this now - it gives me "Compile Error: Invalid use of object" and it highlights the word "Nothing."
Answer: You can check count as well
If Activesheet.QueryTables.Count > 0 then
    Activesheet.QueryTables(1).Delete
End If

Comment: @Ashley - Since this works please mark it as answered by clicking the grey check mark in the top left corner of the answer under the up-down vote arrows.
Comment: @Ashley see (someone answers)[https://stackoverflow.com/help/someone-answers] in the help center, for what your options are. I've upvoted this answer because the best error handling is *avoiding error conditions in the first place*. This answer deserves a checkmark IMO.
Answer: You could always just turn the errors off, run it then turn them back on:
on error resume next
ActiveSheet.QueryTables(1).Delete
On error goto 0

Comment: @JacobH if the deletion raises an error (VBA doesn't *throw exceptions*), `On Error GoTo 0` isn't going to fire it. Try & see. This pattern (OERN+potentially-errorring-statement+OEG0) is quite common and useful to know about, particularly in API's that don't give you any way of avoiding to raise an error.
Comment: Is this a good practice? If the Delete throws an exception does on error goto 0 fire?
Comment: Is this a good practice? Hard to say, philosophically. You want to supress the error - this does that verbatim. To your next question, yes the on error goto 0 fires. On error resume next means that the error is suppressed and the next line fires. In this case, the next line is on error goto 0, which turns errors back on.
Comment: Oh I see now what you meant by fire. Mat's Mug is right.
Answer: Mine worked with a few slight variations to shrivallabha.redij' s solution. Also made it clean all my old query tables at the start of the Sub:
If ActiveWorkbook.Queries.Count > 0 Then
    For i = 1 To ActiveWorkbook.Queries.Count
        ActiveWorkbook.Queries(i).Delete
    Next i
End If


How to link Team Services account with Azure with new console

Question: This was quite easy with the old console. Now its baffling. How do I achieve this feat?
Answer: Answer here.
I browsed for "Team services". The panel that comes up lists the Team Services accounts that you have access to. And then you can link a subscription to them.


Probability with Uniform Distribution with Multiple Variables

Question: Every time you go to a beach for vacation, you take home a little sand to keep as a souvenir. Over your lifetime, you have done this exactly 100 times. On each visit, the weight of sand you take home (measured in ounces) varies, but follows a $\mathrm{U}[10-\sqrt{48}/2, 10+\sqrt{48}/2]$ distribution. Assuming the amounts you take home on each trip are independent, estimate the probability that you have collected at least $980$, but no more than $1030$ ounces of sand.
I began by assigning $X$ as the total ounces of sand where $P(980 \le X \le 1030)$ is the probability we want to find. Then I set $Y$ as the ounces of sand per trip so that the sum of $Y$'s would equal $X$. From there, do I find the probability of $Y_i$, the ounces of sand during trip $i$, using uniform distribution? Then do I raise it to the power of 100 to find $X$?
Comment: The series of independent uniformly distributed random variables is approximately normally distributed for a large sequence.
Comment: @GrahamKemp So would I find the mean (expected value) and variance of Y and multiply it by 100 to find the probability for X?
Answer: Outline: Let $Y_i$ be the amount of sand brought back on trip $i$.  Then
$$X=Y_1+Y_2+Y_3+\cdots +Y_n,$$
where $n=100$.
The mean $\mu$ of each $Y_i$, by symmetry, is easy to find. The variance $\sigma^2$ is less easy. You can look it up, or calculate it from first principles.  By the way, if $W$ is uniformly distributed on the interval $[a,b]$, then $W$ has variance $\frac{1}{12}(b-a)^2$.  So the variance turns out to be quite nice in our case.
The exact distribution of $X$ is complicated. However, the $Y_i$ are nicely behaved independent identically distributed random variables, and $n$ is fairly large.
Thus (Central Limit Theorem) $X$ has approximately normal distribution, mean $100\mu$, variance $100\sigma^2$.
Now the probability that $X$ is between $980$ and $1030$ can be estimated.
Answer: Lindeberg–Lévy Central Limit Theorem.
Suppose $\{X_1, X_2, ..., X_n\}$ is a sequence of i.i.d. random variables with $E[X_i] = \mu$ and $Var[X_i] = \sigma^2 < \infty$. Then as $n$ approaches infinity, the random variables $\sqrt{n}(S_n − \mu)$ converge in distribution to a normal ${\cal N}(0, \sigma^2)$
$$\lim_{n\to\infty}\sqrt{n}\bigg(\mathop{\frac{1}{n}\underbrace{\bigg(\sum_{i=1}^n X_i\bigg)}}_{\text{You wish to find this.}} - \mu\bigg) \sim {\cal N}(0, \sigma^2)$$
That is: $\sum\limits_{i=1}^n X_i \,\dot\sim\,{\cal N}(n\mu, n\sigma^2)$
So then, you need to find the mean ($\mu$) and variance ($\sigma^2$) of an individual sample, when: $$X_i\sim{\cal U}(10-\sqrt{12}, 10+\sqrt{12})$$
Find: $\Pr(\frac{980-n\mu}{\sqrt{n\sigma^2}}\leq Z \leq \frac{1030-n\mu}{\sqrt{n\sigma^2}})$ using your Z-Tables.


How to do Authorization and Authentication in ASP.NET?

Question: I was wondering how do I make it so when a user goes to a page its only displayed if he is logged in and secure, but if he is not logged in he is redirected to the login page? Thanks guys.
Answer: Use Forms Authentication
Answer: FormsAuthentication will provide you with the redirect and subsequent Authorisation cookie but you'll need a Member store such as ASP.NET Membership to keep track of passwords and possibly Roles.
Answer: You can deny all un-authenticated users access in Web.config.  When used with Forms Authentication denied users will be redirected to the login page specified:
<code><authentication mode="Forms">
  <forms loginUrl="~/account/login" timeout="2880" />
</authentication>

<authorization>
  <deny users="?"/>
</authorization>
</code>
Answer: when user get loggedin store the user values in Session and on page load event of the page check the the session variable values.
So you can get the user id authenticate or not.


Descending thirds fingering (Zorba's dance)

Question: I found an arrangement of Zorba's dance. But there is a passage I don't like because I think there are thirds originally which sound much better. The arrangement is in the second picture.
The thirds I want to play:

Note that (it is not in the picture) the lowest third (G-B) is later in few bars (as the melody is shifted by one scale tone down) F major - A. So thumb is not preferred on the F major and then to be consistent also on the G.
I would like to play it legato, so that upper notes are connected (B in the second B-D third doesn't have to be played, if it is not possible)
The very first third in the pictures I play 2-3 and the second 1-4.
Do you have any thoughts on how to play these fast descending thirds?
The arrangement:
Comment: 42 31 (x) 42 31 42 31, or 42 31 42 31 53 42  would be "standard" or "classical" marking. Thirds are thirds, can't pretty them up.
Comment: There is a time to follow these rules about thumbs on black keys, but not here: 53 42 31 21 is by far the fastest option, regardless of the F sharp (I guess that's what you mean by f major).
Answer: If you look at Cortot's edition of the Chopin studies op. 25, no. 6, the one in thirds, he gives eight to ten different fingering possibilities for many of the (chromatic) runs. This example is not chromatic, but even so, I think the idea of a "standard" fingering is not helpful. And you should always try out any variations which you might find easier.
Here, there are only white notes, and you want the top notes to be legato, so the obvious fingering is 543243. Then fit the lower notes in: 53 42 31 21 is the only way to start; your thumb should be practiced at sliding like this. Then you could use 42 31, but this has the disadvantage of a repeated finger (2, on the two Bs). An alternative is 41 32, with a sliding thumb again, and slightly awkward switch to 32. But try both and see which you can get the smoothest.
(I may have misunderstood something; I don't understand several of your points, particularly the bit about "not in the picture".)
Comment: thx,English is not my mother tongue. 53 42 31 21 is what I prefer. I guess top note legato even when descencing sounds better, correct me, if I'm wrong. What I meant by the note "not in the picture" was that in few bars, the same notes/thirds are repeated, but all are shifted by one tone (if makessense by tone I mean tones in the scale, so possibly a semi tone). That means I cannot use 53 42 31 21 fingering, because 21 means thumb on a black key (f major) which I find awkward/slow. In this shifted down case I use 53 42 31 32, which breaks the legato but I haven't come up with anything better.
Comment: And for the double Bs, even if it's possible with 21 and 53 (without repeated finger), I think I'll simplify it to 21 and 4, leaving the second B out.
Answer: The "standard" fingering for scales in thirds, right hand ascending, is groups of 31 42 31 42 etc, plus the occasional 31 42 53 31 42 etc to keep your thumb off the black keys as much as possible. (Be thankful your arrangement only has one sharp in the key signature, not four or five!)
I gave that ascending not descending because for me, it seems easier to figure out how to play this completely legato at a slow tempo (except for the 53 to 31 transitions) ascending rather than descending, though once you see what the movement needs to be, it works in both directions. To get from 42 to 31, your  thumb goes under the 2, and your fourth finger goes over  the 3. Imagine you are a crab walking sideways along the keyboard, or a spider "feeling" with your fourth finger for the next note to play above the third finger.
Descending, the 2 goes over the thumb, and the 4 goes under the 3.
Start by practising this very slowly - 40 notes (not beats!) per minute is plenty fast enough till you start to get the feel of the 42-to-31 transitions. If you try to run before you can walk, your fingers will literally "fall over" each other.
A preparatory exercise is to hold a long note (say G) with your thumb (just to "anchor" your hand and take the weight of your arm), then play B C B C B C etc, legato, but with the fourth finger on B and the third finger on C - the opposite way round from how you would normally finger it. Turn your hand sideways so your fingers point to the right, to make it easier.

Descending thirds fingering (Zorba’s dance)


How do I read guitar tabs written in this format?

Question: I need some help learning how to read some Chinese guitar tabs I found online. They seem completely different to the standard Western format:

I don't even know where to start with these, I suppose the first line is telling me which chords are being played, but I'm more interested in the fingerstyle which is why the 2nd line onwards just confuses me. Why are there x's on the lines instead of numbers? It's a shame because I really love this song but have no idea how I'm going to play it.
Comment: There is some extra info about this at my answer here: http://music.stackexchange.com/a/16843/9198 In particular, it explains about the numbers above the staves, which notate the melody line.
Comment: By the way the text on the upper left tells you to use capo on the first fret. :)
Answer: This is actually a really nice way to notate guitar.  The chord symbol on top tells you what chord to play for the bar, and the tab itself is just indicating the arpeggio pattern.  So for example, in the first full bar, you finger a x32010 C major chord, then play the strings indicated as eighth notes (which are indicated by the eighth note beams).  Then there are a few hammer-ons written in the next-to-last bar when there are some notes outside of this system.
The numbers underneath are for the melody.  The numbers are the scale degrees of the music, the bars beneath are the rhythm (eighth and sixteenth note beams), and a dot above means the second octave.
Answer: I'd read it like this:
Make the chord like the first line says. Then the x's tell you which string to play, starting from the 6th string in the bottom to the 1st in the top.
The bars uniting the notes are to give you the tempo of these notes.
The numbers on the top of the bars are a mistery to me.
Comment: After looking at this for a long time, my best guess at the numbers, underlines, and dots underneath the guitar tab is that it's a tab for another instrument, probably wind blown, and it's for the melody part that goes along with the words.


how to pull the details together from SQL instance?

Question: I am looking to sort the details of number of DB's present in the SQL instance along with their Recovery model type and the size.?
ex: name , recovery_model_desc resides under sys.databases and size from sys.master_files. Also database_id is the shared column.
How to get the result in together?
Comment: `join` both the tables together
Comment: What have you already tried? Can you not just join `sys.databases` to `sys.master_files` on `database_id`? Or do you not know how to use a `JOIN`, is that your question?
Comment: I need to know on JOIN function at this instance, I have basic idea using JOIN but i couldn't make it here
Comment: I've added some reference material links to my answer below alongside the specific code you can use in this example. I hope that's helpful.
Answer: JOIN the two tables together on the key field you have correctly identified:
SELECT db.*, mf.*
FROM sys.databases db
LEFT JOIN sys.master_files mf ON db.database_id = mf.database_id

I suspect that the LEFT JOIN could just be JOIN/INNER JOIN as I don't think there can be records in sys.databases without any corresponding records in sys.master_files, but I don't know for sure, so stuck with a LEFT JOIN for that reason.
If you need some basics around JOINs to get you started with understanding how this works, here are some resources:

MSDN Blog: Introduction to Joins
W3 Schools: SQL Joins
SQL Authority: Introduction to JOINs
Essential SQL: Introduction to Database Joins

I've also often found a visual explanation of SQL Joins to be a helpful reference at times.


which language or tool will be better for reading a video file

Question: Actually I want to know how to read the pixel (raw) data of a avi video file.
How can I put these pixels (raw data) inside another video format so that I'm able to play it using another media player ?
Which language is good at manipulating video streamings of files? By good I mean "have good / free libraries" and "have a easy learning curve".
Comment: if you ask for a language why did you tag the question as 'java'?
Answer: I think you need to understand many concepts on JPEG, i kindly request you to read the following libraries source code from this link .The Ogle DVD Player
http://www.dtek.chalmers.se/groups/dvd/downloads.shtml
 1. libjpeg
 2. libdvdread
 3. ogle-0.9.2.tar.gz
 4. ogle_gui-0.9.2.tar.gz

Extract ogle-0.9.2.tar.gz which is the core library, there you have a folder called mpeg2_video , a file called videostream.c,screenshot.c .This will help in getting started.
Also be aware in Maths such as Fast Fourier Transform.


Why RAM usage is much bigger than Virtual Memory usage

Question: I am running some tests on a very powerful machine ( 24GB RAM, Window 2008 64bit )
I checked my task manager:
Physical memory: 98% ( RAM is 24GB )
But the totally "Memory(Private working set)" usage of all my running processors is no more than 16GB
Where are those extra 8GB used for? Is it used by the OS IO buffer, or somewhere else?
Can anyone contribute some ideas?
Comment: Voting to close as this is not a programming related question....
Comment: Should be on http://superuser.com/
Answer: Starting with Vista/Server 2008 Microsoft use almost all the memory available for caching purposes in order to improve performance:
Why Does Vista Use All My Memory?
Note that this doesn't affect the load time of new processes because the memory used by the cache is just discarded when more RAM is needed.
MS employee Mark Russinovich (cofounder of SysInternals) explains how virtual memory works in Windows:
Pushing the Limits of Windows: Virtual Memory.
The series Pushing the Limits of Windows are quite interesting because Mark explains several concepts of Windows that usually aren't well known or misunderstood (for example the difference between Process Address Spaces and Virtual Memory).
Answer: I thought memory is not shared so each VM has its memory reserved. That's why you see your memory usage high because of overhead to run Host OS.
Comment: But normally OS doesn't need 8GB to run. And most of time we see VM > ram
Comment: WS2008 requires 8gb, so if you run HyperV that's alot of resources consumed. Try with Core Server (w/o GUI)
Comment: Windows Server does *not* require 8Gb of ram, VinceL. http://www.microsoft.com/windowsserver2008/en/us/system-requirements.aspx
Answer: Windows (along with any operating system, including even DOS with SmartDisk!) will maintain a disk and IO cache in memory (including network buffers, etc). Another chunk of memory will go to managing the VM page tables (more RAM = more page tables) and other operating system overhead.
Different OSes have different policies on when they eject the disk cache for process memory, many will even prefer to swap out dead pages from a process instead of reducing the disk cache to near 0.
Comment: Is there any way to check the IO buffer size currently used? the VM page table should be pretty small, in 32bit machine is at most 16M, so should not be a problem


Scripting and Storing Google Form Responses to a database

Question: I've created a Google Form called "Career Progress Report Form" which stores the type of activity you've done on the day. I've created this to keep track of contacts, events, tasks, interviews, etc.
Career Progress Report Form
The Google Form was easy to create and the types of activities separate into different individual pages, however when it sends the responses to a spreadsheet it combines all results. The spreadsheet has too many columns  and not well organized. My ultimate goal is to store the records into a database where I could refer back to contacts, create individual reports on certain activities, create leads, opportunities, and accounts, and other career oriented tasks. I was considering creating individual spreadsheets for each type of activity so I would be able to create those exact columns as tables to a database.
How can this be done?
Details (updated frequently)
So for instance, stay I want to input today that participated in a webinar on Data Analytics and write a note that the webinar was in BrightTalk. On the response spreadsheet, it would input a new record:

Timestamp
Date
Type of Activity
Type of Program
Subject/Focus
Notes

The .... means that there are other columns there that refer to that page. Career Development is page 3 and starts at "Type of Program". Page 2 before that is Research which associates with "Type of Media", "Subject", and "Notes"
So the problem is that the columns for the entire form are in line with each other. So If I needed to see clearly what new information I entered I would have to scroll to the side. Hope this better explains.
Answer: Take look at their API:
Here is a SO question regarding reading from a Google Doc Spreadsheet: spreadsheet api
Essentially, read the values from the spreadsheet and insert them to your DB.
Comment: @Traestar  whatever the result let us know. That way we know if that was the correct solution to your issue.
Comment: The question that you've sent to me that referred to spreadsheet api, I'm not able to use that. So right now I'm backwards engineering from a PHP perspective to accomplish a similar result to the google form (PHP form to MySQL). Sorry if you are looking for a quick response, I'm working on it as I type.
Comment: After I'm done, I will compare the results to the google form as well as look for a way to connect the form to the MySQL database potentially


Alterando a largura da tela faz desaparecer barra de rolagem horizontal

Question: Segue o exemplo em jsfiddle: https://jsfiddle.net/DTcHh/31217/
Segue a imagem do problema:

Segue a imagem como deve ficar:

Navegadores testados:
Google Chrome Versão 57.0.2987.110 (64-bit): Não apresenta o problema
Microsoft Edge 38.14393.0.0 Microsoft EdgeHTML 14.14393: Problema
Firefox 52.0.1 (32-bit) - Problema: (Imagem abaixo)

Opera 43.0 Problema - (Imagem abaixo)

Alguma solução ?
Comment: aqui no meu ... a barra nao desaparece... ela continua aparecendo mas ela nao funciona. o.O
Comment: coloca `.DTFC_RightBodyLiner {
    overflow-y: unset !important;
}` no seu css que o problema do Opera e do Edge resolve
Comment: legal man... voce sabe que pode postar a resposta pra sua pergunta né? assim se alguem tiver o mesmo problema. vai saber como resolver ;)
Answer: Descobri o problema, era a classe table-responsive que envolve em um elemento de rolagem que conflita muito mal com o redimensionamento DataTable.
Então só remover linha:
 que resolve o problema.


Is it OK to keep guitars in a glass or plywood rack?

Question: I have a question about storage. I'm planning to build a rack like thing made out of plywood or glass to store my guitars. Yet, I'm curious to know whether my guitars will have an affect with the environmental conditions such as humidity, water vapor, light, etc... Please advice.
Thank you
Answer: Many folks keep some of their collectible guitars in display cases or guitar cabinets  that may have a glass front to allow viewing of the instrument. However these cases should have a built in humidity control system as it is vitally important to maintain the proper level of relative humidity for your guitars.
When storing guitars, one of the most important consideration is the environmental conditions that the guitar will be subject to during storage.  This would include extremes of temperature and most importantly, relative humidity.
This is particularly important with acoustic guitars who's body is solid wood (verses laminate or composite) or guitars with a solid wood top.  Solid body electric guitars and all laminate body acoustic guitars are not as sensitive to the environment as the solid wood acoustics, but will still be affected.
Wood is very susceptible to relative humidity (basically the amount of moisture in the air).  Too little humidity and the wood drys out and your guitar can develop any number of problems.  Conversely, if your guitar is exposed to conditions where there is too much moisture in the air, the wood can swell and cause different problems.  Here is a link Humidity and Guitars that tells you more about how humidity can affect an acoustic guitar and the optimal humidity range.
Many people choose to store their guitars in a hard-shell case with either a sound hole or in the case humidity control system.  However, if you have quite a few guitars, it might be practical to store them in a dedicated case or cabinet, as long as you have a way to control the temperature and relative humidity levels inside the case or cabinet.
If you can create a weather tight seal with weatherstripping and tightly closing doors, you could use some sponges in containers to provide humidity along with a hygrometer to monitor the humidity level and add or subtract water from the sponges as needed.
Or you could use a small electric humidifier with a built in hygrometer which you would set to maintain the humidity at your desired level (between 45% and 55%).  Of course you would need to be able to get the power cord into the case or cabinet.
If you don't want your guitar "rack" to be sealed, you may want to consider a room humidifier to maintain the optimal humidity level in the room where your guitar rack will reside.  Again, there are many models that will automatically maintain a pre-set humidity level.
Aside from taking steps to insure optimal relative humidity, you should also consider the location of your storage cabinet or rack or case.  It's best not to expose anything to direct sunlight that you don't want to fade over time.  If you live in a climate where there can be temperature extremes, you might not want to locate your storage unit on an outside wall.
One other consideration for security that I would keep in mind.  Guitars can be valuable and if a burglar ever breaks into my home looking for something to steal, my guitars are the last thing I want him to see.  You might want to locate the storage unit in a part of the home where it will be least likely to be found by burglars looking for valuables.
Finally, be sure your guitars are supported inside the case in a manner that does not put undue stress on the neck of the guitar.  You don't want any pressure in either direction that could warp the neck.  Store the guitars so that the necks are not touching anything or so that the guitar is suspended freely from the headstock - with no pressure on the neck itself. For long term storage, I would recommend loosening the strings as well.
Good luck with your storage unit!
Comment: @SahanDeSilva   It's fine to take your guitars out of the rack.  Just be sure that they are not exposed to extreme sudden changes in temperature, (don't take them out of a warm house into very cold outside unless they are in a good guitar case - then leave them in the case) and don't leave them in unfavorable conditions (humidity) for a long period of time.  How long the guitar can remain in a too dry or too wet environment depends on the degree of too dry or too wet and the type wood.  Generally unfavorable conditions can start affecting wood in as little as 6 hours.
Comment: @SahanDeSilva  If your rack is open to the atmosphere in the room and not sealed, you just need to worry about the climate conditions in the room where the rack and guitars are stored.  If you have a weather tight seal on the rack or storage case or cabinet, be sure not to leave the door open long as the controlled conditions inside the case/cabinet will change if you leave the door open.  Just like your refrigerator will get warm if you leave the door open.
Comment: Thank you very much for your info:. Still I need to know something. All the issues you have mentioned in your answer will happen only if I keep the guitars in the rack for a long time, right? What if I take the guitars out of the rack everyday or 4 / 5 times a week and clean both guitars and the rack? Sorry if I sound stupid, because I'm not that knowledgeable about the guitars and the environmental conditions.
Answer: Unless you are building a sealed case like a humidor, the construction material matters very little.  All you should concern yourself with is whether the structure can support the weight of your guitars (and then some).
Environmental considerations are addressed in this answer.


Problem with F minor 7 guitar chord

Question: I am having some problem with an E-shaped F minor 7th barre chord. No matter what I do, it seems impossible to barre 5 strings (and even if I manage somehow to do it, it's very shaky and not clean at all). Any advice what should I do?
Comment: Check out this question : http://music.stackexchange.com/q/1767/7222 . There are also a  lot of other questions addressing this on the site. Most likely either your barreing technique is bad or your fingers aren't strong enough yet as with practice and good technique you should be able to barre all 6 strings on any fret.
Comment: In addition to the above linked question, there are a few other questions specifically about F chords, like http://music.stackexchange.com/questions/22486/barre-chord-f-and-barre-chords-in-general?rq=1. I think we can call this a duplicate even though the Fm7 might be the hardest of all the F barre chords, the tips on being able to play it will be the same for all barre chords.
Comment: But I don't really have a problem with the regular F or even Fm. I got them and use them quite often now, without a problem. It's only a Fm7 that bothers me quite a lot. :/
Comment: The edit does nothing to make this question no longer a duplicate. The process you went through to get the major F and Fm chords down is the same process you can use for Fm7.
Answer: If you can successfully barre in other fret locations, then your difficulty may be related to the guitar setup -- specifically, the nut may be too high. As a beginner, I would let someone experienced inspect the instrument and offer their opinion.
Note that guitar setup involves a number of interrelated factors.
Comment: I have no problem with F barre or A shaped barres, even on 1st fret. Only this Fm7 and maaybe A shaped m7 and dom 7 Bb. Could this be because of the nut height?
Answer: I assume you're trying to do an E-shaped Fm7. You could try playing an f minor 7th somewhere else on your neck, e.g.
D-shape
4
4
5
3
x
x

A-shape
8
9
8
10
8
8

You could also try adding the 7th on the B string, instead of the D string.
1
4
1
3
3
1

Comment: @bah if there's a problem on fret 1 that you're not having elsewhere, definitely worth having someone take a look at the nut height.
Comment: Yes, I probably should have mentioned it's E-shape Fm7. I have no problem on other frets, just recently got it pretty stable on 2 fret. But 1 fret seems really hard. But I'd really like to get this regular E-shape Fm7 working.

Problem with F minor 7 guitar chord


pandas: MultiIndex Slicing - Mixing slices and lists

Question: I am attempting to use the (not really) new slicing operator in pandas, but there is something I am not quite getting.  Suppose I generate the following hierarchical dataframe:
#Generate container to hold component DFs
df_list=[]

#Generate names for third dimension positions
third_names=['front','middle','back']

#For three positions in the third dimension...
for lab in third_names:
    #...generate the corresponding section of raw data...
    d=DataFrame(np.random.uniform(size=20).reshape(4,5),columns='a b c d e'.split(' '))
    #...name the columns dimension...
    d.columns.name='dim1'
    #...generate second and third dims (to go in index)...
    d['dim2']=['one','two','three','four']
    d['dim3']=lab
    #...set index...
    d.set_index(['dim3','dim2'],inplace=True)
    #...and throw the DF in the container
    df_list.append(d)

#Concatenate component DFs together
d3=pd.concat(df_list)

d3_long=d3.stack().sortlevel(0)

print d3_long

Yields:
dim3    dim2   dim1
back    four   a       0.501184
               b       0.627202
               c       0.329643
               d       0.484261
               e       0.884803
        one    a       0.834231
               b       0.918897
               c       0.196537
               d       0.242109
               e       0.860124
        three  a       0.782651
               b       0.998361
               c       0.849685
               d       0.210377
               e       0.866776
        two    a       0.908422
               b       0.737073
               c       0.064402
               d       0.240718
               e       0.044409
front   four   a       0.100877
               b       0.963870
               c       0.254075
               d       0.126556
               e       0.033631
        one    a       0.243552
               b       0.999168
               c       0.752251
               d       0.684718
               e       0.353013
        three  a       0.938928
               b       0.112993
               c       0.615178
               d       0.430318
               e       0.330437
        two    a       0.301921
               b       0.645425
               c       0.464172
               d       0.824765
               e       0.606823
middle  four   a       0.814888
               b       0.228860
               c       0.333184
               d       0.622176
               e       0.151248
        one    a       0.547780
               b       0.592404
               c       0.684111
               d       0.885605
               e       0.601560
        three  a       0.340951
               b       0.839149
               c       0.800098
               d       0.663753
               e       0.215224
        two    a       0.138430
               b       0.917627
               c       0.342968
               d       0.406744
               e       0.822957
dtype: float64

I can get at the first two dimensions with behavior I expect...
print d3_long.loc[(slice('front','middle'),slice('two','four')),:]

Yields:
dim3    dim2   dim1
front   four   a       0.100877
               b       0.963870
               c       0.254075
               d       0.126556
               e       0.033631
        one    a       0.243552
               b       0.999168
               c       0.752251
               d       0.684718
               e       0.353013
        three  a       0.938928
               b       0.112993
               c       0.615178
               d       0.430318
               e       0.330437
        two    a       0.301921
               b       0.645425
               c       0.464172
               d       0.824765
               e       0.606823
middle  four   a       0.814888
               b       0.228860
               c       0.333184
               d       0.622176
               e       0.151248
        one    a       0.547780
               b       0.592404
               c       0.684111
               d       0.885605
               e       0.601560
        three  a       0.340951
               b       0.839149
               c       0.800098
               d       0.663753
               e       0.215224
        two    a       0.138430
               b       0.917627
               c       0.342968
               d       0.406744
               e       0.822957
dtype: float64

However, the following call yields the exact same result.
d3_long.loc[(slice('front','middle'),slice('two','four'),slice('b','d')),:]

It's like it's ignoring the third level of the MultiIndex.  And when I try to use a list construct to get specific locations...
d3_long.loc[(slice('front','middle'),slice('two','four'),['b','d']),:]

It yields a TypeError.  Any thoughts?
Answer: d3_long is actually a Series, so you don't need the last : in your slicer.  Note that your second level slice('two','four') doesn't select anything (it'd be equivalent to [-1:1]).
But if you reverse the order, it should give what you expect.
In [82]: d3_long.loc[slice('front','middle'),slice('four','two'), ['b','d']]
Out[82]:
dim3    dim2   dim1
front   four   b       0.301573
               d       0.478005
        one    b       0.306292
               d       0.281984
        three  b       0.108174
               d       0.776523
        two    b       0.028694
               d       0.527417
middle  four   b       0.285103
               d       0.647165
        one    b       0.807411
               d       0.309446
        three  b       0.277752
               d       0.939555
        two    b       0.470019
               d       0.447640
dtype: float64

Comment: I was so hung up on the error, I didn't even pay attention to the second level order.  This is useful, thanks.


Converter "-12.0000"(string) para -12.0000(double). É possível?

Question: É possível converter "-12.0000"(string) para -12.0000(double) ?
Segue código:
var valor = "-12.0000";
var result = Convert.ToDouble(valor, CultureInfo.InvariantCulture); //-12 <--- perde zeros

Ou se preferir .NET Fiddle: https://dotnetfiddle.net/RnFB1f
Comment: @MatheusMiranda Double é um tipo de dado que guarda valores, não formatação para exibição, ou seja, `12.00000000000000` é a mesma coisa que `12` apenas, os zeros são redundantes, eles por si só não são um valor e não são considerados. Isto que você quer pode ser alcançado com o ToString("0.0000"). Exemplo: `result.ToString("0.0000")` onde a variável result é double.
Comment: @MurariAlex é isso que o MurariAlex disse. Número segue regras matemáticas, texto é apenas desenho dos números que você monta como achar melhor.
Comment: Imagino que vá usar de outra forma, afinal neste código a conversão não é necessária a não ser para demonstração. Dependo de como for usar precisa ser bem diferente disto.
Comment: @Maniero É possível converter `"-12.0000"`(string) para  `-12.0000`(double) sem perder os "0000". ?
Answer: Você terá de passar o cultura para não perder os 0, ficará assim:
double longitude = double.Parse(text, CultureInfo.InvariantCulture);

O aconselhavel é sempre utilizar double para latitude e longitude.
Comment: Continua perdendo os "0".
Comment: Veja aqui: https://dotnetfiddle.net/RnFB1f


SysWOW64 access denied (Windows Server 2012 Standard)

Question: I am trying to call:
<code>[System.IO.File]::Delete($folder)
</code>
from the Powershell ISE (not ISEx86).
I am logged in as Domain User that is an Administrator on this machine to which I connect using RDP.
I have taken ownership over SysWOW64 folder and granted myself FullControl, for this folder, subfolders and files.
But I still get an "Access Denied" when executing the command above from the Powershell console, which runs under my account "Domain\Administrator".
<code>$xxx =  [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
Write-Host $xxx
$sr =  [Environment]::ExpandEnvironmentVariables("%SystemRoot%")
$sr = Join-Path -Path $sr -ChildPath "\SysWOW64\WindowsPowerShell\v1.0\Modules\"
$folder =  Join-Path -Path $sr -ChildPath "\xxx\Modules"
[System.IO.File]::Delete($folder)
</code>

Exception calling "Delete" with "1" argument(s): "Access to the path
  'C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\xxx\Modules' is
  denied." At C:\Users\Administrator.CONTOSO\Documents\Visual Studio
  2015\Projects\xxx.Powershell.Commandlets\xxx.Powershell.Commandlets\install-module.ps1:9
  char:1
  + [System.IO.File]::Delete($folder)
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : UnauthorizedAccessException

How can I get access?
Comment: OP is not good with computer.
Comment: Only people who really know what they're doing should be deleting system directories.  And before you say it, no, you don't qualify, as you weren't even aware that you were using the directory at the time you were trying to delete it.
Comment: Pretty sure that's off-topic here too.
Comment: On ServerFault we keep an air of professionalism not found on sites like StackOverflow.
Comment: Perhaps the [on-topic page for this site](http://serverfault.com/help/on-topic) would be of some interest to you. Helping end users delete directories from their computers isn't even close to what this site is about.
Comment: yes this is off-topic :-)
Comment: but deleting normal user comments is off topic too, the one above can be deleted, but why does a mod delete a normal user comment?
Comment: I had a simple question. So if Serverfault is not the right place for this question I would have appreciated a hint to post it in another forum.
Giving wrong answers is not professional in my opinion ;-) Better say, this is the wrong place for that kind of questions instead of deleting not offending user comments...
Comment: Hopeless to explain it to @HopelessN00b :D
Comment: I'll give up, have a nice evening @HopelessN00b. Goodbye Serverfault
Comment: The account may be a member of the Administrators group and have FullControl over it, but did you actually choose "Run as Administrator..." when launching ISE?
Comment: Yes, I am Administrator. It's indicated in the console title bar.
Comment: Is there a tool that i can run which spits out the necessary information about access rights for this folder. I could post the information here then...
Answer: Erm...  You can't delete active files like this.  You called a 64 bit powershell instance to delete a module for the 64bit shell.  Powershell preloads modules (but doesn't necessarily install them) which locks the module file.
Comment: I don't want to delete a module, the folder is called "Modules" somewhere below SysWOW64...
Comment: .. It is a folder I created with powershell console and now I want to delete the same empty folder with powershell again.
But I get an "Access Denied".
Comment: You didn't create it, it was there before you tried.  It's there with all 64bit installations.
Comment: `C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\` is a system leaf on 64bit windows systems for the 64bit Powershell.
Comment: That directory is integral to your question and the resolution.
Comment: $sr =  [Environment]::ExpandEnvironmentVariables("%SystemRoot%")
$sr = Join-Path -Path $sr -ChildPath "\SysWOW64\WindowsPowerShell\v1.0\Modules\"
$folder =  Join-Path -Path $sr -ChildPath "\xxx\Modules"

It's the Modules folder under xxx folder...
Comment: SysWOW64\WindowsPowerShell\v1.0\Modules is a system folder but I created subfolders xxx\Modules... Do you get it?

I dont want to delete the `SysWOW64\WindowsPowerShell\v1.0\Modules` folder


How to kick off a batch file on server restart?

Question: When the server restarts, I need to kick off a process in a form of a batch file (that basically preloads a bunch of data that will be needed later).
I haven't found an effective way to do this (other than write a Windows service).
Am I missing something simple?
Comment: Is this for 2003, or 2008?  I am almost certain the 2008 task manager can do it, not sure about 2003 though.
Answer: You want to use a startup script for this. The link provided is for a logon script, but the process is the same for a startup script. You just configure it in Computer Policies instead.
If you don't have Group Policy available, or don't want to manage it there, the steps are the same to configure this in the Local Policy.
You'll either use the Group Policy Management Console or the local gpedit.msc to configure this policy:
Answer: If it is Windows 2008, or 2008 R2, the task Scheduler has a trigger for "At startup".

If an earlier version of server, you may be able to use the HKLM/Software/Microsoft/Windows/Currentversion/Run key to launch a process (not recommended)


Lagrange multipliers with constraints

Question: I am trying to get the max and min of the function $f(x,y,z)$ and $h(x,y,z)$ is the constraint. I have done the below steps. Are the value of my points correct for $x,y,z$? If so how do I proceed to find the max and min.
$$f(x,y,z)=xyz$$
$$h(x,y,z)=x+y+z^2=5$$
$$f_x=h_x\lambda \implies yz=\lambda$$
$$f_y=h_y\lambda \implies xz=\lambda$$
$$f_z=h_z\lambda \implies xy=2z\lambda$$
$$\begin{cases} x=2,\\ y=2, \\z=\pm 1,-1. \end{cases}$$
Comment: what is $g$? clarify your notations concerning derivatives
Comment: sorry should be hx rather than gx
Comment: i found 2 points but there should be 6? is there an efficient way to find all points?
Answer: It looks like you've found the points correctly.  To find the maximum and minimum values of $f$ subject to the constraint, evaluate $f$ at these points:
$$f(2,2,1)=4$$
$$f(2,2,-1)=-4$$
So 4 is the maximum value and $-4$ the minimum.
Comment: i ran through a check at http://www.quickmath.com/webMathematica3/quickmath/equations/solve/advanced.jsp and found out that there are more points. can't seem to figure where did it went wrong
Comment: The system of equations does have some more solutions if you allow $\lambda=0$, but that will force two out of the other three variables to be zero, giving $f$ a value of 0, which lies between $-4$ and 4.

Lagrange multipliers with constraints


Dados não estão sendo gravados no BD por PHP

Question: Estou estudando PHP orientado a objetos e, a partir de alguns tutoriais retirados da net (pdo, pojo, Dao...), fiz um sistema bem simples no qual pego o valor inserido no <input type="text"> e gravo no banco de dados.
Aliás, deveria fazer isso. O grande problema é esse, não está gravando o registro. Coloquei um echo no html com a variável para ver se pelo menos estava pegando, e sim, está, mas no bd não grava...
É alguma coisa errada no meu arquivo de conexão ou classe? No momento eu acho que não estou instanciando certo o inserir, seria isso?
PS: Mais para frente quero armazenar o caminho de imagem ou vídeo, tipo um mini gerenciador de galeria de imagens por isso estou usando aquele foreach no teste.php
São os seguintes arquivos: conexao.php, classes.php, funcoes.php e teste.php.

conexao.php
class Conexao {
    public static $instance;
    private function __construct() {
        //
    }
    public static function getInstance() {
        if (!isset(self::$instance)) {
            self::$instance = new PDO('mysql:host=localhost;dbname=nomedobd', 'root', '',
 array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
            self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            self::$instance->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);
        }
        return self::$instance;
    }
}

classes.php
    class Imagem {

    private $id;
    private $nome;
    private $caminho;
    private $tipo_obj;

    public function getId_img() {
        return $this->id;
    }
    public function getNome_img() {
        return $this->nome;
    }
    public function getCaminho_img() {
       // return $this->caminho;
        return $this->caminho;
    }
    public function getTipo_obj() {
       // return $this->tipo_obj;
        return $this->tipo;
    }
    public function setNome($nome) {
        /* $this->id = $id_img;
        $this->nome = $nome_img;
        $this->caminho = $caminho_img;
        $this->tipo_obj = $tipo_obj; */
        $this->nome = $nome;
    }
    public function setCaminho($nome) {
        $this->caminho = $nome;
    }
    public function setTipo($nome) {
        $this->tipo = $nome;
    }

}

funcoes.php
    require_once "conexao.php";
require_once "geralog.php";
require_once "classes.php";

class DaoImagem {

    public static $instance;

    public function __construct() {
        //
    }
    function inputText($nome) {
            return "<input type='text' id='$nome' name='$nome' value='$nome' />";
    }
    public static function getInstance() {
        if (!isset(self::$instance))
            self::$instance = new DaoImagem();

        return self::$instance;
    }

    public function Inserir(Imagem $nome){
        try {
            $sql = "INSERT INTO imagem (
                tipo,
                nome,
                caminho)
                VALUES (
                :tipo,
                :nome,
                :caminho)";

            $p_sql = Conexao::getInstance()->prepare($sql);
            $p_sql->bindValue(":nome", $nome->getNome_img());
           // $p_sql->bindValue(":nome", $imagem->getNome_img());
            $p_sql->bindValue(":caminho", $nome->getNome_img());
           // $p_sql->bindValue(":caminho", $imagem->getCaminho_img());
            $p_sql->bindValue(":tipo", $nome->getNome_img());
           // $p_sql->bindValue(":tipo", $imagem->getTipo_obj());
            return $p_sql->execute();
        } catch (Exception $e) {
            print "Ocorreu um erro ao tentar executar esta ação, foi gerado
 um LOG do mesmo, tente novamente mais tarde.";
            GeraLog::getInstance()->inserirLog("Erro: Código: " . $e->getCode() . " Mensagem: " . $e->getMessage());
        }
    }

teste.php
        <?php

include_once('funcoes_imagem.php');

/* foreach ($_FILES["files"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["files"]["tmp_name"][$key];
        $name = $_FILES["files"]["name"][$key];
        move_uploaded_file($tmp_name, "public/$name");
    }
} */

?>
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Home</title>

        <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>" enctype='multipart/form-data'>
            <?php $nome = new DaoImagem(); ?>
            <?php echo $nome->inputText('nome',$_POST['nome']);?>
            <input type="submit" value="Enviar" />
        </form>
    <?php
        if(isset($_POST['nome'])){
            //$nome = new DaoImagem();
            $envia = new DaoImagem();
            //echo $_POST['nome'];
            print $envia->Inserir($nome);
        }
    ?>

Desde já, obrigado.
Último ajuste:
Catchable fatal error: Argument 1 passed to DaoImagem::Inserir() must be an instance of Imagem, instance of DaoImagem given, called in C:\wamp\www\SistemaUpload\teste2.php on line 34 and defined in C:\wamp\www\SistemaUpload\funcoes_imagem.php on line 25
Comment: Pra começar, altere o comando "SET nome utf8" para "SET NAMES utf8". Tem como colar pra gente a(s) mensagem(ns) de erro?
Comment: Opa, obrigado pela resposta. Tenho aqui o log de erro do php... linha 5 e 29 do teste2.php (teste.php no caso), que é no meu if e onde ele imprime o input na tela...
Comment: [18-Jan-2017 17:41:37 America/Sao_Paulo] PHP Notice:  Undefined variable: PHP_SELF in C:\wamp\www\SistemaUpload\teste2.php on line 27

[18-Jan-2017 17:41:37 America/Sao_Paulo] PHP Stack trace:

[18-Jan-2017 17:41:37 America/Sao_Paulo] PHP   1. {main}() C:\wamp\www\SistemaUpload\teste2.php:0

[18-Jan-2017 17:41:41 America/Sao_Paulo] PHP Notice:  Undefined variable: PHP_SELF in C:\wamp\www\SistemaUpload\teste2.php on line 27

[18-Jan-2017 17:41:41 America/Sao_Paulo] PHP Stack trace:

[18-Jan-2017 17:41:41 America/Sao_Paulo] PHP   1. {main}() C:\wamp\www\SistemaUpload\teste2.php:0
Answer: Para corrigir o erro que você mencionou no comentário, deixe o seu formulário da seguinte forma:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
       <?php $formulario = new DaoImagem(); ?>
       <?php echo $formulario->inputText('nome',$_POST['nome']);?>
       <input type="submit" value="Enviar" />
</form>
Depois, vi que você mencionou o parâmetro ':id_img' em sua string sql, mas não adicionou valor a ele com com bindValue(). Dê uma olhada nisso também.
Comment: Olá Luiz, obrigado pela resposta... O formulário ontem depois de postar vi que faltou o $_server[]... mas a sql já até mudei, pois como a id é PK e automatica, removi da string sql, ficando assim:
INSERT INTO imagem (tipo, nome,caminho) VALUES (:tipo,:nome,:caminho)
Answer: Finalmente consegui... depois de apanhar bastante, descobri que tinha uns erros no na classe funcoes_imagem e no teste precisava instanciar mais uma classe e definir os metodos... Vai aqui o resultado, talvez possa ajudar outras pessoas:
conexão.php (não foi alterado)

funcoes_imagem.php
    require_once "conexao.php";
    require_once "geralog.php";
    require_once "classes.php";

    class DaoImagem {

        public static $instance;

        public function __construct() {
            //
        }
        function inputText($nome) {
                return "<input type='text' id='$nome' name='$nome' value='$nome' />";
        }
        public static function getInstance() {
            if (!isset(self::$instance))
                self::$instance = new DaoImagem();

            return self::$instance;
        }

        public function Inserir(Imagem $nomeCerto){
            try {
                $sql = "INSERT INTO imagem (
                    tipo,
                    nome,
                    caminho)
                    VALUES (
                    :tipo,
                    :nome,
                    :caminho)";

                $p_sql = Conexao::getInstance()->prepare($sql);
                $p_sql->bindValue(":nome", $nomeCerto->getNome_img());
               // $p_sql->bindValue(":nome", $imagem->getNome_img());
                $p_sql->bindValue(":caminho", $nomeCerto->getNome_img());
               // $p_sql->bindValue(":caminho", $imagem->getCaminho_img());
                $p_sql->bindValue(":tipo", $nomeCerto->getNome_img());
               // $p_sql->bindValue(":tipo", $imagem->getTipo_obj());
                return $p_sql->execute();
            } catch (Exception $e) {
                print "Ocorreu um erro ao tentar executar esta ação, foi gerado
     um LOG do mesmo, tente novamente mais tarde.";
                GeraLog::getInstance()->inserirLog("Erro: Código: " . $e->getCode() . " Mensagem: " . $e->getMessage());
            }
        }

teste.php
<?php
include_once('funcoes_imagem.php');
?>
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Home</title>

        <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>" enctype='multipart/form-data'>
            <?php $nome = new DaoImagem(); ?>
            <?php //echo $nome->inputText('nome',$_POST['nome']);?>
            <input type="submit" value="Enviar" />
        </form>
    <?php
        if(isset($_POST['nome'])){
            $nomeCerto = new Imagem();
            $nomeCerto->setNome($_POST['nome']);
            //$nome = new DaoImagem();
            $envia = new DaoImagem();
            //echo $_POST['nome'];
            print $nome->Inserir($nomeCerto);
        }
    ?>


Display an integer in a view

Question: I am new to Giraffe and having difficulties displaying an integer. My model is
type Person =
    {
        FirstName   : string
        LastName    : string
        Age         : int
    }

And my view is:
let index2 (model : Person) =
    [
        partial()
        p [] [
            encodedText model.FirstName
            br []
            encodedText model.LastName
            br []
            int model.Age
        ]
    ] |> layout

The error message returned is "All elements of a list must be of the same type. So how do I display the age?
Answer: I am not quite familiar with Giraffe (rather Fable), so I do not know what to install and set to reproduce it.
Nevertheless, looking at p [] [ ... ], it is clear that the function requires a list as a second parameter and therefore all the elements there should be of the same type.
Let's look inside. As per GiraffeViewEngine.fs, encodedText returns Text which is a case in XmlNode DU:
type XmlNode =
    | ParentNode  of XmlElement * XmlNode list
    | VoidElement of XmlElement
    | Text        of string

So this sets the type for the whole list, XmlNode.
br function is defined as let br = voidTag "br" where voidTag function returns VoidElement which is another case in XmlNode DU, so it is fine.
And so I do not know what you wanted to say by int model.Age, and int is actually an operator in F# to convert object to integer. Anyways, it does not return anything of type XmlNode. Instead, try
p [] [
    encodedText model.FirstName
    br []
    encodedText model.LastName
    br []
    encodedText (string model.Age)
]

Thereby you will ToString the age, it will turn to Text case of XmlNode and the code should compile.

Display an integer in a view


Display batch filename on top of the execution window

Question: I have got 2 batch files, say A.bat and B.bat, which I need to keep open at the same time on my desktop.
When I open the batch file window, I see C:\Windows32\cmd.exe written on top of each window.
This really confuses me as to which window corresponds to which batch file.
Thus, is there a way I can display A on the window corresponding to A.bat and same for B?
I didn't get any cues on the web which brought me here.
Any assistance will be greatly appreciated.
Thanks
Comment: You could use the `title` command for this.
Answer: Make the first line of each .bat file read:
<code>@Title %~nx0
</code>


How should I control my voice while rapping?

Question: I am working on a drum 'n' bass song, and I'm planning on rapping for a few measures for effect. I'm terrible at singing and, since I write electronic music, have rarely recorded any samples that I later put into a song. So I have three questions:

How can I control my voice so that my rap is articulate and easy to understand?
What can I do stylistically to make my voice sound better? I haven't listened to much rap, so what kinds of sounds are usually considered enjoyable and how can I achieve them? Are there any songs I should listen to to get a good idea of what to do?
How should I record my voice? I have access to high-quality microphones.

In case you're interested, here are the lyrics. The song I'm writing is at 196 bpm, and I'm planning on rapping a line per measure at 98 bpm (in half time):

We've got a ticket to ride
A ticket to fast
Coming in second's
No better than last
A hundred miles
Above the ground
Moving a thousand times
The speed of sound
A million people watching
Taking bets, naming names
Guessing which one of us
Will win this wild game
And we're all driven by
The same intense thirst
But I already know
I'm gonna be first
Comment: I'm not sure I fully understand your question.  For number 1, if you enunciate, your words will be clear(current rap seems to prefer making all the words unintelligible though) For number 2, do you mean tone, effects, something else?  For number 3, if you have great mics, use them!
Comment: Don't underestimate the power of Spoken Word. Eg. [this Classic](http://www.youtube.com/watch?v=kbgKb4qSYLE) from Orson Welles with the Ray Charles Singers. Or that Gorillaz song with Dennis Hopper.
Answer:
It is not so much a matter of controlling your voice, but your ability to clearly articulate consonants and vowels.  This is largely controlled by your tongue's dexterity.  If you are rapping quickly, you will need to work on articulation at fast tempi.  Tongue twisters are a great way for developing agility.
Also, know your text so well that it is reflexive.  By being so intimate with it, you will not be concentrating on pronouncing the words, and instead be focusing on expressing the meaning that you are trying to convey.

You have answered your own question by asking it.  Any composer worth their weight in salt will tell you that if you looking for sounds to emulate, you MUST listen to music above all else — the sound will take care of itself.  If you want to know what's popular / enjoyable, follow the sounds that you find enjoyable and make your own sounds from those.

The microphone should be placed at your mouth, approximately the distance from you thumb-to-pinkie extended away from your mouth.  (Make a hand turkey with your thumb on your lips, and the microphone should touch your pinkie.)
Also, I would recommend a pop filter.
Answer: I believe you are talking about breath control. In short, some things you can do are to pay attention to the pitch of your voice while rapping. Monotone is bad- almost EVERY rapper varies his pitch from syllable to syllable (or word to word).
Vary your timing when rapping not according to the the words you are saying, but in response to the timing of the beat you are rapping to or in a set pattern. For example, switching back and forth from grouping syllables in twos and threes almost always helps. (Ex. Blah blah,   blah blah blah,    blah blah)
Practice rapping on an intake of breath as well as an exhale.
Have the beat (and/or vocal melody) worked out before the words and write the words TO the music, not vice versa.
Hope this helps!
Answer: Check that if you rap it without any rhythm/instruments in the background, you can at least pick up a rhythm from the syllables in the lyrics - ie that they imply a rhythm, or work with an implied one.
This depends on how it scans with the music, I guess. I don't think it's easy/possible to lay down rules about what works.
Rap with gaps between the lines starts to sound like you're pausing waiting to say the next line.
However this is quite subjective - it's just an indication of what soulds good to me. Maybe it's worth trying it out on a few people to get an opinon?
Example of a terrible (to my ears) rap (2:30) :

emphasis on the syllables (rhythm of the rapped words) is the same every line so it gets dull sounding quite quickly
rhythm of the rap doesn't really fit the song
on several lines the "conclusion" of the line is halfway through and the empasis is on some unimportant word (eg 'three lions ON my chest')
no real guts or mojo. (sorry John Barnes .. )

A much better rap (though I bet some rap enthusiasts will comment "that's awful, try this ..") - fair enough, it's subjective.

varied in rhythm
varies between 16-beat and 8-beat syllables
scans well and works with the rhythm of the song (which is more like the bpm you're going for)
not sure about the stuttery bit though lol
Answer: Pitch, tone, enunciation...don't matter in rap.  In fact they're often anathema.
What you need to pay very close attention to is PHRASING.  Your voice/rap is a rhythmic instrument, and in fact it's a good training exercise to actually think of your rap as if you're playing a drum set.  The rhythm does not have to be precise, but it absolutely has to be deliberate.


Remove the lines starting with a character in shell

Question: I have dataset as:
file.txt
de
fds
fds
a
sa
1
2
3
1
}

I would like to delete all the lines starting with characters or special characters. So my outfile is:
out.txt
1
2
3
1

I could do it manually with 'sed', but I am looking for a suitable command for this.
my code:
sed -i '/d//g' file.txt
sed -i '/f//g' file.txt
sed -i '/a//g' file.txt
sed -i '/s//g' file.txt
sed -i '/}//g' file.txt

Comment: Oops, you forgot to post your code! StackOverflow is about helping people fix their code. It's not a free coding service. Any code is better than no code at all. Meta-code, even, will demonstrate how you're thinking a program should work, even if you don't know how to write it.
Comment: Thanks @ghoti for pointing out this. I have added my code.
Comment: See: [The Stack Overflow Regular Expressions FAQ](http://stackoverflow.com/a/22944075/3776858)
Comment: `sed -n '/^[0-9]/p' file`
Answer: Use grep with -E option for regex (or egrep in short):
grep -E "^[0-9].*" file.txt

Comment: No need for the `-E` for this regular expression. It's a BRE in addition to ERE. Also, you might want to consider defaulting to single quotes except in cases where you know you need to quote variables. Just a general safety measure and good habit.
Comment: That's right, minimal answer would be "grep '^[0-9]' file.txt". However, I took the opportunity to show that grep could do more than that ;)
Comment: @R.Saban .. Would you please suggest me a modification of this script, if I need to preserve the negative values. I have asked this question here https://stackoverflow.com/questions/45006897/remove-the-lines-starting-with-a-character-in-shell-but-preserve-the-negative-v
Answer: just keep lines starting with a number:
$ sed -i.bak -r '/^[0-9]/!d' filename

or delete lines starting with specific characters:
$ sed -i.bak -r '/^[dfas}]/d' filename