Q:

cabal install fpco-api error

Recently I tried to install fpco-api on OS X 10.9 via cabal install, but got errors during the building phase. Here is the list of error:
... lots of 'loading package'
Loading package asn1-data-0.7.1 ... linking ... done.
Loading package asn1-types-0.2.3 ... linking ... done.
Loading package crypto-pubkey-types-0.4.1 ... linking ... done.
Loading package pem-0.2.1 ... linking ... done.
Loading package certificate-1.3.9 ... linking ... done.
Loading package publicsuffixlist-0.1 ... linking ... done.
Loading package regex-base-0.93.2 ... linking ... done.
Loading package regex-posix-0.95.2 ... linking ... done.
Loading package regex-compat-0.95.1 ... linking ... done.
Loading package socks-0.5.4 ... linking ... done.
Loading package crypto-numbers-0.2.3 ... linking ... done.
Loading package crypto-pubkey-0.2.4 ... linking ... done.
Loading package tls-1.1.5 ... linking ... done.
Loading package cipher-rc4-0.1.4 ... linking ... done.
Loading package tls-extra-0.6.6 ... linking ... done.
Loading package http-conduit-1.9.6 ... linking ... done.
Loading package hslogger-1.2.3 ... linking ... done.
Loading package MissingH-1.2.0.2 ... linking ... done.
Loading package ConfigFile-1.1.1 ... linking ... done.
[ 5 of 10] Compiling FP.API.Run ( src/library/FP/API/Run.hs, dist/build/FP/API/Run.o )

src/library/FP/API/Run.hs:37:1: Warning:
Module `Prelude' does not export `catch'
[ 6 of 10] Compiling FP.API.TH ( src/library/FP/API/TH.hs, dist/build/FP/API/TH.o )
[ 7 of 10] Compiling FP.Server.Types ( src/library/FP/Server/Types.hs, dist/build/FP/Server/Types.o )

src/library/FP/Server/Types.hs:97:36:
Ambiguous occurrence `Loc'
It could refer to either `FP.Server.Types.Loc',
defined at src/library/FP/Server/Types.hs:115:6
or `Control.Monad.Logger.Loc',
imported from `Control.Monad.Logger' at src/library/FP/Server/Types.hs:18:1-27
(and originally defined in `Language.Haskell.TH.Syntax')

src/library/FP/Server/Types.hs:102:46:
Ambiguous occurrence `Loc'
It could refer to either `FP.Server.Types.Loc',
defined at src/library/FP/Server/Types.hs:115:6
or `Control.Monad.Logger.Loc',
imported from `Control.Monad.Logger' at src/library/FP/Server/Types.hs:18:1-27
(and originally defined in `Language.Haskell.TH.Syntax')

src/library/FP/Server/Types.hs:103:46:
Ambiguous occurrence `Loc'
It could refer to either `FP.Server.Types.Loc',
defined at src/library/FP/Server/Types.hs:115:6
or `Control.Monad.Logger.Loc',
imported from `Control.Monad.Logger' at src/library/FP/Server/Types.hs:18:1-27
(and originally defined in `Language.Haskell.TH.Syntax')

src/library/FP/Server/Types.hs:118:17:
Ambiguous occurrence `Loc'
It could refer to either `FP.Server.Types.Loc',
defined at src/library/FP/Server/Types.hs:115:6
or `Control.Monad.Logger.Loc',
imported from `Control.Monad.Logger' at src/library/FP/Server/Types.hs:18:1-27
(and originally defined in `Language.Haskell.TH.Syntax')

src/library/FP/Server/Types.hs:119:19:
Ambiguous occurrence `Loc'
It could refer to either `FP.Server.Types.Loc',
defined at src/library/FP/Server/Types.hs:115:6
or `Control.Monad.Logger.Loc',
imported from `Control.Monad.Logger' at src/library/FP/Server/Types.hs:18:1-27
(and originally defined in `Language.Haskell.TH.Syntax')
Failed to install fpco-api-1.0.5
cabal: Error: some packages failed to install:
fpco-api-1.0.5 failed during the building phase. The exception was:
ExitFailure 1

Does anyone know how to handle this error?

A:

It seems that the monad-logger package started to export the Loc symbol starting with version 0.3.4.0. This version isn't excluded by the Cabal file of fpco-api.
You could try
cabal install fpco-api --constraint="monad-logger < 0.3.4"

to force using an older version of monad-logger.

More explanation about the error:
The module FP.Server.Types in the package fpco-api defines a datatype Loc that's used throughout the package. The module Language.Haskell.TH.Syntax defines a different datatype Loc. This modules isn't used directly by fpco-api, but fpco-api makes use of the monad-logger package, which in turn uses Language.Haskell.TH.Syntax. That's no problem as long as at no point in the program, both different Loc types are in scope. But in its most recent version, 0.3.4.0, the monad-logger package decided to re-export the Loc datatype from Language.Haskell.TH.Syntax. Now in many places where the logger monad is imported in fpco-api, suddenly both Loc types are in scope, and GHC doesn't know to which one the local occurrences of Loc refer.
The proper fix for this error is for fpco-api to be hiding the Loc re-export from the logger monad, or to explicitly refer to the right one by using qualified names. But this requires a source code update of fpco-api. The temporary fix to use an older version of monad-logger should hopefully be sufficient.


Q:

How to capture dialed number instead of client id with Twilio

I am using the browser client and trying to capture the number the caller dialed to reach us. Instead of conn.parameters.To giving me the number the caller dialed, it's giving me the client id that the calls was sent to.
How can I get the dialed number when receiving an incoming call in the browser client?
Thanks

A:

OK, here is how I solved this. I liked Devins ideas but didn't want to involve third part libraries or a database just to accomplish this task.
I hope I am explaining this well enough so it helps someone else down the road.
OK, I solved this by doing the following:
I created a callinfo.php page which required one parameter, the callsid. In the .js page I was able to get the callsid with
var myCallSid = conn.parameters.CallSid;
inside:
Twilio.Device.incoming(function (conn) {
Then I did an ajax call to my callinfo.php by posting the myCallSid to it.
Inside my callinfo.php page the call sid didn't really get me the To number I was after because the callsid was not really for the incoming call, it was for the second leg of the call where the client was called. So, technically the To parameter was really client: joe shmoe or something like that.
So.. What I did was inside my callinfo.php I pulled the call info of the first leg of the call by referencing the parent_call_sid of the second callsid.
Once I had the parentcallsid I used that to lookup info on the call, grab the "to" and whatever else I wanted and return it to my .js file. Once in the JS file, I could of course do what I wanted with the beautiful gems of data I had mined :-)
No database calls, no third party libraries or tools and I got the data I wanted and then some. In the PHP page I can grab all sorts of other data as shown here:
https://www.twilio.com/docs/api/rest/call


Q:

Не возвращается результат в переменной jQuery

Не могу понять, почему не срабатывает калькуляция в коде:

$(document).ready(function(){
  if ($('#type1:checked')) {
    var shed   = base+distance+size1+rubber;
  } else if ($('#type2:checked')) {
    var shed   = base+distance+size2+rubber;
  } else if ($('#type3:checked')) {
    var shed   = base+distance+size3+rubber;
  } else if ($('#type4:checked')) {
    var shed   = base+distance+size3+rubber;
  } else ($('#type5:checked')) {
    var shed   = base2+distance+size4+rubber;
  }
  $('#last__par_count').html(shed);
});

В тег с id=last__par_count не заносится результат вычислений.
Во всех имеющихся переменных есть значения.

A:

Вы неправильно проверяете чекбокс:

$(document).ready(function(){
  var shed = "";
  if ($('#type1').is(':checked')) {
    shed = base+distance+size1+rubber;
  } else if ($('#type2').is(':checked')) {
    shed = base+distance+size2+rubber;
  } else if ($('#type3').is(':checked')) {
    shed = base+distance+size3+rubber;
  } else if ($('#type4').is(':checked')) {
    shed = base+distance+size3+rubber;
  } else if ($('#type5').is(':checked')) {
    shed = base2+distance+size4+rubber;
  }
  $('#last__par_count').html(shed);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


Q:

how to change rails datetime_field defaults?

Me and my co-workers were testing my web app. And, in the form in my computer/local/dev and server/production it shows the date format dd/mm/yyyy 00:00 and for my coworkers mm/dd/yyyy 00:00 am/pm with the same local chrome settings and computer settings.

why is this?
and how can I change this for all users? if possible.

piece of code:

Inicio<%= image_tag("calendar.png", :class => "calendar")%>

              <%= f.datetime_field :Inicio %>

A:

Try below code:
<%= f.date_field :Inicio, as: :date, value: f.object.try(:strftime,"%d/%m/%Y"), class: 'form-control' %>

You can also use this gem: https://github.com/Nerian/bootstrap-datepicker-rails
on your gemfile.rb
gem 'bootstrap-datepicker-rails'

then bundle install and restart rails server
then add this line to app/assets/stylesheets/application.css
*= require bootstrap-datepicker

and add this line to app/assets/javascripts/application.js
//= require bootstrap-datepicker

and to use this in your form:
<%= f.date_field :Inicio, :id => "datepicker" %>

and add this javascript on the same view of your form


Q:

Passing a string value will fail to find the file

I write a shell which will try to collect a file from the file path into current directory if it exists:
collect_file() {
  fpath=$1
  echo $fpath
  if [ -e $fpath ]; then

    fname=`basename $fpath`
    `cp $1 $fname`
    retval=$?
    if [ $retval == 0 ]; then
      echo "Collect file '$fpath'"
    else
      echo "Error: fail to copy file '$fpath'"
    fi

  else
    echo "Error: file '$fpath' not found"
  fi
}

Now, if I pass a bare value ~/.gitconfig, it will succeed, but when I pass a string value "~/.gitconfig", it will fail.
collect_file ~/.gitconfig        # will succeed to copy the file
collect_file "~/.gitconfig"      # will fail

Shows:
# results for bare value
/Users/Xaree/.gitconfig
Collect file '/Users/Xaree/.gitconfig'

# results for string value
~/.gitconfig
Error: file '~/.gitconfig' not found

Why and how can I fix it?

A:

The following refers to a file in the user's home directory:
~/.gitconfig

By contrast, the following refers to a file in a directory named ~:
"~/.gitconfig"

~/ is interpreted as the home directory when the shell performs tilde expansion.  The shell only perform tilde expansion when the ! is unquoted.  If the string is quoted, then ~ just means ~ and nothing else.
Examples
Observe that tilde expansion is performed for only one of the following three statements:
$ echo "~/.bashrc"
~/.bashrc
$ echo ~"/.bashrc"
~/.bashrc
$ echo ~/".bashrc"
/home/john1024/.bashrc

Forcing a tilde expansion
Tilde expansion, as implemented by the shell, offers many features with many special cases.  We could force a general tilde expansion using eval but that would introduce many security issues.  For just the basic case, however, we can safely replace ~/ in a variable with $HOME/ as follows:
fpath="${fpath/~\//$HOME\/}"

A problem with the above is that it will do the replace the first occurrence of ~/ even if the string does not start with ~/.  To avoid that, we can use:
[ "${fpath#\~/}" != "$fpath" ] && fpath="${fpath/~\//$HOME\/}"

This tests to be sure that the string starts with ~/ before it makes the substitution.


Q:

Useful instantiations of “fix” on non-function types?

Every time I’ve used fix :: (a -> a) -> a, it’s been at the type
((a -> b) -> a -> b) -> a -> b

for some a and b. Is there actually some application of fix where its type parameter is not instantiated to a function type, other than a trivial thing like fix (const 0)? What is the purpose of leaving the signature at its most general?

A:

I don't know if you would regard this example as trivial, but you can use fix directly (without going through a function) to build up data:
repeat :: a -> [a]
repeat x = fix (x:)

A:

There are many examples of building corecursive data with fix. I don't know enough to elaborate on the general theory, but it seems as though any data type that is like a stream, in that you can always output one more value given the stream so far, can be computed with fix without feeding it a function type.
Examples
The simplest example (given in Cactus's answer) is a repeating stream of values, for example
x = [1, 1, 1, 1, 1, 1, 1, 1, ...]

This satisfies the equation
(1:) x = x

and can be produced by
>> fix (1:)
[1,1,1,1,1,1,1,1,1,1,...]

A slightly more complicated example is the natural numbers
n = [0, 1, 2, 3, 4, 5, 6, ...]

which satisfy the equation
0 : map (+1) n = n

and can be produced by
>> fix ((0:) . map (+1))
[0,1,2,3,4,5,6,7,8,9,...]

The factorial numbers can be generated most easily if we look at the pair (n,f) where f is the nth factorial number -
x = [(0,1), (1,1), (2,2), (3,6), (4,24), (5,120), ...]

which are fixed if we take the pair (n,f) to (n+1, f*(n+1)) and then cons (0,1) to the start of the list. So they can be generated by
>> fix $ \xs -> (0,1) : map (\(n,f) -> (n+1,f*(n+1))) xs
[(0,1),(1,1),(2,2),(3,6),(4,24),(5,120),(6,720),(7,5040),...]

The fibonacci numbers can be generated similarly, as in user3237465's answer.
Generalizing the examples
All three examples here are essentially recursive functions transformed into corecursive streams, i.e. they have some initial state s and the values emitted by the stream are s, f s, f (f s) etc for some function f. The general method for doing this is the function iterate
iterate :: (a -> a) -> a -> [a]
iterate f x = x : iterate f (f x)

which can be defined in terms of fix -
iterate f x = x : map f (iterate f x)
            = (x:) . (map f) $ iterate f x
            = fix ((x:) . map f)

So any stream which repeatedly applies a function to some state can be written in terms of fix (though, of course, you could simply use iterate instead of fix -- a particular case of the rule that fix is not necessary in a language which allows recursive let expressions).
Non-stream examples
For an example that isn't a stream, consider binary trees with values at the branches -
data Tree a = Tip | Bin a (Tree a) (Tree a) deriving (Show)

If we want a binary tree whose nodes are labelled in breadth first order, note that we could fix such a tree by taking two copies of itself, and incrementing all of the values in the left- and right-branches by the appropriate amount, as defined by the following function -
fun :: (Num a) => Tree a -> Tree a
fun t = Bin 1 (incr 1 t) (incr 2 t)
  where
    incr n (Bin a l r) = Bin (a+n) (incr m l) (incr m r)
      where
        m = 2 * n

Using a simple function takeLevels to display just the initial portion of the tree, we then compute the fixed point as
>> takeLevels 3 $ fix fun
Bin 1 (Bin 2 (Bin 4 Tip Tip) (Bin 5 Tip Tip)) (Bin 3 (Bin 6 Tip Tip) (Bin 7 Tip Tip))

which is what we wanted.

A:

Fibonacci sequence, for example:
fibs = fix ((1:) . (1:) . (zipWith (+) <*> tail))

Or the forever function:
forever x = fix (x >>)

Or another variant of fibonacci sequence:
fibs :: State (Int, Int) [Int]
fibs = fix $ \loop -> do
    (x, y) <- get
    put (y, y + x)
    (x :) <$> loop

main = print $ take 15 $ fst $ runState fibs (1, 1)

prints [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610].


Q:

Is there a tool for tracing SQLs executed on Oracle

Is there a tool (that already comes with Oracle) for tracing SQLs that have been executed? In DB2 there is something called an 'event monitor' which I use to track the tables that have been updated. Is there an equivalent tool in Oracle?
I plan to

enable tracing
go on the website (that uses the db) and change an entry
disable tracing
see output file and record which table has been updated.

There is a table I am looking that should be updated when the entry is changed. I do not know what the name of the table is (and there are many tables), and so I need to trace the SQL executed to find out.
I have tried:
  ALTER SESSION SET sql_trace = true;
  -- go on website and change an entry
  ALTER SESSION SET sql_trace = false;

  tkprof the_trace_file.trc file.out EXPLAIN=system/manager SYS=no

However when following those steps above, no SQLs were recorded.
Is there a tool that Oracle provides? (I would like to avoid downloading external software)

A:

There is a table I am looking that
  should be updated when the entry is
  changed. I do not know what the name
  of the table is (and there are many
  tables), and so I need to trace the
  SQL executed to find out.

I'm thinking you are using the word "trace" here with another meaning than what is usually meant in the Oracle world.
You basically hit some button in the app, and by looking at what SQL queries are running, you want to find what table that code was referencing? Did I get it right?
In that case, you could have a look at v$sql, and look at columns SQL_TEXT and SQL_FULLTEXT.


Q:

Probability of an event

I am wondering if there is a way in Mathematica, a special function perhaps, which would return true or false based on a certain probability I give it. Like Prob[0.7] would return 1: 70% of the time and 0: 30% of the time. I could do something like this of course:
prob=10; (* 1% chance *)
val = RandomInteger[{1, 1000}];
If[val<= prob, True, False];

But this becomes slightly difficult when I need very specific probabilities like 0.21321312444. Or even variable probabilities which would come from a certain function returning different values every time step.

A:

Using built-in statistical functions (Discrete Univariate Distributions).
sampleBernoulli[p_, n_] := RandomVariate[BernoulliDistribution[p], n]

Then
sampleBernoulli[.7, 10]
(* {1, 0, 1, 0, 0, 0, 1, 1, 1, 1} *)

Hope this helps.

A:

Clear[prob]

prob[p_, n : _Integer : 1] := RandomChoice[{p, 1 - p} -> {1, 0}, n]

Total[prob[0.21321312444, 10^5]]/10.^5.

(*  0.21322  *)


Q:

dropdown values

I have the below code that display list of values from database in drop down. The query also selects Jt_JOB_Description. I would like to display the Jt_JOB_Description based on the JT_JOB_TITLE selected in Text Area. Help plz.
<select  name="jTitle" id="jTitle" style="background-color: #D8D8D8">
<%

Statement stt = conn.createStatement();
ResultSet rstt = stt.executeQuery("SELECT JT_JOB_TITLE, JT_JOB_DESCRIPTION FROM     uap.dbo.UAP_JOB_TITLE ORDER BY JT_JOB_TITLE");
 while (rstt.next()) {
%>
 <option value="<%=rstt.getString("JT_JOB_TITLE")%>">        <%=rstt.getString("JT_JOB_TITLE")%>
 </option>
<%
 }
 stt.close();
 rstt.close();
 %>
 </select>

   <textarea class="styled" rows="5" cols="12" name="jDesc" id="jDesc" ></textarea>

A:

Modify your code as given below
<select  name="jTitle" id="jTitle" style="background-color: #D8D8D8" onchange="setText(this)">
<%
String str="";
Statement stt = conn.createStatement();
ResultSet rstt = stt.executeQuery("SELECT JT_JOB_TITLE, JT_JOB_DESCRIPTION FROM uap.dbo.UAP_JOB_TITLE ORDER BY JT_JOB_TITLE");
while (rstt.next()) {
str+=rstt.getString(1)+"@"+rstt.getString(2)+"#";
%>
<option value="<%=rstt.getString("JT_JOB_TITLE")%>"><%=rstt.getString("JT_JOB_TITLE")%>
</option>
<%
}
stt.close();
rstt.close();
%>
</select>

<input type="hidden" name="txtHidStr" id="txtHidStr" value="<%=str %>" />

<textarea class="styled" rows="5" cols="12" name="jDesc" id="jDesc" ></textarea>

and wirte following javascript function
function setText(element){
var arr_main=document.getElementById("txtHidStr").value.split("#");
for(i=0;i<arr_main.length;i++)
{
     arr_val=arr_main[i].split("@");
     if(arr_val[0]==element.value)
     {
        document.getElementById("jDesc").innerHTML=arr_val[1];
        break;
     }
}
}


Q:

PHP and multi threading

I was wondering. If you have a PHP request and the PHP code calls a command line tool via exec..
Is the command line then processed in another thread than the one the PHP script is running under?
And if so are both shared over more than one core?

A:

As the manual suggests:

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

This might give you an idea that the process is not forked and runs on the main thread. PHP actually waits for the output to end and get the last line of the log.
However, there is a way to run your command in background:
nohup MY_COMMAND > /dev/null 2>&1 & echo $!

Since exec receives the value of the last line of the output, this will return the pid of the process and you will be able to kill it later on.

Also, as N.B. mentioned in a comment, you may use fastcgi_finish_request() function if you use fpm - FastCGI Process Manager.
That function gives the client an answer without stopping the script execution. For instance, this is how you send an e-mail without fpm:
mail($recipient, 'Subject', 'Hello, Kitty!');
echo 'Okay, we sent the e-mail';

And this is how you may send an email with fpm:
echo 'Okay, we sent the e-mail';
fastcgi_finish_request();
mail($recipient, 'Subject', 'Hello, Kitty!');

In this case the client will get the echoed text and the mail function will still run in the background.
Just do not forget to close your sessions with session_write_close(); before you use fpm ;)


Q:

How do you get speech dictated without adding it to a grammar list?

I'm new to Speech Recognition, and I'm working on a project that will receive a command from a recognizable list.
For example, I would say "Play song". The computer would ask the song title, and I can say it. It will then compare my answer to my music library and find it.
I know how to add recognizable grammar to the SpeechRecognizer object, how to make the computer speak, and how to play a song in iTunes. I cannot, however, figure out how to get it to dictate or listen and interpret something that isn't in the grammar list. Is there a method I'm missing? Or not yet been simplified by Microsoft? I have no code to show for this, as I am not even sure how to search for this particular idea.
Of course, I could have the program read my entire library, but that's not an optimal solution considering I have tens of thousands of songs. Thanks in advance!

A:

Speech recognition works by comparing the signal to grammars, so there really isn't a good way to get a result without a grammar.  Why not use the music library to generate the grammar list?  I'm sure the result will be much more satisfactory.  A really general grammar won't enable you to tell whether the user said "Madonna," "My Donna," or "Mad on a" with any sort of reliability.  You might want to narrow the grammars further by letting the user choose to say an artist, title or album before they say it.


Q:

How to ensure that byte[ ] is saved as a jpg image through an InputStream in java?

I am trying to save an image into an FTPServer using Apache Commons FTPClient.storeFile(...) method, which requires an InputStream. The image comes as a Byte[] at the beginning.
Here some code:
InputStream is = new ByteArrayInputStream(byteArray);
boolean  done = ftpClient.storeFile(remotePath, is);

However, when I download the uploaded image, it looks very strange and even though the dimensions are respected, the image does not look like it should.
The Image after uploading Looks like this:
Image after uploading
In reality I do not have access to the original Image but I know it is an Image of the open sea with blue water on it.
Thank you!

A:

So, as VGR! accurately pointed out, the Apache Commons ftpClient has two working modes, ASCII and binary mode. By default the ASCII mode is used and one must enforce the treatment of data as binary data explicitly via
    try {
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    }


Q:

How to customize the visible area of the scroll viewer's content

The ScrollViewer's default behavior is, that the content stops on the bottom of the ScrollViewer's view port:

I would like to change the behavior, so that the content can be scrolled to the top of the scroll ScrollViewer's view port:

a) Is it possible to configure the existing scroll viewer that way?
b) If not, what is the best way to achieve that behavior?

A:

Embed the scrollable content in a Grid with 3 rows. The scrollable content occupies the second row. The other two have the same Height of the ScrollViewer:
<ScrollViewer Height="50">
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="50"/>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="50"/>
    </Grid.RowDefinitions>

    <YourScrollableContent Grid.Row="1"/>
  </Grid>
</ScrollViewer>

I've no way to test it in order to see if this code is perfect, but I'm sure this can be a way :)
Maybe you can bind the Height of the 2 rows with the Height of the ScrollViewer:
<RowDefinition Height="{Binding Path=Height,
    RelativeSource={RelativeSource AncestorType=ScrollViewer}}"/>


Q:

error : can't read .... no such variable in TCL script using "after"

I am working in a TCL automation environent at my workplace.
I'm trying to run a delayed command in my script using "after".
The problem i encounter is that when i try to specify commands with variables inside a code block under an "after" , the vars are not recognized and i get an error message.
I'll quote the relevant parts of the code.
proc test_script1 {{bh0 0} ...more vars....} {
.
.
.
after [expr 20000]   {
   set some_value[ ns1::probe_TCP_connections $bh0 $main_duration 1  15]    }

puts "the value i got is $some_value"
}

And i seem to get an error:
can't read "some_value": no such variable
Can anyone suggets what is the problem , and how to oversome it?
thx

A:

You can capture the values of local variables with the help of apply (and it's advisable to use list to build callbacks when they get even slightly non-trivial). Since the body of an apply is a lambda expression with its own scope — a little nameless procedure — you have to use global in it to access state that will persist, and in any case after callbacks are called from the global namespace always (since the mechanism doesn't know how to keep arbitrary stack frames around for the duration of the asynchronous operation).
after 20000 [list apply {{bh0 main_duration} {
    global some_value
    set some_value [ns1::probe_TCP_connections $bh0 $main_duration 1 15]
}} $bh0 $main_duration]

global some_value
vwait some_value
puts "The value was changed to $some_value"

It's possible to get even more sophisticated, especially in Tcl 8.6 which has a coroutine system that can be used to hide the complexity of using continuation passing style programming.


Q:

pass text to an onclick function

I want to pass text element (a string) to an on click function:
document.getElementById("struct_list").innerHTML="
"+text;`

ClickStructList is defined as follow:
ClickStructList=function(text){
window.alert("click");
window.alert(text);
};

This doesn't work, firefox debug istelling me: "C is not defined", C is the value of text.
Thanks for any help
PS: I do not want to use jquery

A:

The quotation marks were missing in your call to ClickStructList ...
this works :
 var ClickStructList=function (text) {
  window.alert("click");
  window.alert(text);
 };

 var text="Hello World";
 document.getElementById("struct_list").innerHTML="
"+text;


Q:

Setting a clip on a seaborn plot

I am having trouble clipping a seaborn plot (a kdeplot, specifically) as I thought would be fairly simple per this example in the matplotlib docs.
For example, the following code:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

fig = plt.figure()
ax = fig.add_subplot(111, frameon=False, xticks=[], yticks=[])

random_points = np.array([p for p in np.random.random(size=(100, 2)) if 0 < p[0] < 1 and 0 < p[1] < 1])

kde = sns.kdeplot(random_points[:,0], random_points[:,1], ax=ax)

xmin, xmax = kde.get_xlim()
ymin, ymax = kde.get_ylim()

patch = mpl.patches.Circle(((xmin + xmax)/2, (ymin + ymax) / 2), radius=0.4)
ax.add_patch(patch)
kde.set_clip_path(patch)

Results in the following output:

I would like to clip this result so that the KDE contour lines do not appear outside of the circle. I haven't found a way to do it thus far...is this possible?

A:

Serenity's answer works for simple shapes, but breaks down for reasons unknown when the shape contains more than three or so vertices (I had difficulty establishing the exact parameters, even). For sufficiently large shapes the fill flows into where the edge should be, as for example here.
It did get me thinking along the right path, however. While it doesn't seem to be possible to do so simply using matplotlib natives (perhaps there's an error in the code he provided anyway?), it's easy as pie when using the shapely library, which is meant for tasks like this one.
Generating the Shape
In this case you will need shapely's symmetric_difference method. A symmetric difference is the set theoretic name for this cut-out operation.
For this example I've loaded a Manhattan-shaped polygon as a shapely.geometry.Polygon object. I won't covert the initialization process here, it's easy to do, and everything you expect it to be.
We can draw a box around our manhattan using manhattan.envelope, and then apply the difference. This is the following:
unmanhattan = manhattan.envelope.symmetric_difference(manhattan)

Doing which gets us to:

Adding it to the Plot
Ok, but this is a shapely object not a matplotlib Patch, how do we add it to the plot? The descartes library handles this conversion.
unmanhattan_patch = descartes.PolygonPatch(unmanhattan)

This is all we need! Now we do:
unmanhattan_patch = descartes.PolygonPatch(unmanhattan)
ax.add_patch(unmanhattan_patch)
sns.kdeplot(x=points['x_coord'], y=points['y_coord'], ax=ax)

And get:

And with a little bit more work extending this to the rest of the polygons in the view (New York City), we can get the following final result:


Q:

Why aren't directories removed from others' local repositories?

I have a project which I removed an entire directory on my local, committed the changes, and published to a new branch on the remote.
People who have already cloned the project checked out the branch and it appears to still contain that directory and all of its sub directories, but they are all empty.
People who have not already cloned the project do so, check out the branch locally, and everything is as I intended.
What causes this?

A:

Git does not version control directories, only files.
Directories are created by Git when a file needs to be put in it. When the file is removed, the directory will remain if anything is in it.


Q:

Taking JSON.stringify string output and copying into JSON.parse it Gives Unexpected token ' in JSON

I took and copied the string output from console.log(JSON.stringify(employee);) and pasted it into parse() but it fails:
//For the below I get Error: Unexpected token ' in JSON at position 1
const person = JSON.parse("{'id':0,'firstName':'Andy','subordinates':[{'id':1,'firstName':'James','subordinates':[{'id':3,'firstName':'Aubrey','subordinates':null}]},{'id':2,'firstName':'Collin','subordinates':null}]}");

However this does work:
// prints out person as a JS object just fine
const rawData = JSON.stringify(employee);
const person = JSON.parse(rawData);

I'm a little confused as to why the first fails.
const employee = {
      id: 0,
      firstName: "Andy",
      subordinates: [
        {
          id: 1,
          firstName: "James",
          subordinates: [
            {
              id: 3,
              firstName: "Aubrey",
              subordinates: null
            }
          ]
        },
        {
          id: 2,
          firstName: "Collin",
          subordinates: null
        }
      ]
    };

A:

you can use like this :
const person = JSON.parse('{"id":0,"firstName":"Andy","subordinates":[{"id":1,"firstName":"James","subordinates":[{"id":3,"firstName":"Aubrey","subordinates":null}]},{"id":2,"firstName":"Collin","subordinates":null}]}');

or if you dont want to change json data , you can use that :
let json_data = "{'id':0,'firstName':'Andy','subordinates':[{'id':1,'firstName':'James','subordinates':[{'id':3,'firstName':'Aubrey','subordinates':null}]},{'id':2,'firstName':'Collin','subordinates':null}]}";

json_data = json_data.replace(/'/g, '"');

const person = JSON.parse(json_data);

hope this topic help you .


Q:

JSON - data.items is undefined

I can not wrap in my data.items because it contains arrays of arrays, and suddenly I feel that it is lost.
data.items is undefined.
I use JQuery to complete with $.each.
My JSON listed below:
{
    "success": true,
    "name": "factors",
    "items": [
        {
            "name": "type de lieux",
            "value": {
                "appartement": "Appartement",
                "maison individuelle": "Maison individuelle"
            }
        },
        {
            "name": "surface",
            "value": {
                "79": "< 80",
                "81": "> 80"
            }
        }
    ]
}

I do this with jQuery, but I return the error message described above:
$.each(data['items'], function(i, item) {
    alert('oki');
});

What should I do as an amendment?
Thanking you in advance.

A:

If you want to iterate use -
var data = {"success":true,"name":"factors","items":[{"name":"type de lieux","value":{"appartement":"Appartement","maison individuelle":"Maison individuelle"}},{"name":"surface","value":{"79":"< 80","81":"> 80"}}]};

$(data.items).each(function(i, item) {
    alert(item.name+" : "+item.value);
});

Example - http://jsfiddle.net/rXETR/


Q:

Proving an integral relation (isotropic function)

In Hansen-McDonald's book Theory of Simple Liquids the following relation is often used:
We want to evaluate the integral
$$\int_V f(\vec r_1, \vec r_2) d \vec r_1$$
We observe that if the function $f$ is isotropic, i.e.
$$f(\vec r_1, \vec r_2) = f(\mid \vec r_1- \vec r_2 \mid) $$
then
$$\int_V f(\vec r_1, \vec r_2) d \vec r_1 = \int_V f(\mid \vec r_1- \vec r_2 \mid) d \vec r_1 =  f(r) \ V $$
where
$$V= \int_V d \vec r$$
This makes sense to me, because if the function only depends on the distance I can choose to fix $\vec r_1$ everywhere in the volume (obtaining a volume term) and I will be left with $f(r)=f(\mid \vec r_1- \vec r_2 \mid)$.
But how can I prove the last relation in a rigorous way? I guess it must be some kind of change of variables, but I cannot figure out which one.
Update
This relation is used for example in equation (2.5.15):

(notice that $\rho = N/V$. Also, $g(r) \to 1$ for $r\to \infty$)
I also just found out that a similar relation, which we can write as
$$\int_V \int_V f(\mid \vec r_1-\vec r_2\mid) d\vec r_1 d\vec r_2 = V \int_V f(r) d\vec r$$
is used in equation (2.5.18-19), with the following explanation:

(notice that in this case $v(r) \to 0$ for $r \to \infty$)
It would be also nice to start by proving this in two dimensions, i.e. for
$$\int_I \int_I f(\mid x-y\mid) dx dy \ \ \text{and} \ \ \int_I f(\mid x-y\mid) dy$$
where $I$ is a closed interval, even if I'm starting to suspect (see John Barber's answer) that this result is not rigorous.

A:

I think something must be wrong here. Counterexample:
Suppose
$$
f\left(\vec{r}_1, \vec{r}_2\right) =
f\left(\left| \vec{r}_1 - \vec{r}_2\right|\right) =
\exp\left(-\frac{1}{2}\frac{{\left|\vec{r}_1 - \vec{r}_2\right|}^2}{\epsilon^2}\right)
$$
for some small $\epsilon$. Suppose the length scale of $V$ is much larger than $\epsilon$, and consider the quantity
$$
g\left(\vec{r}_2\right) = \int_V d\vec{r}_1\, f\left(\vec{r}_1, \vec{r}_2\right)\, .
$$
The integrand is a narrow Gaussian centered at $\vec{r}_2$. If $\vec{r}_2$ is more than several multiples of $\epsilon$ away from the boundary of $V$, then essentially all of the Gaussian is integrated over, and
$$
g\left(\vec{r}_2\right) \approx {\left(2\pi \epsilon^2\right)}^{d/2}\, ,
$$
where $d$ is the dimensionality of the space.
If $\vec{r}_2$ is on the boundary of $V$, then about half the Gaussian is integrated over, and we have
$$
g\left(\vec{r}_2\right) \approx \frac{1}{2}{\left(2\pi \epsilon^2\right)}^{d/2}\, .
$$
These bear no resemblance to (what appears to be) the asserted relationship
$$
g\left(\vec{r}_2\right) = V\, f\left( \left| \vec{r}_2 \right| \right)\, .
$$
What section of H&M does this appear in? I've got a copy of it around here somewhere. I'm wondering if perhaps the actual relationship might be
$$
\int_V d\vec{r}_1 \int_V d\vec{r}_2\, f\left(\vec{r}_1-\vec{r}_2\right)
 = V \int_V d\vec{r}_1\, f\left(\vec{r}_1\right)\, ,
$$
which should be perfectly valid so long as $f$ is sufficiently strongly peaked or localized. Since it's H&M, I would imagine that $f$ is something like $f(r) = \exp\left[-U(r)/k_B T\right]$ or $f(r) = 1 - \exp\left[-U(r)/k_B T\right]$, where $U$ is an intermolecular potential?
Response to Update:
The thing to keep in mind is that there are some assumptions implicit in H&M that are relevant here. These integral identities don't apply to just any radial function, but only to the sort relevant in molecular thermodynamics. This assumes that the function $f(\vec{r})$ varies on a molecular length scale $\epsilon$, and that the domain of integration $V$ is more like a macroscopic length scale. So we have a radical difference of scales here. Outside a length scale $\epsilon$, the function $f$ will typically be either zero or constant. Under these assumptions, some of these integral "identities" are approximately true.
I'm not going to get into H&M Equations (2.5.15) and (2.5.18) copied above. They depend on the precise definition of the two-particle distribution function, which is beyond the scope of a math.stackexchange post.
I do want to address the last part of your update. Define:
$$
g(y) = \int_I dx\,  f(x - y)\, .
$$
Here $I$ is an interval of length $L$, and we assume that $f$ is compactly supported (more or less) over an interval of length on the order of $\epsilon$, a small number. An example would be:
$$
f(x) = \exp\left(-\frac{1}{2}\frac{x^2}{\epsilon^2}\right)\, .
$$
By the same argument as above,
$$
g(y) = \mathrm{constant} \approx \int_{-\infty}^{+\infty} dx\,  f(x)
$$
unless $y$ is within a distance of about $\epsilon$ of one of the boundaries of $I$. Thus the assertion in the original post is actually wrong, even for H&M-type functions, and isn't what is being used in the equations from H&M.
However:
\begin{align}
\int_I dy\, g(y) &\approx \int_I dy \int_{-\infty}^{+\infty} dx\,  f(x) \\
&\approx L \int_I dx\, f(x) \;+\; \text{An error of order $\epsilon$}\, .
\end{align}
Here I've implicitly assumed that the domain $I$ is sufficiently "centered" that
$$
\int_{-\infty}^{+\infty} dx\,  f(x) \approx \int_I dx\,  f(x)\, .
$$
As long as $f$ falls off sufficiently rapidly (i.e. don't try this with particles mediated by a Coulomb potential!), we can ignore the error term, and the "double integral" identity should approximately hold.
Update to address Equation 2.5.15 above:
Theory of Simple Liquids can be found here on Google Books. The relevant page is 31.
I've gone over the steps leading to equation 2.5.15, and I don't think it makes sense as written. I'm convinced it's a typo. 2.5.15 doesn't seem to follow from 2.5.14. I think the argument of the integral in 2.5.15 is supposed to be:
$$
g^{(2)}_N(r' + r, r') = g^{(2)}_N\left(\left|r' + r - r'\right|\right) = g^{(2)}_N\left(\left|r\right|\right) = g(r)
$$
That makes much more sense to me, and leads to the desired result.


Q:

How can I format the following console output in a class function implementation file?

The problem tells me:
"The class should have member functions to print the date in the following format"

3/15/13        //showShortDate
March 13, 2013 //showLongDate
15 March, 2013 //showEuroDate

The following in the function implementation file will not compile and give a "cout : undeclared identifier" error. I have #include <iostream> in the main program .cpp file.
// Date.cpp is the Date class function implementation file

    #include "Date.h"

    Date::Date(int m, int d, int y)
    {  month = m;
       day = d;
       year = y;
    }

    Date::Date()
    {
      month = 1;
      day = 1;
      year = 2001;
    }

    void Date::showShortDate()
    {
      cout << month << "/" << day << "/" << year;
    }
    void Date::showLongDate()
    {
       cout << month << " " << day << ", " << year;

    }
    void Date::showEuroDate()
    {
       cout << day << " " << month << " " << year;
    }

A:

Change it to:
void Date::showShortDate()
{
  std::cout << month << "/" << day << "/" << year;
}
void Date::showLongDate()
{
   std::cout << month << " " << day << ", " << year;

}
void Date::showEuroDate()
{
   std::cout << day << " " << month << " " << year;
}

Or do using namespace std; which i don't recommend.
include also in case you don't have already: #include <iostream>
Basically there are standard functions in C++ which are defined within a namespace.
That namespace is std if you want to access these functions you need to tell the compiler where these functions come from. You do that by adding std:: in front of the function. Or by telling it to use the std namespace ( again not recommended ).

Read this to understand the basic idea behind a namespace.


Q:

Redis - linux / Error when Installing redis on linux: `cc: command not found`

I wish to install redis on my red-hat environment. I do the following:
wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable
make

I got the next error:
make[3]: *** [net.o] Error 127
make[3]: Leaving directory `/tmp/redis-stable/deps/hiredis'
make[2]: *** [hiredis] Error 2
make[2]: Leaving directory `/tmp/redis-stable/deps'
make[1]: [persist-settings] Error 2 (ignored)
    CC adlist.o
/bin/sh: cc: command not found
make[1]: *** [adlist.o] Error 127
make[1]: Leaving directory `/tmp/redis-stable/src'
make: *** [all] Error 2

How can I fix it?

A:

You are trying to install redis from source code. What this process do is to compile and create executable on your machine and then install it. For doing this you need various tools like gcc etc. Best way is to install all of them together by installing that group. Run this from terminal
yum grouplist

This will show all groups available and then choose group you want to install or run directly
yum groupinstall 'Development Tools'

This will save you from other problems which might come in future while installing from source.

A:

for those of you who encounter this error
check this github issue
before make run this command
$ cd deps; make hiredis lua jemalloc linenoise

A:

Install build essential first

sudo apt-get install build-essential

then install the dependencies

cd deps
make hiredis lua jemalloc linenoise


Q:

How can I interact with a server in ObjectiveC without receiving a wrong response?

This is my first question here :)
I really need help with some servers and PHP stuff. Here's the question:
I have a NSMutableURLRequest that interacts with a php file like this:
    NSInteger userID = 4;

    NSString * logInString = [NSString stringWithFormat:@"id=%i&mode=HARD", userID];
    NSData * logInData = [logInString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%d", [logInData length]];

    NSMutableURLRequest * logInRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://myurl.lol/login.php"]];
    [logInRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [logInRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [logInRequest setHTTPMethod:@"POST"];
    [logInRequest setHTTPBody:logInData];

    [NSURLConnection sendAsynchronousRequest:logInRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        if ([data length] >0 && error == nil) {
            NSString * responseString = [NSString stringWithUTF8String:data.bytes];
            NSLog(@"%@", responseString);
            [self performSelectorOnMainThread:@selector(responseWasReceived:) withObject:responseString waitUntilDone:YES];
        }
        else if ([data length] == 0 && error == nil) {
            [self performSelectorOnMainThread:@selector(didNotReceivedResponse) withObject:nil waitUntilDone:YES];
        }
        else if (error != nil) {
            [self performSelectorOnMainThread:@selector(errorDidOccurred) withObject:nil waitUntilDone:YES];

            NSLog(@"Error = %@", error);
        }
    }];

And my PHP is like this:
include("database.php");

if ($_REQUEST['mode'] == 'HARD') {
    $query = mysql_query('SELECT COUNT(*) as total FROM users WHERE id = "' . $_REQUEST['id'] . '"');

    $fetch_username = mysql_fetch_object($query);
    $usernames_coincidences = $fetch_username -> total;

    if ($usernames_coincidences == 1) {
        exit("ACCESS GRANTED");
    } else {
        exit("USER DOES NOT EXIST");
    }
}

I should receive "ACCESS GRANTED" string, and sometimes it happens, but also sometimes I receive a bad response like "ACCESS GRANTED¿" or "ACCESS GRANTEDOL".
What's the problem? Do you think I should use Synchronous Request inside a method and perform it with performSelector:inBackground:?

A:

You're attempting to construct responseString with raw data that is not necessarily NULL-terminated.
Instead of this:
[NSString stringWithUTF8String:data.bytes];

use this instead:
[[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding];

Note that I'm not taking into account whether you're using ARC or not. Your original call produced an autoreleased value; mine does not; be sure you don't wind up leaking.


Q:

Best design principle in java while retrieving data from multiple tables

Consider the following situation. I have 3 tables in a resource planning project(created using mysql)

raw_materials (stores details about all raw materials)
procurement_orders (stores details about all details about requests sent to vendors for sending us the quotations. This table references the raw_materials table.)
quotations (contains details about all quotations sent by vendors to us. This table references the procurement_orders table).

I have created dbManagers for each of them using java which specialize in storing,retrieving,deleting data from respective tables.
My question is if i want to retrieve data which has to needs data from other tables, what is the best way to do it. eg:I want quotations of all raw_materials having stock below x. then according to me there are two ways

i write it in dbManager for rawMaterials. The flaw with this technique is it tries to access data out of its domain directly.
in dbManager of of raw_Materials create instances of other dbManagers. The flaw here is the iterations will large. As in if there are 300 raw materials, i will have to call method of the procurement_request's dbManager 300 times. If it returns multiple values we will again have to call dbMnager of quatations many no. of times(many of them will be unwanted) affecting performance.

My question is what is the best way to design it in a proper oo way without hitting the performance.

A:

This is a rather larger question than can easily be handled quickly, but aligning java classes to tables is not necessarily a good approach, precisely because as you note, some things naturally involve multiple tables in complex relations.
I'd recommend starting by looking at Martin Fowler's book Patterns of Enterprise Application Architecture.
.
There are also some notes on the patterns in this book at his website.
Your usage most nearly resembles Table Data Gateway.  Following this pattern, it would be perfectly reasonable to have methods in each of your dbManager classes that retrieves data from its associated table but involves another table as part of a where clause.
You might also want to consider Object-relational mapping as implemented for instance by Hibernate.


Q:

Is there SWT Combo Box with any Object as data and LabelProvider for display?

I'm searching for an implementation of a Combo Box in SWT that will allow me to set the the entries in it with a list of any Object, in a similar way to Trees and Tables.
Ideally I want the String when dropped down to be able to be different to the final String once selected. IE a drop down to select a person that shows their age next to their name in the list, but only their name when selected and placed in the box.
All I can find that exists are String based Combo Boxes with no way of describing different display options, so I guess i's going to have to build a new component if I want the thing to work, but I was hoping someone has already implemented such a thing (since I've seen this sort of functionality in some applications) and I just can't find it?
I hope to create something like this.

A:

The JFace ComboViewer seems to be what you want. It is backed by a ModelProvider which holds your Objects. A LabelProvider is used to display the text inside the combo.
Here is an excellent tutorial by Vogella.
Here is an example that does what you want. It basically saves the current combo selection if a boolean of the displayed objects:
public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());

    final ComboViewer viewer = new ComboViewer(shell, SWT.READ_ONLY);

    viewer.setContentProvider(ArrayContentProvider.getInstance());

    /* if the current person is selected, show text */
    viewer.setLabelProvider(new LabelProvider() {
        @Override
        public String getText(Object element) {
            if (element instanceof Person) {
                Person current = (Person) element;

                if(current.isSelected())
                    return current.getName();
                else
                    return "";
            }
            return super.getText(element);
        }
    });

    final Person[] persons = new Person[] { new Person("Baz"),
            new Person("BazBaz"), new Person("BazBazBaz") };

    viewer.setInput(persons);

    /* within the selection event, tell the object it was selected */
    viewer.addSelectionChangedListener(new ISelectionChangedListener() {
        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection selection = (IStructuredSelection) event.getSelection();
            Person person = (Person)selection.getFirstElement();

            for(Person p : persons)
                p.setSelected(false);

            person.setSelected(true);

            viewer.refresh();
        }
    });

    viewer.setSelection(new StructuredSelection(viewer.getElementAt(0)), true);

    shell.pack();
    shell.setSize(200, shell.getSize().y);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}

public static class Person {
    private String name;

    /* this will be true for the selected person */
    boolean isSelected;

    public Person(String name) {
        this.name = name;
        this.setSelected(false);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean isSelected) {
        this.isSelected = isSelected;
    }

}

A:

Many thanks to Baz for putting me on the right track and providing me with some initial code. But having taken all this in I wanted something cleaner to use in my RCP view itself and also though a generic instance of a combo box would be a nice to have in future, so I've wrapped all the boilerplate stuff in a new class that you can use like this:
    List<Person> persons = new ArrayList<Person>();
    persons.add(new Person("Baz",26));
    persons.add(new Person("Glen",27));
    persons.add(new Person("Jimmy",18));

    TypedComboBox<Person> box = new TypedComboBox<Person>(parent);

    box.addSelectionListener(new TypedComboBoxSelectionListener<Person>() {

        @Override
        public void selectionChanged(TypedComboBox<Person> typedComboBox,
                Person newSelection) {
            System.out.println(newSelection);
        }
    });

    box.setLabelProvider(new TypedComboBoxLabelProvider<Person>() {

        @Override
        public String getSelectedLabel(Person element) {
            return element.getName();
        }

        @Override
        public String getListLabel(Person element) {
            return element.getName() + " | " + element.getAge();
        }
    });

    box.setContent(persons);

    box.selectFirstItem();

For my view where I'm going to need multiple selection boxes with various objects I am much more happy using the typed box as I'm not casting stuff and reproducing boilerplate code in the body of the view's code.
You don't have to set a label provider if you just want the toSting() method used, otherwise there are two labels to provide, one for the selected item, and one for all the others.
Just in case anyone stumbles upon this question with the same issue as me here's my code, feedback would be greatly appreciated.
import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class TypedComboBox<T> {

    private ComboViewer viewer;
    private TypedComboBoxLabelProvider<T> labelProvider;
    private List<T> content;
    private List<TypedComboBoxSelectionListener<T>> selectionListeners;
    private T currentSelection;

    public TypedComboBox(Composite parent) {
        this.viewer = new ComboViewer(parent, SWT.READ_ONLY);
        this.viewer.setContentProvider(ArrayContentProvider.getInstance());

        viewer.setLabelProvider(new LabelProvider() {
            @Override
            public String getText(Object element) {
                T typedElement = getTypedObject(element);
                if (labelProvider != null && typedElement != null) {
                    if (typedElement == currentSelection) {
                        return labelProvider.getSelectedLabel(typedElement);
                    } else {
                        return labelProvider.getListLabel(typedElement);
                    }

                } else {
                    return element.toString();
                }
            }
        });

        viewer.addSelectionChangedListener(new ISelectionChangedListener() {
            @Override
            public void selectionChanged(SelectionChangedEvent event) {
                IStructuredSelection selection = (IStructuredSelection) event
                        .getSelection();
                T typedSelection = getTypedObject(selection.getFirstElement());
                if (typedSelection != null) {
                    currentSelection = typedSelection;
                    viewer.refresh();
                    notifySelectionListeners(typedSelection);
                }

            }
        });

        this.content = new ArrayList<T>();
        this.selectionListeners = new ArrayList<TypedComboBoxSelectionListener<T>>();
    }

    public void setLabelProvider(TypedComboBoxLabelProvider<T> labelProvider) {
        this.labelProvider = labelProvider;
    }

    public void setContent(List<T> content) {
        this.content = content;
        this.viewer.setInput(content.toArray());
    }

    public T getSelection() {
        return currentSelection;
    }

    public void setSelection(T selection) {
        if (content.contains(selection)) {
            viewer.setSelection(new StructuredSelection(selection), true);
        }
    }

    public void selectFirstItem() {
        if (content.size()>0) {
            setSelection(content.get(0));
        }
    }
    public void addSelectionListener(TypedComboBoxSelectionListener<T> listener) {
        this.selectionListeners.add(listener);
    }

    public void removeSelectionListener(
            TypedComboBoxSelectionListener<T> listener) {
        this.selectionListeners.remove(listener);
    }

    private T getTypedObject(Object o) {
        if (content.contains(o)) {
            return content.get(content.indexOf(o));
        } else {
            return null;
        }
    }

    private void notifySelectionListeners(T newSelection) {
        for (TypedComboBoxSelectionListener<T> listener : selectionListeners) {
            listener.selectionChanged(this, newSelection);
        }
    }

And the label provider interface.
public interface TypedComboBoxLabelProvider<T> {

    public String getSelectedLabel(T element);

    public String getListLabel(T element);

}

And the selection listener:
public interface TypedComboBoxSelectionListener<T> {

    public void selectionChanged(TypedComboBox<T> typedComboBox, T newSelection);
}


Q:

Load Content On Tab Open Using Spry

Is it possible to load the content of a Spry tab when the tab is opened, rather than load all the content of all the tabs in the beginning?
I would prefer accomplishing this without the use of an iframe.

A:

A simple enough way would be to start all the tabs off with empty content, except the one that loads with the page.
From what I see from a simple view source they have this structure.

Tab 1

Tab 2

Tab 3

Tab 4

 Tab 1 Content

 Tab 2 Content

Tab 3 Content

More Content

More Content

 Tab 4 Content

Attach onclick event listeners on #tp1.TabbedPanelsTab, and link it to an ajax request. When the user clicks the tab, it will start the request and populate the form.
It may be easier to add an ID that references where to get the data for that particular form. For example, tab one could have ID "salesRecords". Lets also say that you get all your data from getContent.php. Now when the user actives the onclick event, you use an ajax request to fetch the information from url "getContent.php?id="+this.id, which will of course use the query string to return the revelvant information.


Q:

SQL Server: Sanitizing @param against injection attacks

For the sake of argument, let's just say I have to create a local variable containing a SQL query that has an INSERT:
 DECLARE @insert NVARCHAR(MAX)
 SELECT @insert = 'INSERT INTO [dbo].[' + @table + '] VALUES...
 EXEC (@insert)

This INSERT is also going to contain a column value:
 DECLARE @insert NVARCHAR(MAX)
 SELECT @insert =
  'INSERT INTO [dbo].[' + @table + '] VALUES (N''' + @message + ''')'
 EXEC (@insert)

Now, I'm obviously concerned about an injection attack, and would like to ensure that @message's value can't make @insert's value malicious or malformed as a query to EXEC.
This brings us to my question: is escaping the ' characters in @message sufficient? Are there any other characters that could appear in @message that could escape out?
Example:
 DECLARE @insert NVARCHAR(MAX)
 SELECT @message = REPLACE(@message,'''','''''')
 SELECT @insert =
  'INSERT INTO [dbo].[' + @table + '] VALUES (N''' + @message + ''')'
 EXEC (@insert)

(When I say "have to", this is because my query is in a stored procedure, and this stored procedure accepts @table, which is the destination table to INSERT into. I'm not interested in discussing my architecture or why the table to INSERT into is "dynamically" specified via a procedure parameter. Please refrain from commenting on this unless there's another way besides EXEC()ing a query to specify a table to INSERT into when then table name is received as a procedure parameter.)

A:

Use sp_executesql and the built-in quotename(). This article, The Curse and Blessings of Dynamic SQL, is pretty much the definitive reference.


Q:

Sorting the array using keys

I have an array that carries all the routes of my framework. It looks like this
$routes=[
    '/[:name]/[:name]/[:name]'   =>['ALL','dynamic','blog']

    '/news'                      =>['ALL','static','news'],

    '/about'                     =>['ALL','static'],

];

I want to sort the array based on

number of slashes(/)
number of dynamic parameters

in the keys. How will I accomplish it?

A:

Two things are important here. You need to preserve the key to value relationship. That implies that you use array sorting functions like uasort() instead of usort(). The next thing is, that you have to use a user-defined sorting function, which expresses your sorting algo. It describes how you want to sort your routes.
It's also possible to sort by keys: then array_flip() is your friend.
You might use this for starting:
<?php

$routes=[
    '/about'                     =>['ALL','static'],
    '/[:name]/[:name]/[:name]'   =>['ALL','dynamic','blog'],
    '/news'                      =>['ALL','static','news'],
];

function sortShortestRoute($a, $b)
{
    return (count($a) < count($b)) ? -1 : 1;
}

function sortStaticBeforeDynamic($a, $b)
{
    if($a[1] === 'static' && $b[1] === 'static') {
        return 1;
    }

    if($a[1] === 'dynamic' && $b[1] === 'dynamic') {
        return -1;
    }

    if ($a[1] === $b[1]) {
        return 0;
    }
}

// first sort
uasort($routes, 'sortStaticBeforeDynamic');

var_dump($routes);

// second sort
uasort($routes, 'sortShortestRoute');

var_dump($routes);


Q:

Show/Hide Multiple Table Columns in Javascript

I need to show/hide multiple related columns using either just CSS or javascript in an HTML table using checkboxes. For instance, if the "Beer" checkbox is checked I need to show all three columns related to Beer, if it is unchecked hide all three columns.

Show: <input type="checkbox">Beer</input>
<input type="checkbox">Wine</input>
<input type="checkbox">Vodka</input>
<input type="checkbox">Whiskey</input>

    BeerCol1
    BeerCol2
    BeerCol3
    WineCol1
    WineCol2
    WineCol3
    VodkaCol1
    VodkaCol2
    VodcaCol3
    WhiskeyCol1
    WhiskeyCol2
    WhiskeyCol3

           Beer Value 1
           Beer Value 2
           Beer Value 3
           Wine Value 1
           Wine Value 2
           Wine Value 3
           Vodka Value 1
           Vodka Value 2
           Vodka Value 3
           Whiskey Value 1
           Whiskey Value 2
           Whiskey Value 3

           Beer Value 4
           Beer Value 5
           Beer Value 6
           Wine Value 4
           Wine Value 5
           Wine Value 6
           Vodka Value 4
           Vodka Value 5
           Vodka Value 6
           Whiskey Value 4
           Whiskey Value 5
           Whiskey Value 6

A:

If you can add attributes, try this:

#beer:checked ~ table .beer,
#whiskey:checked ~ table .whiskey,
#wine:checked ~ table .wine,
#vodka:checked ~ table .vodka {
  visibility: visible;
}

th, td {
  visibility: hidden;
}
Show:
<input id="beer" name="beer" type="checkbox"/>
Beer
<input id="wine" name="wine" type="checkbox"/>
Wine
<input id="vodka" name="vodka" type="checkbox"/>
Vodka
<input id="whiskey" name="whiskey" type="checkbox"/>
Whiskey

  BeerCol1
  BeerCol2
  BeerCol3
  WineCol1
  WineCol2
  WineCol3
  VodkaCol1
  VodkaCol2
  VodcaCol3
  WhiskeyCol1
  WhiskeyCol2
  WhiskeyCol3

  Beer Value 1
  Beer Value 2
  Beer Value 3
  Wine Value 1
  Wine Value 2
  Wine Value 3
  Vodka Value 1
  Vodka Value 2
  Vodka Value 3
  Whiskey Value 1
  Whiskey Value 2
  Whiskey Value 3

  Beer Value 4
  Beer Value 5
  Beer Value 6
  Wine Value 4
  Wine Value 5
  Wine Value 6
  Vodka Value 4
  Vodka Value 5
  Vodka Value 6
  Whiskey Value 4
  Whiskey Value 5
  Whiskey Value 6


Q:

Afinal para que serve a função repr no python?

Sou meio novato em python e queria saber para que realmente serve essa função tão confusa, procurei em varios sites porém nenhum tem realmente dizendo para que serve ela

A:

__repr()__ serve para representar um objeto como uma string. Não precisa ser chamado diretamente. Toda vez que o Python precisa resolver um objeto como string, __repr__() será chamado automaticamente.
Vários tipos de objetos implementam __repr__() por padrão. Para objetos, normalmente __repr__() devolve a descrição e a referência em memória para o objeto.
A grande vantagem de __repr__() é justamente poder reescrevê-lo, como fiz aqui. Ao invés de escrever o objeto como <tipo + referência>, você pode formatar sua string da maneira como bem entender:
class MeuObjeto(object):
    def __init__(self):
        self.valor1 = 1
        self.valor2 = "2"

    def __repr__(self):
        return str(self.valor1) + ", " + self.valor2

Teste:
>>> o = MeuObjeto()
>>> o
1, 2

A:

O repr chama o método interno __repr__ do objeto. A ideia dele é retornar uma representação como string de qualquer objeto - mas pensando antes no programador do que no usuário final do programa. Sobretudo é o repr que é chamado para cada resultado de expressão quando usamos o Python no modo interativo.
Assim, por exemplo, para uma string numa variável a, repr(a) retorna a string, mas com aspas simples em volta. Em contraste, str(a) mostra o objeto como string, mas numa forma que seja amigável de ser mostrada para o usuário, quando o programa estiver em execução. (Ou seja, o conteúdo da string, sem as aspas). Veja a diferença:
>>> a = "maçã"
>>> a  # internamente, o Python chama o "a.__repr__"
'maçã'
>>> print(a) # internamente, o Python (o código no "print") chama "a.__str__"
maçã

Via de regra, para objetos simples, built-in, havia a idaia de que se você copiasse a saída do repr e colasse como texto num terminal Python ou programa, você recriaria o objeto inicial de volta. Isso vale para strings, listas, dicionários, tuplas e sets - e você pode criar reprs de seus próprios objetos de forma que também valha pra eles. Mas o __repr__ padrão mostra o nome da classe e o ID da instância (que no Python é igual o endereço de memória do objeto, mas isso é um detalhe de implementação): ou seja, não é possível recriar o objeto "repr"esentado por padrão, mas pode-se distinguir uma instância de outra olhando-se os seus reprs no terminal.
Diferença entre __repr__ e  repr
Por fim, vale notar que todo objeto em Python tem um método __repr__ - por que o o object, raiz de todos os objetos em Python tem um - e esse método é chamado automaticamente em várias situações: para ter uma forma de texto de um objeto para uma sessão interativa de Python, uma representação de texto a ser incluída de forma recursiva numa representação de texto de outro objeto, que contenha o objeto inicial, e algumas outras.
Já o método "built-in" repr é a forma de se chamar explicitamente os __repr__ de um objeto quando queremos fazer isso. Assim como o len pode chamar o método __len__ e também para hash e __hash__, next e __next__ - a idéia é que essas funções built-in funcionem praticamente como operadores unários para acessar essas funcionalidades que os objetos tem e que são escritas na forma de métodos com os "nomes mágicos", com dois underscores. (Em textos não oficiais - como e-mails, cursos, e tutorais, você vai ver esses métodos sendo chamados de métodos "dunder" - uma contração de "double-underscore".)
E por fim, vale dizer que quando é solicitada a representação como string de um objeto, com str, o Python busca primeiro o método __str__ - mas ao contrário do __repr__ nem todos os objetos tem um método __str__padrão. (A classe object não implementa __str__) então a função built-n str ao não encontrar o  __str__ chama o __repr__ do objeto para ter sua representação como string.  Esse é um dos motivos de ser preferível chamar os métodos built-in a chamar os métodos "dunder" diretamente - mesmo que para o repr não haja quase nenhuma diferença entre fazer uma coisa e outra.
Em Python2 tinhamos agravantes do tipo: o método __repr__ sempre tinha que retornar uma string, não um texto unicode. E os objetos, além do método __str__ podiam implementar também o __unicode__. Ademais, o repr de strings transformavam qualquer caractere não ASCII em uma sequência de escape do tipo "\0xPython 3 simplificou bastante tudo isso.


Q:

How to track down segmentation fault in Linux?

My server went down suddenly and the ISP supports says it may have had a segmentation fault. I am wondering how to track down and possibly fix this so it will not occur again?
Thanks

A:

Such segfaults are usually logged in the system's syslog facility. The exact name of which changes by distro, though dmesg should have it if it's recent enough; it'll be in /var/log one way or the other, though.
Interpreting the message will be another story entirely. But at least you'll know what faulted.


Q:

Don't display icon on MenuBar in Android

I'm building an app with AndroidStudio. I want to display an ActionBar in my application.
I want to add a menu into my AppCompactActivity. This is the menu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- Search, should appear as action button -->
    <item android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_save"
        android:showAsAction="always"
        android:title="Salva"/>
</menu>

This is the layout that I can see from Android Studio preview.

This is my AppCompactActivity:
public class setting extends AppCompatActivity{
    public Program program;
    public TextView textTargetUri;
    public TextView labelUrl;
    public ImageView targetImage;
    private static final int SELECT_PICTURE = 1;

    private String selectedImagePath;
    private ImageView img;
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting);
        img = (ImageView)findViewById(R.id.ImageView01);

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_setting, menu);
        return super.onCreateOptionsMenu(menu);
    }
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
        case R.id.action_search:
            getSchermataHome();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}

But this is the layou that I can see:

How can I fixed it?

A:

Try using the following code
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/action_search"
    android:icon="@android:drawable/ic_menu_save"
    android:title="Salva"
    app:showAsAction="ifRoom|always"/>
</menu>

change always to ifRoom|always with app attribute


Q:

Can an anonymous method in C# call itself?

I have the following code:
class myClass
{
private delegate string myDelegate(Object bj);

protected void method()
   {
   myDelegate build = delegate(Object bj)
                {
                    var letters= string.Empty;
                    if (someCondition)
                        return build(some_obj); //This line seems to choke the compiler
                    else string.Empty;

                };
   ......
   }
}

Is there another way to set up an anonymous method in C# such that it can call itself?

A:

You can break it down into two statements and use the magic of captured variables to achieve the recursion effect:
myDelegate build = null;
build = delegate(Object bj)
        {
           var letters= string.Empty;
           if (someCondition)
               return build(some_obj);
           else string.Empty;
        };

A:

If you're creating a recursive function, I'd recommend avoiding anonymous delegates.  Just create a method and have it call itself recursively.
Anonymous methods are meant to be anonymous - you shouldn't be calling them by name (non-anonymously).

A:

Anonymous Recursion in C# has a terrific discussion on this topic.

Recursion is beautiful and lambdas are
  the ultimate abstraction.  But how can
  they be used together?  Lambdas are
  anonymous functions and recursion
  requires names...

Since this popped up again, here's an example of using the Y-combinator:
// This is the combinator
public static Func<A,R> Y<A,R>( Func<Func<A,R>, Func<A,R>> f )
{
    Func<A,R> g = null;
    g = f( a => g(a) );
    return g;
}

Here's a usage of it to call an anonymous, recursive function ...
Func<int,int> exp = Y<int,int>( e => x => ( x <=1 ) ? 1 : x * e( x - 1 ) );
Console.WriteLine( exp(5) );

You will note that if you do not use the Y-combinator and set up the recursion with just the delegate, you do not get correct recursion.  For example ...
// This is BAD. Do not do this!
Func<int,int> badRec = null;
badRec = x => ( x <= 1 ) ? 1 : x * badRec( x - 1 );

But everything works fine ...
Console.WriteLine( badRec(5) );

// Output
// 120

But try this ...
Func<int,int> badRec = null;
badRec = x => ( x <= 1 ) ? 1 : x * badRec( x - 1 );

Func<int,int> badRecCopy = badRec;

badRec = x => x + 1;

Console.WriteLine( badRec(4) );
Console.WriteLine( badRecCopy(5) );

// Output
// 5
// 25

What?!?
You see, after the line badRec = x => x + 1;, the delegate you actually have is this ...
badRecCopy = x => ( x <= 1 ) ? 1 : x * ( (x+1)-1 );

So, badRec is incrementing the value by 1 which we expect (4+1=5), but badRecCopy is now actually returning the square of the value (5*( (5+1)-1 ) which we almost certainly did not expect.
If you use the Y-combinator, it will work as expected ...
Func<int,int> goodRec = Y<int,int>( exp => x => ( x <=1 ) ? 1 : x * exp( x - 1 ) );
Func<int,int> goodRecCopy = goodRec;

And you get what you expect.
goodRec = x => x + 1;

Console.WriteLine( goodRec(4) );
Console.WriteLine( goodRecCopy(5) );

// Output
// 5
// 120

You can read more about the Y-combinator (PDF Link).


Q:

How to get backends to actually do anything - GAE Python

I'm trying to get a backend in Google Appengine to run a task from the taskqueue. It runs without errors, but the task is not performed. I've found the documentation extremely confusing.
My cron.yaml:
- description: backend test
  url: /send_to_backend
  schedule: every 2 minutes

My app.yaml:
- url: /send_to_backend
  script: test.app
  login: admin

My backends.yaml:
- name: backendtest
  class: B1

My queue.yaml:
total_storage_limit: 500M
queue:
    - name: test
      rate: 1/s
      max_concurrent_requests: 1

My handlers in main.py:
class BackendHandler(webapp2.RequestHandler):
    def get(self):
    taskqueue.add(url='/test', target='backendtest')

class TestHandler(webapp2.RequestHandler):
    def get(self):
        test.test()

The function that does the actual work, in test.py:
def test():
    company = Company()
    company.name = "Advanced Micro Devices, Inc"
    company.exchange = "NASDAQ"
    company.put()

AMD is never entered into the db, and I'm at a loss. Am I even doing this the right way? Do backends and taskqueues go together like this?

A:

Yes, backends and task queues go together like this.
Unfortunately you didn't post completely runnable example so it's hard to say how many fixes you need. One fix that you definitely need is change get -> post in TestHandler (queue tasks processing is done by POST)
Below there is fully runnable and working version of your example. Do not forget that "The development server doesn't automatically run your cron jobs", so try it with curl in dev environment:
app.yaml
application: stackoverflow-21225722
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:

- url: /.*
  script: main.app
  login: admin

backends.yaml
backends:
- name: backendtest
  class: B1

cron.yaml
- description: backend test
  url: /send_to_backend
  schedule: every 2 minutes

main.py
from google.appengine.api import taskqueue
import test
import webapp2

class BackendHandler(webapp2.RequestHandler):
    def get(self):
      taskqueue.add(url='/test', target='backendtest')

class TestHandler(webapp2.RequestHandler):
    def post(self):
       test.test()

app = webapp2.WSGIApplication([
    ('/send_to_backend', BackendHandler),
    ('/test', TestHandler)
], debug=True)

queue.yaml
total_storage_limit: 500M
queue:
    - name: test
      rate: 1/s
      max_concurrent_requests: 1

test.py
from google.appengine.ext import ndb

class Company(ndb.Model):
    name = ndb.StringProperty()
    exchange = ndb.StringProperty()

def test():
    company = Company()
    company.name = "Advanced Micro Devices, Inc"
    company.exchange = "NASDAQ"
    company.put()


Q:

Yii2 currency format : difference between localhost and server

I have PHP5/Yii2 application deployed on Nginx with i18n in place.
I have DEV and PROD servers both running Debian 3.2.73-2+deb7u2 x86_64.
Yii configuration is repo-synced, envirnoment specific settings in
main-local.php do not have anything to do with localization.
This line:
Yii::$app->formatter->asCurrency($invoiceLine->amount,$invoice->currency);
gives different result in DEV and PROD:
DEV: 100,00 €
PROD: EUR 100,00
I cannot find what setting would make PROD behave the same way as DEV. I do not want any solution that formats amount explicitly in yii code. I just want to know what I must do to have the same configuration on both servers.

A:

This simply means you need to enable PHP internationalization extension (aka intl) on your prod server : http://php.net/manual/en/book.intl.php
Read more about \yii\i18n\Formatter::asCurrency() :

This function does not require the PHP intl extension to be installed to work, but it is highly recommended to install it to get good formatting results.

Read more about PHP internationalization extension installation.
For example, to install it on Debian :
sudo apt-get install php5-intl

Don't forget to restart your web server after.


Q:

Using Views to Display Taxonomy Terms Along with a single image field of the latest content type that has that taxonomy term

Let's say I have the following content type called Gallery that has an image field and a term reference field that can contain multiple terms from a single vocabulary.
In addition, I have several contents of these content types that share terms.
Would it be possible to create a view so that it satisfies the following conditions?

List all terms from a certain vocabulary
Have each term accompanied by an image (from the image field) from only the Gallery content type that uses that term
Term and Image should be listed once. If the term is being used by more than one Gallery content, the term should appear with the image from the latest content using that specific term.

The first two conditions are very straightforward to accomplish, independently. But once I try to accomplish both at the same time, I end with a display of all images paired with a single term it's associated with.
If that image is tagged with three different terms, then that same image appears three times, each instance using each of the terms.
Further, if one term is used for x number of different content, then that term will appear x number of times.
Was just wondering if there's a way to set it up so that it's 1 term, 1 image (preferably from the latest content type).

A:

Apparently there's a module called Views distinct that would eliminate duplicate entries due to having one field having the same values.


Q:

How can I move a  continuously at every given time-interval?

This is my code :
<!DOCTYPE html>

BELLA

The problem is that the div moves only ONE time. Why it isn't running continuosly ?

A:

You need to increment margin value to move div like this -

var myDiv = document.getElementById("a");
var myVar = setInterval(spostaDiv, 1000);
var margin = 0;

function spostaDiv() {
  margin += 10;
  myDiv.style.marginLeft = margin + "px";
}

BELLA


Q:

Using prototype with Jquery

Is there any way of using prototype to coexist with Jquery.
What i mean is not Jquery with prototype with the Jquery NoConflict tag but the other way around.
I have to override prototypes utility methods to coexist with other libraries?
I have no control over the Jquery Scripts

A:

When jQuery is included, it takes a copy of whatever is defined as $ and stores a reference to it. When you use jQuery.noConflict it restores that reference, and returns jQuery which allows you to "rename" jQuery.
If you want to rename Prototype, that should be entirely possible.
// 1. include Prototype
//    $ == Prototype
// 2. include jQuery
//    $ == jQuery

var jq = jQuery.noConflict();
var $p = $;
$ = jq;

// now, $ == jQuery
// and $p == Prototype


Q:

Netstat -ban (or -oan) equivalent in .NET

I'd like to know if a particular process is using a given port, i.e. netstat -ban. I came across using IPGlobalProperties to get the list of active connections, but this doesn't seem to include process information.
It would be nice if there exists some class in C# that lets me do this programmatically. Ideally, I wouldn't have to pipe the cmd shell Process output.

A:

Please see this question...
Which PID listens on a given port in c#
Basically you PInvoke GetExtendedTcpTable()


Q:

Redirect to "finish_sign_up" when Users subscribe with Omniauth Facebook

I installed Facebook signup with the gem 'Omniauth' and now Users can connect with it. And I use Devise in my website.
I want to know how I have to redirection path like finish sign up  after Users are connected with Facebook because they have to fill a form with specific information.
Do I add a new condition in an existing controller file? I created one which names omniauth_callbacks_controller.rb
and the code is:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    user = User.find_for_facebook_oauth(request.env['omniauth.auth'])

    if user.persisted?
      sign_in_and_redirect user, event: :authentication
      set_flash_message(:notice, :success, kind: 'Facebook') if is_navigational_format?
    else
      session['devise.facebook_data'] = request.env['omniauth.auth']
      redirect_to new_user_registration_url
    end
  end
end

And I try to do this
if user.persisted?
      sign_in_and_redirect user, event: :authentication
      set_flash_message(:notice, :success, kind: 'Facebook') if is_navigational_format?
user.thing_you_want_to_check.blank?
     redirect_to finish_sign_up_path

    else
      session['devise.facebook_data'] = request.env['omniauth.auth']
      redirect_to new_user_registration_url
    end
  end
end

A:

add a condition that checks whether the fields have been filled out in your sessions controller create action:
def create
  user = User.from_omniauth(env["omniauth.auth"])
  session[:user_id] = user.id
  if user.thing_you_want_to_check.blank?
     redirect_to finish_sign_up_path
  else
    redirect_to root_url, notice: "Signed In!"
  end
end

EDIT using the updated code you provided:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

def facebook
    user = User.find_for_facebook_oauth(request.env['omniauth.auth'])
if user.persisted? && user.some_field.blank?
   redirect_to # put the path you want them to go to here
elsif user.persisted?
  sign_in_and_redirect user, event: :authentication
  set_flash_message(:notice, :success, kind: 'Facebook') if is_navigational_format?
else
  session['devise.facebook_data'] = request.env['omniauth.auth']
  redirect_to new_user_registration_url
end

end
end
The some_field should be the field they would fill out at the path you're directing them to. If it already exists, you just want them to sign_in and not have to go to that path. That's why we're checking to make sure it's blank.


Q:

React render string as HTML in ant design

I'm using ant design dropdown. I have dynamic data from API and when I try to render those data into dropdown menu, It is rending as string.
So I used this react-html-parser library to render string as HTML but it does not work.
renderSocialMedia = () => {
if (this.props.weblookup) {
  let socialmedialookup = this.props.weblookup
  webitems = ""
  return socialmedialookup.map((k, index) => {
    if (k.name.toLowerCase() != "other")
      return webitems = "<Menu.Item key=" + k.id + ">" + k.name + "</Menu.Item>"
  })
 }
}

{ReactHtmlParser(webitems)}

<FormItem>
 {getFieldDecorator('AddNetwork', {
  initialValue: "",
 })(
 <Dropdown overlay={
  <Menu onClick='{this.handleMenuClick}'>

{ReactHtmlParser(webitems)}

  </Menu>
} trigger={['click']}>

  Add Username
  <Icon type="down" />

</Dropdown>
)}

OUTPUT:

A:

As you're using React you must properly format a DOM element. So, Try this,
return webitems = <Menu.Item key={ k.id }>{ k.name}</Menu.Item>

Hope it helps. Happy Coding!!


Q:

edittext inside scrollview, how to scroll to edittext when it gets the focus

have an edittext inside scrollview.  (and there are other views inside scrollview above edittext.)
When user presses the edittext, keyboard becames visible and the visible area of the scrollview becames small. Because of that edittext does not shown in the screen. (it does not scroll the scrollview so that edit text will be shown.)
After user presses any key in the keyboard, scrollview scrolls so that edittext becames visible again.

how can i force the scrollview to scroll so that edittext will be visible before user presses on the keyboard?

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:layout_weight="1" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        android:paddingBottom="0dip"
        android:paddingLeft="0dip"
        android:paddingRight="0dip"
        android:paddingTop="0dip" >

        <include
            layout="@layout/trade_row_item_3cell" />

        <include
            android:id="@+id/rowQuantity"
            layout="@layout/trade_quantity_selection_row_layout" />

        <include
            layout="@layout/trade_row_item_3cell" />

        <include
            layout="@layout/trade_price_selection_et_row_layout" />

        <include
            layout="@layout/trade_row_item_3cell" />

        <include
            layout="@layout/trade_row_item_3cell" />

       <Button
            style="@style/CustomButtonText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_weight="0" />
    </LinearLayout>
</ScrollView>

<include
    layout="@layout/trade_bottom_view" />

Here is the layout(trade_quantity_selection_row_layout) which contains the edittext
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:layout_gravity="left"
android:background="@android:drawable/list_selector_background">
<TextView
    android:id="@+id/tvLeft"
    android:layout_width="0dip"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:singleLine="true"
    android:textColor="#000000"
    android:paddingLeft="10dip"
    android:gravity="center_vertical"
    android:layout_gravity="center_vertical"/>
<EditText
    android:id="@+id/etRight"
    android:paddingLeft="10dip"
    android:background="@null"
    android:layout_width="0dip"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:inputType="number"
    android:gravity="center_vertical"
    android:layout_gravity="center_vertical"/>
<ImageView
    android:id="@+id/ivRight"
    android:src="@drawable/proceed"
    android:paddingRight="10dip"
     android:layout_weight="0"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"/>

trade_row_item_3cell layout contains linearlayout with edittexts.

A:

First get the x/y coordinates of your Edittext using View.getLocationOnScreen (int[] location) ( After the method returns, the array contains the x and y location in that order)
OR
This links helps you find the views coordinates  - https://stackoverflow.com/a/2761184/28557
Then
scrollView.scrollTo(x, y);

hope this helps


Q:

How can I use `defineProperty` to create a readonly array property?

I have the following as a part of a module (names simplified for purpose of question):
In "module.js":
var _arr;

_arr = [];

function ClassName () {
    var props = {};

    // ... other properties ...

    props.arr = {
        enumerable: true,
        get: function () {
            return _arr;
        }
    };

    Object.defineProperties(this, props);

    Object.seal(this);
};

ClassName.prototype.addArrValue = function addArrValue(value) {

    // ... some code here to validate `value` ...

    _arr.push(value);
}

In "otherfile.js":
var x = new ClassName();

With the implementation above, and the sample code below, adding values to arr can be achieved in two ways.
// No thank you.
x.arr.push("newValue"); // x.arr = ["newValue"];

// Yes please!
x.addArrValue("newValue"); // Only this route is desired.

Does anyone know how to achieve a readonly array property?
Note: writeable is false by default and no difference is observed if I explicitly set it.

A:

Object.freeze() will do what you're asking (on browsers properly implementing the spec).  Attempts to modify the array will either fail silently or throw TypeError when in strict mode.
The easiest solution is to return a new frozen copy (freeze is destructive):
return Object.freeze(_arr.slice());

However, if more reading than writing is expected, lazy-cache the most recently accessed frozen copy and purge upon write (since addArrValue controls writes)
Lazy caching read-only copy using modified original example:
"use strict";
const mutable = [];
let cache;

function ClassName () {
    const props = {};

    // ... other properties ...

    props.arr = {
        enumerable: true,
        get: function () {
            return cache || (cache = Object.freeze(mutable.slice());
        }
    };

    Object.defineProperties(this, props);

    Object.seal(this);
};

ClassName.prototype.addArrValue = function addArrValue(value) {

    // ... some code here to validate `value` ...

    mutable.push(value);
    cache = undefined;
}

Lazy caching read-only copy using ES2015 classes:
class ClassName {
    constructor() {
        this.mutable = [];
        this.cache = undefined;
        Object.seal(this);
    }

    get arr() {
        return this.cache || (this.cache = Object.freeze(this.mutable.slice());
    }

    function addArrValue(value) {
        this.mutable.push(value);
        this.cache = undefined;
    }
}

A "transparent" re-usable class hack (rarely required):
class ReadOnlyArray extends Array {
    constructor(mutable) {
        // `this` is now a frozen mutable.slice() and NOT a ReadOnlyArray
        return Object.freeze(mutable.slice());
    }
}

const array1 = ['a', 'b', 'c'];
const array2 = new ReadOnlyArray(array1);

console.log(array1); // Array ["a", "b", "c"]
console.log(array2); // Array ["a", "b", "c"]
array1.push("d");
console.log(array1); // Array ["a", "b", "c", "d"]
console.log(array2); // Array ["a", "b", "c"]
//array2.push("e"); // throws

console.log(array2.constructor.name); // "Array"
console.log(Array.isArray(array2));   // true
console.log(array2 instanceof Array); // true
console.log(array2 instanceof ReadOnlyArray); // false

A proper re-usable class:
class ReadOnlyArray extends Array {
    constructor(mutable) {
        super(0);
        this.push(...mutable);
        Object.freeze(this);
    }
    static get [Symbol.species]() { return Array; }
}

const array1 = ['a', 'b', 'c'];
const array2 = new ReadOnlyArray(array1);

console.log(array1); // Array ["a", "b", "c"]
console.log(array2); // Array ["a", "b", "c"]
array1.push("d");
console.log(array1); // Array ["a", "b", "c", "d"]
console.log(array2); // Array ["a", "b", "c"]
//array2.push("e"); // throws

console.log(array2.constructor.name); // "ReadOnlyArray"
console.log(Array.isArray(array2));   // true
console.log(array2 instanceof Array); // true
console.log(array2 instanceof ReadOnlyArray); // true


Q:

Obtain form input fields using jQuery?

I have a form with many input fields.
When I catch the submit form event with jQuery, is it possible to get all the input fields of that form in an associative array?

A:

$('#myForm').submit(function() {
    // get all the inputs into an array.
    var $inputs = $('#myForm :input');

    // not sure if you wanted this, but I thought I'd add it.
    // get an associative array of just the values.
    var values = {};
    $inputs.each(function() {
        values[this.name] = $(this).val();
    });

});

Thanks to the tip from Simon_Weaver, here is another way you could do it, using serializeArray:
var values = {};
$.each($('#myForm').serializeArray(), function(i, field) {
    values[field.name] = field.value;
});

Note that this snippet will fail on <select multiple> elements.
It appears that the new HTML 5 form inputs don't work with serializeArray in jQuery version 1.3. This works in version 1.4+

A:

Late to the party on this question, but this is even easier:
$('#myForm').submit(function() {
    // Get all the forms elements and their values in one step
    var values = $(this).serialize();

});

A:

The jquery.form plugin may help with what others are looking for that end up on this question. I'm not sure if it directly does what you want or not.
There is also the serializeArray function.


Q:

Scala with Spring: Constructor autowiring

I'm looking for "idiomatic" way to autowire Scala classes with Spring through constructor injection.
I've tried something like this:
   @Component
   class MyService @Autowired() ( val myDao: MyDao) extends Logging {
   ...
   }

But I get an error:
Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [MyService]: No default constructor found; nested exception is java.lang.NoSuchMethodException: MyService.()
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:964) ~[spring-beans-3.0.7.RELEASE.jar:3.0.7.RELEASE]

A:

I've added support for @Autowired on the constructor of a Scala object into the spring-scala project. This is only (at time of writing) in the nightly snapshot.
This allows you to do
@Component
@Autowired
class Service(dep : Dependency) { }

https://github.com/spring-projects/spring-scala


Q:

BQ51050B compatibility criteria

I started another project where I need to charge a few devices (preferably simultaneously) wirelessly. They all have BQ51050B and the corresponding coil/battery.
I need to know what I should look at when deciding on what IC to choose to be compatible with the mentioned device.
On the receiver, I am running 3.7V 60mAH batteries and using this coil.
On the charger, I intend to control the chips using the I2C protocol.

A:

Since asking this question I realized that the qi standard really helps you with sorting out  which active component (i.e. chip) works with which passive components (i.e. coil, battery). What is more, it can also tell you which device to pair with. For example if you have a transmitter chip, the version of qi helps you determine which receiver chip to use.
Read the datasheets.


Q:

App crashes when I try to reference the firebase database

I'm very new with Swift and Firebase. My current project is in Xcode 8. I followed a few tutorials and now I'm stuck. I might have found the problem. When I try to reference the database, the app crashes. That happens at the following line:
var ref = Firebase.Database().reference()

I have tried many things like adding the following lines of code:
var ref: DatabaseReference!
ref = Database.database().reference()

But that didn't work. I also tried to remove a few files and make a new podfile and did the same thing as before with the Terminal. In my Podfile I have the following things:
pod 'Firebase/Database'
pod 'Firebase/Auth'
pod 'Firebase/Storage'
pod 'Firebase/Core'

This is my current code:
import UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        var ref = Firebase.Database().reference()

        window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()
        window?.rootViewController = UINavigationController(rootViewController: ViewController())

        return true
    }

Maybe it's a stupid question but I'm stuck.

A:

I'd just use the code below as you don't need to call Firebase.Database:
let reference = Database.database().reference()

You'll want to not do anything like what you're trying to do, inside your AppDelegate file. You'll want to do this inside you controller classes. For example, your default ViewController class that XCode creates for you. Any questions, let me know. We've all been there!


Q:

$1_{\cup_n A_n} \le \sum_n 1_{A_n}$

Let $\{A_n\}$ a sequence of subsets of $\Omega$. Show:
$1_{\cup_n A_n} \le \sum_n 1_{A_n}$
If the sequence of sets are mutually disjoint, the inequality holds with equality. Now suppose not mutually disjoint. There exists $i, j \in \mathbb{N}$ such that $A_i \cap A_j \ne \emptyset$. Hence, the inequality would instead hold with strict equality.
How am I supposed to show that this inequality holds in general? Induction?

A:

You may simply show that it holds for every $x\in\Omega$. If $x\notin A_n$ for all $n\in\mathbb N$ then $x\notin\bigcup_{n=1}^\infty A_n$. Therefore, in this case $$1_{\bigcup_{n=1}^\infty A_n}(x)=0\leq\sum_{n=1}^\infty 1_{A_n}(x),$$ since every function $1_{A_n}$ is non-negative and therefore, so is their sum. If, on the other hand, $x\in A_{n_0}$ for some $n_0\in\mathbb N$, then $x\in\bigcup_{n=1}^\infty A_n$. Therefore $$1_{\bigcup_{n=1}^\infty A_n}(x)=1=1_{A_{n_0}}(x)\leq\sum_{n=1}^{\infty}1_{A_n}(x),$$ where the last inequality again holds because every summand is non-negative.


Q:

.htaccess redirect root to index.php

I need to redirect from http://example.com/ to http://example.com/index.php.

A:

Use this:
DirectoryIndex index.php

A:

Try this:
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^$
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule ^$ http://example.com/index.php [L,R=301]


Q:

two arrays are synchronous change,Maybe a bug from VUE

I have two object list and TEMP_ARR. They are not the same in memory, but when I change one, the other changes. Very strange, maybe a bug from VUE.
http://jsfiddle.net/3yx2a9vk/4/

A:

In Vue data are observable by default. If you assign one to another then it holds references. So, the solution is to create a new copy.
this.list = JSON.parse(JSON.stringify(TEMP_ARR));