Efficient MILP problem reformulation
I am trying to solve the following MILP through LP solve. A link for the
original problem is here
The total number of binary variables = M*N
The total number of real variables = N
The total number of constraints = N + M*N + M
M ~ 10, N ~ 40. (H_i, W_i | i = 1 to N) and T are constants.
minimize sum { CW_k | k = 1, ..., N }
with respect to
C_i_k in { 0, 1 }, Feeder i placed in column k, i = 1, ..., M; k = 1,
..., N
CW_k >= 0, Width of column k //k = 1, ..., N
and subject to
//Total height of each column less than T
// I have already implemented height of present column <= height of prev col
// to avoid duplicate solutions.
[1] sum { H_i * C_i_k | i = 1, ..., M } <= T, k = 1, ..., N
//Width of each column = max( widths of individual feeders in that column)
[2] CW_k >= W_i * C_i_k, i = 1, ..., M; k = 1, ..., N
// Each feeder can be placed in only 1 column.
[3] sum { C_i_k | k = 1, ..., N } = 1, i = 1, ..., M
However, beyond a particular value of N (say 20) lp_solve just appears to
hang. I am told that the above size is pretty much "handle-able" for
solvers.
Is there any way I can re-formulate the above MILP so that it can be
solved more efficiently. I have not tried out other solvers but I guess
the performance shall not vary much.
Any help shall be appreciated.
Thanks!
Monday, 30 September 2013
Linux Speedtest (or download) capable of 10Gbps
Linux Speedtest (or download) capable of 10Gbps
We recently just got some brand new servers from Softlayer out of Dallas
05 that should have 10Gbps connectivity and I'd like to test this claim
against a few locations. Does anyone have any good method of testing this?
I obviously don't expect to see the full 10Gbps due to various factors but
I'd like to see just how good it is.
We recently just got some brand new servers from Softlayer out of Dallas
05 that should have 10Gbps connectivity and I'd like to test this claim
against a few locations. Does anyone have any good method of testing this?
I obviously don't expect to see the full 10Gbps due to various factors but
I'd like to see just how good it is.
Compare and contrast interfaces in Java and Delphi
Compare and contrast interfaces in Java and Delphi
I am a Java developer who has recently been thrust into wearing a Delphi
developer hat.
As is typically the case in such situations, I wind up trying to do things
in Delphi while still using my 'Java' mindset, and I get confounded when
they don't work.
Today's issue is the notion of an interface. In Java, I can define an
interface, give it some methods, and later declare a class that implements
that interface.
I have tried to do the same thing in Delphi, and got my fingers burned. I
declared an interface that extended IInterface. But when it came time to
implement that interface, I was greeted by a number of unimplemented
methods errors for methods I didn't declare (QueryInterface, _AddRef,
_Release).
A little Google told me that I needed to extend the TInterfacedObject
instead of TObject. This made me uneasy because it suggests that I cannot
simply add an interface to some third-party class unless that class
ultimately extends TInterfacedObject.
But now, when it becomes time to set my interfaced object .Free, I'm
getting EInvalidPointer exceptions.
As a result, I'm beginning to conclude that the word interface means
something completely different to a Java developer, and a Delphi
developer.
Can someone who is proficient at both languages enlighten me as to the
differences?
Cheers.
I am a Java developer who has recently been thrust into wearing a Delphi
developer hat.
As is typically the case in such situations, I wind up trying to do things
in Delphi while still using my 'Java' mindset, and I get confounded when
they don't work.
Today's issue is the notion of an interface. In Java, I can define an
interface, give it some methods, and later declare a class that implements
that interface.
I have tried to do the same thing in Delphi, and got my fingers burned. I
declared an interface that extended IInterface. But when it came time to
implement that interface, I was greeted by a number of unimplemented
methods errors for methods I didn't declare (QueryInterface, _AddRef,
_Release).
A little Google told me that I needed to extend the TInterfacedObject
instead of TObject. This made me uneasy because it suggests that I cannot
simply add an interface to some third-party class unless that class
ultimately extends TInterfacedObject.
But now, when it becomes time to set my interfaced object .Free, I'm
getting EInvalidPointer exceptions.
As a result, I'm beginning to conclude that the word interface means
something completely different to a Java developer, and a Delphi
developer.
Can someone who is proficient at both languages enlighten me as to the
differences?
Cheers.
Dates in all activity
Dates in all activity
Hi am using Date picker in more than three class with same validation.
Instead I must write in one class and call that function in other classes
when I required, is it possible Below code for Date picker.
public class MainActivity extends Activity {
private TextView tvDisplayDate;
private Button btnChangeDate;
private int myear;
private int mmonth;
private int mday;
static final int DATE_DIALOG_ID = 999;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setCurrentDateOnView();
addListenerOnButton();
}
// display current date
public void setCurrentDateOnView() {
tvDisplayDate = (TextView) findViewById(R.id.tvDate);
final Calendar c = Calendar.getInstance();
myear = c.get(Calendar.YEAR);
mmonth = c.get(Calendar.MONTH);
mday = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
tvDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(mmonth + 1).append("-").append(mday).append("-")
.append(myear).append(" "));
}
public void addListenerOnButton() {
btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
btnChangeDate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
// set date picker as current date
DatePickerDialog _date = new DatePickerDialog(this,
datePickerListener, myear,mmonth,
mday)
{
@Override
public void onDateChanged(DatePicker view, int year, int
monthOfYear, int dayOfMonth)
{
if (year < myear)
view.updateDate(myear, mmonth, mday);
if (monthOfYear < mmonth && year == myear)
view.updateDate(myear, mmonth, mday);
if (dayOfMonth < mday && year == myear && monthOfYear
== mmonth)
view.updateDate(myear, mmonth, mday);
}
};
return _date;
}
return null;
}
private DatePickerDialog.OnDateSetListener datePickerListener = new
DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
myear = selectedYear;
mmonth = selectedMonth;
mday = selectedDay;
// set selected date into textview
tvDisplayDate.setText(new StringBuilder().append(mmonth + 1)
.append("-").append(mday).append("-").append(myear)
.append(" "));
Date dateObject1 = new Date(myear - 1900, mmonth, mday);
Date dateObj2 = new Date(System.currentTimeMillis());
if(dateObject1.before(dateObj2) || dateObject1.equals(dateObj2)){
//the program runs normally
}
else{
new AlertDialog.Builder(MainActivity.this)
.setTitle("Wrong Data Input!")
.setMessage("The end Date must be Before
the start Date, please insert new Date
values")
.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
}
};
}
Hi am using Date picker in more than three class with same validation.
Instead I must write in one class and call that function in other classes
when I required, is it possible Below code for Date picker.
public class MainActivity extends Activity {
private TextView tvDisplayDate;
private Button btnChangeDate;
private int myear;
private int mmonth;
private int mday;
static final int DATE_DIALOG_ID = 999;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setCurrentDateOnView();
addListenerOnButton();
}
// display current date
public void setCurrentDateOnView() {
tvDisplayDate = (TextView) findViewById(R.id.tvDate);
final Calendar c = Calendar.getInstance();
myear = c.get(Calendar.YEAR);
mmonth = c.get(Calendar.MONTH);
mday = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
tvDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(mmonth + 1).append("-").append(mday).append("-")
.append(myear).append(" "));
}
public void addListenerOnButton() {
btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
btnChangeDate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
// set date picker as current date
DatePickerDialog _date = new DatePickerDialog(this,
datePickerListener, myear,mmonth,
mday)
{
@Override
public void onDateChanged(DatePicker view, int year, int
monthOfYear, int dayOfMonth)
{
if (year < myear)
view.updateDate(myear, mmonth, mday);
if (monthOfYear < mmonth && year == myear)
view.updateDate(myear, mmonth, mday);
if (dayOfMonth < mday && year == myear && monthOfYear
== mmonth)
view.updateDate(myear, mmonth, mday);
}
};
return _date;
}
return null;
}
private DatePickerDialog.OnDateSetListener datePickerListener = new
DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
myear = selectedYear;
mmonth = selectedMonth;
mday = selectedDay;
// set selected date into textview
tvDisplayDate.setText(new StringBuilder().append(mmonth + 1)
.append("-").append(mday).append("-").append(myear)
.append(" "));
Date dateObject1 = new Date(myear - 1900, mmonth, mday);
Date dateObj2 = new Date(System.currentTimeMillis());
if(dateObject1.before(dateObj2) || dateObject1.equals(dateObj2)){
//the program runs normally
}
else{
new AlertDialog.Builder(MainActivity.this)
.setTitle("Wrong Data Input!")
.setMessage("The end Date must be Before
the start Date, please insert new Date
values")
.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
}
};
}
Sunday, 29 September 2013
is MyISAM or Innodb.. With no future support for MyISAM if my app runs using it should i worry?
is MyISAM or Innodb.. With no future support for MyISAM if my app runs
using it should i worry?
The program is old and was written for MYISAM tables. With several of
these in use, it would be a major effort (and worry about problems
afterward) to switch. As long as I can continue to run older versions of
MySQL is there any other reason to change? I do not need more speed, the
tables are ridiculously small as it is and never had a single problem. I
hate to fix things that aren't broken as they usually are broken afterward
using it should i worry?
The program is old and was written for MYISAM tables. With several of
these in use, it would be a major effort (and worry about problems
afterward) to switch. As long as I can continue to run older versions of
MySQL is there any other reason to change? I do not need more speed, the
tables are ridiculously small as it is and never had a single problem. I
hate to fix things that aren't broken as they usually are broken afterward
Scala: Type Mismatch found, Unit required: Boolean
Scala: Type Mismatch found, Unit required: Boolean
I have been trying to run this code but somehow have hit the wall with
'unit mismatch, boolean expected error'. I have run through various
questions on Stackoverflow but haven't found anything concrete that
answers my question.
def balance(chars: List[Char]): Boolean =
{
var i = 0;
var j = 0;
if (Count(i, j) == 0){
true
}
else{
false
}
def Count(count: Int, Pos: Int): Int =
{
if (Pos == chars.length)
{
count
}
else
{
if (chars(Pos) == '(')
{
Count(count + 1, Pos + 1);
}
else
{
Count(count - 1, Pos - 1);
}
}
}
}
I have been trying to run this code but somehow have hit the wall with
'unit mismatch, boolean expected error'. I have run through various
questions on Stackoverflow but haven't found anything concrete that
answers my question.
def balance(chars: List[Char]): Boolean =
{
var i = 0;
var j = 0;
if (Count(i, j) == 0){
true
}
else{
false
}
def Count(count: Int, Pos: Int): Int =
{
if (Pos == chars.length)
{
count
}
else
{
if (chars(Pos) == '(')
{
Count(count + 1, Pos + 1);
}
else
{
Count(count - 1, Pos - 1);
}
}
}
}
UserControl in XAML with parametrs (Win Store App)
UserControl in XAML with parametrs (Win Store App)
I need to send parametrs to my usercontrol. I now how implement sending
but I don't how to take this parametrs. My code:
<UserControls:ItemTemplateControl Parametr="23"/>
Thanks in advance!
I need to send parametrs to my usercontrol. I now how implement sending
but I don't how to take this parametrs. My code:
<UserControls:ItemTemplateControl Parametr="23"/>
Thanks in advance!
Saturday, 28 September 2013
C++: Possible GCC 4.7.1 bug related to virtual templated multiple inheritance?
C++: Possible GCC 4.7.1 bug related to virtual templated multiple
inheritance?
I have code with inheritance that looks like this:
B
/ \
/ \
/ \
BI D
(template) /
\ /
\ /
DI
(template)
The templates are instantiated at runtime through factories, and
everything is glued together with boost::any. Things should work fine,
except they don't. I get segfaults and obscure crashes.
I have sort of pinpointed the problem. It seems to be a bug, but I'm not a
C++ expert, and I may be unwittingly invoking undefined behavior.
A fully independent, working example is contained in the files below.
Here's the main.cpp file:
#include <iostream>
#include "base.hpp"
int main(void)
{
std::unique_ptr<Base> base = Base::create("Hello world!");
std::cout << "base -> " << base.get() << std::endl;
base->check();
return 0;
}
Base::create() is a factory method which calls another factory method,
Derived::create(), which instantiates class DerivedImpl<T>.
base->check() simply prints the value of this.
One would expect of the program to print the exact same address; it's same
object, after all. Alas, it doesn't. In my case, the offset is by 4, but
that's arbitrary.
The rest of the source is below. Run the example for yourself. I'd like
this mystery, if there even is one, resolved.
base.hpp
#ifndef BASE_HPP
#define BASE_HPP
#include <memory>
#include <string>
class Base
{
public:
static std::unique_ptr<Base> create(const std::string&);
virtual ~Base();
virtual void check(void) = 0;
protected:
virtual void init(const std::string&) = 0;
virtual void init(void) = 0;
};
inheritance?
I have code with inheritance that looks like this:
B
/ \
/ \
/ \
BI D
(template) /
\ /
\ /
DI
(template)
The templates are instantiated at runtime through factories, and
everything is glued together with boost::any. Things should work fine,
except they don't. I get segfaults and obscure crashes.
I have sort of pinpointed the problem. It seems to be a bug, but I'm not a
C++ expert, and I may be unwittingly invoking undefined behavior.
A fully independent, working example is contained in the files below.
Here's the main.cpp file:
#include <iostream>
#include "base.hpp"
int main(void)
{
std::unique_ptr<Base> base = Base::create("Hello world!");
std::cout << "base -> " << base.get() << std::endl;
base->check();
return 0;
}
Base::create() is a factory method which calls another factory method,
Derived::create(), which instantiates class DerivedImpl<T>.
base->check() simply prints the value of this.
One would expect of the program to print the exact same address; it's same
object, after all. Alas, it doesn't. In my case, the offset is by 4, but
that's arbitrary.
The rest of the source is below. Run the example for yourself. I'd like
this mystery, if there even is one, resolved.
base.hpp
#ifndef BASE_HPP
#define BASE_HPP
#include <memory>
#include <string>
class Base
{
public:
static std::unique_ptr<Base> create(const std::string&);
virtual ~Base();
virtual void check(void) = 0;
protected:
virtual void init(const std::string&) = 0;
virtual void init(void) = 0;
};
why is "href" attribute needed in "a" tag in FB share code
why is "href" attribute needed in "a" tag in FB share code
<a href="#"
onclick="
window.open(
'https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(location.href),
'facebook-share-dialog',
'width=626,height=436');
return false;">
Share on Facebook
</a>
Apologies if this is a beginner question. But why is "href" there? What
purpose does it serve? I am not getting its purpose.
I am assuming "onclick" a new window will be opened which has all the
information in it about the link to be shared and the FB target
destination.
Then why is "href" there????
<a href="#"
onclick="
window.open(
'https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(location.href),
'facebook-share-dialog',
'width=626,height=436');
return false;">
Share on Facebook
</a>
Apologies if this is a beginner question. But why is "href" there? What
purpose does it serve? I am not getting its purpose.
I am assuming "onclick" a new window will be opened which has all the
information in it about the link to be shared and the FB target
destination.
Then why is "href" there????
R: remove repeating row entries in gridExtra table
R: remove repeating row entries in gridExtra table
Problem:
I create a table using the gridExtra package:
require("gridExtra")
# Prepare data frame
col1 = c(rep("A", 3), rep("B", 2), rep("C", 5))
col2 = c(rep("1", 4), rep("2", 3), rep("3", 3))
col3 = c(1:10)
df = data.frame(col1, col2, col3)
# Create table
grid.arrange(tableGrob(df, show.rownames=F))
The output looks like:
Question:
I would like to get rid of the repeating row entries and achieve spanning
entries which like like this:
Any ideas how to achieve this?
Problem:
I create a table using the gridExtra package:
require("gridExtra")
# Prepare data frame
col1 = c(rep("A", 3), rep("B", 2), rep("C", 5))
col2 = c(rep("1", 4), rep("2", 3), rep("3", 3))
col3 = c(1:10)
df = data.frame(col1, col2, col3)
# Create table
grid.arrange(tableGrob(df, show.rownames=F))
The output looks like:
Question:
I would like to get rid of the repeating row entries and achieve spanning
entries which like like this:
Any ideas how to achieve this?
Order SQL search results by how many fields match
Order SQL search results by how many fields match
My question is, if I have fields like: rooms, district, bathrooms,
floor_material etc. then how can I order my Query results by the number of
field matches?
How do I check before echoing, how many fields match? Also, I don't want
to display results, where all fields match, but also results where 50%
result match, these should be in the bottom.
Also the script should show what fields don't match.
Where should I start?
Thanks in advance, Otto
My question is, if I have fields like: rooms, district, bathrooms,
floor_material etc. then how can I order my Query results by the number of
field matches?
How do I check before echoing, how many fields match? Also, I don't want
to display results, where all fields match, but also results where 50%
result match, these should be in the bottom.
Also the script should show what fields don't match.
Where should I start?
Thanks in advance, Otto
Friday, 27 September 2013
Delphi Application freezes while loading data
Delphi Application freezes while loading data
My Delphi application communicates with server through HTTP request. Every
30 seconds It calls one procedure DownLoad(URL) which returns the data to
the application.
As the data size large it will take around 5-6 seconds to return data. Now
when it downloads the data, it will freeze whole screen. I am going to use
threading so that once data downloading completes it will notify
application about data downloading is completed and application will not
get hanged/freeze.
I wanted to know if that is the only option to acomplish this? or if there
is any ways other than threading? Any good example of threading is
welcome.
Thanks.
My Delphi application communicates with server through HTTP request. Every
30 seconds It calls one procedure DownLoad(URL) which returns the data to
the application.
As the data size large it will take around 5-6 seconds to return data. Now
when it downloads the data, it will freeze whole screen. I am going to use
threading so that once data downloading completes it will notify
application about data downloading is completed and application will not
get hanged/freeze.
I wanted to know if that is the only option to acomplish this? or if there
is any ways other than threading? Any good example of threading is
welcome.
Thanks.
Does Windows OS kill a background process that has been idle for a while?(printing)
Does Windows OS kill a background process that has been idle for a
while?(printing)
My code spawns a tiff printer and I want to keep the printer around in
between print sessions. i.e other processes would be performed by my code
in between those print sessions. My problem is that the printer dies off
roughly after 10 minutes each time. I believe this is because the process
associated with the spawned printer(PNSrv9.exe) is killed somehow. So if
the session that occurs in between my print sessions takes longer than 10
minutes, my print session wouldn't work because there would be no printer.
Does anyone know if the OS kills a process if it's not being actively used
after a while or if it is possible that a program can kill itself after a
while if its not being used? I have looked around and found nothing to
indicate the former.
while?(printing)
My code spawns a tiff printer and I want to keep the printer around in
between print sessions. i.e other processes would be performed by my code
in between those print sessions. My problem is that the printer dies off
roughly after 10 minutes each time. I believe this is because the process
associated with the spawned printer(PNSrv9.exe) is killed somehow. So if
the session that occurs in between my print sessions takes longer than 10
minutes, my print session wouldn't work because there would be no printer.
Does anyone know if the OS kills a process if it's not being actively used
after a while or if it is possible that a program can kill itself after a
while if its not being used? I have looked around and found nothing to
indicate the former.
Fire function when Grunt task is completed
Fire function when Grunt task is completed
I have a grunt multitask registerd and i'm trying to fire a function once
a task has ended. I'm using grunt.task.run. Here is the code.
grunt.task.run(["clean", "sass:prod", "cssmin", "concat", "uglify",
"copy:dev"]);
I want to run a function once the copy:dev task is completed. Any ideas?
I have a grunt multitask registerd and i'm trying to fire a function once
a task has ended. I'm using grunt.task.run. Here is the code.
grunt.task.run(["clean", "sass:prod", "cssmin", "concat", "uglify",
"copy:dev"]);
I want to run a function once the copy:dev task is completed. Any ideas?
Advice on using one application as a front-end for logging into another application
Advice on using one application as a front-end for logging into another
application
I've written an app in Grails using Spring Security that can handle all of
the user oriented tasks like login, logout, reset password, and new user
registration with email verification. The app also can manage user roles
and the like. It has it's own postgres database to store user information.
I want to use the Grails app as a front-end for another legacy Tomcat GWT
app that uses Spring Security and that only has login/logout, and it
depends on user data being populated through LDAP. It has no user
registration front end, or reset password functionality. The legacy app
has it's own postgres database with user information.
I plan on running two instances of Tomcat on two different ports on the
same machine to host these two apps. Both apps will have access to all
databases.
The question is, what is the best way to have the Grails app accept
logins, and then pass the user on to the legacy app? Am I describing
Single Sign On?
The legacy app has code for preauthentication, but it looks to me like
just passing a user name through the request header is not secure! How
would the legacy app know that the user is really logged in? I've been
reading a little about Secure Remote Passwords, and I'm wondering if it
might be a way to handle securely logging into the Grails app, and passing
off control to the legacy app?
Any advice is appreciated!
application
I've written an app in Grails using Spring Security that can handle all of
the user oriented tasks like login, logout, reset password, and new user
registration with email verification. The app also can manage user roles
and the like. It has it's own postgres database to store user information.
I want to use the Grails app as a front-end for another legacy Tomcat GWT
app that uses Spring Security and that only has login/logout, and it
depends on user data being populated through LDAP. It has no user
registration front end, or reset password functionality. The legacy app
has it's own postgres database with user information.
I plan on running two instances of Tomcat on two different ports on the
same machine to host these two apps. Both apps will have access to all
databases.
The question is, what is the best way to have the Grails app accept
logins, and then pass the user on to the legacy app? Am I describing
Single Sign On?
The legacy app has code for preauthentication, but it looks to me like
just passing a user name through the request header is not secure! How
would the legacy app know that the user is really logged in? I've been
reading a little about Secure Remote Passwords, and I'm wondering if it
might be a way to handle securely logging into the Grails app, and passing
off control to the legacy app?
Any advice is appreciated!
Python - spectragram how to
Python - spectragram how to
How do I generate a spectrogram of a 1D signal in python?
I'm not sure how to do this and I was given an example, spectrogram e.g.
but this is in 2D.
I code here that generates a mix of frequencies and I can pick these out
in the fft, how may I see these in a spectrogram - I appreciate that the
frequencies in my example don't change over time; so does this mean I'll
see a straight line across the spectrogram?
my code and the output image:
# create a wave with 1Mhz and 0.5Mhz frequencies
dt = 2e-9
t = np.arange(0, 10e-6, dt)
y = np.cos(2*pi*1e6*t) + (np.cos(2*pi*2e6*t) * np.cos(2*pi*2e6*t))
y = y*np.hanning(len(y))
yy = np.concatenate((y,([0]*10*len(y))))
# FFT of this
Fs= 1/dt # sampling rate, Fs = 500MHz = 1/2ns
n = len(yy) # length of the signal
k = np.arange(n)
T = n/Fs
frq = k/T # two sides frequency range
frq = frq[range(n/2)] # one side frequency range
Y = fft(yy)/n # fft computing and normalization
Y = Y[range(n/2)] / max(Y[range(n/2)])
# plotting the data
subplot(3,1,1)
plot(t*1e3,y,'r')
xlabel('Time (micro seconds)')
ylabel('Amplitude')
grid()
# plotting the spectrum
subplot(3,1,2)
plot(frq[0:600],abs(Y[0:600]),'k')
xlabel('Freq (Hz)')
ylabel('|Y(freq)|')
grid()
# plotting the specgram
subplot(3,1,3)
Pxx, freqs, bins, im = specgram(y, NFFT=512, Fs=Fs, noverlap=10)
show()
How do I generate a spectrogram of a 1D signal in python?
I'm not sure how to do this and I was given an example, spectrogram e.g.
but this is in 2D.
I code here that generates a mix of frequencies and I can pick these out
in the fft, how may I see these in a spectrogram - I appreciate that the
frequencies in my example don't change over time; so does this mean I'll
see a straight line across the spectrogram?
my code and the output image:
# create a wave with 1Mhz and 0.5Mhz frequencies
dt = 2e-9
t = np.arange(0, 10e-6, dt)
y = np.cos(2*pi*1e6*t) + (np.cos(2*pi*2e6*t) * np.cos(2*pi*2e6*t))
y = y*np.hanning(len(y))
yy = np.concatenate((y,([0]*10*len(y))))
# FFT of this
Fs= 1/dt # sampling rate, Fs = 500MHz = 1/2ns
n = len(yy) # length of the signal
k = np.arange(n)
T = n/Fs
frq = k/T # two sides frequency range
frq = frq[range(n/2)] # one side frequency range
Y = fft(yy)/n # fft computing and normalization
Y = Y[range(n/2)] / max(Y[range(n/2)])
# plotting the data
subplot(3,1,1)
plot(t*1e3,y,'r')
xlabel('Time (micro seconds)')
ylabel('Amplitude')
grid()
# plotting the spectrum
subplot(3,1,2)
plot(frq[0:600],abs(Y[0:600]),'k')
xlabel('Freq (Hz)')
ylabel('|Y(freq)|')
grid()
# plotting the specgram
subplot(3,1,3)
Pxx, freqs, bins, im = specgram(y, NFFT=512, Fs=Fs, noverlap=10)
show()
INCLUDEPATH in QT creator doesn't work
INCLUDEPATH in QT creator doesn't work
I've got a problem with include in QtCreator, in my .pro file I've got :
INCLUDEPATH += "C:\OpenCV\build\include"
and in my cpp : #include
result : Cannot open include file: 'opencv\cv.h': No such file or directory
but if I write this in my cpp:
include "C:\OpenCV\build\include\opencv\cv.h"
it works!!!
Any idea why?
thanks
I've got a problem with include in QtCreator, in my .pro file I've got :
INCLUDEPATH += "C:\OpenCV\build\include"
and in my cpp : #include
result : Cannot open include file: 'opencv\cv.h': No such file or directory
but if I write this in my cpp:
include "C:\OpenCV\build\include\opencv\cv.h"
it works!!!
Any idea why?
thanks
Thursday, 26 September 2013
Ho to setup iOS Infobar in a cordova/phonegap project
Ho to setup iOS Infobar in a cordova/phonegap project
I have created a cordova/phonegap project. With the new iOS 7, now the
infobar lays above my header (dark blue). By default the infobar is in
black font, how can I change it into white or any other color?
Thanks, Nik
I have created a cordova/phonegap project. With the new iOS 7, now the
infobar lays above my header (dark blue). By default the infobar is in
black font, how can I change it into white or any other color?
Thanks, Nik
Thursday, 19 September 2013
SQL Server FREETEXTTABLE with optional query on linked table
SQL Server FREETEXTTABLE with optional query on linked table
I'm trying to build a search stored procedure for my application. I'm
using sql server 2008. The search allows the user to query several fields
on the "Case" table along with a free text search on the "Case.Name". The
user can also perform a free text search on a linked table "Address".
Is it possible to make the second free text search optional, without
having 2 queries. I've actually got several fields users can search across
multiple linked tables so I'd have to write a statement for every possible
combination of fields.
In my stored proc I've got:
SELECT DISTINCT Cases.*, Case_ftt.Rank
FROM
dbo.Contacts INNER JOIN
dbo.CaseContacts ON dbo.Contacts.ContactID =
dbo.CaseContacts.ContactID RIGHT OUTER JOIN
dbo.Cases ON dbo.CaseContacts.CaseID = dbo.Cases.CaseID LEFT
OUTER JOIN
dbo.Addresses ON dbo.Cases.AddressID = dbo.Addresses.AddressID
-- CaseName
INNER JOIN
(
(SELECT [Key], [Rank] FROM FREETEXTTABLE(Cases, Name, @Name))
UNION
(SELECT CaseID as [Key], 0 as [Rank] FROM Cases WHERE
@Name='""')
) as Case_ftt on Case_ftt.[Key] = Cases.CaseID
-- Address
INNER JOIN
FREETEXTTABLE(Addresses, *, @Address)as Address_ftt
on Address_ftt.[Key] = Cases.AddressID
WHERE
(CaseStatusID = @CaseStatusID OR @CaseStatusID IS NULL) AND
(CaseTypeID = @CaseTypeID OR @CaseTypeID IS NULL) AND
CaseStatusID <> 'VOID'
ORDER BY
Case_ftt.[Rank] DESC
OPTION (RECOMPILE)
With the Case freetexttable used the union to make it optional, which
works as expected but the same does not work for the address field as not
all cases are linked to addresses so null address are not included in the
result set.
I'm trying to build a search stored procedure for my application. I'm
using sql server 2008. The search allows the user to query several fields
on the "Case" table along with a free text search on the "Case.Name". The
user can also perform a free text search on a linked table "Address".
Is it possible to make the second free text search optional, without
having 2 queries. I've actually got several fields users can search across
multiple linked tables so I'd have to write a statement for every possible
combination of fields.
In my stored proc I've got:
SELECT DISTINCT Cases.*, Case_ftt.Rank
FROM
dbo.Contacts INNER JOIN
dbo.CaseContacts ON dbo.Contacts.ContactID =
dbo.CaseContacts.ContactID RIGHT OUTER JOIN
dbo.Cases ON dbo.CaseContacts.CaseID = dbo.Cases.CaseID LEFT
OUTER JOIN
dbo.Addresses ON dbo.Cases.AddressID = dbo.Addresses.AddressID
-- CaseName
INNER JOIN
(
(SELECT [Key], [Rank] FROM FREETEXTTABLE(Cases, Name, @Name))
UNION
(SELECT CaseID as [Key], 0 as [Rank] FROM Cases WHERE
@Name='""')
) as Case_ftt on Case_ftt.[Key] = Cases.CaseID
-- Address
INNER JOIN
FREETEXTTABLE(Addresses, *, @Address)as Address_ftt
on Address_ftt.[Key] = Cases.AddressID
WHERE
(CaseStatusID = @CaseStatusID OR @CaseStatusID IS NULL) AND
(CaseTypeID = @CaseTypeID OR @CaseTypeID IS NULL) AND
CaseStatusID <> 'VOID'
ORDER BY
Case_ftt.[Rank] DESC
OPTION (RECOMPILE)
With the Case freetexttable used the union to make it optional, which
works as expected but the same does not work for the address field as not
all cases are linked to addresses so null address are not included in the
result set.
Javascript for-in loops: How do I relatively increment a CSS value on each iteration?
Javascript for-in loops: How do I relatively increment a CSS value on each
iteration?
Javascript for-in loops: How do I relatively increment a CSS value on each
iteration?
I'm trying to increment a margin-left value with each passing of a loop.
How is this achieved?
Here's the JSFiddle: http://jsfiddle.net/3hxDK/2/
Here's what I'm trying to do:
var myObj = {
"dog":"pony",
"sass":"tude",
"war":"peace"
};
for (i in myObj) {
$('#mainDiv').append("<p>" + i + "</p>");
$('p').css("marginLeft","++20px");
}
So the output would have each
tag incremented by 20px more than the
tag before it.
Any ideas?
iteration?
Javascript for-in loops: How do I relatively increment a CSS value on each
iteration?
I'm trying to increment a margin-left value with each passing of a loop.
How is this achieved?
Here's the JSFiddle: http://jsfiddle.net/3hxDK/2/
Here's what I'm trying to do:
var myObj = {
"dog":"pony",
"sass":"tude",
"war":"peace"
};
for (i in myObj) {
$('#mainDiv').append("<p>" + i + "</p>");
$('p').css("marginLeft","++20px");
}
So the output would have each
tag incremented by 20px more than the
tag before it.
Any ideas?
Should I use click events followed by $state.transitionTo rather than hrefs when using ui-router?
Should I use click events followed by $state.transitionTo rather than
hrefs when using ui-router?
I am currently using a link like this to cause a transition.
<a href="/questions/5"><span class="ng-binding">1</span></a>
With ui-router would it be possible for me to replace the href with a
click event that fired a function in my controller passing in the question
number and then have the controller trigger a change of state using the
$state.transitionTo ?
If so then when using ui-router is this better than haing href's placed in
my HTML ?
hrefs when using ui-router?
I am currently using a link like this to cause a transition.
<a href="/questions/5"><span class="ng-binding">1</span></a>
With ui-router would it be possible for me to replace the href with a
click event that fired a function in my controller passing in the question
number and then have the controller trigger a change of state using the
$state.transitionTo ?
If so then when using ui-router is this better than haing href's placed in
my HTML ?
FormsAuthenticationTicket and SlidingExpiration
FormsAuthenticationTicket and SlidingExpiration
I have this snippet of code in to authenticate create a Forms
AuthenticationTicket:
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
username, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent,
groups);
I think this is pretty boilerplate code. However, when I go to set my
slidingExpiration attribute in my web.config file as so:
<forms loginUrl="domain.com/auth/login.aspx" slidingExpiration="true"
defaultUrl="https://domain.com" cookieless="UseDeviceProfile"
domain="domain.com">
</forms>
It appears that my slidingExpiration is not working. I have tried
requesting a page within the time that it specifies (from what I
understand in between minute 30 and minute 60), but it still logs me out.
Why is this happening?
Thanks!
I have this snippet of code in to authenticate create a Forms
AuthenticationTicket:
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
username, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent,
groups);
I think this is pretty boilerplate code. However, when I go to set my
slidingExpiration attribute in my web.config file as so:
<forms loginUrl="domain.com/auth/login.aspx" slidingExpiration="true"
defaultUrl="https://domain.com" cookieless="UseDeviceProfile"
domain="domain.com">
</forms>
It appears that my slidingExpiration is not working. I have tried
requesting a page within the time that it specifies (from what I
understand in between minute 30 and minute 60), but it still logs me out.
Why is this happening?
Thanks!
unable to add refrence of restful wcf service in windows service
unable to add refrence of restful wcf service in windows service
When i tried to add the reference of restful wcf service to windows
service. I am getting "The type or namespace name 'RestfulService' could
not be found (are you missing a using directive or an assembly
reference?)" error.
MY Interface Is
[ServiceContract(Name = "RJContract",
Namespace = "RestfulService",
SessionMode = SessionMode.Allowed)]
public interface IService1
{
[OperationContract]
[WebGet(UriTemplate = "/rjdata/{name}")]
string RJData(string name);
}
App.Config
<system.serviceModel>
<services>
<service name="RestfulService.Service1">
<host>
<baseAddresses>
<add baseAddress =
"http://localhost:8732/RestfulService/Service1/" />
</baseAddresses>
</host>
<endpoint binding="webHttpBinding"
contract="RestfulService.IService1"
bindingConfiguration="RESTBindingConfiguration"
behaviorConfiguration="RESTEndpointBehavior"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="RESTBindingConfiguration">
<security mode="None" />
</binding>
</webHttpBinding>
<netTcpBinding>
<binding name="DefaultBinding">
<security mode="None"/>
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="RESTEndpointBehavior">
<webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json"
automaticFormatSelectionEnabled="true"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"
aspNetCompatibilityEnabled="true" />
</system.serviceModel>
But i am able to add the reference with the following.
[ServiceContract(Name = "RJContract",
Namespace = "RestfulService",
SessionMode = SessionMode.Allowed)]
public interface IService1
{
[OperationContract]
[WebGet(UriTemplate = "/rjdata/{name}")]
string RJData(string name);
}
When i tried to add the reference of restful wcf service to windows
service. I am getting "The type or namespace name 'RestfulService' could
not be found (are you missing a using directive or an assembly
reference?)" error.
MY Interface Is
[ServiceContract(Name = "RJContract",
Namespace = "RestfulService",
SessionMode = SessionMode.Allowed)]
public interface IService1
{
[OperationContract]
[WebGet(UriTemplate = "/rjdata/{name}")]
string RJData(string name);
}
App.Config
<system.serviceModel>
<services>
<service name="RestfulService.Service1">
<host>
<baseAddresses>
<add baseAddress =
"http://localhost:8732/RestfulService/Service1/" />
</baseAddresses>
</host>
<endpoint binding="webHttpBinding"
contract="RestfulService.IService1"
bindingConfiguration="RESTBindingConfiguration"
behaviorConfiguration="RESTEndpointBehavior"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="RESTBindingConfiguration">
<security mode="None" />
</binding>
</webHttpBinding>
<netTcpBinding>
<binding name="DefaultBinding">
<security mode="None"/>
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="RESTEndpointBehavior">
<webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json"
automaticFormatSelectionEnabled="true"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"
aspNetCompatibilityEnabled="true" />
</system.serviceModel>
But i am able to add the reference with the following.
[ServiceContract(Name = "RJContract",
Namespace = "RestfulService",
SessionMode = SessionMode.Allowed)]
public interface IService1
{
[OperationContract]
[WebGet(UriTemplate = "/rjdata/{name}")]
string RJData(string name);
}
Objective C reading array from file fails on different locations
Objective C reading array from file fails on different locations
I am developing a mac app and I want to put my settings (array of strings)
into a file. If that file exists in the same folder as the app it is read
and it overwrites default settings.
No problems writing the file but when reading with code:
NSArray* settingsInput = [[NSArray alloc]
initWithContentsOfFile:@"./SettingsFile"];
something strange happens. When running the app from XCode (the settings
file is in the build/debug folder next to the app) settings are read
without a problem. When I archive the app and run it from the desktop, the
file cannot be loaded. Even when I copy the app from the build folder to
the desktop it does not work.
What could be the reason for this kind of behaviour? How can I read this
file?
I am developing a mac app and I want to put my settings (array of strings)
into a file. If that file exists in the same folder as the app it is read
and it overwrites default settings.
No problems writing the file but when reading with code:
NSArray* settingsInput = [[NSArray alloc]
initWithContentsOfFile:@"./SettingsFile"];
something strange happens. When running the app from XCode (the settings
file is in the build/debug folder next to the app) settings are read
without a problem. When I archive the app and run it from the desktop, the
file cannot be loaded. Even when I copy the app from the build folder to
the desktop it does not work.
What could be the reason for this kind of behaviour? How can I read this
file?
edtitext default values comes in emulator not on device
edtitext default values comes in emulator not on device
I am having a weird problem, I have few EditText boxes in xml and I have
given them default values. I am using shared preferences too wherein I
save values entered by user.
Problem is that in Emulator EditText works fine but on real physical
device values are empty, am i missing something???
<EditText
android:id="@+id/etTRQPO"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal"
android:singleLine="true"
android:text="15">
</EditText>
I am having a weird problem, I have few EditText boxes in xml and I have
given them default values. I am using shared preferences too wherein I
save values entered by user.
Problem is that in Emulator EditText works fine but on real physical
device values are empty, am i missing something???
<EditText
android:id="@+id/etTRQPO"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal"
android:singleLine="true"
android:text="15">
</EditText>
Wednesday, 18 September 2013
how to access the parent tag using javascript from inside a child tag
how to access the parent tag using javascript from inside a child tag
Say I have the following code
<div id='div1'>
<div onclick="f1(parent div tag)">
hello
</div>
</div>
I think my code is clear. Here I want to access the <div> with id 'div1'
(or say the id of it if available) to send it as a parameter to the
JavaScript function f1(). How can I do It?
I am getting no reference for exactly this problem from anywhere else.
Please help me out.
Say I have the following code
<div id='div1'>
<div onclick="f1(parent div tag)">
hello
</div>
</div>
I think my code is clear. Here I want to access the <div> with id 'div1'
(or say the id of it if available) to send it as a parameter to the
JavaScript function f1(). How can I do It?
I am getting no reference for exactly this problem from anywhere else.
Please help me out.
Parse a version information xml and print it using c++ libxml
Parse a version information xml and print it using c++ libxml
Here is the input I get.
<record name="Version">
<field name="major" value="03 "/>
<field name="minor" value="01 "/>
<field name="micro" value="00 "/>
<field name="patch" value="05 "/>
</record>
need to print it like "Version: 03.01.00.05"
MgmtXml::dumpXmlNode(
recordNodePtr,
str);
//with above statement, I get the xml file into "str" in same format
every-time
doc = xmlParseMemory(str.c_str(), str.length());
cur = xmlDocGetRootElement(doc);
v = xmlGetProp(cur, (const xmlChar *)"name");
printf("\n%s:\n", v); //here it prints Version:
// don't know how to print the rest, which is 03.01.00.05
Thanks!
Here is the input I get.
<record name="Version">
<field name="major" value="03 "/>
<field name="minor" value="01 "/>
<field name="micro" value="00 "/>
<field name="patch" value="05 "/>
</record>
need to print it like "Version: 03.01.00.05"
MgmtXml::dumpXmlNode(
recordNodePtr,
str);
//with above statement, I get the xml file into "str" in same format
every-time
doc = xmlParseMemory(str.c_str(), str.length());
cur = xmlDocGetRootElement(doc);
v = xmlGetProp(cur, (const xmlChar *)"name");
printf("\n%s:\n", v); //here it prints Version:
// don't know how to print the rest, which is 03.01.00.05
Thanks!
How can I combine multiple rows of a table into multiple columns in Mysql with 1 query?
How can I combine multiple rows of a table into multiple columns in Mysql
with 1 query?
I have a table that stores values based on two identifying values (product
code, and a detail code) that make each row unique and a 3rd value that
stores a type of value based on the detail code. What I would like to do
is display all of the third values for any one product code in new
columns. The detail code would act as a column header.
What I have tried so far:
SELECT id1,
CASE WHEN id2 ='A'
THEN value
ELSE 0
END A,
CASE WHEN id2 ='B'
THEN value
ELSE 0
END B
FROM table1
WHERE id2 = 'A' OR id2 = 'B'
GROUP BY id1
This has worked ok, except that when a value for id2 = 'A' exists inn the
table, the CASE WHEN for id2 = 'B' defaults to 0 instead of the correct
value, if there is one. If there is no record for the id2 = 'A' then the
CASE WHEN will work correctly for id2 = 'B'.
I'm assuming there's also a better way to go about this, but had trouble
finding this exact situation anywhere. I can definitely use the data
without the multiple columns, but was hoping not to/learn something
with 1 query?
I have a table that stores values based on two identifying values (product
code, and a detail code) that make each row unique and a 3rd value that
stores a type of value based on the detail code. What I would like to do
is display all of the third values for any one product code in new
columns. The detail code would act as a column header.
What I have tried so far:
SELECT id1,
CASE WHEN id2 ='A'
THEN value
ELSE 0
END A,
CASE WHEN id2 ='B'
THEN value
ELSE 0
END B
FROM table1
WHERE id2 = 'A' OR id2 = 'B'
GROUP BY id1
This has worked ok, except that when a value for id2 = 'A' exists inn the
table, the CASE WHEN for id2 = 'B' defaults to 0 instead of the correct
value, if there is one. If there is no record for the id2 = 'A' then the
CASE WHEN will work correctly for id2 = 'B'.
I'm assuming there's also a better way to go about this, but had trouble
finding this exact situation anywhere. I can definitely use the data
without the multiple columns, but was hoping not to/learn something
Iterate through appended items using jQuery
Iterate through appended items using jQuery
I have a form that uses jQuery for magic. On that form is a button Add
Account. That button appends fields Account and Amount and also another
button Remove Account (which if you can guess, removes those two fields).
This all works nicely...
On the same form there is another field Salary, which I would like to
compare with the total of all the Amount fields. The problem is when I use
jQuery's $.each() to iterate through the Amount fields it only recognizes
those fields that were present in the DOM when the page loaded, and not
the newly added fields.
How can I iterate through these appended Amount fields? (Or maybe there is
a better to do this altogether?)
What I'm doing now:
$(document).ready(function(){
$('#form').on('keyup', '.amount', balanceAmountsWithSalary);
});
var balanceAmountsWithSalary = function(){
var salary = parseInt($('#salary').val(),10);
var total = 0;
$('#accounts .account').each(function(){
var amount = parseInt($(this).find('.amount').val(),10);
total += amount;
});
if (total === salary) {
$('#accounts .account').each(function(){
// Do some stuff to each input.amount located in div.account
});
} else {
$('#accounts .account').each(function(){
// Do some BAD stuff to each input.amount located in div.account
});
}
}
Thanks!
I have a form that uses jQuery for magic. On that form is a button Add
Account. That button appends fields Account and Amount and also another
button Remove Account (which if you can guess, removes those two fields).
This all works nicely...
On the same form there is another field Salary, which I would like to
compare with the total of all the Amount fields. The problem is when I use
jQuery's $.each() to iterate through the Amount fields it only recognizes
those fields that were present in the DOM when the page loaded, and not
the newly added fields.
How can I iterate through these appended Amount fields? (Or maybe there is
a better to do this altogether?)
What I'm doing now:
$(document).ready(function(){
$('#form').on('keyup', '.amount', balanceAmountsWithSalary);
});
var balanceAmountsWithSalary = function(){
var salary = parseInt($('#salary').val(),10);
var total = 0;
$('#accounts .account').each(function(){
var amount = parseInt($(this).find('.amount').val(),10);
total += amount;
});
if (total === salary) {
$('#accounts .account').each(function(){
// Do some stuff to each input.amount located in div.account
});
} else {
$('#accounts .account').each(function(){
// Do some BAD stuff to each input.amount located in div.account
});
}
}
Thanks!
Is there a lemmatizer for PHP?
Is there a lemmatizer for PHP?
Does anyone know of a lemmatizer in PHP? Or, at worst, some way to use a
lemmatizer in another language (python NLTK, for instance?) in a PHP
webapp?
I'm building a macro-etymological analyzer and I've encountered this issue
where the etymological database doesn't contain conjugated words. A
lemmatizer would correct this, I think, by giving me the word "say" when
the dictionary can't find "said," and returning "good" when the dictionary
can't find "better," etc.
Does anyone know of a lemmatizer in PHP? Or, at worst, some way to use a
lemmatizer in another language (python NLTK, for instance?) in a PHP
webapp?
I'm building a macro-etymological analyzer and I've encountered this issue
where the etymological database doesn't contain conjugated words. A
lemmatizer would correct this, I think, by giving me the word "say" when
the dictionary can't find "said," and returning "good" when the dictionary
can't find "better," etc.
Pro and Con about AutoLayout
Pro and Con about AutoLayout
yesterday, I have a problem with CGRectMake, which I already posted here :
CGRectMake is not working with UIView
it caused by AutoLayout enabled on my project. so I have to disable it.
case closed...
but today, when I run my project on 3.5 inch simulator I have a new
problem... all of my textfield, button, etc seems like a mess...
everything has no proper space between them. unlike when I have autoLayout
enabled. here's how it looks like :
is this the consequences of not enabling autoLayout? if so, what should I
do to make constant space between textfield, space of label to navbar,
etc...
thank you
yesterday, I have a problem with CGRectMake, which I already posted here :
CGRectMake is not working with UIView
it caused by AutoLayout enabled on my project. so I have to disable it.
case closed...
but today, when I run my project on 3.5 inch simulator I have a new
problem... all of my textfield, button, etc seems like a mess...
everything has no proper space between them. unlike when I have autoLayout
enabled. here's how it looks like :
is this the consequences of not enabling autoLayout? if so, what should I
do to make constant space between textfield, space of label to navbar,
etc...
thank you
How can I disable jslider using plugin?
How can I disable jslider using plugin?
I would like to make jslider disabled when button is clicked. like this.
$('#sliderID').slider('disable');
I use egorkhmelev jslider plugin. https://github.com/egorkhmelev/jslider
Need help on urgent. Thanks.
I would like to make jslider disabled when button is clicked. like this.
$('#sliderID').slider('disable');
I use egorkhmelev jslider plugin. https://github.com/egorkhmelev/jslider
Need help on urgent. Thanks.
Android to setaction bar without title bar
Android to setaction bar without title bar
I want to set action bar without title bar.
I have tried @android:style/theme.light.notitlebar as well as i also tried
this link Adding an action bar to Theme.Black.NoTitleBar Android
but it is not working . Where i am wrong, please help me
I want to set action bar without title bar.
I have tried @android:style/theme.light.notitlebar as well as i also tried
this link Adding an action bar to Theme.Black.NoTitleBar Android
but it is not working . Where i am wrong, please help me
Tuesday, 17 September 2013
usb camera Implementation in Android.....?
usb camera Implementation in Android.....?
I want to implement USB camera in my android application. all the pictures
should be taken from the USB camera connected to the android device. I
dont have much Idea on how to work on linux as well. Any suggestions would
be helpful. I am using jelly bean for the device.
I want to implement USB camera in my android application. all the pictures
should be taken from the USB camera connected to the android device. I
dont have much Idea on how to work on linux as well. Any suggestions would
be helpful. I am using jelly bean for the device.
Newbie lua - timed bonus
Newbie lua - timed bonus
I am fairly new to the lua language and I wonder if anyone out there can
help please?
I am making a game in lua - specifically Corona SDK - and I am stuck (and
have been for about a week now) on a timed health bonus ( the player would
get a health bonus every 4 hours) and the second part is the Player would
get a free spin of a wheel type game that will give them the chance to win
free items to use in the game.
The part that is really confusing me is how do I get the timed bonus to be
accurate (ex. every 4 hours and once a day) to fire off the functions for
the bonuses? I also want there to be a count down timer showing
hours:minutes:seconds left before next available bonus can be collected???
Is this impossible to do? Please help me. I am really confused and fairly
new to all of this.
I have searched and tried to find tutorials and example code for about 5
or 6 days now but to no avail.
here is some of my code so far...
function hourlyBonus()
local date = os.date( "*t" )
local currentHour = date.hour
lastHourlyBonusClaimedHour =
GameSave.lastHourlyBonusClaimedHour or date.hour
--account for the 24 hour clock
if currentHour > 12 then
currentHour = currentHour - 12
end
if lastHourlyBonusClaimedHour > 12 then
lastHourlyBonusClaimedHour = lastHourlyBonusClaimedHour - 12
end
if currentHour == (lastHourlyBonusClaimedHour + 4) then
lastHourlyBonusClaimedHour = currentHour
-- increase the bonus
print("New 4 hour bonus ThisHour is:
"..thisHourNum)
else
local hoursToWait = (4 - (currentHour -
lastHourlyBonusClaimedHour))
--have to wait for hourly bonus
print("Have to wait: "..hoursToWait.."hours,
"..minutes.."minutes, and "..second.."seconds
to collect hourly Bonus still!")
print("CurrentHour is:"..currentHour)
print("LastHourlyBonusClaimedHour is
:"..lastHourlyBonusClaimedHour)
end
GameSave.lastHourlyBonusClaimedHour =
lastHourlyBonusClaimedHour
GameSave:save()
end
I am totally lost. If anyone has some sample code I could look at or show
me how to do this I would greatly appreciate it! Thanks for any help in
advance.
I am fairly new to the lua language and I wonder if anyone out there can
help please?
I am making a game in lua - specifically Corona SDK - and I am stuck (and
have been for about a week now) on a timed health bonus ( the player would
get a health bonus every 4 hours) and the second part is the Player would
get a free spin of a wheel type game that will give them the chance to win
free items to use in the game.
The part that is really confusing me is how do I get the timed bonus to be
accurate (ex. every 4 hours and once a day) to fire off the functions for
the bonuses? I also want there to be a count down timer showing
hours:minutes:seconds left before next available bonus can be collected???
Is this impossible to do? Please help me. I am really confused and fairly
new to all of this.
I have searched and tried to find tutorials and example code for about 5
or 6 days now but to no avail.
here is some of my code so far...
function hourlyBonus()
local date = os.date( "*t" )
local currentHour = date.hour
lastHourlyBonusClaimedHour =
GameSave.lastHourlyBonusClaimedHour or date.hour
--account for the 24 hour clock
if currentHour > 12 then
currentHour = currentHour - 12
end
if lastHourlyBonusClaimedHour > 12 then
lastHourlyBonusClaimedHour = lastHourlyBonusClaimedHour - 12
end
if currentHour == (lastHourlyBonusClaimedHour + 4) then
lastHourlyBonusClaimedHour = currentHour
-- increase the bonus
print("New 4 hour bonus ThisHour is:
"..thisHourNum)
else
local hoursToWait = (4 - (currentHour -
lastHourlyBonusClaimedHour))
--have to wait for hourly bonus
print("Have to wait: "..hoursToWait.."hours,
"..minutes.."minutes, and "..second.."seconds
to collect hourly Bonus still!")
print("CurrentHour is:"..currentHour)
print("LastHourlyBonusClaimedHour is
:"..lastHourlyBonusClaimedHour)
end
GameSave.lastHourlyBonusClaimedHour =
lastHourlyBonusClaimedHour
GameSave:save()
end
I am totally lost. If anyone has some sample code I could look at or show
me how to do this I would greatly appreciate it! Thanks for any help in
advance.
iOS 7: SKStoreProductViewController not displaying on 64 bit
iOS 7: SKStoreProductViewController not displaying on 64 bit
The SKStoreProductViewController (which loads the iTunes store in app)
does not appear to load on iOS 7 compiled for 64 bit.
I have tested Xcode 5 running on 32 bit and the
SKStoreProductViewController loads fine, however, when run on 64 bit, it
does not display. The rest of my app seems fine on 64 bit.
Has anyone else encountered this problem?
Thanks.
The SKStoreProductViewController (which loads the iTunes store in app)
does not appear to load on iOS 7 compiled for 64 bit.
I have tested Xcode 5 running on 32 bit and the
SKStoreProductViewController loads fine, however, when run on 64 bit, it
does not display. The rest of my app seems fine on 64 bit.
Has anyone else encountered this problem?
Thanks.
How to keep a running instance of geany 1.23.1 glued to a desktop?
How to keep a running instance of geany 1.23.1 glued to a desktop?
I am running Slackware linux and geany 1.23.1. I keep a running instance
of geany open in virtual desktop #3 and use the other desktops for other
work. When I open a new file from an other desktop, it opens in the
running instance, BUT that instance then jumps to my current desktop. The
older geany 1.19 left the running instance in #3, and opened the new file.
How can I get 1.23.1 to do the same? I read the geany manual. Nada.
I am running Slackware linux and geany 1.23.1. I keep a running instance
of geany open in virtual desktop #3 and use the other desktops for other
work. When I open a new file from an other desktop, it opens in the
running instance, BUT that instance then jumps to my current desktop. The
older geany 1.19 left the running instance in #3, and opened the new file.
How can I get 1.23.1 to do the same? I read the geany manual. Nada.
to count business days including list having holiday list
to count business days including list having holiday list
I am having two tables one is biz_date and holiday. create table biz_date
(t_date string,start_date string,biz_day int) create table holiday (h_date
string) now i want to count number of h_date that comes between t_date and
start_date for each row in biz_date table and then subtract it from
biz_day . biz_day is the business day for that day of month. i tried this
query
select b.t_date,b.biz_day,b.biz_date-cnt,h.h_date,
if(b.start_date>=h_date && b.t_date> h.h_date) then count(h_date)as cnt
from biz_date b,holiday h;
I am having two tables one is biz_date and holiday. create table biz_date
(t_date string,start_date string,biz_day int) create table holiday (h_date
string) now i want to count number of h_date that comes between t_date and
start_date for each row in biz_date table and then subtract it from
biz_day . biz_day is the business day for that day of month. i tried this
query
select b.t_date,b.biz_day,b.biz_date-cnt,h.h_date,
if(b.start_date>=h_date && b.t_date> h.h_date) then count(h_date)as cnt
from biz_date b,holiday h;
Auditing an Oracle constraint violation?
Auditing an Oracle constraint violation?
Can I to audit an Oracle constraint violation?
I created a constraint in a table and I want to audit it when some process
violate this constraint. This is possible? How can I do it?
I'm using Oracle 11g.
Can I to audit an Oracle constraint violation?
I created a constraint in a table and I want to audit it when some process
violate this constraint. This is possible? How can I do it?
I'm using Oracle 11g.
Sunday, 15 September 2013
Fold / Collapse the except code section in sublime text 2
Fold / Collapse the except code section in sublime text 2
is there any plugin or shortcut to hide all except code section in sublime
text 2?
is there any plugin or shortcut to hide all except code section in sublime
text 2?
I run the migrations on code igniter succefully (so it seems) but there's no trace of it in the db
I run the migrations on code igniter succefully (so it seems) but there's
no trace of it in the db
I'm running CI on vagrant and when I run the code in my controller
<?php
class Migration extends Admin_Controller
{
public function __construct ()
{
parent::__construct();
}
public function index ()
{
$this->load->library('migration');
if (! $this->migration->current()) {
show_error($this->migration->error_string());
}
else {
echo 'Migration worked!';
}
}
}
It echoes in my browser Migration worked, but it doesn't show anything on
my database. Run Mysql Command lines because I can't go to phpMyAdmin in
CI for some reason.
I'm noob to LAMP (more familiar with rails stack)
no trace of it in the db
I'm running CI on vagrant and when I run the code in my controller
<?php
class Migration extends Admin_Controller
{
public function __construct ()
{
parent::__construct();
}
public function index ()
{
$this->load->library('migration');
if (! $this->migration->current()) {
show_error($this->migration->error_string());
}
else {
echo 'Migration worked!';
}
}
}
It echoes in my browser Migration worked, but it doesn't show anything on
my database. Run Mysql Command lines because I can't go to phpMyAdmin in
CI for some reason.
I'm noob to LAMP (more familiar with rails stack)
parse byte count in ftp log
parse byte count in ftp log
I'm running on an arm architecture. Should be a bash script. I would like
to graph total bytes coming and out of my ftp server.
I parse the ftp.log file with this command to get this output:
`cat ftp.log | grep loaded`
the interesting lines are in this format:
Sep 14 18:46:00 sharecenter pure-ftpd: (doc@omega) [NOTICE]
/mnt/HD/HD_a2//SAVE/backupffp.sh downloaded (423 bytes, 0.78KB/sec) Sep 15
22:06:47 sharecenter pure-ftpd: (doc@omega) [NOTICE]
/mnt/HD/HD_a2//SAVE/ffp-2013-09-14.tar.bz2 downloaded (904753213 bytes,
1928.17KB/sec) Sep 15 22:32:26 sharecenter pure-ftpd: (doc@omega) [NOTICE]
/mnt/HD/HD_a2//SAVE/test.avi uploaded (576711530 bytes, 1465.80KB/sec)
Now I need to get the values after the "(" and before the word "bytes" and
add them.
Example:
--> downloaded 423+904753213=904753636 => returned value: 904753636
--> uploaded 576711530 => returned value: 576711530
Now the script will run every 5 minutes, so the result has to take into
account only the numbers between the last 5 minutes. Example: At 22:05
script runs and adds all bytes. When script runs again at 22:10 only the
transfered bytes between 22:05 to 22:10 should be added.
For rrd you need a simple output, 2 variables "dowloaded" and "uploaded".
So I will need those 2 values in those 2 variables.
I hope I am clear enough, if not don't hesitate to ask for more information.
Many thanks for your help.
I'm running on an arm architecture. Should be a bash script. I would like
to graph total bytes coming and out of my ftp server.
I parse the ftp.log file with this command to get this output:
`cat ftp.log | grep loaded`
the interesting lines are in this format:
Sep 14 18:46:00 sharecenter pure-ftpd: (doc@omega) [NOTICE]
/mnt/HD/HD_a2//SAVE/backupffp.sh downloaded (423 bytes, 0.78KB/sec) Sep 15
22:06:47 sharecenter pure-ftpd: (doc@omega) [NOTICE]
/mnt/HD/HD_a2//SAVE/ffp-2013-09-14.tar.bz2 downloaded (904753213 bytes,
1928.17KB/sec) Sep 15 22:32:26 sharecenter pure-ftpd: (doc@omega) [NOTICE]
/mnt/HD/HD_a2//SAVE/test.avi uploaded (576711530 bytes, 1465.80KB/sec)
Now I need to get the values after the "(" and before the word "bytes" and
add them.
Example:
--> downloaded 423+904753213=904753636 => returned value: 904753636
--> uploaded 576711530 => returned value: 576711530
Now the script will run every 5 minutes, so the result has to take into
account only the numbers between the last 5 minutes. Example: At 22:05
script runs and adds all bytes. When script runs again at 22:10 only the
transfered bytes between 22:05 to 22:10 should be added.
For rrd you need a simple output, 2 variables "dowloaded" and "uploaded".
So I will need those 2 values in those 2 variables.
I hope I am clear enough, if not don't hesitate to ask for more information.
Many thanks for your help.
CUDA: Non-multiple block sizes
CUDA: Non-multiple block sizes
I'm trying to familiarize myself with CUDA programming, and having a
pretty fun time of it. I'm currently looking at this pdf which deals with
matrix multiplication, done with and without shared memory. Full code for
both versions can be found here. This code is almost the exact same as
what's in the CUDA matrix multiplication samples. Although the non-shared
memory version has the capability to run at any matrix size, regardless of
block size, the shared memory version must work with matrices that are a
multiple of the block size (which I set to 4, default was originally 16).
One of the problems suggested at the end of the pdf is to change it so
that the shared memory version can also work with non-multiples of the
block size. I thought this would be a simple index check, like in the
non-shared version:
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if(row > A.height || col > B.width) return;
But this doesn't work. Here's the full code, minus the main method (a bit
of a mess, sorry), which has been modified somewhat by me:
void MatMul(const Matrix A, const Matrix B, Matrix C) {
// Load A and B to device memory
Matrix d_A;
d_A.width = d_A.stride = A.width;
d_A.height = A.height;
size_t size = A.width * A.height * sizeof(float);
cudaError_t err = cudaMalloc(&d_A.elements, size);
printf("CUDA malloc A: %s\n",cudaGetErrorString(err));
err = cudaMemcpy(d_A.elements, A.elements, size, cudaMemcpyHostToDevice);
printf("Copy A to device: %s\n",cudaGetErrorString(err));
Matrix d_B;
d_B.width = d_B.stride = B.width;
d_B.height = B.height;
size = B.width * B.height * sizeof(float);
err = cudaMalloc(&d_B.elements, size);
printf("CUDA malloc B: %s\n",cudaGetErrorString(err));
err = cudaMemcpy(d_B.elements, B.elements, size, cudaMemcpyHostToDevice);
printf("Copy B to device: %s\n",cudaGetErrorString(err));
Matrix d_C;
d_C.width = d_C.stride = C.width;
d_C.height = C.height;
size = C.width * C.height * sizeof(float);
err = cudaMalloc(&d_C.elements, size);
printf("CUDA malloc C: %s\n",cudaGetErrorString(err));
dim3 dimBlock(BLOCK_SIZE, BLOCK_SIZE);
dim3 dimGrid((B.width + dimBlock.x - 1) / dimBlock.x, (A.height +
dimBlock.y-1) / dimBlock.y);
MatMulKernel<<<dimGrid, dimBlock>>>(d_A, d_B, d_C);
err = cudaThreadSynchronize();
printf("Run kernel: %s\n", cudaGetErrorString(err));
// Read C from device memory
err = cudaMemcpy(C.elements, d_C.elements, size, cudaMemcpyDeviceToHost);
printf("Copy C off of device: %s\n",cudaGetErrorString(err));
// Free device memory
cudaFree(d_A.elements);
cudaFree(d_B.elements);
cudaFree(d_C.elements);
}
// Get a matrix element
__device__ float GetElement(const Matrix A, int row, int col) {
return A.elements[row * A.stride + col];
}
// Set a matrix element
__device__ void SetElement(Matrix A, int row, int col, float value) {
A.elements[row * A.stride + col] = value;
}
// Get the BLOCK_SIZExBLOCK_SIZE sub-matrix Asub of A that is
// located col sub-matrices to the right and row sub-matrices down
// from the upper-left corner of A
__device__ Matrix GetSubMatrix(Matrix A, int row, int col) {
Matrix Asub;
Asub.width = BLOCK_SIZE;
Asub.height = BLOCK_SIZE;
Asub.stride = A.stride;
Asub.elements = &A.elements[A.stride * BLOCK_SIZE * row + BLOCK_SIZE *
col];
return Asub;
}
// Matrix multiplication kernel called by MatMul()
__global__ void MatMulKernel(Matrix A, Matrix B, Matrix C) {
// Block row and column
int blockRow = blockIdx.y;
int blockCol = blockIdx.x;
int rowTest = blockIdx.y * blockDim.y + threadIdx.y;
int colTest = blockIdx.x * blockDim.x + threadIdx.x;
if (rowTest>A.height || colTest>B.width)
return;
// Each thread block computes one sub-matrix Csub of C
Matrix Csub = GetSubMatrix(C, blockRow, blockCol);
// Each thread computes one element of Csub
// by accumulating results into Cvalue
float Cvalue = 0.0;
// Thread row and column within Csub
int row = threadIdx.y;
int col = threadIdx.x;
// Loop over all the sub-matrices of A and B that are
// required to compute Csub
// Multiply each pair of sub-matrices together
// and accumulate the results
for (int m = 0; m < (BLOCK_SIZE + A.width - 1)/BLOCK_SIZE; ++m) {
// Get sub-matrix Asub of A
Matrix Asub = GetSubMatrix(A, blockRow, m);
// Get sub-matrix Bsub of B
Matrix Bsub = GetSubMatrix(B, m, blockCol);
// Shared memory used to store Asub and Bsub respectively
__shared__ float As[BLOCK_SIZE][BLOCK_SIZE];
__shared__ float Bs[BLOCK_SIZE][BLOCK_SIZE];
// Load Asub and Bsub from device memory to shared memory
// Each thread loads one element of each sub-matrix
As[row][col] = GetElement(Asub, row, col);
Bs[row][col] = GetElement(Bsub, row, col);
// Synchronize to make sure the sub-matrices are loaded
// before starting the computation
__syncthreads();
// Multiply Asub and Bsub together
for (int e = 0; e < BLOCK_SIZE; ++e)
{
Cvalue += As[row][e] * Bs[e][col];
}
// Synchronize to make sure that the preceding
// computation is done before loading two new
// sub-matrices of A and B in the next iteration
__syncthreads();
}
// Write Csub to device memory
// Each thread writes one element
SetElement(Csub, row, col, Cvalue);
}
notable things which I changed: I added a check in MatMulKernel that
checks if our current thread is trying to work on a spot in C that doesn't
exist. This doesn't seem to work. Although it does change the result, the
changes don't seem to have any pattern other than that later (higher x or
y value) entries seem to be more affected (and I get a lot more
non-integer results). I also changed the given dimGrid calculation method
and the loop condition for m in MatMulKernel(before it was just width or
height divided by block size, which seemed wrong).
Even the solutions guide that I found for this guide seems to suggest it
should just be a simple index check, so I think I'm missing something
really fundamental.
I'm trying to familiarize myself with CUDA programming, and having a
pretty fun time of it. I'm currently looking at this pdf which deals with
matrix multiplication, done with and without shared memory. Full code for
both versions can be found here. This code is almost the exact same as
what's in the CUDA matrix multiplication samples. Although the non-shared
memory version has the capability to run at any matrix size, regardless of
block size, the shared memory version must work with matrices that are a
multiple of the block size (which I set to 4, default was originally 16).
One of the problems suggested at the end of the pdf is to change it so
that the shared memory version can also work with non-multiples of the
block size. I thought this would be a simple index check, like in the
non-shared version:
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if(row > A.height || col > B.width) return;
But this doesn't work. Here's the full code, minus the main method (a bit
of a mess, sorry), which has been modified somewhat by me:
void MatMul(const Matrix A, const Matrix B, Matrix C) {
// Load A and B to device memory
Matrix d_A;
d_A.width = d_A.stride = A.width;
d_A.height = A.height;
size_t size = A.width * A.height * sizeof(float);
cudaError_t err = cudaMalloc(&d_A.elements, size);
printf("CUDA malloc A: %s\n",cudaGetErrorString(err));
err = cudaMemcpy(d_A.elements, A.elements, size, cudaMemcpyHostToDevice);
printf("Copy A to device: %s\n",cudaGetErrorString(err));
Matrix d_B;
d_B.width = d_B.stride = B.width;
d_B.height = B.height;
size = B.width * B.height * sizeof(float);
err = cudaMalloc(&d_B.elements, size);
printf("CUDA malloc B: %s\n",cudaGetErrorString(err));
err = cudaMemcpy(d_B.elements, B.elements, size, cudaMemcpyHostToDevice);
printf("Copy B to device: %s\n",cudaGetErrorString(err));
Matrix d_C;
d_C.width = d_C.stride = C.width;
d_C.height = C.height;
size = C.width * C.height * sizeof(float);
err = cudaMalloc(&d_C.elements, size);
printf("CUDA malloc C: %s\n",cudaGetErrorString(err));
dim3 dimBlock(BLOCK_SIZE, BLOCK_SIZE);
dim3 dimGrid((B.width + dimBlock.x - 1) / dimBlock.x, (A.height +
dimBlock.y-1) / dimBlock.y);
MatMulKernel<<<dimGrid, dimBlock>>>(d_A, d_B, d_C);
err = cudaThreadSynchronize();
printf("Run kernel: %s\n", cudaGetErrorString(err));
// Read C from device memory
err = cudaMemcpy(C.elements, d_C.elements, size, cudaMemcpyDeviceToHost);
printf("Copy C off of device: %s\n",cudaGetErrorString(err));
// Free device memory
cudaFree(d_A.elements);
cudaFree(d_B.elements);
cudaFree(d_C.elements);
}
// Get a matrix element
__device__ float GetElement(const Matrix A, int row, int col) {
return A.elements[row * A.stride + col];
}
// Set a matrix element
__device__ void SetElement(Matrix A, int row, int col, float value) {
A.elements[row * A.stride + col] = value;
}
// Get the BLOCK_SIZExBLOCK_SIZE sub-matrix Asub of A that is
// located col sub-matrices to the right and row sub-matrices down
// from the upper-left corner of A
__device__ Matrix GetSubMatrix(Matrix A, int row, int col) {
Matrix Asub;
Asub.width = BLOCK_SIZE;
Asub.height = BLOCK_SIZE;
Asub.stride = A.stride;
Asub.elements = &A.elements[A.stride * BLOCK_SIZE * row + BLOCK_SIZE *
col];
return Asub;
}
// Matrix multiplication kernel called by MatMul()
__global__ void MatMulKernel(Matrix A, Matrix B, Matrix C) {
// Block row and column
int blockRow = blockIdx.y;
int blockCol = blockIdx.x;
int rowTest = blockIdx.y * blockDim.y + threadIdx.y;
int colTest = blockIdx.x * blockDim.x + threadIdx.x;
if (rowTest>A.height || colTest>B.width)
return;
// Each thread block computes one sub-matrix Csub of C
Matrix Csub = GetSubMatrix(C, blockRow, blockCol);
// Each thread computes one element of Csub
// by accumulating results into Cvalue
float Cvalue = 0.0;
// Thread row and column within Csub
int row = threadIdx.y;
int col = threadIdx.x;
// Loop over all the sub-matrices of A and B that are
// required to compute Csub
// Multiply each pair of sub-matrices together
// and accumulate the results
for (int m = 0; m < (BLOCK_SIZE + A.width - 1)/BLOCK_SIZE; ++m) {
// Get sub-matrix Asub of A
Matrix Asub = GetSubMatrix(A, blockRow, m);
// Get sub-matrix Bsub of B
Matrix Bsub = GetSubMatrix(B, m, blockCol);
// Shared memory used to store Asub and Bsub respectively
__shared__ float As[BLOCK_SIZE][BLOCK_SIZE];
__shared__ float Bs[BLOCK_SIZE][BLOCK_SIZE];
// Load Asub and Bsub from device memory to shared memory
// Each thread loads one element of each sub-matrix
As[row][col] = GetElement(Asub, row, col);
Bs[row][col] = GetElement(Bsub, row, col);
// Synchronize to make sure the sub-matrices are loaded
// before starting the computation
__syncthreads();
// Multiply Asub and Bsub together
for (int e = 0; e < BLOCK_SIZE; ++e)
{
Cvalue += As[row][e] * Bs[e][col];
}
// Synchronize to make sure that the preceding
// computation is done before loading two new
// sub-matrices of A and B in the next iteration
__syncthreads();
}
// Write Csub to device memory
// Each thread writes one element
SetElement(Csub, row, col, Cvalue);
}
notable things which I changed: I added a check in MatMulKernel that
checks if our current thread is trying to work on a spot in C that doesn't
exist. This doesn't seem to work. Although it does change the result, the
changes don't seem to have any pattern other than that later (higher x or
y value) entries seem to be more affected (and I get a lot more
non-integer results). I also changed the given dimGrid calculation method
and the loop condition for m in MatMulKernel(before it was just width or
height divided by block size, which seemed wrong).
Even the solutions guide that I found for this guide seems to suggest it
should just be a simple index check, so I think I'm missing something
really fundamental.
Multi Level Responsive Menu ... Transiction between mobile and non mobile
Multi Level Responsive Menu ... Transiction between mobile and non mobile
I created a multilevel responsive menu: http://codepen.io/mdmoura/pen/FrIbq
1 - By placing the mouse over "content" item a sub menu will appear;
2 - When resizing the menu to mobile size a Menu link will appear and the
menu disappears.
So far so good ... What is missing is:
A - When clicking in Menu link the menu should become visible or invisible;
B - When one of the submenus is clicked then its child ul should become
visible or invisible.
Of course (A) and (B) should be only mobile version, so width less than
800px.
I tried to solve it using enquire.js: http://codepen.io/mdmoura/pen/alxkI.
So I have:
$('nav a[href="#"]').click(function (event) {
event.preventDefault();
});
enquire.register("screen and (max-width: 800px)", {
match: function () {
$('nav a[href="#"]').on('click.match', function () {
$(this).next('ul').toggle();
})
},
unmatch: function () {
$('nav a[href="#"]').off('click.match');
}
});
But I get problems when resizing from Mobile version and not Mobile
version ...
Could someone help me out? Using Enquire or not ...
Thank You, Miguel
I created a multilevel responsive menu: http://codepen.io/mdmoura/pen/FrIbq
1 - By placing the mouse over "content" item a sub menu will appear;
2 - When resizing the menu to mobile size a Menu link will appear and the
menu disappears.
So far so good ... What is missing is:
A - When clicking in Menu link the menu should become visible or invisible;
B - When one of the submenus is clicked then its child ul should become
visible or invisible.
Of course (A) and (B) should be only mobile version, so width less than
800px.
I tried to solve it using enquire.js: http://codepen.io/mdmoura/pen/alxkI.
So I have:
$('nav a[href="#"]').click(function (event) {
event.preventDefault();
});
enquire.register("screen and (max-width: 800px)", {
match: function () {
$('nav a[href="#"]').on('click.match', function () {
$(this).next('ul').toggle();
})
},
unmatch: function () {
$('nav a[href="#"]').off('click.match');
}
});
But I get problems when resizing from Mobile version and not Mobile
version ...
Could someone help me out? Using Enquire or not ...
Thank You, Miguel
/proc/mtprof/status: open failed: ENOENT (No such file or directory)
/proc/mtprof/status: open failed: ENOENT (No such file or directory)
I am getting following exception when apps lunch but not crash
LOG::
09-15 17:23:03.504: E/KeyguardUpdateMonitor(236): Object tried to add
another INFO callback 09-15 17:23:03.543: E/AudioYusuHardware(103):
setParameters still have param.size() = 1 09-15 17:23:03.556:
E/WifiStateMachine(236): set suspend optimizations failed! 09-15
17:23:07.368: E/ActivityManager(236): mtprof entry can not found! 09-15
17:23:07.368: E/ActivityManager(236): java.io.FileNotFoundException:
/proc/mtprof/status: open failed: ENOENT (No such file or directory) 09-15
17:23:07.368: E/ActivityManager(236): at
libcore.io.IoBridge.open(IoBridge.java:448) 09-15 17:23:07.368:
E/ActivityManager(236): at
java.io.FileInputStream.(FileInputStream.java:78) 09-15 17:23:07.368:
E/ActivityManager(236): at
java.io.FileInputStream.(FileInputStream.java:105) 09-15 17:23:07.368:
E/ActivityManager(236): at
com.android.server.am.ActivityRecord.mtProf(ActivityRecord.java:852) 09-15
17:23:07.368: E/ActivityManager(236): at
com.android.server.am.ActivityRecord.windowsDrawn(ActivityRecord.java:653)
09-15 17:23:07.368: E/ActivityManager(236): at
com.android.server.am.ActivityRecord$Token.windowsDrawn(ActivityRecord.java:225)
09-15 17:23:07.368: E/ActivityManager(236): at
com.android.server.wm.WindowManagerService$H.handleMessage(WindowManagerService.java:7054)
09-15 17:23:07.368: E/ActivityManager(236): at
android.os.Handler.dispatchMessage(Handler.java:99) 09-15 17:23:07.368:
E/ActivityManager(236): at android.os.Looper.loop(Looper.java:154) 09-15
17:23:07.368: E/ActivityManager(236): at
com.android.server.wm.WindowManagerService$WMThread.run(WindowManagerService.java:756)
09-15 17:23:07.368: E/ActivityManager(236): Caused by:
libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
09-15 17:23:07.368: E/ActivityManager(236): at
libcore.io.Posix.open(Native Method) 09-15 17:23:07.368:
E/ActivityManager(236): at
libcore.io.BlockGuardOs.open(BlockGuardOs.java:110) 09-15 17:23:07.368:
E/ActivityManager(236): at libcore.io.IoBridge.open(IoBridge.java:432)
09-15 17:23:07.368: E/ActivityManager(236): ... 9 more
I am getting following exception when apps lunch but not crash
LOG::
09-15 17:23:03.504: E/KeyguardUpdateMonitor(236): Object tried to add
another INFO callback 09-15 17:23:03.543: E/AudioYusuHardware(103):
setParameters still have param.size() = 1 09-15 17:23:03.556:
E/WifiStateMachine(236): set suspend optimizations failed! 09-15
17:23:07.368: E/ActivityManager(236): mtprof entry can not found! 09-15
17:23:07.368: E/ActivityManager(236): java.io.FileNotFoundException:
/proc/mtprof/status: open failed: ENOENT (No such file or directory) 09-15
17:23:07.368: E/ActivityManager(236): at
libcore.io.IoBridge.open(IoBridge.java:448) 09-15 17:23:07.368:
E/ActivityManager(236): at
java.io.FileInputStream.(FileInputStream.java:78) 09-15 17:23:07.368:
E/ActivityManager(236): at
java.io.FileInputStream.(FileInputStream.java:105) 09-15 17:23:07.368:
E/ActivityManager(236): at
com.android.server.am.ActivityRecord.mtProf(ActivityRecord.java:852) 09-15
17:23:07.368: E/ActivityManager(236): at
com.android.server.am.ActivityRecord.windowsDrawn(ActivityRecord.java:653)
09-15 17:23:07.368: E/ActivityManager(236): at
com.android.server.am.ActivityRecord$Token.windowsDrawn(ActivityRecord.java:225)
09-15 17:23:07.368: E/ActivityManager(236): at
com.android.server.wm.WindowManagerService$H.handleMessage(WindowManagerService.java:7054)
09-15 17:23:07.368: E/ActivityManager(236): at
android.os.Handler.dispatchMessage(Handler.java:99) 09-15 17:23:07.368:
E/ActivityManager(236): at android.os.Looper.loop(Looper.java:154) 09-15
17:23:07.368: E/ActivityManager(236): at
com.android.server.wm.WindowManagerService$WMThread.run(WindowManagerService.java:756)
09-15 17:23:07.368: E/ActivityManager(236): Caused by:
libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
09-15 17:23:07.368: E/ActivityManager(236): at
libcore.io.Posix.open(Native Method) 09-15 17:23:07.368:
E/ActivityManager(236): at
libcore.io.BlockGuardOs.open(BlockGuardOs.java:110) 09-15 17:23:07.368:
E/ActivityManager(236): at libcore.io.IoBridge.open(IoBridge.java:432)
09-15 17:23:07.368: E/ActivityManager(236): ... 9 more
Why can't I use type []chan *Message as type []chan interface{} in a function argument?
Why can't I use type []chan *Message as type []chan interface{} in a
function argument?
This is the error message I am getting:
cannot use c.ReceiverChans (type []chan *Message) as type []chan interface
{} in function argument
function argument?
This is the error message I am getting:
cannot use c.ReceiverChans (type []chan *Message) as type []chan interface
{} in function argument
Saturday, 14 September 2013
VB.Net Currency Converter - Is there an easier way?
VB.Net Currency Converter - Is there an easier way?
Just picked programming up as a hobby, and am very bad. I am trying to
build a basic currency converter from the book I have.
My question: Is there is a better way than taking the user input (lets say
5 dollars), convert the text string to a double, multiply by the rate, and
then convert it back to a string in order to display it in the other
textbox? I mainly ask because the textbook hasn't said how to convert
double to string yet, and I found it online but I feel like I'm missing
something.
Thanks
Just picked programming up as a hobby, and am very bad. I am trying to
build a basic currency converter from the book I have.
My question: Is there is a better way than taking the user input (lets say
5 dollars), convert the text string to a double, multiply by the rate, and
then convert it back to a string in order to display it in the other
textbox? I mainly ask because the textbook hasn't said how to convert
double to string yet, and I found it online but I feel like I'm missing
something.
Thanks
How to pass variables to mailto method
How to pass variables to mailto method
I need to know if its possible to pass variables to the mailto: method.
I want to have something along the lines like this, so it opens a new
email on outlook.
var email = "random@random.random"
var subject = "test"
window.href = "mailto:email?subject=subject"
Now i want to know if i can pass these variables. I don't care about the
body of the email I just wanna have the email address and the subject line
passed in. I can't ActiveXObject because my code is on the server side
rather then the client side so it wont have permission to create objects.
Or at least thats what i got from reading into opening outlook from
javascripts.
I need to know if its possible to pass variables to the mailto: method.
I want to have something along the lines like this, so it opens a new
email on outlook.
var email = "random@random.random"
var subject = "test"
window.href = "mailto:email?subject=subject"
Now i want to know if i can pass these variables. I don't care about the
body of the email I just wanna have the email address and the subject line
passed in. I can't ActiveXObject because my code is on the server side
rather then the client side so it wont have permission to create objects.
Or at least thats what i got from reading into opening outlook from
javascripts.
Issue with Main Page Navigation not Updating after pointing site to directory
Issue with Main Page Navigation not Updating after pointing site to directory
I've built a site for a client using a one-page WordPress theme:
motorarzt.com
The main navigation on the home page uses Anchors to scroll to the
different pages.
I put WordPress in a directory /ma/ and then updated the index.php file
and the htacess file as normal. On the main home page the URLS are working
fine - and also working fine on the sidebar.
The problem is when I go to a single page with this theme, the main
navigation URLs are still showing the directory. Here's an example:
motorarzt.com/services/
The links should be http://motorarzt.com/#services NOT
http://motorarzt.com/ma#services
Really hoping someone here can help me out...wondering if this is an issue
with how the theme is developed and how i may tweak/fix it.
thanks! Lisa
I've built a site for a client using a one-page WordPress theme:
motorarzt.com
The main navigation on the home page uses Anchors to scroll to the
different pages.
I put WordPress in a directory /ma/ and then updated the index.php file
and the htacess file as normal. On the main home page the URLS are working
fine - and also working fine on the sidebar.
The problem is when I go to a single page with this theme, the main
navigation URLs are still showing the directory. Here's an example:
motorarzt.com/services/
The links should be http://motorarzt.com/#services NOT
http://motorarzt.com/ma#services
Really hoping someone here can help me out...wondering if this is an issue
with how the theme is developed and how i may tweak/fix it.
thanks! Lisa
Setting default values to null fields when mapping with Jackson
Setting default values to null fields when mapping with Jackson
I am trying to map some JSON objects to Java objects with Jackson. Some of
the fields in the JSON object are mandatory(which I can mark with
@NotNull) and some are optional.
After the mapping with Jackson, all the fields that are not set in the
JSON object will have a null value in Java. Is there a similar annotation
to @NotNull that can tell Jackson to set a default value to a Java class
member, in case it is null?
I am trying to map some JSON objects to Java objects with Jackson. Some of
the fields in the JSON object are mandatory(which I can mark with
@NotNull) and some are optional.
After the mapping with Jackson, all the fields that are not set in the
JSON object will have a null value in Java. Is there a similar annotation
to @NotNull that can tell Jackson to set a default value to a Java class
member, in case it is null?
After installing bootstrap
After installing bootstrap
After installed bootstrap and less rails , when using "btn btn-primary"
class to _form create button , Its showing like --- same button as
previous plus getting green around that button . I mean to say that half
property from previous and half from bootstrap . How can i get rid of that
. Sorry for my bad english
After installed bootstrap and less rails , when using "btn btn-primary"
class to _form create button , Its showing like --- same button as
previous plus getting green around that button . I mean to say that half
property from previous and half from bootstrap . How can i get rid of that
. Sorry for my bad english
my micromax A26 is not shown in eclipse(Android) device chooser but shown in device manager
my micromax A26 is not shown in eclipse(Android) device chooser but shown
in device manager
I am developing my own android application and want to usb debug with my
micromax a26 device,but can't able to detect in eclipse(Android).
in device manager
I am developing my own android application and want to usb debug with my
micromax a26 device,but can't able to detect in eclipse(Android).
Control the default music player of android or any other music player
Control the default music player of android or any other music player
How to control the default music player of android or any other player? By
controlling i mean pause, play, next etc. Do i have to bind the service? I
have tried to use the IMediaPlaybackService but it is not working. There
is certainly a way out as i have seen apps in the android market which
controls the music player. Any idea?
How to control the default music player of android or any other player? By
controlling i mean pause, play, next etc. Do i have to bind the service? I
have tried to use the IMediaPlaybackService but it is not working. There
is certainly a way out as i have seen apps in the android market which
controls the music player. Any idea?
Friday, 13 September 2013
Fade from normal text to italics text smoothly?
Fade from normal text to italics text smoothly?
Is there a way to make it so when my user hovers over normal text that is
an anchor, the text smoothly transitions into oblique or italicized text
to show it is a link (including an underline)
Here's an example of what I'm trying to do...
<a href="http://oldsite.com>
<p class="footertext">Take me to the old site...</p>
</a>
p.footertext {
font-size:12px;
padding-left:4px;
text-decoration:none; }
p.footertext:hover {
/*text:decoration: "italicize smoothly"*/ }
Is there a way to make it so when my user hovers over normal text that is
an anchor, the text smoothly transitions into oblique or italicized text
to show it is a link (including an underline)
Here's an example of what I'm trying to do...
<a href="http://oldsite.com>
<p class="footertext">Take me to the old site...</p>
</a>
p.footertext {
font-size:12px;
padding-left:4px;
text-decoration:none; }
p.footertext:hover {
/*text:decoration: "italicize smoothly"*/ }
Create a bean and autowire it
Create a bean and autowire it
I currently have numerous classes with a field like
private MyStuff myStuff = new MyStuff();
It would be preferable if there was a MyStuff singleton which all the
classes used. Our project has a MyConfiguration class with some Beans in
it, but they don't seem to get used, at least not directly, so I can't use
them for examples. I have been tasked to create a MyStuff bean in the
MyConfiguration class, and then inject it into my other classes.
What I have so far:
@Configuration
public class MyConfiguration
{
@Bean
public MyStuff myStuff()
{
return new MyStuff();
}
}
public SomeClass
{
public void dealWithStuff()
{
myStuff.myMethod();
}
@Autowired
private MyStuff someStuff;
}
This does not compile. The compiler says "variable someStuff may not have
been initialized". Apparently it does not see the bean or make the
connection. What am I missing?
I currently have numerous classes with a field like
private MyStuff myStuff = new MyStuff();
It would be preferable if there was a MyStuff singleton which all the
classes used. Our project has a MyConfiguration class with some Beans in
it, but they don't seem to get used, at least not directly, so I can't use
them for examples. I have been tasked to create a MyStuff bean in the
MyConfiguration class, and then inject it into my other classes.
What I have so far:
@Configuration
public class MyConfiguration
{
@Bean
public MyStuff myStuff()
{
return new MyStuff();
}
}
public SomeClass
{
public void dealWithStuff()
{
myStuff.myMethod();
}
@Autowired
private MyStuff someStuff;
}
This does not compile. The compiler says "variable someStuff may not have
been initialized". Apparently it does not see the bean or make the
connection. What am I missing?
Strange error when trying to run executable:
Strange error when trying to run executable:
I have written a program for class. The program compiles with no warnings
or errors, but when I try to run the executable, I receive a prompt that
says: "Usage: lab.exe " I've never seen anything like this and I can't
debug it because the executable doesn't run.
The project is an OpenGL project written in C++ using a sort of homebrew
of OpenGL libraries. Any ideas?
I have written a program for class. The program compiles with no warnings
or errors, but when I try to run the executable, I receive a prompt that
says: "Usage: lab.exe " I've never seen anything like this and I can't
debug it because the executable doesn't run.
The project is an OpenGL project written in C++ using a sort of homebrew
of OpenGL libraries. Any ideas?
page wrapper with max-width breaks layout on zoom in
page wrapper with max-width breaks layout on zoom in
I have all my pages in one main div called "wrapper", and it is set to
max-width: 1000px, which I need in order to make my site responsive.
The problem is, if I zoom in the layout breaks because of the max-width
property. If i just set it to width instead of max-width it doesn't break
(which makes sense), but I simply want to know if there is a solution for
this ?
So, can I have max-width on the #wrapper without breaking the layout on
zoom in?
I have all my pages in one main div called "wrapper", and it is set to
max-width: 1000px, which I need in order to make my site responsive.
The problem is, if I zoom in the layout breaks because of the max-width
property. If i just set it to width instead of max-width it doesn't break
(which makes sense), but I simply want to know if there is a solution for
this ?
So, can I have max-width on the #wrapper without breaking the layout on
zoom in?
How many combinations can chmod in linux have?
How many combinations can chmod in linux have?
I know there's 0,1,5,6 and 7 for each category of user
e.g. 755, 644, 600 etc
how many combinations can we have?
also, there's this u+755... what is this about really?
I know there's 0,1,5,6 and 7 for each category of user
e.g. 755, 644, 600 etc
how many combinations can we have?
also, there's this u+755... what is this about really?
Video-js custom skinning
Video-js custom skinning
I am using the 'less2css' css editor for customising video-js. to save a
custom skin, it states 'replace all instances of 'vjs-default-skin'with
new name..
to be clear, I have to change EVERY instance of that name that i find
ANYWHERE within the css file?
there is no shortcut to do this within 'less2css' "
thanks,
keith.
I am using the 'less2css' css editor for customising video-js. to save a
custom skin, it states 'replace all instances of 'vjs-default-skin'with
new name..
to be clear, I have to change EVERY instance of that name that i find
ANYWHERE within the css file?
there is no shortcut to do this within 'less2css' "
thanks,
keith.
Java - Openjpa: how to specify sequence generator starting from hibernate hbm
Java - Openjpa: how to specify sequence generator starting from hibernate hbm
I've to switch persistence of a project using HIBERNATE to OPENJPA and I
started from entities and hbm files which define type of columns, etc.
I've an Id on hibernate generated in that way:
<id name="id" type="java.lang.Integer">
<column name="id"/>
<generator class="sequence">
<param name="sequence">seq_illness</param>
</generator>
</id>
how can I "translate" it ointo Jpa annotation to my entity class, in
particular how can I represent sequence generator? I'm new to this feature
and I don't understand well usage of
@GeneratedValue(strategy = GenerationType.SEQUENCE)
how can I reproduce sequence parameter and define the correct sequence
generator?
I've to switch persistence of a project using HIBERNATE to OPENJPA and I
started from entities and hbm files which define type of columns, etc.
I've an Id on hibernate generated in that way:
<id name="id" type="java.lang.Integer">
<column name="id"/>
<generator class="sequence">
<param name="sequence">seq_illness</param>
</generator>
</id>
how can I "translate" it ointo Jpa annotation to my entity class, in
particular how can I represent sequence generator? I'm new to this feature
and I don't understand well usage of
@GeneratedValue(strategy = GenerationType.SEQUENCE)
how can I reproduce sequence parameter and define the correct sequence
generator?
Thursday, 12 September 2013
string index out of bound exception while carrying search operation
string index out of bound exception while carrying search operation
when I am carrying out a search operation after fetching the contacts,it
shows this exception when I type the letters very fast in the search bar
and the application crashes.Could you please help me out to resolve this
issue.I am including the portion of the code also along
@Override
public boolean onQueryTextChange(String newtext) {
String searchString = newtext;
int textLength = searchString.length();
ArrayList<Masterlistmodel> type_name_filter = new
ArrayList<Masterlistmodel>();
/* String text = edtField.getText().toString(); */
for (int i = 0; i <masterarr.size(); i++) {
String Name = masterarr.get(i).getName();
if (searchString.equalsIgnoreCase(Name.substring(0,
textLength))) {
type_name_filter.add(masterarr.get(i));
}
}
type_name_copy = type_name_filter;
listUpdate(type_name_copy);
return true;
}
@Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}
when I am carrying out a search operation after fetching the contacts,it
shows this exception when I type the letters very fast in the search bar
and the application crashes.Could you please help me out to resolve this
issue.I am including the portion of the code also along
@Override
public boolean onQueryTextChange(String newtext) {
String searchString = newtext;
int textLength = searchString.length();
ArrayList<Masterlistmodel> type_name_filter = new
ArrayList<Masterlistmodel>();
/* String text = edtField.getText().toString(); */
for (int i = 0; i <masterarr.size(); i++) {
String Name = masterarr.get(i).getName();
if (searchString.equalsIgnoreCase(Name.substring(0,
textLength))) {
type_name_filter.add(masterarr.get(i));
}
}
type_name_copy = type_name_filter;
listUpdate(type_name_copy);
return true;
}
@Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}
Insert multiple rows in sql
Insert multiple rows in sql
Can someone tell me why this query is wrong?
$tbl_name = "Attributes";
$pieces = //some array
//other variables... blah blah blah
$query = "INSERT INTO $tbl_name (Word, What, When) VALUES";
foreach($pieces as $word){
$query .= "('$word', '$What', '$When'),";
}
$query = substr($query, 0, -1); //to remove the last comma
mysql_query($query) or die(mysql_error());
If you can tell, I am trying to insert multiple rows with a single query.
When I try and run it, I get hit with a syntax error, but I am 99.9999%
sure there are no spelling mistakes. Am I doing something wrong by trying
to insert multiple rows at once like this?
Can someone tell me why this query is wrong?
$tbl_name = "Attributes";
$pieces = //some array
//other variables... blah blah blah
$query = "INSERT INTO $tbl_name (Word, What, When) VALUES";
foreach($pieces as $word){
$query .= "('$word', '$What', '$When'),";
}
$query = substr($query, 0, -1); //to remove the last comma
mysql_query($query) or die(mysql_error());
If you can tell, I am trying to insert multiple rows with a single query.
When I try and run it, I get hit with a syntax error, but I am 99.9999%
sure there are no spelling mistakes. Am I doing something wrong by trying
to insert multiple rows at once like this?
AngularJs pagination on grouping elements
AngularJs pagination on grouping elements
I'm trying to paginate over a grouped list, but I have the error of
circular dependencies.
I'm new about angular, got this code from other answer on SO here, but
cannot paginate it.
This is a fiddle: http://jsfiddle.net/Tropicalista/qyb6N/1/
angular.module('test', ['ui.bootstrap']);
function Main($scope, $q) {
$scope.players = [//my data]
// create a deferred object to be resolved later
var teamsDeferred = $q.defer();
// return a promise. The promise says, "I promise that I'll give you your
// data as soon as I have it (which is when I am resolved)".
$scope.teams = teamsDeferred.promise;
// create a list of unique teams
var uniqueTeams = unique($scope.players, 'team');
// resolve the deferred object with the unique teams
// this will trigger an update on the view
teamsDeferred.resolve(uniqueTeams);
// function that takes an array of objects
// and returns an array of unique valued in the object
// array for a given key.
// this really belongs in a service, not the global window scope
function unique(data, key) {
var result = [];
for (var i = 0; i < data.length; i++) {
var value = data[i][key];
if (result.indexOf(value) == -1) {
result.push(value);
}
}
$scope.noOfPages = Math.ceil(result.length / 10);
return result;
}
$scope.currentPage = 1;
$scope.pageSize = 5;
$scope.maxSize = 2;
}
angular.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
I'm trying to paginate over a grouped list, but I have the error of
circular dependencies.
I'm new about angular, got this code from other answer on SO here, but
cannot paginate it.
This is a fiddle: http://jsfiddle.net/Tropicalista/qyb6N/1/
angular.module('test', ['ui.bootstrap']);
function Main($scope, $q) {
$scope.players = [//my data]
// create a deferred object to be resolved later
var teamsDeferred = $q.defer();
// return a promise. The promise says, "I promise that I'll give you your
// data as soon as I have it (which is when I am resolved)".
$scope.teams = teamsDeferred.promise;
// create a list of unique teams
var uniqueTeams = unique($scope.players, 'team');
// resolve the deferred object with the unique teams
// this will trigger an update on the view
teamsDeferred.resolve(uniqueTeams);
// function that takes an array of objects
// and returns an array of unique valued in the object
// array for a given key.
// this really belongs in a service, not the global window scope
function unique(data, key) {
var result = [];
for (var i = 0; i < data.length; i++) {
var value = data[i][key];
if (result.indexOf(value) == -1) {
result.push(value);
}
}
$scope.noOfPages = Math.ceil(result.length / 10);
return result;
}
$scope.currentPage = 1;
$scope.pageSize = 5;
$scope.maxSize = 2;
}
angular.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
How to show user location on XCode 4.5 simulator - prompt won't appear?
How to show user location on XCode 4.5 simulator - prompt won't appear?
I have an MKMapView in a View Controller for my app and I checked "Shows
User Location" in the Attributes tab of the MKMapView. The first
simulation took awhile to load, as I expected, and the prompt came up
asking whether to show the user location (Don't Allow / Allow). I chose
'Don't Allow' just to test the option first, but now the prompt will not
return and I cannot show user location at all. I searched for an answer
but could not find one. Sorry, I'm still a beginning iOS developer!
Thanks!
I have an MKMapView in a View Controller for my app and I checked "Shows
User Location" in the Attributes tab of the MKMapView. The first
simulation took awhile to load, as I expected, and the prompt came up
asking whether to show the user location (Don't Allow / Allow). I chose
'Don't Allow' just to test the option first, but now the prompt will not
return and I cannot show user location at all. I searched for an answer
but could not find one. Sorry, I'm still a beginning iOS developer!
Thanks!
Auto-complete AWK variable
Auto-complete AWK variable
I want to auto-complete the name of a variable (array), in this way:
array$1[something]++
I'm trying to obtain this:
array1[something]++
or
array53[something]++
In C, I remember I couldn't do that.. but in AWK I don't know, because if
I do:
array'$1'[something]++
it auto-completes the name:
arraySCRIPTPARAMETER[something]++
Any ideas? Am I wrong?? Thanks people!!!!
I want to auto-complete the name of a variable (array), in this way:
array$1[something]++
I'm trying to obtain this:
array1[something]++
or
array53[something]++
In C, I remember I couldn't do that.. but in AWK I don't know, because if
I do:
array'$1'[something]++
it auto-completes the name:
arraySCRIPTPARAMETER[something]++
Any ideas? Am I wrong?? Thanks people!!!!
Map must replicated to Wan but not required to be distributed in Hazelcast. Is this Possible?
Map must replicated to Wan but not required to be distributed in
Hazelcast. Is this Possible?
Using Hazelcast for months now. and following this group since long. I
have an issue in fixing hazelcast for my senario. I have two clusters,
each having two nodes and WAN replication is success-full for many of my
map. I have two maps that does not required to be distributed on the node
of the same cluster, still the data must be replicated on the other
cluster node. ie. one node of one cluster and one node of another cluster
must contain same map.
Have googled and searched lot things about this senario but unfortunately
didnt find any solution. Please let me know such a configuration is
possible or not.
Thanx
Hazelcast. Is this Possible?
Using Hazelcast for months now. and following this group since long. I
have an issue in fixing hazelcast for my senario. I have two clusters,
each having two nodes and WAN replication is success-full for many of my
map. I have two maps that does not required to be distributed on the node
of the same cluster, still the data must be replicated on the other
cluster node. ie. one node of one cluster and one node of another cluster
must contain same map.
Have googled and searched lot things about this senario but unfortunately
didnt find any solution. Please let me know such a configuration is
possible or not.
Thanx
Wednesday, 11 September 2013
Can I use single SetSubclassWindow procedure to subclass multiple edit controls, and if I can, how to do it?
Can I use single SetSubclassWindow procedure to subclass multiple edit
controls, and if I can, how to do it?
Can I use single SetSubclassWindow procedure to subclass multiple edit
controls, and if I can, how to do it?
I want to subclass multiple edit controls with the same subclass procedure.
So far, I did it like this:
SetWindowSubclass( GetDlgItem( hwnd, IDC_EDIT1 ), SomeSubclassProcedure,
0, 0);
SetWindowSubclass( GetDlgItem( hwnd, IDC_EDIT2 ), SomeSubclassProcedure,
0, 0);
Everything works, but I just want to check with more experienced
developers, so I can be sure, since I am a beginner.
Also, I would like to know if I should use RemoveWindowSubclass when I
destroy dialog box that contains edit controls.
I haven't used it in my code, since I pass no data as 4th parameter to the
SetWindowSubclass.
controls, and if I can, how to do it?
Can I use single SetSubclassWindow procedure to subclass multiple edit
controls, and if I can, how to do it?
I want to subclass multiple edit controls with the same subclass procedure.
So far, I did it like this:
SetWindowSubclass( GetDlgItem( hwnd, IDC_EDIT1 ), SomeSubclassProcedure,
0, 0);
SetWindowSubclass( GetDlgItem( hwnd, IDC_EDIT2 ), SomeSubclassProcedure,
0, 0);
Everything works, but I just want to check with more experienced
developers, so I can be sure, since I am a beginner.
Also, I would like to know if I should use RemoveWindowSubclass when I
destroy dialog box that contains edit controls.
I haven't used it in my code, since I pass no data as 4th parameter to the
SetWindowSubclass.
Ejs engine with html not working
Ejs engine with html not working
i'm using html files instead of ejs, but the express engine is ejs
views
|
|--header.html
|--footer.html
|
|--index.html
I configured like
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
I render my index template by this:
res.render('index.html', {title: 'test'});
But how can i include header and footer.html in index.html
Similar posts Node.js express: confuse about ejs template
Existing example which is not working
https://github.com/visionmedia/express/tree/master/examples/ejs
i'm using html files instead of ejs, but the express engine is ejs
views
|
|--header.html
|--footer.html
|
|--index.html
I configured like
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
I render my index template by this:
res.render('index.html', {title: 'test'});
But how can i include header and footer.html in index.html
Similar posts Node.js express: confuse about ejs template
Existing example which is not working
https://github.com/visionmedia/express/tree/master/examples/ejs
Find, Copy & Paste Values under Multiple Columns
Find, Copy & Paste Values under Multiple Columns
Below code is for copying values under "Apple" Column in sheet1 to
"AppleNew" Column in sheet2. (Thanks to Tim)
But If I have multiple columns (Orange, Banana etc) is there way to write
more simpler code that sort of go through the loop instead of having to
copy and paste code for the each columns?
Dim rng as range, rngCopy as range, rng2 as range
set rng = Sheet1.Rows(3).Find(What:="Apple", LookIn:=xlValues,
LookAt:=xlWhole)
if not rng is nothing then
set rngCopy = Sheet1.range(rng.offset(1,0), _
Sheet1.cells(rows.count,rng.column).end(xlUp))
set rng2 = Sheet2.Rows(1).Find(What:="AppleNew", LookIn:=xlValues, _
LookAt:=xlWhole)
if not rng2 is nothing then rngCopy.copy rng2.offset(1,0)
end if
Below code is for copying values under "Apple" Column in sheet1 to
"AppleNew" Column in sheet2. (Thanks to Tim)
But If I have multiple columns (Orange, Banana etc) is there way to write
more simpler code that sort of go through the loop instead of having to
copy and paste code for the each columns?
Dim rng as range, rngCopy as range, rng2 as range
set rng = Sheet1.Rows(3).Find(What:="Apple", LookIn:=xlValues,
LookAt:=xlWhole)
if not rng is nothing then
set rngCopy = Sheet1.range(rng.offset(1,0), _
Sheet1.cells(rows.count,rng.column).end(xlUp))
set rng2 = Sheet2.Rows(1).Find(What:="AppleNew", LookIn:=xlValues, _
LookAt:=xlWhole)
if not rng2 is nothing then rngCopy.copy rng2.offset(1,0)
end if
Unable to Set VISUAL environement variable in bashrc
Unable to Set VISUAL environement variable in bashrc
I am trying to set the VISUAL and EDITOR environment variables in a server
for default usage with crontab.
When I do a manual export VISUAL=vim, things work perfectly.
But when I add the lines
EDITOR=vim
VISUAL=vim
to my .bashrc file and logout and re-login, I don't see any changes on
opening crontab -e. If later I do echo $VISUAL, I get the response vim
What am I doing wrong here?
I am trying to set the VISUAL and EDITOR environment variables in a server
for default usage with crontab.
When I do a manual export VISUAL=vim, things work perfectly.
But when I add the lines
EDITOR=vim
VISUAL=vim
to my .bashrc file and logout and re-login, I don't see any changes on
opening crontab -e. If later I do echo $VISUAL, I get the response vim
What am I doing wrong here?
Lazy loading does not works for ManyToOne in eclipselink
Lazy loading does not works for ManyToOne in eclipselink
Address has many-to-one relationship with person like :
Person :
@Id
@Column(name="personid")
private Long personId;
private String firstName;
private String lastName;
private String email;
@OneToMany(cascade =
CascadeType.ALL,mappedBy="person",targetEntity=Address.class,fetch=FetchType.LAZY)
private List addressArray=new ArrayList<>();
public Person() {
}
and Address :
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="personId")
private Person person;
I want to access person's firstname from the address object like
"address.person.firstname" but it always eager load the person ?
Address has many-to-one relationship with person like :
Person :
@Id
@Column(name="personid")
private Long personId;
private String firstName;
private String lastName;
private String email;
@OneToMany(cascade =
CascadeType.ALL,mappedBy="person",targetEntity=Address.class,fetch=FetchType.LAZY)
private List addressArray=new ArrayList<>();
public Person() {
}
and Address :
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="personId")
private Person person;
I want to access person's firstname from the address object like
"address.person.firstname" but it always eager load the person ?
'or' and '||' - asking for x or y in this situation?
'or' and '||' - asking for x or y in this situation?
I have the following code in application.html.erb
...
<body>
<div class="container">
<%= render 'layouts/header' %>
<section class="<%= "login_section" if login_or_signup? %>"> #here's
the issue
<% flash.each do |key, value| %>
<div class="flash <%= key %>"><%= value %></div>
<% end %>
<%= yield %>
</section>
<%= render 'layouts/footer' %>
</div>
</body>
...
login_section is a css class that formats the header differently, and I'd
like that to be set only if the current path is /login or /signup - so the
login_or_signup? helper is defined like so:
def login_or_signup?
request.path == login_path || signup_path
end
I've also tried the guts of that as login_path or signup_path, (login_path
|| signup_path), and (login_path or signup_path) but none of them will
evaluate to true correctly ("correctly" being when the path is either
/login or /signup). I've tried writing this as
def login_or_signup?
request.path == login_path
end
and that works as expected.
I have the following code in application.html.erb
...
<body>
<div class="container">
<%= render 'layouts/header' %>
<section class="<%= "login_section" if login_or_signup? %>"> #here's
the issue
<% flash.each do |key, value| %>
<div class="flash <%= key %>"><%= value %></div>
<% end %>
<%= yield %>
</section>
<%= render 'layouts/footer' %>
</div>
</body>
...
login_section is a css class that formats the header differently, and I'd
like that to be set only if the current path is /login or /signup - so the
login_or_signup? helper is defined like so:
def login_or_signup?
request.path == login_path || signup_path
end
I've also tried the guts of that as login_path or signup_path, (login_path
|| signup_path), and (login_path or signup_path) but none of them will
evaluate to true correctly ("correctly" being when the path is either
/login or /signup). I've tried writing this as
def login_or_signup?
request.path == login_path
end
and that works as expected.
How to solve the parse error in PHP 5.2
How to solve the parse error in PHP 5.2
How to replace the following code to work on PHP 5.2. The below code
generates a Parse error: syntax error, unexpected T_FUNCTION
$list = array('0' => 'No Activity', '1' => 'Pending','2' => 'Approved',
'3' => 'Rejected', ''=>'All');
'value'=>function ($data, $row) use ($list){ return $data->test=
$list[$data->Test] ; },
How to replace the following code to work on PHP 5.2. The below code
generates a Parse error: syntax error, unexpected T_FUNCTION
$list = array('0' => 'No Activity', '1' => 'Pending','2' => 'Approved',
'3' => 'Rejected', ''=>'All');
'value'=>function ($data, $row) use ($list){ return $data->test=
$list[$data->Test] ; },
how to submit GET form with jstl parameter
how to submit GET form with jstl parameter
i have following form it does not show jstl parameter in url after submiting
<form action="Contactus.jsp?param1=${value1}" method="get">
<input type="submit" value="${btnregister}" id="registration-link">
</form>
After submitting form it only shows Contactus.jsp? and param1 disappears.
Why?
i have following form it does not show jstl parameter in url after submiting
<form action="Contactus.jsp?param1=${value1}" method="get">
<input type="submit" value="${btnregister}" id="registration-link">
</form>
After submitting form it only shows Contactus.jsp? and param1 disappears.
Why?
Tuesday, 10 September 2013
CImg Error : 'gm.exe' is not recognized as an internal or external command,
CImg Error : 'gm.exe' is not recognized as an internal or external command,
I am new to c++ programming , today i was trying to save an image using
CImg . CImg is C++ Template Image Processing Library .
The basic code i wrote is(Please forgive any syntax erros , as copied part
of my codes) :
#include "CImg.h"// Include CImg library header.
#include <iostream>
using namespace cimg_library;
using namespace std;
const int screen_size = 800;
//-------------------------------------------------------------------------------
// Main procedure
//-------------------------------------------------------------------------------
int main()
{
CImg<unsigned char> img(screen_size,screen_size,1,3,20);
CImgDisplay disp(img, "CImg Tutorial");
//Some drawing using img.draw_circle( 10, 10, 60, RED);
img.save("result.jpg"); // save the image
return 0;
}
But I cannot run my program as it says :
Invalid Parameter - 100%
'gm.exe' is not recognized as an internal or external command,
operable program or batch file.
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
[CImg] *** CImgIOException *** [instance(800,800,1,3,02150020,non-shared)]
CImg<unsigned char>::save_other() : Failed to save file 'result.jpg'.
Format is not natively supported, and no external commands succeeded.
terminate called after throwing an instance of
'cimg_library::CImgIOException'
what(): [instance(800,800,1,3,02150020,non-shared)] CImg<unsigned
char>::save_other() : Failed to save file 'result.jpg'. Format is not
natively supported, and no external commands succeeded.
Though i can see the image , I cannot save it. After googling a bit i
found people saying to install ImageMagick , i have installed it but no
help . Some of the Forum says to compile against libjpeg, libpng,
libmagick++. I am using Eclipse CDT plugin to write C++ project . Please
help me .
I am new to c++ programming , today i was trying to save an image using
CImg . CImg is C++ Template Image Processing Library .
The basic code i wrote is(Please forgive any syntax erros , as copied part
of my codes) :
#include "CImg.h"// Include CImg library header.
#include <iostream>
using namespace cimg_library;
using namespace std;
const int screen_size = 800;
//-------------------------------------------------------------------------------
// Main procedure
//-------------------------------------------------------------------------------
int main()
{
CImg<unsigned char> img(screen_size,screen_size,1,3,20);
CImgDisplay disp(img, "CImg Tutorial");
//Some drawing using img.draw_circle( 10, 10, 60, RED);
img.save("result.jpg"); // save the image
return 0;
}
But I cannot run my program as it says :
Invalid Parameter - 100%
'gm.exe' is not recognized as an internal or external command,
operable program or batch file.
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
[CImg] *** CImgIOException *** [instance(800,800,1,3,02150020,non-shared)]
CImg<unsigned char>::save_other() : Failed to save file 'result.jpg'.
Format is not natively supported, and no external commands succeeded.
terminate called after throwing an instance of
'cimg_library::CImgIOException'
what(): [instance(800,800,1,3,02150020,non-shared)] CImg<unsigned
char>::save_other() : Failed to save file 'result.jpg'. Format is not
natively supported, and no external commands succeeded.
Though i can see the image , I cannot save it. After googling a bit i
found people saying to install ImageMagick , i have installed it but no
help . Some of the Forum says to compile against libjpeg, libpng,
libmagick++. I am using Eclipse CDT plugin to write C++ project . Please
help me .
Dart - set mimetype of HttpClientRequest
Dart - set mimetype of HttpClientRequest
Is there some way to set the mimeType of HttpClientRequest ?
I'm trying to do some unittests where I create an instance of HttpClient
and then sent a post request with a bytes of data to a HttpServer and then
parse it based on the mimeType I set. Something like this :
import 'dart:io';
void main() {
HttpServer.bind('localhost', 8080)
.then((HttpServer server) {
server.listen((HttpRequest request) {
String mimeType = request.headers.contentType.mimeType;
if (mimeType == 'application/json') {
// parse bytes of data to json and then to map
} else if (mimeType == 'text/plain') {
// parse bytes of data to string
}
// do something with data
// close response
});
});
HttpClient client = new HttpClient();
client.open('POST', '127.0.0.1', 8080, '/')
.then((HttpClientRequest r) {
r.add('{"val": 5}'.codeUnits);
// already tried both
r.headers.set(HttpHeaders.CONTENT_TYPE, 'application/json'); //
doesn't work
r.headers.contentType = ContentType.parse('application/json'); //
doesn't work
r.close();
});
}
So the HttpHeaders is immutable. Any workaround?
Is there some way to set the mimeType of HttpClientRequest ?
I'm trying to do some unittests where I create an instance of HttpClient
and then sent a post request with a bytes of data to a HttpServer and then
parse it based on the mimeType I set. Something like this :
import 'dart:io';
void main() {
HttpServer.bind('localhost', 8080)
.then((HttpServer server) {
server.listen((HttpRequest request) {
String mimeType = request.headers.contentType.mimeType;
if (mimeType == 'application/json') {
// parse bytes of data to json and then to map
} else if (mimeType == 'text/plain') {
// parse bytes of data to string
}
// do something with data
// close response
});
});
HttpClient client = new HttpClient();
client.open('POST', '127.0.0.1', 8080, '/')
.then((HttpClientRequest r) {
r.add('{"val": 5}'.codeUnits);
// already tried both
r.headers.set(HttpHeaders.CONTENT_TYPE, 'application/json'); //
doesn't work
r.headers.contentType = ContentType.parse('application/json'); //
doesn't work
r.close();
});
}
So the HttpHeaders is immutable. Any workaround?
Apache SVN server requirements?
Apache SVN server requirements?
Are there any minimum server requirements for using Apache SVN? If not,
what are some general server specifications used for Apache SVN? Any
information on server capacities for Apache SVN would be appreciated!
Are there any minimum server requirements for using Apache SVN? If not,
what are some general server specifications used for Apache SVN? Any
information on server capacities for Apache SVN would be appreciated!
Java String "constant" confusion
Java String "constant" confusion
I'm slightly confused and obviously missing something here:
I read that java.lang.String's "are constant; their values cannot be
changed after they are created."
But if i write the following code:
String line;
line = "Test1";
System.out.println(line);
line = "Test2";
System.out.println(line);
The terminal outputs:
Test1
Test2
It appears I am able to set a value, and then set another value for the
string later.
No difference if i try this way:
String line2 = "Test3";
System.out.println(line2);
line2 = "Test4";
System.out.println(line2);
I am still able to set the value after its been set initially.
Where have I gone wrong here?
Thanks.
I'm slightly confused and obviously missing something here:
I read that java.lang.String's "are constant; their values cannot be
changed after they are created."
But if i write the following code:
String line;
line = "Test1";
System.out.println(line);
line = "Test2";
System.out.println(line);
The terminal outputs:
Test1
Test2
It appears I am able to set a value, and then set another value for the
string later.
No difference if i try this way:
String line2 = "Test3";
System.out.println(line2);
line2 = "Test4";
System.out.println(line2);
I am still able to set the value after its been set initially.
Where have I gone wrong here?
Thanks.
Mixing Knockout and Razor Variables
Mixing Knockout and Razor Variables
I am struggling with what I imagine is a really daft problem. I am
iterating through a collection in Knockout.JS using 'foreach', and need to
create a link for each item using variables within the collection.
The problem is that my url is generated on the fly using variables from
the view model, and I need to combine these with variables in the Knockout
collection.
Here is my block containing the Knockout loop.
<div data-bind="foreach: pagedList" class="span8"
style="border-bottom: 1px solid #0094ff;">
<div style="cursor: pointer;">
<p data-bind="text: hotelId"></p>
<p data-bind="text: name"></p>
<p data-bind="text: hotelRating"></p>
<p data-bind="text: propertyCategory"></p>
</div>
</div>
Ideally I want to add the link to the parent div through the
'onclick="window.location=' method. I have tried using Action.Link and
adding in the Knockout variables through string concatenation, as so;
<div style="cursor: pointer;" onclick="window.location="@Url.Action(
"Index", "Hotel", new { regionId = Model.region.regionId,
regionName =
HttpUtility.UrlPathEncode(Model.region.regionNameLong.ToString().Replace(",","")).Replace("%20","-"),
hotelId = " + hotelID() + ", hotelName =
HttpUtility.UrlPathEncode(Convert.ToString(" + name() +
").Replace(",","")).Replace("%20","-") })"> </div>
But this gives an 'Object not instantiated error'. Secondly, I tried using
Knockout first, through the 'data-bind="attr:' method, as so;
<a href="someurl" data-bind="attr: { href: '/Region/' +
'@Model.region.regionId ' + '/' +
'@HttpUtility.UrlPathEncode(Model.region.regionNameLong.ToString().Replace(",","")).Replace("%20","-")
' + '/' + hotelID() + '/' +
'@HttpUtility.UrlPathEncode(Convert.ToString(" + name() +
").Replace(",","")).Replace("%20","-")' }, text: hotelId()"></a>
Again no dice.
I know this is mixing client side and server side paradigms, but can't
think of another way without ditching Knockout.
Does anybody have any experience with this?
I am struggling with what I imagine is a really daft problem. I am
iterating through a collection in Knockout.JS using 'foreach', and need to
create a link for each item using variables within the collection.
The problem is that my url is generated on the fly using variables from
the view model, and I need to combine these with variables in the Knockout
collection.
Here is my block containing the Knockout loop.
<div data-bind="foreach: pagedList" class="span8"
style="border-bottom: 1px solid #0094ff;">
<div style="cursor: pointer;">
<p data-bind="text: hotelId"></p>
<p data-bind="text: name"></p>
<p data-bind="text: hotelRating"></p>
<p data-bind="text: propertyCategory"></p>
</div>
</div>
Ideally I want to add the link to the parent div through the
'onclick="window.location=' method. I have tried using Action.Link and
adding in the Knockout variables through string concatenation, as so;
<div style="cursor: pointer;" onclick="window.location="@Url.Action(
"Index", "Hotel", new { regionId = Model.region.regionId,
regionName =
HttpUtility.UrlPathEncode(Model.region.regionNameLong.ToString().Replace(",","")).Replace("%20","-"),
hotelId = " + hotelID() + ", hotelName =
HttpUtility.UrlPathEncode(Convert.ToString(" + name() +
").Replace(",","")).Replace("%20","-") })"> </div>
But this gives an 'Object not instantiated error'. Secondly, I tried using
Knockout first, through the 'data-bind="attr:' method, as so;
<a href="someurl" data-bind="attr: { href: '/Region/' +
'@Model.region.regionId ' + '/' +
'@HttpUtility.UrlPathEncode(Model.region.regionNameLong.ToString().Replace(",","")).Replace("%20","-")
' + '/' + hotelID() + '/' +
'@HttpUtility.UrlPathEncode(Convert.ToString(" + name() +
").Replace(",","")).Replace("%20","-")' }, text: hotelId()"></a>
Again no dice.
I know this is mixing client side and server side paradigms, but can't
think of another way without ditching Knockout.
Does anybody have any experience with this?
When is it correct to use quotation marks when defining an object literal?
When is it correct to use quotation marks when defining an object literal?
In pure JavaScript, is there a difference between the two snippets below?
// Snippet one
var myObject = {
"property":"something"
}
// Snippet two
var myObject = {
property:"something"
}
MDN and the Google JavaScript style guide suggest that the two are
equivalent.
The JSON specification mandates the use of quotation marks.
When is it correct to use quotation marks when defining an object literal,
if at all? Does it imply/make any difference to the interpreter? Is it
simply a case of choosing one or the other and being as consistent as
possible?
In pure JavaScript, is there a difference between the two snippets below?
// Snippet one
var myObject = {
"property":"something"
}
// Snippet two
var myObject = {
property:"something"
}
MDN and the Google JavaScript style guide suggest that the two are
equivalent.
The JSON specification mandates the use of quotation marks.
When is it correct to use quotation marks when defining an object literal,
if at all? Does it imply/make any difference to the interpreter? Is it
simply a case of choosing one or the other and being as consistent as
possible?
Persistent animation with kineticjs and tweens
Persistent animation with kineticjs and tweens
I have a "periodic" animation defined by a sequence of tweens in
kineticjs. I would like the animation to repeat forever with the page
being still responsive to other events. Which is the best way to do it? Is
defining a function that calls itself a good strategy?
I have a "periodic" animation defined by a sequence of tweens in
kineticjs. I would like the animation to repeat forever with the page
being still responsive to other events. Which is the best way to do it? Is
defining a function that calls itself a good strategy?
Jquery select previous element
Jquery select previous element
I am new to Jquery and I've had a look through the replies on here but I
can't find any specific answers to my question.
I have a (ASP) generated table a snippet of which is:
<a href="javascript:__doPostBack('gv2','Select$15')"
style="color:White;">S</a></td><td style="font-size:XX-Small;">1104</td>
<td style="font-size:XX-Small;">320.20.0116.090</td>
<td style="font-size:XX-Small;">*Not Found*</td>
What I'm trying to do is highlight the *Not Found text and then disable
the preceeding href so the link cannot be clicked.
I have developed the following selector:-
$('td').highlight('Not
Found').each(function(){$(this).prev("a").removeAttr("href")});
The highlight selector works but the removeattr doesn't. Syntax is
probably incorrect but any pointers would be very useful.
I am new to Jquery and I've had a look through the replies on here but I
can't find any specific answers to my question.
I have a (ASP) generated table a snippet of which is:
<a href="javascript:__doPostBack('gv2','Select$15')"
style="color:White;">S</a></td><td style="font-size:XX-Small;">1104</td>
<td style="font-size:XX-Small;">320.20.0116.090</td>
<td style="font-size:XX-Small;">*Not Found*</td>
What I'm trying to do is highlight the *Not Found text and then disable
the preceeding href so the link cannot be clicked.
I have developed the following selector:-
$('td').highlight('Not
Found').each(function(){$(this).prev("a").removeAttr("href")});
The highlight selector works but the removeattr doesn't. Syntax is
probably incorrect but any pointers would be very useful.
Monday, 9 September 2013
JasperReports: unable to get URL parameter to work
JasperReports: unable to get URL parameter to work
I'm trying to modify an existing Jasper Report. The existing one works
great, and retrieves a couple of parameters from the URL of the page that
generates it.
I want to pass a third parameter to the report, but after hours trying I
have not been able to get it to work (the parameter value is always null
or the default value, no matter what value is passed in the URL).
I have tried to figure out how it was done with the parameters that are
already working, but I didn't find anything, either with the JasperReports
UI or studying the resulting (jr)xml file.
What really puzzles me is that the parameter names in the URL are "id" and
"date", but they are referred to in the report as "p_id" and "p_date". I
can't find where that transformation or mapping takes place, so I think
that is the step I'm missing.
I'll be very thankful if you can give me any hint!!!
I'm trying to modify an existing Jasper Report. The existing one works
great, and retrieves a couple of parameters from the URL of the page that
generates it.
I want to pass a third parameter to the report, but after hours trying I
have not been able to get it to work (the parameter value is always null
or the default value, no matter what value is passed in the URL).
I have tried to figure out how it was done with the parameters that are
already working, but I didn't find anything, either with the JasperReports
UI or studying the resulting (jr)xml file.
What really puzzles me is that the parameter names in the URL are "id" and
"date", but they are referred to in the report as "p_id" and "p_date". I
can't find where that transformation or mapping takes place, so I think
that is the step I'm missing.
I'll be very thankful if you can give me any hint!!!
PHP Form Submit Button Unclickable
This summary is not available. Please
click here to view the post.
How to get custom fields like Invoice number to show on Paypal receipts
How to get custom fields like Invoice number to show on Paypal receipts
We are using PayPal website payment pro and we can send money live and all
is well.
Our issues are:
when we view the recent payment, it should say "payment from John
Smith"...but ours just say "payment from". the name of the person does not
show up. well our accounting section wants it back. :-) not sure why its
not or which parameter of the DoDirectPayment request I need for this.
The user submission form has an invoice number field. I also need the
invoice number to show on the details page of the PayPal payment receipt.
I was able to get stuff like shipping address to show up by using its
parameter, but no idea to have Invoice Number show up.
I know it can be done because the old website had these and they used
website payments pro API to send payments. I just am not sure of how to do
this. thee is no mention of this in the API references that I see,
especially for DoDirectPayments method. Any help appreciated
Norman
We are using PayPal website payment pro and we can send money live and all
is well.
Our issues are:
when we view the recent payment, it should say "payment from John
Smith"...but ours just say "payment from". the name of the person does not
show up. well our accounting section wants it back. :-) not sure why its
not or which parameter of the DoDirectPayment request I need for this.
The user submission form has an invoice number field. I also need the
invoice number to show on the details page of the PayPal payment receipt.
I was able to get stuff like shipping address to show up by using its
parameter, but no idea to have Invoice Number show up.
I know it can be done because the old website had these and they used
website payments pro API to send payments. I just am not sure of how to do
this. thee is no mention of this in the API references that I see,
especially for DoDirectPayments method. Any help appreciated
Norman
C++ window named pipes client receives only one message
C++ window named pipes client receives only one message
I'm new to pipes and interprocess communications. I was testing my code
where my server sends a string to the client for further processing, but
my client gets the first message only and blocks while the server keeps on
sending messages. Any help please ?
Server code:
int p_connect()
{
pipe=CreateNamedPipe(
"\\\\.\\pipe\\coordonees", //name
PIPE_ACCESS_OUTBOUND,// outbound trafic only
PIPE_TYPE_BYTE,// data as byte stream
1,// 1 instance of this pipe only
0,// no outbound buffer
0,// no inbound buffer
0,//default wait time
NULL //default sec
);
if(!pipe || pipe==INVALID_HANDLE_VALUE)
{
cout<< "error : failed to connect to com pipe !"<<endl;
return 1;
}
cout << "Waiting for connections to stream ..."<<endl;
BOOL result=ConnectNamedPipe(pipe,NULL);
if(!result)
{
cout << "error : failed to establish connection to pipe !"<<endl;
CloseHandle(pipe);
return 1;
}
cout << "connected ! sending detection data to pipe ..."<<endl;
return 0;
}
sending messages :
result=WriteFile(pipe,data,wcslen(data)*sizeof(wchar_t),&bytes,NULL);
Client reading code:
HANDLE pipe = CreateFile(
"\\\\.\\pipe\\coordonees",
GENERIC_READ, // only need read access
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (pipe == INVALID_HANDLE_VALUE)
{
wcout << "Failed to connect to pipe." << endl;
// look up error code here using GetLastError()
system("pause");
return 1;
}
wcout << "Reading data from pipe..." << endl;
// The read operation will block until there is data to read
DWORD numBytesRead = 0;
BOOL result;
numBytesRead = 0;
result=0;
wchar_t buffer[50];
result = ReadFileEx(
pipe,
buffer, // the data from the pipe will be put here
127 * sizeof(wchar_t), // number of bytes allocated
&numBytesRead, // this will store number of bytes
actually read
NULL // not using overlapped IO
);
I'm new to pipes and interprocess communications. I was testing my code
where my server sends a string to the client for further processing, but
my client gets the first message only and blocks while the server keeps on
sending messages. Any help please ?
Server code:
int p_connect()
{
pipe=CreateNamedPipe(
"\\\\.\\pipe\\coordonees", //name
PIPE_ACCESS_OUTBOUND,// outbound trafic only
PIPE_TYPE_BYTE,// data as byte stream
1,// 1 instance of this pipe only
0,// no outbound buffer
0,// no inbound buffer
0,//default wait time
NULL //default sec
);
if(!pipe || pipe==INVALID_HANDLE_VALUE)
{
cout<< "error : failed to connect to com pipe !"<<endl;
return 1;
}
cout << "Waiting for connections to stream ..."<<endl;
BOOL result=ConnectNamedPipe(pipe,NULL);
if(!result)
{
cout << "error : failed to establish connection to pipe !"<<endl;
CloseHandle(pipe);
return 1;
}
cout << "connected ! sending detection data to pipe ..."<<endl;
return 0;
}
sending messages :
result=WriteFile(pipe,data,wcslen(data)*sizeof(wchar_t),&bytes,NULL);
Client reading code:
HANDLE pipe = CreateFile(
"\\\\.\\pipe\\coordonees",
GENERIC_READ, // only need read access
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (pipe == INVALID_HANDLE_VALUE)
{
wcout << "Failed to connect to pipe." << endl;
// look up error code here using GetLastError()
system("pause");
return 1;
}
wcout << "Reading data from pipe..." << endl;
// The read operation will block until there is data to read
DWORD numBytesRead = 0;
BOOL result;
numBytesRead = 0;
result=0;
wchar_t buffer[50];
result = ReadFileEx(
pipe,
buffer, // the data from the pipe will be put here
127 * sizeof(wchar_t), // number of bytes allocated
&numBytesRead, // this will store number of bytes
actually read
NULL // not using overlapped IO
);
Design history tracking database using django-rest-framework
Design history tracking database using django-rest-framework
I am using the django-rest-framework api for the first time. Here's my
question:
I need to design a database in which there are two tables:
Server => To save the server information such as ip address and server name
id: INT, name: VARCHAR, ip_address: VARCHAR
Deploy => The deploys on the server including the deploy date and a
comment message
id: INT, server_id: FK to Server, deploy_date: DATETIME, message: VARCHAR
I am asked to keep track of the deploy information and design the
following APIs:
get /servers/ => get all the server information with the latest deploy on
that server
Example:
[
{
"id" : 1,
"name" : "qa-001",
"ip_address" : "192.168.1.1",
"deploy" :
{
"id" : 1,
"deploy_date" : "2013-09-09 12:00:00",
"message" : "test new api"
}
},
{
"id" : 2,
"name" : "qa-002",
"ip_address" : "192.168.1.2",
"deploy" :
{
"id" : 2,
"deploy_date" : "2013-09-10 12:00:00",
"message" : "test second message"
}
}
]
get /deploys/ => get all the deploy information
Example:
[
{
"id" : 1,
"deploy_date" : "2013-09-09 12:00:00",
"message" : "test new api",
"server_id" : 1
},
{
"id" : 2,
"deploy_date" : "2013-09-10 12:00:00",
"message" : "test second message",
"server_id" : 2
},
{
"id" : 3,
"deploy_date" : "2013-09-08 12:00:00",
"message" : "test new api",
"server_id" : 1
}
]
// Deploy 3 does not show up in the get servers return json
// because deploy 1 was deployed on the same server but later than deploy 3.
POST /deploys/ => To insert a new deploy
POST /servers/ => To insert a new server
...
I have played around with django-rest-framework tutorial code and read
about different api documentations but couldn't figure out how to
implement the features that I list above.
Please let me know if you have any ideas on how to implement this or if
you think another database design would fit this requirement more.
Thanks!
I am using the django-rest-framework api for the first time. Here's my
question:
I need to design a database in which there are two tables:
Server => To save the server information such as ip address and server name
id: INT, name: VARCHAR, ip_address: VARCHAR
Deploy => The deploys on the server including the deploy date and a
comment message
id: INT, server_id: FK to Server, deploy_date: DATETIME, message: VARCHAR
I am asked to keep track of the deploy information and design the
following APIs:
get /servers/ => get all the server information with the latest deploy on
that server
Example:
[
{
"id" : 1,
"name" : "qa-001",
"ip_address" : "192.168.1.1",
"deploy" :
{
"id" : 1,
"deploy_date" : "2013-09-09 12:00:00",
"message" : "test new api"
}
},
{
"id" : 2,
"name" : "qa-002",
"ip_address" : "192.168.1.2",
"deploy" :
{
"id" : 2,
"deploy_date" : "2013-09-10 12:00:00",
"message" : "test second message"
}
}
]
get /deploys/ => get all the deploy information
Example:
[
{
"id" : 1,
"deploy_date" : "2013-09-09 12:00:00",
"message" : "test new api",
"server_id" : 1
},
{
"id" : 2,
"deploy_date" : "2013-09-10 12:00:00",
"message" : "test second message",
"server_id" : 2
},
{
"id" : 3,
"deploy_date" : "2013-09-08 12:00:00",
"message" : "test new api",
"server_id" : 1
}
]
// Deploy 3 does not show up in the get servers return json
// because deploy 1 was deployed on the same server but later than deploy 3.
POST /deploys/ => To insert a new deploy
POST /servers/ => To insert a new server
...
I have played around with django-rest-framework tutorial code and read
about different api documentations but couldn't figure out how to
implement the features that I list above.
Please let me know if you have any ideas on how to implement this or if
you think another database design would fit this requirement more.
Thanks!
How to make an external HTML file content not be appeared in the home paged?
How to make an external HTML file content not be appeared in the home paged?
Sorry for the confusing title, I really don't know how to title my question,
I am trying to make a dropdown shopping cart, I have designed the cart
using html css php and jquery. the file name cart.php
<div class="maincontainer">
....
....
</div>
There is a shopping cart button in the home page "index.php", to make the
cart.php be appeared as a dropdown in the index.php
I have include the car.php as include "cart.php"
First problem: all the cart.php content are being shown on the top of the
index.php even if I set the maincontainer display to none
2nd problem, I cant figure out how to call the cart in a div on index.php ?
3rd, What topic or keyword should i search, to learn how to solve the
above issues?
I am learning all my own :)
Sorry if the question is too simple.
Sorry for the confusing title, I really don't know how to title my question,
I am trying to make a dropdown shopping cart, I have designed the cart
using html css php and jquery. the file name cart.php
<div class="maincontainer">
....
....
</div>
There is a shopping cart button in the home page "index.php", to make the
cart.php be appeared as a dropdown in the index.php
I have include the car.php as include "cart.php"
First problem: all the cart.php content are being shown on the top of the
index.php even if I set the maincontainer display to none
2nd problem, I cant figure out how to call the cart in a div on index.php ?
3rd, What topic or keyword should i search, to learn how to solve the
above issues?
I am learning all my own :)
Sorry if the question is too simple.
Authorization c# mvc
Authorization c# mvc
I want to create c# mvc internet application that allows users to edit
their own accounts. I want to have fields such as first name, surname,
date of birth and location.
I'm aware of the built in authorization and the Authorize attribute for
the controllers. I do currently have the default AccountController in the
project.
I'm just not sure what the best way is to extend on the default username
and password properties for each user? Should I store the membership id in
a new class containing the other properties or is there a better way?
I want to create c# mvc internet application that allows users to edit
their own accounts. I want to have fields such as first name, surname,
date of birth and location.
I'm aware of the built in authorization and the Authorize attribute for
the controllers. I do currently have the default AccountController in the
project.
I'm just not sure what the best way is to extend on the default username
and password properties for each user? Should I store the membership id in
a new class containing the other properties or is there a better way?
Regex to remove and preserve lines
Regex to remove and preserve lines
pI'm looking to use the following regex line to remove malicious code from
my site;/p pcodefind -type f -name \*.php -exec sed -i
's/.*eval(base64_decode(\CmVycm.*/lt;?php/g' {} \;/code/p pThis will
preserve codelt;?php/code which I want but I noticed that many of the
injections are throughout php files on multiple lines, meaning not just
the very first codelt;?php/code So is it possible to do an if do otherwise
statement where if its on line 1 of a php file preserve the php tag
otherwise remove the entire line if its anywhere else?/p
pI'm looking to use the following regex line to remove malicious code from
my site;/p pcodefind -type f -name \*.php -exec sed -i
's/.*eval(base64_decode(\CmVycm.*/lt;?php/g' {} \;/code/p pThis will
preserve codelt;?php/code which I want but I noticed that many of the
injections are throughout php files on multiple lines, meaning not just
the very first codelt;?php/code So is it possible to do an if do otherwise
statement where if its on line 1 of a php file preserve the php tag
otherwise remove the entire line if its anywhere else?/p
Sunday, 8 September 2013
Issue with List picker FullModeItemTemplate template
Issue with List picker FullModeItemTemplate template
I am using the Listpicker control in my WP8 app, where
FullModeItemTemplate is defined to display a custom list of options and I
enabled SelectionMode to Multiple, so that user can select multiple
options from the Listpicker. On code behind, i am binding the text.
My main question, with below my xaml output of the fullmode has lot of
free space between each list item. I couldn't able to figure out how to
minimize the gap between...
<toolkit:ListPicker x:Name="userCountryList" ItemsSource="{Binding
CountryList}" Header="Choose a country or region:"
SelectionMode="Multiple" FullModeItemTemplate="{StaticResource
DataTemplate2}" />
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="DataTemplate2">
<StackPanel Orientation="Horizontal">
<TextBlock HorizontalAlignment="Left" FontSize="28"
TextWrapping="Wrap" Text="{Binding CountryName}"
VerticalAlignment="Center" Width="Auto"/>
</StackPanel>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
Current fullmode output is like below:
I am using the Listpicker control in my WP8 app, where
FullModeItemTemplate is defined to display a custom list of options and I
enabled SelectionMode to Multiple, so that user can select multiple
options from the Listpicker. On code behind, i am binding the text.
My main question, with below my xaml output of the fullmode has lot of
free space between each list item. I couldn't able to figure out how to
minimize the gap between...
<toolkit:ListPicker x:Name="userCountryList" ItemsSource="{Binding
CountryList}" Header="Choose a country or region:"
SelectionMode="Multiple" FullModeItemTemplate="{StaticResource
DataTemplate2}" />
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="DataTemplate2">
<StackPanel Orientation="Horizontal">
<TextBlock HorizontalAlignment="Left" FontSize="28"
TextWrapping="Wrap" Text="{Binding CountryName}"
VerticalAlignment="Center" Width="Auto"/>
</StackPanel>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
Current fullmode output is like below:
Creating hashes from parsed HTML
Creating hashes from parsed HTML
I'm getting second table from this page, parse it and trying to generate
hashes from this data. The problem is that each object is separated by
this grey TR but I can only manage this by getting every single TR from
this table.
How can I determine proper TR by getting those between gray ones?
For now I'm using this line to get each TR:
parsed_html.css("table")[1].css("tr")
I'm getting second table from this page, parse it and trying to generate
hashes from this data. The problem is that each object is separated by
this grey TR but I can only manage this by getting every single TR from
this table.
How can I determine proper TR by getting those between gray ones?
For now I'm using this line to get each TR:
parsed_html.css("table")[1].css("tr")
Sub domain in rails app?
Sub domain in rails app?
I've built a rails app that running on one domain. I would like to add a
separate site within the app for charges through stripe.
If I create a new controller, how do I point it to a sub domain of that
same domain?
How do I get it to work with Heroku?
I've built a rails app that running on one domain. I would like to add a
separate site within the app for charges through stripe.
If I create a new controller, how do I point it to a sub domain of that
same domain?
How do I get it to work with Heroku?
Error when linking with POCO library compiled with i686-w64-mingw32
Error when linking with POCO library compiled with i686-w64-mingw32
I am using i686-w64-mingw32 downloaded from sf to compile POCO libraries.
Libraries are compiled and libPoco*.a files are created (with some
warnings). Now when I want to use those files (e.g. in a small sample
project which converts string to integer), linker throws error saying:
./Debug/main.o:main.cpp:(.text+0xab): undefined reference to
`imp__ZN4Poco12NumberParser5parseERKSs'
The strange thing is that if I do compilation for both sides (lib and test
app) using TDM-MinGW-4.7.1 everything is fine!
I tried setting "-march=i386;-m32" on both compilations but no luck. Here
is log of linker when I try to build my test app:
g++ -o ./Debug/testpoco @"testpoco.txt" -L. -Lc:/poco/lib/
-lPocoFoundationmtd -v
Using built-in specs.
COLLECT_GCC=g++
...
Target: i686-w64-mingw32
...
Thread model: win32
gcc version 4.8.1 (rev5, Built by MinGW-W64 project)
...
COLLECT_GCC_OPTIONS='-o' './Debug/testpoco.exe' '-L.' '-Lc:/poco/lib/'
'-v' '-shared-libgcc' '-mtune=generic' '-march=i686'
...
./Debug/main.o:main.cpp:(.text+0xab): undefined reference to
`_imp___ZN4Poco12NumberParser5parseERKSs'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[1]: *** [Debug/testpoco] Error 1
testpoco.mk:77: recipe for target 'Debug/testpoco' failed
I am using i686-w64-mingw32 downloaded from sf to compile POCO libraries.
Libraries are compiled and libPoco*.a files are created (with some
warnings). Now when I want to use those files (e.g. in a small sample
project which converts string to integer), linker throws error saying:
./Debug/main.o:main.cpp:(.text+0xab): undefined reference to
`imp__ZN4Poco12NumberParser5parseERKSs'
The strange thing is that if I do compilation for both sides (lib and test
app) using TDM-MinGW-4.7.1 everything is fine!
I tried setting "-march=i386;-m32" on both compilations but no luck. Here
is log of linker when I try to build my test app:
g++ -o ./Debug/testpoco @"testpoco.txt" -L. -Lc:/poco/lib/
-lPocoFoundationmtd -v
Using built-in specs.
COLLECT_GCC=g++
...
Target: i686-w64-mingw32
...
Thread model: win32
gcc version 4.8.1 (rev5, Built by MinGW-W64 project)
...
COLLECT_GCC_OPTIONS='-o' './Debug/testpoco.exe' '-L.' '-Lc:/poco/lib/'
'-v' '-shared-libgcc' '-mtune=generic' '-march=i686'
...
./Debug/main.o:main.cpp:(.text+0xab): undefined reference to
`_imp___ZN4Poco12NumberParser5parseERKSs'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[1]: *** [Debug/testpoco] Error 1
testpoco.mk:77: recipe for target 'Debug/testpoco' failed
Subscribe to:
Comments (Atom)