Q:

How to submit WordCount.jar to hadoop via servlet

I now have a WordCount.jar stored in the linux local file system and a file containing a set of words stored in HDFS .
How can i run this WordCount.jar through a servlet and specify the input and output paths in the servlet.
    package org.apache.hadoop.examples;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

public class WordCount {

  public static class TokenizerMapper
       extends Mapper<Object, Text, Text, IntWritable>{

    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();

    public void map(Object key, Text value, Context context
                    ) throws IOException, InterruptedException {
      StringTokenizer itr = new StringTokenizer(value.toString());
      while (itr.hasMoreTokens()) {
        word.set(itr.nextToken());
        context.write(word, one);
      }
    }
  }

  public static class IntSumReducer
       extends Reducer<Text,IntWritable,Text,IntWritable> {
    private IntWritable result = new IntWritable();

    public void reduce(Text key, Iterable<IntWritable> values,
                       Context context
                       ) throws IOException, InterruptedException {
      int sum = 0;
      for (IntWritable val : values) {
        sum += val.get();
      }
      result.set(sum);
      context.write(key, result);
    }
  }

  public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();
    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
    if (otherArgs.length < 2) {
      System.err.println("Usage: wordcount <in> [<in>...] <out>");
      System.exit(2);
    }
    Job job = Job.getInstance(conf, "word count");
    job.setJarByClass(WordCount.class);
    job.setMapperClass(TokenizerMapper.class);
    job.setCombinerClass(IntSumReducer.class);
    job.setReducerClass(IntSumReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);
    for (int i = 0; i < otherArgs.length - 1; ++i) {
      FileInputFormat.addInputPath(job, new Path(otherArgs[i]));
    }
    FileOutputFormat.setOutputPath(job,
      new Path(otherArgs[otherArgs.length - 1]));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
  }
}

A:

Generally following steps

Put your wordcount class jar file to your server classpath as well as necessary hadoop client jar files
Specify the input and output dir as http request argument
Parse the dirs from http request in your servlet doGet() method
Use JobClient to submit your job


Q:

Selecting radio buttons to make text appear

Using radio buttons displayed on a panel, is it possible to select the radio button and then display some text on the panel explaining what the user has selected?
So here is a list of radio buttons
    public void RadioButtons() {
    btLdap = new JRadioButton ("Ldap");
    btLdap.setBounds(60,85,100,20);
    panelHolder.add(btLdap);

    btKerbegos = new JRadioButton ("Kerbegos");
    btKerbegos.setBounds(60,115,100,20);
    panelHolder.add(btKerbegos);

    btSpnego =new JRadioButton("Spnego");
    btSpnego.setBounds(60,145,100,20);
    panelHolder.add(btSpnego);

    btSaml2 = new JRadioButton("Saml2");
    btSaml2.setBounds(60,175,100,20);
    panelHolder.add(btSaml2);
}

User selects btLdap
btLdap.setSelected(true);

Now how do you make the text appear on the panel not a message box

A:

If you want to display a text when a radio button is selected you could use ActionListener.
final JTextArea textArea = new JTextArea();
add(textArea);

JRadioButton radioButton = new JRadioButton();
add(radioButton);
radioButton.addActionListener(new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        textArea.setText("Selected");
    }
});

JRadioButton radioButton2 = new JRadioButton();
add(radioButton2);
radioButton2.addActionListener(new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        textArea.setText("Selected 2");
    }
});

radioButton.setSelected(true);

When the first is selected it will change the text of the JTextArea with The first is selected!, same the second radio button but with The second is selected.
As you said, radioButton.setSelected(true); setSelected is used to select/deselect a radio button.
In this example i used textArea, but you can use everything which have a method to change the text it contains (an image too!)
Official DOC, here.

Anyway, actionPerformed is not called when setSelected is used so i would go to something like a method
private void updateText(int index)
{
    String text = null;

    switch (index)
    {
        case 0:
            text = "Selected";
            break;
        case 1:
            text = "Selected 2";
            break;
    }

    textArea.setText(text);
}

And then call updateText(0 or 1 etc.) when you want to select setSelected another radio button and update the text too.
All this is useful, if you want to show a "what happens if you press it" message, but if you just want to change the text of the area with the text of the radio button, just use
textArea.setText(e.getActionCommand());


Q:

Adding a new column with words extracted row by row

I would need to add per each column a new column which contains words satisfying the following condition:
df['Names'].str.extractall(r'\b([A-Z][a-z]*)\b')

i.e. words having letter capitalized.
The code above extract these words but for all the column, not distinguishing rows.
An example of data is
Names
My Lord: come le bande albanesi trafficano i g..
Viaggi di nozze 2020, i dieci eventi imperdibi..
Ma perché vi sto raccontando tutto questo, per Niente

The new column should be
Names
My Lord: come le bande albanesi trafficano i g..
Viaggi di nozze 2020, i dieci eventi imperdibi..
Ma perché vi sto raccontando tutto questo, per Niente

New
['My', 'Lord']
['Viaggi']
['Ma','Niente']

I think I should iterate over the rows. Could you please point me in the right direction?

A:

You can change to findall
df['My'] = df['Names'].str.findall(r'\b([A-Z][a-z]*)\b')


Q:

Isn't this answer link-only?

I have flagged this answer several times:

[Yes.][1]
This isn't the only method for doing it, but this is probably the most
  elegant method I've encountered.
[Here's another one.][2]

But moderators keep declining it. I've used to think that link-only answers don't add value to SO. I see this answer as a clear link-only, am I wrong?

A:

When you flagged it, what action would you have us take?
Delete it?
No. It conveys useful information (both of those links work and the first one is Gold).
Edit it to include the code to solve the issue?
There are 16 moderators.  Why is the onus on the moderator to edit a post that you can edit?
So while you may be right that it a link-only answer (sigh), it doesn't meet any of the criteria for deletion, and even if it did meet a single criteria for deletion, its deletion would make Stack Overflow a worse place because we're deleting useful content.
The answer has been flagged five times.  I'm surprised that none of the people elected to improve the answer.
Here are the results of those flags:
Nov 8 '13 at 15:34    User 1    not an answer                       Disputed
Nov 10 '13 at 1:46    User 2    invalid flags                       Disputed
Jan 13 at 9:01        User 3    (custom) it is very low quality     Helpful
Sep 1 at 18:19        User 4    (custom) it is a link-only answer   Helpful
3 mins ago            User 5    not an answer                       Declined

I've anonymized who flagged it, as well as the moderators that handled it; (and there may or may not be five different flaggers), but this tells you the breakdown of how the flags were handled.
Disputed means that the community did not agree.
"Helpful" but the answer sticking around means that the moderators thought the flagger flagged in Good faith, but elected not to take any action.
"Declined" means the moderator believes either the user acted in Bad Faith, or there was not a reason to mark it "Helpful".
I've edited the answer to include the completed CSS needed to make the answer more powerful.
If you see an answer that has a lot of upvotes that is comprised of just a link, there are many things you can do, flagging it should be the last resort.
You can:

Edit it
Leave a comment for the author
See if the answer's quality (or lack thereof) is a result of the question, and improve the question or vote to close it.
Flag the answer

Flagging is the nuclear option. Flags only result in one of two outcomes:

The content is deleted (bad if the links convey useful information)
Nothing.

Previously, previously, previously, previously, previously, previously, previously, previously, previously, previously, previously, previously, previously, previously, previously, previously, previously.


Q:

How do I highlight a particular word from a column inside a text using django?

So let's say I have 3 columns.
Text                          | Subject         | connector
Cancer is caused by windmills.| cancer, windmill| caused by
These are all saved inside a postgreSQL database. How do I highlight the words, cancer and windmill (from subject) and caused by (from connector), inside the text and display it on the webpage?
{% if db.cause and db.connector in db.text %}
{{ db.text }}

But this highlights the whole text instead of those 4 words cancer, windmill and caused by.
Update from @selcuk's suggestion:
in templatetags/filters.py:
@register.filter
def highlight(text, search):
    highlighted = text.replace(search, '{}'.format(search))
    return mark_safe(highlighted)

in page.html:
{% for db in context %}
  {% if db.cause and db.connector in db.text %}
  {% with cause=db.cause %}
  {{ db.text|highlight:cause }}
  {% endwith %}
  {% else %}
  {{ db.text }}
  {% endif %}

End result: Nothing is highlighted and no error messages.
Desired Output: Only Cancer, caused by and windmill to be highlighted

A:

Replace() has been changed to re.sub because replace() is unable to handle case insensitive words/characters.
In templatetags/filters.py:
from django import template
from django.utils.safestring import mark_safe
import re

register = template.Library()

@register.filter
def highlight(text, search):
    search = re.split((" "), search)

    for i in search:
        highlighted = re.sub(i, '{}'.format(i), text, flags=re.IGNORECASE)
        text = highlighted
    return mark_safe(text)


Q:

Ajax and CSRF protection

Without going into too much details I have a site which is 100% Ajax. All requests to the site (both GET and POST) are done via Ajax. Now I have to implement CSRF protection, and all the solutions I came across boil down to sending a CSRF token in the headers, but most of them get this token from either HTML or a cookie that came with the GET request.
Now as my site is 100% Ajax and it doesn't reload. I wonder if I could, before each POST request, make a GET request to the server to get token and then submit it in the headers along with the POST request, for example
Submit GET request to aaa.com/get-csrf-token to get the token and then submit that token along with the request in the headers, if someone from another site makes a GET request to aaa.com/get-csrf-token and the server returns a token, then as far as I know they are still not able to read that value.
As the token is generated on a per session basis, I can simply check that the submitted token is the same token I have in the memchache which is associated with that session.
Could someone tell me if this would work?

A:

Yes, you could do this.  This should be fine.  It is a reasonable defense against CSRF.
Do make sure that side-effecting actions can only happen via POSTs (never via  GET), and that all POSTs check for the presence of the token.  Also, make sure you generate the token as a cryptographically-strong pseudorandom number (e.g., using CryptGenRandom(), /dev/urandom, SecureRandom, or similar) and store it in session state.
I don't know if this has any benefit over, say, cookie double-submission -- but you could do it, and it should protect against CSRF successfully.


Q:

Stuck with a strange error: undefined method `user_profiles_path'

This error tells me - undefined method 'user_profiles_path', while my routes are like 'user_profile_path'. Profile is a singleton child resource of users. Not sure what is causing this error. The error is raised by <%= form_for [@user, @profile] do |f| %> in _form.html.erb.
Routes.rb:
devise_for :users, :path_names => { :sign_in => "login", :sign_up => "register" } do
   get "/login", :to => "devise/sessions#new"
   get "/register", :to => "devise/registrations#new"
   get "/logout", :to => "devise/sessions#destroy"
   get '/account' => 'devise/registrations#edit'
 end

  root :to => "questions#redirect_on_visit"

  match 'home', :to => "questions#index"

  resources :questions do
    resources :question_responses
  end

  resources :users do
    resource :profile
  end

_form.html.erb:
<%= form_for [@user, @profile] do |f| %>

 <%= f.error_messages %>

    <%= f.label :display_name, "Display Name" %>

    <%= f.text_field :display_name, :size => "43" %>

    <%= f.label :current_location, "Current Location" %>

    <%= f.text_field :current_location, :size => "43" %>

<%= f.label :nationality, "Nationality" %>

    <%= f.collection_select :nationality, Profile::NATIONALITY, :include_blank => true %>

<%= f.label :home_place, "Home Place" %>

    <%= f.collection_select :home_place, Profile::HOME_PLACE, :include_blank => true %>

<%= f.label :occupation, "Occupation" %>

    <%= f.collection_select :occupation, Profile::OCCUPATION, :include_blank => true %>

<%= f.label :interest, "Interests" %>

    <%= f.collection_select :interest, Profile::INTERESTS, :include_blank => true %>

<%= f.label :hobby, "Hobbies" %>

    <%= f.collection_select :hobby, Profile::HOBBIES, :include_blank => true %>

    <%= f.label :bio, "Short Bio" %>

    <%= f.text_area :bio, :size => "50x5" %>

    <%= f.submit "Create Profile" %>

<% end %>

profiles_controller.rb:
class ProfilesController < ApplicationController

  before_filter :find_user

  def new
    @profile = @user.build_profile
  end

  def edit

  end

  private

  def find_user
    @user = User.find(params[:user_id])
  end
end

application.html.erb:
<% if user_signed_in? %>
            <% if !current_user.try(:profile) %>
                Signed in as
<%= link_to current_user.email, new_user_profile_path(current_user.id) %>

            <% else %>
                Signed in as
<%= link_to current_user.email, edit_user_profile_path(current_user.id) %>

            <% end %>
            Not you? <%= link_to "Sign out", logout_path %>
        <% else %>
            <%= link_to "Sign up", new_user_registration_path %> or <%= link_to "Sign in", new_user_session_path %>
        <% end %>

Routes:
user_profile POST   /users/:user_id/profile(.:format)                             profiles#create
               new_user_profile GET    /users/:user_id/profile/new(.:format)                         profiles#new
              edit_user_profile GET    /users/:user_id/profile/edit(.:format)                        profiles#edit
                                GET    /users/:user_id/profile(.:format)                             profiles#show
                                PUT    /users/:user_id/profile(.:format)                             profiles#update
                                DELETE /users/:user_id/profile(.:format)

A:

Okay this error is a known bug as reported here: https://github.com/rails/rails/issues/1769
And I found the right way to specify URL.
form_for([@user, @profile], url: user_profile_path(@user))
Syntactically important to have braces and important that there is no space between form_for and parenthesis.


Q:

Invoke code-behind method when browser is closing

I need to find a way to intercept browser closing and invoke a metod to update a record with several information about logged user in DB. It's very important this record is updated when the user is logging-out or when he close the browser. Obviously when the user clicks 'Logout' I handle the update in the server-side event, but what if the user simply exit from browser?
Someone suggest to use the window.onbeforeunload event and make an asynchronous call to some WS or WebMethod to execute the code, but this doesn't convince me at all: the problem with onbeforeunload is that it shows a confirm prompt. I need to avoid this message and simply invoke the method.
So I'm wondering if there is a 'server-side' solution without using ajax or javascript.
For example... a way to trigger some event on session abandon or session clear, or some other way to solve this problem just working on code-behind...

A:

There is no way you could have a server-side solution to know something that happens in the client browser.


Q:

ООП Python. Индексация списка в методе класса

from copy import deepcopy

class Matrix:
    def __init__(self, m):
        self.matrix = deepcopy(m)

    def __add__(self, other):
        sumMatrix = []
        for i in range(len(self.matrix)):
            tempMatrix = []
            for x, y in zip(self.matrix[i], other[i]):
                tempMatrix.append(x + y)
            sumMatrix.append(tempMatrix)
        return sumMatrix

Необходимо реализовать класс Matrix. Он должен содержать:
1) Конструктор от списка списков. Гарантируется, что списки состоят из чисел, не пусты и все имеют одинаковый размер. Конструктор должен копировать содержимое списка списков, т. е. при изменении списков, от которых была сконструирована матрица, содержимое матрицы изменяться не должно.
2) метод add, принимающий вторую матрицу того же размера и возвращающий сумму матриц.
Вопрос: когда реализую метод add (нужно получить список сумм списков),
m1 = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
m2 = Matrix([[0, 1, 0], [20, 0, -1], [-1, -2, 0]])
print(m1 + m2)

то получаю ошибку, что класс 'Matrix' не индексируемый, хотя подается список списков по моей логике.
TypeError: 'Matrix' object does not support indexing

Подскажите пожалуйста в чем проблема и как ее решить?

A:

Замените
for x, y in zip(self.matrix[i], other[i]):

на
for x, y in zip(self.matrix[i], other.matrix[i]):

Т.к. other у вас - это тоже Matrix, а он сам по себе не является списком списков, он только содержит в себе этот список списков в атрибуте .matrix, и к этому атрибуту нужно обратиться явно.
Ну, либо можно реализовать дандер-метод __getitem__ и тогда ваш Matrix будет сам по себе уметь возвращать результат по индексу, но в рамках данной задачи в такой доработке мало смысла.
И, кстати, в текущем варианте у вас __add__ ничего не возвращает. Так что сложить-то он сложит, но этот результат никуда не попадает, и ваш принт напечатает None. Так что добавьте туда return.


Q:

SVN "PROPFIND request failed on..."

I was checking out a repository (say foo) from SVN while doing some other commits / updates. My server died and I was left with an incomplete checkout. Fine. The problem is when I go back to access the foo repository, but I am unable to. It just hangs forever.
So, I went to http://subversion.apache.org/faq.html#bdb-recovery and ran svnadmin recover. I received an error, so I ended up having to use db_recover and the command said it completed successfully.
Now when I try to access the repository, I am getting:
svn: PROPFIND request failed on '/foo'
svn: PROPFIND of '/foo': 500 Internal Server Error (https://svn.foobar.com)

Also, if I navigate to https://svn.foobar.com/foo I see:
<D:error>
<C:error/>
<m:human-readable errcode="160029">
Could not open the requested SVN filesystem
</m:human-readable>
</D:error>

Anyone have any thoughts?
Note: All other repositories work. It is just this one.

A:

Did you run 'svnadmin recover' as the user usually using the repository (e.g. apache account)?
If not the reason could be that some files are now owned by the user running 'svnadmin recover' leaving the apache account without rights to change the repository files.


Q:

urllib2 urlopen works very randomly

For some reasons this part where I fetch JSON data from following url will only works sometimes. And sometimes it will return 404 error, and complain about missing header attribute. It will work 100% of the time if I paste it onto a web browser. So I'm sure the link is not broken or something.
I get the following error in Python:
AttributeError: 'HTTPError' object has no attribute 'header'
What's the reason for this and can it be fixed?
Btw I removed API key since it is private.
try:
    url = "http://api.themoviedb.org/3/search/person?api_key=API-KEY&query=natalie+portman"
    header = { 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16' }
    req = urllib2.Request(url, None, header)
    f = urllib2.urlopen(req)
except urllib2.HTTPError, e:
    print e.code
    print e.msg
    print e.header
    print e.fp.read()

A:

As is documented here, you need to explicitly accept JSON. Just add the second line after the first.
req = urllib2.Request(url, None, header)
req.add_header('Accept', 'application/json')


Q:

How to insert soft return in LaTex?

I have one problem with my project. I want to insert soft return. If I insert \\ the text is not fully justified. Can I insert soft return like in MS Word?

I have no idea how to fully justify first line. I used \\ before 'It' word.

A:

I suspect that I'm missing something very important. If you want to make a document look like it was generated by MS Word, why employ (La)TeX? Much more straightforward to use MS Word, isn't it?
Using \linebreak "works" -- but at the high cost of making the paragraph look pitiful.

\documentclass[a4paper]{scrartcl}
\usepackage{newtxtext} % text font: Times Roman clone
\setlength\parindent{0pt} % just for this example
\begin{document}
normal spacing in paragraph:

\medskip
Mineral aerosol represents one of the largest mass fractions of the global aerosol. It consists of windblown soil and is produced mainly in the arid areas of our planet, in particular in the great deserts. Its annual production rate is estimated to be in the order of \dots

\bigskip
using \verb+\linebreak+ after first sentence:

\medskip
Mineral aerosol represents one of the largest mass fractions of the global aerosol. \linebreak It consists of windblown soil and is produced mainly in the arid areas of our planet, in particular in the great deserts. Its annual production rate is estimated to be in the order of \dots
\end{document}


Q:

Streaming live to co-hosts

I've recently started livestreaming, and during the test stream feedback was received that I tended to concentrate a fair amount on the game I was streaming, and not able to respond to commenters on the stream, despite my moderators' having a system to flag posts for my attention.
To resolve this, I started a Skype call with said moderators so they could participate in the stream too. However it was quickly noticed that their participation was limited to responding to comments and talking about the site that the stream was being hosted on (it's a YouTube stream embedded in my game site), because the stream output lags by about a minute.
To fix that, I started sharing my screen on Skype, thus allowing the moderators on call to see my screen and therefore the stream with much less delay. However, this started causing problems because it made the video stream lag for the viewers, and I had to stop the Skype video.
I'm using XSplit Broadcaster, and during real streams I will be streaming to YouTube as well as to a local recording. XSplit is perfectly capable of broadcasting to multiple sources (and my bandwidth easily allows it - I get a minimum of 16Mbit upload and the stream quality I'm sending is 4.5Mbit), however I'm wondering if there's any way I can provide a live stream to my moderators, so they can see what I'm seeing and participate properly in real(-ish)time.
Any advice on this would be much appreciated!

A:

You need your own stream server.  The problem with services like YouTube and Twitch.TV is that your stream has to go through a lot of processing and content distribution on their end before it goes out to viewers.  That processing takes time and results in lag.  You can send the exact same stream to your own stream server and have it directly related with far FAR less delay (sub-second to a couple seconds), but are limited to the capabilities of your stream server to meet demand.
I've only done this kind of thing with Windows Expression Encoder in the past using a Windows Media Streaming server which is pretty easy to use, but only works on WMV files and thus isn't really all that good of a modern solution for h.264 video in cross platform streams.  RED5 should theoretically be capable of relaying a stream for you and you could either set it up locally or preferably throw it up on a VPS somewhere that can do the relaying for you (as 16mbit will get consumed really fast sending a 4.5mbps stream to multiple people).
Streaming is unfortunately not particularly easy to get setup and going for yourself though and that is a big part of why services that simplify it, like Youtube and Twitch.TV, are so popular despite their massive lag times.


Q:

Understanding of for loop and function c++

Running on Visual Studio 2015 Community edition
Actually i am revising the concept of c++ in which i came accross an error while calling a function. For example:
string GetGuessAndPrintBack() {

    string Guess = "";
    cout << "Enter your Guess Here ";
    getline(cin, Guess);    //taking input from user
    cout << "Your Guess is " << Guess << endl;    //repeating back the user input
    return Guess;
}

int main()
{
    constexpr int NO_OF_TURN = 5;
    for (int i = 0; i < NO_OF_TURN; i++) {
        GetGuessAndPrintBack();
        cout << endl;
    }
    return 0;
}

It asks the user to guess according to NO_OF_TURN. But when the for-loop is defined in the function/Method GetGuessAndPrintBack() such as:
string GetGuessAndPrintBack()
{
    constexpr int NO_OF_TURN = 5;
    for (int i = 0; i < NO_OF_TURN; i++) {
        string Guess = "";
        cout << "Enter your Guess Here ";
        getline(cin, Guess);      //taking input from user
        cout << "Your Guess is " << Guess << endl;       //repeating back the user input
        return Guess;
    }
}

int main()
{
    GetGuessAndPrintBack();
    cout << endl;
    return 0;
}

It asks for the guess only one time.

A:

It asks for the guess only once because you have the return Guess statement inside the for loop. At the first iteration of the for-loop, the return statement is executed and the GetGuessAndPrintBack() function is terminated.
The return Guess statement should be outside the for-loop statement.


Q:

For Safety's Sake, how do you answer an electrical question?

TL;DR There's probably something better you could do for the next half hour then read this.

Should they all begin with a pretext warning?
Should the OP's perceived ability tailor your context?

New user just asked a question for (a somewhat bad) example, and doesn't really sound like they should be poking around inside a breaker box. Where as, if someone spits out correct jargon I'd be inclined to just comment: Are you getting 220? (as I think they lost one of the incoming legs during a storm, but just blurting that out might not be the best idea to suggest as they might go sticking a VO meter into it, incorrectly)

(coherency from here on is suspect; it has become a dualistic question asking many ways to avoid giving poor advice and the diving-into of questions that for whatever reason, you shouldn't be. You have been warned)
I used to try to answer these questions but I couldn't deal with the fact of the possible ramifications of my answers. I know how to do... stuff. But most anything I know how to do was shown to me; not an online, bulleted blog: Ok, step one hold screwdriver in left hand... (erm, but I'm right handed)
Being given the steps to solve a problem is hardly the knowledge necessary to safely complete any electrical project.
Some questions sound like: Oh man, you really shouldn't be doing, what it is that you're doing.

Should I continue to ignore electrical questions even though I may have some sound advice, trusting in SE that if it is bad, it will be vetted by the system (even though, that still wouldn't make me anymore comfortable answering)?

It may be that I don't trust my self to answer them first, sometimes even when it's pretty obvious what what they need to hear. (but sometimes it isn't and then begins the epic comments session, see below) The meta behind this being, what's to tell the difference between a valid question that's deserving of an answer, and someone that you shouldn't give one to.
For this I have a good example: I was helping diagnose hooking up new thermostat wires inside a furnace, where I then asked if they put the cover back on when they tried testing it. Of course that's because the panel closes the safety switch or it won't work. They figured this out themselves eventually, but it was information I was unwilling to give; not to keep trade secrets, but because if you didn't know, or couldn't figure it out; should you know?

Or is it of course (as always), on a case by case basis
But if that's true, doesn't it not matter what their 'case' is; SE is for the greater community at large. That information will be there for anyone at least smart enough to ask how.

Maybe I'm just paranoid. Or maybe this is some real world shit that can get you killed.
Simply put, on trouble-shooting questions especially, I'd guess we'd have to first establish the OP's comfort level, and then provide each necessary step for them. (and then whatever future readers do with this information is up to those people?)
Perhaps I've digressed... (Ya think?) Having basically answered my own question with one of my own mottoes: If you don't know, don't answer. So, one last try if you're still looking for a question somewhere in all this to possibly answer:

What is a good method to access the OP's comfort level and avoid getting into a gigantic-comment exchange? (and the other thing, see below)

If I've rambled on into drivel, I apologize. Please feel free to poke holes in any of my logic or simply answer with, Yea dude, just go on to the next one. Or any pro-tips on ... well, frankly, everybody waking up tomorrow after reading one of my answers?
 I think, some of this may be a valid concern that may be pertinent to other SE sites. Replace the word 'electric' with whatever that may be, and post any part of it, altering it however, and wherever you want. Or please feel inclined to post similar topics on your other sites, For Safety's Sake.
Because, as I was once told here in my early days on DiY.se, Sometimes the best answer is no.

A:

I can't answer for you, but I can tell you how I try to handle this. First, I try to answer questions at the same level of detail that they were asked. For example. If the OP asks a very general broad question, I provide a broad high level answer.  I don't give enough detail for them to take action on it, so it's not likely they start poking around with a meter without seeking more advice.
Next I use technical jargon, to try and confuse out the folks that shouldn't be poking around.  I've been criticized by folks for not using the "common" terms, but I do so for a reason.  If you know enough to follow my answers, you're probably at the level where you're not going to kill yourself. If you don't, you'll likely follow up with additional questions or ask questions in the comments.
This is where another strategy comes in. If the OP reads my answer, and comes back with a comment that shows they're not qualified to be do the work. I'll tell them that they should contact a pro, or get some help.
You can also try to use the terms folks use to try and gauge their competency. For instance, if the OP refers to the grounded conductor as "commmon". I assume they may have a background in DC, or they've spent time on the wrong forums.  Other terms can also give you some hints, "110", "220", "GFI". These terms tell me that either the OP is old school, or they've been poking around forums.
All in all, it's about trying to gauge the OPs level of knowledge, and provide information at their level. And NEVER be afraid to tell somebody to get professional help (from an Electrician, not a psychiatrist).

A:

Again, as tester says - I can only tell you what I do.
I try to never write aggressively in answer to a question. People are here wanting to learn. I also will work very hard to understand what the person is asking, which does not always the words that went down on the paper.
I have worked in a number of countries where were people who were using english as a 2nd or 3rd language. If they are kind enough to speak english to me, when I am a guest in their country, and their native language is russian, I will work hard to figure out what is being said.
If someone is going off the deep end, I will try to divert. I have said things like 'what can I do to convince you not to try this'. I will try to push the safety issue instead of preaching that the CODE is an absolute, anyone with a few years in construction or maintenance has done things that were not to code.
Foolish is one thing, but I know that there are wire nuts out there that should have been red, and I used yellow. I still sleep at night
If the question asks for code quotes, then I will respond that way. If the question or comment spins on single word, used in a certain context, I will correct it if there is any way to do it.
I will try to answer comments with less hostility than the original. Maybe there is something hidden in rude words that will allow me to learn, or teach.
I worked as an electrician in the commercial / residential end of the world for a few years. I do not have a License for electrical work.
My vast experience is in the Entertainment Industry - an odd beast at best. Theater, Film, Television, Trade Shows, Cruise Ships all have quirks, some good, some bad. The number of things that someone will call a 'code violation' or as being 'against code' are just fine.
When something is only going to be in 1 city for 3 days, the word 'temporary' allows things that would make a building inspector faint. 20 cables 500' long of 4/0 loaded to 400 Amps with a connector every 100' that is big enough to insert a finger. Where the access to the general public is a piece of black cloth. Just not a big problem. In Times Square it would also require a 3' portable barrier.
So I try to be open to circumstances not being exactly as described.
If the most obvious answer to the question is found on the first page of a google search. I would rather give someone the information correctly here, and offer a few words to better explain. If one of the first 10 links in google will give the answer a person wants, something like 'Sure, no problem', and here the only answer given is 'call a professional - you could kill yourself.'
I will answer the question with, Yes, but here is why you really want to spend the money. There might be a chance the person understands why, rather than thinking one guy says call a pro, and the other yeah, go ahead and do it. I think it is better that I take the middle road.
I enjoy teaching, that is part of the idea behind stack exchange, take time to explain things to others. My degree in strong in physics. Science is so damn coo;, information is power and all that stuff. Someone taught me what I know, or gave me the chance to learn, I have this in mind in my answers.
The concept of using some jargon makes sense. My thought is that this is not the only place someone is looking for answers, how will the first page of links on google answer going to tell me about some technical term. I know a few cases where the same name is used for different things depending on if you learned the term on the East coast or the West coast.
I will openly debate or correct even those I think are wrong, no matter what their points score. Annoying to have your score voted down, because someone read what they wanted to read, and not the words you wrote, but if that is the worst that happens on any given day, life is good.
I also write too many words, so I try to give a short answer, and say I explain completely down below. :)
And then I explain below.
Oddest thing I have learned, an extension cord, with the female end cut off, is still and extension cord, and distinctly different from a male plug assembeled onto a pieece of the same type of cable. I am still working on figuring out the difference, if you know, please pass the information along.


Q:

get datagridview cell value on first index changing

I have a datagridview (dgv) and set some shortcut for it. I want to get my desired cell value when dgv selectedIndexChanged .
this is what I've done for selectedIndexChanged event:
if (dgv.Rows.Count > 0)
{
      lblId.Text = dgv.CurrentRow.Cells[0].Value.ToString();
      lblStaffName.Text = dgv.CurrentRow.Cells[1].Value.ToString();
      lblStock.Text = dgv.CurrentRow.Cells[4].Value.ToString();
}

and defined some shortcut for my dgv.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
  if (keyData == (Keys.Alt | Keys.Down))
   {
      if (dgv.Rows.Count > 0)
       {
          dgv.Focus();
          if (dgv.CurrentRow.Index < (dgv.Rows.Count - 1))
            {
                dgv.Rows[dgv.CurrentRow.Index + 1].Selected = true;
                dgv.FirstDisplayedScrollingRowIndex = dgv.CurrentRow.Index + 1;
                pnl.BackColor = Color.FromKnownColor(KnownColor.Lime);
            }
        }
     }
}

NOTE: as you can see, when I press Alt+keyDown dgv index will increase and change to one step more.
My problem is when I pressed Alt+keyDown the index change and selected as well but the value won't get new value until I press again Alt+keyDown twice!
Is there any event that I must writing code in there? thanks :)

A:

To change the selected index in a data-bound DataGridView it's better to rely on the binding context this way:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == (Keys.Alt | Keys.Down))
    {
        var bc = dgv.BindingContext[dgv.DataSource, dgv.DataMember];
        if (bc.Position < bc.Count - 1)
            bc.Position++;
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}

But if the DataGridView is not data-bound or just for learning purpose you want to fix your code, you can write such code:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == (Keys.Alt | Keys.Down))
    {
        if (dgv.CurrentCell == null)
        {
            if (dgv.ColumnCount >= 1 && dgv.RowCount >= 1)
            {
                dgv.CurrentCell = dgv[0, 0];
                return true;
            }
        }
        else
        {
            var rowIndex = dgv.CurrentCell.RowIndex;
            var columnIndex = dgv.CurrentCell.ColumnIndex;
            if (rowIndex < dgv.RowCount - 1)
            {
                dgv.CurrentCell = dgv[columnIndex, rowIndex + 1];
                return true;
            }
        }
    }
    return base.ProcessCmdKey(ref msg, keyData);
}

I also removed dgv.Focus() because when you use shortcuts to navigate between rows, you don't need focus, but if you need it for any reason, use it.


Q:

Just what is an IntPtr exactly?

Through using IntelliSense and looking at other people's code, I have come across this IntPtr type; every time it has needed to be used I have simply put null or IntPtr.Zero and found most functions to work. What exactly is it and when/why is it used?

A:

It's a "native (platform-specific) size integer." It's internally represented as void* but exposed as an integer. You can use it whenever you need to store an unmanaged pointer and don't want to use unsafe code. IntPtr.Zero is effectively NULL (a null pointer).

A:

It's a value type large enough to store a memory address as used in native or unsafe code, but not directly usable as a memory address in safe managed code.
You can use IntPtr.Size to find out whether you're running in a 32-bit or 64-bit process, as it will be 4 or 8 bytes respectively.

A:

Here's an example:
I'm writing a C# program that interfaces with a high speed camera. The camera has its own driver that acquires images and loads them into the computer's memory for me automatically.
So when I'm ready to bring the latest image into my program to work with, the camera driver provides me with an IntPtr to where to image is ALREADY stored in physical memory, so I don't have to waste time/resources creating another block of memory to store an image that's in memory already. The IntPtr just shows me where the image already is.


Q:

unrequested permissions not declared in androidmanifest--crashlytics maybe?

I've just noticed that my app has new permission requests that I have not explicitly declared in my AndroidManifest.xml. I didn't see these declared in any of the manifests in the
"intermediates" directory created by gradle, and the only dependency that I declare without an explicit version is crashlytics (as they suggest to do), i.e:
compile 'com.crashlytics.android:crashlytics:1.+'
The new permissions found in the full manifest are:
<android:uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        android:maxSdkVersion="18" />
    <android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <android:uses-permission
        android:name="android.permission.READ_EXTERNAL_STORAGE"
        android:maxSdkVersion="18" />

So what my guess is that whatever new version of crashlytics is now requesting this?

A:

If you're using Gradle to build, you can add the following to your AndroidManifest.xml to remove the permission:
    <uses-permission android:name="android.permission.READ_PHONE_STATE" tools:node="remove" />


Q:

Only execute function when screen size is above 992

When I scroll down the bigger image disappears and the smaller image appears. However when I use this on a smaller screen it's crab so I want it to only work for screens that are above 992px.
I want the function to only be active when people have a resolution of 992px or above. I have no clue how to that.
$(window).resize(function() {
  if ($(this).width() > 992) {
    $(window).scroll(function() {
      if ($(window).scrollTop() < 20) {
        $('.navbar-brand').stop(true, true).fadeIn("slow");
        $('.image-scroll').css('display', 'None');
      } else {
        $('.navbar-brand').stop(true, true).fadeOut("slow");
        $('.image-scroll').css('display', 'block');
      }
    });
  }
});

A:

While you want to execute the function on window resize and scroll .. it'll be better to create a function .. you need to put the if statement inside an event not the event inside the if
$(document).ready(function(){
  $(window).on('scroll resize' , Scroll_Action)
});

function Scroll_Action(){
    if($(window).scrollTop() < 20 && $(window).width() > 992){
        $('.navbar-brand').stop(true,true).fadeIn("slow");
        $('.image-scroll').css('display', 'None');
    } else {
        $('.navbar-brand').stop(true,true).fadeOut("slow");
        $('.image-scroll').css('display', 'block');
    }
}


Q:

Test-path checking for access with powershell

I am trying to find out who on my network has Access installed. I have had several problems getting the list to work correctly, so I have used the output txt file.  Anyway even if it's not a great way to do this it should still work.  Can anyone tell me why this is not working?
$Computers = Get-QADComputer | select name | Out-File "c:\access_search.txt"
$Computers = Get-Content "c:\access_search.txt"
$Path = "\c$\Program Files\Microsoft Office\Office12\Access.pip"
$AccessPath = "\\" + $PCName + $Path
Foreach ($PCname in $Computers){
$Result = Test-Path $AccessPath
if ($Result -eq "True")
{$Pcname}
}

A:

You're not testing the correct path since it's being assigned prior to the foreach loop where you define $PCname.  This means that you're testing the path \\\c$\Program Files\Microsoft Office\Office12\Access.pip every time.
Try this:
$Computers = Get-QADComputer | select name | Out-File "c:\access_search.txt"
$Computers = Get-Content "c:\access_search.txt"
$Path = "\c$\Program Files\Microsoft Office\Office12\Access.pip"
Foreach ($PCname in $Computers){
    $AccessPath = "\\" + $PCName + $Path
    $Result = Test-Path $AccessPath
    if ($Result -eq "True")
        {$Pcname}
}


Q:

Detecting user-activity on mac os x

I use the function "IOPMSchedulePowerEvent" to schedule Sleep or Wake-Events and registered my daemon with "IORegisterForSystemPower" to receive power-state-changes. Everything works fine!
When system going sleep and later waking up at scheduled time, my daemon do some work, and after it system should going sleep again.
Now my questions:

How can i detect, if the system was awaked by user or by the scheduled time?
How can i detect, if a user currently working with the system, so the daemon have not to put it in sleep-mode???

Thanks
Nobik

A:

There's an easy way to detect various forms of user interaction: Using CGEventSourceCounterForEventType you can query the number of keyboard presses or mouse moves since boot time. By doing this at regular intervals and comparing the counts, you can detect interaction.


Q:

Hover transitional delay with sequential message

What I'm trying to achieve is a fake loading message as the user hovers over the div before it shows the actual div content.
.info {  opacity: 0; width: 200px; height: 300px;transition-duration: 0.3s; transition-delay: 2s;  margin-top: -20px; background-color: #000;}

.info:hover { opacity: 1; transition-duration: 0.3s; transition-delay: 2s; }

.access {opacity: 0.0;  transition-duration: 0.3s; transition-delay: 0.5s; background-color: #000; color: #fff}
.access:hover { opacity: 1;  transition-duration: 0.3s; transition-delay: 0.5s;  }

http://jsfiddle.net/499hM/
As you can see, the message appears and then the div but the message reappears over the top of the div and fades it out - I want the message to disappear once the div has "loaded". I'm hoping this can be achieved through CSS alone?

A:

you canuse the adjacent selector and set 2 transitions on 2 different child of your boxe.
the .loading message first in flow, once hovered shows up and the next child (+ .infos) will show up on top of it a little while after. from there, the .infos takes over the :hover to keep on top.
DEMO:
http://codepen.io/gc-nomade/pen/jilLp

    loading ...

    Infos

div {
  border:solid;
  width:200px;
  height:200px;
  border:gray solid 5px;
  margin:auto;
  text-align:center;
  position:relative;
}
.loading , .infos{
  position:absolute;
  top:0;
  left:0;
  margin:0;
  height:100%;
  width:100%;
  line-height:200px;
  background:black;
  color:white;
  z-index:5;
  opacity:0;
}
.infos {
  z-index:0;
  background:yellow;
  line-height:1.2em;;
  color:red;
}
.loading:hover {
  opacity:1;
}
.loading:hover + .infos, .infos:hover {
  opacity:1;
  transition:2s 1s;
  z-index:10;
}


Q:

C# settings GUI

I wrote my first C# program a while ago. It got somewhat big. My .settings file has over 20 different parameters - booleans, sizes, strings, ints. I'd like to provide users with a GUI to change them during runtime instead of editing the app.exe.config file which is somewhat advanced and confusing.
I'm very inexperienced with C# but seems like there should be a better way than for me to manually create a form, drag in labels, inputs, checkboxes, radio buttons, and manually handle all gui events and what happens when values get changed and whatnot. Building this gui by hand seems like a lot of work.
How do you guys handle the settings of a C# app? Can't I generate something from the XML?

A:

In WinForms applications you can add a control to a Form and then click the (PropertyBinding) under (ApplicationSettings) in the Property box.
The dialog allows you to bind properties of the control to a parameter in the config file. It is an extra step during design but it must be done.
These settings will end up in the user config file (I strongly advise against the application config file for this)
You will have to provide the user with a way to specify these settings by either:

having the user edit the config file - very dangerous because it is very easy to mess that up.
allowing the user to manipulate the UI (drag-drop) and save the settings from code. - a lot of work to prevent the user painting himself in a corner.
a separate/standalone designer application that combines 1. and 2.


Q:

insert key$ and $value to database form foreach

I am trying to insert data of key and value from foreach. But I am getting error saying- Notice: Array to string conversion in…..(line number 22)
but I have checked both $key and $value using var_dump and found the array values are perfect. Then whats the solution to insert this $key $value data at a time to my database? also please note when i run it, the $key value is inserting successfully in db but $value value field is getting blink and getting same error in browser. you can check my db table in attached picture if required
foreach ($_POST['qty'] as $key => $value) {
 mysqli_query($conn, "INSERT INTO combine (rand_id,product_id,product_qty)VALUES('$rand_id','$key','$value')");
}

A:

As per your array and error message $value is not a string, its an array, you can get the value from $value by using one more foreach().
Example:
foreach ($_POST['qty'] as $key => $value) {
  foreach ($value as $finalVal) {
    $include[] = "('$rand_id','$key','$finalVal')";
  }
}
$values = implode(",", $include);

$query = "INSERT INTO combine (rand_id,product_id,product_qty) VALUES $values";

Also note that, you can INSERT values in one single query as given example. Store all values in an array and than implode() with comma.
In last, your code is open for SQL Injection, you need to prevent your code. You can follow this post: How can I prevent SQL injection in PHP? Yes Prepared Statements & Parameterized Queries is the best option for preventing.


Q:

How to find the common root of a sequence of strings recursively?

I want to be able to read in a sequence of strings and return the common stem of the strings. For example, if I had the following sequence:
val testSeq: Seq[String] = Seq("RootA_", "RootB_", "RootC_")

Then only the string "Root" should be returned.
My current function looks like this but using intersect means that the unwanted "_" is returned as part of the root, i.e. "Root_". I tried using takeWhile but was unsuccessful.
def findRoot(ss: Seq[String], root: String): String = ss match {
  case h :: Nil => h.intersect(root)
  case h :: t => findRoot(t, h.intersect(t.head))
}

If there's a built in Scala method for this could you please let me know! Otherwise if anyone wants to have a crack at solving this one it would be much appreciated!

A:

As far as I know, there is no scala stdlib function returning common prefix of two strings.
You can calculate common prefix using zip and takeWhile
def findRoot(seq: Seq[String]): String = {

    def prefix(a: String, b: String) = a
        .zip(b)
        .takeWhile { case (a, b) => a == b }
        .map(_._1)
        .mkString

    @tailrec
    def find(ss: Seq[String], root: String): String = ss match {
        case h :: Nil => prefix(h, root)
        case h :: t => find(t, prefix(h, root))
    }

    find(seq.tail, seq.head)

}


Q:

Confused with the DLL. No .lib or .h

I currently have a C# project that uses a 32 bit dll. What I am trying to do is to use the dll in a C++ project , unfortunately the dll referenced in the project does not come with a .h or .lib file so I am confused on how I could access the classes in the dll or use the dll file in my project in C++ (Visual Studio 2010) . I read here that if a dll file contains classes its a good chance it might be a COM component.Any suggestions on what I should be looking at in order to integrate and consume methods and objects in that dll.
Update:
I checked if it was a COM by doing an import statement. However I get a "cannot find .tlb file". Then I decided to use dependency walker to check for any exported methods (objects)it seems there are none. I clicked on the main file (which has been highlighted) and couldn't see any exported functions. Any hints on what I should check for next ?. Here is what I get from dependency walker.

A:

With only a .dll and without a corresponding .h or .exp, one place that you might try looking would be the exports table.  Tools such as Dependency Walker can show you this information.
One caveat with Dependency Walker is that you'll want to use the right version (x86 or x86_64) for the binary (your DLL).  If you're not sure, pick one version and try loading it.  Under the CPU column, middle panel, look to see if it says "x64" or "x86" to determine which one you should be using.
With the provided screenshot of Dependency Walker (indicating a dependency on MSCOREE.DLL), I agree with Eugene - this is most likely a .NET library, not a COM library.  You will want to check one of the other questions about calling .NET managed code from C/C++.


Q:

How to create a split button in Ant Design?

We need to implement a split button in Ant Design React UI. It already provides Button component which doesn't support splitting. It also has Dropdown that can split button as shown in example - https://codesandbox.io/s/cool-brahmagupta-us4kv
The problem of this implementation is that the dropdown will be closed if you click on it. This is OK for menu, but we need to put a more complex form there. It should be closed when you click outside of the dropdown, but not when you click inside.
Is this possible with Ant Design?

A:

The desired behavior is best achievable with Tooltip, with it you can render any custom component.
By design, DropDown should render a Menu and not a custom component like you did as it accepts a Menu type according to docs.


Q:

Multiplying two one-dimensional arrays

A quick question that bugs me (both from a mathematical perspective and implementation-wise). How do you multiply two one-dimensional arrays?
If we have:
int[] a = {1,2,3};
int[] b = {4,5,6};

And we wanna put the result into a variable c, how do you do the math and the implementation? Should c also be one-dimensional or two-dimensional?
Thank you in advance!
EDIT:
To everyone asking what I want. I'm trying to solve a math problem that literally tells me:
a = {1,2,3};
b = {4,5,6};

c = a * b; //what is c?

I found nothing on the internet on how to do it mathematically and I am equally puzzled on how to do it in a programming language.

A:

I'm not sure if you are trying to find the sum if everything, or trying to create a matrix with the multiplication.
For sum refer to duffymo's answer.
For a new array, the end product will be:
int[][] c= {{4, 8, 12}, {5, 10, 15}, {6, 12, 18}};
Idea: You can just loop through both of them and multiply each index. Then store the products in int[][] c. You can also just have them in a list depending on your implementation like so: c = {4, 8, 12, 5, 10, 15, 6, 12, 18}.
int[][] c = new int[a.length][b.length];
// int[] c = new int[a.length * b.length];
for(int i = 0; i < a.length; i++){
    for(int j = 0; j < b.length; b++){
        c[i][j] = a[i] * b[j];
        // c[i * a.length + j] = a[i] * b[j]; if you want to store it in a 1D array
        // Try a few examples to see why this will work for 1D array
    }
}


Q:

Skipping Incompatible Libraries at compile

When I try to compile a copy of my project on my local machine, I get an error stating that it 's skipping over incompatible libraries.  This isn't the case when I'm messing around with the live version hosted on the server at work [it makes perfectly there].
Various other sites have lead me to believe that this might be an environment issue, as I'm developing on a 64-bit distro of Ubuntu and I assume the server version is running on 32-bit.  Nevertheless, after setting my environment variables to:
CFLAGS+=" -m32"
CXXFLAGS+=" -m32"

I still receive the same compile error of:
/usr/bin/ld: skipping incompatible /dvlpmnt/libPI-Http.a when searching for -lPI-Http

Can haz tutorial?
==Edit==
This was the output I recieved when I followed Jonathan's advice:
http.o: ELF 32-bit LSB relocatable, Intel 80386, version 1 (SYSV), not stripped

Apparently, the library in question is 32-bit after all?

A:

That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.
Of course, if you're also getting an error along the lines of can't find lPI-Http then you have a problem :-)
It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:

Just to check: usually you would add
flags to CFLAGS rather than
CTAGS - are you sure this is
correct? (What you have may be correct - this will depend on your build system!)
Often the flag needs to be passed to the linker too - so you may also need to modify LDFLAGS

If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx etc) that was being executed?

A:

Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http argument to the compiler/linker is not valid.  The error occurs when no other library can be found with the right content.
So, you need to look to see whether /dvlpmnt/libPI-Http.a is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32 option.  Then you need to establish whether there is an alternative libPI-Http.a or libPI-Http.so file somewhere else that is 32-bit.  If so, ensure that the directory that contains it is listed in a -L/some/where argument to the linker.  If not, then you will need to obtain or build a 32-bit version of the library from somewhere.
To establish what is in that library, you may need to do:
mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk

The 'file' step tells you what type of object files are in the archive.  The rest just makes sure you don't make a mess that can't be easily cleaned up.


Q:

What is the best browser for simulating?

I need a browser that is efficient at calculating sums using Javascript.
Things that are required:

Browser that is fast
GUI not required
Runs of Windows/Linux
Big plus if free

A:

Take a look at PhantomJS.

PhantomJS is a headless WebKit scriptable with a JavaScript API. It
  has fast and native support for various web standards: DOM handling,
  CSS selector, JSON, Canvas, and SVG

PhantomJs is a "headless browser", which will let you concentrate on your JS without having to worry about a GUI.  It is widely used for testing on many FOSS projects.


Q:

Laravel 5.1 How to send email verification email after registration?

I need users to verify their email address after registration. I have confirmation_code and confirmed fields in users table. How can I send an email after a user registration?

A:

You need a normal blade template being the body
Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
    $m->to($user->email, $user->name)->subject('Your Reminder!');
});

In just place a the confirmation_code in the email and define a route, e.g.
    mypage.com/emailverification/1389734jhikdfsjkb1234908adkb
When the user vists the link you check the database for this entry and set the status of the registration to completed.
For more information check http://laravel.com/docs/5.1/mail#sending-mail
For a detailed tutorial check: http://bensmith.io/email-verification-with-laravel


Q:

.NET Short Unique Identifier

I need a unique identifier in .NET (cannot use GUID as it is too long for this case).
Do people think that the algorithm used here is a good candidate or do you have any other suggestions?

A:

This one a good one - http://www.singular.co.nz/blog/archive/2007/12/20/shortguid-a-shorter-and-url-friendly-guid-in-c-sharp.aspx
and also here
YouTube-like GUID
You could use Base64:
string base64Guid = Convert.ToBase64String(Guid.NewGuid().ToByteArray());

That generates a string like E1HKfn68Pkms5zsZsvKONw==. Since a GUID is
  always 128 bits, you can omit the == that you know will always be
  present at the end and that will give you a 22 character string. This
  isn't as short as YouTube though.

A:

I use a similar approach as Dor Cohen's but removing some special characters:
var uid = Regex.Replace(Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "[/+=]", "");

This will output just alphanumeric characters. The UIDs are not guaranteed to have always the same length. Here is a sample run:
vmKo0zws8k28fR4V4Hgmw
TKbhS0G2V0KqtpHOU8e6Ug
rfDi1RdO0aQHTosh9dVvw
3jhCD75fUWjQek8XRmMg
CQUg1lXIXkWG8KDFy7z6Ow
bvyxW5aj10OmKA5KMhppw
pIMK8eq5kyvLK67xtsIDg
VX4oljGWpkSQGR2OvGoOQ
NOHBjUUHv06yIc7EvotRg
iMniAuUG9kiGLwBtBQByfg

A:

var ticks = new DateTime(2016,1,1).Ticks;
var ans = DateTime.Now.Ticks - ticks;
var uniqueId = ans.ToString("x");

Keep a baseline date (which in this case is 1st Jan 2016) from when you will start generating these ids. This will make your ids smaller.
Generated Number: 3af3c14996e54


Q:

Facebook Integration in Libgdx

I'm trying to integrate Facebook login in my game but since now I couldn't achieve this.
i have followed the instructions in :
https://github.com/libgdx/libgdx/wiki/Interfacing-with-platform-specific-code
And created my interface and implemented it for Android project but still no success. When i call my loginFacebook function , it shows me a circular load screen and my game screen comes back.
public class AndroidFacebookAdapter implements FacebookIntegration {

    private String name;
    private Activity androidActivity;

    public AndroidFacebookAdapter(Activity andAct) {
        super();
        this.name = "";
        this.androidActivity = andAct ;
    }

    @Override
    public void loginFacebook() {

        Gdx.app.log("AndroidFacebookAdapter"," Facebook login starts");

        //Session.openActiveSession(this, allowLoginUI, callback)
        androidActivity.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Gdx.app.log("AndroidFacebookAdapter"," runOnUiThread runs");
                Session.openActiveSession(androidActivity, true, new Session.StatusCallback() {

                    // callback when session changes state
                    @Override
                    public void call(Session session, SessionState state, Exception exception) {
                      if (session.isOpened()) {
                        Gdx.app.log("AndroidFacebookAdapter"," session.isOpened returns true ");
                        // make request to the /me API
                        Request.newMeRequest(session, new Request.GraphUserCallback() {

                          // callback after Graph API response with user object
                          @Override
                          public void onCompleted(GraphUser user, Response response) {
                            if (user != null) {
                                Gdx.app.log("AndroidFacebookAdapter"," Facebook Login Succefull");
                                name = user.getName();
                            }
                          }
                        }).executeAsync();
                      }
                    }
                  });

            }
        });

    }

    @Override
    public String getName() {

        return name;
    }

}

In my Android project i send this interface to the core project .
    andAdap = new AndroidFacebookAdapter(this);

    initialize(new MyGdxGame(andAdap), config);

And i called it when screen is touched.
game.facebookIntegration.loginFacebook();

In logcat i see :
10-27 13:06:47.988: I/AndroidFacebookAdapter(16774):  Facebook login starts
10-27 13:06:47.988: I/AndroidFacebookAdapter(16774):  runOnUiThread runs

After i see a circular loading screen (nothing on screen just black) then my game screen comes back again . In which step i made a mistake ?
Thank you for your answers .
EDIT 1 : After realizing i was already signed in my facebook account , i logged out. Then tried again and it was working. It was opening the Facebook app to ask me for credentials but even i enter the right user name / password my "onCompleted" function is not called.
Edit 2 : Now my problem solved , thanks to the tutorial at http://blog.supercookie.co.uk/post/94802569132/facebook-integration-w-libgdx
I just needed to use UiLifecycleHelper class and its implementation. My interface implmenting class now.
public class AndroidFacebookAdapter implements FacebookIntegration {

    private String name;
    public AndroidLauncher androidActivity;
    private final UiLifecycleHelper uiHelper;

    public AndroidFacebookAdapter(Activity andAct) {
        super();
        this.name = "";
        this.androidActivity = (AndroidLauncher) andAct ;
        this.uiHelper = new UiLifecycleHelper(this.androidActivity, new Session.StatusCallback() {
            @Override
            public void call(Session session, SessionState sessionState, Exception e) {

            }
        });
    }

    private void loginFacebookImp() {

        Gdx.app.log("AndroidFacebookAdapter"," Facebook login starts");

        androidActivity.runOnUiThread(new Runnable()
        {

            @Override
            public void run()
            {
                Gdx.app.log("AndroidFacebookAdapter"," runOnUiThread runs");
                Session.openActiveSession(androidActivity, true, new Session.StatusCallback()
                {

                    // callback when session changes state
                    @Override
                    public void call(Session session, SessionState state, Exception exception)
                    {
                        Gdx.app.log("AndroidFacebookAdapter"," openActiveSession call start");
                        if (session.isOpened())
                        {
                            Gdx.app.log("AndroidFacebookAdapter"," session.isOpened returns true ");
                            // make request to the /me API
                            Request.newMeRequest(session, new Request.GraphUserCallback()
                            {

                                  // callback after Graph API response with user object
                                  @Override
                                  public void onCompleted(GraphUser user, Response response) {
                                      Gdx.app.log("AndroidFacebookAdapter"," onCompleted start");
                                    if (user != null) {
                                        Gdx.app.log("AndroidFacebookAdapter"," Facebook Login Succesfull");
                                        Gdx.app.log("AndroidFacebookAdapter"," Facebook name is " +  user.getName());
                                        name = user.getName();
                                    }
                                    else
                                    {
                                        Gdx.app.log("AndroidFacebookAdapter"," Facebook Login failed");
                                    }
                                  }
                            }).executeAsync();
                        }
                        else
                        {
                            Gdx.app.log("AndroidFacebookAdapter"," session.isOpened() is false");
                        }
                    }
                  });

            }
        });

    }

    private boolean isLoggedInImp()
    {
        return Session.getActiveSession() != null && Session.getActiveSession().isOpened();
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void loginFacebook() {
        loginFacebookImp();
    }

    public void onCreate(Bundle savedInstanceState) {
        uiHelper.onCreate(savedInstanceState);
    }

    public void onResume() {
        uiHelper.onResume();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        uiHelper.onActivityResult(requestCode, resultCode, data);
    }

    public void onSaveInstanceState(Bundle outState) {
        uiHelper.onSaveInstanceState(outState);
    }

    public void onPause() {
        uiHelper.onPause();
    }

    public void onStop() {
        uiHelper.onStop();
    }

    public void onDestroy() {
        uiHelper.onDestroy();
    }

    @Override
    public boolean isLoggedIn() {

        return isLoggedInImp();
    }

}

A:

As in edit 2 , just add the UiLifecycleHelper android side interface implementing class. Then it is working as expected. For more explanation :
http://blog.supercookie.co.uk/post/94802569132/facebook-integration-w-libgdx


Q:

Linking a pdf file within a paragraph

I don't have Drupal installed on my computer (do I have to?). I access the admin site to make changes. I need to add a PDF file that describes an event. In order to do this quickly, I simply inserted some text describing the event, and at some point in the test, I want a link that people will click and the pdf file opens up.
I am totally clueless as to what I'm doing wrong. I typed <a href= "/files/pdfdocname.pdf"> in front of the word I want linked. the link is active. However, it redirects to a page that says the page doesn't exist.
Is there another code I need to use? My document is found in the files folder of the root directory of the website.

A:

This is more of a general web question as opposed to being specifically Drupal related.
To answer your first question, no, you do not need to have Drupal installed on your personal computer in order to make changes to an existing site.
Here are a few things to check:

The server could not locate your file. Double check your file path and URL to your PDF. If your PDF is located in the public directory (starting from your web site root) "sites/default/files", then the corresponding URL would be http://www.example.com/sites/default/files/mypdf.pdf If you type in your URL in your browser, it should load it up.
If you are sure that you have the correct URL, but the PDF will not load up, double check the permissions on that file. Here is a good post about permissions: What are the recommended directory permissions?


Q:

How to update row status with jquery change() and display in respective table

I'm facing major issue in changing status of a particular row in table with  <select> tag .
I'm using  jquery-Ajax so, here go functionality by this when is click on <select  on any particular row for Example: Lets say i have changed the status of  table row of id 2 from Pending to Delivered. On this jquery change() event triggers  and it fetchs the value from 'tag' and sends the value to other file through ajax. Till here everything goes right the data goes through ajax and row with particular id's status  is getting updated successfully.
But on Front end it does not change the status of the particular row. but it changes status of only first row .
Here i need it to change status of the particular row.
Note : I have searched in stackoverflow for this question. but those answere not come close to my question. Here are those links below Link 1link2link3
THANK YOU IN ADVANCE
Here is the Output and i have explained details in images also

There is the full code
HTML page : index.php
 <?php
    include('processing.php');
    $newobj = new processing();
?>

        <title>Jquery Ajax select <tag> with PHP Mysql</title>

                Id
                Product name
                Status
                Action

            <?php echo $newobj->display();?>

AJAX HANDLER PAGE : ajaxreceiver.php
    <?php
    include('processing.php');
    $newobj = new processing();

    if(isset($_POST['statusname'],$_POST['getid'])){
        $statusid = $_POST['statusname'];
        $id = $_POST['getid'];

        $newobj->getdata($statusid,$id);
    }
?>

PHP CLASSES FILE : processing.php
  <?php
    class processing{
        private $link;

        function __construct(){
            $this->link= new mysqli('localhost','root','','example');
            if(mysqli_connect_errno()){
                die ("connection failed".mysqli_connect_errno());
            }
        }

        function display(){
            $sql = $this->link->stmt_init();
            $id=1;
            if($sql->prepare("SELECT id,productname,status FROM ajaxselect")){
                $sql->bind_result($id,$productname,$status);
                if($sql->execute()){
                    while($sql->fetch()){
            ?>

                            <?php echo $id;?>
                            <?php echo $productname;?>

<?php echo $status;?>

                                <select status-id=<?php echo $id;?> id="selectstatus" class="selectstatus">
                                    <option>Pending</option>
                                    <option>Delivered</option>
                                    <option>Cancelled</option>
                                    <option>Amount Paid</option>
                                </select>

            <?php
                    }
                }
            }
        }

        function getdata($statusid,$id){
            $sql = $this->link->stmt_init();
            if($sql->prepare("UPDATE ajaxselect SET status=? WHERE id=?")){
                $sql->bind_param('si',$statusid,$id);
                if($sql->execute()){
                    echo $statusid;
                }
                else
                {
                    echo "Update Failed";
                }
            }
        }
    }
?>

A:

the problem is in this line :
$("#display").html(result);
so what's going here ?
you are creating display id for every row, which is not good practice to do , specially in your particular .
there are various solutions for this problem ,
1)
("#display", $(this).parent().parent()).html(result);
here you are going to apply the action to particular ID which is belongs to the parent of the parent of the particular class which had received the change action
2)
giving the display row unique id for each row
for example like follows :-
<p id="display_<?php echo $id; ?>"><?php echo $status;?>

and then apply your action to it directly ,
$("#display_" + getid).html(result);
3)
and this solution is similar to the past one , by giving the parent
 a unique id
for example :-
<tr id='parent_<?php echo $id; ?>'>
and then apply your action it from your ajax like this
$("#display", $('#parent_' + getid)).html(result);
or even :
$('#parent_' + getid + ' #display').html(result);


Q:

"Justification of" or "justification for"?

Do "justification of" or "justification for" mean different things? Is one more appropriate than the other?

A:

If you are describing the action being justified, say "justification for". If you are identifying the person offering the justification or being justified, say "justification of".
For example, "What was Bob's justification for arriving late?" vs "We listened to Bob's justification of himself."
The same is true when the word is used in a theological context. "We receive justification for our sins through the atoning work of Christ" vs "The justification of the sinner is received ..."
Or if you're thinking of "justification" in the sense of the placement of text on a line, you should always use "of". "The justification of the customer name on the form is determined by ..."


Q:

Find the inverse of $f(x)=x^3+x+1$.

$$f(x)=x^3+x+1$$
I didn't learn this at school and I want to know how I can get the inverse of this function.
Do you use differentiation?
I have this solution but I don't understand what it means $(f^{-1})'(3)$=$1$.
Is that differentiation?

A:

First you have to check that $f$ is bijective (assuming that the domain and the codomain are both $\Bbb R$).  The surjectivity is clear as $f$ is continuous and $\lim_{x\to\pm\infty}f(x)=\pm\infty$.  For injectivity, we have
$$f(x)=f(y)\iff x^3-y^3+x-y=0\iff (x-y)(x^2+xy+y^2+1)=0.$$
Since $x^2+xy+y^2+1=(x+y/2)^2+3(y/2)^2+1>0$, we see that $$f(x)=f(y) \iff x=y,$$ so $f$ is injective.  Hence, $f$ is a bijection, and we can find the inverse.
Suppose that $f(x)=t$.  Then, $x^3+x=t-1$.  We assume alla Cardano's method that $x=u+v$ such that $x^2+1=u^2-uv+v^2$, so $u^3+v^3=x(x^2+1)=x^3+x=t-1$.  Now, $$u^2-uv+v^2=x^2+1=(u+v)^2+1\implies uv=-\frac13\implies u^3v^3=-\frac1{27}.$$
That is, $u^3$ and $v^3$ are roots of $z^2-(t-1)z-\frac1{27}$, which means
$$\{u^3,v^3\}=\left\{\frac{(t-1)\pm\sqrt{(t-1)^2+\frac{4}{27}}}{2}\right\}.$$
So, wlog, we can take
$$u=\sqrt[3]{\frac{(t-1)+\sqrt{(t-1)^2+\frac{4}{27}}}{2}}\wedge v=\sqrt[3]{\frac{(t-1)-\sqrt{(t-1)^2+\frac{4}{27}}}{2}}. $$
This gives
$$f^{-1}(t)=x=u+v=\sqrt[3]{\frac{(t-1)+\sqrt{(t-1)^2+\frac{4}{27}}}{2}}+\sqrt[3]{\frac{(t-1)-\sqrt{(t-1)^2+\frac{4}{27}}}{2}}.$$


Q:

Inserting serialized value into wp_postmeta using update_post_meta

I'm looking to insert this serialized value into a meta_value in the wp_postmeta table
a:1:{s:8:"quantity";s:1:"2";}

I've tried numerous things
Such as creating the associative array manually.
$defaultquantityarray =  array('quantity' => '2');
$defaultquantity = serialize($defaultquantityarray);

update_post_meta( $post_id, '_default_attributes', $defaultquantity);

I've also referenced the update_post_meta
 documentation and found reference to something like this
$escaped_json = 'a:1:{s:8:"quantity";s:1:"2";}';

update_post_meta( $post_id, '_default_attributes', wp_slash( $escaped_json ));

and additionally with a:1:.
Both result in this insert into my meta_value row
s:29:"a:1:{s:8:"quantity";s:1:"2";}";

This is all being performed in a WP_Query loop.
How do I insert a meta_value of a:1:{s:8:"quantity";s:1:"2";} into my _default_attributes meta_key?

A:

Wow okay, so after posting this I almost immediately came up with the solution.
It was a combination of the two things I tried.
$defaultquantityarray =  array(
 'quantity' => '2'
);

update_post_meta( $post_id, '_default_attributes', $defaultquantityarray);

Apparently WordPress automatically serializes data in some meta_values, and I was essentially serializing them twice hence the s:29: prefix.


Q:

Serve content from a different server in a ASP.NET MVC 3 application

Currently Url.Content("a.jpg") would return something like "/a.jpg"
Is there a way to force all content to be served from another server?
I want Url.Content("a.jpg") to return something like: "http://somehost/a.jpg"

A:

The Url.Content helper works only with internal to the current application urls. If you want to work with external urls you could write a custom url helper for that purpose:
public static class UrlExtensions
{
    public static string ContentExternal(this UrlHelper urlHelper, string contentPath)
    {
        var uriBuilder = new UriBuilder("http://somehost");
        uriBuilder.Path = contentPath;
        return uriBuilder.ToString();
    }
}

and then:
@Url.ContentExternal("/Content/images/a.jpg")


Q:

Does ASP.NET Custom Errors override the actual HTTP response code?

If I were to specify a page for redirect using the ASP.NET Custom Errors feature, would my application still spit out the HTTP status code for that particular error?
For example if had a line in my web.config that had all Internal Server Errors redirect to Errors/500.aspx and then I encountered a 500 error, I would then be redirected to my custom Errors/500.aspx page. Will my application still respond with a HTTP 500 at any point in this exchange?
I'm just curious...

A:

No, because your browser would interpret that 500 response as an error and show you it's error.  Instead, it probably responds with one of the redirect status codes to send you to the defined error page.


Q:

django - class view 404 if no result

I have the following class-based view -
class DeployFilterView(generics.ListAPIView):
    serializer_class = DefinitionSerializer

    def get_queryset(self):
        jobname = self.request.GET.get('jobname')
        if jobname.count("\\") == 1:
            jobname = jobname.replace("\\", "")
            queryset = Jobmst.objects.db_manager('Admiral').filter(jobmst_name=jobname).exclude(jobmst_prntname__isnull=True, jobmst_dirty='X')
        else:
            parent, job = jobname.rsplit('\\', 1)
            queryset = Jobmst.objects.db_manager('Admiral').filter(jobmst_prntname=parent, jobmst_name=job).exclude(jobmst_dirty='X')

        return queryset

I want to have it return a 404 response if either queryset returns no information how do I go about chaining that in?
I'm using Django Rest Framework.  Right now if I call a URL and there's no data it passes a 200 OK which I don't want.  Below is what I'm trying -
class DeployFilterView(generics.ListAPIView):
    serializer_class = DefinitionSerializer

    def get_queryset(self):
        jobname = self.request.GET.get('jobname')
        if jobname.count("\\") == 1:
            jobname = jobname.replace("\\", "")
            queryset = Jobmst.objects.db_manager('Admiral').filter(jobmst_name=jobname).exclude(jobmst_prntname__isnull=True, jobmst_dirty='X')
        else:
            parent, job = jobname.rsplit('\\', 1)
            queryset = Jobmst.objects.db_manager('Admiral').filter(jobmst_prntname=parent, jobmst_name=job).exclude(jobmst_dirty='X')
        try:
            if queryset == True:
                return queryset
            else:
                raise exceptions.DoesNotExist

But it fails on saying my indenting is wrong but I don't see how it is.

A:

It's likely throwing an issue because you have no except block. You don't need to keep the try block; since you're just doing an if/else statement.
Also, your if queryset == True: is unnecessary, you can just do if queryset:.
Try something like:
from django.http import Http404

# The rest of your code here...

if queryset:
    return queryset
else:
    raise Http404

For more information you can check out django's documentation on returning 404 errors.


Q:

OpenGL GLUT window very slow, why?

The problem
I have just now begun working with OpenGL using GLUT. The code below compiles and displays two wireframe cubes and a sphere. The problem is that when I attempt to drag or resize the window it induces a noticeable delay before  following my mouse.
This problem does not occur on my colleague's computer, same code.
I am working with Visual Studio 2012 c++ express on a Windows 7 computer.
I am a not an experienced programmer.
The code
    // OpenGLHandin1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <GL/glut.h>

void initView(int argc, char * argv[]){
    //init here
    glutInit(&argc, argv);
    //Simple buffer
    glutInitDisplayMode( GLUT_SINGLE | GLUT_RGBA );
    glutInitWindowPosition(100,100);
    glutInitWindowSize(800,400);
    glutCreateWindow("Handin 2");
}
void draw(){

    glClearColor(0,0,0,1);
    glClear(GL_COLOR_BUFFER_BIT);
    //Background color

    glPushMatrix();
    glLoadIdentity();
    glTranslatef(0.6, 0, 0);

    glColor3f(0.8,0,0);
    glutWireCube(1.1); //Draw the cube
    glPopMatrix();

    glPushMatrix();
    glLoadIdentity();
    glTranslatef(-0.5, 0, -0.2);

    glColor3f(0,0.8,0);
    glutWireCube(1.1); //Draw the cube
    glPopMatrix();

    glPushMatrix();
    glLoadIdentity();
    glTranslatef(0, 1.2, 0);
    glRotatef(90, 1, 0, 0);

    glColor3f(1,1,1);
    glutWireSphere(0.6, 20, 20); //Draw the sphere
    glPopMatrix();

    //draw here
    //glutSwapBuffers();
    glutPostRedisplay();
    glFlush();

}
void reshape (int w, int h){
    glViewport(0,0,w ,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45, (float)w/(float)h, 1.5, 10);
    gluLookAt(1.5, 2.5, 4,
              0, 0.6, 0,
              0, 1, 0); //Orient the camera
    glRotatef(5, 0, 0, 1);
    glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char * argv[])
{
    initView(argc,argv);
    glutDisplayFunc(draw);
    glutReshapeFunc(reshape);
    glutMainLoop();
}

A:

Solution:
It seems that the simple solution using Sleep(1) in the render function worked. You've also asked why - I'm not sure I will be able to solve this properly, but here's my best guess:
Why does it even work?
Your fellow students can have VSync turned on by default in their drivers. This causes their code to run only as fast as the screen can refresh, most probably 60 fps. It gives you around 16 miliseconds to render the frame, and if the code is efficient (taking, say, 2 ms for render) it leaves plenty of time for the CPU to do other OS-related stuff, such as moving your window.
Now, if you disable vertical sync, the program will try to render as many frames as possible, effectively clogging all other processes. I've suggested you to use Sleep, because it reveals this one particular issue. It doesn't really matter if it's 1 or 3 ms, what it really does is say "hey, CPU, I'm not doing anything in particular right now, so you may do other things".
But isn't it slowing my program?
Using Sleep is a common technique. If you're concerned with that lost 1 ms every frame, you can also try putting Sleep(0), as it should act exactly the same - giving the spare time to the CPU. You could also try enabling vertical sync and verifying if indeed my guess was correct.
As a side note, you can also look at CPU usage graphs with and without sleep. It should be 100% (or 50% on a dual-core CPU) without (running as fast as possible), and much lower with, depending on your program requirements and your CPU's speed.
Additional remarks about Sleep(0)
After the sleep interval has passed, the thread is ready to run. If you specify 0 milliseconds, the thread will relinquish the remainder of its time slice but remain ready. Note that a ready thread is not guaranteed to run immediately. Consequently, the thread may not run until some time after the sleep interval elapses. - it's from here.
Also note that on Linux systems behavior might be slightly different; but I'm not a linux expert; perhaps a passer-by could clarify.


Q:

Wrapping non-child elements in jquery

I currently have a html document in the following format:

a

bla

more bla

b

different bla

I am looking for a way to wrap both the
 and it's following
 inside a div, so it would look like:

a

bla

more bla

b

different bla

But I have been unsuccessful using wrap and wrapAll to achieve this.

A:

var tagName = 'h1';
$(tagName).each(function ()
{
    var $this = $(this);
    $this.add($this.nextUntil(tagName)).wrapAll('

');
});

Demo demo demo demo demo


Q:

Ambiguity about -masu forms of ていく and てくる in informal speech

いく and くる are usually considered a pair of antonyms and ていく and てくる is a pair of common constructions from them. When conjugated to the masu form, the first one becomes ていきます and the second one becomes てきます. However in informal speech the first one can also be contracted to てぃきます which is not very different from the latter, just like ていく itself becomes てく. So how to tell which one the speaker is intended to say?

A:

It depends on contexts. For example, when you are asked if you do something, これから やってきます will be interpreted as contraction from て行き, i.e "I'll do it from now on". On the other hand, it means "it will come soon" when you are asked when a certain climate comes.


Q:

Task Event using Tridion 2013

Is it possible to write an event handler for the finish event of a Task in 2013.
Is it possible to catch the Committed Event of a Task in 2013?
I see there is a WorkflowEventArgs, but I am having a hard time finding the 'subject' of the event.  Would VersionedItem be the correct subject?

A:

Task is a process definition with 1 activity, so you need FinishProcessEventArgs and subject is a Process


Q:

determining if variable based on database query is null in php

I have the following snippet of php code in which I am trying to have the output be NULL if the php query does not yield any results but if it does yield results I have the output to be NOT NULL.
 $dbconnSrc = pg_connect("host=$dbhost dbname=$dbname user=$dbuser password=$dbpass") or die ("Could not connect");

$sql="select area, radius from circle where level>50";

$res = pg_query($dbconnSrc, $sql);
var_dump(isset($res));
echo "$res\n";
while($row = pg_fetch_array($res, NULL, PGSQL_ASSOC))
{
    $radius=$row["radius"];
    print "radius is $radius\n";
    if (isset($radius)){
        echo "NOT NULL\n";
    }
    else
    {
         echo "NULL\n";
    }
}

Unfortunately, I am not getting the desired results, so I was wondering if anyone knows who to tweak this code to get the desired results.

A:

$radius will always be set because you're setting it.
Try this instead.
$dbconnSrc = pg_connect("host=$dbhost dbname=$dbname user=$dbuser password=$dbpass") or die ("Could not connect");

$sql="select area, radius from circle where level>50";

$res = pg_query($dbconnSrc, $sql);
var_dump(isset($res));
echo "$res\n";
while($row = pg_fetch_array($res, NULL, PGSQL_ASSOC))
{
    // using $row directly here - no need to create another variable
    print "radius is " . $row['radius'] . "\n";

    // inspecting $row here for the entry first, then to see if it's empty
    if ( array_key_exists( 'radius', $row ) || empty( $row['radius'] ) ){
        echo "NOT NULL\n";
    }
    else
    {
         echo "NULL\n";
    }
}


Q:

How to seach a list of customers in java using Scanner:

Can anyone help me please?
I'm working on this assignment and I'm almost done with my code, except that I don't know how to search the list of customers by typing their names. !

Get a list of customers from a file
Customer contains first name, last name, and email address
Sort the list by last name
Search the list for a given name
List item
import java.util.*;
import java.io.*;

public class computer {

public static void main(String args[]){
    Scanner console = new Scanner(System.in);

    //create a file named myFile.txt
    createFile object1 = new  createFile();
    object1.openFile();
    object1.addRecords();
    object1.closeFile();

    //This code reads the File and outputs it on the screen
    System.out.println("-----------------------------------------------------------------------");
    System.out.println("This is the list of customers being read from a file called myFile.txt ");
    System.out.println("-----------------------------------------------------------------------");
    readFile r = new readFile();
    r.openFile();
    r.readfile();
    r.closeFile();

    LinkedList<customers> list = new LinkedList<customers>();
    try
    {
      Scanner file = new Scanner(new File("myFile.txt"));
      while(file.hasNext())
      {
        String name = file.next();
        String lname = file.next();
        String email = file.next();
        list.add(new customers(name,lname, email));
      }
    }
    catch (Exception e) {
        // TODO: handle exception
    }
    Collections.sort(list,new Mycustomers());
    System.out.println("This is the list of customers sorted by their last names: ");
    System.out.println("--------------------------------------------------------------");
    System.out.println();
    for(customers cu:list){
        System.out.println(cu);
    }

A:

Start with how you print the list, but instead printing every one, first compare the name in each with the name you are looking for (can't give more detail without more details on customers); if it matches, do whatever you need to do and break the loop.
To read in what name to search for, I'll repeat what user3567040 said:
Scanner s = new Scanner(System.in);
String name =s.nextLine();

(although you might need 2 Strings: one for the first name, and another for the last.


Q:

Table transformation with dplyr

I have a table called df. This table contains three columns (Code,Description and Rate).

#CODE

df<-data.frame(
  Code=c("01","0101","0101 21 00 00","0101 29","0101 29 10 00","0101 29
          90 00","0101 30 00 00","0101 90 00 00","NA","0102 21","0102 21 10
          00","0102 21 30 00","0102 21 90 00"),
  Description=c("LIVE ANIMALS", "Live horses, asses, mules","Live horses,
                asses, mules and hinnies","Pure-bred breeding horses","Live
                horses (excl. pure-bred for breeding)","Horses for
                slaughter","Live horses (excl. for slaughter, pure-bred for
                breeding)","Live asses","Live mules and hinnies","Live
                bovine animals","Pure-bred cattle for breeding","Pure-bred
                breeding heifers female bovines that have never
                calved","Pure-bred breeding cows (excl. heifers)"),
  Rate=c("NA","NA","5","NA","5","10","15","7","NA","NA","10","15","20"))

So my intention is to make subset of upper table which will only contain field of column Code which have 10-digits and calculate average. This means the code should only extract rows with 10-digits codes (0101 21 00 00,0101 29 10 00, 0101 29 90 00,0101 30 00 00,0101 90 00 00,0102 21 10 00,0102 21 30 00 and 0102 21 90 00) like table below.Average of column Rate is 2,75.

So can anybody help me how to transform this table ?

A:

We can remove the spaces from the codes and then count the characters. That lets use filter to 10-digit codes only. We can then add a summarise if we want the mean (note that it is not 2.75)
library(tidyverse)
df <- tibble(Code = c("01", "0101", "0101 21 00 00", "0101 29", "0101 29 10 00", "0101 29 90 00", "0101 30 00 00", "0101 90 00 00", "NA", "0102 21", "0102 21 10 00", "0102 21 30 00", "0102 21 90 00"), Description = c("LIVE ANIMALS", "Live horses, asses, mules", "Live horses,  asses, mules and hinnies", "Pure-bred breeding horses", "Live horses (excl. pure-bred for breeding)", "Horses for slaughter", "Live horses (excl. for slaughter, pure-bred for breeding)", "Live asses", "Live mules and hinnies", "Live  bovine animals", "Pure-bred cattle for breeding", "Pure-bred breeding heifers female bovines that have never calved", "Pure-bred breeding cows (excl. heifers)"), Rate = c("NA", "NA", "5", "NA", "5", "10", "15", "7", "NA", "NA", "10", "15", "20"))
df %>%
  filter(Code %>% str_remove_all("\\s") %>% str_length %>% `==`(10))
#> # A tibble: 8 x 3
#>   Code         Description                                            Rate
#>   <chr>        <chr>                                                  <chr>
#> 1 0101 21 00 … Live horses,  asses, mules and hinnies                 5
#> 2 0101 29 10 … Live horses (excl. pure-bred for breeding)             5
#> 3 0101 29 90 … Horses for slaughter                                   10
#> 4 0101 30 00 … Live horses (excl. for slaughter, pure-bred for breed… 15
#> 5 0101 90 00 … Live asses                                             7
#> 6 0102 21 10 … Pure-bred cattle for breeding                          10
#> 7 0102 21 30 … Pure-bred breeding heifers female bovines that have n… 15
#> 8 0102 21 90 … Pure-bred breeding cows (excl. heifers)                20

df %>%
  filter(Code %>% str_remove_all("\\s") %>% str_length %>% `==`(10)) %>%
  summarise(mean_rate = mean(as.integer(Rate)))
#> # A tibble: 1 x 1
#>   mean_rate
#>       <dbl>
#> 1      10.9

Created on 2019-05-08 by the reprex package (v0.2.1)