Saturday, 31 August 2013

install karmasphere plugin in netbeans

install karmasphere plugin in netbeans

I want to run a hadoop mapreduce program (for example WordCount) with
netbeans. I found that there is "karmasphere studio for hadoop" that is a
plugin in netbeans. I follow the bellow instruction to install the plugin
: http://www.hadoopstudio.org/home/installation-guide/ but when I add the
plugin name and url, the "karmasphere studio" does not appearnce in my
available plugins, so I can not download and install it. I have netbeans
7.3.1 with jdk7. anybody know what should I do?

Excel VBA Run-Time Error When Pasting

Excel VBA Run-Time Error When Pasting

I need some help with Excel VBA. I get a "runtime error '1004':
Application-defined or object-defined error" on the "Sheets("Basic
Materials").Rows(lastRow1).Paste" line when trying to paste the whole row.
I used google to try to fix it, but came up with no clear solution (most
errors seemed to be with users using the select cells command for copying
and pasting).
row_last = 100
lastRow1 = 1
lastRow2 = 1
For rowfix = 2 To (row_last - 1)
If (Sheets(1).Cells(rowfix, 4).Value = "Basic Materials") Then
Sheets(1).Rows(rowfix).Copy
Sheets("Basic Materials").Rows(lastRow1).Paste
lastRow1 = lastRow1 + 1
ElseIf (Sheets(1).Cells(rowfix, 4).Value = "Change") Then
Sheets(1).Rows(rowfix).Copy
Sheets("Change").Rows(lastRow2).Paste
lastRow2 = lastRow2 + 1
End If
Next rowfix
Any help would be much appreciated!

Selenium webdriver does not click on element

Selenium webdriver does not click on element

I have an issue with selenium webdriver is not able to click on one
particular element I am using ruby and this happens on chrome. everything
works fine on firefox. Even on Chrome if I execute the script in debug
mode, it is able to click that particular element. I tried with setting
the focus on the element before click event and also with increased wait
before click. Nothing worked.
Thanks

Java Method Design query

Java Method Design query

This is a fairly rudimentary question but one that I am kind of on the
fence about. Lets say I have a class A and it has methods
method1,method2,method3,method4 and a main method.
method2 is only invoked by method1; method4 is only invoked by method3.
The solution says to invoke the method1 from main and also method2 from
main and same with method3 and 4.
So isn't it bad design to have the main method invoke method1, and method2
explicitly? What is the point of having private methods in a class if you
invoke them in the main method even though they are only dependent on a
single method in the whole class?
Wouldn't it be cleaner to call method2 from method1 and method4 from
method3 since in both cases the latter method is only invoked by the
former?
I thought this was the whole point of helper methods, so that we are able
to abstract away unnecessary details of the implementation.
Again my apologies for the simplicity of the question, I am quite new to
java.
Class A{
public static void main(String[] args){
int x = method1()
if ( x = 0){
//user wants to create a new account
method2()
}
}
private static int method1(){
//some code to check user login credentials in list of users
//if login credentials fail,user is asked if they want to create a new
account, if yes,
//method 2 is invoked
//return value is whether the user wants to create a new account or not.
}
private static void method2(){
//creates new account for user and is only invoked by method1.
}
}
In the above case wouldn't it just be easier to call method2() from
method1() instead of calling it in the main(). I would like to know if
there are any advantages or disadvantages of this style of implementation.

PHP Division with variables, not working

PHP Division with variables, not working

I am having some difficulties dividing a cart total on an e-commerce site,
in order to create a deposit amount for a customer to pay.
As you'll see below, I am trying to display 25% of the order total as a
deposit amount. however, I have tried many variations of this, and all
return "0".
If I echo any of the variable independently, they echo the correct value,
but when dividing one by the other the result is "0" everytime.
Any help is appreciated, I feel like I am missing something very simple..
Thanks
<?php $amount = $woocommerce->cart->get_total(); ?>
<?php $percent = 4; ?>
<?php $deposit = $amount / $percent; ?>
<strong><?php echo $deposit; ?></strong>

python find the 2nd highest element

python find the 2nd highest element

1.In a given array how to find the 2nd or 3rd,4th ,5th values.
2.Also if we use max() function in python what is the order of complexity
i.e, associated with this function max()
def nth_largest(li,n):
li.remove(max(li))
print max(ele) //will give me the second largest
#how to make a general algorithm to find the 2nd,3rd,4th highest value
#n is the element to be found below the highest value

Fatal error: Call to undefined function normalizamyway() php abstract class

Fatal error: Call to undefined function normalizamyway() php abstract class

I have this error in this code, I use the same structure of PHP - extend
method like extending a class , what is the problem?
abstract class lidacomentradas
{public $texto;
function __construct($entrada) {
$this->texto = $entrada;
}
abstract public function normalizaMyWay();
public function normaliza() {
$this->texto = str_replace("'",'"',$this->texto);
$this->texto = preg_replace("/[():]/", "", $this->texto);
$this->texto = NormalizaEspacos($this->texto );
normalizaMyWay();
}
}
class titulo extends lidacomentradas {
public function normalizaMyWay(){;}
public function criaUrl(){
return str_replace("
","_",(strtolower(LimpaTexto($this->texto))));
}
}
class corpo extends lidacomentradas {
public function normalizaMyWay() {
$lixo=strpos("Esta not&iacute;cia foi
acessada",$this->texto);
if ($lixo<>0) {$this->texto= substr($this->texto,0,$lixo);}
}
}

Phonegap/Cordova plugin not loading

Phonegap/Cordova plugin not loading

I created a dummy project and a sample custom plugin that would only show
the activity indicator ( the one found on the top left part of the screen
).
I'm using cordova 3.0.0
js file: js/libs/plugins/networkactivity.js
iOS file(s): NetworkActivity.h || NetworkActivity.m
my js file:
cordova.define('cordova/plugin/js/networkactivity', function(){
var exec = require("cordova/exec");
var networkactivity = function() {};
networkactivity.prototype.ShowIndicator(isHidden){
exec(null, null, "NetworkActivity", "ShowIndicator", [isHidden]);
}
var networkactivity = new networkactivity();
module.exports = networkactivity;
});
in my config.xml
in my view:
if(!window.plugins) window.plugins = {};
else{
window.plugins.networkactivity =
cordova.require("cordova/plugin/js/networkactivity");
window.plugins.networkactivity.ShowIndicator(true);
}
But My plugin doesn't seem to load. Any help?

Friday, 30 August 2013

How to hide an element for a certain user forever if clicked

How to hide an element for a certain user forever if clicked

I am trying to figure out how to hide an element to not show again if a
user clicks the dismiss button. Basically it is just a drop down with
promotional information. If the user clicks dismiss, I do not want this
element to show to that user ever again.
I would like it to function like the banner seen here http://codecanyon.net/
Is there a way to do this? I tried Googling this answer but could not
really find this example. I am assuming this needs to be achieved with
cookies. Also, if that is the case, would that cause any issues with SSL
Encrypted pages?
Here is my code:
<div id="promotional-banner">
<div id="promotional-wrapper">
<div id="promotional-container">
<p class="left"><img src="<?php echo
Mage::getStoreConfig(Mage_Core_Model_Store::XML_PATH_SECURE_BASE_URL);
?>media/wysiwyg/infortis/fortis/custom/rewards.png"
alt="Earn Rewards" title="Earn Rewards" /> Earn reward
points every time you shop at WeePumpkin.com</p>
<div class="right close-button"><span>X</span> Dismiss</div>
<div class="clear"></div>
</div>
</div>
</div>
<script type="text/javascript">
$$ = jQuery;
$$(document).ready( function() {
if ($$("#promotional-banner").is(":hidden")) {
$$("#promotional-banner").delay("1000").fadeIn();
}
$$("div.close-button").click(function(){
$$("#promotional-banner").delay("slow").fadeOut();
});
});
</script>

Thursday, 29 August 2013

Redirect POST Request in RESTful Controller - Zend Framework2

Redirect POST Request in RESTful Controller - Zend Framework2

After getting used to the RESTful Web Services in Zend Framework2, I
encountering a typical redirect problem when dealing with POST Request.
The problem is that I have furnished an extra action in my indexController
which extends AbstractRestfulController for the POST Request. But when
testing the URI in Simple Restful Client, I found out that the request is
automatically routed to the create method in the indexController.
Is there a way how I can forcefully redirect the POST Request to one of
the actions which I wanted to that is set in the routes in
module.config.php file
Well here is my indexController:
<?php
namespace Project\Controller;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\Mvc\MvcEvent as Event;
use Zend\View\Model\JsonModel as Json;
use XmlStrategy\View\Model\XmlModel as Xml;
class IndexController extends AbstractRestfulController
{
public function getList ()
{
;
}
public function get ($id)
{
;
}
public function addAction ()
{
return $this->create(array(
'test' => "Test",
));
}
public function update ($id, $data)
{
;
}
public function create ($data)
{
;
}
public function delete ($id)
{
;
}
}
This is how im furnishing the routes
<?php
namespace Project;
return array(
'router' => array(
'routes' => array(
'home' => array(
'child_routes' => array(
'project' => array(
'type' => "Segment",
'options' => array(
'route' => "/project",
'defaults' => array(
'controller' =>
"Project\Controller\Index",
),
),
'may_terminate' => true,
'child_routes' => array(
'add' => array(
'type' => "Segment",
'options' => array(
'route' => "/add",
'defalults' => array(
'contoller' =>
"Project\Controller\Index",
'action' => "add",
),
),
'may_terminate' => true,
),
),
),
),
),
),
),
'view_manager' => array(
'strategies' => array(
"ViewJsonStrategy",
"ViewXMLStrategy",
),
),
);
But as described, when the URI with POST Request
www.myproject.com/project/add, i can see that it is redirected to the
create action in my controller
This is the error "Zend\View\Renderer\PhpRenderer::render: Unable to
render template "project/index/create"; resolver could not resolve to a
file"
Any help would be appreciated.
Thanks

Wednesday, 28 August 2013

SSRS 2008 R2 Expression Issue

SSRS 2008 R2 Expression Issue

I need to do an average caluculation based on DATE NOT being in the last
full week (Sun-Sat)
If date <> lastfullweek then field else 0...
SSRS doesn't have a last full week, any ideas

JSP getAttribute() returning null

JSP getAttribute() returning null

So in my Servlet I have the following:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
req.setAttribute("colnames","ka");
req.setAttribute("items", new String[]{});
//System.out.println(req.getAttribute("colNames"));
req.getRequestDispatcher("/index.jsp").forward(req,resp);
}
My Servlet:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page isELIgnored="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>NewGem OrderInfo</title>
<script src="sorttable.js"></script>
</head>
<body>
<%= request.getAttribute("colnames") %>
<table id="table" class="sortable">
<tr>
<c:forEach items="${param.colNames}" var="col">
<td>${col}</td>
</c:forEach>
</tr>
<c:forEach items="${param.items}" var="row">
<tr>
<c:forEach items="${row.elements()}" var="value">
<td>${value}</td>
</c:forEach>
</tr>
</c:forEach>
</table>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<display-name>EntityDumpServlet</display-name>
<welcome-file-list>
<welcome-file>dump</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>EntityDumpServlet</servlet-name>
<servlet-class>
com.jpmorgan.d1.ptg.web.EntityDumpServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>EntityDumpServlet</servlet-name>
<url-pattern>/dump</url-pattern>
</servlet-mapping>
</web-app>
So I'm just running the get, have only this servlet nothing else.
I know that I should use JSTL and I am, but this was my way of checking
that it was not a JSTL problem but some what a java problem. Anyone have
any ideas?

Download image and include cookie in request

Download image and include cookie in request

I'm developing an app using MoSync. I need to download and display an
image that requires the user to be logged in to access it. The server uses
an HttpOnly cookie to maintain the session. What are my options, please?

Tuesday, 27 August 2013

Need to write the contents on next column of file for elif condition result?

Need to write the contents on next column of file for elif condition result?

I am reading from a file and checking the numbers in the second column. I
have perform the following checks:
Number is less than 0.20
Number is less than 0.30
Number is less than 0.40
Number is less than 0.50
If condition one is true write the value which satisfies the condition as
the first column in an output file.
If condition two is true write the which satisfies the condition as the
second column in the same output file.
If condition three is true write the value which satisfies the condition
as colunm3 in the the same output file.
If condition four is true write the value which satisfies the condition as
colunm4 in the the same output file.
This is what I have so far:
f = open('outfilename','r')
d = open('newfile','w')
lines = f.readlines()
for line in lines:
job = line.split()
if(float(job[2]) < 0.20):
d.write(str(job[2]))
d.write('\n')
elif(float(job[2]) < 0.30):
d.write(str(job[2]))
d.write('\n')
elif(float(job[2]) < 0.40):
d.write(str(job[2]))
d.write('\n')
elif(float(job[2]) < 0.50):
d.write(str(job[2]))
d.write('\n')
d.close()
f.close()
But I am getting this output:
0.061
0.0
0.012
0.0
0.079
0.03
0.109
0.044
0.019
0.035
0.018
0.019
0.004
0.147
0.111
0.184
0.121
0.005
0.299
0.091
0.077
0.245
0.345
0.323
0.456
0.399
0.499
Can someone help me figure out what is wrong with my code?

checking equality for two byte arrays

checking equality for two byte arrays

i am checking the equality of two byte arrays and i wanted some help
because what i have returns false even though the arrays should be equal.
within my debug i could see both of a1 and b1 are equal but it is not
going inside the while loop to increment i.
public bool Equality(byte[] a1, byte[] b1)
{
int i;
bool bEqual ;
if (a1.Length == b1.Length)
{
i = 0;
while ((i < a1.Length) && (a1[i]==b1[i]))
{
i++ ;
}
if (i == a1.Length)
{
bEqual = true;
}
}
return bEqual ;
}
this always returns false: (a1[i]==b1[i])

Exception thrown when serializing Hibernate object to JSON

Exception thrown when serializing Hibernate object to JSON

Well I'm using Hibernate to load a tiny database to some classes
representing the tables and interact with the database. All fine, and I
can really see all results... And I don't have any null field, all of them
are been used.
Here I show the "main" class (table).
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonProperty;
@JsonAutoDetect
public class Advertisement
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int id;
public SessionT session;
public int idRoom;
public String image;
public Advertisement()
{
}
/* Getters and Setters */
@JsonProperty
public int getID() /* Get example */
{
return this.id;
}
}
And also
@JsonAutoDetect
public class SessionT
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int id;
public int iStatus;
public String sStatus;
public Date dtDateStart;
public Date dtDateEnd;
public boolean bhide;
/* Constructor, Getter and Setters*/
}
My objective is generate a JSON from a LIST of Advertisement and send
through Http.
ObjectMapper mapper = new ObjectMapper();System.out.println("mapper
started!");
mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
response.getOutputStream().println(mapper.writeValueAsString(ads));
And for some reason I'm getting the following error:
org.codehaus.jackson.map.JsonMappingException: No serializer found for
class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no
properties discovered to create BeanSerializer (to avoid exception,
disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through
reference chain:
java.util.ArrayList[0]->entities.slave.Advertisement["session"]->entities.slave.SessionT_$$_javassist_2["hibernateLazyInitializer"])
I'm using jackson-all-1.9.11 and JBoss Studios 6.01
Anyone can help me??

I/O wait values on SSD vs. SATA disks

I/O wait values on SSD vs. SATA disks

I have a task where I should benchmark two servers, one that has a RAID10
SATA configuration and second server has RAID10 SSD configuration.
Both servers would be placed as gateway mail server and should provide us
an approximate value how much mail traffic they could handle and what
would happen in case of huge loads - to test this I'm sending in from
100-500 emails per second and monitoring CPU usage/Disk I/O, queue size.
The I/O wait values are similar on both servers ( SATA: peak 10%, SSD peak
11% ), but the SSD server is faster in processing emails out of the queue
- I'm wondering if the percentage of Disk I/O has different meanings on
SATA and SSD drives due to the write/read difference.
Could you suggest a best way to compare both drives (servers) and if
monitoring I/O wait is the best course of action ?
Looking forward to your suggestions!

JQuery mouseover/mouseout Function - Better Code?

JQuery mouseover/mouseout Function - Better Code?

Is there a better way to write the Following code?
I am using Aloha Editor and in my jQuery, any elements with the class
editable will get a 3px dashed border on mouseover, the code below is
working fine, and I am just wanting to know if there is a "best practice
or a better way" to write this code:
$(function(){
$('[class^="editable"]').mouseover(function(){
$(this).css('border','3px dashed #a7a7a7');
});
$('[class^="editable"]').mouseout(function(){
$(this).css('border','0px dashed #ffffff');
});
});

Calc Content-MD5 in AFNetworking

Calc Content-MD5 in AFNetworking

I'm attempting to calculate the content-md5 header for the payload of a
multipart-form upload:
NSURLRequest *request = [client multipartFormRequestWithMethod:@"POST"
path:@"/upload"
parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>
formData) {
[formData appendPartWithFileData:imageData name:@"avatar"
fileName:@"avatar.png"
mimeType:@"image/png"];
}];
I tried to read the HTTPBodyStream :
if ([request HTTPBodyStream]) {
NSInteger result;
uint8_t buffer[1024];
while((result = [[request HTTPBodyStream] read:buffer maxLength:1024])
!= 0)
{
if(result > 0) {
[data appendString:[NSString stringWithUTF8String:(char
*)buffer]];
} else {...}
}
But I end up in an infinite loop. Is there a way to do this?

Monday, 26 August 2013

Embedding TTF and using with g2d

Embedding TTF and using with g2d

I'm trying to embed a TTF font and then use draw it with Grapics2D. I've
been able to create the font, but I'm not exactly sure how to pass the
font to setFont. I make a new font here, which throws no exceptions:
private Font pixel = Font.createFont(Font.TRUETYPE_FONT,
this.getClass().getResourceAsStream("font/amora.ttf"));
But I can't figure out how to draw it with setFont();
Here's my code:
private static final long serialVersionUID = 1L;
private Timer timer;
private Char Char;
private Font pixel = Font.createFont(Font.TRUETYPE_FONT,
this.getClass().getResourceAsStream("font/amora.ttf")); <<<--------
public Board() throws FontFormatException, IOException {
addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.BLACK);
setDoubleBuffered(true);
Char = new Char();
timer = new Timer(5, this);
timer.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(Char.getImage(), Char.getX(), Char.getY(), this);
g.setColor(Color.white);
g.setFont( What goes here? ); // <------------
g.drawString("Amora Engine rev25 (acetech09)", 10, 20);
g.drawString(Char.getDebugStats(0), 10, 40);
g.drawString(Char.getDebugStats(1), 10, 60);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
public void actionPerformed(ActionEvent e) {
Char.move();
repaint();
}
}
Any help would be greatly appreciated. Thanks.

How to write Java String Program more succinctly

How to write Java String Program more succinctly

Below is a program I've written for a beginning Java course. The user
inputs their first and last name and it changes the names to Pig Latin.
The program runs fine, output is perfect but I wanted to take this further
and make the code shorter and easier to read. (Because I'm really new to
this, my code isn't the most elegant but I'd like to change that.) I built
in a default to make the first and last all lowercase so it wouldn't mess
up the end product (I'm not sure if this is necessary). (Our teacher wants
just the first letter moved to the last, add "ay" to end of each name and
capitalize the first letter of each new pig latin name.)
package pkg5003_program2;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//user input first name
System.out.print("Enter First Name:" );
Scanner scanFirst = new Scanner(System.in);
String firstName = scanFirst.next();
//default first name to all lower case
String firstLowerCase = firstName.toLowerCase();
//initialize "ay" string
String ay = new String("ay");
//switch first letter to last
String newFirst = firstLowerCase.substring(1) +
firstLowerCase.charAt(0);
//add ay string
String pigLatFirst = newFirst.concat(ay);
//user input last name
System.out.print("Enter Last Name:" );
Scanner scanLast = new Scanner(System.in);
String lastName = scanLast.next();
//default last name to all lower case
String lastLowerCase = lastName.toLowerCase();
//switch first letter to last
String newLast = lastLowerCase.substring(1) +
lastLowerCase.charAt(0);
//add ay string
String pigLatLast = newLast.concat(ay);
//change first letter to uppercase for first name
String finalFirst = pigLatFirst.substring(0,1).toUpperCase() +
pigLatFirst.substring(1);
//change first letter to uppercase for last name
String finalLast = pigLatLast.substring(0,1).toUpperCase() +
pigLatLast.substring(1);
//print output
System.out.println("In Pig latin your name is: " + finalFirst
+ " " + finalLast);
System.out.println("Program written by Ashley Dinatale");
}
}

Move data via macro

Move data via macro

OK first off, all the data is originally in a xlsm file. A macro runs (via
task scheduled)and make the tabs into csv file. Work perfectly.
Second I have a website that reads the data, and displays it in a graph.
The javascript that i used to make this work, reads the data from columns.
works perfectly.
Now for the problem... The csv files that are exported via the macro,
don't read properly. this is due to the first and last lines of data.
first line i don't need, however i can use the last line.
So here i want i ask... 1. how do i remove the first row 2. is there a way
i can move the row into the next column.
This is what it looks like now.
Auto+Hide Fit Fit Fit
No. Name Comm MTD
E00043 Julie 2
E00143 Jodie 1
E00198 Jason 0
E00289 Ronald 0
E00345 Patimah 2
E00356 Jenny 1
TARGET 6
I would like it to look like this.
No. Name Comm MTD TARGET
E001 Julie 2 6
E002 Jodie 1
E003 Jason 0
E004 Ronald 0
E005 Patimah 2
E006 Jenny 1
I don't want to manually edit the data if possible, as this process is
meant to be automated.
Any help would be appreciate

damaged /var/lib/dpkg/status no backup file

damaged /var/lib/dpkg/status no backup file

After following instructions for resolving update for 10.04 LTS I have
damaged a status file and can't find a backup file because I can't find
the /var/backups folder.

What does void(*)() mean in code

What does void(*)() mean in code

I saw this code today in some fb profile, and was not able to understand
what is and how this is working:-
(*(void(*)()) shellcode)()
Can someone please explain me, what does above code mean ?
Full Code Snippet Below :-
#include <stdio.h>
#include <string.h>
char *shellcode = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69"
"\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80";
int main(void)
{
fprintf(stdout,"Length: %d\n",strlen(shellcode));
(*(void(*)()) shellcode)();
return 0;
}
Thanks

How to align text input with sorting button inside ?

How to align text input with sorting button inside ?

I'm having bad time trying to align a clickable element on the right of a
text <input> element. It wouldn't be a problem if I would have fixed
dimensions, but the <input> will be inside of a container with variable
size. The resizing will be made with a js function. I need to place the
clickable element on the far right, inside the <td> and, the remaining
space to be filled 100% by the <input>. At this moment I'm totally
confused and I cannot come with a clean solution that doesn't involve
nested tables inside table cell.
At this moment, the clickable is <a> tag, but I'm not even sure if that's
the best approach. Need some clear advice right now.
Here is the basic code:
<html>
<head>
<style type="text/css">
table{border-collapse:collapse;}
td{
border: 1px solid black;
padding: 2px;
}
.container{
width: 100px;/*this will be dinamically resized with JS*/
}
input[type="text"]{
width: 100%;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<td>
<div class="container">
<input type="text"><a href="#" onclick="/*call
myFunc*/" >&#9650;</a>
</div>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>
data1
</td>
</tr>
</tbody>
</table>
</body>
</html>

Is there any made solution how to work with db out of UI thread?

Is there any made solution how to work with db out of UI thread?

I've looked around but didn't find a ready made solution to work with
database on a worker thread. I personally don't really like the idea to
use AsyncTask to put db operations out of UI thread, are there any more
elegant solutions? Thanks a lot and sorry if I was googling bad.

Header php Get method from list

Header php Get method from list

In test.php I have the following code:
<php?
header ('Location: $link ');
$link = $_GET["id"]
ss1 = 'http://drrd.com';
ss2 = 'http://drrd2.com';
ss3 = 'http://drrd3.com';
ss4 = 'http://drrd4.com';
ss5 = 'http://drrd5.com';
ss6 = 'http://drrd6.com';
ss7 = 'http://drrd7.com';
?>
When I go to test.php?id=ss3 the page should redirect me to http://drrd3.com/
How could I do that?

Find matrices $X$ such that for any matrix $Y$ we have $\det(X^2 + Y^2) \geq 0$ – math.stackexchange.com

Find matrices $X$ such that for any matrix $Y$ we have $\det(X^2 + Y^2)
\geq 0$ – math.stackexchange.com

What is the characterization of real matrices $X \in \mathbb{C}^{n\times
n}$ such that for any real matrix $Y \in \mathbb{R}^{n\times n}$:
$$\det(X^2 + Y^2) \geq 0?$$

Sunday, 25 August 2013

Stopping Nested Timeouts in Javascript

Stopping Nested Timeouts in Javascript

I want to execute a piece of arbitrary code and be able to stop it
whenever I want. I figured I could do this with setTimeout and then use
clearTimeout to stop it. However if the code in the timeout creates it's
own timeouts, then those keep executing even after I clear the original.
Example:
var timeoutID = setTimeout(
function(){
console.log("first event can be stopped with
clearTimout(timeoutID)");
setTimeout(function(){console.log("but not this one")}, 5000)
}, 5000)
Now one way would be to control the code being executed and make it store
the value of any additional timeouts into a global variable and clear them
all at once. But is there a better way to do this? And is there a way to
do this on arbitrary code?

Receiving error for profit calculator?

Receiving error for profit calculator?

Still new to Java and I am tasked with making a profit calculator for a
paper boy, however I received this error:
Enter the number of daily papers delivered: 50
Enter the number of Sunday papers delivered: 35
The amount collected for daily papers was: Exception in thread "main"
java.util
IllegalFormatConversionException: d != java.lang.Double
at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
at lab2b_MontelWhite.main(lab2b_MontelWhite.java:24)
Here is what I have so far:
//Paper Boy's Wages Calculator
import java.util.Scanner;
public abstract class lab2b
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in);
int x;
int y;
int result;
System.out.print("Enter the number of daily papers delivered: ");
x = input.nextInt();
System.out.print("Enter the number of Sunday papers delivered: ");
y = input.nextInt();
double dailyResult = x * .3;
System.out.printf("The amount collected for daily papers was: %d\n",
dailyResult);
int SundayResult = y * 1;
System.out.printf("The amount collected for Sunday papers was: %d\n",
SundayResult);
double totalResult = dailyResult + SundayResult;
System.out.printf("The total amount of money collected was: %d\n",
totalResult);
double ProfitResult = (SundayResult + dailyResult)/2;
System.out.printf("The paper boy's profit is: %d\n", ProfitResult);
}
}
What am I doing wrong? I have added doubles, I have changed the name of
the "results". I'm just not sure what I am doing wrong.

What in the world is a .el8 file?

What in the world is a .el8 file?

I am taking an online Latin class, and they gave me a video to watch.
A .el8.
What? el8? I have never heard of that in my life. It's supposed to be a
video, so I tried renaming it to a .mov (Latin teachers not being known
for computational excellence), but no dice.
I'm running OS X 10.8. How do I open this thing?
Running file on it shows:
/Users/admin/Desktop/U734806R4970S3962792726.mov: data
And the first few lines of looking at it in vi are as follows:
^@^@^@^@^[U734806R4970S3962792726.el8T^L°w<80> ú#^?^G^@^@<88>
ú#Ä^@#^@ÀÚ°wsÒѳ^@^@#^@^@
^@^@x^@ú#^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@üîÓ^P^Kê°wvp³wgÒѳ^@^@#^@^@^@^@^@^@^@^@^@
-#^@^@^@^@^@^B^D^@^@à(D
^@^@^@^@^PÖh
^@^@#^@^B^D#%^@^@^@^@
-#^@þ^C^@^@TïÓ^Pðo³w^@^@^@^@^@^@#^@^@^@#^@ø;^@^@ÿ<9e>iê^DÀCä@âQ<8c>PÂCä@5^X^@^@^R7
^A^@^@^@ÔîÓ^P>^\±w^@^@#^@à(D^@^@^@^@^@^@^@^@^@^@^@#^@à(D
^@^@#^@þ^C^@ý^D^@^@^@^XÖh
^XÖh
¸c0
þ^C^@^@~^C^@^@ÌïÓ^P×<93>³w^@^@#^@à(D
^@^H^@^@¢s³wWÓѳ^@^@^@^@^@^@#^@è(D
<82>^C^@^@H.V
¨$î#^P ^@^@<94><82>¯w§Óѳ^B^D^@^@0.#^@^@^@^@^@^@^@#^@^PïÓ^P -#^@hïÓ^P^XÖh
H.V
xïÓ^P<9b><82>¯^@^@^@^@^@^@çiv^XÖh
^C^@^@^@<84>ïÓ^Phã°w0^A#^@¨^Fÿ^@þÿÿÿ¢s³wÕs³w^@^@^@^@^XÖh
<94><82>¯w?Óѳ^@^H^@^@è(D
^@^@^@^@^@^@^@^@ò½^@^@;C:\eLecta\Server\TempRecordings\U734806R4970S3962792726.el8¢s³wÕs³w^@^@^@^@è(D

Saturday, 24 August 2013

Mysql query optimization Multi Column Index solves this slowness?

Mysql query optimization Multi Column Index solves this slowness?

+----------------------------+------------------------------------------------------------------------------+------+-----+---------+----------------+
| Field | Type
| Null | Key | Default | Extra |
+----------------------------+------------------------------------------------------------------------------+------+-----+---------+----------------+
| type |
enum('Website','Facebook','Twitter','Linkedin','Youtube','SeatGeek','Yahoo')
| NO | MUL | NULL | |
| name | varchar(100)
| YES | MUL | NULL | |
| processing_interface_id | bigint(20)
| YES | MUL | NULL | |
| processing_interface_table | varchar(100)
| YES | MUL | NULL | |
| create_time | datetime
| YES | MUL | NULL | |
| run_time | datetime
| YES | MUL | NULL | |
| completed_time | datetime
| YES | MUL | NULL | |
| reserved | int(10)
| YES | MUL | NULL | |
| params | text
| YES | | NULL | |
| params_md5 | varchar(100)
| YES | MUL | NULL | |
| priority | int(10)
| YES | MUL | NULL | |
| id | bigint(20) unsigned
| NO | PRI | NULL | auto_increment |
| status | varchar(40)
| NO | MUL | none | |
+----------------------------+------------------------------------------------------------------------------+------+-----+---------+----------------+
select * from remote_request use index ( processing_order ) where
remote_request.status = 'none' and type = 'Facebook' and reserved = '0'
order by priority desc limit 0, 40;
This table receives an extremely large amount of writes and reads. each
remote_request ends up being a process, which can spawn anywhere between 0
and 5 other remote_requests depending on the type of request, and what the
request does.
The table is currently sitting at about 3.5 Million records, and it goes
to a snail pace when the site itself is under heavy load and I have more
then 50 or more instances running simultaneously. (REST requests are the
purpose of the table just in case you were not sure).
As the table grows it just gets worse and worse. I can clear the processed
requests out on a daily basis but ultimatly this is not fixing the
problem.
What I need is for this query to always have a very low response ratio.
Here are the current indexes on the table.
+----------------+------------+----------------------------------+--------------+----------------------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name |
Seq_in_index | Column_name | Collation | Cardinality |
Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+----------------+------------+----------------------------------+--------------+----------------------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| remote_request | 0 | PRIMARY |
1 | id | A | 2403351 | NULL |
NULL | | BTREE | | |
| remote_request | 1 | type_index |
1 | type | A | 18 | NULL |
NULL | | BTREE | | |
| remote_request | 1 | processing_interface_id_index |
1 | processing_interface_id | A | 18 | NULL |
NULL | YES | BTREE | | |
| remote_request | 1 | processing_interface_table_index |
1 | processing_interface_table | A | 18 | NULL |
NULL | YES | BTREE | | |
| remote_request | 1 | create_time_index |
1 | create_time | A | 160223 | NULL |
NULL | YES | BTREE | | |
| remote_request | 1 | run_time_index |
1 | run_time | A | 343335 | NULL |
NULL | YES | BTREE | | |
| remote_request | 1 | completed_time_index |
1 | completed_time | A | 267039 | NULL |
NULL | YES | BTREE | | |
| remote_request | 1 | reserved_index |
1 | reserved | A | 18 | NULL |
NULL | YES | BTREE | | |
| remote_request | 1 | params_md5_index |
1 | params_md5 | A | 2403351 | NULL |
NULL | YES | BTREE | | |
| remote_request | 1 | priority_index |
1 | priority | A | 716 | NULL |
NULL | YES | BTREE | | |
| remote_request | 1 | status_index |
1 | status | A | 18 | NULL |
NULL | | BTREE | | |
| remote_request | 1 | name_index |
1 | name | A | 18 | NULL |
NULL | YES | BTREE | | |
| remote_request | 1 | processing_order |
1 | priority | A | 200 | NULL |
NULL | YES | BTREE | | |
| remote_request | 1 | processing_order |
2 | status | A | 200 | NULL |
NULL | | BTREE | | |
| remote_request | 1 | processing_order |
3 | type | A | 200 | NULL |
NULL | | BTREE | | |
| remote_request | 1 | processing_order |
4 | reserved | A | 200 | NULL |
NULL | YES | BTREE | | |
+----------------+------------+----------------------------------+--------------+----------------------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
Any idea how i solve this? Is it not possible to make some sort of
complicated index that would automatic order them with priority, then take
the first 40 that match the 'Facebook' type? It currently is scanning more
then 500k rows of the table before it returns a result which is grossly
inefficient.
Some other version of the query that I have been tinkering with are:
select * from remote_request use index (
type_index,status_index,reserved_index,priority_index ) where
remote_request.status = 'none' and type = 'Facebook' and reserv
ed = '0' order by priority desc limit 0, 40
It would be amazing if we could get the rows scanned to under 1000 rows
depending on just how many types of requests enter the table.
Thanks in advance, this might be a real nutcracker for most except the
most experienced mysql experts?

301 redirect: SEO urls, same article ID

301 redirect: SEO urls, same article ID

I've searched around and couldn't find an example such as this one.
To make a long story short, the news script i was using sucked and i
switched to another one. i managed to copy the database tables all in to
the new news script and so all of the article IDs are exactly the same as
my old news script. Now I'm having issues redirecting the old urls.
My old links look like this, where the view-number represents the article
id http://www.mysite.com/news/view-252-lots-of-friendly-url-text/
My new links look like this where the -r number represent the article id
http://www.mysite.com/page/view/cat/lots-of-friendly-url-text-r238
If anyone out there can give me some pointers on how i can possibly
redirect these with some wildcards it would be greatly appreciated.

Installing windows 7 on Inspiron 14z hybrid hdd/ssd

Installing windows 7 on Inspiron 14z hybrid hdd/ssd

So the copy of Windows 8 wont boot on my Inspiron 14z Ultrabook, I don't
have a recovery disc, and don't want to wait for Dell to send me a new
disc. I think I'd rather have Windows 7 anyways. I have a copy of Windows
7 and I'm trying to install it but I want to ensure that the hybrid
hdd/ssd (500GB 5400 RPM SATA HDD and 32GB mSATA SSD) will work when I'm
done installing.
So when I get to the part where I select the partition to install the
drive I see the following:
Name Total Size Free Space Type
Disk 0 Part 1: ESP 500 MB 447 MB System
Disk 0 Part 2: DIAGS 40 MB 35 MB OEM (Reserved)
Disk 0 Part 3 128 MB 128 MB MSR (Reserved)
Disk 0 Part 4: WINRETOOLS 500 MB 220 MB OEM (Reserved)
Disk 0 Part 5: OS 450.9 GB 317.2 GB Primary
Disk 0 Part 6: PBR Image 13.7 GB 261 MB OEM
Disk 1 Part 1 8 GB 0 MB Primary
Disk 1 Unallocated Space 21.8 GB 21.8 GB
So should I delete all of the Disk 0 partitions, format them as one and
then install? Are there any partitions I should leave for functionality
like hibernation?
What do I do about Disk 1 (SSD)?
How do I ensure that the SSD portion is setup correctly and working?
The SSD portion of the drive is just supposed to work like cache for the
HDD right?
EDIT: I should add that even though I've worked as an IT pro in the past,
I have absolutely no experience when it comes to these types of drives and
Win8.

How to link jQuery with HTML buttons?

How to link jQuery with HTML buttons?

Hej!
I have this code (JUST AN EXAMPLE !):
function random(min, max) {
return min + parseInt(Math.random() * (max-min+1));
}
function getKey(length, charset) {
var key = "";
while(length--) {
key += charset[random(0, charset.length-1)];
}
return key;
}
$(document).ready(function() {
var key = getKey(16, "0123456789ABCDEF");
});
And want to link this (javascript) to a submit-input-button (html) (or
something like this). So, when I clicked the button he generates each time
a new "key".
Can you please find with me a solution? :-)

Why do we need "a:link"? Why not just "a"?

Why do we need "a:link"? Why not just "a"?

It seems the following variants produce identical results:
/* 1 */
a, a:visited, a:active { color: black; }
a:hover { color: red; }
/* 2 */
a, a:link, a:visited, a:active { color: black; }
a:hover { color: red; }
/* 3 */
a:link, a:visited, a:active { color: black; }
a:hover { color: red; }
Most guidance on the web uses 2 or 3. Why not go for the simplest variant
which is 1? I cannot find a good reason to ever apply :link if all you
need is one style for normal links and one for hover.
Is it best-practice to not use :link? Why or why not?

Chrome iframe issue, duplicated content

Chrome iframe issue, duplicated content

I have two iframes on a page pulling from two different URLs, but when
loaded in Chrome v30, the iframes show the same information. In FF,
Safari, and IE, they all work as expected, showing the two different
frames.
http://bit.ly/15jKG4w

Create a mdadm raid mirror of an existing lvm

Create a mdadm raid mirror of an existing lvm

Hello I'm trying to figure out how I can create a pretty strange mdadm
mirror of my lvm.
I have 4 disks, (sda,b,c,d). Each disk has 2 partitions: 1Gb - physical
volume 500mb - Swap
My system lvm volume is currently made of two physical drives:
/dev/sda1 - 1Gb
/dev/sdb1 - 1Gb
Creating a 2Gb volume group for my root partition.
/dev/mapper/sys-root
What I want to do now is mirror my sys-root volume onto the other two
disks. I originally thought I would create mirror as:
mdadm --create /dev/md0 --level=1 --raid-disks=4 missing missing
/dev/sdc1 /dev/sdd1
Except I realise that all that would do is mirror the the contents of 1
drive onto the other 3.
What would be the method of mirroring /dev/mapper/sys-root onto my other 2
disks? Unfortunately doing this from scratch isn't an option as I need to
use the existing file system.

Friday, 23 August 2013

How to select previous tab which we have selected already in action bar?

How to select previous tab which we have selected already in action bar?

here my problem ill explain. I have added tabs in action bar all tabs
working properly by selecting and replacing fragments but when i click the
tab which i have selected previous tab which ill give error. here my code.
public class MainActivity extends Activity {
public static Context appContext;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appContext = getApplicationContext();
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab connectionTab = actionbar.newTab().setText("Connection");
ActionBar.Tab masterDataTab = actionbar.newTab().setText("Master Data");
Fragment connection = new AFragment();
Fragment masterData = new BFragment();
connectionTab.setTabListener(new MyTabsListener(connection));
masterDataTab.setTabListener(new MyTabsListener(masterData));
actionbar.addTab(connectionTab);
actionbar.addTab(masterDataTab);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
}
return false;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}
}
class MyTabsListener implements ActionBar.TabListener { public Fragment
fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(MainActivity.appContext, "Reselected!",
Toast.LENGTH_LONG).show();
// ft.replace(R.id.fragment_container, fragment); }
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
}

SQL How to add parentheses to output data

SQL How to add parentheses to output data

For a college assignment I need to show the last column ouput data in
parentheses as show below:-
My current query is:-

SELECT
SUBSTRING(FirstName,1,1) AS '',
'.' AS'',
LastName AS '', UPPER(Title) AS ''
FROM employees
WHERE (Title !='Sales Representative');

This query shows the output as:-
B . Brown STOREMAN
C . Carr RECEPTIONIST
D . Dig DRIVER

I need it to show:-
B . Brown (STOREMAN)
C . Carr (RECEPTIONIST)
D . Dig (DRIVER)

How do I add newline within text string to zipfile using python 2.7

How do I add newline within text string to zipfile using python 2.7

Writing text to a zipfile using python. Below if the section of code I am
using to do this. I can't figure out what character I need to use to get
it to add new lines to the zipfile.
if Count:
TextX = "The following species are present:"
blurb = "\r\nINSERT TABLE HERE\r\n\r\nSA* - South America\r\nNA** -
North America\r\nCA*** - Central America"
else:
TextX = "No species are present."
blurb = ""
Right now "if Count" is true, the output in the document looks like this:
INSERT TABLE HERE SA* - South America NA** - North America CA*** -
Central America
I want it too look like this:
INSERT TABLE HERE
SA* - South America
NA** - North America
CA*** - Central America
Below is some other pertinent script snippet that might help troubleshoot.
The script is 600+ lines long which is why I did not include the whole
thing. Everyting works except this piece.
replaceText = {"TextSpecies" : TextX,
"TEXTBLURB" : blurb}
template = zipfile.ZipFile("C:\\Template.docx")
response = zipfile.ZipFile(results, "a")
with open(template.extract("word/document.xml", databaseDir + "\\")) as
tempXmlFile:
tempXml = tempXmlFile.read()
for key in replaceText.keys():
tempXml = tempXml.replace(str(key), str(replaceText.get(key)))
with open(databaseDir + "\\temp.xml", "w+") as tempXmlFile:
tempXmlFile.write(tempXml)
for file in template.filelist:
if not file.filename == "word/document.xml":
response.writestr(file.filename, template.read(file))
response.write(databaseDir + "\\temp.xml", "word/document.xml")
response.close()
template.close()
Ideas as to how to add new lines? I tried \r, \n, \r\n, ^11. None worked.
Thanks in advance.

Best iOS data structure to store sizes and colours of a product

Best iOS data structure to store sizes and colours of a product

I am developing an iOS application that deals with products. These
products obviously can have sizes and colours (clothes, for example). Now
I need a good data structure to store the available colours and sizes for
the current product (for one product at a time). The price has also to be
a part of the data structure, since every colour-size combination might
have a different price, as well as a URL for the product image of the
specified size.
I have thought of a two-dimensional array (i.e. NSArrays of NSArray) with
first dimension as colour and second as the size and the content of the
cell is the price and the URL, but then there is some inconvenience when
the product has only sizes without colours or vice versa.
Is there some other better data structure that satisfies my needs, or my
choice was the best?
Thanks!

Set GridView selector default

Set GridView selector default

Within my Android app currently, I have a GridView that uses a custom
adapter to populate it with multiple custom views.

This GridView is defined as follows:
<GridView
android:id="@+id/grid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:isScrollContainer="false"
android:listSelector="@drawable/selector"
android:numColumns="3"
android:stretchMode="columnWidth" />
As you can see, I have defined a custom 'List Selector' that allows users
to see what item of the grid view they have selected.

What I want to know is the following, Is it possible that when the grid
view is populated using the custom adapter the List Selector can be set to
a default value? (Currently the list selector only appears once a user has
made a choice - obviously).

The custom GridView adapter is a simple adapter that extends BaseAdapter.
Many thanks

In WinJS how to avoid outer div event handler affects inner div event handler

In WinJS how to avoid outer div event handler affects inner div event handler

I want to set different event handlers on nested divs, and the events are
both triggered by right-click. Both event handlers would draw different
buttons on the same area.
My code would be like this:
<div id="a">
<div id="b data-win-control="WinJS.UI.ListView">
...
</div>
</div>
I addEventListener on "div a" and "listview", the problem is that while I
right-click on listView elements, triggering listView's event handler
first, and then a's event handler which will override listView's effects.
How to avoid triggering a's event handler when right-click on listView?
Thanks

Thursday, 22 August 2013

Sum all values in every column of a data.frame in R

Sum all values in every column of a data.frame in R

Given this data set:
Name Height Weight
1 Mary 65 110
2 John 70 200
3 Jane 64 115
I'd like to sum every qualifier columns (Height and Weight) yielding
199 425
The problem is that the qualifiers can be more than just 2 (i.e. more than
just Height and Weight).
I can do this.
res <- c(sum(people$Height),sum(people$Weight))
But it gets too long when the qualifier increase. What's the compact way
to do it?

POST comment via Youtube API

POST comment via Youtube API

$url = 'http://www.youtube.com/feeds/api/videos/' . $video_id . '/comments';
$data = array('key' => $api_key);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type:
application/atom+xml\r\nContent-Length: {$text}\r\nAuthorization:
Bearer {$_access_token}\r\nGData-Version: 2\r\nX-GData-Key:
key=$api_key",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
I get
<b>Warning</b>:
file_get_contents(http://www.youtube.com/feeds/api/videos/ZButc20/comments):

How to increase the value of a unix timestamp stored in a variable by X hours?

How to increase the value of a unix timestamp stored in a variable by X
hours?

I have a php function that creates a unix timestamp and stores it in a
variable. Let's call that variable $timestamp. I'm looking for a function
that will allow return two new variables that are a each a different
number of hours later than the original timestamp. Is there a way to do
this?

Crash in access 'Assets' by AssetManager in Service

Crash in access 'Assets' by AssetManager in Service

Crashed log:
08-22 15:33:32.040 I/ActivityManager( 191): Process app.processName (pid
3999) (adj 0) has died.
08-22 15:33:32.040 E/WifiService( 191): Multicaster binderDied
08-22 15:33:32.040 W/ActivityManager( 191): Force removing r: app died, no
saved state
08-22 15:33:32.040 D/PowerManagerService( 191): releaseWakeLockLocked
flags=0x0 tag=My Tag myUID=1000 myPID=191 myTID=359
Before the application signed by default keystore everything is fine, it
works normally. However, the application crashed after using release
keystore . I try to figure out the reason then I discovered that the app
crashed when the process was trying to access assets folder:
getAssets().list("folder");
My application's manifest is
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.package"
android:versionCode="0"
android:versionName="1.0.1" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission
android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission
android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_LOGS"/>
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"/>
<uses-permission
android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS" />
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="15" />
<application
android:name="com.app.package.application"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:enabled="true"
android:largeHeap="true" >
<activity
android:name="com.app.package.Activity"
android:label="@string/title_activity_main"
android:theme="@android:style/Theme.Holo.NoActionBar.Fullscreen"
android:launchMode="singleTask"
android:configChanges="orientation|screenSize"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:enabled="true"
android:name="com.service.package.Service"
android:exported="true"
android:isolatedProcess="false">
<intent-filter>
<action android:name="com.service.package.IService"></action>
</intent-filter>
</service>
</application>
</manifest>
The folder was accessed in Service which was triggered by Activity called
startService().
I have no idea what is going on. If someone know that please help me. Thanks.
I suspect it may be the permission problem that causes this crash.

English sentence structure

English sentence structure

My daughter wrote a short story at school and wrote ''said the woman'' the
teacher corrected this and wrote '' the woman said'' Is it not correct
either way?

How standard is the C++11 standard currently?

How standard is the C++11 standard currently?

I am currently updating my knowledge on C++ to the new standard. It makes
me feel like a little kid that just got the awesomest toy: I want to play
with it all the time but I don't want to lose my friends because of it.
I am involved in a few open source projects for which some of the new
features would be extremely useful, so I am quite keen on using them. My
question is how many users can compile C++11 code, e.g. what's the
adoption rate of C++11-complete compilers in the general public? Does
anyone have related information?
I know that gcc 4.8.1 and clang 3.3 are C++11 feature complete, but I have
no idea how many people actually use compilers that are up to date. I know
most codemonkeys surely do, but what about the average open source user?
Slapping potential users in the face and telling them to update their
compilers is not really an option.
I am aware that this question may be criticised/closed for being similar
to these questions:
How are you using C++11 today?
To use or not to use C++0x features
I would like to point out that things are different now, since we are
talking about an actual approved standard. I believe that being aware of
its adoption rate is important in practice for programming.

Wednesday, 21 August 2013

How to search and display XML file in browser

How to search and display XML file in browser

I'm looking for ways to display XML file in browser by using asp.net method.
Below is the code that I'm using to search for any .XML file with the word
"verify" as its title.
Now, I'm just wondering if there is a way to display the XML file in the
web browser.
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
'To find subdirectories with a specific pattern/WILD CARD
'ms-help://MS.VSExpressCC.v80/MS.NETFramework.v20.en/dv_vbcn/html/c9265fd1-7483-4150-8b7f-ff642caa939d.htm
'Me.ListBox1.Items.Clear()
Dim path As String = "\\g1w6223c\e$"
Dim searchPattern As String = "*verify*.xml"
For Each value As String In My.Computer.FileSystem.GetFiles(path,
FileIO.SearchOption.SearchAllSubDirectories, searchPattern
)
ListBox1.Items.Add(value)
TextBox1.Text = "found"
Next
End Sub

ios can I observer ( NSNotificationCenter) from different thread

ios can I observer ( NSNotificationCenter) from different thread

I have a question for you guys. I was wondering I generate another thread
and set NSNotificationCenter to observe a event in the main thread?, what
will be the best of doing this?
I'll really appreciate your help

How to Prove: $|Z_1 + Z_2| \leq |Z_1| + |Z_2|$

How to Prove: $|Z_1 + Z_2| \leq |Z_1| + |Z_2|$

How to Prove: $$|Z_1 + Z_2| \leq |Z_1| + |Z_2|$$ $ Z_1,Z_2 \in \mathbb{C}$

Combobox with BeanItemContainer and BeanFieldGroup throw Conversion exception

Combobox with BeanItemContainer and BeanFieldGroup throw Conversion exception

I make some test to see how can bind combobox to some bean property, but i
got an exception: "ConversionException: Could not convert value to String
at ..........." My sample work ok with indexedContainer for combobox, but
i have some trouble with BeanItem container. What i have: 1. TestCountry,
simple java bean for BeanItemContainer (i don't put here setter and getter
or constructor for simplicity):
public class TestCountry implements Serializable {
private String name;
private String shortName;
}
instantiation of BeanItemContainer
BeanItemContainer<TestCountry> _data = new
BeanItemContainer<TestCountry>(TestCountry.class);
_data.addItem(new TestCountry("Afganistan","AF"));
_data.addItem(new TestCountry("Albania","AL"));
bean filed group. Here TestBean is another bean with simple string
property's ("firstName","phone","contry")
BeanFieldGroup<TestBean> binder = new
BeanFieldGroup<TestBean>(TestBean.class);
combobox
ComboBox myCombo = new ComboBox("Select your country", _data);
essential code
binder.bind(myCombo, "country");
When i try to commit the binder i got an error about conversion problem to
string. From what i understand reading books and vaadin api,
BeanItemContainer uses the beans themselves as identifiers and (here may
be wrong) binder use item identifier to bind property. So here is the
problem, conversion from Bean to string. I try'it to implement toString(),
hash() and equals() on my TestCountry bean but without success. What can
do to use BeanItemContainer in this scenario?
Thanks in advance!!

Fileset with several filtering conditions

Fileset with several filtering conditions

I have the following files and folder :
-screen_20_08_2013
-xxx.html
-connect_21_08_2013
-contact.html
-screen_22_09_2013
-yyy.html
-screen_23_09_2013
-zzz.xml
I would like to zip all folders(including the files) containing screen
after a modified date of 21/08/2013
I have tried the following:
<zip destfile="logs.zip">
<fileset dir="mydir" excludes="*">
<date datetime="08/21/2013 00:00 AM" when="after"/>
<include name="**/screen*" />
</fileset>
</zip>
The datetime filtering is working fine but it does also include folder
starting with connect.
I am expecting to have a zip containing:
-screen_22_09_2013
-yyy.html
-screen_23_09_2013
-zzz.xml
Any help would be greatly appreciated.
Many thanks

i want to fill my field on click of combobox in for loop

i want to fill my field on click of combobox in for loop

sir i m trying to fill my field on click of combobox in for loop.I m
getting this but only in my one row.When i genrate another new row its is
not taking the value. i have more than one row to fill the field on click
of combo. i even try to use this with class but its is not happening. my
html code is
<td align="center"><input type="text" size="6" maxlength="6" maxlength="6"
id="code" name="code_0" class="code1 form-input-oth"/></td>
<script type="text/javascript">
function Expedisi(t)
{
var y = document.getElementById("code");
y.value = t.value;
}
</script>
when i do this with using for loop in javascript the code is
<script type="text/javascript">
function Expedisi(t)
{
var y;
for(var i=0; i<y.length;i++){
document.getElementById("code").innerHTML=y[i];
y[i].value = t.value;
}
}
</script>
but the above code is not working .. plz sir help me out

Google analytics server side implementation

Google analytics server side implementation

I would like to track the usage of a website using google analytics. I
have only access to the log files which has the events triggered by the
users. Is there any way to parse the log files(.csv) ,send the data and
view the same in the analytics dashboard.
Can some one please help me with an answer.

Tuesday, 20 August 2013

How to call a dismissBlock property on a pushed view controller?

How to call a dismissBlock property on a pushed view controller?

I have two view controllers, both inside a navigation controller. The
first controller a table view, and I set up delegation correctly for the
table view. When I tap a row on the parent view controller, I want the
child controller to appear, and I do this. This works, that is the child
view controller appears, and I have a "back" navigation button.
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Create and push another view controller.
ChildVC *detailVC = [[ChildVC alloc]
initWithNibName:@"MyViewController" bundle:nil];
// When user dismisses controller do this...
[detailVC setDismissBlock:^{
NSLog(@"Dismiss block called");
}];
// Setup navigation
[self.navigationController pushViewController:detailVC animated:YES];
}
In ChildVC.h I have
@interface ChildVC : UIViewController
@property (nonatomic, copy) void (^dismissBlock)(void);
@end
In ChildVC.m I have the following to try to execute the parent view's
dismiss block code, but to no avail, that is, I don't see the NSLog
executed.
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
if (![[self.navigationController viewControllers] containsObject:self]) {
// We were removed from the navigation controller's view
controller stack
// thus, we can infer that the back button was pressed
**// How do I call the presenting controller's dissmissBlock?**
**// I tried the following to no avail, since
presentingViewController is nil**
[[self presentingViewController] dismissViewControllerAnimated:YES
completion:_dismissBlock];
}
}
If using a dismiss block is not the mechanism here, what is? Thanks!

How is the memory managed for a thread?

How is the memory managed for a thread?

I understand that .net threads are pretty heavy weight, consuming ~1MB of
memory each (mostly for the stack). Now, if this was a user .net class I
know that it is likely going to put most of the memory into LOH. However,
since it is a core class, I am wondering what the behavior is.
The reason for this question is because I am memory profiling an
(potentially long lived) application at the moment, and there seems to be
a slow leak. I had noticed that VS is showing 33 threads (in various
states, included stopped). I am wonder if the frugal usage of threads
could be fragmenting the memory (along with a few LOH DTOs).

Python: Why does a a lambda define the variable in an inline if?

Python: Why does a a lambda define the variable in an inline if?

Toying around with lambdas in Python I discovered that the following code
is legal in Python 2.7.3 and returns the lambda:
x = lambda: 1 if x else 2
Why does the lambda define x when used in this way?

Can't eliminate Access corruption

Can't eliminate Access corruption

My firm's Access database has been having some serious problems recently.
The errors we're getting seem like they indicate corruption -- here are
the most common:
Error accessing file. Network connection may have been lost.
There was an error compiling this function.
No error, Access just crashes completely.
I've noticed that these errors only happen with a compiled database. If I
decompile it, it works fine. If I take an uncompiled database and compile
it, it works fine -- until the next time I try to open it. It appears that
compiling the database into a .ACCDE file solves the problem, which is
what I've been doing, but one person has reported that the issue returned
for her, which has me very nervous.
I've tried exporting all of the objects in the database to text, starting
with a brand new database, and importing them all again, but that doesn't
solve the problem. Once I import all of the objects into the clean
database, the problem comes back.
One last point that seems be related, but I don't understand how. The
problem started right around the time that I added some class modules to
the database. These class modules use the VBA Implements keyword, in an
effort to clean up my code by introducing some polymorphism. I don't know
why this would cause the problem, but the timing seems to indicate a
relationship.
I've been searching for an explanation, but haven't found one yet. Does
anyone have any suggestions?

filling with zeros the list obtained from a comparison

filling with zeros the list obtained from a comparison

I have this function that receives 3 lists:
DOCUMENTO 1
[['ser', 'VSIS3S0', 1], ['francisco_villa', 'NP00000', 2], ['norte',
'NCMS000', 1], ['revolucion_mexicana', 'NP00000', 1], ['nombrar',
'VMP00SM', 1], ['centauro', 'NCMS000', 1]] DOCUMENTO 2 [['pintor',
'NCMS000', 1], ['ser', 'VSIS3S0', 1], ['muralista', 'AQ0CS0', 1],
['diego_rivera', 'NP00000', 1], ['frida_kahlo', 'NP00000', 1], ['caso',
'NCMS000', 1]] CONSLUTA [['ser', 'VSIP3S0', 1], ['francisco_villa',
'NP00000', 1], ['quien', 'NP00000', 1]]
function:
def vectores(doc1,doc2,consulta):
res=[]
l1=[]
cont = 0
r = doc1 + doc2 + consulta
for i in r:
l1.append(i[0])
for e in doc1:
if e[0] in l1:
res.append(e[2])
else:
res.append(e[0]==0 * len(l1))
return res
[1, 2, 1, 1, 1, 1] -> res
I need to compare if the key[0] of doc1 exists in key[0] of l1 then append
key[2] to the res, and if they don't match append a zero, forming a vector
with lenght of l1
Like this output:[1, 2, 1, 1, 1, 1, 0, 0, 0, ...]
Thank you in advance! ;)

Module pattern $.bind not working

Module pattern $.bind not working

Im new to the javascript module pattern and can't get something like this
to work, am I missing something? The $.bind don't give any errors and
dropBox is not NULL.
var Application = (function(d, w, $, p) {
var drop, dragStart, dragEnter, dragOver, dragLeave;
drop = function(e) {
};
dragStart = function(e) {
};
dragEnter = function(e) {
};
dragOver = function(e) {
};
dragLeave = function(e) {
};
return {
init: function() {
var dropBox = $('#someid');
dropBox.bind('dragstart', dragStart);
dropBox.bind('dragenter', dragEnter);
dropBox.bind('dragover', dragOver);
dropBox.bind('drop', drop);
dropBox.bind('dragleave', dragLeave);
}
};
})(document, window, window.jQuery);

TypeError: object is not a function - fetching collection data using Angular / rails part2

TypeError: object is not a function - fetching collection data using
Angular / rails part2

this is a follow up of this SO TypeError: object is not a function -
fetching collection data using Angular / rails
The goal of this question is to find out how to use angular, typeahead in
rails application on working plunker code....
Wish to understand why the below angular code is working in plunker
code,but when used in rails app, with the same data, there is this error:
TypeError: object is not a function
at Object.source (http://localhost:3000/assets/angular.js?body=1:6300:13)
at getMatchesAsync
(http://localhost:3000/assets/angular-ui-bootstrap.js?body=1:1820:30)
at http://localhost:3000/assets/angular-ui-bootstrap.js?body=1:1871:13
at http://localhost:3000/assets/angular.js?body=1:12030:15
at Array.forEach (native)
at forEach (http://localhost:3000/assets/angular.js?body=1:134:11)
at $setViewValue (http://localhost:3000/assets/angular.js?body=1:12029:5)
at http://localhost:3000/assets/angular.js?body=1:11423:14
at Object.Scope.$eval
(http://localhost:3000/assets/angular.js?body=1:7994:28)
at Object.Scope.$apply
(http://localhost:3000/assets/angular.js?body=1:8074:23
)
class UsersController < ApplicationController
def angular
@users = User.all
render json: @users, only: %w(full_name id)
end
end
resources :users do
collection do
get :angular
end
end

Monday, 19 August 2013

Ancestry Gem saves all threaded messages as Parent

Ancestry Gem saves all threaded messages as Parent

Currently implementing Threaded Messaging. via RailsCast
I've installed the Ancestry gem, however all messages that I create are
parents. ie.) Ancestry = nil
Even after passing my parent:id to new action
Message Controller
def index
@message = Message.new
@user = current_user
@sent_messages = current_user.sent_messages
@received_messages = current_user.received_messages
end
def new
@message = Message.new
@message.parent_id = params[:parent_id]
end
Index.html
<% for incoming in @received_messages %>
<%= render partial: "message", locals: {incoming: incoming} %>
_message.html.erb
</div>
<%= link_to "Reply", new_message_path(:parent_id => incoming) ,class:
"regular" %>
</div>
new.html.erb
<%= form_for @message do |f| %>
<p>
To:<br />
<%= f.hidden_field :parent_id %>
<%= f.hidden_field :recipient, :value => (@message.parent.sender.name) %>
</p>
<p>
Message<br />
<%= f.text_area :body %>
</p>
<p>
<%= submit_tag "Send Threaded Reply" %>
</p>
<% end %>
Message.rb
class Message < ActiveRecord::Base
attr_accessible :recipient, :subject, :body, :parent_id
has_ancestry
end
My console after creating a message:
Key point - I'm passing the parent_id (144) in Message however ancestry
still passes as nil.
Parameters: {"utf8"=>"&#10003;",
"authenticity_token"=>"gKVr06oT+6OcAERHAzSX79vTlJLniofmEOjZPdZmfwM=",
"message"=>{**"parent_id"=>"114"**, "recipient"=>"Rach Miller",
"body"=>"meh and more meh"}, "commit"=>"Send Threaded Reply"}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = 17
LIMIT 1
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."name" =
'Rach Miller' LIMIT 1
(0.2ms) BEGIN
SQL (0.7ms) INSERT INTO "messages" ("ancestry", "body", "created_at",
"read_at", "recipient_deleted", "recipient_id", "sender_deleted",
"sender_id", "subject", "updated_at") VALUES ($1, $2, $3, $4, $5, $6,
$7, $8, $9, $10) RETURNING "id" [["ancestry", nil], ["body", "meh and
more meh"], ["created_at", Tue, 20 Aug 2013 03:14:15 UTC +00:00],
["read_at", nil], ["recipient_deleted", false], ["recipient_id", 18],
["sender_deleted", false], ["sender_id", 17], ["subject", nil],
["updated_at", Tue, 20 Aug 2013 03:14:15 UTC +00:00]]

urllib2.ProxyHandler - query

urllib2.ProxyHandler - query

Definition :
urllib2.ProxyHandler([proxies])
Cause requests to go through a proxy. If proxies is given, it must be a
dictionary mapping protocol names to URLs of proxies. The default is to
read the list of proxies from the environment variables _proxy. If no
proxy environment variables are set, then in a Windows environment proxy
settings are obtained from the registry's Internet Settings section, and
in a Mac OS X environment proxy information is retrieved from the OS X
System Configuration Framework.
My understanding , if proxy is not set explicity it detects proxy from
registry settings .
Buet when I run the below code:
import urllib2
proxy_support = urllib2.ProxyHandler({})
print "1"
opener = urllib2.build_opener(proxy_support)
print "2"
urllib2.install_opener(opener)
print "3"
response = urllib2.urlopen('http://google.com')
print "4"
html = response.read()
I get the error :
1
2
3
urllib2.URLError: <urlopen error [Errno 10060] A connection attempt failed
because the connected party did not properly respond after a period of
time, or established connection failed because connected host has failed
to respond>
This means the the piece of code is not able to open the website . I am
not sure where am I going wrong , shouldn't as per definition ,
urllib2.ProxyHandler , get the proxy off from registry , since I haven't
explicitly set the proxy ?

Safely delete and modify elements within Apache XmlBeans object?

Safely delete and modify elements within Apache XmlBeans object?

We are using Apache XmlBeans, with code generated from a schema. My
assigned task is to read in an XML instance that conforms to the schema,
modify it in various application-specific ways, then revalidate. For
example, change the value of an element, delete an element from a list,
etc. I am using Java method calls like removeMyElement(i) to remove the
element at position (i). I am not using Cursors or any low-level DOM
access.
I am clearly doing the changes wrong because my code causes the XmlBeans
core to throw XmlValueDisconnectedException on certain operations. The
explanation for this exception seems to be that the XmlObject has become
disconnected from its underlying store.
I checked the XmlBeans FAQ and the sample code for guidelines. I found
many samples at http://xmlbeans.apache.org/samples/ that show how to
create an object from scratch, how to read in XML, how to validate XML,
etc. Unfortunately I didn't find a sample that does a messy change to the
content. The FAQ at http://wiki.apache.org/xmlbeans/XmlBeansFaq doesn't
have a good question on this either.
I have discovered (by some googling) posts stating that after calling a
method to remove an element in a list, I must immediately call the
getElementsArray() method again. That's reasonable, a good start.
We thought it would be convenient to gather a list of objects (references
to XmlBeans objects) that need to be modified, then iterate over the list
changing them. But use of a cached object reference is where I run into
the ditch.
Does every change to an XmlObject backed by the XmlBeans XmlStore cause
all existing references to become invalid? I don't yet have the right
mental model for what's going on when I call the java methods.
Please point me or send advice, thanks in advance.

Value at poiComment of type org.json.JSONObject cannot be converted to JSONArray

Value at poiComment of type org.json.JSONObject cannot be converted to
JSONArray

Good Morning people, my head is going to explode cause of this error
Value {...} at poiComment of type org.json.JSONObject cannot be converted
to JSONArray
this is the json file:
{
"poiComment": [
{
"id": "1",
"poiComment": "I'm at The Pine. http://4sq.com/a1UXvc"
},
{
"id": "2",
"poiComment": "bday dinner w. my bff &lt;3 (@ The Pine)
http://4sq.com/a1UXvc"
},
{
"id": "3",
"poiComment": "I'm at The Pine. http://4sq.com/a1UXvc"
}
]
}
and i use this way (last time i used a jsonobject it worked):
JSONObject jso1 = new JSONObject(response1);
JSONArray jArray1 = jso1.getJSONArray("poiComment");
How is it possible??
Thanks in advance for help

Constructing an "intelligent" command

Constructing an "intelligent" command

I'm trying to create a command with an optional argument using
\newcommand{\Af}[1]{{\mathbf{A}_{(#1)}}
where the argument is a number.
However, I'd like that if no argument is given the bracket were dropped.
Question
How could I define a command which decides whether or not write the brackets?

Sunday, 18 August 2013

HOw to resume Fragment from BackStack if exists

HOw to resume Fragment from BackStack if exists

Hello I am using Fragment. I have created three instances of Fragment and
initialize them at the top of the class. I am adding fragment to an
activity like this:
Decalring and initializing:
Fragment A = new AFragment();
Fragment B = new BFragment();
Fragment C = new CFragment();
Replacing/Adding Fragment:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, A);
ft.addToBackStack(null);
ft.commit();
These snippets are working properly. And every Fragment is attached on
activity and saved to backStack successfully.
So when I launch A and then launch C and then launch B, the stack becomes
| |
|B|
|C|
|A|
___
And when I press back button, B is destroyed and C is resumed.
But when I again launch fragment A, instead of resuming from backstack, it
is added on the top of the backstack
| |
|A|
|C|
|A|
___
But I want to resume A and destroy all fragments upon it (if any).
Actaully I just like the deafult backStack behavior of activity. So how
can I do that?
Expected: (A should be resumed and top Fragments are to be destroyed)
| |
| |
| |
|A|
___

Why does this list matcher not working as expected?

Why does this list matcher not working as expected?

I am practicing to use extractor:
scala> object LE {
| def unapply[A](theList: List[A]) =
| if (theList.size == 0) None
| else Some((theList.head, theList.tail))
| }
defined module LE
It works for matching one element:
scala> List(0, 1, 2) match {
| case head LE more => println(head, more)
| }
(0,List(1, 2))
But does not appear to work for matching more than one element:
scala> List(0, 1, 2) match {
| case head LE next LE more => println(head, more)
| }
<console>:10: error: scrutinee is incompatible with pattern type;
found : List[A]
required: Int
My list extractor looks very similar to Scala's Stream extractor, which
can be used like this:
val xs = 58 #:: 43 #:: 93 #:: Stream.empty
xs match {
case first #:: second #:: _ => first - second
case _ => -1
}
So what difference prevents my LE from being used in such a way?

How to map a vector to a different range in R?

How to map a vector to a different range in R?

I have a vector in the range [1,10]
c(1,2,9,10)
and I want to map it to a different range, for example [12,102]
c(12,22,92,102)
Is there a function that already does this in R?

Install failed container error

Install failed container error

Application 1: My project almost 90 percentage finished, at this stage I
was trying to create widget for my app when I was running after creating
and adding the widget successfully to the project the error INSTALL FAILED
CONTAINER ERROR occurs. Ok now I just tried to delete the .asec (i.e
/mnt/secure/asec/example.asec) which is not working for me. I also tried
to set the installation location android:installLocation="auto" which is
not also working. Finally I decided to delete my Widget (Class, layout and
everything related with the widget) and then tried still the error INSTALL
FAILED CONTAINER ERROR occurs
Application 2: And One more problem with my one more application which is
also at 90 percentage of finishing state, it shows
08-18 23:03:38.928: E/AndroidRuntime(3235): FATAL EXCEPTION: main
08-18 23:03:38.928: E/AndroidRuntime(3235):
java.lang.NoClassDefFoundError:
com.jeremyfeinstein.slidingmenu.lib.SlidingMenu
08-18 23:03:38.928: E/AndroidRuntime(3235): at
in.blogspot.pcnlap.skillgun3.MainActivity.onCreate(MainActivity.java:31)
This is a Jfeinstein10/SlidingMenu I ran this second application more than
100 times for testing purpose at that time it did'nt showed any error