text:
Q: Rails4 refactor Model make DRY I try to optimize the following Accounting model class and have two questions:
1) How can i replace the multiple attribute setters with a more elegant method?
2) Is there a better way than the if conditional in the replace_comma_with_dot method
class Accounting < ActiveRecord::Base

  validates :share_ksk, :central_office, :limit_value, :fix_disagio,
            presence: true, numericality: { less_than: 999.99, greater_than_or_equal_to: 0.00 },
            format: { with: /\d*\.\d{0,2}$/, multiline: true, message: I18n.t('accounting.two_digits_after_decimal_point')}

  def share_ksk=(number)
    replace_comma_with_dot(number)
    super
  end

  def central_office=(number)
    replace_comma_with_dot(number)
    super
  end

  def limit_value=(number)
    replace_comma_with_dot(number)
    super
  end

  def fix_disagio=(number)
    replace_comma_with_dot(number)
    super
  end

  def replace_comma_with_dot(number)
    if number.is_a? String
      number.sub!(",", ".")
    elsif number.is_a? Float
      number
    else
      ""
    end
  end

end

As user Pardeep suggested i'm trying to replace my getters with define_method:
  [:share_ksk=, :central_office=, :limit_value=, :fix_disagio=].each do |method_name|
    self.class.send :define_method, method_name do |number|
      replace_comma_with_dot(number)
      super
    end
  end

What am i missing?

A: You can define methods dynamically using the define_method, you can fine more information here
and you can update your replace_comma_with_dot with this
def replace_comma_with_dot(number)
  return number.sub!(",", ".") if number.is_a? String
  return number if number.is_a? Float
  ""
end

end

A: Instead of having a method in your model, I'd extract the functionality and append it to either the String or Integer classes:
#lib/ext/string.rb
class String
  def replace_comma_with_dot
    number.sub!(",",".") #Ruby automatically returns so no need to use return
  end
end

This - if your number is a string will allow you to do the following:
number = "67,90"
number.replace_comma_with_dot

To use this in the app, the setters are okay. You could achieve your functionality as follows:
 def fix_disagio=(number)
    self[:fix_disagio] = number.replace_comma_with_dot
 end

Your update is okay, except I would shy away from it myself as it creates bloat which doesn't need to be there.
I was looking for a way to set the attributes when you pull from the db, but then I realized that if you're having to set this each time you call the model, surely something will be wrong.
I would personally look at changing this at db level, failing that, you'd probably be able to use some sort of localization to determine whether you need a dot or comma.
There is a good answer here which advocates adding to the ActiveRecord::Base class:
class ActiveRecord::Base
  def self.attr_localized(*fields)
    fields.each do |field|
      define_method("#{field}=") do |value|
        self[field] = value.is_a?(String) ? value.to_delocalized_decimal : value
      end
    end
  end
end

class Accounting < ActiveRecord::Base
  attr_localized :share_ksk
end


text:
Q: Second Order Methods for conservation laws Consider the scalar conservation law $u_t+f(u)_x=0.$
I understand that Lax-Wendroff scheme is second order accurate, because of the way it is derived using Taylor series. However since this scheme is not TVD there are various methods obtained from Lax-Wendroff scheme by introducing a correction term/Limiters. For example minmod, superbee, van Leer etc.
Now I have the following doubts:

*

*Are these schemes second order accurate always? If so how to prove?

*How to prove that these schemes converge to Kruzkov entropy solutions? (They are not monotone anymore!! So the standard monotone argument may not work)

A: For the first part, these slope- or flux-limiter schemes are not second-order accurate anymore. In fact, their order of accuracy measured numerically is rather around 1.6-1.8. This becomes obvious after realising that they are a kind of compromise between first-order and second-order schemes, see e.g. the 2002 book by R.J. LeVeque.
For the second part, I may find some special cases where this property is proven in literature. To be updated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Substituting $t_0$ in Wronskian to solve 2nd order non homogeneous ode? Hey everyone I need some help understanding how to use Lagrange method and specifically the Wronskian used in it to solve 2nd order non homogeneous ode.
 Let :
$$y''(t)+a_1y'(t)+a_2y(t)=f(t)$$
I know that the general solution to a non homogeneous 2nd order ode is:
$$y(t)=c_1y_1(t)+c_2y_2(t)+y_p(t)$$
Where $y_1$ and $y_2$ are two linear independant solutions of the homogenous ode and $y_p$ is a particular solution of the non homogeneous ode.
I also know that we can find $y_p$ using the Wronskian in the formula:
$$y_p=\int_{t_0}^t \frac{y_1(s)y_2(t)-y_1(t)y_2(s)}{W_{(y_1,y_2)}(s)}f(s)ds$$
Here's where I'm confused:
I'm not sure what $t_0$ should be... I think that any $t_0 \in I$, where $I$ is the interval for which the two solutions $y_1$ and $y_2$ are continuous will do but I'm still not sure how to choose the value to substitute to $t_0$.
For example for the ode: $y''-y'-2y=e^{-t}$ I found that two linear independant solutions of the homogeneous are $y_1=e^{-t}$ and $y_2=e^{2t}$ and the particular solution should be:
$y_p=\int_{t_0}^t \frac{y_1(s)y_2(t)-y_1(t)y_2(s)}{W_{(y_1,y_2)}(s)}f(s)ds$
The Wronskian is $W(s)=3e^s $ so
$y_p=\int_{t_0}^t \frac{e^{-s}e^{2t}-e^{-t}e^{2s}}{3e^s}e^{-s}ds$
I could go on to integrate the function but I'm not sure what I should substitute $t_0$ with.. My books solution suggests $t_0=0$ but why?
Thanks in advance!

A: $$y_p=\int_{t_0}^t \frac{e^{-s}e^{2t}-e^{-t}e^{2s}}{3e^s}e^{-s}ds$$
$$y_p=\frac 13e^{2t}\int_{t_0}^t {e^{-s}ds-\frac 13e^{-t}\int_{t_0}^t }ds$$
At $t_0$ the function in the integrand becomes a constant. At $t$ you get a function of t. I don't know if I am clear. You should evaluate the integral at $t_0=0$ as suggested by your book and also at different values to see what happens. You end with the same answer because the homogeneous solution will absorb the extra terms of the particular solution.
$$y_p=\frac 13e^{2t}\int_{t_0}^t {e^{-s}ds-\frac 13e^{-t}\int_{t_0}^t }ds$$
$$y_p=-\frac 13e^{2t}|e^{-s}|_{t_0}^t -\frac 13e^{-t}|s|_{t_0}^t $$
$$y_p=-\frac 13e^{2t}(e^{-t}-e^{t_0})-\frac 13e^{-t}(t-{t_0}) $$
$$y_p=-\frac 13e^{2t}(e^{-t}-e^{t_0})-\frac 13e^{-t}(t-{t_0}) $$
The first term is absorbed byt the homogeneous solution. It remains only the following term:
$$\boxed {y_p=-\frac 13e^{-t}t}$$
The rest are extra terms as you can check...


text:
Q: Add menu options in a running powershell script I am using a PowerShell script with an interactive console menu that uses functions in the switch part. looks like this:
function startmenu {
    do {
        [int]$selection = 0
        while ($selection-lt 1 -or $selection-gt 5){
            Write-Host "1. Search"
            write-host "2. Change"
            Write-Host "3. do stuff"
            write-host "4. Clear Screen"
            write-host "5. Exit"

            [int]$selection= read-host "choose one option"
            switch ($selection) {
                1{find}
                2{change}
                3{dostuff}
                4{cls}
                5{exit}
            }
        }
    }
    while ($selection -ne 4)}

Right now I am trying to build a new script with a similar menu for ssh connections.
Since PowerShell has its own ssh client.
Sometimes you have to add new servers to your server list,
like putty or something. So I want to add new options to my menu while running the script.
maybe with a function "add a new server to list".
But I have no idea how to realize this.
my colleagues would use this scrip as well and they may have other servers so the menu has to be some kind of
dynamic for every user of it.
Everyone should build their own list without touching the script.
Is there any possible way? my PowerShell knowledge is pretty basic.
Thanks!

A: To have a console menu where users can add options, perhaps the following will give you an idea of how you could do that:
function Show-Menu {
    [CmdletBinding()]
    param (
        [string[]]$options = @('FileZilla', 'Posh-SSH PowerShell', 'WinSCP','PuTTY')
    )
    # store the options in a List object for easy addition
    $list = [System.Collections.Generic.List[string]]::new()
    $list.AddRange($options)

    # now start an endless loop for the menu handling
    while ($true) {
        Clear-Host
        # loop through the options list and build the menu
        Write-Host "`r`nPlease choose from the list below.`r`n"
        $index = 1
        $list.Sort()
        $list | ForEach-Object { Write-Host ("{0}.`t{1}" -f $index++, $_ )}
        Write-Host "`r`nN.`tAdd a new item to the list"
        Write-Host "Q.`tQuit"

        $selection = Read-Host "`r`nEnter Option"

        switch ($selection) {
            {$_ -like 'N*' } {
                # the user want to add a new item to the menu
                $item = (Read-Host "Please add a new item").Trim()
                if (![string]::IsNullOrWhiteSpace($item) -and $list -notcontains $item) {
                    Write-Host "Adding new item '$item'.." -ForegroundColor Yellow
                    $list.Add($item)
                }
            }
            {$_ -like 'Q*' } {
                # if the user presses 'Q', exit the function
                return
            }
            default {
                # test if a valid numeric input in range has been given
                if ([int]::TryParse($selection, [ref]$index)) {
                    if ($index -gt 0 -and $index -le $list.Count) {
                        # do whatever you need to perform
                        $selection = $list[$index - 1]  # this gives you the text of the selected item

                        # for demo, just output on screen what option was selected
                        Write-Host "Building connection using $selection" -ForegroundColor Green
                        # return the selection made to the calling script
                        return $selection
                    }
                    else {
                        Write-Host "Please enter a valid option from the menu" -ForegroundColor Red
                    }
                }
                else {
                    Write-Host "Please enter a valid option from the menu" -ForegroundColor Red
                }
            }
        }

        # add a little pause and start over again
        Start-Sleep -Seconds 1
    }
}

# call the function
$choice = Show-Menu

Hope this helps


text:
Q: Find the names of all students who are enrolled in both A and B classes Based on the schema below where
The primary keys are sid and cid. And the table schema is below.

*

*Students (sid: integer, name: string, major: string, age: integer)

*Enrollment (sid: integer, cid: integer)

*Classes (cid: integer, name: string, instructor: string, room: string, time: time)
A student would be listed in the table enrollment with a sid and cid and the student will also be listed in the student table with the same sid. The cid will come from the Classes table.
I am having trouble finding the names of all students who are enrolled in both 'A' and 'B' classes. Where A & B is a string for the class name.
SELECT S.name FROM Students S JOIN Classes C JOIN Enrollment E ON C.name = "A" AND C.name = "B"

A: You can use aggregation and a HAVING clause:
SELECT Sid, S.name
FROM Students S JOIN
     Enrollment E
     USING (sid) JOIN
     Classes C
     USING (cid)
WHERE C.name IN ('A', 'B')
GROUP BY sid, S.name
HAVING COUNT(*) = 2;   -- "2" is the number of classes in the `IN` list

Notes:

*

*You need ON or USING clauses for your joins.

*String constants should use single quotes, not double quotes.

*This assumes that a student is not enrolled for the same class more than once.  If that is possible, then use HAVING COUNT(DISTINCT c.name) = 2.

EDIT:
For "A" and not "B", you can do:
HAVING MIN(c.name) = 'A' and MIN(c.name) = MAX(c.name)

A: SELECT S.name FROM Students S
JOIN Enrollment E ON S.sid=E.sid
JOIN Classes C ON C.cid=E.cid
WHERE C.name = 'A'
INTERSECT
SELECT S.name FROM Students S
JOIN Enrollment E ON S.sid=E.sid
JOIN Classes C ON C.cid=E.cid
WHERE C.name = 'B'

A: I wouldn't join at all. You want rows from the students table, so select FROM students. You want a condition met, so use WHERE. As for looking up data in other tables, you can use IN or EXISTS.
select name
from students
where sid in
(
  select sid from enrollment where cid = (select cid from classes where name = 'A')
)
and sid in
(
  select sid from enrollment where cid = (select cid from classes where name = 'B')
)
order by name;


text:
Q: ROS rosmake error I am currently working on a project with ROS. I am completely new to ROS and it's features. Currently i'm doing a tutorial on ROS and started using code for the first time. although i do have some experience with c++, i can't figure out what is going wrong. In ROS i use the rosmake command and it fails to compile the cpp file/code. Can anyone help me figure out why the error occurs? (and possibly how to fix it?)
below is the cpp file code:
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
int main(int argc, char **argv)
{
ros::init(argc, argv, "example1_a");
ros::NodeHandle n;
ros::Publisher chatter_pub = n.advertise<std_
msgs::String>("message", 1000);
ros::Rate loop_rate(10);
while (ros::ok())
{
std_msgs::String msg;
std::stringstream ss;
ss << " I am the example1_a node ";
msg.data = ss.str();
//ROS_INFO("%s", msg.data.c_str());
chatter_pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}

And here the build log:
mkdir -p bin
cd build && cmake -Wdev -DCMAKE_TOOLCHAIN_FILE=/opt/ros/indigo/share/ros/core/rosbuild/rostoolchain.cmake  ..
[rosbuild] Building package chapter2_tutorials
[rosbuild] using multiarch 'x86_64-linux-gnu' for finding Boost
-- Using CATKIN_DEVEL_PREFIX: /home/rospc/dev/rosbook/chapter2_tutorials/build/devel
-- Using CMAKE_PREFIX_PATH: /opt/ros/indigo
-- This workspace overlays: /opt/ros/indigo
-- Using PYTHON_EXECUTABLE: /usr/bin/python
-- Using Debian Python package layout
-- Using empy: /usr/bin/empy
-- Using CATKIN_ENABLE_TESTING: ON
-- Skip enable_testing() for dry packages
-- Using CATKIN_TEST_RESULTS_DIR: /home/rospc/dev/rosbook/chapter2_tutorials/build/test_results
-- Found gtest sources under '/usr/src/gtest': gtests will be built
-- Using Python nosetests: /usr/bin/nosetests-2.7
-- catkin 0.6.16
-- Using these message generators: gencpp;genlisp;genpy
[rosbuild] Including /opt/ros/indigo/share/roslisp/rosbuild/roslisp.cmake
[rosbuild] Including /opt/ros/indigo/share/roscpp/rosbuild/roscpp.cmake
[rosbuild] Including /opt/ros/indigo/share/rospy/rosbuild/rospy.cmake
-- Configuring done
-- Generating done
-- Build files have been written to: /home/rospc/dev/rosbook/chapter2_tutorials/build
cd build && make -j8 -l8
make[1]: Entering directory `/home/rospc/dev/rosbook/chapter2_tutorials/build'
make[2]: Entering directory `/home/rospc/dev/rosbook/chapter2_tutorials/build'
make[3]: Entering directory `/home/rospc/dev/rosbook/chapter2_tutorials/build'
make[3]: Leaving directory `/home/rospc/dev/rosbook/chapter2_tutorials/build'
[  0%] Built target rospack_genmsg_libexe
make[3]: Entering directory `/home/rospc/dev/rosbook/chapter2_tutorials/build'
make[3]: Leaving directory `/home/rospc/dev/rosbook/chapter2_tutorials/build'
[  0%] Built target rosbuild_precompile
make[3]: Entering directory `/home/rospc/dev/rosbook/chapter2_tutorials/build'
make[3]: Entering directory `/home/rospc/dev/rosbook/chapter2_tutorials/build'
Scanning dependencies of target example1_a
Scanning dependencies of target example1_b
make[3]: Leaving directory `/home/rospc/dev/rosbook/chapter2_tutorials/build'
make[3]: Leaving directory `/home/rospc/dev/rosbook/chapter2_tutorials/build'
make[3]: Entering directory `/home/rospc/dev/rosbook/chapter2_tutorials/build'
make[3]: Entering directory `/home/rospc/dev/rosbook/chapter2_tutorials/build'
[100%] [100%] Building CXX object CMakeFiles/example1_b.dir/src/example1_b.cpp.o
Building CXX object CMakeFiles/example1_a.dir/src/example1_a.cpp.o
/home/rospc/dev/rosbook/chapter2_tutorials/src/example1_a.cpp: In function 'int main(int, char**)':
/home/rospc/dev/rosbook/chapter2_tutorials/src/example1_a.cpp:8:42: error: 'std_' was not declared in this scope
 ros::Publisher chatter_pub = n.advertise<std_
                                          ^
/home/rospc/dev/rosbook/chapter2_tutorials/src/example1_a.cpp:8:32: error: parse error in template argument list
 ros::Publisher chatter_pub = n.advertise<std_
                                ^
/home/rospc/dev/rosbook/chapter2_tutorials/src/example1_a.cpp:9:30: error: no matching function for call to 'ros::NodeHandle::advertise(const char [8], int)'
 msgs::String>("message", 1000);
                              ^
/home/rospc/dev/rosbook/chapter2_tutorials/src/example1_a.cpp:9:30: note: candidates are:
In file included from /opt/ros/indigo/include/ros/ros.h:45:0,
                 from /home/rospc/dev/rosbook/chapter2_tutorials/src/example1_a.cpp:1:
/opt/ros/indigo/include/ros/node_handle.h:236:15: note: template<class M> ros::Publisher ros::NodeHandle::advertise(const string&, uint32_t, bool)
     Publisher advertise(const std::string& topic, uint32_t queue_size, bool latch = false)
               ^
/opt/ros/indigo/include/ros/node_handle.h:236:15: note:   template argument deduction/substitution failed:
/home/rospc/dev/rosbook/chapter2_tutorials/src/example1_a.cpp:9:30: error: template argument 1 is invalid
 msgs::String>("message", 1000);
                              ^
In file included from /opt/ros/indigo/include/ros/ros.h:45:0,
                 from /home/rospc/dev/rosbook/chapter2_tutorials/src/example1_a.cpp:1:
/opt/ros/indigo/include/ros/node_handle.h:302:13: note: template<class M> ros::Publisher ros::NodeHandle::advertise(const string&, uint32_t, const SubscriberStatusCallback&, const SubscriberStatusCallback&, const VoidConstPtr&, bool)
   Publisher advertise(const std::string& topic, uint32_t queue_size,
             ^
/opt/ros/indigo/include/ros/node_handle.h:302:13: note:   template argument deduction/substitution failed:
/home/rospc/dev/rosbook/chapter2_tutorials/src/example1_a.cpp:9:30: error: template argument 1 is invalid
 msgs::String>("message", 1000);
                              ^
make[3]: *** [CMakeFiles/example1_a.dir/src/example1_a.cpp.o] Error 1
make[3]: Leaving directory `/home/rospc/dev/rosbook/chapter2_tutorials/build'
make[2]: *** [CMakeFiles/example1_a.dir/all] Error 2
make[2]: *** Waiting for unfinished jobs....
Linking CXX executable ../bin/example1_b
make[3]: Leaving directory `/home/rospc/dev/rosbook/chapter2_tutorials/build'
[100%] Built target example1_b
make[2]: Leaving directory `/home/rospc/dev/rosbook/chapter2_tutorials/build'
make[1]: *** [all] Error 2
make[1]: Leaving directory `/home/rospc/dev/rosbook/chapter2_tutorials/build'
make: *** [all] Error 2

This next code is from the second file, which does compile and creates no errors:
#include "ros/ros.h"
#include "std_msgs/String.h"

void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
ROS_INFO("I heard: [%s]", msg->data.c_str());
}

int main(int argc, char **argv)
{
ros::init(argc, argv, "example1_b");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("message", 1000, chatterCallback);
ros::spin();
return 0;
}

A: Line breaks in C++ code can only be done in 3 ways :
cout<<"Error:This is a really long error "
"message that exceeds the maximum permitted length.\n";

or
cout<<"Error:This is a really long error \
message that exceeds the maximum permitted length.\n";

or
c\
o\
u\
t<<"Error:This is a really long error \
message that exceeds the maximum permitted length.\n";

other than that, it will throw you errors ...

A: Change:
ros::Publisher chatter_pub = n.advertise<std_
msgs::String>("message", 1000);

By:
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("message", 1000);

PS : You should not use rosmake. It's an old tool to build your workspace.
Use catkin_make or catkin build.
Note: You can't use both catkin_make and catkin build on the same workspace. If you want to switch you need to clean your workspace. For that it's easy, you have to erase your build, devel and install directory in your workspace folder.
$ cd ~/catkin_ws
$ sudo rm -r devel build install

Alternative ways :
If you use catkin_make and want to clean your workspace to switch to catkin build use
$ catkin_make clean
$ catkin build

If you use catkin build and want to clean your workspace to switch to catkin_make use
$ catkin clean
$ catkin_make

rosmake vs catkin:
Since ROS Groovy, it's not recommended to use rosmake, here is why we use catkin:

*

*Make better use of all tools provided by Cmake,

*Cmake's C means Cross Platform. The idea is to make ROS more portable on different architectures (ARM) and OS (OS X and Windows).

*With rosbuild each package had its own Cmake, package dependency management was less stable.

*Cmake can compile smarter by parallelizing dependencies.

*Reduce memory space by optimizing dependencies.

*A single installation target which allows companies to run closed and proprietary software on ROS.

catkin_make vs catkin build:
Quite the same, but the most recent catkin build. Nowadays, some people recommend to switch from catkin_make to catkin build. The main difference between both is that catkin build has a better isolation package. It will build each package a workspace.

A: Use C++11 for make your project.
For this use the cmake flag in your command:
catkin_make -DCMAKE_CXX_FLAGS=-std=c++11

Or
catkin build -DCMAKE_CXX_FLAGS=-std=c++11


text:
Q: How to create real-time changes in JavaScript So I wrote a pretty basic code. I'm a real noob. Started JavaScript 3 days back. I want the sorting process to be visualized while the sorting is going on. But when the SORT button is clicked after a while the sorted array is show. But what I want is to show the changes happening to the array in real-time.
Please help me out.
var array = [];
container_content= "";
for (var i=0; i < 50; i++) {
    array.push(Math.random() *500)
}

container_content = "";

function myFunction(element) {
    container_content += '

';
}
array.forEach(myFunction);
$(".container").html(container_content);

function another(element, index){
    element.style.height = array[index]
}
$( "div" ).each( function( index, element ){
    $( this ).css('height', array[index]);
});

$('button').click(function(){
    var i, j, temp;
    for(i = 0; i < array.length; i++)
    {
        for(j = 0; j < array.length-1; j++)
        {
            if( array[j] > array[j+1])
            {
                // swap the elements
                temp = array[j];
                array[j] = array[j+1];
                array[j+1] = temp;
            }
        }
            $( "div" ).each( function( index, element ){
            $( this ).css('height', array[index]);
            });

    }

})

A: I took what you were trying to do and broke it  down into 4 basic functions (1 main function and 3 helper functions).
runSort is the main function that uses all the other helper functions to do everything.
makeArrayAndUnsyncedBars generates your random array and basic divs that you'll use as green "bars", but it doesn't set the heights of these divs according to the values in the array.
syncArrayToBars sets the heights of these "bar" divs according to the values in the array
sortUntilNextSwap sorts the array until either a swap occurs or the sort completes. this function returns false if it made a swap (meaning that it's still working its way through the array) or true otherwise.

var FRAMES_PER_SECOND = 50;

var sortInterval = null;
function runSort() {
  clearInterval(sortInterval);

  makeArrayAndUnsyncedBars(50);
  syncArrayToBars();

  sortInterval = setInterval(function() {
    var finishedSorting = sortUntilNextSwap();
    syncArrayToBars();

    if (finishedSorting) clearInterval(sortInterval);
  }, Math.round(1000 / FRAMES_PER_SECOND));
}

var array = [];
function makeArrayAndUnsyncedBars(numberOfValues) {
  var htmlToAdd = "";
  array = [];
  for (var i = 0; i < numberOfValues; i++) {
    htmlToAdd += "

";
    array.push(rando(150));
  }
  $("#bars").html(htmlToAdd);
}

function syncArrayToBars() {
  for (var i = 0; i < array.length; i++) $(".bar").eq(i).css({
    height: array[i] + "px"
  });
}

var i, j, temp;
function sortUntilNextSwap() {
  for (i = 0; i < array.length; i++) {
    for (j = 0; j < array.length - 1; j++) {
      if (array[j] > array[j + 1]) {
        // swap the elements
        temp = array[j];
        array[j] = array[j + 1];
        array[j + 1] = temp;
        return false;
      }
    }
  }
  return true;
}
.bar {
  width: 5px;
  background: #5aedab;
  border-radius: 3px;
  display: inline-block;
  margin: 0px 3px;
}

<button onclick="runSort();">Run sort</button>

EDIT: I should mention that I used rando.js for the randomness out of habit, but it's not super necessary here given that you use Math.random() very little anyway. Take it out or leave it in according to your preference.


text:
Q: why math.Ceiling (double a) not return int directly?
Possible Duplicate:
Why doesn't Math.Round/Floor/Ceiling return long or int?

msdn defined this method:Returns the smallest integer greater than or equal to the specified double-precision floating-point number.
but in fact,it is
public static double Ceiling (
    double a
)

why not return int directly? what does microsoft think of ?

A: It's because the range of a double (±5.0 × 10−324 to ±1.7 × 10308) is much greater than the range of an int (-2,147,483,648 to 2,147,483,647). If the return type were int many possible inputs would fail. For example Math.Ceiling might be forced to throw an OverflowException in a checked context, or it might even return an incorrect result in an unchecked context. This is undesirable behaviour.
Also some special values such as NaN and PositiveInfinity can be returned by this method. This is only possible if the return type is double.
If you believe that the result will fit into an int, you can add an explicit cast:
int result = (int)Math.Ceiling(a);


text:
Q: Prove three bisectors always meet at a common point in any triangle How do you prove that three bisectors meet at a common point in any triangle? I have read carefully the content in Kiselev but cannot devise a proof on my own.
Is the proof for this complicated?

A: Let the vertices of the triangle be $P_1, P_2, P_3$.
Let $B_1$ be the bisector of the angle $P_3 P_1 P_2$.
Let $B_2$ be the bisector of the angle $P_1 P_2 P_3$.
Let $B_3$ be the bisector of the angle $P_2 P_3 P_1$.
The key observation is

A point $Q$ is on $B_1$ iff the distance of $Q$ to the side $P_1 P_2$ is the same as the distance of $Q$ to the side $P_1 P_3$.

Analogous statements hold for $B_2$ and $B_3$.
Let $O$ be the intersection of $B_1$ and $B_2$. Then the distances of $O$ to all three sides are the same. Therefore, $O$ is also on $B_3$ and so the three bisectors meet at $O$.


text:
Q: App stopped running on device - 'No such file or directory' Initially I started building an iPhone app (App still in development stage) using Xcode 4.2, it was working fine on both device and simulator.Later, we wanted to add support for iPhone 5 (4 inch display). When I ran it on Xcode 4.5 (including Default-568h.png), it was working fine (on the simulator both 3.5 inch and 4 inch). But when i tried to run it on device, it keeps on giving me the error
"Could not launch appname.app" No such file or directory (/Users/<user>/Library/Developer/Xcode/DerivedData/appname-ffotpypmbvaguyhfvnnejhjotpbp/Build/Products/Debug-iphoneos/appname.app/appname).
I tried the following steps, but no luck :(

*

*Deleted the app from device. Restarted the device.

*Quit XCode.Trashed all folders from `DerivedData.Cleaned the project. Restarted
machine.

*Set Build for active architectureto YES

*Deleted Required device capabilities from -info.plist

Do I have any other options to try, or should I repeat these again and again?

A: The last time I had a similar issue, a normal clean wasn't enough, as it left some derived data. In Xcode, select the Product menu and hold down the option key to reveal "Clean Build Folder...", or even better, close Xcode and delete /Users/<user>/Library/Developer/Xcode/DerivedData/ entirely.


text:
Q: Issues with inspect.py when used inside Jython I am using an application developed in Jython. When I try to use the inspect.py in that, it shows error message.
My code goes like this
import inspect,os,sys,pprint,imp
def handle_stackframe_without_leak(getframe):
    frame = inspect.currentframe()
    try:
        function = inspect.getframeinfo(getframe)
        print inspect.getargvalues(getframe)
    finally:
        del frame
#
def raja(a):
    handle_stackframe_without_leak(inspect.currentframe())
    print a
#
def callraja():
    handle_stackframe_without_leak(inspect.currentframe())
    raja("raja@ad.com")
#
callraja()
raja("raja@ad.com")
#

When I run this using python.exe, there are no issues. However, using this inside the app throwing the following error
 File "C:\Program Files\jython221ondiffjava\Lib\inspect.py", line 722, in getframeinfo
 File "C:\Program Files\jython221ondiffjava\Lib\inspect.py", line 413, in findsource
 File "C:\Program Files\jython221ondiffjava\Lib\sre.py", line 179, in compile
 File "C:\Program Files\jython221ondiffjava\Lib\sre.py", line 227, in _compile
 File "C:\Program Files\jython221ondiffjava\Lib\sre_compile.py", line 437, in compile
 File "C:\Program Files\jython221ondiffjava\Lib\sre_compile.py", line 421, in _code
 File "C:\Program Files\jython221ondiffjava\Lib\sre_compile.py", line 143, in _compile
ValueError: ('unsupported operand type', 'branch')

    at org.python.core.Py.makeException(Unknown Source)
    at sre_compile$py._compile$1(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py:143)
    at sre_compile$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyTableCode.call(Unknown Source)
     at org.python.core.PyFunction.__call__(Unknown Source)
    at sre_compile$py._code$11(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py:421)
    at sre_compile$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyFunction.__call__(Unknown Source)
    at sre_compile$py.compile$12(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py:437)
    at sre_compile$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyFunction.__call__(Unknown Source)
    at org.python.core.PyObject.invoke(Unknown Source)
    at sre$py._compile$13(C:\Program Files\jython221ondiffjava\Lib\sre.py:227)
    at sre$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre.py)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyFunction.__call__(Unknown Source)
    at sre$py.compile$8(C:\Program Files\jython221ondiffjava\Lib\sre.py:179)
    at sre$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre.py)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyFunction.__call__(Unknown Source)
    at org.python.core.PyObject.invoke(Unknown Source)
    at inspect$py.findsource$24(C:\Program Files\jython221ondiffjava\Lib\inspect.py:413)
    at inspect$py.call_function(C:\Program Files\jython221ondiffjava\Lib\inspect.py)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyFunction.__call__(Unknown Source)
    at inspect$py.getframeinfo$54(C:\Program Files\jython221ondiffjava\Lib\inspect.py:722)
    at inspect$py.call_function(C:\Program Files\jython221ondiffjava\Lib\inspect.py)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyFunction.__call__(Unknown Source)
    at org.python.core.PyObject.invoke(Unknown Source)
    at custom$py.handle_stackframe_without_leak$4(C:\Program Files\<my app>\jars\custom.py:29)
    at custom$py.call_function(C:\Program Files\<my app>\.\jars\custom.py)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyFunction.__call__(Unknown Source)
    at definitions$py.gotonotificationprofile$122(C:\Program Files\<my app>\.\jars\definitions.py:1738)
    at definitions$py.call_function(C:\Program Files\<my app>\.\jars\definitions.py)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyFunction.__call__(Unknown Source)
    at notificationcases$py.A003$2(C:\Program Files\<my app>\.\jars\notificationcases.py:143)
    at notificationcases$py.call_function(C:\Program Files\<my app>\.\jars\notificationcases.py)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyFunction.__call__(Unknown Source)
    at org.python.pycode._pyx171.f$0(003:8)
    at org.python.pycode._pyx171.call_function(003)
    at org.python.core.PyTableCode.call(Unknown Source)
    at org.python.core.PyCode.call(Unknown Source)
    at org.python.core.Py.runCode(Unknown Source)
    at org.python.util.PythonInterpreter.execfile(Unknown Source)

Any help will be appreciated.
Thanks
Rajasankar

A: Have you tried running your program on the command line with Jython (so outside of the app)?  When I run your program with Jython 2.2.1 or Jython 2.5.0, I get identical output as from Python.

A: This might help http://grinder.sourceforge.net/faq.html#re-problems.
For a quick check, try adding import re in findsource method (C:\Program Files\jython221ondiffjava\Lib\inspect.py)

def findsource(object):
    """Return the entire source file and starting line number for an object.
    (...snip...)"""
    import re
    file = getsourcefile(object) or getfile(object)

Can't promise anything, though...


text:
Q: anchor links and margins I'm currently building a webpage where some elements are placed on fixed positions near the top edge. So whenever I navigate to anchors, those get placed right under those fixed elements. I wonder if there's some style or other method that when navigating to a anchor, this happens with some additional offset/margin?
Example source code

This covers the top 100px of the screen.

Foo

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam
nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum
dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam
erat, sed diam voluptua. At vero eos et accusam et justo duo dolores e
ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem
ipsum dolor sit amet.

Bar

Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse
molestie consequat, vel illum dolore eu feugiat nulla facilisis at
vero eros et accumsan et iusto odio dignissim qui blandit praesent
luptatum zzril delenit augue duis dolore te feugait nulla facilisi.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat
volutpat.

Say this HTML is available at http://example.com/foobar.html one could link to http://example.com/foobar.html/#bar – a browser will scroll to the anchor named/id "bar". But in this example there's that 100px high fixed element, that will obstruct the upper parts of the "Bar" contents. Now I'd like to have some style/option that tells the browser, not to scroll the element to the top of the document window, but to leave a certain "scroll margin" (in this case a scroll margin of about 200px). This is not about element margins, as these influence the layout. But this is not about layout, but giving hints for the scrolling behaviour.

A: In order to get a cross-browser/cross-device solution where your anchor is truly invisible in the sense that it does not take up any space on the page, it is important that you format your anchor tag like this:

We used a class so you can style all of your anchor tags at once, (assuming the fixed div is part of your normal page template)... you could set it as an ID as the question poses though.
And format your CSS as follows:
a.top {
position: relative;
top:-100px;
display: block;
height: 0;
width:0;
}

Using Position: relative allows you to pull the anchor our of the normal page flow.
setting the top to a negative dimension that equals the height of your fixed element will push the content you are jumping to into full view.
Browsers such as Chrome do not respect this positioning unless the anchor actually displays. Adding content to the anchor such as   will force the anchor to display but in many instances that would create a vertical space as big as the line-height of the , so it is better to set the display to block and the width and height to 0.

A: Here is my solution: http://jsfiddle.net/ufewB/
HTML

        Fixed position element
        Jump to foo

Foo

Lorem ipsum text

CSS
#fixed {
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:100px;
    background-color:red;
}
#spacer { height:800px; }
* { margin:0px; padding:0px; }
#container { width:960px; margin:auto; }
#foo { position:relative; top:-100px; }

Basically, I gave the   the CSS position:relative; top:-100px and I took all the elements contained inside the anchor and put them next to the anchor instead. I did this because you are in essence creating an invisible link, removing it from the normal document flow, and positioning it 100px higher than it would normally be.
Doing it this way, when the page places the hash link at the top of the page, whatever content was next to the link will be 100px lower. Additionally, another benefit of doing it this way is you don't have to mess with tweaking the flow of the document; you're just changing the flow of an invisible anchor tag, which makes maintenance much easier

A: scroll-margin-top is a good solution now (2022)


text:
Q: how to pass values from gridview in parent page to form in popup page im having a gridview in only page and on clicking a button column field Gridview1_RowCommand gets executed.What im stuck at is on how to pass a single refno(which is in the grid) to the popup page.i want to use this refno to generate a query
help on this will really be appreciated
the below code i wat i used and im stuck here..
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{

    Page.RegisterStartupScript("test", "<script language='javascript'>Openpopup();</script>");
}

 <script language='javascript'>
   var popupobj;
  function Openpopup()
{
      popupobj = window.open("popup.aspx", "_blank", "width=1000,height=500,statusbar=no,toolbar=no,scrollbars=no,resizable=no,navbar=no,screenX=800,screenY=800top=100,left=100");
    popupobj.focus();
}
 </script>

A: Since you are using RowCommand event, to be able to send this value to the Popup you need to set the RowIndex as a CommandArgument of the Button you are clicking to open the popup.
Set the Value(refno) to passed to Popup in DataKey.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    var Button1= e.Row.FindControl("Button1") as Button;
    Button1.CommandName = "ButtonClick";
    // cast RowIndex in line code to string if e.CommandArgument accepts string
    Button1.CommandArgument = e.Row.RowIndex;
}

Now in the RowCommand
protected void GridView1_RowCommand(object sender, GridViewRowCommandArgs e)
{
    if(e.CommandName == "ButtonClick")
    {
        var refno = GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)]["refno"];
        Page.RegisterStartupScript("test", "<script language='javascript'>Openpopup(' + refno + ');</script>");
    }
}

This way now you have refno in the Javascript function argument. Pass this argument as a querystring in the Javascript popup function.
This way you can access refno in the Popup page.


text:
Q: jQuery : loop through nested objects I would like to loop trough nested objects. here is my code :
var defaults = {
    toolTips: {
        printVersion: {
            toolTip1: {
                link_s: '#mm_tooltip1_link',
                tooltip_s: '#mm_tooltip1'
            },
            toolTip2: {
                link_s: '#mm_tooltip2_link',
                tooltip_s: '#mm_tooltip2'
            },
            toolTip3: {
                link_s: '#mm_tooltip3_link',
                tooltip_s: '#mm_tooltip3'
            }
        }
    }
};

var settings;
var $archives_dialog;

$.madmagz = function(options) {
    settings = $.extend({}, defaults, options);
    init();
};

function init(){
    initToolTips();
}

function initToolTips() {
    $(settings.toolTips).each ( function (i, tooltip_group) {
        $(tooltip_group).each (function (i, tooltip) {
            // do stuff
        });
    });
}

In every each loop, I get the same object. How can I go down in every nested objects ?

A: You need the $.each() helper method to loop over objects.
function initToolTips() {
    $.each(defaults.toolTips, function(i, tooltip_group) {
        $.each(tooltip_group, function(i2, tooltip) {
            alert(i2);
        });
    });
}

Ref.: jQuery.each()

A: Use .children()
http://api.jquery.com/children/


text:
Q: Xcode tests fail due to missing library in test bundle Using Xcode 7.3, Cocoapods 0.39.0
At some point in the recent past, perhaps due to an upgrade of Xcode and/or Cocoapods, our tests stopped working with the following runtime issue:
2016-04-18 16:32:55.318 MyApp[15066:9003314] Failed to load test bundle
from file:///<huge filepath to .xctest wrapper>: Error Domain=NSCocoaErrorDomain
Code=3587 "dlopen_preflight(<same huge filepath to .xctest wrapper>): Library not
loaded: @rpath/Nocilla.framework/Nocilla

Reason: image not found" UserInfo={NSLocalizedFailureReason=The bundle is damaged
or missing necessary resources., NSLocalizedRecoverySuggestion=Try reinstalling the
bundle., NSFilePath=<huge filepath to .xctest wrapper>, NSDebugDescription=
dlopen_preflight(<huge filepath to .xctest wrapper>): Library not loaded:
@rpath/Nocilla.framework/Nocilla

I don't know anything like enough about Xcode and test bundle internals to debug this.
How do I restore my tests to working order? Thank you.
Edit: The only way I was able to unblock my work was to remove Nocilla. Fortunately, I discovered it wasn't actually used for anything. We just as well could have relied on it, however, so the question stands.


text:
Q: Error converting string to DateTime private void SaveButton_Click(object sender, EventArgs e)
{
   try
   {
       if (ValidateInput())
       {
          if (md.NAME_ID("LOGIN", "UID", "UNAME", UserNameTextBox.Text) != "")
          {
              MessageBox.Show("User already exist");
              return;
          }
          string PASS = "";
          if (UpassTextBox.Text != "")
          {
              PASS = base64Encode(UpassTextBox.Text);
          }
          else
          {
             PASS = "";
          }
          LoginTbl login = new LoginTbl(Convert.ToString(md.Max_ID("UID", "LOGIN")),
                               Convert.ToDateTime(DT1.Value.ToShortDateString()),
                               Convert.ToBoolean(ActiveRadioButton.Checked ? true : false),
                               UserNameTextBox.Text, PASS, MobileTextBox.Text,
                               RemarksTextBox.Text, UpdateCheckBox.Checked,
                               DeleteCheckBox.Checked, MenuCheckBox.Checked,
                               AddItemCheckBox.Checked, SearchItemCheckBox.Checked,
                               ListViewCheckBox.Checked, PurchaseCheckBox.Checked,
                               PurReturnCheckBox.Checked, PurPerformaCheckBox.Checked,
                               PurImportsCheckBox.Checked, PurReportsCheckBox.Checked,
                               SaleCheckBox.Checked, SaleReturnCheckBox.Checked,
                               SalePerformaCheckBox.Checked, SaleReportsCheckBox.Checked,
                               InventoryCheckBox.Checked, PaymentCheckBox.Checked,
                               JVCheckBox.Checked, AccLedgerCheckBox.Checked,
                               TrailCheckBox.Checked, PLCheckBox.Checked,
                               AccReportsCheckBox.Checked, SmsCheckBox.Checked,
                               EmailCheckBox.Checked, SmsReportsCheckBox.Checked,
                               StockNavigationCheckBox.Checked);

          if (new LoginDAL().Save(login))
          {
             MessageBox.Show("User has been added successfully");
             REFRESH_FORM();
             T1.Text = Convert.ToString(md.Max_ID("UID", "LOGIN"));
          }
          else
          {
             MessageBox.Show("Not added try again");
          }

      }
      else {
             MessageBox.Show("Please enter into \'*\' empty fields");

           }
   }
   catch (Exception ex)
   {
      MessageBox.Show("Error: " + ex.Source + ": " + ex.Message, "Connection Error !!");
   }
}

when i try to save then it will give an error Conversion failed when converting date/time from character string.

A: Here
Convert.ToDateTime(DT1.Value.ToShortDateString())

you convert your DateTime to a string and then back to a date. This is not necessary. Remove both conversions and use DT1.Value directly.

A: Why do you convert the DateTime to string at all just to parse it back to DateTime? If you want to remove the time component from the date use DateTime.Date:
So instead of:
Convert.ToDateTime(DT1.Value.ToShortDateString())

this
DT1.Value.Date

A: To convert a string-based date to a System.DateTime object, you can use the Convert.ToDateTime(String) method or the DateTime.Parse(String) static method
Convert.ToDateTime(DT1.Value.ToShortDateString())


text:
Q: How can I get the meta data in Json format from a GitLab URL without using a personal token key and without project ID in Python (Django framework)? I tried many codes:
 url = "https://gitlab.com/meta_tool/repository"
 parsed_url = urlparse(url)
 path_parts = parsed_url.path.split("/")
 owner = path_parts[1]
 repo_name = path_parts[2]
 gitlab = Gitlab('https://gitlab.com')
 project = gitlab.projects.get(owner+"/"+repo_name)
 print(project.name)

Or other codes but some did not work.


text:
Q: Adding RadioButtons in Android I want to add radio buttons such that only one of them is selected at a time among 4 buttons and I want to place them as:
        RadioButton1  RadioButton2
        RadioButton3  RadioButton4

I am trying the following code but 1&2 forms a grp and 3&4 forms a different grp and there are two value selected a time. Can anyone check it and share the correct way to do it?
<ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/apple" />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    >

    <RadioGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/rdogrp_main"
        android:orientation="vertical"
        >

    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/rdogrp1"
        android:orientation="horizontal"
        >

    <RadioButton
        android:id="@+id/RadioButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Orange"
        android:textColor="#000000"
        />

    <RadioButton
        android:id="@+id/RadioButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="50dp"
        android:text="BlueBerry"
        android:textColor="#000000"
        />
    </RadioGroup>

    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/rdogrp2"
        android:orientation="horizontal"
        >
    <RadioButton
        android:id="@+id/RadioButton3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Apple  "
        android:textColor="#000000"
        />

    <RadioButton
        android:id="@+id/RadioButton4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="50dp"
        android:text="Santra :P"
        android:textColor="#000000"
        />
    </RadioGroup>

    </RadioGroup>
</LinearLayout>

A: For that you need to create only one RadioGroup and add four different RadioButton.
And for adding UI refer this url : Manage Layout Inside a Horizontal Oriented Radiogroup .
I hope this will help you.

A: Try Like this..
         <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
<RadioGroup
    android:id="@+id/rdogrp_main"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <RadioButton
        android:id="@+id/RadioButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.20"
        android:text="India"
        android:textColor="#000000" />

    <RadioButton
        android:id="@+id/RadioButton2"
        android:layout_width="74dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.57"
        android:text="Austraila"
        android:textColor="#000000" />
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <RadioButton
        android:id="@+id/RadioButton3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.25"
        android:text="Srilanka  "
        android:textColor="#000000" />

    <RadioButton
        android:id="@+id/RadioButton4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.48"
        android:text="SouthAfrica"
        android:textColor="#000000" />
</LinearLayout>

 </RadioGroup>

 </LinearLayout>

Let me know if you solve the problem...

A: Ok I find a solution for you:
I know it is not the best solution but it works! :)
Just copy the xml file and activity code bellow:
Activity:
package com.example.stackoverflow;

import android.os.Bundle;
import android.app.Activity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.RadioButton;

public class MainActivity extends Activity {

    private static String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final RadioButton radiobutton1 = (RadioButton) findViewById(R.id.RadioButton1);
        final RadioButton radiobutton2 = (RadioButton) findViewById(R.id.RadioButton2);
        final RadioButton radiobutton3 = (RadioButton) findViewById(R.id.RadioButton3);
        final RadioButton radiobutton4 = (RadioButton) findViewById(R.id.RadioButton4);

        radiobutton1.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                radiobutton1.setChecked(true);
                radiobutton2.setChecked(false);
                radiobutton3.setChecked(false);
                radiobutton4.setChecked(false);
                return true;
            }
        });

        radiobutton2.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                radiobutton2.setChecked(true);
                radiobutton1.setChecked(false);
                radiobutton3.setChecked(false);
                radiobutton4.setChecked(false);
                return true;
            }
        });

        radiobutton3.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                radiobutton3.setChecked(true);
                radiobutton1.setChecked(false);
                radiobutton2.setChecked(false);
                radiobutton4.setChecked(false);
                return true;
            }
        });

        radiobutton4.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                radiobutton4.setChecked(true);
                radiobutton1.setChecked(false);
                radiobutton2.setChecked(false);
                radiobutton3.setChecked(false);
                return true;
            }
        });

    }

}

activity_main.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TableLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:background="#FFDDDDDD" >

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <RadioGroup
                android:id="@+id/rdogrp1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal" >

                <RadioButton
                    android:id="@+id/RadioButton1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Orange"
                    android:textColor="#000000" />

                <RadioButton
                    android:id="@+id/RadioButton2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="50dp"
                    android:text="BlueBerry"
                    android:textColor="#000000" />
            </RadioGroup>
        </TableRow>

        <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <RadioGroup
                android:id="@+id/rdogrp2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal" >

                <RadioButton
                    android:id="@+id/RadioButton3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Apple  "
                    android:textColor="#000000" />

                <RadioButton
                    android:id="@+id/RadioButton4"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="50dp"
                    android:text="Santra :P"
                    android:textColor="#000000" />
            </RadioGroup>
        </TableRow>
    </TableLayout>

</RelativeLayout>


text:
Q: finding the user while assigning new access token I have a website where when user logsIn, they are assigned an access and a refresh token. When the access token is expried, a request to the server is made and checks if the refresh token is present in the global array in the database. If it is, a new access token is assigned to the user.
But I wanted to ask if should also check for the user by the information given by the refresh token when it is decoded. Or it is not necessary.
Please suggest me good practice and also tell me if something is wrong with my process.
routes.post("/newAccessToken", async (req, res) => {
  const token = req.headers.cookie?.split("=")[1];
  try {
    const existingToken = await refreshTokens.findOne({
      tokens: { $in: [token] },
    });

    if (existingToken) {
      const email = await jwt.verify(token, process.env.RefreshTokenSecret);
      if (email) {
        const user = await userSchema.findOne({ email });
        if (user) {
          const newAccessToken = await jwt.sign(
            { email },
            process.env.AccessTokenSecret
          );
          res.json({ newAccessToken });
        }
      } else res.json({ message: "token is invalid" });
    } else res.json({ message: "No token found" });
  } catch (error) {
    console.log(error);
  }
});


text:
Q: Animation for moving an ImageView up and down I am new to Animation in Android and searched a lot about Move up and Down an ImageView, but there are lot tuts about move left to right. I can't find a tut to move up and Down. Can please anyone tell me how can I achieve this?
I am adding some code here, that I have learned from YouTube to move an image left to right(imga is ImageView) -
 Animation img = new TranslateAnimation(Animation.ABSOLUTE, 150, Animation.ABSOLUTE, Animation.ABSOLUTE);
            img.setDuration(3000);
            img.setFillAfter(true);

            imga.startAnimation(img);

A: Use this xml for animation
anim/up_down.xml
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:interpolator="@android:anim/linear_interpolator" >

<!-- Move -->

<translate
    android:duration="800"
    android:fillAfter="true"
    android:fromYDelta="0%p"
    android:toYDelta="70%p" />

<translate
    android:duration="800"
    android:fillAfter="true"
    android:fromYDelta="0%p"
    android:startOffset="800"
    android:toYDelta="-70%p" />

</set>

In Java Class:
// Animation
Animation animUpDown;

 // load the animation
animUpDown = AnimationUtils.loadAnimation(getApplicationContext(),
            R.anim.up_dwon);

  // start the animation
  view.startAnimation(animUpDown);

A: You need to know the logic behind movement of image or object that will animate in the axis from x to x delta or from y to y delta where

*

*Values in x=n variable to x= -n variable depict that image will move
from right to left delta

*Values in  x= -n variable to x=n variable depict that image will move
from left to right delta

*Values in  y=n variable to y=-n variable depict that image will move
from top to bottom delta

*Values in  y=-n variable to y=n variable depict that image will move
from bottom to top delta

Below image will take you to the 10 standard Mathematics

Note: Here n is considered the DP or point of the vertices.


text:
Q: Rails 4 - how to add for a scope with ".find_by_sql" another scope? I use a scope like this:
# controller

    sales_rep = Car.sales_rep(branch_id)

# model - scope
  scope :sales_rep, -> (branch_id) {
    find_by_sql("... a big, complicated query ...")
  }

This works well so far, but I need to add another "filters", such as:
sales_rep = Car.sales_rep(branch_id).by_year(params[:year]).by_year(params[:month])

I add the additional scopes to the model:
  scope :by_year, (lambda do |year|
    if year.present?
       where('YEAR(s.delivery_date) = ?', year)
    end
  end)
  scope :by_month, (lambda do |month|
    if month.present?
       self.where('MONTH(s.delivery_date) = ?', month)
    end
  end)

When I run this code, I get this error:
undefined method `by_year' for #<Array:0x007f8203f8a660>

How to make accept a find_by_sql query another scope query?
Thank you


text:
Q: issue renaming package in android studio I'm trying to rename my app package name in android studio because when I try to upload to google play it says prefix "com.example" is reserved. So I've been to manifest file - double click in "example" and then refractor this, changed to "myapps" and changed it in the whole project.
Now I try to upload it and I still get the same error message. Anybody knows how to fix this error ?
Many thanks in advance

A: It seems simple. There are many ways from which one is this:
After you change the name manually in the AndroidManifest.xml, you click on the R.java class and then press F6.
R.java resides in the app/build/generated/source/r/debug/(packagename) directory. It contains resource IDs for the things you use in the android app. Check this question for more information.
Also, Amir is right, try to use a more unique package name. Example: com.(familyname) or your company domain.
For further information, you can visit this question.


text:
Q: Actualizar una columna en función de otras 3 postgresql necesito actualizar una columna en base a la siguiente condición

Necesito actualizar la columna nombre_generadora con el campo mvietiquet cuando el campo de mvingenera sea igual a mvinprinci, entonces actualizar todos los campos que tengan ese numero en mvinprinci en nombre_generadora.
Por ejemplo, un valor de mvingenera es '040000S0' y en mvinprinci hay 20 campos que tienen ese valor, tendría que darle a esos 20 campos en nombre_generadora el nombre de mvieqtiquet que corresponde a '040000S0'.

A: No sé si ya lo has conseguido, sería de la siguiente forma:
update nombre_tabla set nombre_generadora = mvietiquet
where mvinprinci = mvingenera;

Si no añades una condición se actualizan todos los datos.


text:
Q: Does $(\mathbf{y}-\mathbf{Ax})^T(\mathbf{y}-\mathbf{Ax}) = \mathbf{x}^T\mathbf{AAx}-2\mathbf{x}^T\mathbf{Ay}+\mathbf{y}^T\mathbf{y}$ I am told, that if $\mathbf{A}$ is symmetric $\mathbf{A}^T=\mathbf{A}$ and:
$$ (\mathbf{y}-\mathbf{Ax})^T(\mathbf{y}-\mathbf{Ax}) = \mathbf{x}^T\mathbf{AAx}-2\mathbf{x}^T\mathbf{Ay}+\mathbf{y}^T\mathbf{y}$$
But I do not understand.  I get:
$$ (\mathbf{y}-\mathbf{Ax})^T(\mathbf{y}-\mathbf{Ax}) = \mathbf{x}^T\mathbf{AAx}-\mathbf{y}^T\mathbf{Ax}-\mathbf{x}^T\mathbf{Ay}+\mathbf{y}^T\mathbf{y}$$
What am I missing?  Thanks.

A: Note that $y^TAx$ = $1\times n$ times $n\times n$ times $n\times 1$, so a $1\times 1$ matrix. Thus $y^TAx = (y^TAx)^T = x^TA^Ty = x^TAy$.


text:
Q: Date and Integer Inputs get reset when Post-back occurs I have a form that a user needs to fill out. If they enter the correct values for all required fields including the "Date of Birth" and "Total number of persons to occupy apartment" the values they entered are removed during a Page Postback.
This occurs if the user fails to click on the checkbox to accept the terms and conditions. All other values including DropDownList values retain their selected values on Post-back except for the "Date of Birth" and "Total number of persons to occupy apartment".
How can I figure this out?
Application Model
public class Application
{
    public int ApplicationId { get; set; }
    public string AppFirstName { get; set; }
    public string AppLastName { get; set; }
    public DateTime AppDateOfBirth { get; set; }
    public int AppTotalPersonsOccupy { get; set; }
    public bool AppAgreeToTerms { get; set; }

    public int StateId { get; set; }
    public State State { get; set; }
}

ApplicationFormViewModel
public class ApplicationFormViewModel
{
    [Required(ErrorMessage = "First Name is required")]
    [Display(Name = "First Name")]
    [StringLength(25)]
    [MaxLength(25)]
    public string AppFirstName { get; set; }

    [Required(ErrorMessage = "Last Name is required")]
    [Display(Name = "Last Name")]
    [StringLength(25)]
    [MaxLength(25)]
    public string AppLastName { get; set; }

    [Required(ErrorMessage = "Please make a selection")]
    [Display(Name = "State")]
    public int StateId { get; set; }
    public IEnumerable<SelectListItem> States { get; set; }

    [Required(ErrorMessage = "Date of Birth is required")]
    [Display(Name = "Date of Birth")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    [DataType(DataType.Date)]
    public DateTime AppDateOfBirth { get; set; }

    [Required(ErrorMessage = "Total number of persons to occupy apartment is required")]
    [Display(Name = "Total number of persons to occupy apartment")]
    [Range(1, 10, ErrorMessage = "Must be between 1 to 10")]
    public int AppTotalPersonsOccupy { get; set; }

    //[Required(ErrorMessage = "You must exept terms to continue")]
    [Display(Name = "I agree to the pre rental application terms & conditions")]
    //[Range(typeof(bool), "false", "false", ErrorMessage = "You must accept the Terms")]
    [Controllers.ApplicationController.CheckBoxRequired(ErrorMessage = "You must agree to the terms and condtions!")]
    public bool AppAgreeToTerms { get; set; }
}

ApplicationController
public class ApplicationController : Controller
{
    private readonly ApplicationDbContext _db;

    public ApplicationController(ApplicationDbContext db)
    {
        _db = db;
    }

    // GET: /<controller>/
    public IActionResult Index()
    {
        return View();
    }

    public class CheckBoxRequired : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            //get the entered value
            var application = (ApplicationFormViewModel)validationContext.ObjectInstance;
            //Check whether the IsAccepted is selected or not.
            if (application.AppAgreeToTerms == false)
            {
                //if not checked the checkbox, return the error message.
                return new ValidationResult(ErrorMessage == null ? "You must agree to the terms and condtions!" : ErrorMessage);
            }
            return ValidationResult.Success;
        }
    }

    // GET: /Create
    public IActionResult Create()
    {
        ApplicationFormViewModel renterdropdownvm = new ApplicationFormViewModel()
        {
            States = _db.States.Select(i => new SelectListItem
            {
                Text = i.StateInt,
                Value = i.StateId.ToString()
            }),
        };
        return View(renterdropdownvm);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(ApplicationFormViewModel applicationVM)
    {
        if (ModelState.IsValid)
        {
            var applicationObj = new Application();
            {
                applicationObj.AppFirstName = applicationVM.AppFirstName;
                applicationObj.AppLastName = applicationVM.AppLastName;
                applicationObj.StateId = applicationVM.StateId;
                applicationObj.AppDateOfBirth = applicationVM.AppDateOfBirth;
                applicationObj.AppTotalPersonsOccupy = applicationVM.AppTotalPersonsOccupy;
                applicationObj.AppAgreeToTerms = applicationVM.AppAgreeToTerms;
            }

            _db.Applications.Add(applicationObj);
            await _db.SaveChangesAsync();

            var newlyCreatedId = applicationObj.ApplicationId;
            return RedirectToAction(nameof(Confirmation), new { id = newlyCreatedId });
        }

        // re-populate the dropdown field here before returning the view
        ApplicationFormViewModel applicationvmrepopulate = new ApplicationFormViewModel()
        {
            States = _db.States.Select(i => new SelectListItem
            {
                Text = i.StateInt,
                Value = i.StateId.ToString()
            }),
        };

        return View(applicationvmrepopulate);
    }

    // GET: Application/Confirmation/id
    public async Task<IActionResult> Confirmation(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var appconfirm = await _db.Applications.SingleOrDefaultAsync(m => m.ApplicationId == id);

        if (appconfirm == null)
        {
            return NotFound();
        }

        return View(appconfirm);
    }

}

Create View
<form method="post" asp-action="Create">

        <input asp-for="AppFirstName" class="form__control" />

        <input asp-for="AppLastName" class="form__control" />

        <select asp-for="StateId" asp-items="@Model.States" class="form__select-control">
            <option></option>
        </select>

        <input asp-for="AppDateOfBirth" type="date" value="" class="form__control" />

        <input asp-for="AppTotalPersonsOccupy" type="number" value="" class="form__control" />

"I AGREE TO THE TERMS AND CONDITIONS"

        <input asp-for="AppAgreeToTerms" class="form__check-input">

    <input type="submit" value="Submit Rental Application" class="btn btn__block" />

A:
This occurs if the user fails to click on the checkbox to accept the terms and conditions. All other values including DropDownList values retain their selected values on Post-back except for the "Date of Birth" and "Total number of persons to occupy apartment.

After a lot of investigation and research, I am able to find the issue
in your code. You have set the value empty as value="" while the
page has been reloaded which is not correct.
Solution:
You should modify a few of the properties within your existing code at "Create View" as below:
Instead Of

        <input asp-for="AppDateOfBirth" type="date" value="" class="form__control" />

        <input asp-for="AppTotalPersonsOccupy" type="number" value="" class="form__control" />

Note: Setting value="" as empty for your two-property AppDateOfBirth and AppTotalPersonsOccupy causing the removal of
this two input fields during post-back action.
Replace With

        <input asp-for="AppDateOfBirth" type="date" class="col-md-6 form-control" />

        <input asp-for="AppTotalPersonsOccupy" type="number"  class="col-md-6 form-control" />

Output

I have tested that in my environment and it's working as expected.


text:
Q: load URL into WebBrowser with MVVM I'm makeing an app where you have a listbox in the buttom with a logo of different websites, and a WebBrowseron the top. The idea is that when you press on a logo, the webBrowser load the corresponding page. I already make this work, but I want to remake the app with MVVM to make it better. I've made the listbox with all the logos, but I dont know how to load the URL onto the WebBrowser when I click on the logo.

A: Not 100% sure if this will work on Phone7 but worth a shot...
Fist off the WebBrowser Source property is not bindable as its not a DependancyProperty so you will have to make a helper class to create an AttachedProperty to help with the binding.
Then you can link your ListBox SelectedItem to the new LinkSource property using the Property that contains the actual link from your ListBoxItem.
Example:
Xaml:
<Window x:Class="WpfApplication8.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication8"
        Title="MainWindow" Height="233" Width="405" Name="UI">

    <StackPanel Orientation="Horizontal" DataContext="{Binding ElementName=UI}">
        <ListBox x:Name="listbox" ItemsSource="{Binding Links}" Width="100" DisplayMemberPath="Name"/>
        <WebBrowser local:WebBrowserHelper.LinkSource="{Binding ElementName=listbox, Path=SelectedItem.Site}" Width="200"/>
    </StackPanel>

</Window>

Code:
public partial class MainWindow : Window
{
    private ObservableCollection<Link> _links = new ObservableCollection<Link>();

    public MainWindow()
    {
        InitializeComponent();
        Links.Add(new Link { Name = "StackOverflow", Site = new Uri("http://stackoverflow.com/") });
        Links.Add(new Link { Name = "Google", Site = new Uri("http://www.google.com/") });
    }

    public ObservableCollection<Link> Links
    {
        get { return _links; }
        set { _links = value; }
    }
}

// ListBox item
public class Link
{
    public string Name { get; set; }
    public Uri Site { get; set; }
}

// helper calss to create AttachedProperty
public static class WebBrowserHelper
{
    public static readonly DependencyProperty LinkSourceProperty =
        DependencyProperty.RegisterAttached("LinkSource", typeof(string), typeof(WebBrowserHelper), new UIPropertyMetadata(null, LinkSourcePropertyChanged));

    public static string GetLinkSource(DependencyObject obj)
    {
        return (string)obj.GetValue(LinkSourceProperty);
    }

    public static void SetLinkSource(DependencyObject obj, string value)
    {
        obj.SetValue(LinkSourceProperty, value);
    }

    // When link changed navigate to site.
    public static void LinkSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        var browser = o as WebBrowser;
        if (browser != null)
        {
            string uri = e.NewValue as string;
            browser.Source = uri != null ? new Uri(uri) : null;
        }
    }

}

Result:

A: Your question are actually two questions.

*

*There're several ways to pick up clicks from listbox. Most basic one is <Listbox SelectedItem="{Binding selectedItem,mode=TwoWay}" ...

*To set the web browser's URL, you could implement INotifyPropertyChanged in your VM, declare public Uri browserUri { get; private set; } in your WM, be sure to raise PropertyChanged when you change the property, and in XAML <WebBrowser Source="{Binding browserUri}" />


text:
Q: Update statement in python SQLite3 with several variables So I have the following statement
cursor.execute("UPDATE IllnessTable SET (?) = (?) WHERE IllnessName = (?)",
(self.SymptomName,self.IllnessStatus[ControlVar],CurrentIllnessName))

where self.SymptomName is a String, self.IllnessStatus[ControlVar] is an integer and CurrentIllnessName is a string. The variables exist and correspond directly to my table. I'm wondering what's wrong with this SQL statement itself as I just get:
sqlite3.OperationalError: near "(": syntax error

A: You can use the ? placeholder only for literals, not for identifiers such as column names. Use string formatting in your programming language to produce a SQL with the identifiers you want.
Also, enclosing the ? in parens is not necessary.
Therefore, change to something like:
cursor.execute("UPDATE IllnessTable SET {} = ? WHERE IllnessName = ?".format(self.SymptomName),
(self.IllnessStatus[ControlVar],CurrentIllnessName))


text:
Q: Placing a device model in a Text widget I need to print my device's model in a Text widget.
I tried using the FutureBuilder widget to get the device model.
import 'package:flutter/material.dart';
import 'package:device_info/device_info.dart';

class DeviceInfoPage extends StatelessWidget {
  String s;
  Future _getModel() async{
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    return androidInfo.model;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          FutureBuilder(
            future: _getModel(),
            builder: (BuildContext context, AsyncSnapshot snap) {
              if(snap.hasData) {}
              else {}
            }
          ),
        ],
      ),
    );
  }
}

I'm trying to get the androidInfo.model string from the _getModel method. I understand that the return type is Future, so I tried using a future builder to get the value.  But now I'm at a loss.  Trying _getModel().then(value) won't work, so I don't know how to extract the device model.

A: From the snap parameter. I suppose you can do something like:
FutureBuilder(
    future: _getModel(),
    builder: (BuildContext context, AsyncSnapshot<String> snap) {
      if(snap.hasData) {
        Text('Model: ${snap.data}')
      } else {
        Text('Awaiting model...')
      }
    }
),

The recommended is to check the connection state. Check the docs example for more information and maybe refactor to something like that:
FutureBuilder<String>(
  future: _getModel(),
  builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.active:
      case ConnectionState.waiting:
        return Text('Awaiting result...');
      case ConnectionState.done:
        if (snapshot.hasError)
          return Text('Error: ${snapshot.error}');
        return Text('Result: ${snapshot.data}');
    }
    return null;
  },
)


text:
Q: Problem with API request which returns tab delimited table When I'm sending request to this API using Python
CSVContent = requests.get(f'https://api-audience.gemius.com/v1/available-periods?output=csv&session={token}').text

I get tab delimited table

How can I convert this to csv file?
When I read line by line there is extra row added
after each line in csv file :-/
enter image description here

A: you can use str.split method
it works like 'a, b, c'.split(',') # or any other delimiter
for line in csv_data:
    splitted = line.split('\t')
    print(splitted[0])

this is the most simple way
but the other more correct way is using csv module
pamreader = csv.reader(csv_data, delimiter='your delimeter')
for row in parmreader:
    print(row)


text:
Q: Modifying a result set in a Stored Procedure, then returning that modified set I am currently in the process of designing my database for a mobile/web application. When I look at competing apps I see a massive flaw in how they handle user locations. Due to the nature of the application this could cause privacy and security issues for the users.
I need to store all user's locations in my database, but I want to reduce the possibility of an outside source gaining access to this data if the user does not want it shared.
After researching possible ways of doing this, I believe it is in my best interest to return values through stored procedures, limit db user access etc.
What I want to achieve is returning the results of a stored procedure. After the results have been modified. In this case, the procedure will run through the results. Check a value on the record and omit the relevant data if required.
From what I have read and understood the best way for me to achieve this is through creating a temporary table. Run a Select Query on my actual table into a cursor. Loop through the results, check the relevant value in the record, the insert into the temp table accordingly.
E.g.
Begin Procedure
Check if temp table already exists, drop if necessary
Create Temp Table, based on schema of the "permanent" table.
Run SELECT * FROM PERMTABLE WHERE Location within bounds ORDER BY Location ASC INTO CURSOR
LOOP THROUGH CURSOR
IF 'Show_Loc' IS FALSE
INSERT INTO TEMPTABLE WITHOUT LOCATION
ELSE
INSERT AS NORMAL

SELECT * FROM TEMPTABLE
DROP TEMPTABLE
END

Is there a better way of achieving this, or am I on the right track?
Also I am concerned that there will be a large volume of requests to the same procedure. Will there be any issues if the procedure was called multiple times at the exact same time in regards to temporary tables? Do I need to generate random names, or do MySQL/SQL Server handle this automatically?

A:
Is there a better way of achieving this, or am I on the right track?

Yes there is and no, I don't think you are on the right track. There is almost no reason to use a cursor in this situation.
If ShowLocation is a value on each record in the table then this is the kind of situation where a CASE statement comes in handy.
SQL Server code would be similar to the following
CREATE PROCEDURE dbo.GetLocationData
AS
SELECT
  <all_other_fields_here>,
  CASE
     WHEN ShowLocation = 1 THEN Location
     ELSE NULL
END AS Location
FROM PERMTABLE
WHERE Location within bounds -- not entirely sure how you're doing this
ORDER BY Location;
GO


text:
Q: When using Proguard, do you need a separate config for each referenced library? My application has references to HoloEverywhere and SherlockActionBar, both which are in-workspace projects. When I enabled Proguard for the application only, it crashes giving these errors:
11-15 11:50:11.090: E/AndroidRuntime(24823): Caused by: java.lang.RuntimeException: java.lang.NoSuchMethodException: <init> [class android.app.Activity, int]
11-15 11:50:11.090: E/AndroidRuntime(24823):    at com.actionbarsherlock.a.a(Unknown Source)
11-15 11:50:11.090: E/AndroidRuntime(24823):    at org.holoeverywhere.a.a.l(Unknown Source)
11-15 11:50:11.090: E/AndroidRuntime(24823):    at org.holoeverywhere.a.a.setContentView(Unknown Source)

Is this because I only enabled Proguard for the app and not the other in-workspace projects HE and ABS?
I am using the default proguard-project.txt in the sdk and did not add any additional rules.

A: No you do not.
Use these rules to keep the referenced classes un-obfuscated.
-keep class com.actionbarsherlock.** {*;}
-keep class org.holoeverywhere.** {*;}

A: this also will help
## ActionBarSherlock 4.4.0 specific rules ##

-keep class android.support.v4.app.** { *; }
-keep interface android.support.v4.app.** { *; }
-keep class com.actionbarsherlock.** { *; }
-keep interface com.actionbarsherlock.** { *; }
-keepattributes *Annotation*

## hack for Actionbarsherlock 4.4.0, see        https://github.com/JakeWharton/ActionBarSherlock/issues/1001 ##
-dontwarn com.actionbarsherlock.internal.**


text:
Q: How to manipulate EPS files in Java? I am looking for an EPS library in Java. Our application generate images in different format on the server and we plan to add EPS support. I'd like the EPS library to be able to superimpose 2 images; foreground and background.
I did a quick search and the libraries I found do not seem ready for prime time.
Any recommendations?
Thanks.

A: Nothing leaps out, but it might be useful to simply reach out to ImageMagick to do this, possibly via JMagick or im4java, or maybe just via exec.


text:
Q: Different results for certain group if filter is applied in user function vs. no filter I have a data set which consists out of multiple describing variables (type, origin etc.) and timestamps per observation of an item. The timestamps specify different states reached by the item.
The Items are parts of different system-units, which are identified by an ID. A unit must consist of at least one item but there is no upper limit.
A much simplified example data set is:
library(tidyverse)

set.seed(10)

data <- data.frame(ID=paste(c(rep(2010,times=250),rep(2011,times=200),rep(2012,times=300)),"_",sprintf("%02d", sample(50,replace=TRUE,size=750))),
                   year=c(rep(2010,times=250),rep(2011,times=200),rep(2012,times=300)),
                   Cat=sample(c("A","B","C","D","E"),replace=TRUE,size=750)) %>%
  mutate(Time_1=strptime(paste(year,"-01-01 01:",c(sprintf("%02d",rep(59,times=750))),":",sample(2,replace=TRUE,size=750),sep=""),format="%Y-%m-%d %H:%M:%S"),
         Time_2=strptime(paste(year,"-01-01 02:",c(sprintf("%02d",sample(0,replace=TRUE,size=750))),":",sample(59,replace=TRUE,size=750),sep=""),format="%Y-%m-%d %H:%M:%S"))

Some items are considered relevant and some items are considered irrelevant. The following lookup-table gives information about that:
lookup <- data.frame(Cat=c("A","B","C","D","E"),
                     Relevant=c(TRUE,FALSE,FALSE,FALSE,TRUE))

df <- data %>%
  left_join(lookup)

I wrote a function which does the following:

*

*Applies a filter if passed as an argument

*Adds a column with the smallest timestamp per unit only considering relevant items

*Checks if the time difference between time1 and the smallest timestamp per unit matches a condition

*Returns the result as summary

For the example data set the function would look like:
foo <- function(data,Filter=FALSE) {

  new_column <- data %>%
  filter(Relevant) %>%
  group_by(ID) %>%
  slice_min(order_by = Time_2,with_ties=FALSE) %>%
  select(ID,Time_2) %>%
  rename("Time_2_mod"="Time_2") %>%
  ungroup()

  Obj <- data %>%
    {if (isFALSE(Filter)) .  else filter(.,eval(rlang::parse_expr(Filter)))} %>%
    left_join(new_column) %>%
    mutate(check=Time_2_mod-Time_1 < 90) %>%
    group_by(year) %>%
    summarise(count_checked=sum(check, na.rm=TRUE))

  return(Obj)

}

Now, the output without filter is:
> foo(df)
Joining, by = "ID"
# A tibble: 3 x 2
   year count_checked
* <dbl>         <int>
1  2010           175
2  2011           149
3  2012           245

With filter applied for some of the years I get a different result:
> foo(df,Filter="year==2010")
Joining, by = "ID"
# A tibble: 1 x 2
   year count_checked
* <dbl>         <int>
1  2010           232

> foo(df,Filter="year==2011")
Joining, by = "ID"
# A tibble: 1 x 2
   year count_checked
* <dbl>         <int>
1  2011           173

> foo(df,Filter="year==2012")
Joining, by = "ID"
# A tibble: 1 x 2
   year count_checked
* <dbl>         <int>
1  2012           245

Why is that?

A: It took me quite a while to figure it out and I got to the answer by deconstructing the function step by step. The key was to look at the result of the difference in mutate(check=Time_2_mod-Time_1 < 90). So I changed it to mutate(check=Time_2_mod-Time_1) followed by head(10) to only see the first 10 rows.
Function now is:
foo_2 <- function(data,Filter=FALSE) {

  new_column <- data %>%
    filter(Relevant) %>%
    group_by(ID) %>%
    slice_min(order_by = Time_2,with_ties=FALSE) %>%
    select(ID,Time_2) %>%
    rename("Time_2_mod"="Time_2") %>%
    ungroup()

  Obj <- data %>%
    {if (isFALSE(Filter)) .  else filter(.,eval(rlang::parse_expr(Filter)))} %>%
    left_join(new_column) %>%
    mutate(check=Time_2_mod-Time_1) %>%
    head(10)

  return(Obj)

}

Result without filtering:
> foo_2(df)
Joining, by = "ID"
          ID year Cat              Time_1              Time_2 Relevant          Time_2_mod    check
1  2010 _ 43 2010   C 2010-01-01 01:59:02 2010-01-01 02:00:40    FALSE                <NA>  NA secs
2  2010 _ 09 2010   B 2010-01-01 01:59:02 2010-01-01 02:00:49    FALSE 2010-01-01 02:00:18  76 secs
3  2010 _ 10 2010   E 2010-01-01 01:59:02 2010-01-01 02:00:55     TRUE 2010-01-01 02:00:49 107 secs
4  2010 _ 48 2010   B 2010-01-01 01:59:02 2010-01-01 02:00:47    FALSE 2010-01-01 02:00:13  71 secs
5  2010 _ 12 2010   C 2010-01-01 01:59:02 2010-01-01 02:00:54    FALSE 2010-01-01 02:00:03  61 secs
6  2010 _ 08 2010   D 2010-01-01 01:59:01 2010-01-01 02:00:45    FALSE 2010-01-01 02:00:19  78 secs
7  2010 _ 39 2010   C 2010-01-01 01:59:01 2010-01-01 02:00:24    FALSE 2010-01-01 02:00:21  80 secs
8  2010 _ 19 2010   E 2010-01-01 01:59:01 2010-01-01 02:00:21     TRUE 2010-01-01 02:00:21  80 secs
9  2010 _ 24 2010   B 2010-01-01 01:59:01 2010-01-01 02:00:51    FALSE                <NA>  NA secs
10 2010 _ 15 2010   D 2010-01-01 01:59:01 2010-01-01 02:00:43    FALSE 2010-01-01 02:00:02  61 secs

And with the filters applied:
> foo_2(df,Filter="year==2010")
Joining, by = "ID"
          ID year Cat              Time_1              Time_2 Relevant          Time_2_mod
1  2010 _ 43 2010   C 2010-01-01 01:59:02 2010-01-01 02:00:40    FALSE                <NA>
2  2010 _ 09 2010   B 2010-01-01 01:59:02 2010-01-01 02:00:49    FALSE 2010-01-01 02:00:18
3  2010 _ 10 2010   E 2010-01-01 01:59:02 2010-01-01 02:00:55     TRUE 2010-01-01 02:00:49
4  2010 _ 48 2010   B 2010-01-01 01:59:02 2010-01-01 02:00:47    FALSE 2010-01-01 02:00:13
5  2010 _ 12 2010   C 2010-01-01 01:59:02 2010-01-01 02:00:54    FALSE 2010-01-01 02:00:03
6  2010 _ 08 2010   D 2010-01-01 01:59:01 2010-01-01 02:00:45    FALSE 2010-01-01 02:00:19
7  2010 _ 39 2010   C 2010-01-01 01:59:01 2010-01-01 02:00:24    FALSE 2010-01-01 02:00:21
8  2010 _ 19 2010   E 2010-01-01 01:59:01 2010-01-01 02:00:21     TRUE 2010-01-01 02:00:21
9  2010 _ 24 2010   B 2010-01-01 01:59:01 2010-01-01 02:00:51    FALSE                <NA>
10 2010 _ 15 2010   D 2010-01-01 01:59:01 2010-01-01 02:00:43    FALSE 2010-01-01 02:00:02
           check
1        NA mins
2  1.266667 mins
3  1.783333 mins
4  1.183333 mins
5  1.016667 mins
6  1.300000 mins
7  1.333333 mins
8  1.333333 mins
9        NA mins
10 1.016667 mins

> foo_2(df,Filter="year==2011")
Joining, by = "ID"
          ID year Cat              Time_1              Time_2 Relevant          Time_2_mod
1  2011 _ 38 2011   D 2011-01-01 01:59:01 2011-01-01 02:00:17    FALSE 2011-01-01 02:00:23
2  2011 _ 25 2011   B 2011-01-01 01:59:02 2011-01-01 02:00:27    FALSE 2011-01-01 02:00:07
3  2011 _ 22 2011   C 2011-01-01 01:59:01 2011-01-01 02:00:58    FALSE 2011-01-01 02:00:20
4  2011 _ 11 2011   C 2011-01-01 01:59:01 2011-01-01 02:00:57    FALSE 2011-01-01 02:00:36
5  2011 _ 35 2011   C 2011-01-01 01:59:01 2011-01-01 02:00:03    FALSE 2011-01-01 02:00:41
6  2011 _ 29 2011   A 2011-01-01 01:59:01 2011-01-01 02:00:44     TRUE 2011-01-01 02:00:04
7  2011 _ 28 2011   A 2011-01-01 01:59:01 2011-01-01 02:00:25     TRUE 2011-01-01 02:00:13
8  2011 _ 34 2011   A 2011-01-01 01:59:01 2011-01-01 02:00:46     TRUE 2011-01-01 02:00:03
9  2011 _ 01 2011   B 2011-01-01 01:59:01 2011-01-01 02:00:43    FALSE 2011-01-01 02:00:19
10 2011 _ 08 2011   E 2011-01-01 01:59:01 2011-01-01 02:00:07     TRUE 2011-01-01 02:00:07
           check
1  1.366667 mins
2  1.083333 mins
3  1.316667 mins
4  1.583333 mins
5  1.666667 mins
6  1.050000 mins
7  1.200000 mins
8  1.033333 mins
9  1.300000 mins
10 1.100000 mins

> foo_2(df,Filter="year==2012")
Joining, by = "ID"
          ID year Cat              Time_1              Time_2 Relevant          Time_2_mod    check
1  2012 _ 15 2012   E 2012-01-01 01:59:02 2012-01-01 02:00:29     TRUE 2012-01-01 02:00:26  84 secs
2  2012 _ 18 2012   A 2012-01-01 01:59:01 2012-01-01 02:00:01     TRUE 2012-01-01 02:00:01  60 secs
3  2012 _ 08 2012   A 2012-01-01 01:59:02 2012-01-01 02:00:21     TRUE 2012-01-01 02:00:21  79 secs
4  2012 _ 10 2012   D 2012-01-01 01:59:02 2012-01-01 02:00:23    FALSE 2012-01-01 02:00:10  68 secs
5  2012 _ 03 2012   C 2012-01-01 01:59:02 2012-01-01 02:00:20    FALSE 2012-01-01 02:00:12  70 secs
6  2012 _ 02 2012   B 2012-01-01 01:59:02 2012-01-01 02:00:25    FALSE 2012-01-01 02:00:42 100 secs
7  2012 _ 46 2012   C 2012-01-01 01:59:01 2012-01-01 02:00:23    FALSE 2012-01-01 02:00:34  93 secs
8  2012 _ 22 2012   E 2012-01-01 01:59:01 2012-01-01 02:00:45     TRUE 2012-01-01 02:00:24  83 secs
9  2012 _ 27 2012   D 2012-01-01 01:59:01 2012-01-01 02:00:56    FALSE 2012-01-01 02:00:27  86 secs
10 2012 _ 35 2012   D 2012-01-01 01:59:02 2012-01-01 02:00:32    FALSE 2012-01-01 02:00:24  82 secs

You know will easily recognize that the units in the last column checkseem to depend on the year filtered. Which is only half the truth. The difference of two date/times is a difftime. And if no unit is given, the function will choose "auto"matically

a suitable set of units is chosen, the largest possible (excluding "weeks") in which all the absolute differences are greater than one.

Source
So that is what produced the inconsistency in results. It was not the filter but that the difftimes for the years 2010 and 2011 were at least one minute and therefor minutes were used as unit while in the year 2012 there was at least one difftime which was less than one minute so seconds was used as unit.
To fix that behaviour mutate(check=Time_2_mod-Time_1 < 90) should be changed to mutate(check=difftime(Time_2_mod,Time_1,units="secs") <90)
foo_3 <- function(data,Filter=FALSE) {

  new_column <- data %>%
  filter(Relevant) %>%
  group_by(ID) %>%
  slice_min(order_by = Time_2,with_ties=FALSE) %>%
  select(ID,Time_2) %>%
  rename("Time_2_mod"="Time_2") %>%
  ungroup()

  Obj <- data %>%
    {if (isFALSE(Filter)) .  else filter(.,eval(rlang::parse_expr(Filter)))} %>%
    left_join(new_column) %>%
    mutate(check=difftime(Time_2_mod,Time_1,units="secs") <90) %>%
    group_by(year) %>%
    summarise(count_checked=sum(check, na.rm=TRUE))

  return(Obj)

}

This returns consistent results with and without filtering.
> foo_3(df)
Joining, by = "ID"
# A tibble: 3 x 2
   year count_checked
* <dbl>         <int>
1  2010           175
2  2011           149
3  2012           245

> foo_3(df,Filter="year==2010")
Joining, by = "ID"
# A tibble: 1 x 2
   year count_checked
* <dbl>         <int>
1  2010           175

> foo_3(df,Filter="year==2011")
Joining, by = "ID"
# A tibble: 1 x 2
   year count_checked
* <dbl>         <int>
1  2011           149

> foo_3(df,Filter="year==2012")
Joining, by = "ID"
# A tibble: 1 x 2
   year count_checked
* <dbl>         <int>
1  2012           245


text:
Q: What is the preferred mechanism to use icons with button labels I have seen the following snippet of UI code to use icons with labels

    Save

OR
would it make sense to make combine this into a single entity (i.e. image icon plus the label).
My concern is if we choose a different theme (color scheme), then I will not be able to use different colors for my labels and might have to regenerate the image. Using the first approach gives me the flexibility to do so.

A: I dont know about the layout or the colors you are using but the following are my points:

*

*Relative alignment between the image and the text can be difficult to acheive (with my basic HTML/CSS knowledge) when you have the two separately

*You cay that you prefer to have them separate because you want the possibility to change the color of text during "color scheme changes". But are you sure you dont want to change the images as well (another set of icons)? You might have the same problem of color mismatches. (You might choose the icons in such a manner that they "go along" with all the color schemes of your site, then again you can choose the color of your labels in the same menner).
Again, I am not sure of the layout/colors you are choosing, so the definitive answer is (as always) "depends on your site"

A: Consider hyperlink cues for common link icons.  For example:
html
View Holidays

CSS
a[href $='.pdf'] {
       padding-right: 18px;
       background: transparent url(icon_pdf.gif) no-repeat center right;
    }

Styling of each can be handled in CSS.  Works for just about every file type extension out there.  This might not work for your specific example (would have to see the larger context) but it's a great trick for download links, etc.


text:
Q: Cassandra Data Model I'm working on a POC to showcase how Cassandra works. I took Digg as an example. I wanted to create a data model that'll let me:
1) Add links
2) Add a link to a user favorite list.
3) Attached predetermined tags to links
I came up with two Column Families:

*

*Links

*

*url is the key

*

*id (a generated uuid)

*user (who added it)

*favCount (no of users who favorited the link)

*upCount (no of users who liked it)

*downCount (no of users who disliked it)

*UserFavs

*

*user is the key

*

*id (as many ids as the user has favorited)

This works fine for requirements #1 and #2 above, but when I come to #3 it gets trickier. I can add tags like 'java', 'languages', 'architecture' as column names with empty values in the Links column family. But querying will take a long time, let's say if I were to find out all the links that were tagged under 'java'.
Can anyone throw some ideas of how this can be implemented.
If I'm not clear with the question, please let me know.
Thanks, Kumar

A: You could create a secondary index, i.e. a column family keyed on tag. Each row contains all the links for that particular tag. Note that this may result in very wide rows (i.e. with many columns) each of which will be stored on a single cassandra node. You might want a scheme to split these up if they get very large.
See http://www.datastax.com/docs/0.7/data_model/cfs_as_indexes
or http://pkghosh.wordpress.com/2011/03/02/cassandra-secondary-index-patterns/
or google cassandra secondary index


text:
Q: wireless network cannot be established One of our windows 7 laptop cannot connect to our wireless LAN whereas other laptops are able to connect to the same WIFI without any troubles.
When an ethernet cable is connected and wireless connection is turned ON, it says WPA-PSK2 signal is active with 54 mbps. The wireless adapter is getting an IP address of 10.10.10.1 and the ethernet adapter with 10.10.10.2.
I tried to ping both addresses from the modem and there was 50 %, 75 % and 100 % packet loss to wireless adapter and ethernet adapter has no issues.
We use a special DNS addresss supplied by the ISP and the ethernet LAN internet connection is working ok. I tried to ping another computer when wireless LAN only is enabled, it couldn't ping to other computer on the network.
So there seems to be some problem with the wireless adapter and/or driver. But when I took that laptop to a different WIFI, it connected without any problems.

A: A little bit more detail could be useful here. Specifically, what kind of router are you using? What kind of firmware on the router? Who made your wireless card? Just to be clear, is that packet loss you mentioned (50%,75%, and 100%) when your computer is plugged in via Ethernet, or is it occurring when your computer is only connected with WiFi? Have you
I doubt you've got a drive problem, considering that your ethernet works just fine and you're not reporting any symptoms traditionally associated with hard drives. The fact that the problem exists only on your network suggests that the problem has been created by some sort of conflicting settings, so I'll try and provide some guidance for resolving those.
Assuming that all your software is up-to date, try disconnecting from the network, then deleting it from your computer's list of remembered networks. Then try to reconnect.
If you're still having difficulty, try checking out the Event Viewer in Windows, and see if there's anything useful there. Also, check to see if your router has logging enabled. If that's the case, see if it's reporting any exceptions when you try to connect. With only your question to go on, I can't really provide much more detail. A reinstall of Windows could be worth a try, but it's a pain, so I'd use that as a near-to-last resort.