Saturday, 31 August 2013

How to divide ASCII code in Powershell

How to divide ASCII code in Powershell

so in Powershell I want to take the ASCII code of a document and divide it
all by a Variable. Here is example code.
$file = Get-Content $home\example.txt -encoding byte
$value = 32984729847569237498
$file/$value | Set-Content $home\example.txt -encoding byte
Now the problem is that it says I cant divide it because there is no
op.Division. I can multiply it but the problem there is that it just takes
the contents of example.txt and copies it 32984729847569237498 times. What
I want it to do is divide the ASCII code by 32984729847569237498 so that
you can only get the original contents of the file back if you multiply it
by 32984729847569237498.

how to design the database for the follwing scenario?

how to design the database for the follwing scenario?

I'm working on a regression test project. Let's say the model is like: R =
f(C). C is the collection of test cases with the size is about 2000, and R
is the result of all test cases. It will produce about 2000000 records to
insert into the db on every daily run. We'll keep a baseline for the R,
and baseline is initialized as the R of the first daily run. After each
daily run, we'll compare the result with the baseline(we call the
difference between the daily run result with the baseline as Regression
Issue). If there are differences, we'll investigate it and update some
records of the baseline or file a bug if necessary. baselinetable:
(casename, resultid) is primary key. buildnumber casename resultid result
1 case1 0 abc 1 case1 1 def 1 case2 0 ijk resulttable's schema is the same
as baselinetable except: (buildnumber, casename, resultid) is the primary
key. buildnumber casename resultid result 1 case1 0 abc 1 case1 1 def 1
case2 0 ijk 2 case1 0 abc 2 case1 1 fff 2 case2 0 ijk The problem is that:
the db grows too fast (2000000 records per day). So I tried the following
2 solution: solution A: Only keep those records which are different with
current baseline. resulttable: (buildnumber, casename, resultid) is the
primary key. buildnumber casename resultid result baseline_buildnumber 1
case1 0 abc 1 1 case1 1 def 1 1 case2 0 ijk 1 2 case1 1 fff 1 Because the
baseline could be updated, so I add column 'baseline_buildnumber' to mark
which baseline is based on. And accordingly, we need keep multiple version
of baseline be add the buildnumber as primary key: baselinetable:
(buildnumber, casename, resultid) is primary key. buildnumber casename
resultid result 1 case1 0 abc 1 case1 1 def 2 case1 1 fff 1 case2 0 ijk
This solution can remarkably reduce the size of db. But it's complicate:
First, when insert the daily run results, we need to compare the result
with the latest baseline(eg. the 1st,3rd,4th row of the baselinetable
above). Second, if we don't investigate and update the baseline before the
next daily run. It will comes into the following situation: The latest
baseline build is Num1, and the result of build Num2 and build Num3 both
are based on baseline Num1. It's simple to get the Regression Issue of
build Num2. Because the diff result is based on baseline Num1 and Num1 is
also the latest baseline build, so all the diff results of build Num2 are
Regression Issue. But if we update the baseline to build Num2, then we
want to get the Regression Issue of build Num3. We need to compare the
diff result of build Num3 with the baseline Num2, and also need to fetch
the diff between baseline Num1 and baseline Num2, because the
baseline_buildnumber is Num1(which is not the latest baseline build) when
we insert the diff result of build Num3.
Do you guys have any better idea? Thanks very much!

Container class storing, retrieving and addressing issues

Container class storing, retrieving and addressing issues

I'm having trouble with storing data of template type into a non-STL
container. I need to be able to store an address of a created object,
return it, and then properly address the element stored in it later when
an overloaded operator[] is called on the container object. The following
is the code I have implemented so far.
#ifndef FOO_H
#define FOO_H
#include <assert.h>
template<typename T>
class Foo
{
unsigned capacity, items;
T *elements;
public:
Foo(char * pBuffer, unsigned nBufferSize){ ///====== Constructs the
container from a pre-defined buffer.
elements = new T[nBufferSize];
capacity = nBufferSize;
items = 0;
}
~Foo(){
delete[] elements;
}
// Resizes Container
void Resize()
{
T *elements2 = new T[Capacity()*2];
for (unsigned i=0; i < Capacity(); i++)
elements2[i] = elements[i];
delete[] elements;
elements = elements2;
capacity = Capacity()*2;
}
T * Add(){ ///====== Adds an element to the
container, constructs it and returns it to the caller. ====== Note that
the return address needs to be persistent during the lifetime of the
object.
T Obj;
if (IsFull())
{
Resize();
items++;
}
else{
elements[items] = Obj;
items++;
}
return &elements[items-1];
}
void Remove(T * nIndex){ ///====== Removes an object from
the container.
items--;
T *elements2 = new T[capacity-1];
unsigned location = 0;
for (unsigned i=0; i < Capacity(); i++)
{
T* address = &elements[i];
if (&address == &nIndex) // I know this isn't the right way to
find the location of an incoming object.
// Still trying to figure out the right
way of finding that object in the buffer
based of the pointer being passed in.
{
location = i;
break;
}
}
for (unsigned nBefore=0; nBefore < location; nBefore++)
elements2[nBefore] = elements[nBefore];
for (unsigned nAfter=location+1; nAfter < Capacity(); nAfter++)
elements2[nAfter-1] = elements[nAfter];
delete[] elements;
elements = elements2;
}
unsigned Count() const{ ///====== Number of elements
currently in the container.
return items;
}
unsigned Capacity() const{ ///====== Max number of elements the
container can contain. You can limit the capacity to 65536 elements if
this makes your implementation easier.
return capacity;
}
bool IsEmpty() const{ ///====== Is container empty?
if (items >= 1)
return false;
return true;
}
bool IsFull() const{ ///====== Is container full?
if (items == Capacity())
return true;
return false;
}
T const * operator [] (unsigned nIndex) const{ ///======
Returns the n th element of the container [0..Count -1].
assert(nIndex >= 0 && nIndex < Capacity());
return &elements[nIndex];
}
T * operator [] (unsigned nIndex){ ///======
Returns the n th element of the container [0..Count -1].
assert(nIndex >= 0 && nIndex < Capacity());
return &elements[nIndex];
}
};

Returning multiple arrays using JSON in PHP

Returning multiple arrays using JSON in PHP

I am trying to return 2 arrays along with a third variable by encoding all
of them into a JSON array. I want access to all the keys of both the
arrays and also the third variable. I have had a hard time trying to do
so. All i was able to do was this, without any success..
Help required. Is there a way I can copy the whole json_encoded
data['states'] into a JS array?
onlineStudents.php
<?php
require_once 'myfunctions.php';
$query="Select * from online_students";
$result= queryMysql($query);
$data["total"]=mysql_num_rows($result)-1;
$query="Select distinct state from online_students";
$result=queryMysql($query);
while($row= mysql_fetch_array($result))
{
$query2="select * from online_students where state='$row[state]'";
$result2=queryMysql($query2);
$data["states"]=mysql_num_rows($result2);
}
$query="Select distinct college from online_students";
$result= queryMysql($query);
while($row= mysql_fetch_array($result))
{
$query2="Select * from online_students where college='$row[college]'";
$result2=queryMysql($query2);
$data["colleges"]=mysql_num_rows($result2);
}
echo json_encode($data);
?>
myfunctions.php
function queryMysql($query)
{
$result=mysql_query($query) or die(mysql_error());
return $result;
}
myfunctions.js
function peoples()
{
$.getJSON("onlineStudents.php",function(data){
$("#chat_head_number").html(": "+data['total']);
$("#chat_states_number").html(data['states']); //i want the whole
array data[states] instead of a single value
$("#chat_college_number").html(data['colleges']);
});
}

echo back array variables to html form when submitting

echo back array variables to html form when submitting

After alot of digging around some very informative posts and info to try
and find out how to solve this issue I thought I would ask around to see
if anyone has any pointers. I have an html form with various inputs
(checkboxes, text boxes etc...). Each input section has its own submit or
'Upload' button. On Upload a php script is called and various bits of
processing is done before data is sent over a pipe to a Python script for
further stuff. I am currently echoing back input variables to the form on
submission so that the html page does not refresh (or should I say the
inputted data is not lost to the users view) on an Upload event, however,
I now have to do the same for a bunch of checkboxes and text boxes the
values of which are stored in an array. The code I have written so far is
as follows (I am new to both php and html so please excuse the
inefficiency that I'm sure is obvious)
html/php
<margin>CH1</margin><input type="checkbox"name="ANout[]"value="AN1_OUT"
<?php if(in_array('AN1_OUT',$_POST['ANout']))echo'checked';?>>
Voltage<input type="text"size="5"name="ANout[]"
value="<?php $ANout[$i]=$_POST['ANout'];
if(!empty($ANout[$i]))echo"$ANout[$i]";?>">
<br>
The code above works fine for the checkboxes which happily remain after an
Upload button is pressed but not for the array. When the Upload event
occurs I simply get 'Array' written in the text box. I have tried existing
code I have written to echo back other text input in the form (see below)
and which works but these are for sole entries, not arrays. I have tried
various configurations of syntax but I always seem to get the same result.
Working Code:
<margin>Duty Cyle</margin><input type="text"name="PWM1DC"size="3"
value="<?php $PWM1DC = $_POST['PWM1DC'];
if(!empty($PWM1DC))echo "PWM1DC";?>">
<br>
Any clues would be appreciated.

Unable to send json data using durandal JS using Knockout Binding

Unable to send json data using durandal JS using Knockout Binding

var xyz= {
a: ko.observable(),
b: ko.observable(),
c: ko.observable(),
d: ko.observable()
};
function setupControlEvents()
{
$("#save").on("click",handleSave);
}
function handleSave()
{
var data = ko.toJSON(xyz);
//alert("data to send "+data);
//var d = serializer.serialize(data);
url ="../save";
http.post(url,data).then(function(){
alert("success");
console("save was success");
});
I am able to get the data but unable to save .. when i alert the data that
i am sending i get this data to send
{"a":"A","b":"B","c":"C","d":"D","observable":{"full":true}}
i tried to serialize with durandal's serialize.serialize() but still not
working .. i think i am unable to send the data because i am getting
obserbvable in json data so please kindly help me to solve this..

Friday, 30 August 2013

In jquery, how can I set the background-image of an element without hardcoding the url of the image in my javascript?

In jquery, how can I set the background-image of an element without
hardcoding the url of the image in my javascript?

I have an image element that I can reference by its class and/or id and I
have a div. I want to set the background-image of the div to the image
element, but I don't want to hardcode the url path in my JavaScript code.
How can I do this? I saw lots of answers to this but they all hardcoded
the url in the JavaScript code.

Thursday, 29 August 2013

How to mail the content of a text file using dbmail?

How to mail the content of a text file using dbmail?

I'm trying to send the content of a text file by email. Can it be done
using dbmail?

How Can I Avoid view State In my asp page

How Can I Avoid view State In my asp page

I am using asp.net and i am new developer. i want to avoid using viewstate
in my page. i have two content Place holder like this:
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent"
runat="server">
</asp:Content >
<asp:Content ID="Content1" ContentPlaceHolderID="BodyContent"
runat="server">
</asp:Content >
Can i do something with the Contentplaceholder how can i do this. Please
help me. I have tried a lot to avoid but i cant.
With Regard.

Getter and setter for bounded wild card type property

Getter and setter for bounded wild card type property

I have a class that contains a List<? extends BaseType>. Now BaseType can
have two subtypes: SubTypeA and SubTypeB. At runtime the list may be
either a List<SubTypeA> or List<SubTypeB>. How should the signature of
getter and setter look for this property?
class ListHolder{
private List<? extends BaseType> listOfBaseType;
//getter and setter for listOfBaseType
}

Wednesday, 28 August 2013

PHP - Use Field Names as Variable

PHP - Use Field Names as Variable

I am getting the error "Warning: mysql_field_name() expects parameter 1 to
be resource, object given in... on line 28"
I am fairly new to PHP, but what I am trying to accomplish is read a HTML
file and replace a custom tag with the value of the record. The tag
structure is |+FIELD-NAME-Record#+| For example if my sql returns two
records for the "Name" field it will look for the following two tags
|+Name1+| and |+Name2+| in the HTML file and replace it with the two
returned values. Say Adam and Jim.
Below is the code that I have so far.
$c = '|+Name1+|<br>|+Name2+|';
echo(ReplaceHTMLVariables(mysqli_query($con,"SELECT * FROM nc_names"),$c));
function ReplaceHTMLVariables($results, $content){
while($row = mysqli_fetch_array($results)){
//Define a variable to count what record we are on
$rNum = 1;
//Loop through all fields in the record
$field = count( $row );
for ( $i = 0; $i < $field; $i++ ) {
//Use the field name and record number to create variables to
look for then replace with the current record value
$content = str_replace("|+".mysql_field_name( $results, $i
).$rNum."+|",$row[$i],$content);
}
//move to next record
$rNum++;
}
return $content;
}
Line 28 references this line
$content = str_replace("|+".mysql_field_name( $results, $i
).$rNum."+|",$row[$i],$content);

select records with a column with specific value on specific date sql server 2000

select records with a column with specific value on specific date sql
server 2000

I have the following table:
ColA ColB ColC
1 A 08/22/2013
2 B 08/22/2013
3 A 08/28/2013
4 C 08/28/2013
How to select all records but the ones with ColB='A' with a date older
than today's date 08/28/2013
Result should be like below:
ColA ColB ColC
2 B 08/22/2013
3 A 08/28/2013
4 C 08/28/2013

Grid widget not working - Ext JS

Grid widget not working - Ext JS

So I have a grid class that I am defining here:
Ext.define('MC.view.portal.MetadataWidget', {
extend: 'Ext.grid.Panel',
id: 'metadatawid',
title: 'Graph',
store: Ext.data.StoreManager.lookup('metadatastore'),
alias: 'widget.metadatawidget',
initComponent: function() {
this.columns = [
{header: 'KBE Name', dataIndex: 'KBE_NAME', flex: 3, tdCls:
'grid_cell'},
...//remaining rows
];
this.callParent(arguments);
}
});
And I am trying to define it in my app.js using it's alias:
Ext.create('Ext.panel.Panel', {
id: 'app_container',
width: '100%',
height: 1000,
renderTo: 'container',
layout: 'hbox',
border: false,
requires: [ 'MC.view.portal.MetadataWidget' ],
items: [
{ xtype: 'metadatawidget', height: 400, width: ...
However I'm getting this error:
TypeError: name is undefined
if (name === from || name.substring(0, from.length) === from) {
Besides implementing a controller, this is basically following the same
way they define a widget in the Sencha docks, but I cannot find the reason
for my error. Any ideas?
-the store works
-directories are fine
-creating the widget causes the trouble
Cheers!

Update object and get old value via JPA

Update object and get old value via JPA

I want to log changes of an account. Therefore, I have created an entity
class that shall log the changes. Each time, an account entity is saved or
updated a logging object is created.
When the object is updated with a new balance the old balance shall be
retrieved from the database. As the object is bound to the session
retrieving its old balance is not trivial, because one always gets the new
balance.
To circumvent, I detached the object from the session. Yet, this seems to
be a workaround that should be avoided.
The following code snippets shall illustrate the scenario.
Any suggestion is highly appreciated!
The test:
public class AccountServiceTest
{
@Autowired
AccountService accountService;
@Autowired
ChangeAccountService changeAccountService;
@Test
public void shouldHaveChangeLog()
{
Account account = this.accountService.updateAccount(new Account(0,
10.0));
assertThat(account.getId(), is(not(0L)));
account.setBalance(20.0);
account = this.accountService.updateAccount(account);
final List<ChangeAccountLog> changeResultLogs =
this.changeAccountService.findAll();
assertThat(changeResultLogs.get(1).getNewBalance(),
is(not(changeResultLogs.get(1).getOldBalance())));
}
}
The service of the domain class to be logged:
@Service
public class AccountService
{
@Autowired
AccountRepository accountRepository;
@Autowired
ChangeAccountService changeAccountService;
public Account findById(final long id)
{
return this.accountRepository.findOne(id);
}
public Account updateAccount(final Account account)
{
this.changeAccountService.saveLog(account);
return this.accountRepository.save(account);
}
}
The service of the logging class:
@Service
public class ChangeAccountService
{
@Autowired
AccountService accountService;
@Autowired
ChangeAccountLogRepository repository;
public ChangeAccountLog save(final ChangeAccountLog changeAccountLog)
{
return this.repository.save(changeAccountLog);
}
public List<ChangeAccountLog> findAll()
{
return this.repository.findAll();
}
public ChangeAccountLog saveLog(final Account account)
{
final Double oldAccountBalance = oldAccountBalance(account);
final Double newAccountBalance = account.getBalance();
final ChangeAccountLog changeAccountLog = new ChangeAccountLog(0,
oldAccountBalance, newAccountBalance);
return this.repository.save(changeAccountLog);
}
@PersistenceContext
EntityManager em;
private Double oldAccountBalance(final Account account)
{
this.em.detach(account);
final Account existingAccount =
this.accountService.findById(account.getId());
if (existingAccount != null)
{
return existingAccount.getBalance();
}
return null;
}
}
The class of which objects are to be logged:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Account
{
@Id
@GeneratedBalance
protected long id;
Double balance;
}
The logging class:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class ChangeAccountLog
{
@Id
@GeneratedBalance
private long id;
private Double oldBalance;
private Double newBalance;
}

Hi everybody I cannot execute the code inside SPSecurity.RunWithElevatedPrivileges any ideas about this

Hi everybody I cannot execute the code inside
SPSecurity.RunWithElevatedPrivileges any ideas about this

this is function where i get all toles related to each user in group the
problem in debug the code inside spsecurity.RunwithElevatedPrivilages
doesn't Execute, and when i remove this line it return to me access denied
for users
public bool IsUserAuthorized(SPUser user, string roleName)
{
bool flagForRoles = true;
SPRoleAssignment RoleAss = null;
Guid siteId = SPContext.Current.Site.ID;
Guid webId = SPContext.Current.Web.ID;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//put your code here to get the group and test for the user
using(SPSite site=new SPSite(siteId))
{
using (SPWeb web = site.OpenWeb(webId))
{
SPGroupCollection groupcoll = user.Groups;
foreach (SPGroup group in groupcoll)
{
RoleAss =
web.RoleAssignments.GetAssignmentByPrincipal((SPPrincipal)group);
foreach (SPRoleDefinition RoleDef in
RoleAss.RoleDefinitionBindings)
{
if (string.Equals(RoleDef.Name, "Contribute"))
{
flagForRoles = false;
break;
}
else if(string.Equals(RoleDef.Name,roleName))
{
flagForRoles=true;
break;
}
}
}
web.Dispose();
site.Dispose();
}
}
});
return flagForRoles;
}

Allowing remote desktop over 2 different NICs

Allowing remote desktop over 2 different NICs

I have 2 networks plugged into a server 2008 R2 box. Both are separate
vlans with internet connections. I want network B to be able to remote
desktop into the server using IP 10.20.0.16 and network A remote desktop
into it via 10.10.0.16.
NIC A has the IP, default gateway, and DNS servers set up. NIC B just has
IP and default gateway (NO DNS). Metric is statically set with NIC A being
20 and NIC B being 40.
The server isn't really used for internet access, just for internal
traffic. Is there anything I need to be worried about by having two
default gateways set up?
Active Routes:
Network Destination Netmask Gateway Interface Metric
0.0.0.0 0.0.0.0 10.10.0.1 10.10.0.16 276
0.0.0.0 0.0.0.0 10.20.0.1 10.20.0.16 296
10.20.0.0 255.255.255.0 On-link 10.20.0.16 296
10.20.0.16 255.255.255.255 On-link 10.20.0.16 296
10.20.0.255 255.255.255.255 On-link 10.20.0.16 296
127.0.0.0 255.0.0.0 On-link 127.0.0.1 306
127.0.0.1 255.255.255.255 On-link 127.0.0.1 306
127.255.255.255 255.255.255.255 On-link 127.0.0.1 306
172.18.0.0 255.255.0.0 On-link 10.10.0.16 276
10.10.0.16 255.255.255.255 On-link 10.10.0.16 276
10.10.255.255 255.255.255.255 On-link 10.10.0.16 276
224.0.0.0 240.0.0.0 On-link 127.0.0.1 306
224.0.0.0 240.0.0.0 On-link 10.10.0.16 276
224.0.0.0 240.0.0.0 On-link 10.20.0.16 296
255.255.255.255 255.255.255.255 On-link 127.0.0.1 306
255.255.255.255 255.255.255.255 On-link 10.10.0.16 276
255.255.255.255 255.255.255.255 On-link 10.20.0.16 296
===========================================================================
Persistent Routes:
Network Address Netmask Gateway Address Metric
0.0.0.0 0.0.0.0 10.10.0.1 Default
0.0.0.0 0.0.0.0 10.20.0.1 Default

Tuesday, 27 August 2013

Convert docx page 1 at a time to an image

Convert docx page 1 at a time to an image

I need to convert docx file to an image page by page. So if I Pass page
number to a method - that method should read that page out of docx file
and convert that to an image. Any example of that using Apache POI API ? I
did that for pptx file but was not able to find similar methods for docx.
Following is the code for pptx.
FileInputStream is = new FileInputStream(strTempPath);
XMLSlideShow pptx = new XMLSlideShow(is);
is.close();
double zoom = 2; // magnify it by 2
AffineTransform at = new AffineTransform();
at.setToScale(zoom, zoom);
Dimension pgsize = pptx.getPageSize();
XSLFSlide[] slide = pptx.getSlides();
}
// BufferedImage img = new
BufferedImage((int)Math.ceil(pgsize.width*zoom),
(int)Math.ceil(pgsize.height*zoom), BufferedImage.TYPE_INT_RGB);
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height,
BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
//graphics.setTransform(at);
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width,
pgsize.height));
slide[iPageNo].draw(graphics);
// FileOutputStream output = new
ByteArrayOutputStream("C:/Temp/aspose/word/slide-" + (10 + 1) +
".png");
output = new ByteArrayOutputStream();
javax.imageio.ImageIO.write(img, "png", output);

inserting elements into array creates nested array where they aren't wanted

inserting elements into array creates nested array where they aren't wanted

Ok, i'll try to explain this best i can:
i'm storing a post_meta_key in WP. the value is an array.
i'm starting up by doing a get_post_meta - which, of course, if it's empty
on the first time, returns an empty array
(http://codex.wordpress.org/Function_Reference/get_post_meta). $single is
set to false. we'll call this array $voters, as this will store the list
of voters (the Key will be the userId, the value is an array - which is
the next thing i'm describing)
i'm then looping through my inputs, sanitizing them, and creating another
key=>value array - this is called the current_vote array - this is the
value.
I would like to insert the current_vote as a value into the voters array.
right now, i've got this: $voters[$voter_id] = $current_vote;
i would think that it would create a key from the $voter_id, and put the
current_vote array as the value, and IT DOES that.
BUT! as the second vote comes in, it doesn't just insert another key into
the existing array - it takes that first vote, and inserts it into a NEW
array!
so, first vote looks like this:
Array
(
[13] => Array
(
[13] => 0
[15] => 75
[21] => 0
[34] => 0
[16] => 0
[50] => 0
[28] => 0
[45] => 0
[10] => 0
[40] => 0
[41] => 0
[52] => 0
[22] => 0
[29] => 0
[23] => 0
[30] => 0
[48] => 0
[53] => 0
[38] => 0
[35] => 0
[61] => 0
[26] => 0
[9] => 0
[62] => 0
[54] => 0
[49] => 0
[14] => 0
[19] => 0
[42] => 0
[55] => 0
[5] => 0
[12] => 0
[46] => 0
[56] => 0
[32] => 0
[36] => 0
[2] => 0
[17] => 0
[4] => 0
[27] => 0
[44] => 0
[25] => 0
[57] => 0
[37] => 0
[3] => 0
[51] => 0
[31] => 0
[43] => 0
[47] => 0
[39] => 0
)
)
but once the second vote comes in, it looks like this:
Array
(
[0] => Array
(
[13] => Array
(
[13] => 0
[15] => 75
[21] => 0
[34] => 0
[16] => 0
[50] => 0
[28] => 0
[45] => 0
[10] => 0
[40] => 0
[41] => 0
[52] => 0
[22] => 0
[29] => 0
[23] => 0
[30] => 0
[48] => 0
[53] => 0
[38] => 0
[35] => 0
[61] => 0
[26] => 0
[9] => 0
[62] => 0
[54] => 0
[49] => 0
[14] => 0
[19] => 0
[42] => 0
[55] => 0
[5] => 0
[12] => 0
[46] => 0
[56] => 0
[32] => 0
[36] => 0
[2] => 0
[17] => 0
[4] => 0
[27] => 0
[44] => 0
[25] => 0
[57] => 0
[37] => 0
[3] => 0
[51] => 0
[31] => 0
[43] => 0
[47] => 0
[39] => 0
)
)
[4] => Array
(
[13] => 75
[15] => 0
[21] => 0
[34] => 0
[16] => 0
[50] => 0
[28] => 0
[45] => 0
[10] => 0
[40] => 0
[41] => 0
[52] => 0
[22] => 0
[29] => 0
[23] => 0
[30] => 0
[48] => 0
[53] => 0
[38] => 0
[35] => 0
[61] => 0
[26] => 0
[9] => 0
[62] => 0
[54] => 0
[49] => 0
[14] => 0
[19] => 0
[42] => 0
[55] => 0
[5] => 0
[12] => 0
[46] => 0
[56] => 0
[32] => 0
[36] => 0
[2] => 0
[17] => 0
[4] => 0
[27] => 0
[44] => 0
[25] => 0
[57] => 0
[37] => 0
[3] => 0
[51] => 0
[31] => 0
[43] => 0
[47] => 0
[39] => 0
)
)
so, the element is inserted correctly (new element has key 4), but the
first element is inserted into a new array key 0.
and here's my full code:
$quarter = substr($date, 1,1);
$year = substr($date, 2,4);
$voters = get_post_meta(2165, 'bonus_votesq'. $quarter . $year);
//initialize vote arrays and vars
$votes = $_POST['votes'];
$voter_id = $_POST['voter_id'];
$voting_array = array();
$current_vote = array();
parse_str($votes, $voting_array);
foreach ($voting_array as $vid => $awarded_points) {
$current_vote[sanitize_key($vid)] = sanitize_key($awarded_points);
}
/* push the local array into what will be the global array
*/
$voters[$voter_id] = $current_vote;
//if meta_data doesn't exist, update_post_meta creates one. if it
does, it updates it.
update_post_meta(2165,'bonus_votesq'. $quarter . $year, $voters);
echo print_r($voters);
what the bleeping F is going on???

URGENT: Transition Effect

URGENT: Transition Effect

I need to get a transition effect which can be found at:
http://leaverou.github.io/animatable/ I need the effect 34. But I want it
to stop after one spin.
As I'm new, can you give me the exact code which I need to use.
Thanks, any help is appreciated.

After maven dependency update from spring 3.0 to 3.1.1 and hibernate 3.6 to 4.0 . Lots of error are coming

After maven dependency update from spring 3.0 to 3.1.1 and hibernate 3.6
to 4.0 . Lots of error are coming

After I changes spring version from 3.0 to 3.1.1
and hibernate version from 3.6.filal to 4.1.7.Final
so I have to change transaction manager class to
org.springframework.orm.hibernate4.HibernateTransactionManager
and session manager class to
org.springframework.orm.hibernate4.LocalSessionFactoryBean
I tried various a lot but am not able to debug . . I have changed junit to
4.9 as some places I searched that this can also be a problem.
What can be the problem
java.lang.ClassNotFoundException:
org.springframework.test.context.transaction.TransactionConfiguration
at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
~[catalina.jar:6.0.32]
at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
~[catalina.jar:6.0.32]
at
org.springframework.core.type.classreading.RecursiveAnnotationAttributesVisitor.visitEnd(AnnotationAttributesReadingVisitor.java:167)
~[org.springframework.core-3.1.1.RELEASE.jar:3.1.1.RELEASE]
at org.springframework.asm.ClassReader.a(Unknown Source)
[org.springframework.asm-3.1.1.RELEASE.jar:3.1.1.RELEASE]
at org.springframework.asm.ClassReader.accept(Unknown Source)
[org.springframework.asm-3.1.1.RELEASE.jar:3.1.1.RELEASE]
at org.springframework.asm.ClassReader.accept(Unknown Source)
[org.springframework.asm-3.1.1.RELEASE.jar:3.1.1.RELEASE]
at
org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:54)
[org.springframework.core-3.1.1.RELEASE.jar:3.1.1.RELEASE]
..
..
..
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
~[na:1.6.0_45]
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
~[na:1.6.0_45]
at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_45]
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
[bootstrap.jar:6.0.32]
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
[bootstrap.jar:6.0.32]

How to change color of line chart in android achartengine dynamically?

How to change color of line chart in android achartengine dynamically?

I am using Achartengine for LineChart. I already added line color for
XYSeriesRenderer object. I am getting dynamic values from a library. If x
value reached maximum, I need to change the color of line chart. I am
using only one series. I tried and I couldn't. Is there any way to change
line color dynamically?

Push Notification using GCM without own Server

Push Notification using GCM without own Server

I want to create push notifications for android using GCM but without
setting up my own server. Are there any third party servers who provides
this facility ?
Thanks in advance

Monday, 26 August 2013

Jquery $.post Issue

Jquery $.post Issue

I want to my post data to login.php page. But problem is $.post() not
working. tell me the error of this code.
/includes/login.page (this one is a lightbox)
<form id="forgot-username-form" method="get" >
<label id="email">Forgotten your username ?</label>
<input type="email" name="forgot_username"
id="user-email" />
<input type="submit" name="forgot_username"
value="Send"/>
</form>
/script/username.js
$(document).ready(function(){
$("#forgot-username-form").submit(function() {
var email = $("#user-email").val();
alert(email);
$.post("login.php",{email:email},function(result){
alert(result);
});
});
});
/login.php
if(isset($_GET['email'])){
$email = $_GET['email'];
echo $email;
}
help me to find a error of this code.

Macro that maps a number to pifont ding character

Macro that maps a number to pifont ding character

With pifont, the darkened circled number starts from 182.

I made a macro that maps \dcircle{1} to \ding{182} as follows.
\newcommand{\dcircle}[1]{\ding{181 + #1}}
However, \dcircle{1} returns the characters that I don't expect:

What might be wrong?

Algorithm for calculating total cost in groups of N

Algorithm for calculating total cost in groups of N

I have a limited supply of objects and as the objects are purchased, the
price goes up accordingly in groups of N (every time N objects are bought,
price increases). When trying to purchase a number of objects, what is the
easiest way to calculate total cost?
Example:
I have 24 foo. For every N(example using 3) that are purchased, the price
increases by 1.
So if I buy 1 at the prices of 1 then there are 23 left and 2 left at the
price of 1.
After 1 has been purchased, someone wishes to buy 6. Well the total cost
would be = (2*1)+(3*2)+(1*3)

Defining Multiple Ranges with an if Statement in R

Defining Multiple Ranges with an if Statement in R

I have a situation where I have a table called districts with a column
called zone, for which 410 values, numbers 1-410 are stored...
Currently, the R code is structured like this:
# add II data to the external matrix
zoneNames <- districts$zone
maxExternalZoneNum <- 99 #assumes externals first in zone numbering and
are less than 99
vehicle[zoneNames > maxExternalZoneNum, zoneNames > maxExternalZoneNum] <-
get(paste(p, "vehicle", sep=""))[zoneNames > maxExternalZoneNum, zoneNames
> maxExternalZoneNum]
assign(paste(p, "vehicle", sep=""),vehicle)
rm(vehicle)
Except that for my purpose, the 99 maxExternalZoneNum does not apply. I
have 1-30 external zone numbers plus another external zone number, 410.
31-409 are "internal" zones, and cannot be renumbered. So I must define
maxExternalZoneNum as a range of values, 1:30 and 410.
What methods could I deploy to efficiently handle the change in the
maxExternalZoneNum so that it does not break the execution of this code?

Set first line AutoFiltered

Set first line AutoFiltered

How can I make the first line to be AutoFiltered with
GetType().InvokeMember and BindingFlags.SetProperty?
range.GetType().InvokeMember("AutoFilter", BindingFlags.SetProperty, null,
range, new object[] { 1, Type.Missing, xlAnd, Type.Missing, true });

Select table from database where value is X

Select table from database where value is X

So far I've found out that this gives me a list of all the tables which
has the column name "store_id" - but I only want it to select the columns
if "store_id" = 4, how could I do this?
Right now I use this to find the tables which has the "store_id" column.
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('store_id')
AND TABLE_SCHEMA='db1';

Sunday, 25 August 2013

Moving splash screen like facebook's splash screen

Moving splash screen like facebook's splash screen

how can i do a splash screen like facebook's splash screen? In facebook's
splash screen the facebook logo moves up and then apear the login view in
the same view. How can I do it? I tried to draw aî animation on existing
view but i couldn't get the current canvas.

List of Services for SQL Server 2012 Express

List of Services for SQL Server 2012 Express

I recently installed VS2013 Preview onto a clean OS and I'm trying to
figure out if SQL Server Express 2012 got installed. Unfortunately, when I
look in Control Panel->Administrative Tools->Services, the only thing I
see mentioning SQL is the "SQL Server VSS Writer"
Can someone tell me what entries I should see in Control
Panel->Administrative Tools->Services after a successful installation of
SQL Server Express?
Ideally, both SQL Server Express and SQL Server Management Studio would
have been installed on my PC when I installed VS2013 Preview but that
doesn't seem to be the case for me.
NOTEs:
I see a bunch of SQL Server Entries in Control Panel->Programs and
Features but when I try to connect to [ComputerName]\SQLExpress via the
SQL Editor of VS2013 Preview, I get a can't connect error.
If I remember correctly, a default installation of VS2010 Pro will also
install a copy of SQL Sever Express, so I would expect a VS2013
installation to do the same

Accent marks in Windows console - Java

Accent marks in Windows console - Java

I've done a basic guessing game with Java. It's in Spanish so it has some
accent marks (á,é) and some inverted exclamations marks (¡). The problem
is that when I run the program on the Command Line it doesn't show the
accents and it looks weird to read... Can someone help me with this?

Objective-C: How to add thumbanils to a TableView From Videos?

Objective-C: How to add thumbanils to a TableView From Videos?

Bellow i have some code that reads and lists the names of files in the
documents directory of my application. This works fine and i know want to
add thumnails from each of the videos i get so i found this code:
NSURL *videoURL = [NSURL fileURLWithPath:@""];
MPMoviePlayerController *player = [[MPMoviePlayerController alloc]
initWithContentURL:videoURL];
UIImage *thumbnail = [player thumbnailImageAtTime:1.0
timeOption:MPMovieTimeOptionNearestKeyFrame];
cell.imageView.image = thumbnail;
[player stop];
However I'm not sure where to point the path to my files so that it adds a
different thumbnail for every separate video my tableview is displaying.
Here is my full code where I'm getting the video files and displaying in
table:
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:@"MainCell"];
if (cell == nil) {
cell = [[UITableViewCell
alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"MainCell"];
}
NSLog(@"urlstring %@",[filePathsArray objectAtIndex:indexPath.row]);
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePathsArray = [[NSFileManager defaultManager]
subpathsOfDirectoryAtPath:documentsDirectory error:nil];
cell.textLabel.text = [filePathsArray[indexPath.row] lastPathComponent];
filePathsArray = [[NSArray alloc] initWithArray: [[[NSFileManager
defaultManager] subpathsOfDirectoryAtPath:documentsDirectory
error:nil]mutableCopy]];
NSURL *videoURL = [NSURL fileURLWithPath:@""];
MPMoviePlayerController *player = [[MPMoviePlayerController alloc]
initWithContentURL:videoURL];
UIImage *thumbnail = [player thumbnailImageAtTime:1.0
timeOption:MPMovieTimeOptionNearestKeyFrame];
cell.imageView.image = thumbnail;
[player stop];
return cell;
}
Thanks in advance.

Liquid width solution to link with 2 background images?

Liquid width solution to link with 2 background images?

I need to give a link background styling. As the width will vary I need to
use 2 images, which is why I have a span within my link.
Ive also needed to float the link left, which means I have to set
paragraphs to clear both.
My solution works but it seems like a lot of css and adding extra html
elements. Is there a more elegant solution?
http://jsfiddle.net/p9aXg/16/
<p>Here is some text Here is some text Here is some text Here is some text
Here is some text Here is some text Here is some text Here is some text
Here is some text Here is some text </p>
<a href="#" class="my-link"><span> This is a link sdafsdafsdaf </span>
</a>
<p>Here is some text Here is some text Here is some text Here is some text
Here is some text Here is some text Here is some text Here is some text
Here is some text Here is some text </p>
a {
background: url("http://smartpeopletalkfast.co.uk/body-link-bg.jpg")
100% 50%;
line-height: 50px;
float: left;
}
a span {
background: url("http://smartpeopletalkfast.co.uk/body-link-bg-2.jpg")
no-repeat;
height: 49px;
display: block;
padding-left: 20px;
padding-right: 40px;
}
p {
clear: both;
}

Django Tastypie Nested parent / child

Django Tastypie Nested parent / child

I have a parent / child relationship in the same model. Example:
Parent Comment

Child comment 01

Child comment 02
I'd like to build an API that brings all of the child threads in nested
fasion. Currently it just brings up the parent comments.
My current API.py looks like this:
class ThreadResource(ModelResource):
locations = fields.ToManyField('forum.api.comments','parent', full=True)
class Meta:
queryset = comments.objects.all()
resource_name = 'Comments'
class comments(ModelResource):
class Meta:
queryset = comments.objects.all()
resource_name = 'comms'
The way i did that in models is:
class comments(models.Model):
title = models.CharField(max_length=255)
parent = models.ForeignKey('self', blank=True,null=True)
sort = models.IntegerField(default=0)
content = models.CharField(max_length=255)

Why doesn't os.system ignore SIGINT?

Why doesn't os.system ignore SIGINT?

I am reading Linux System Programming.
When introducing the system(command) function, the book states that during
execution of the command, SIGINT is ignored.
So, assuming that os.system is just a wrapper of the underlying system
function, I try the following:
loop.py
while True: print 'You should not be able to CTRL+C me ;p'
test_loop.py
import os os.system("python loop.py")
Now that I'm executing loop.py with system, I'm expecting SIGINT to be
ignored, but when I use CTRL+C on the running program it still get killed.
Any idea why os.system differ from the system() function?

Saturday, 24 August 2013

What does bind_param accomplish?

What does bind_param accomplish?

I'm learning about avoiding SQL injections and I'm a bit confused.
When using bind_param, I don't understand the purpose. On the manual page,
I found this example:
$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?,
?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
Now, assuming those 4 variables were user-inputted, I don't understand how
this prevents SQL injections. By my understanding, they can still input
whatever they want in there.
I also can't find an explanation for the 'sssd' in there. What does it do?
Is that what makes it secure-er?
Final question: I read on another question that mysqli_real_escape_string
is deprecated, but it doesn't say that in the manual. How is it
deprecated? Can it not escape special characters anymore for some reason?
Note: This question explained what bind_param does, but I still don't
understand why it is any safer or more protected. Bind_param explanation

passing a php variable into javascript function

passing a php variable into javascript function

I am trying to pass a php value, obtained from a join query, to a
javascript function. The javascript function will open a new window and
show some data based on the passed value.My query works fine but the php
value is not passed to the JS function.
My code :
<script type="text/javascript">
function product(var) {
window.open( "view_product_info.php?var", "myWindow",
"status = 1, height = 300, width = 300, resizable = 0" )
}
</script>
\\ the line where i am trying to pass the php varibale
echo '<td align="center" ><a href="javascript:product('.$product_id.');">
<br/> '.$row['product_name'].'</a></td>';
why the php value $product_id is not passed to the product function.
Thanks in advance.

How to call a constructor from a class, in main method

How to call a constructor from a class, in main method

I know this is probably a super simple question but I can't seem to figure
it out for the life of me.
As the title states I just want to call the constructor in the Main Method.
class Example{
public static void main (String[] args)
{
//I want to call the constructor in the mpgCalculator class....
}
public class mpgCalculator {
public double compute(double mpg, double sizeOfTank)
{
double mpL = mpg * 4;
double tankSizeL = sizeOfTank * 4;
double kmpL = mpL * 1.6;
double result = kmpL / tankSizeL;
return result;
}
}
}

Trouble installing Ephem on a custom distribution of Python ie. Maya (3D / CGI software)

Trouble installing Ephem on a custom distribution of Python ie. Maya (3D /
CGI software)

I downloaded pyEphem for Mac. To install it, I opened a terminal window
and went to the folder I unzipped it to, and typed:
python setup.py install
Works perfectly. However, I use a software called Maya, which I create
custom tools for in Python. pyEphem is only useful to me in Maya. How can
I install / import ephem in Maya's Python?
Thank you SO much in advance for anyone who can help me with this. Best, Paul

Actionmailer - heroku app

Actionmailer - heroku app

This is a newbie question so please excuse me, I have been working with
rails, but this is the first time i am trying to require gems from a
heroku app that does not include rails - just a plain Ruby app. ok I have
a app.rb file looking like this:
require "sinatra"
require 'koala'
require 'action_mailer'
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:address => "smtp.sendgrid.net",
:port => 587,
:domain => "MYDOMAIN",
:authentication => :plain,
:user_name => "USER_NAME",
:password => "PASSWORD",
:enable_starttls_auto => true
}
ActionMailer::Base.view_paths= File.dirname(__FILE__)
class TestMailer < ActionMailer::Base
default :from => "MY_EMAIL"
def welcome_email
mail(:to => "MY_EMAIL", :subject => "Test mail", :body => "Test mail
body")
end
end
What I would like to do is run
TestMailer::deliver_test_email
in the console and get the details or run
TestMailer::deliver_test_email.deliver
to send a test email
but all i get is :
NameError: uninitialized constant Object::TestMailer
I have included actionmailer in the Gemfile and its also in the Gemfile.lock
I am sure it is something straight forward for an experienced Ruby dev,
but I am struggling could anyone help me please?
Thanks

Is there a way to sort backups listed in Rom Manager?

Is there a way to sort backups listed in Rom Manager?

One of the older versions of Rom Manager I used to use did this, but more
recently my backups, as listed by Rom Manager, seem to be listed in
whichever order they please. This is quite annoying when I keep a lot of
backups and they are all named only by ROM, date, and time.
Is there a way to sort them alphabetically and/or by date?
I'm using a Motorola Droid X (shadow). I switch between MIUI (Feb. 2012,
GB 2.3.7) and CM9 (July 2012, ICS 4.0.4). Using the latest Rom Manager
from the Play store, which appears to be 5.5.2.8.
Thanks for any suggestions.
EDIT: Nevermind. Turns out the Rom Manager installation on CM9 wasn't
actually up to date, and apparently my backups were not all named
consistently. It seems that Rom Manager uses the format:
YYYY-MM-DD-HH.nn.ss
while CWM Recovery uses the format:
YYYY-MM-DD.HH.nn.ss
which is why they didn't seem to sort correctly. Updating and making the
names consistent solved the issue.

Friday, 23 August 2013

Parsing nested JSON entries

Parsing nested JSON entries

So far i've only ever parsed JSON that was on an initial array but am
unsure how to proceed.
Here is my JSON:
{
"SongDeviceID": [
{
"SID": "714",
"SDID": "1079287588763212246"
},
{
"SID": "715",
"SDID": "1079287588763212221"
},
{
"SID": "716",
"SDID": "1079287588763212230"
}
]
}
And here is what I have so far in my code:
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:
jsonResponse options: NSJSONReadingMutableContainers error: &e];
NSArray * responseArr = [NSArray arrayWithObject:jsonResponse];
for (NSDictionary *dict in responseArr)
I think im going about this the wrong way because im used to having only
one layer deep JSON responses, can somebody help me out?

Sliding code for a Visual studio 2012 game for windows 8 in c#

Sliding code for a Visual studio 2012 game for windows 8 in c#

I am currently developing a snake and ladder game. but i like to have a
sliding option of the players coins on dice roll. I am writing it in
visual c#. Can anyone help me please in completing my game.
If the dice shows 5 then the respective player's coin should show the
sliding animation from 1 to 5 for an example. and it should continue from
there for the next turn.

Images are not scaling on Foundation

Images are not scaling on Foundation

I have been playing around with the ZURB Foundation Framework on this site:
http://www.maxi-muth.de/test/zurb/

I used this Foundation Template:
http://foundation.zurb.com/page-templates4/grid.html
It seems like it has problems with scaling the images.
By using Chrome everything is displayed fine.
In Firefox the images at the Landing Page are overlapping each others
(/they are displayed in their original size (which is not happening in the
original Foundation template)
Same is happening with the Foundation Thumbnails used here:
http://www.maxi-muth.de/test/zurb/shortcodes
What do I need to do to get (back?) the automatic scaling?

Git - how to find first commit of specific branch

Git - how to find first commit of specific branch

In following example tree:
A-B-C-D-E (master branch)
\
F-G-H (xxx branch)
I'm looking for F - the first commit in xxx branch. I think that it is
possible with:
git log xxx --not master
and the last listed commit should be F. Is it correct solution or maybe
there are some disadvantages of it?
I know that there were similar questions on stackoverflow, but nobody
proposed such solution, and I'm not sure if I do it right.

Munin's load plugin does not appear

Munin's load plugin does not appear

I just did a fresh install of Munin 2.0.6-4 on a Debian 7.1 server from
the debian repositories. The "load" plugin appears as loaded:
# munin-node-configure | grep load
load | yes |
vserver_loadavg | no |
However, I can't see any "Load average" graph. For all I know, the load
plugin seems to be working:
# munin-run load config
graph_title Load average
graph_args --base 1000 -l 0
graph_vlabel load
graph_scale no
graph_category system
load.label load
graph_info The load average of the machine describes how many processes
are in the run-queue (scheduled to run "immediately").
load.info 5 minute load average
# munin-run load
load.value 0.05
I have no idea how to debug this any further.

rewrite rule with .htaccess to mask url

rewrite rule with .htaccess to mask url

My present url structure :
domain.com/items/view/5
domain.com/user/view/5
domain.com/user/edit/5

Now i don't want users to directly know the 'id' in the url, as they can
directly fire a query from the address bar.
Hence i want to mask the url to :

domain.com
i.e. domain.com/anything will come as it is but the url will not change.
Thanks in advance.
Also note that i have already made .htaccess file with following code to
remove 'index.php' from the url and that is working perfect.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>

Thursday, 22 August 2013

Curve of centers of curvature

Curve of centers of curvature

I really can't find the English name of the curve of the centers of
curvature of a curve. Formulated more precisely: Suppose $\alpha$ is a
regular curve in $\mathbb{E}^2$ and $||\alpha(t)'||=1$. How do you call
$\gamma(t) = \alpha(t)+ \frac{1}{\kappa(t)}N(s)$ in English? I'm following
a geometry course in dutch and there this curve is called "centrale
kromme" (literal translation: central curve) or "evoluut" in case this
would ring any bells...
Thanks!

Why is this hanging?

Why is this hanging?

private async void button1_Click(object sender, EventArgs e)
{
var cookie = webBrowser1.Document.Cookie;
await
Task.WhenAll(
listBox1
.Items
.Cast<string>()
.Select(async s =>
{
var data = "action=relationship&user_id=" + s +
"&relation=follow";
var req = WebRequest.Create("http://example.com") as
HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
req.Headers["cookie"] = cookie;
using (var sw = new StreamWriter(await
req.GetRequestStreamAsync(), Encoding.ASCII))
{
sw.Write(data);
sw.Close();
}
}));
listBox1.Items.Clear();
}
I've tried this a million times, and it runs it two times every time. And
when it runs it those two times, it does what it's supposed to.
What it's supposed to do is take items from a listbox, and use each item
as part of a POST request, then when it's done, clear the listbox.
Can someone explain what's wrong?
Thank you.

Issue with importing a databse into phpMyAdmin

Issue with importing a databse into phpMyAdmin

I am learing how to use SQL. I set up a localhost. In the course of that
journey I was confronted to the issue of importing sql files into
phpMyAdmin. I did the right click on config.inc.php and clicked on the
Notepad++ that I previously installed. I typed in there the following
code: $cfg['UploadDir']='c:\Files'; Of course I created on the hard drive
C the 'Files'. Now that I came back into phpMyAdmin, clicked on my
database, clicked on import, this is what I got as message: "The directory
you set for upload work cannot be reached." Can anyone help me here with
this issue? Thanks.

The "Request" section is not working :(

The "Request" section is not working :(

For the past 2 days I haven't been able to collect from my requests. I get
a message that says "Something went wrong. We're working on fixing this
soon." How long is soon? Because 2 days is too long and others have been
waiting longer than that. We need this fixed ASAP. This is happening for
every game we play. And we're losing out on a lot of our gifts because of
this error. I'm hoping that you can fix this real fast please so that we
can all get back to collecting our gifts and being happy.
Thank You Doreen

Fitting image to UAModalPanel

Fitting image to UAModalPanel

I'm currently using UAModalPanel and I just want show pictures with this
component. So I did the following:
#import <UIKit/UIKit.h>
#import "UAModalPanel.h"
@interface LolcatPanel : UAModalPanel
- (void)showLolcat;
@end
#import "LolcatPanel.h"
@implementation LolcatPanel
- (void)showLolcat
{
int pic = (arc4random() % 10) + 1;
NSString *intString = [NSString stringWithFormat:@"%d", pic];
NSMutableString *picture = [[NSMutableString alloc]
initWithString:intString];
[picture appendString:@".jpg"];
NSLog(@"Loading image %@", picture);
NSString* imageName = [[NSBundle mainBundle] pathForResource:intString
ofType:@"jpg"];
UIImage *testImage = [UIImage imageWithContentsOfFile:imageName];
if (testImage == nil) {
NSLog(@"FAILED");
}
UIImageView *imgView = [[UIImageView alloc]
initWithFrame:CGRectMake(0, 0, self.bounds.size.width,
self.bounds.size.height)];
imgView.image = testImage;
imgView.contentMode = UIViewContentModeScaleToFill;
[self addSubview:imgView];
}
@end
I want to show pictures fitting in the UAModelPanel, but ATM the results
are not really good.

Naming of a class which is receiving raw messages and calls known interface

Naming of a class which is receiving raw messages and calls known interface

How to name a class which is responsible for:
receiving messages like Receive(string address, byte[] body) { /* ... */},
parse address, deserealize body, and call the right method of known
interface tree with typed parameters (taken from deserialized body), for
example Open(int timeout)
react on events of known interface tree, like event Action<string>
OpeningError, build the right address string, serialize parameters to
byte[] and raise own event Action<string, byte[]> NewMessage

Wednesday, 21 August 2013

Detect a knock/clap to iPhone/iPad

Detect a knock/clap to iPhone/iPad

I am planning to develop an gyroscope based project like TipSkip, handle
event knock to device from behind or detect a clap ,I searched google but
I didn't find anything except core motion guide and event handling guide.
Thanks for any help

How to explain the execution results of these three python codes?

How to explain the execution results of these three python codes?

Following are three python codes:
======= No. 1 =======
def foo(x, items=[]):
items.append(x)
return items
foo(1) #return [1]
foo(2) #return [1,2]
foo(3) #return [1,2,3]
====== No. 2 ========
def foo(x, items=None):
if items is None:
items = []
items.append(x)
return items
foo(1) #return [1]
foo(2) #return [2]
foo(3) #return [3]
====== No. 3 =======
def foo(x, items=[]):
items.append(x)
return items
foo(1) # returns [1]
foo(2,[]) # returns [2]
foo(3) # returns [1,3]
For code No.1, since the value of items is not provided, I think it should
take a default value of [] all the time. But the parameter items behaves
like a static variable, retaining its value for subsequent use. The code
of No.2 executes as I expected: each time foo is invoked, items take the
default value None. As for code No.3, I totally have no idea. Why the
above three pieces of codes execute so differently? Can you explain? Thank
you.
PS: I'm using python 3.3.1

Is joomla and Wordpress really for designers, or should I write my own cms?

Is joomla and Wordpress really for designers, or should I write my own cms?

Having designed websites for years, the idea of moving to a cms and
simplifying content updates is appealing, especially as it gives the
customer the ability to manage some of their own updates, but am
struggling to get the design control into joomla or Wordpress.
I've purchased Artisteer and still seem to be moulding my sites' design
into artisteer as opposed to vice versa.
Am now considering writing my own cms and wondered if people had any
thoughts. I don't want to design the cms for the masses, just me. Have
very good php, MySQL skills but have heard about ruby on rails and need to
work out the balance of learning something new or sticking with php.
Thanks for any thoughts or opinions!!

Modify color scale legend guide to match line size in ggplot2

Modify color scale legend guide to match line size in ggplot2

How do you override the aes size value for a ggplot2 legend guide based on
a column in the data set?
Refer to this example:
library(data.table)
set.seed(26798)
dt<-rbind(data.table(Trial="A",Value=rweibull(1000,1.0,0.5)),
data.frame(Trial="B",Value=rweibull(100,1.2,0.75)))
# Add a count and something like a cumulative distribution:
dt2<-dt[order(Trial,Value),list(Value,N=.N),by=Trial][,list(Value,N,y=1-cumsum(N)/sum(N)),by=Trial]
dt2
## Trial Value N y
## 1: A 0.0003628745 1000 0.999
## 2: A 0.0013002615 1000 0.998
## 3: A 0.0017002173 1000 0.997
## 4: A 0.0022597343 1000 0.996
## 5: A 0.0026608082 1000 0.995
## ---
##1096: B 1.6821827814 100 0.040
##1097: B 2.2431595707 100 0.030
##1098: B 2.5122479833 100 0.020
##1099: B 2.5519954416 100 0.010
##1100: B 2.6848412995 100 0.000
ggplot(dt2) +
geom_line(aes(x=Value,y=y,group=Trial,color=Trial,size=N)) +
scale_size(range=c(0.1, 2)) +
guides(size=F, color=guide_legend(override.aes=list(size=2)))

I would like the line thickness for each value of Trial in the guide
legend to match the line in the plot (i.e. "A" should be thick and "B"
should be thin). Edit: @Arun gave a good suggestion for adjusting each
thickness manually, but my actual dataset has many factor levels and is
constantly changing, so I need it to be "dynamic".
The answer from @DidzisElferts to a similar question (Control ggplot2
legend look without affecting the plot) shows how to set the size to a
static value. The size=2 part in the last line of the example above lets
me change the line size of the legend, but I would like it to match the
size of the line in the plot. Using size=N instead seems logical, but it
gives the error "object 'N' not found". What is the correct syntax?

Text was truncated or one or more characters had no match in the target code page - Special Characters

Text was truncated or one or more characters had no match in the target
code page - Special Characters

I have a text file with Vertical Bar{|} separated values and I am using a
Flat File source to read the values which fails with the above error.
I have a Flat File Connection Manager, where I set the columnwidth of each
column. The particular column which causes error has
DataType - DT_WSTR
OutputColumnWidth - 30
The problem is raised only when the particular column has special
characters like 'Société Amomyna da Pramt Hgyme' though it still has only
30 characters.
If increase the column width it works but I need to is that the right
solution to increase a much higher column width.

Change background color on refresh

Change background color on refresh

I want my site to have a different background color for the body every
time I refresh the page. Can you please tell me how this would be done
using Javascript or PHP? Thank you.

Tuesday, 20 August 2013

How to continue evaluating a binary tree in scheme

How to continue evaluating a binary tree in scheme

I need to evaluate a scheme function that inputs a number and a binary
tree and it outputs the data expression in the binary tree that is of the
same depth as the number. For example the root of a tree is 1 and the root
of the sub trees are 2 and so on.
This is what I have so far and I keep getting the error message Error in
null?: expected a list; got '1'. (This is another method of solving a
problem that I had asked earlier about) Could you explain this using the
terms that I have already used as I am new to scheme programming.
Thank you
(define fetch-exp (ă (n bt)
(cond [(not (deep-enough? n bt)) ¤#f]
[(one? n) (root bt)]
[(deep-enough? n (left-tree bt))
(fetch-exp (left-tree bt) (sub1 n))]
[(deep-enough? n (right-tree bt))
(fetch-exp (right-tree bt) sub1 n)]
[else ¤#f])))
(define deep-enough?
(ă (n bt)
(cond [(> (tree-depth bt) n) ¤#t]
[(equal? (tree-depth bt) n) ¤#t]
[else ¤#f])))

CSS3 div move on hover not ease-out

CSS3 div move on hover not ease-out

Ok guys, here's the problem: I made this simple menu with three
menu-items, and I want to move each div to the right every time I hover on
it (simple, right? Unfortunately not...)
While it does the ease-in animation, it won't do at all the ease-out one,
the result being not fluid, but blocky and not cool at all.
I searched online and on StackOverflow, too, and applied all
fixes/suggestions made, but I wasn't able to get it to work.
Here's the code (to try, for example, on jsFiddle)
HTML:
<div id="menu-container">
<div class="menu1">Menu 01</div>
<div class="menu2">Menu 02</div>
<div class="menu3">Menu 03</div>
</div>
CSS:
#menu-container div{
height: 30px;
width: 200px;
border:1px solid #999;
background-color:#222;
color:#ccc;
left: 0;
-webkit-transition: all 0.5s ease-in-out;
-moz-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
}
#menu-container div:hover{
position: relative;
color:#fff;
background-color:#333333;
left: 20px;
padding-left: -20px;
}
#menu-container div.menu1:hover{
border-color: red;
}
#menu-container div.menu2:hover{
border-color: blue;
}
#menu-container div.menu3:hover{
border-color: green;
}
What am I doing wrong? Is there a way to fix it?
Thanks in advance

Arrow on popViewController not going where I tell it

Arrow on popViewController not going where I tell it

I have a UIPickerController that appears when you click a button though
the arrow on it doesn't change position from the bottom even when I use
UIPopoverArrowDirectionUp.
- (IBAction)addPicture:(id)sender {
CGRect rect = CGRectMake(0,650,768,1024);
[popOverController presentPopoverFromRect:rect inView:self.view
permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
I guess this must be quite common
Thanks in advance

how to show popover with direction up or down relative to the button's current position

how to show popover with direction up or down relative to the button's
current position

Ok I have a scroll view added as a sub view with a height of approx. 500.
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(x,y,500,300)];
[self.view addSubView:scrollView];
Now I have another view say View1 which contains a lot of buttons arranged
in a vertical direction. View1's height is approx. twice the height of my
scrollView. View1 = [[UIView alloc]
initWithFrame:CGRectMake(0,0,100,300)]; [scrollView addSubView: View1];
now I set my scrollView's content size to fit in my View1. [scrollView
setContentSize: CGSizeMake(1000,300)];
Now able to scroll through my View1 completely. Now I need to show a
popUpViewController when a button within my View1 is pressed with a
direction up or down depending upon the button's current location. For
example if the button lies below the half way in my scrollView's frame,
the popOverViewController should pop up with an upward direction.
Now how do I get relative coordinates of the button to scroll View frame,
and if that button had an initial position below my scrollView's
frame.height.y/2 and after scrolling the button moved up say to a position
above my scrollView's frame.height.y/2, how do you get the relative
coordinates then. I have tried the convertRect: toView: but no success. I
hope you guys understand what i am trying to say here.

Php form to run Google Text to Speech script on server

Php form to run Google Text to Speech script on server

so I want to run this via php exec.
./text2speech.sh "My name is Oscar and I am testing the audio."
Below is my code, how can I send the "" without interfering with the php?
<?php
function doSomething($command) {
exec("./text2speech.sh". " $command", $output);
echo "Returned output:";
var_dump($output);
}
if(count($_POST) > 0 && isset($_POST['command'])) \
{
doSomething($_POST['command']);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Terminal Emulator</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input autocomplete="off" id="command" name="command"
type="text">
<input type="submit" value="Submit">
</form>
</body>
</html>

Replace image with javascript

Replace image with javascript

I'm very new to coding on the web and I'm trying to make something work.
I'm trying to make a little webpage with an easy function to replace an
existing image on the page with an image that the users chooses from his
own computer. All of this is expected to be done offline. I have however,
no idea how..
How do I tackle this?
p.s. With offline I mean, I am expected that this can be done locally
without uploading to a server or anything. I am supposed to put this
little page on a usb stick so it can be used as a little tool.

Monday, 19 August 2013

Solving inequalities, simplifying radicals, and factoring. (Pre calculus)

Solving inequalities, simplifying radicals, and factoring. (Pre calculus)

(Q.1) Solve for x in (x^3) - 5x > 4(x)^2 its a question in pre calculus
for dummies workbook, chapter 2. The answer says: then factor the
quadratic: x(x-5)(x+1)>0. Set your factors equal to 0 so you can find your
key points.When you have them, put these points on a number line and plug
in test numbers form each possible section to determine whether the factor
would be positive or negative. Then, given that you're looking for
positive solution, think about the possibilities: (+)(+)(+) = +, ++- = - ,
-+- = +, --- = -. Therefore, your solution is -1 < x < 0 or x > 5. so i
know how he got the x>5 but i don't get the -1 < x < 0 cuz it suppose to
be x > -1 and what these possibilities have to do with the solution ?
please explain to me in details.
(Q.2) solve for x in (x^5/3) - 6x = (x^4/3) same book. The answer says:
Next, factor out an x from each term: x(x^2/3 - x^1/3 - 6) = 0. The
resulting expression is similar to y^3(y^2 - y - 6), which factors into
y^3(y+2)(y-3).Similarly, you can factor x(x^2/3 - x^1/3 - 6) into x(x^1/3
+ 2)(x^1/3 - 3) = 0 I don't get how did he factor the main equation and
x^5/3 became x^2/3 and x^4/3 became x^1/3. I know how to factor like this
but with numbers not fractions. And also how this expression x(x^2/3 -
x^1/3 - 6) = 0 is similar to that y^3(y^2 - y - 6). I'm solving for x so
why he got the y into the answer now ?! (weird)
(Q.3) simplify 8/(4^2/3) same book. The answers says: change it to
8/sqrt[3]{4^2} ( i get this one ) but then he said multiply the numerator
and denominator by one more cube root of 4 . so how i can multiply 8/
\sqrt[3]{4^2} to 8/ \sqrt[3]{4} and get 4 ? isn't supposed to be 8/
\sqrt[3]{4^2} X 8/ \sqrt[3]{4^2} equals 4 ?

No Burflags in registry

No Burflags in registry

I have a problem where my Windows 2012 Domain Controller SYSVOL and
NETLOGON shares did not get created on my secondary domain controller.
When I run dcdiag /q it tells me that it failed the advertising test, and
cannot access the netlogon share.
Everything I have read about this issue tells me to do a non-authoritative
restore by changing the registry value in:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\NtFrs\Parameters\Backup/Restore\Process
at Startup
However, I do not have this registry key in the registry. Is this the
cause of my issue? Or do I have to create this key?

IOS Cancelling Local Notifications

IOS Cancelling Local Notifications

I dont like asking vague questions but I couldnt exactly tell what the
problem is.
In my app I set some daily local notifications. Shooting everyday at
200PM. I later removed the codes that sets the local notifications, and
added push notification feature.
I test the push and it works (whenever I want to). But I still get the old
notifications as well, could it be because I set them earlier somewhere on
the phone itself. Is there a way to cancel them without coding. For
example are they cancelled if I remove the app?

refreshing javascript files in firefox

refreshing javascript files in firefox

I have a rails app that I am developing in firefox. Recently, my
javascript files have stopped refreshing when I open the app in the
browser. I tried using ctrl + f5, deleting my cache and cookies and
history, renaming the files, even deleting the file altogether to try and
get something to change, but nothing happened. When I view the source code
of the page, everything is correct, but the app doesn't do what it is
supposed to. I'm not able to put random numbers at the end of the src
attributes, because I am getting all my javascript files from the rails
helper <%= javascript_include_tag "application" %>. Is there anything else
I can do to get my javascript files to refresh?

SQL Pivoting or Transposing or ... column to row?

SQL Pivoting or Transposing or ... column to row?

I have a question and this looks way better in SQLfiddle:
http://www.sqlfiddle.com/#!3/dffa1/2
I have a table with multirows for each user with datestamp and test
results and i would like to transpose or pivot it into one line result as
follows where each user has listed all time and value results:
USERID PSA1_time PSA1_result PSA2_time PSA2_result PSA3_time PSA3_result ...
1 1999-.... 2 1998... 4 1999... 6
3 1992... 4 1994 6
4 2006 ... 8
Table below:
CREATE TABLE yourtable ([userid] int, [Ranking] int,[test] varchar(3),
[Date] datetime, [result] int) ;
INSERT INTO yourtable ([userid], [Ranking],[test], [Date], [result])
VALUES ('1', '1', 'PSA', 1997-05-20, 2), ('1', '2','PSA', 1998-05-07, 4),
('1', '3','PSA', 1999-06-08, 6), ('1', '4','PSA', 2001-06-08, 8), ('1',
'5','PSA', 2004-06-08, 0), ('3', '1','PSA', 1992-05-07, 4), ('3',
'2','PSA', 1994-06-08, 6), ('4', '1','PSA', 2006-06-08, 8) ;

After take a picture and save it, sometimes the program crash, doesn't return to the activity

After take a picture and save it, sometimes the program crash, doesn't
return to the activity

I'm calling the function dispatchTakePictureIntent to take a picture. But
after take the picture and save it, the application doesn't returns
correctly to the actual activity, the application crash.
when my button is press i call
dispatchTakePictureIntent(1);
then:
public void dispatchTakePictureIntent(int actionCode) {
try {
Intent takePictureIntent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = createImageFile();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(f));
startActivityForResult(takePictureIntent, actionCode);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* Intent takePictureIntent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, actionCode);*/
}
public File createImageFile() throws IOException {
// Create an image file name
final String nomeForm = "teste";
String imageFileName = nomeForm +".jpeg";
File path = getExternalFilesDir(Environment.DIRECTORY_DCIM);
File image = new File(path,imageFileName );
// String getAbsolutePath = image.getAbsolutePath();
Toast.makeText(this, "Image saved to:\n" + image,
Toast.LENGTH_LONG).show();
return image;
}

Sunday, 18 August 2013

My jquery product slider has a big grey butt

My jquery product slider has a big grey butt

Sorry about the title because I don't know how to describe this question
in just one sentence.
I made a picture to describe this better(this is a picture i took while it
was sliding.)
http://i.imgur.com/l82fTOU.jpg
I'm currently using the caroufredsel slider plugin and its great, but
styling it has been a pain in the butt for me.whatI want to do is to make
sure the slider doesn't have the weird boarder/grey box any more and the
slides ends on the far edge just like where the slider starts in the above
picture.
here is the html:
div class="list_carousel">
<ul id="foo2">
<li>c</li>
<li>a</li>
<li>r</li>
<li>o</li>
<li>u</li>
<li>F</li>
<li>r</li>
<li>e</li>
<li>d</li>
<li>S</li>
<li>e</li>
<li>l</li>
<li> </li>
</ul>
<div class="clearfix"></div>
<a id="prev2" class="prev" href="#">&lt;</a>
<a id="next2" class="next" href="#">&gt;</a>
<div id="pager2" class="pager"></div>
</div>
and here is the css
.list_carousel {
background-color: #ccc;
margin: 0 0 30px 47.5px;
height: 280px;
}
.list_carousel ul {
margin: 0;
padding: 0;
list-style: none;
display: block;
}
.list_carousel li {
font-size: 40px;
color: #999;
text-align: center;
background-color: #eee;
border: 5px solid #999;
width: 180px;
height: 250px;
padding: 0;
margin: 6px;
display: block;
float: left;
}
.list_carousel.responsive {
width: auto;
margin-left: 0;
}
.clearfix {
float: none;
clear: both;
}
.prev {
float: left;
margin-left: 10px;
}
.next {
float: right;
margin-right: 10px;
}
.pager {
float: left;
width: 300px;
text-align: center;
}
.pager a {
margin: 0 5px;
text-decoration: none;
}
.pager a.selected {
text-decoration: underline;
}
.timer {
background-color: #999;
height: 6px;
width: 0px;
}
javascript:
$('#foo2').carouFredSel({
auto: false,
prev: '#prev2',
next: '#next2',
pagination: "#pager2",
mousewheel: true,
swipe: {
onMouse: true,
onTouch: true
}
});

Nested for loops seem to execute separately for some reason

Nested for loops seem to execute separately for some reason

I am attempting to process a two-dimensional array in C. I tried two
nested for loops, but it seems that the two loops execute separately. I
expect that the inside loop loops eight times for each loop of the outside
loop, resulting in eight times the number of outside loops being the total
number of loops.
As a simplified test, I tried this:
#include <stdio.h>
int main() {
int x = 0;
int y = 0;
for (; x < 7; x++, printf("(%d,%d)", x, y)) {
for (; y < 8; y++, printf("(%d,%d)", x, y)) { }
}
}
This resulted in these results:
(0,1)(0,2)(0,3)(0,4)(0,5)(0,6)(0,7)(0,8)(1,8)(2,8)(3,8)(4,8)(5,8)(6,8)
Could somebody please explain to me why this might be happening? Thanks.

Mavericks compatibility with 2012 Macbook

Mavericks compatibility with 2012 Macbook

I am considering purchasing a refurbished Macbook. The model was
originally released in June 2012. I want to know if this laptop is
compatible with the upcoming Mavericks release of OSX. The Apple store
online help is understandably reluctant to commit to compatibility
questions about an as-yet-unreleased product.
Have you used the developer release of Mavericks with this laptop? Any
issues?

How can I put a query to average DOW sales?

How can I put a query to average DOW sales?

How can i join a condition to this query? What i need is average by DOW
with the following condition... Example : Product A at Store 1 has Monday
unit sales that go like this:
Week 1 – 5
Week 2 – 10
Week 3 – 3
Week 4 – 3
Week 1 will have no lost sales, as it is the first week. In week 2, the
baseline average would be 5 – since the week 2 sales is greater than 5,
then there is no lost sales. The average going into week 3 would be 7.5.
Week 3 sales are 3, so the gross lost sales is 4.5. Condn. 1. IF
SALES AVERAGE IS LESS THAN 2.0 PER DAY, THEN THE CALCULATION IS NOT
NECESSARY. LOST SALES SHOULD BE ZERO.
Condn. 2. THE AVERAGE IS THE LAST 13 WEEKS OF SALES FOR THAT
STORE/DAY OF WEEK/PRODUCT. ZEROS DO NOT COUNT IN THE AVERAGE. SO, WEEK
14 SHOULD BE THE AVERAGE OF WEEK 2 TO WEEK 14, ASSUMING THAT ALL OF THESE
DAYS HAVE SALES>0.
(QUERY)
select product_id,
store_id,
trans_date,
promo_sales,
promo_sold_qty,
'Baseline Average(13 week)_1',
from fact_product_hourly
where product_id=650231 and store_id = 886
and dayofweek(trans_date)=2
and trans_date between '2012-11-11' and '2013-07-31'
Please help.

Finding the Vectorized Way to Perform FOR Loops with Calculation Between Rows

Finding the Vectorized Way to Perform FOR Loops with Calculation Between Rows

I'm trying to find a vectorized procedure that can replace the following
code (which takes a LONG time to run):
for (i in 2:nrow(z)) {
if (z$customerID[i]==z$customerID[i-1])
{z$timeDelta[i]<-(z$time[i]-z$time[i-1])} else {z$timeDelta[i]<- NA}
}
I tried looking for different apply snippets, but haven't found anything
useful.
Thanks in advance!
Yoni
EDIT: Sample Data:
customerID time
1 2013-04-17 15:30:00 IDT
1 2013-05-19 11:32:00 IDT
1 2013-05-20 10:14:00 IDT
2 2013-03-14 18:41:00 IST
2 2013-04-24 09:52:00 IDT
2 2013-04-24 17:08:00 IDT
And I want to get the following output:
customerID time timeDelta*
1 2013-04-17 15:30:00 IDT NA
1 2013-05-19 11:32:00 IDT 31.83
1 2013-05-20 10:14:00 IDT 0.94
2 2013-03-14 18:41:00 IST NA
2 2013-04-24 09:52:00 IDT 40.59
2 2013-04-24 17:08:00 IDT 0.3
*I prefer the time will be in days

Unknown template function T()

Unknown template function T()

I've gotten some code in C++ that I am trying to uderstand, but there is
one part that I just can't grasp, even though I've searched around about
it on the Internet. My question is what this means:
if (!(T() < x))
In the struct:
struct Positive_Check_Except
{
template<typename T>
static bool validate(const T& x)
{
if (!(T() < x))
throw check_error(std::to_string(x) + " not positive exception");
return true;
}
};

Saturday, 17 August 2013

Samsung Smart TV is Freezing Using the Revlotional Slider concrete5 Addon

Samsung Smart TV is Freezing Using the Revlotional Slider concrete5 Addon

What Iam trying to do is to make a simple digital signage using concrete5
CMS using the Revolutional Slider in it and displaying the content Using a
samsung smart tv by developing a smart hub app that displays my concrete5
web and the Rev slider addon. So what is happening is that when the show
start after few seconds the TV will Freeze and will not interact with the
remote control untill power is shutoff from it ....
Any Help Suggestions Or support Thank you

What is the difference between following statements

What is the difference between following statements

What is the difference between following 2 scanf statements,
#include<stdio.h>
void main()
{
int a,b;
clrscr();
printf("\n Enter values for a and b");
scanf("%d",&a); // Format specifier as %d
scanf("%i",&b); // Format specifier as %i
printf("\n a is %d and b is %i",a,b);
getch();
}
I given values a as 10 and b as 20. It is giving same values as an output,
So my questions are
what is the difference between %d and %i.??
What about the memory for each variable ??
Is there is any difference between %d and %i as a format specifier ???

Detect touches for 2 subviews

Detect touches for 2 subviews

I have a UIView sitting atop a UIScrollView.
I'd like to be able to scroll my ScrollView normally while having my
UIView catch:
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
The only issue is I cannot seem to get both subviews to detect touches at
the same time. I can set the top one to userInteractionEnabled to NO. But
that doesnt really help me get them both.
Any thoughts??
Thanks!

Please help me understand an abbreviated word ("RP") in a context

Please help me understand an abbreviated word ("RP") in a context

Can you help me understand what my client meant about RP in this context.
"I canceled my application since the payment scheme wasn't validated in RP."
What doe's RP means?
Thanks!

What are some algorithms that can assist with reservation time scheduling?

What are some algorithms that can assist with reservation time scheduling?

Here's the gist of the problem: There are multiple service providers who
each have their own schedules of availability. There are multiple
customers who seek their services. Customers need to be able to book a
reservation time for the service but they should only be able to book
times in which some service provider is available (ie they don't really
care which particular provider they get so long as they get a provider).
Unfortunately, service providers may change schedules between when the
customer registers and when the service is provided, meaning that even
with the reservation safeguards in place there could still end up being
too many reservations for a given time.
I would like to know what work has already been done on this sort of
problem, and additionally:
Should providers actually be "assigned" to customers in a persistent way
even though providers are interchangeable?
Depending on the answer to the previous question, how might I determine
the provider's "next assignment" based on the current time, other
providers' schedules, and scheduled reservations?
I've thought a lot about this problem but I am stumped and left with
unsatisfying solutions. As someone with no CS background I would
appreciate some insight and/or a better way to think about the problem.

Unable to create spree extension - unable to activate rails-3.2.4 activesupport version conflicts

Unable to create spree extension - unable to activate rails-3.2.4
activesupport version conflicts

I'm a newbie to Ruby/Rails/Spree and am trying to follow this tutorial
http://guides.spreecommerce.com/developer/extensions_tutorial.html#creating-an-extension
to create a simple spree extension.
I enter this command:
spree extension simple_sales
and cd into spree_simple_sales
Any rails command I type now within this directory (eg. rails -v) results
in this error:
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:1637:in
`raise_if_conflicts': Unable to activate rails-3.2.4, because
activesupport-4.0.0 conflicts with activesupport (= 3.2.14),
actionpack-4.0.0 conflicts with actionpack (= 3.2.14), railties-4.0.0
conflicts with railties (= 3.2.14), activerecord-4.0.0 conflicts with
activerecord (= 3.2.14), actionmailer-4.0.0 conflicts with actionmailer (=
3.2.14) (Gem::LoadError)
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:746:in
`activate'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:780:in
`block in activate_dependencies'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:766:in
`each'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:766:in
`activate_dependencies'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:750:in
`activate'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:780:in
`block in activate_dependencies'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:766:in
`each'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:766:in
`activate_dependencies'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:750:in
`activate'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems.rb:212:in
`rescue in try_activate'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems.rb:209:in
`try_activate'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:59:in
`rescue in require'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:35:in
`require'
from D:/Dev/Tests and
Tutorials/rails/extensions/spree_simple_sales/lib/spree_simple_sales/engine.rb:3:in
`<class:Engine>'
from D:/Dev/Tests and
Tutorials/rails/extensions/spree_simple_sales/lib/spree_simple_sales/engine.rb:2:in
`<module:SpreeSimpleSale>'
from D:/Dev/Tests and
Tutorials/rails/extensions/spree_simple_sales/lib/spree_simple_sales/engine.rb:1:in
`<top (required)>'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in
`require'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in
`require'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0/lib/rails/engine/commands.rb:11:in
`<top (required)>'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in
`require'
from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in
`require'
from script/rails:7:in `<main>'
What can I do to fix this? I am on Win 7, have used RailsInstaller to
install Ruby 1.9.3. I have both Rails 4.0.0 and 3.2.14 but am using Rails
3.2.14 with Spree. Thanks!