Q:

PHP Call to a member function on a non-object -> Classes

I want my script to read a file and create classes, then I want it to read the exact same file again so it makes changes to those classes according to what the file says. But I'm getting an error on the second While: Call to a member function getlasttrade() on a non-object.
  <?php

include ("Ideia.php");

$handle = @fopen("C:\Users\A\Desktop\Projecto ES/input.txt", "r");

if ($handle) {
    $booleanuser = FALSE;

    while (!feof($handle)) {

        $buffer = fgets($handle, 4096);
        $partial = substr($buffer, 0, 4);
        $nomeuser;
        $iduser;
        $saldo = substr($buffer, 0, 5);
        $portefolio = substr($buffer, 0, 9);
        $nomeportefolio;
        $posicaoigual = strpos($buffer, "=");

        //-------CRIA O USER----------//
        if ($partial == "user") {
            $booleanuser = TRUE;
            $nomeuser=substr($buffer, 0, 5);
            $iduser=substr($buffer, 4);
            $nomeuser = new User($iduser);
        }

        if ($booleanuser == FALSE) {
            //-------CRIA A IDEIA----------//
            if ($partial == "idea") {
                $nomeideia=substr($buffer, 0, 5);
                $idideia=substr($buffer, 4, $posicaoigual-5);
                $nomeideia = new Ideia($idideia, substr($buffer, $posicaoigual+1));
                }
        }

        if ($booleanuser == TRUE){
            //-------ADICIONA O SALDO AO USER----------//
            if ($saldo == "Saldo"){
                $nomeuser->addsaldo(substr($buffer, 7));
            //echo $nomeuser->greetuser();
            }

        //-------CRIA O PORTEFOLIO----------//
            if ($portefolio == "Portfolio"){
                $nomeportefolio="portefolio".$iduser;
                $nomeportefolio = new Portefolio($iduser,$iduser);
            }

        //------ADICIONA AS IDEIAS AO PORTEFOLIO----------//
            if ($partial == "idea"){
                $nomeportefolio->addideiasportefolio("0",substr($buffer, 4, 1), substr($buffer, $posicaoigual+1));
            }
        }
    }
    fclose($handle);
}

$letakeover = @fopen("C:\Users\Bia\Desktop\Projecto ES/input.txt", "r");
if ($letakeover) {
//-----------------------------------TAKEOVER-----------------------------------//

        //$nomeideia="idea1";
        //echo $nomeideia->getlasttrade(1);

    while (!feof($letakeover)) {

        $buffer = fgets($letakeover, 4096);
        $posicaoigual = strpos($buffer, "=");
        $idideia=substr($buffer, 4, $posicaoigual-5);
        $nomeideia = substr($buffer, $posicaoigual+1);

        echo $nomeideia->getlasttrade($idideia);
        echo "ola";
    }

    fclose($handle);
}

?>

If i write the function here it echos the right thing. Can someone help?
    if ($partial == "idea") {
        $nomeideia=substr($buffer, 0, 5);
        $idideia=substr($buffer, 4, $posicaoigual-5);
        $nomeideia = new Ideia($idideia, substr($buffer, $posicaoigual+1));
        //echo $nomeideia->getlasttrade($idideia);
    }

A:

Your first $nomeideia is an object:
$nomeideia = new Ideia($idideia, substr($buffer, $posicaoigual+1))

Your second, is clearly not:
$nomeideia = substr($buffer, $posicaoigual+1);

Either you got confused with variables (using two with the same name) or you overlooked something.
I can't tell you if you need to use a new Idea object for the second case too, though, as I do not know what your code does, but the error is clearly there.
I guess it's the same as the first one, since they look pretty similar.


Q:

Using :after pseudo element after anchor element - browser differences

I have an <a> element, after which I want to show a > sign, using the :after pseudo element.
The <a> element's content is dynamic, so its width changes, and sometimes the content event spans a few rows (since this <a> element is inside a <div> who's width is fixed).
I would like the >'s horizontal position to start at the end of the longest row. That is, when I give it that right:0; rule, it should be at the right most edge of the element (the vertical position doesn't matter right now):

That's the way it behaves in FF, but in Chrome and IE, the > appears at the end of the shortest row:

I'd like to understand what causes the difference between the browsers, but more importantly, I'd like all browsers to behave like FF - placing the :after at the end of the longest row. Is that possible?
I put the above code on dabblet

A:

That's because your a element is set to display inline by default, and Firefox handles positioning within inline elements slightly differently to Chrome and IE.
To fix this in both Chrome and IE (whilst retaining the look in Firefox), simply give your a element an inline-block display:
a {
    position:relative;
    display:inline-block;
}

Modified Dabblet demo.


Q:

Swift equivalent to each_slice

Is there something similar to Ruby's Enumerable#each_slice in Swift?
Ruby example:
arr = ["a", "b", "c", "d"]
arr.each_slice(2) {|s1, s2| puts s1 + s2 }

Output:
ab
cd

A:

As a small modification of the code from How to implement Haskell's splitEvery in Swift?, you could define an array extension
extension Array {
    func eachSlice<S>(nInEach: Int, transform: [T] -> S) -> [S] {
        var result = [S]()
        for from in stride(from: 0, to: self.count, by: nInEach) {
            let to = advance(from, nInEach, self.count)
            result.append(transform(Array(self[from ..< to])))
        }
        return result
    }
}

and then use it as
let arr = ["a", "b", "c", "d"]
arr.eachSlice(2) { println("".join($0)) }

Output:

ab
cd

Another example:
let iarr = [1, 2, 3, 4, 5, 6, 7]
let sliceSums = iarr.eachSlice(3) {
    reduce($0, 0) { $0 + $1 } // sum of slice elements
}
println(sliceSums)
// [6, 15, 7]

Update for Swift 3:
extension Array {
    func eachSlice<S>(_ nInEach: Int, transform: (ArraySlice<Element>) -> S) -> [S] {
        var result = [S]()
        var from = startIndex
        while from != endIndex {
            let to = indices.index(from, offsetBy: nInEach, limitedBy: endIndex) ?? endIndex
            result.append(transform(self[from ..< to]))
            from = to
        }
        return result
    }
}

let iarr = [1, 2, 3, 4, 5, 6, 7]
let sliceSums = iarr.eachSlice(3) { $0.reduce(0, +) }
print(sliceSums) // [6, 15, 7]


Q:

Get OAuth code from Codeigniter's SEO friendly URLs

How can I get proper redirection from an OAuth site to my CodeIgniter site using routes?
I'm receiving the following URL from an OAuth site:
http://example.com/demo/beem/login/?oauth_token=abcdefghijklmno12n3n4n5n6&oauth_verifier=j2j3j4j5j6j7j89j1j2j3j4j5j6j7j8

http://example.com/demo/ is my base URL.
When this URL is redirected to my website, it goes to the default 'welcome' controller.
Can someone guide me on using routes for this purpose?

A:

You can add to your config/routes.php file:
route['beem/login/?oauth_token=(:any)'] = 'welcome';

To redirect all the trafic from that url to your own controller called Welcome


Q:

Show multiple data in a single data in chart.js

I have design a simple graph with chart.js, Which looking cool.
But now i want to show their data between one Month to another Month.
Means their are following data:
1th january, 2017 : 12
3rd January, 2017: 16
And so on..
now i want to show their January to February data as image,which is shown below:

Here is my simple code
    var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: 'line',

    // The data for our dataset
    data: {
        labels: ["January 2017", "February 2017", "March 2017", "April 2017", "May 2017", "June 2017", "July 2017"],
        datasets: [{
            label: "My First dataset",
            backgroundColor: 'rgb(255, 99, 132,0.25)',
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 15],
            lineTension:0
        }]
    },

    // Configuration options go here
    options: {}
});

jsfiddle Here : https://jsfiddle.net/2qxj9t00/2/
I've google so many times but no any solution are their, so kindly suggest me. Thanks :)

A:

You can accomplish this using the following x-axis ticks callback function ...
ticks: {
   callback: function(e) {
      var tick = e.match(/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept|Oct|Nov|Dec).*?\d+/g)[0];
      if (tick != aR) {
         aR = tick;
         return tick;
      }
   }
}

assuming your labels array would look somewhat like this.. ["1st January 2017", "3rd January 2017", "4th February 2017", ...]
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

var aR = null; //store already returned tick
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ["1st January 2017", "3rd January 2017", "4th February 2017", "9th February 2017", "3rd March 2017", "15th March 2017"],
      datasets: [{
         label: "My First dataset",
         backgroundColor: 'rgba(255, 99, 132, 0.5)',
         borderColor: 'rgb(255, 99, 132)',
         data: [12, 16, 10, 11, 9, 15],
         lineTension: 0
      }]
   },
   options: {
      scales: {
         xAxes: [{
            ticks: {
               autoSkip: false,
               callback: function(e) {
                  var tick = e.match(/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept|Oct|Nov|Dec).*?\d+/g)[0];
                  if (tick != aR) {
                     aR = tick;
                     return tick;
                  }
               }
            }
         }],
         yAxes: [{
            ticks: {
               min: 0,
               max: 30
            }
         }]
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart" height="200"></canvas>


Q:

Change state of an existing object

Hello I am working with react context and I have encountered a problem.
I have this component that contains all the logic :
import React , {useContext} from 'react';
import {TodoContext} from '../../contexts/todo-context';
import Todo from './Todo';
import './Todos.css';

export default function TodoList() {
    const [todos , setTodos] = useContext(TodoContext);

    const markComplete = (e) => {
       setTodos(prevState => [...prevState , {...e.target.value , done:true} ]);
       console.log(todos);
    }

    return (

            {todos.map(todo => (<Todo key={todo.id} todo={todo} markComplete={markComplete} /> ))}

    )
}

I am passing down a markComplete function which will be used in the Todo component.
The Todo component :
import React from 'react'
export default function Todo({todo , markComplete}) {
    return (

            <input type="checkbox" value={todo} onChange={markComplete}></input>

{todo.title}

    )
}

Here I have a checkbox which onChange should trigger my markComplete function. This works, but the markComplete function doesnt change my state for some reason. Here's the function again :
const markComplete = (e) => {
   setTodos(prevState => [...prevState , {...e.target.value , done:true} ]);
   console.log(todos);
}

It also generates an error saying that i should pass a key down (which i am already doing)
The state :
const [todo, setTodo] = useState([
    {
        title : 'Do the dishes',
        done : false ,
        id: 123
    },
    {
        title : 'wash car',
        done : false ,
        id: 423
    },
    {
        title : 'Buy pen',
        done : false ,
        id: 323
    }
]);

A:

The way you update your state is wrong.
Note that in your todo item, you did:
<input type="checkbox" value={todo} onChange={markComplete}></input>
While todo is itself an object, meaning that when doing this:
setTodos(prevState => [...prevState , {...e.target.value , done:true} ]);

You basically spreaded the object wrongly. In fact, the result of the next state update update:
0: {title: "Do the dishes", done: false, id: 123}
1: {title: "wash car", done: false, id: 423}
2: {title: "Buy pen", done: false, id: 323}
3: {0: "[", 1: "o", 2: "b", 3: "j", 4: "e", 5: "c", 6: "t", 7: " ", 8: "O", 9: "b", 10: "j", 11: "e", 12: "c", 13: "t", 14: "]", done: true}

This explains the unique key error you got.
One possible solution would be to use a wrapper to the change handler that passes the item id and the checked status:
function Todo({todo , markComplete}) {
    const handleChange = React.useCallback(e => {
        markComplete(todo.id, e.target.checked);
    }, [todo, markComplete]);

    return (

            <input type="checkbox" value={todo.id} onChange={handleChange}></input>

{todo.title}

    )
}

markComplete:
const markComplete = (id, checked) => {
   setTodos(prevState => prevState.map(it => it.id === id ? ({ ...it, done: checked }) : it));
}

I would also recommend using useCallback in the above function.
Here's a fiddle: https://jsfiddle.net/vdzbj16a/


Q:

Selenium - Java - Unable to click a link

My problem mainly is that my code doesn't run, I tried for more than 2 hours. I have seen  many posts also, but some are written in different computer languages (not in Java), so I am confused now.
Below is my code for just clicking a button. All I want to do is click a button and go to new page.
 WebDriver driver = new HtmlUnitDriver();
 driver.get("file:///C:/Users/Sanya/Desktop/New%20folder%20(2)/page%203%20alerts.htm");

 WebElement element = driver.findElement(By.partialLinkText("Alert"));
 element.click();

A:

You can try the below one...
Actions action = new Actions(driver);
action.click(driver.findElement(By.partialLinkText("Alert"))).build().perform();

It was worked for me :-)


Q:

PHP if title contains $variable

I have my variable, $mustcontain and I have the following:
if ($getvideoviews >= $minimumvideoviews
    AND $getvideolikes >= $minimumvideolikes
    AND $VidDuration >= $minvidlenght
    AND $getchannelsubscribers >= $minsubs)

What I need is to check if $videotitle contains what´s in $mustcontain and if true then proceed to show some more information

A:

You can use strpos() or in_array():
If $mustcontain is a string:
if ($getvideoviews >= $minimumvideoviews
    && $getvideolikes >= $minimumvideolikes
    && $VidDuration >= $minvidlenght
    && $getchannelsubscribers >= $minsubs
    && strpos($videotitle, $mustcontain) !== false) {
        // do sth. with it
    }

If $mustcontain is an array:
if ($getvideoviews >= $minimumvideoviews
    && $getvideolikes >= $minimumvideolikes
    && $VidDuration >= $minvidlenght
    && $getchannelsubscribers >= $minsubs
    && in_array($videotitle, $mustcontain) !== false) {
        // do sth. with it
    }


Q:

Differences between Just in Time compilation and On Stack Replacement

Both of them pretty much do the same thing. Identify that the method is hot and compile it instead of interpreting. With OSR, you just move to the compiled version right after it gets compiled, unlike with JIT, where the compiled code gets called when the method is called for the second time.
Other than this, are there any other differences?

A:

In general, Just-in-time compilation refers to compiling native code at runtime and executing it instead of (or in addition to) interpreting. Some VMs, such as Google V8, don't even have an interpreter; they JIT compile every function that gets executed (with varying degrees of optimization).
On Stack Replacement (OSR) is a technique for switching between different implementations of the same function. For example, you could use OSR to switch from interpreted or unoptimized code to JITed code as soon as it finishes compiling.
OSR is useful in situations where you identify a function as "hot" while it is running. This might not necessarily be because the function gets called frequently; it might be called only once, but it spends a lot of time in a big loop which could benefit from optimization. When OSR occurs, the VM is paused, and the stack frame for the target function is replaced by an equivalent frame which may have variables in different locations.
OSR can also occur in the other direction: from optimized code to unoptimized code or interpreted code. Optimized code may make some assumptions about the runtime behavior of the program based on past behavior. For instance, you could convert a virtual or dynamic method call into a static call if you've only ever seen one type of receiver object. If it turns out later that these assumptions were wrong, OSR can be used to fall back to a more conservative implementation: the optimized stack frame gets converted into an unoptimized stack frame. If the VM supports inlining, you might even end up converting an optimized stack frame into several unoptimized stack frames.

A:

Yes, that's pretty much it. Just-in-time compilation can improve performance by compiling "hot spots" (spots of bytecode that are known / supposed to execute very often) of bytecode to native instructions. On-Stack Replacement complements JIT capabilities by replacing long running interpreted "hot" bytecode by it's compiled version when it becomes available. The mentioned On-Stack Replacement article shows a nice example where JIT compilation would not be very useful without OSR.


Q:

Are these questions better suited to SuperUser?

Software, script or a tool to automate managing which tests to run
When unit test fail, show the related file changes from git repo
I honestly don't remember why I thought they'd go here,
because reading them now I think I'm more asking for a way to do those things,
rather than asking for particular tools or softwares, which although necessary to achieve the goal are not really at the center of the question.
Thoughts?

A:

Thats one of the tricky things about SR - we do have a natural overlap with Superuser (and well, most of the generalist, and OS specific sites).
I think a good way to approach the problem on hand is to look at how software recommendation questions ought to be asked on SU, as opposed to SR.
Yonking from my answer on MSU

I'm trying to search for specific text fields in a directory, but only
  in .txt files - I've tried the following approaches (blah blah blah)
  but they had these specific problems (blah blah blah). I'm looking for
  an outcome thats like (foo bar baz). I run yoyodyne OS, and my system has a rocketdyne hardware text search accelerator I'd like to be able to use. How would I do this?

Is a better 'software rec' question for SU - you're focusing on a problem, mention solutions you have tried and what's the outcome you want.

I need a tool for searching for specific text fields in a directory,
  but only in .txt files

I need it to work in yoyodyne OS
It needs to be free as in beer
Since I'm have a rocketdyne hardware text search accelerator, I'd prefer to have support for this but its optional

In a sense, a good SR question is a laundry list of features. You're looking for a tool to solve your problem, as opposed to a solution solved by a tool. Your features narrow down the possible answers to avoid excessive listification.
Both of your questions are really in the fuzzy grey line between the sites IMO, and ought to be fine here.


Q:

How to change dropdown menu button title, by selecting item?

I need to change title of dropdown when I select item in the dropdown list, this is my code for now

<button type="button" class="btn btn-default dropdown-toggle" data-
toggle="dropdown">
Option: Groups
 </button>

Group 1

Group 2

Group 3

and this is jQuery
$(".dropdown-menu li a").click(function(){

 $(this).parents(".btn-group").find('.selection').text($(this).text());
 $(this).parents(".btn-group").find('.selection').val($(this).text());

});

Still doesn't change my title when I select any of these.

A:

Add this to your :

Maybe you forgot to include the JQuery library.


Q:

Lucene query returns things I'm not expecting

I'm querying a Lucene index file which structure I didn't build. This index contains Documents with fields structured like this:

As you can see the 'type' field is always empty, however the 'all' field contains data formatted in a way so that is searchable and it contains a type=ta sort of syntax.
The weird thing is that when I query this index using type:ta it actually outputs something even though the type field is always empty.
What's happening here?
EDIT
After googling a bit more I found out a weird concept (at least for me, coming from SQL database background) that data can be stored (Store.YES and Store.NO) in different ways . Lucene indexing: Store and indexing modes explained
This is a very unusual concept for me as I don't find many reasons to NOT store data. What's the reason behind using Store.NO? I will most likely always want to have the data there even though I'm not displaying it anywhere... I mean if data is indexed it must be stored anyhow, right?

A:

What's the reason behind using Store.NO?

Consider the queries:

What documents contain the term 'foo'?
What terms does document '1234' contain?

An index for the first will map term -> document. The second will map document -> term. Most people only want to use Lucene for the first type of query, so they only build the first type of index (Store.NO). If you want to do the second type of query, you'll need to build both types of indices. This takes up more space. (It is in theory possible to loop through all terms and figure out the document without actually building this index, but it's really slow.)
"Reverse index" might be a more appropriate name than "store."


Q:

The meaning of the Dexter lock in the series Dexter

Every time the series started I remember wondering about the lock on Dexter's door. I was sure I had the same one in my garage so I went to check and it turned out to be a "Dexter" lock. Is there a specific meaning to this?

A:

Well, it did look pretty solid...
But no, I don't think there was a special meaning - apart from making Dexter's normal morning-ritual look "gruesome" by using weird camera-angles.
Also, remember that the whole opening credits - plus a bit extra - were shown in one of the episodes of the first season, to show that "life is good, and everything is great in Dexter's life"...  It was also parodied in a episode right after Dexter's son is born, and he's extremely sleep-deprived due to the baby - his t-shirt got baby-food/burp stains, his shoe-laces snaps, and he looks dead tired.


Q:

Punching - Force or Momentum?

If I want to punch a person inflicting maximum damage, what do I need to care about?
My force of punching, i.e, do I need more acceleration? Or do I need momentum, i.e my velocity for punching?

A:

In the end it is the (kinetic) impact Energy $E=\frac{p^2}{2m}$ that counts, so you'll need a high momentum. However, to create this momentum you'll need force since $F=\frac{d}{dt}p$. In other words, the more the impact velocity, the more damage, but to create this velocity, you'll need acceleration


Q:

Add line break and bold text in response php

I am returning a ajax response with Symfony2 where I need to split into two lines the content of a message and put some text in bold.The function I am using is:
 public function showuserAction()
   {
    $nid=$this->get('request')->request->get('nid');
    $em = $this->getDoctrine()->getEntityManager();
    $user = $em->getRepository('Bundle:Users')->findUser($nid);

    if($user){
        return new JsonResponse(array('message' => 'This NID belongs to the user: '.$user->getName()), 200);
    }
}

ajax call:
$.ajax({
  type: 'POST',
  url: Routing.generate('showuser'),
  data: {dni:dni},
  dataType: 'json',
  success: function(response) {

    alert(response.message);

  }
 })

I hope the following results:
This NID belongs to the user:
Username formatted in bold

A:

I would suggest you send the message and username as separate fields in the returned JSON like this:
return new JsonResponse(
    array(
        'message' => 'This NID belongs to the user: ',
        'username' => $user->getName()
    ),
    200
);

And then handle how they're formatted on the front-end where the JSON is loaded.
APIs, which is what your JSON response is, should just be about data not what that data should look like, separating these two in your mind when you're coding will help keep your code cleaner and more maintainable.


Q:

Export html table to ppt on client side?

I want to know whether we have any jquery or javascript solution to convert html table to powerpoint.Only solution I got is html table export. Here we have all the export options but I want solution only for powerpoint. I can use Html table export but my concern is, for one export i should use whole plugin. Is there a sample code only for ppt?

A:

If the size of the library is a concern for you, your best bet may be to modify the js library on your own. Taking out pieces of code that may not be related to the power point functions.  And then testing, progressively making the library smaller and smaller.  Other than that I didn't find any where obvious that already has this solution available.
By performing the exercise above I was able to take the tableExport.js file from 12kb to 5kb (non minimized) while still maintaining the export to power-point functionality.
/*The MIT License (MIT)

Copyright (c) 2014 https://github.com/kayalshri/

Permission is hereby granted....
....
*/

(function($){
    $.fn.extend({
        tableExport: function(options) {
            var defaults = {
                    separator: ',',
                    ignoreColumn: [],
                    tableName:'yourTableName',
                    type:'powerpoint',
                    escape:'true',
                    htmlContent:'false',
                    consoleLog:'false'
            };

            var options = $.extend(defaults, options);
            var el = this;

            if(defaults.type == 'powerpoint'){
                //console.log($(this).html());
                var excel="
";
                // Header
                $(el).find('thead').find('tr').each(function() {
                    excel += "
";
                    $(this).filter(':visible').find('th').each(function(index,data) {
                        if ($(this).css('display') != 'none'){
                            if(defaults.ignoreColumn.indexOf(index) == -1){
                                excel += "" + parseString($(this))+ "	";
                            }
                        }
                    });
                    excel += '
';

                });

                // Row Vs Column
                var rowCount=1;
                $(el).find('tbody').find('tr').each(function() {
                    excel += "
";
                    var colCount=0;
                    $(this).filter(':visible').find('td').each(function(index,data) {
                        if ($(this).css('display') != 'none'){
                            if(defaults.ignoreColumn.indexOf(index) == -1){
                                excel += ""+parseString($(this))+"	";
                            }
                        }
                        colCount++;
                    });
                    rowCount++;
                    excel += '
';
                });
                excel += '
'

                if(defaults.consoleLog == 'true'){
                    console.log(excel);
                }

                var excelFile = "";
                excelFile += "";
                excelFile += "";
                excelFile += "";
                excelFile += "";
                excelFile += excel;
                excelFile += "";
                excelFile += "";

                var base64data = "base64," + $.base64.encode(excelFile);
                window.open('data:application/vnd.ms-'+defaults.type+';filename=exportData.doc;' + base64data);

            }

            function parseString(data){

                if(defaults.htmlContent == 'true'){
                    content_data = data.html().trim();
                }else{
                    content_data = data.text().trim();
                }

                if(defaults.escape == 'true'){
                    content_data = escape(content_data);
                }

                return content_data;
            }

        }
    });
})(jQuery);

You can replace your tableExport.js file with this code and call it the same way by passing in powerpoint as the type, or you can omit it and it will still work.

A:

You can use the same solution, by modifying the JS files to use only the part related to MS-Office. Actually, the function that transforms Porwerpoint table is the same as it transforms Excel and Word.
To do this, you would need only the jquery.base64.js file, and the file tableExport.js, but changing all the tableExport.js contents of the following:
/*The MIT License (MIT)
Copyright (c) 2014 https://github.com/kayalshri/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

(function($){
        $.fn.extend({
            tableExport: function(options) {
                var defaults = {
                        separator: ',',
                        ignoreColumn: [],
                        tableName:'yourTableName',
                        type:'excel',
                        escape:'true',
                        htmlContent:'false',
                        consoleLog:'false'
                };

                var options = $.extend(defaults, options);
                var el = this;

                if(defaults.type == 'excel' || defaults.type == 'doc'|| defaults.type == 'powerpoint'  ){
                    //console.log($(this).html());
                    var excel="
";
                    // Header
                    $(el).find('thead').find('tr').each(function() {
                        excel += "
";
                        $(this).filter(':visible').find('th').each(function(index,data) {
                            if ($(this).css('display') != 'none'){
                                if(defaults.ignoreColumn.indexOf(index) == -1){
                                    excel += "" + parseString($(this))+ "	";
                                }
                            }
                        });
                        excel += '
';

                    });

                    // Row Vs Column
                    var rowCount=1;
                    $(el).find('tbody').find('tr').each(function() {
                        excel += "
";
                        var colCount=0;
                        $(this).filter(':visible').find('td').each(function(index,data) {
                            if ($(this).css('display') != 'none'){
                                if(defaults.ignoreColumn.indexOf(index) == -1){
                                    excel += ""+parseString($(this))+"	";
                                }
                            }
                            colCount++;
                        });
                        rowCount++;
                        excel += '
';
                    });
                    excel += '
'

                    if(defaults.consoleLog == 'true'){
                        console.log(excel);
                    }

                    var excelFile = "";
                    excelFile += "";
                    excelFile += "";
                    excelFile += "";
                    excelFile += "";
                    excelFile += excel;
                    excelFile += "";
                    excelFile += "";

                    var base64data = "base64," + $.base64.encode(excelFile);
                    window.open('data:application/vnd.ms-'+defaults.type+';filename=exportData.doc;' + base64data);

                }

                function parseString(data){

                    if(defaults.htmlContent == 'true'){
                        content_data = data.html().trim();
                    }else{
                        content_data = data.text().trim();
                    }

                    if(defaults.escape == 'true'){
                        content_data = escape(content_data);
                    }

                    return content_data;
                }

            }
        });
    })(jQuery);

All other files, including jspdf folder can be deleted.
This way you can export the table  to the excel, doc and PowerPoint format (actually, when exported to doc and powerpoint, what you do is embed an Excel spreadsheet in the documents, so the plugin is the same for all three formats)
Use the plugin in the same way as the original plugin


Q:

How to copy notebooks between different Sagemaker instances?

My search didn't yield anything useful so I was wondering if there is any easy way to copy notebooks from one instance to another instance on Sagemaker? Of course other than manually downloading the notebooks on one instance and uploading to the other one!

A:

The recommended way to do this (as of 12/16/2018) would be to use the newly- launched Git integration for SageMaker Notebook Instances.

Create a Git repository for your notebooks
Commit and push changes from Notebook Instance #1 to your Git repo
Start Notebook Instance #2 using the same Git repo

This way your notebooks are persisted in the Git repo rather than on the  instance, and the Git repo can be shared by multiple instances.
https://aws.amazon.com/blogs/machine-learning/amazon-sagemaker-notebooks-now-support-git-integration-for-increased-persistence-collaboration-and-reproducibility/


Q:

selecting a range of columns in database

how can i select a range of columns in a database(Sqlserver eg..)
i have name,id,and a dynamically created columns named after dates..
do if i query from 1-1-2011 to 16-1-2011 ..the query should return all the dates between   that range...
excluding Sundays...
i am using access db with c#
so...i try is to select the columns from start date till we reach end date..
but how can it be done..(this removes Sundays too..:) )
also cant columns be selected using a index or something...like in arrays??
eg.schema  is like this,,,,,column names are (id,name,'1-1-2011','2-1-2011','4-1-2011','6-1-2011','6-1-2011')..how do i display all rows from 2-1-2011 to 6-1-2011?

A:

Try this
StringBuilder query = new StringBuilder("Select ID,Name ")
    DateTime begindate=DateTime.Parse("2-1-2011");
    DateTime enddate=DateTime.Parse("6-1-2011");
    DateTime tempDate = begindate;
    while(tempDate<=enddate )
    {
        if(tempDate.DayOfWeek!=DayOfWeek.Sunday)
        {
            if (tempDate==begindate )
            {
                query.Append(",");
            }
            query.Append(","+tempDate.ToString("dd-MM-yyyy"));
        }
        tempDate = tempDate.AddDays(1);
    }
    query.Append(" From table Name");

then execute the generated select statement.


Q:

Java DatagramSocket not receiving packets

I have made a simple program to send and receive a packet from a SA:MP server, which contains information about the specified server. This works correctly when I send the packet with a program called "Packet Sender", but my Java program just doesn't want to work. This is the code I am currently using:
        DatagramSocket dataSocket = new DatagramSocket(iPort);
        dataSocket.setSoTimeout(iTimeout);
        byte[] bytepacket = szPacket.getBytes(Charset.forName("UTF-8"));
        byte[] buf = new byte[256];
        DatagramPacket recpacket = new DatagramPacket(buf, buf.length);
        DatagramPacket packet = new DatagramPacket(bytepacket, bytepacket.length, address, iPort);
        packet.setData(bytepacket);
        packet.setAddress(address);
        packet.setPort(iPort);
        dataSocket.connect(address, iPort);
        socketConnected = true;
        System.out.println("Local port: " + dataSocket.getLocalPort());
        System.out.println("Local IP: " + dataSocket.getLocalAddress());
        System.out.println("Remote port: " + dataSocket.getPort());
        System.out.println("Remote IP: " + dataSocket.getInetAddress());
        System.out.println("Recieve Timeout: "+iTimeout+" milliseconds.");
        dataSocket.send(packet);
        System.out.println("Sent packet: "+ packet.getData());
        dataSocket.receive(recpacket);
        String recieved = new String(recpacket.getData(), 0, recpacket.getLength());
        System.out.println("Recieved packet: "+ recieved);
        dataSocket.close();
        dataSocket.disconnect();

This is my debug:
Packet: SAMPÀßµai
Local port: 7777
Local IP: /192.168.0.103
Remote port: 7777
Remote IP: samp.lawlessrp.com/192.223.24.181
Recieve Timeout: 5000 milliseconds.
Sent packet: [B@76dd3333
java.net.SocketTimeoutException: Receive timed out
at java.net.DualStackPlainDatagramSocketImpl.socketReceiveOrPeekData(Native Method)
at java.net.DualStackPlainDatagramSocketImpl.receive0(Unknown Source)
at java.net.AbstractPlainDatagramSocketImpl.receive(Unknown Source)
at java.net.DatagramSocket.receive(Unknown Source)
at lillyramcharan.blacksirrah239.tracker.main.<init>(main.java:199)
at lillyramcharan.blacksirrah239.tracker.launch.init(launch.java:17)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

In the debug "Packet" is the packet before it is converted into bytes. It is also missing one character due to it being an invalid ascii character (represented as CANCEL).
Here is a screenshot of the program I mentioned earlier, sending and returning the packet:
http://puu.sh/6gRd5.png
EDIT:
I have already tried disabling my firewall/allowing javaw (it is an applet) through my firewall, as well as packets with the port 7777 and 55056.
Any help would be appreciated!
Thanks

A:

There is nothing obviously wrong with your code, so you need to do some investigation.
For example, find and install a packet logger and use it to see if the packet is actually being send over the wire and if a reply packet is coming back from the server.

Actually, there is a possible clue in the output messages:
    Local IP: /192.168.0.103
    Remote IP: samp.lawlessrp.com/192.223.24.181

You have set up your program to listen on the IP address 192.168.0.103.  That is a private IP address.  But you are trying to talk to 192.223.24.181, which is a (notionally) public IP address.  If 192.223.24.181 is not in your organization's network(s), the chances, it won't know how to route packets to your address ... and they will get silently dropped.


Q:

Solving Math Expression in loops and storing in a dataframe with R

The below input is the sample dataset of many rows and columns. I need to perform different math calculations by iterations on these row by row and store it in a data frame.
A1 B1  B2  B3  B4  C1  C2  C3  C4  C5  C6  C7
2   6   4   4   2   3   3   4   4   1   1   6
4   2   3   5   3   2   5   5   6   2   3   0
6   2   4   6   4   22  6   5   6   3   5   77
6   3   5   7   5   0   6   5   7   4   5   6
6   4   6   8   0   6   7   0   8   5   6   5
6   5   3   9   6   7   7   6   9   6   7   4
5   6   2   4   7   6   7   7   1   2   7   5

For the first row I need to perform the below calculations
 A. A1 +    B1 + B2           + C2 + C3 + C4
 B. A1 +    B1 + B2 + B3      + C2 + C3 + C4 +C5
 C. A1 +    B1 + B2 + B3 +B4  + C2 + C3 + C4 +C5 +C6

For the second  row also  I need to perform the same calculations as first one and also for the rest of the rows
 A. A1 +    B1 + B2           + C2 + C3 + C4
 B. A1 +    B1 + B2 + B3      + C2 + C3 + C4 +C5
 C. A1 +    B1 + B2 + B3 +B4  + C2 + C3 + C4 +C5 +C6

The output of the result one should be in the following format
A   B   c
23  28  31
25  32  38
29  38  47
32  43  53
31  44  50
36  51  64

Can anyone please help me solve this issue  for iteration to solve  for large number of rows and columns

A:

xx = read.table(text = "A1 B1  B2  B3  B4  C1  C2  C3  C4  C5  C6  C7
2   6   4   4   2   3   3   4   4   1   1   6
4   2   3   5   3   2   5   5   6   2   3   0
6   2   4   6   4   22  6   5   6   3   5   77
6   3   5   7   5   0   6   5   7   4   5   6
6   4   6   8   0   6   7   0   8   5   6   5
6   5   3   9   6   7   7   6   9   6   7   4
5   6   2   4   7   6   7   7   1   2   7   5", header = T)

xx = as.matrix(xx)

# Create a matrix to multiply by
yy = matrix(0, nrow = ncol(xx), ncol = 3)
colnames(yy) = c("A", "B", "C")
rownames(yy) = colnames(xx)

# A. A1 +    B1 + B2           + C2 + C3 + C4
# B. A1 +    B1 + B2 + B3      + C2 + C3 + C4 +C5
# C. A1 +    B1 + B2 + B3 +B4  + C2 + C3 + C4 +C5 +C6
#          A1 B1 B2 B3 B4 C1 C2 C3 C4 C5 C6 C7
yy[, 1] = c(1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0)
yy[, 2] = c(1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0)
yy[, 3] = c(1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0)

xx %*% yy
#       A  B  C
# [1,] 23 28 31
# [2,] 25 32 38
# [3,] 29 38 47
# [4,] 32 43 53
# [5,] 31 44 50
# [6,] 36 51 64
# [7,] 28 34 48

You could probably make a function that generates the columns of yy if you can describe the logic behind what terms get added for each row. This is also very flexible. The matrix used is all 1's and 0's because your linear combinations are 1 * A1 + 1 * B1 + 1 * B2 + 0 * B3 + .... You could use numbers other than 1 for other linear combinations.


Q:

Ruby OpenStates NoMethodError - undefined method `map'

I'm having issues with a Ruby gem that used to work, but now doesn't.  It's openstates https://rubygems.org/gems/openstates .  The code to find Legislators doesn't seem to work anymore.  We have had this code in production for a while, but are now getting this error
NoMethodError - undefined method `map' for #<String:0x007ff0b51941c0>

openstates (0.0.1) lib/openstates/model.rb:37:in `where'

This is the how we are calling the method.
OpenStates::Legislator.where(parameters)

parameters = {:state=>"Ca"}

A:

Your code hasn't changed, the gem hasn't changed, but the API probably has.
Here's a very basic module to help you get an Array from OpenStates::Legislator.where(parameters) :
require 'open-uri'
require 'active_support/core_ext/object'

module OpenStates
  class Legislator
    @cache={}
    class << self
      def where(parameters)
        url = "https://openstates.org/api/v1/legislators/?#{parameters.to_query}"
        @cache[url] ||= get_json(url)
      end

      private

      def get_json(url)
        puts "# Downloading #{url}"
        sleep 2
        JSON.load(open(url))
      end
    end
  end
end

parameters = {:state=>"Ca"}
p OpenStates::Legislator.where(parameters).first(2)

It outputs :
# Downloading https://openstates.org/api/v1/legislators/?state=Ca
[
    {
                  "last_name" => "Gatto",
                 "updated_at" => "2016-09-24 07:16:00",
         "nimsp_candidate_id" => nil,
                  "full_name" => "Mike Gatto",
                         "id" => "CAL000123",
                 "first_name" => "Mike",
                "middle_name" => "",
                   "district" => "43",
                    "chamber" => "lower",
                      "state" => "ca",
               "votesmart_id" => "120220",
                      "party" => "Democratic",
            "+capitol_office" => {
             "phone" => "(916) 319-2043",
            "street" => "P.O. Box 942849, Room 4140",
               "zip" => "94249-0043",
              "city" => "Sacramento"
        },
                    "all_ids" => [
            "CAL000123",
            "CAL000246",
            "CAL000246",
            "CAL000367"
        ],
                     "leg_id" => "CAL000123",
                     "active" => true,
        "transparencydata_id" => "76584a5322274b9b892642b7b6ae3db5",
                  "photo_url" => "http://assembly.ca.gov/sites/assembly.ca.gov/files/memberphotos/AD43.jpg",
          "+district_offices" => [
            {
                 "phone" => "(818) 240-6330",
                "street" => "300 East Magnolia, Suite 504",
                   "zip" => "91502",
                  "city" => "Burbank"
            }
        ],
                        "url" => "http://asmdc.org/members/a43",
                    "country" => "us",
                 "created_at" => "2012-01-31 19:25:09",
                      "level" => "state",
                  "+district" => "43",
                    "offices" => [
            {
                    "fax" => nil,
                   "name" => "Capitol Office",
                  "phone" => "916-319-2043",
                "address" => "P.O. Box 942849, Room 5136\nSacramento, CA 94249-0043",
                   "type" => "capitol",
                  "email" => nil
            },
            {
                    "fax" => nil,
                   "name" => "District Office",
                  "phone" => "818-558-3043",
                "address" => "300 East Magnolia Blvd, Suite 504\nBurbank, CA 91502",
                   "type" => "district",
                  "email" => nil
            }
        ],
                     "+party" => "Democratic",
                   "suffixes" => ""
    },
    {
                  "last_name" => "Gordon",
                 "updated_at" => "2016-09-24 07:16:01",
    ...


Q:

How can my vampires hide in public?

So, my vampires are somewhat different. Here's a short summary, though it might be a lot to take in:
Vampires are created from humans by malfunctioning robotic headcrab masks. Vampires' original purpose was to be perfect soldiers, and so they possess biological immortality, perfect regeneration (no scars, regrow limbs) and peak-human physical characteristics. However, they have to eat a lot (though a lot less compared to what they can do) and can't be in the sunlight for too long without becoming significantly weakened and also risking super cancer, thanks to the designers who scrapped melanin (making vampires look albino pale) because it was "bloat" and made the synthesis of Vitamin D harder. Garlic and garlic bread works against vampires because their noses are hypersensitive.
The weak-to-sunlight thing doesn't matter for soldiers in skintight leather suits (Don't ask!), but there's this poor rich aristocrat girl (16) who just saw her parents and herself getting murdered and only survived because the blood and viscera sprayed everywhere, including the mask (tacky prop at the time).
Edit: The aforementioned mask is capable of locomotion (think of a really scary bug). It seeks out human targets and latches onto their face. Then, it wraps its legs around the head and with the help of hundreds of needles, injects nanomachines directly into the brain. These machines are responsible for turning the human into a vampire. The process finishes during nighttime and can't be reverted.
Once finished, the mask detaches and crawls away, seeking out new candidates.
And just to be clear, the masks are ancient technology if their perverted creator and being mistaken for a tacky prop wasn't a telling sign.
What is she supposed to do when Van Hellsing comes into town? "Oh don't look at me like that, I'm just your average aristocrat orphan who miraculously survived being stabbed in the chest (53 times) with a hunting knife and since then, is wearing a sombrero whenever going outside."
Sure, you probably feel sorry for a nice young lady who just lost her entire family and was non-consensually turned into Bella Swan; Hellsing doesn't.

So, aristocracy seems to be the most targeted group. A vampire usually can only rely on themselves, and we're in the Edwardian era. Also, there's Hellsing and his lackeys, who know what to look for and are above the law and money.
How can an aristocrat, who became a vampire against their will, disguise themselves when walking among humans without risking being caught?

A:

Go Clubbing
She's an aristocrat and the only surviving scion of an aristocratic family.  It's probably safe to say that she's pretty well-off.
So she can have whatever eccentricities she wants.  If she wants to sleep all day and party in the evening, she can do that, and she doesn't need to go out in public in daytime because she's tired of people recognizing her with pity in their eyes or the paparazzi hounding her when the light's good.
Makeup deals with pallor, and if you're going to dance clubs, heavy makeup seems apropos.

A:

Fake Her Own Death
If she's the sole survivor of an attack and became a vampire against her will, that carries a significant about of trauma with it. Enough trauma that a suicide would be believable. Her best shot at dodging the vampire hunter is to admit that she's a vampire to everyone in her town, declare that she's killing herself out of grief, and then promptly locking herself in her mansion and then lighting the whole thing on fire in broad daylight.
How she escapes dying from that is her problem, although I can think of numerous ways including secret passages, wells, or body doubles. Hellsing might be suspicious, sure, but vampire hunters have better things to do than going after a 16-year-old who's probably dead in the form of other vampires who definitely aren't dead.
At this point, the aristocrat enacts stage two of her plan. She flees to the largest city she can find, hoping to get lost there, and uses the remains of her family's fortune to do so. It's probably a good idea to use untraceable forms of money, like cash or gold, melted down, for this. Then, using makeup, she disguises herself by darkening her skin and gives herself a wicked burn scar across half her face, which she conceals in a hood. Now she's safe and untraceable, and she has an excuse for wearing a hood all the time.

A:

I don't have any suggestions for diet, regeneration, or pallor. However, your joke about always wearing a sombrero isn't far off. Feminine fashion of the era would actually shield a vampire from the sun quite well. Large sun-hats were all the rage, and showing too much skin was still frowned upon.
Example from a 1911 Punch cartoon:

Sources:

Edwardian Era Wikipedia entry
1900s fashion Wikipedia entry
A very comprehensive article from Bellatory


Q:

What can we infer from (x|y)=(x|z) in a real inner product space?

$(x|y) = (x|z)$
I think the vectors $y$ and $z$ are parallel to each other.
What else can be said?

A:

I think you are talking about
$$
\langle x,y \rangle=\langle x,z \rangle
$$
being true for any $x,y,z \in (V, \langle\cdot,\cdot\rangle)$, then you can not infer $y$ and $z$ being parallel to each other.
A counterexample would be $V=\mathbb{R}^3$ and $x=(1,0,0)^t, y=(0,1,0)^t$ and $z=(0,0,1)^t$. Even though with the standard inner product
$$
\langle x,y \rangle=1\cdot0+0\cdot1+0\cdot0=0=1\cdot0+0\cdot0+0\cdot1=\langle x,z \rangle
$$
your identity holds, it is obviously not true that $y$ is parallel to $z$.
However, the following holds because of the bilinearity of the inner product:
$$
\langle x,y \rangle=\langle x,z \rangle \Leftrightarrow \langle x,y-z \rangle=0
$$
which means that $x \perp y-z$.


Q:

ubuntu hanging at unpacking linux header 3.13.0-49

My Acer desktop with Ubuntu 14.04 was hanging after sudo apt-get update; sudo apt-get upgrade at the unpacking of linux header 3.13.0-49. The mouse and screen seemed frozen.

A:

I managed to ssh through from another pc, which took forever. The pc was very slow. I managed to kill some processes and then rebooted. Now if I try to log in to my profile from the acer pc it loops back to the log in screen. I can ssh in to the acer though from another pc. I tried to update & upgrade again and it came up with:
E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.

Thus ran sudo dpkg --configure -a and sudo apt-get update; sudo apt-get upgrade again. Rebooted and now I can log in using the acer pc. I think the problem was with the memory being full. I have motion cctv software that has been running for a few days and this seems to have loaded the memory which may have caused the crash. This did happen quite suddenly though ( the freeze ) so it could be something else. Needless to say the problem seems to have disappeared.


Q:

Hide/Show element on mouseover/out using jquery

On a page there are multiple elements like this

1

2

3

and
.hide{
    display:none;
}

.bodyText {

}

Now when mouse enteres the bodyText element the text should fade in and out when mouse leaves the element. What I tried:
$('.bodyText').on('mouseover', function(event){
    $(this).fadeIn();
});

$('.bodyText').on('mouseout', function(event){
    $(this).fadeOut();
});

This does absolutely nothing. Any ideas how to do this?
I want to achieve this kind of effect: http://www.google.com/intl/de/about/datacenters/gallery/index.html#/

A:

Since your
 elements are hidden they can't trigger the mouseover event - your mouse can't hover an element that is not present.
You should have them visible and hide/show a child element.
DEMO


Q:

Updating \if@firstcolumn mid-paragraph

I want to adjust the \marginnote command (from the marginnote package) to work with twocolumn documents  (like \marginpar can, but with the ability to use it e.g. inside a minipage). For this, I need to know in which column the note is.
\marginpar uses \if@firstcolumn for this (in \@addmarginpar). This switch, however, is only updated after each paragraph, leading to a wrong value in paragraphs that break over column breaks. As can be seen in the MWE below, \marginpar gets around this issue somehow.
Is it possible to update \if@firstcolumn mid-paragraph? If it is not, how can I ensure that \marginnote sets the note in the correct margin?

\documentclass[twocolumn]{article}
\setlength\columnsep{2cm}

\usepackage{marginnote}

\makeatletter

\long\def\cc#1#2{%
    \begingroup
    \count@=0%
    \loop\ifnum\count@<#1\advance\count@ 1\relax#2\repeat
    \endgroup
}

\begin{document}

\cc{22}{%
    \cc{22}{\if@firstcolumn first \else second \fi}%
    \rule{1em}{1em} \marginpar{\the\count@}%
    \cc{22}{\if@firstcolumn first \else second \fi}%
    \par
}

\end{document}

A:

you can't usefully change \if@firstcolumn mid paragraph as a paragraph is fully set (including the expansion of all macros and \if... tests) while the paragraph is being set in a single line before being broken in to lines and those lines assigned to columns.
You could (for example) use \pdfsavepos to record a position and look in the next run at the x coordinate of that position.


Q:

Cordova Android Update Broke XMLHttpRequest Downloads

I am working with Cordova Android.
I updated my Android SDK and removed then added my android platform.
cordova platform rm android
cordova platform add android

Now my XMLHttpRequest download script no longer works... I don't need help with the script as I know it works as I was using it directly before the update. Also checked my server logs and there are no errors. The files can also be accessed by directly accessing the server through a browser.
var dlUrl = "http://myserver.com/" + fileName;
var fileSystem = cordova.file.externalApplicationStorageDirectory;

window.resolveLocalFileSystemURL(fileSystem, function (dir) {
dir.getFile(fileName, {create: true}, function (file) {

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", transferCompleteDb);
oReq.responseType = "blob";
oReq.open("GET", dlUrl, true);
oReq.onload = function (oEvent) {
var blob = oReq.response;

if (oReq.status == '523' || oReq.status == '404') {
   //...
} else {
if (blob) {
    var writeToFile = saveFile(file, blob);
} else {
//...
} } };

oReq.onloadend = function () {
   //...
};

oReq.onerror = function (e) {

alert('xml error. status [' + e.target.status + '] [' + oReq.status );
//***
//*** This is where it fails. The error code is just 0, no other info
//     The request isn't even getting a chance to get a response
//      Cordova is blocking it in some setting
};

oReq.send(null);
//...

Cordova is blocking the download through some setting I am missing...
Are there any settings I should manually change inside the Android platform for newer versions?
My index header, unchanged from before the update
<meta http-equiv="Content-Security-Policy"
      content="default-src 'self' myserver.com http://myserver.com data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">

I also tried just using * for all values to open it wide open but made no change
From what I understand permissions are now prompted inside the app and I should be getting some kind of prompt if a permission is needed for the download. I have completely uninstalled and erased storage for the old app several times over before trying the new builds that will no longer work.
My other scripts are able to create folders and files in the area I am storing the download. So it is just the XMLHttpRequest code that can't be called.
Any suggestions? Spent a few days battling this one...
Thanks.

A:

Problem solved...
The Cordova update changed it so that XMLHttpRequest can only handle links with https. So all my links that used http stopped working, and of course threw no errors as that is the joy of working with Cordova. Wasted a full week on this one. Hopefully this can help someone with the same problem.
Also, your server doesn't actually have to serve https... Cordova is happy if you just add https to your http links and it will work fine.


Q:

Perl create variables from substring of another variable

I am sure this can be done with split(), but I am more interested in doing it with s// if possible.  I want to compare a supplied IP address with an array of IP addresses and find a match if existing.  I also want to consider a partial match successful only if the entire element (not a substring of the array element) is a match.
For example: Supplied IP: 10.12.13.14
If the current array element is 10.12. or 10. or 10.12.13. We can consider that a match, but not 10.12.11.
This is to find if a given IP exists in the hosts.allow TCP wrappers file on a Linux host.  I will add functionality to append the address if it is not covered in the file.  Since Partial subnet matches like 10.120. or 192.168. work, I need to test for those as well.  That is the code I am missing below where the placeholder "OR SUBSTRING MATCHES" exists.  I want to know if my $IP = "1.2.3.4"; how do I make substring variables so I can perform a string comparison on "1.2.3." and "1.2." ?
#PSEUDO CODE EXAMPLE
my @IPS = (10.12.13.14, 191.168.1.2, 10.8., 172.16. );
my $IP = "10.8.3.44";
foreach (@IPS) { if( $IP eq $_ || split(/\d+\./, 1-3, $IP) eq $_ ) { print $IP matches current IP: $_\n}
# That split is supposed to represent "10." "10.8." and "10.8.3."  That is the logic I am trying to accomplish, but I would like to use s// if it fits the job, otherwise I am open to split() or other suggestions

#REAL CODE EXAMPLE
#!/usr/bin/perl

my $IP = $ARGV[0];
my $FILE = '/etc/hosts.allow';

# Make sure it is an IP with either 157. or 140. as first octet

unless ( $IP =~ qr/(140|157)\.(\d{1,3}\.){2}\d{1,3}/ ) {
die "Usage: $0 IP Address" } else {
    open (FH, "<", "$FILE");
    foreach $LINE (<FH>) {
        if ( $LINE =~ qr/^sshd: (.*)/i ) {
            @LIST = split(", ", $1);
            foreach (@LIST) {
                chomp $_;
                if($IP eq $_) || (OR SUBSTRING MATCHES ) <-need code here {
                    print "IP ADDRESS: $IP found! \n";
                } else { print "$_ is not a match\n"};
            }
        }
    }
}

A:

How about:
if ( ($IP eq $_) || ($IP =~ /^\Q$_/) )  {


Q:

Dozer API Date Mapping config without XML

Anyone know how to convert the following into the api call format for Dozer? The documentation on the Dozer mapping site is pretty slim when it comes to the java mappings.
   <mappings>
  <configuration>
    <date-format>MM/dd/yyyy HH:mm</date-format>
  </configuration>

  <mapping wildcard="true">
    <class-a>org.dozer.vo.TestObject</class-a>
    <class-b>org.dozer.vo.TestObjectPrime</class-b>
    <field>
      dateString
      dateObject
    </field>
  </mapping>
  <mapping>
    <class-a>org.dozer.vo.SomeObject</class-a>
    <class-b>org.dozer.vo.SomeOtherObject</class-b>
    <field>
      srcField
      destField
    </field>
  </mapping>
</mappings>

A:

As of version 5.5.1 of Dozer, API syntax cannot perform all mappings. The <configuration> element in your mapping can only be done with XML.
If you can accept a version that bypasses the <configuration> limitation by adding some duplication, then the API mapping below should match your XML mapping:
BeanMappingBuilder mappingBuilder = new BeanMappingBuilder() {
    @Override
    protected void configure() {

        String dateFormat = "MM/dd/yyyy HH:mm";

        mapping(TestObject.class, TestObjectPrime.class,
                TypeMappingOptions.wildcard(true),
                TypeMappingOptions.dateFormat(dateFormat))
                .fields("dateString", "dateObject");

        mapping(SomeObject.class, SomeOtherObject.class,
                TypeMappingOptions.dateFormat(dateFormat))
                .fields("srcField", "destField");
    }
};

DozerBeanMapper apiBeanMapper = new DozerBeanMapper();
apiBeanMapper.addMapping(mappingBuilder);

If you're interested in further details, I've added a simple ApiAndXmlMappingTest example to PasteBin.


Q:

What is the relationship name of my (brother/sister)-in-law's (brother/sister) to me?

For example:

I have a sister named Charlotte
Martin has a brother named William
Charlotte is married to Martin

Martin is my brother-in-law, but what is William to me?
I originally posted this question on English.StackExchange. A commenter referred me to ask it on this stack.

A:

There is no common word (though see below) for this relationship in English, but there is one in Spanish: concuñado/a. So William is your concuñado. This word is used a lot at some of our family gatherings.
Note that cuñado/a is Spanish for brother/sister-in-law.
However the terms co-brother-in-law and co-sister-in-law are sometimes used for this in English, but they are generally used when translating to English from a language that has a specific word for the relationship.

A:

Well there isn't a special name for this - he is just your brother-in-law's brother.


Q:

How do I get a yum_package resource to run before a chef_gem package?

I am writing a recipe that uses ruby_libvirt, it requires libvirt-devel.
So I need yum_package libvirt-devel to run before chef_gem ruby_libvirt.
I put the yum_package in a recipe a head of the chef_gem, in the role runlist.
I was hoping that would force the issue.
chef_gem seems to be evaluated ahead of time.

A:

As chef_gem installs ruby gems in compile stage, you should make yum_package to run in this stage too.
yum_package 'libvirt-devel' do
  action :nothing
end.run_action :install

chef_gem 'ruby_libvirt'

chef_gem resource however should be used only in cases when Chef requires some gem to be installed (e.g. when it uses it further in recipe). If you just need to install a gem use gem_package resource. It is evaluated in execution phase like any other resource.
yum_package 'libvirt-devel'
gem_package 'ruby_libvirt'

More on compile and execution phases of Chef-run.


Q:

Would you be interested in an automatic TeX bot?

I see that many new users, who have no idea about MathJax, ask poorly formatted questions and somebody has to come along and edit them. Would you be interested to automate this? Will Math SE incorporate this bot provided it works well?

A:

I think this would be a very difficult task. In the unambiguous cases, adding math formatting doesn't add much value to the post. Added value begins where the math formatting clarifies math which is hard to read in ASCII representation, and that usually requires some decisions:

Whether 1/2a is $\frac12a$ or $\frac1{2a}$
Whether a lone a or I is a variable name or part of a sentence
Whether Ax is $A$ times $x$ or $A_x$
Whether to represent a * as $*$, $^*$, $\cdot$, $\times$ or invisible times in a given situation
Whether < and > mean $<$ and $>$ or rather $\langle$ and $\rangle$
Whether (x,y) was meant as $\begin{pmatrix}x\\y\end{pmatrix}$
Whether ncr was meant as $_nC_r$ or $n*c*r$
Whether x^y+z was meant as $x^y+z$ or $x^{y+z}$

(Feel free to edit this post to add other ambiguous notation to this list.)
You could give up in all these situations, and decide to play it safe by not editing the post at all. But in that case, the situations where adding markup would be most useful would be missed. And I think you'd end up skipping the vast majority of posts.
Or you could have your bot make the above decisions without really understanding the mathematical intention (which is often hard to understand even for human editors, so I just assume your bot has no chance of actually understanding that). In which case, chances are that you'd make the wrong decisions more often than not. In which case the poster may get downvoted because your bot made the question incomprehensible, and future editors will have to look not only at the latest text but also at its history in order to fix the problems right.
To phrase this differently: yes, if your bot were working really well, i.e. so well that it avoids all the problems I outlined above, then I'd be very interested in this, and I'd like to see it in action. In this case I'd also encourage you to publish a couple of papers on how you did all the things I consider difficult. If on the other hand the purpose of your question is figuring out whether this project is worth your time, then I'd say no, because I honestly don't believe the problems to be reasonably solvable in the near future.

Are you aware of LSTMs? Don't you think they are powerful enough for this problem?

I doubt it. As outlined above, correcting math formatting requires an understanding of the question which goes beyond mere syntax but well into the mathematical semantics. So you'd have to actually understand the question at a semantic level.
I think that if your code were able to understand math this well, then applying that technology to a sufficient corpus of math literature would almost enable the bot to not only correct the formatting but also provide answers with references from literature. Sounds extremely unlikely to me.

Can we get unedited, poorly formatted questions in bulk, to learn from it?

SEDE has all the posts. Or if you want the data offline, grab the data dump from either the torrent or the HTTP download. With the right queries, it should be possible to even obtain edits which look like they were mostly adding TeX markup, so these would provide you with a before-after kind of information. Something like this query of mine. This should be more valuable than mere unedited posts, since it also tells you what to aim for, and will give you a glimpse of what kind of edits our users do perform.


Q:

AngularJS - What is wrong with this directive I want to call on load

I have created a directive because I want to do some DOM manipulation when page loads. But it simply won't trigger. Here is my directive function:
Directive
function onLoadFixes(){
    return function (scope,element,attrs){
        $(element).on('load',function(event){
                console.log("element loaded");
                $(".breadcrumb-igdm").append($("#idBreadcrumbs").children());
                $("input").val(copyURLtoClipboard());
        });}
}

This is how it is mapped
.directive("uponLoadFixes", onLoadFixes)

HTML

{{phase.title}}

PROJECT PHASE {{phase.title}}

    <upon-load-fixes></upon-load-fixes>

                            {{stream.title}}

                            {{stage.title}}

Any pointers are welcome.
Header.html

                Page Name

 Home

Waterfall

            <upon-load-fixes></upon-load-fixes>

            <input type="text" id="copyurl" value=""> Copy URL

 Feedback

 Help

New Directive
( function(angular) {
    'use strict';

    var uponLoadFixes = function() {
        function controller() {

        }

        function link(scope, element, attrs) {
            console.log("doing something " + copyURLtoClipboard());
            element.append(angular.element(document.querySelector("#idBreadcrumbs")).children());
            angular.element(document.querySelector("#copyurl")).val(copyURLtoClipboard()); // get this function into the directive as well or make it a service

        }

        return {
            restrict : 'E',
            link : link,
            controller : controller,
            scope : {}
        };
    };

    angular.module('myMappy').directive('uponLoadFixes', [ uponLoadFixes ]);
})(angular);

A:

you don't have to use load event in angularjs,
here is an example, you should try to follow,
(function (angular) {
        'use strict';

        var uponLoadFixes = function () {
            function controller() {

            }

            function link(scope, element, attrs) {
                //here do something
                var $$breadcrumb = element.find('.breadcrumb-igdm'); //try to fin the element with angularjs
                $$breadcrumb.append($("#idBreadcrumbs").children());
                $("input").val(copyURLtoClipboard());  //get this function into the directive as well or make it a service
            }

            return {
                restrict: 'E',
                link: link,
                controller: controller,
                scope: {}
            };
        };

        angular.module('')
                .directive('uponLoadFixes', [uponLoadFixes]);
    })(angular);


Q:

Custom numeric input

Cheers! I'm not good in front-end, so, designer-peeps, do you have any idea how to realize input similar to this, from what should I start?

A:

Here is the very basic example of how it can be done. Of course you need to change the styles and adjust the elements upon your needs. However the idea should be understandable.
HTML:

–<input value="0" />+

CSS:
.spin {
    display: inline-block;
}
.spin span {
    display: inline-block;
    width: 20px;
    height: 22px;
    text-align: center;
    padding-top: 2px;
    background: #ff0;
    border: 1px solid #aaa;
    border-radius: 0 4px 4px 0;
    cursor: pointer;
}
.spin span:first-child {
    border-radius: 4px 0 0 4px;
}
.spin input {
    width: 40px;
    height: 20px;
    text-align: center;
    font-weight: bold;
}

JavaScript:
var spins = document.getElementsByClassName("spin");
for (var i = 0, len = spins.length; i < len; i++) {
    var spin = spins[i],
        span = spin.getElementsByTagName("span"),
        input = spin.getElementsByTagName("input")[0];

    input.onchange = function() { input.value = +input.value || 0; };
    span[0].onclick = function() { input.value = Math.max(0, input.value - 1); };
    span[1].onclick = function() { input.value -= -1; };
}

DEMO: http://jsfiddle.net/fPQvK/


Q:

Passing $(this) to jQuery .hover() functions

I wrote a simple tooltip functionality, to be seen here.
The thing is, in both handler functions set in .hover() I need access to $(this) and other 2 variables based on it. In order do achieve that, I declare the same 3 variables in both handlers:
$('a').hover(
    function () {
        var $this = $(this);
        var link_offset = $this.offset();
        var link_tooltip = $this.data('tooltip');
        // Rest of the code
    },
    function () {
        var $this = $(this);
        var link_offset = $this.offset();
        var link_tooltip = $this.data('tooltip');
        // Rest of the code
    }
);

DRY principle should be respected, so my question is: Is there other and smarter/less dirty way of passing the same variables set to both functions within .hover()?
Obvioulsy, the variables can't be global (and globals are evil anyway).
Any ideas how to achieve this with jQuery or pure JS?

A:

Call one named function inside the anonymous callbacks:
$('a').hover(function() {
        hoverFunc($(this), true)
    }, function() {
        hoverFunc($(this), false)
    });

function hoverFunc($this, is_hovered) {
    var link_offset = $this.offset();
    var link_tooltip = $this.data('tooltip');
    if (is_hovered) {
        console.log('ok')
        // do something
    } else {
        console.log('out')
        // do something else
    };
}

http://jsfiddle.net/mblase75/8njk2m32/


Q:

How can I determine if something is an array or an object in PHP?

What is the best way to determine if something is an array or an object in PHP?  I get a response from a web service and it's either an array or an object depending on how many returned results there are.  It is impossible to predict ahead of time how many there will be, so I need to figure out how to process it appropriately.  What is the best way to do this?
TIA.

A:

Take a look at the is_object and is_array PHP functions.

A:

is_array


Q:

html get method - two words value issue

every request with country name as an one word goes through, only "united kingdom" doesn't.
$("#content").load('view.php?country=united kingdom');

many thanks

A:

Escape United Kingdom using encodeURIComponent, mainly to replace the space with a plus sign.
Example:
country = "united kingdom";
$("#content").load('view.php?country=' + encodeURIComponent(country));

Alternatively, use the .load data parameter, which is automatically escaped.
$("#content").load('view.php', { country: "united kingdom" });

A:

Try with encodeURI:
$("#content").load(encodeURI('view.php?country=united kingdom'));


Q:

Protect assembly?

I have a .NET DLL (C#/VB) with custom controls, extension and other stuff.
I want that it should be available for me only.
Is there any way to restrict unauthorized access to a DLL?

A:

Well, do not redistribute the assembly in the first place. As soon as assembly is out in the wild, anybody can use it. You can make this harder by obfuscating it, but "entry points" will still be there and usable.
Theoretically, you can do something with CAS, but I'm not particularly sure this is at all possible.

A:

Your best option is to pack/encrypt/obfuscate the DLL as Anton pointed out. And then pray that nobody will go through all the hassle of unpacking it.
The usual term for this is simply "packing".
This is what game developers do with f.ex Sony's SecuROM.
But all packing programs have the same drawbacks:

They can be reverse-engineered and the encryption key must be embedded in the binary
They usually cost money, and those that don't (UPX) are easily unpacked.
Platform incompatability issues can be introduced by the unpacking process.
Packed binaries tend to freak Anti-viruses out.

Companies that use packers usually ship binaries that must be able to run on every thinkable computer. If you really meant it, I guess you could encrypt every single dll shipped with a unique key and then require it be ran with internet access for some challenge-response magic during the decryption phase. Overkill at any rate.
You could also make your own packer, but believe me when I say it: You don't want to go there ;)
In short, what you want is not simple to achieve even for the big players. How long does it take for a SecuROM game to show up on piratebay? So the only thing you can do is "raise the bar" and hope to go unnoticed by the good reverse-engineers.
Lastly, knowing what you're getting yourself into: Will it be worth it for you? Let's say you shipped the DLL unpacked - as it is. People will still need to reverse-engineer it to use it. Who uses undocumented 3rd-party libraries anyway? I've only done that once or twice in moments of insanity.


Q:

Using external API calls as a data source in domain-driven-design

I have a two-layer application which has the bottom layer for collecting data from external APIs and adding it to database and the second layer is for return data from database that is based on the data that I collected from the external API calls.
so I managed to put the external API calls in the infrastructure repositories with their interface in the domain.
So generally where I'm exactly stuck is to save this data that I'm collecting in database without creating a model for this data in the domain since this data is dependable on the external API I want to have this two layers totally separated collecting the data and return the other data without breaking the principles of domain-driven-design.

A:

What I will try to answer here is how DDD could help and highlight that the import is an implementation detail after you applied some DDD principle to find a useful design and an appropriated implementation.
So you need data for your App/Bounded context which will have to generate statistics (if you can put more business language here DDD will be even more helpful). What is the business use of this app ? what are the languages (Ubiquitous Language) and boundaries (BC) ? How is it going to interop with others contexts (Context Mapping).
You will need implement this model, and here you could use the concepts defined and define a persistence model (potentially the language used in the API isn't the language used by your app) and also you might need some validations and business rules during the import of the data. Because you might define Aggregates that ensure the integrity of the system, well here I am speculating. But this is a scenario how I would applied DDD and to make the point that we cannot apply DDD to import. But import is potentially an implementation detail.


Q:

How to dispaly result list into TableLayout row in android?

I have a little bit problem that displaying list data to TextView in Android. My scenario is I have a TableLayout with Default One TableRow. Inside table row, I has been created new LinearLayout. Then, Four TextView created inside LinearLayout. I adding some default value to this textview. My default value is

1, 2014-02-05, S02, 20

Here my code snippet for above scenari0.
<TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@color/sync_history_table_color"
        android:id="@+id/history_table"
        android:orientation="vertical"
        >
<TableRow
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingTop="1dp"
            android:id="@+id/row_start">

        <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="30dp" android:id="@+id/row_linear" android:layout_weight="1"
                android:background="@color/isp_home_color">

            <TextView android:layout_width="0dp" android:layout_height="match_parent" android:text="@string/sync_default_no"
                      android:id="@+id/history_display_no" android:layout_weight="0.165"
                      android:gravity="center_vertical|left" android:paddingLeft="10dp"
                      android:textColor="@color/sync_history_text_color"/>

            <TextView android:layout_width="0dp"
                      android:layout_height="match_parent"
                      android:text="@string/sync_default_date"
                      android:id="@+id/history_display_date"
                      android:layout_weight="0.5"
                      android:layout_gravity="center"
                      android:gravity="center"
                      android:textColor="@color/sync_history_text_color"/>

            <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:text="@string/sync_default_order"
                    android:id="@+id/history_display_orderid"
                    android:layout_weight="0.5"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:textColor="@color/sync_history_text_color"/>
            <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:text="@string/sync_default_qty"
                    android:id="@+id/history_display_quantity" android:layout_weight="0.5" android:layout_gravity="center"
                    android:gravity="center"
                    android:textColor="@color/sync_history_text_color"/>
        </LinearLayout>

    </TableRow>

</TableLayout>

Actually, I want to create dynamically TableRow, LinearLayout and TextView. Then, I put the list result to add these. The list result come from sqlite db. But, I can't get what I want. Here my code for looping the list and display the result. But, I got my some default value. Please pointing to me how can I get this. Thanks.
Here snippet for display list.
public void displayHistory(){
    List<IspHistoryListObject> historyList = sqlaccess.getAllItems();
    TableLayout showRow = (TableLayout) findViewById(R.id.history_table);
    int count = 0;
    for(IspHistoryListObject hl : historyList) {
        count++;
        TableRow tr = new TableRow(this);
        LinearLayout ll = new LinearLayout(this);
        ll.setLayoutParams(new LinearLayout.LayoutParams(50,30));
        TextView tv_sync_no = new TextView(this);
        TextView tv_sync_date = new TextView(this);
        TextView tv_sync_orderid = new TextView(this);
        TextView tv_sync_qty = new TextView(this);
        tv_sync_no.setText(String.valueOf(count));
        tv_sync_date.setText(hl.getSyncDate().substring(0,10));
        tv_sync_orderid.setText(hl.getSyncOrderIdRef());
        tv_sync_qty.setText(String.valueOf(hl.getQty()));
        ll.addView(tv_sync_no);
        ll.addView(tv_sync_date);
        ll.addView(tv_sync_orderid);
        ll.addView(tv_sync_qty);
        tr.addView(ll);
        showRow.addView(tr);
    }
}

A:

try this way here I gave sample or demo code you have to modify as per your requirement and still have problem let me know
main layout
1. table.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    android:orientation="vertical">
</TableLayout>

table row layout
2. table_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/history_display_no"
        android:layout_weight="0.25"
        android:gravity="center"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:id="@+id/history_display_date"
        android:layout_weight="0.25"
        android:gravity="center"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:id="@+id/history_display_orderid"
        android:layout_weight="0.25"
        android:gravity="center"/>
    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:id="@+id/history_display_quantity"
        android:layout_weight="0.25"
        android:gravity="center"/>

</TableRow>

activity class
3. Activity
public class MyActivity extends Activity {

    private TableLayout tableLayout;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.table);
        tableLayout=(TableLayout)findViewById(R.id.tableLayout);

        for (int i=0;i<5;i++){
            View tableRow = LayoutInflater.from(this).inflate(R.layout.table_item,null,false);
            TextView history_display_no  = (TextView) tableRow.findViewById(R.id.history_display_no);
            TextView history_display_date  = (TextView) tableRow.findViewById(R.id.history_display_date);
            TextView history_display_orderid  = (TextView) tableRow.findViewById(R.id.history_display_orderid);
            TextView history_display_quantity  = (TextView) tableRow.findViewById(R.id.history_display_quantity);

            history_display_no.setText(""+(i+1));
            history_display_date.setText("2014-02-05");
            history_display_orderid.setText("S0"+(i+1));
            history_display_quantity.setText(""+(20+(i+1)));
            tableLayout.addView(tableRow);
        }
    }
}


Q:

Selecting rows from ndarray via bytearray

I have a bytearray that is pulled from redis.
r.set('a', '')
r.setbit('a', 0, 1)
r.setbit('a', 1, 1)
r.setbit('a', 12, 1)

a_raw = db.get('a')
# b'\xc0\x08'
a_bin = bin(int.from_bytes(a, byteorder="big"))
# 0b1100000000001000

I want to use that bytearray to select rows from an ndarray.
arr = np.arange(12)
arr[a_raw]
# array([0, 1, 12])

Edit Both solutions work, but I found @paul-panzer's to be faster
import timeit

setup = '''import numpy as np; a = b'\\xc0\\x08'; '''

t1 = timeit.timeit('idx = np.unpackbits(np.frombuffer(a, np.uint8)); np.where(idx)',
              setup = setup, number=10000)

t2 = timeit.timeit('idx = np.array(list(bin(int.from_bytes(a, byteorder="big"))[2:])) == "1"; np.where(idx)',
              setup = setup, number=10000)

print(t1, t2)
#0.019560601096600294 0.054518797900527716

Edit 2 Actually, the from_bytes method doesn't return what I'm looking for:
redis_db.delete('timeit_test')
redis_db.setbit('timeit_test', 12666, 1)
redis_db.setbit('timeit_test', 14379, 1)
by = redis_db.get('timeit_test')

idx = np.unpackbits(np.frombuffer(by, np.uint8))
indices = np.where(idx)

idx = np.array(list(bin(int.from_bytes(by, byteorder="big"))[2:])) == "1"
indices_2 = np.where(idx)

print(indices, indices_2)
#(array([12666, 14379]),) (array([   1, 1714]),)

A:

Here is a way using unpackbits:
>>> a = b'\xc0\x08'
>>> b = np.arange(32).reshape(16, 2)
>>> c = np.arange(40).reshape(20, 2)
>>>
>>> idx = np.unpackbits(np.frombuffer(a, np.uint8))
>>>
# if the sizes match boolen indexing can be used
>>> b[idx.view(bool)]
array([[ 0,  1],
       [ 2,  3],
       [24, 25]])
>>>
# non matching sizes can be worked around using where
>>> c[np.where(idx)]
array([[ 0,  1],
       [ 2,  3],
       [24, 25]])
>>>


Q:

Why does Apple's website not make extensive use of CSS3 fonts?

Ever since Steve Jobs published his Thoughts on Flash, I've always seen Apple as advocators of open web standards. Scrolling halfway down the What is Safari page seems to confirm this notion.
So, why does Apple overwhelmingly use images for their headers? For example,

and on Retina displays,

Wouldn't it make sense, with respect to both open web standards and page load time, to instead link to the fonts in a CSS file?

A:

Apple has been notably touchy about 3rd-Party use of their fonts in the past and I'm inclined to say they still are.  Apple use to include a few fonts in OS 8, for example, which had Apple-copyrighted design.  You had access to them in that anything that specifically used that font rendered correctly, but if you wanted to be able to select the font in a text document, you had to jump through some hoops and enable it manually.
The font in question is almost definitely Myriad Pro or an Apple derivative.  You "must" purchase a license to use it commercially.
While I generally agree with your assessment of using CSS3 fonts, it seems that Apple may be more concerned with copyright.  Load time differences are probably negligible for most people accessing the Apple site.  I'm sure they have people in Marketing looking at that data.


Q:

Using the output of "du" for math in a shell script (need to strip suffix)

i have this code
strg=`du -s -BM /path/folder`
dstrg=5120
num=`expr $dstrg -$strg`
num1=`echo $num\* 100 |bc`
num2=`echo $num1/5120 |bc`
echo $num2

i get to the variable strg the folder usage at mb and then
I want to use it to remove it from the available space that is 5gb
but i got syntax error

A:

If an integer result suffices, you don't even need bc -- and in no circumstances is expr advised for use with modern shells:
#!/usr/bin/env bash
#              ^^^^- ensure that bash extensions are available

declare -- strg=$'4096M\t/path/folder'  # possible result of strg=$(du -s -BM /path/folder)

strg=${strg%%M*}   # delete everything after the first M in the string, inclusive

dstrg=5120

num=$(( ( (dstrg - strg) * 100) / 5120 ))
echo "$num"

...properly emits 20 as output.

See:

Parameter expansion -- the syntax used in ${strg%%M*}. Also see BashFAQ #100, describing string manipulation in bash in general.
Arithmetic expansion -- describing $(( )), the modern syntax (for all shells compatible with the 1991 POSIX sh standard) replacing expr.


Q:

How to merge each 5 lines into 1 line from 1100 lines

I have a file containing 1100 lines, I want to merge each 5 lines into one line for all 1100 lines.
I can do it manually, but it really takes time.
I used replace function with expression:
Find: \r\n replace with (space)
But it requires one by one replacement
Can anyone help?

My file looks like:
john
micheal
johnson
mike
alberto
lorenzo
sebstian ................ till 1100 lines

I want to make every 5 lines together in one line for all 1100, so it should look like:
john micheal johnson mike alberto
lorenzo sebstian ...... till 5
and so on

Pics to explain more:
It's currently like this:

I want it to be like this:

A:

Assuming the line separator is \r\n.
Make sure you set Search Mode to Regular Expression and . matches new-line is unchecked.
Find:
(.*)\r\n(.*)\r\n(.*)\r\n(.*)\r\n(.*)\r\n

Replace with:
\1 \2 \3 \4 \5\r\n

Explanation:
. - any character.
* - zero or more of what's before it.
So .* - zero or more of any character.
\r\n - new-line.
(...) (in brackets) - assigns what's matched the next group number, starting from 1 (so the first thing in brackets is group 1, second is group 2, third is group 3, etc.)
\1 - references the first group (similarly for \2-\5).
See this for more information.


Q:

Calculating Q value in dqn with experience replay

consider the Deep Q-Learning algorithm
1   initialize replay memory D
2   initialize action-value function Q with random weights
3   observe initial state s
4   repeat
5       select an action a
6           with probability ε select a random action
7           otherwise select a = argmaxa’Q(s,a’)
8       carry out action a
9       observe reward r and new state s’
10      store experience <s, a, r, s’> in replay memory D
11
12      sample random transitions <ss, aa, rr, ss’> from replay memory D
13      calculate target for each minibatch transition
14          if ss’ is terminal state then tt = rr
15          otherwise tt = rr + γmaxa’Q(ss’, aa’)
16      train the Q network using (tt - Q(ss, aa))^2 as loss
17
18      s = s'
19  until terminated

In step 16 the value of Q(ss, aa) is used to calculate the loss. When is this Q value calculated? At the time the action was taken or during the training itself?
Since replay memory only stores < s,a,r,s' > and not the q-value, is it safe to assume the q value will be calculated during the time of training?

A:

Yes, in step 16, when training the network, you are using the the loss function (tt - Q(ss, aa))^2 because you want to update network weights in order to approximate the most recent Q-values, computed as rr + γmaxa’Q(ss’, aa’) and used as target. Therefore, Q(ss, aa) is the current estimation, which is typically computed during training time.
Here you can find a Jupyter Notebook with a simply Deep Q-learning implementation that maybe is helpful.