Android start service on boot, can't receive the broadcast
My service don't start on system boot, only when the user press the
refresh button. I've tried everythng searched in stack but nothing i've
rewrited my code 4 times and nothing, i want my service run in a time
interval and when the refresh button is pressed, i can´t understand why is
not running on boot, Have i missed something?
Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.moody"
android:installLocation="internalOnly"
android:versionCode="0"
android:versionName="0.6.7.2 alpha" >
<permission
android:name="com.android.moody.permission.GET_SERVER_DATA"
android:protectionLevel="normal" />
<uses-sdk
android:maxSdkVersion="18"
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<uses-permission
android:name="com.android.moody.permission.GET_SERVER_DATA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:allowClearUserData="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="activities.MainActivity"
android:label="@string/app_name" >
</activity>
<activity
android:name="activities.Menu_esq"
android:label="@string/title_activity_menu_esq" >
</activity>
<activity
android:name="activities.BaseActivity"
android:label="@string/title_activity_base" >
</activity>
<activity
android:name="activities.MainView"
android:label="@string/title_activity_main_view" >
</activity>
<activity
android:name="activities.LoginActivity"
android:label="@string/app_name"
android:noHistory="true"
android:windowSoftInputMode="adjustResize|stateVisible" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.moody.LeftActivity"
android:label="@string/title_activity_left" >
</activity>
<activity
android:name="com.example.moody.RightActivity"
android:label="@string/title_activity_right" >
</activity>
<activity
android:name="activities.UserDetailsActivity"
android:label="@string/title_activity_user_details" >
</activity>
<activity
android:name="fragments.FragTopicsPreview"
android:label="@string/title_activity_copy_of_topics_preview" >
</activity>
<activity android:name="activities.LoadingActivity" >
</activity>
<service
android:name="service.ServiceBackground"
android:enabled="true"
android:icon="@drawable/ic_launcher"
android:label="@string/moody_service" >
</service>
<receiver android:name="service.Alarm" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver
android:name="service.StartServiceReceiver"
android:permission="com.android.moody.permission.GET_SERVER_DATA" >
<intent-filter>
<action android:name="moody_get_data" />
</intent-filter>
</receiver>
</application>
ServiceBackground
public class ServiceBackground extends Service {
Alarm alarm = new Alarm();
public ServiceBackground() {
// TODO Auto-generated constructor stub
}
private boolean isRunning = false;
Object getContent;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
// android.os.Debug.waitForDebugger();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// Starts the alarm
alarm.setAlarm(getApplicationContext());
// Announcement about starting
Log.d("service", "Service Started");
// Start a Background thread
isRunning = true;
Thread backgroundThread = new Thread(new BackgroundThread());
backgroundThread.start();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
// Stop the Background thread
isRunning = false;
}
private class BackgroundThread implements Runnable {
public void run() {
try {
while (isRunning) {
Log.d("service", "Thread started");
new ManContents().getAll(getResources(),
getApplicationContext());
isRunning = false;
}
stopSelf();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Alarm
public class Alarm extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, ServiceBackground.class));
}
public void setAlarm(Context context) {
String alarm = Context.ALARM_SERVICE;
AlarmManager am = (AlarmManager) context.getSystemService(alarm);
Intent intent = new Intent("moody_get_data");
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
int type = AlarmManager.ELAPSED_REALTIME_WAKEUP;
// long interval = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
long interval = 1000 * 60 * 2;
long triggerTime = SystemClock.elapsedRealtime() + interval;
am.setRepeating(type, triggerTime, interval, pi);
}
public void CancelAlarm(Context context) {
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent
.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
StartServiceReceiver
public class StartServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("service", "Starting service from serviceReceiver");
Intent service = new Intent(context, ServiceBackground.class);
context.startService(service);
}
}
NOTES:
i already tried starting the service directly without filters, but for no
reason don't start, so with filters was the only way that worked.
I also tried without the StartServiceReceiver.java, with the intent inside
the alarm but no luck, i can change the code again if somebody thinks that
its the problem.
I've the while(isRunning) in the thread only for future purpose, but i
think the problem it's not because this.
Thursday, 3 October 2013
Wednesday, 2 October 2013
iOS 7 viewDidLoad executes slowly while pushing viewcontroller
iOS 7 viewDidLoad executes slowly while pushing viewcontroller
I was trying to push a viewcontroller B into navigation controller from A
and then assigning some properties of B in A. In this case, assigning of
properties was done and then viewDidLoad of viewcontroller A was executed.
Here, assigning properties in A should be done only after viewDidLoad of A
has done. For example,
[b.navController pushViewController:a animated:YES]; a.status = @"loaded";
Here status was assigned first and then viewDidLoad of A was executed.
This happens only in iOS 7 where as in iOS6 it works fine.
Can any one please let me know where was the problem?
Thank you.
I was trying to push a viewcontroller B into navigation controller from A
and then assigning some properties of B in A. In this case, assigning of
properties was done and then viewDidLoad of viewcontroller A was executed.
Here, assigning properties in A should be done only after viewDidLoad of A
has done. For example,
[b.navController pushViewController:a animated:YES]; a.status = @"loaded";
Here status was assigned first and then viewDidLoad of A was executed.
This happens only in iOS 7 where as in iOS6 it works fine.
Can any one please let me know where was the problem?
Thank you.
Pass the location of a file to a method in java?
Pass the location of a file to a method in java?
I'm trying to create an object that gets the location and sets an
jEditorPane to the contents of the located file.
Code:
File file = new File("Summary.html");
private void EditoPaneMethod(File file) {
frmRules.pack();
frmRules.setVisible(true);
edpRules.setEditable(false);
try {
edpRules.setPage(file.toURI().toURL());
} catch (IOException ex) {
Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null,
ex);
}
}
Could someone point me in the right direction?
I'm trying to create an object that gets the location and sets an
jEditorPane to the contents of the located file.
Code:
File file = new File("Summary.html");
private void EditoPaneMethod(File file) {
frmRules.pack();
frmRules.setVisible(true);
edpRules.setEditable(false);
try {
edpRules.setPage(file.toURI().toURL());
} catch (IOException ex) {
Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null,
ex);
}
}
Could someone point me in the right direction?
uncaught TypeError on savebutton
uncaught TypeError on savebutton
I was haveing problems with a save button on a website i am working on. i
get this error in chrome: Uncaught TypeError: Cannot read property
'contentWindow' of undefined
and this error in firefox: TypeError:
$(...).children(...).children(...).children(...)[3] is undefined
here is the pice of code where the error is located:
$('.btnAddProduct').click(function(){
if(busy != 1){
busy = 1;
var error = 0;
if($('input[name="txtTitle"]').val() == ''){
error = 1;
alert('Het titel veld is nog leeg');
$('input[name="txtTitle"]').focus();
}
if(error != 1){
$('.content_load_icon').html('<img
src="../../includes/images/layout/load_small.gif" />');
var content =
$('#cke_ckeditor').children().children().children()[3].contentWindow.document.childNodes[1].childNodes[1].innerHTML;
$.ajax({
url: '../../action/ac_productbeheer.php?a=add',
type: 'POST',
data: {txtTitle: $('input[name="txtTitle"]').val(),
txtParentPage: $('select[name="txtParentProduct"]').val(),
txtContent: content, create: true},
success: function(data, textStatus, xhr) {
$('.content_load_icon').html('');
$('.txtContentConsole').html('Product succesvol
opgeslagen!').show().delay(2000).fadeOut(200);
busy = 0;
saved = 1;
window.location =
'../../modules/productbeheer/index.php';
},
error: function(xhr, textStatus, errorThrown) {
$('.content_load_icon').html('');
$('.txtContentConsole').html('Fout bij opslaan!
Probeer het later nog een
keer.').show().delay(2000).fadeOut(200);
busy = 0;
}
});
} else {
error = 0;
busy = 0;
}
}
});
I hope one of you guys/girls can help me with this problem.
I was haveing problems with a save button on a website i am working on. i
get this error in chrome: Uncaught TypeError: Cannot read property
'contentWindow' of undefined
and this error in firefox: TypeError:
$(...).children(...).children(...).children(...)[3] is undefined
here is the pice of code where the error is located:
$('.btnAddProduct').click(function(){
if(busy != 1){
busy = 1;
var error = 0;
if($('input[name="txtTitle"]').val() == ''){
error = 1;
alert('Het titel veld is nog leeg');
$('input[name="txtTitle"]').focus();
}
if(error != 1){
$('.content_load_icon').html('<img
src="../../includes/images/layout/load_small.gif" />');
var content =
$('#cke_ckeditor').children().children().children()[3].contentWindow.document.childNodes[1].childNodes[1].innerHTML;
$.ajax({
url: '../../action/ac_productbeheer.php?a=add',
type: 'POST',
data: {txtTitle: $('input[name="txtTitle"]').val(),
txtParentPage: $('select[name="txtParentProduct"]').val(),
txtContent: content, create: true},
success: function(data, textStatus, xhr) {
$('.content_load_icon').html('');
$('.txtContentConsole').html('Product succesvol
opgeslagen!').show().delay(2000).fadeOut(200);
busy = 0;
saved = 1;
window.location =
'../../modules/productbeheer/index.php';
},
error: function(xhr, textStatus, errorThrown) {
$('.content_load_icon').html('');
$('.txtContentConsole').html('Fout bij opslaan!
Probeer het later nog een
keer.').show().delay(2000).fadeOut(200);
busy = 0;
}
});
} else {
error = 0;
busy = 0;
}
}
});
I hope one of you guys/girls can help me with this problem.
Tuesday, 1 October 2013
getSubmittedValue() is coming null jsf
getSubmittedValue() is coming null jsf
I facing one problem in jsf, when i attached to my , as shown below
<h:inputText id="" value="" binding="">
<a4j:support
actionListener="Action_Class.validateUserName"
event="onblur" />
</h:inputText>
As shown in above, when i am tabbing out from field, validateUserName has
to call.it is calling,but when i am trying to get my submitted value as
shown below, null is coming. UIInput input = actionEvent.getParent();
String userName = input.getSubmittedValue(); username is coming as
null.(The submitted value is coming only in IE browser, but in remaining
browsers i am getting null as submitted value). Kindly do needful.
I facing one problem in jsf, when i attached to my , as shown below
<h:inputText id="" value="" binding="">
<a4j:support
actionListener="Action_Class.validateUserName"
event="onblur" />
</h:inputText>
As shown in above, when i am tabbing out from field, validateUserName has
to call.it is calling,but when i am trying to get my submitted value as
shown below, null is coming. UIInput input = actionEvent.getParent();
String userName = input.getSubmittedValue(); username is coming as
null.(The submitted value is coming only in IE browser, but in remaining
browsers i am getting null as submitted value). Kindly do needful.
MySQL Design For High Frequency Billing System
MySQL Design For High Frequency Billing System
I have a feeling I'm gonna get butchered for asking this question, but
here it goes...
I have 5 million daily subscriptions & expect/hope to have 50million in 12
months. I need to renew/bill these very, very quickly. I've tried every
permutation of index & looping I could think of, but its the SELECT
queries are still too slow. Perhaps my mistake is MySQL design, perhaps
its my daemon that uses MySQL, perhaps its simply because I'm using MySQL
- please let me know your thoughts and/or advice. Thanks!
** Subscription Table looks like this **
subscription_id (PK)
subscriber_id
service_id
add_date
current_period_start_date
current_period_end_date
next_bill_date (used to ensure two threads dont grab to bill at same time)
last_successful_bill_date
has_outstanding_balance
** Money-people-owe-me table looks like this *
id
subscription_id (UK)
outstanding_balance
next_bill_date
number_bill_attempts
(a fair amount of people dont always pay, I give them unpaid access for a
bit while I continue trying to bill, eventually I cut off their service
though)
** Billing Daemon looks like this **
Run multi-threaded on multiple machines, here is the master thread:
For each service
stuffToBill[] = SELECT stuff ORDER BY next_bill_date FOR UPDATE LIMIT XXX;
UPDATE stuff SET next_bill_date = later WHERE id IN (stuffToBill[ids])
COMMIT
Put them on a queue for billing workers
Running EXPLAIN shows that I'm using decent indexing, but nitty gritty of
the SQL combined with the fact that I am running the same daemon on
multiple servers makes it lock up / generally overload the I/O queue on my
DBM. DBM is quality hardware.
Thanks again for your advice!
I have a feeling I'm gonna get butchered for asking this question, but
here it goes...
I have 5 million daily subscriptions & expect/hope to have 50million in 12
months. I need to renew/bill these very, very quickly. I've tried every
permutation of index & looping I could think of, but its the SELECT
queries are still too slow. Perhaps my mistake is MySQL design, perhaps
its my daemon that uses MySQL, perhaps its simply because I'm using MySQL
- please let me know your thoughts and/or advice. Thanks!
** Subscription Table looks like this **
subscription_id (PK)
subscriber_id
service_id
add_date
current_period_start_date
current_period_end_date
next_bill_date (used to ensure two threads dont grab to bill at same time)
last_successful_bill_date
has_outstanding_balance
** Money-people-owe-me table looks like this *
id
subscription_id (UK)
outstanding_balance
next_bill_date
number_bill_attempts
(a fair amount of people dont always pay, I give them unpaid access for a
bit while I continue trying to bill, eventually I cut off their service
though)
** Billing Daemon looks like this **
Run multi-threaded on multiple machines, here is the master thread:
For each service
stuffToBill[] = SELECT stuff ORDER BY next_bill_date FOR UPDATE LIMIT XXX;
UPDATE stuff SET next_bill_date = later WHERE id IN (stuffToBill[ids])
COMMIT
Put them on a queue for billing workers
Running EXPLAIN shows that I'm using decent indexing, but nitty gritty of
the SQL combined with the fact that I am running the same daemon on
multiple servers makes it lock up / generally overload the I/O queue on my
DBM. DBM is quality hardware.
Thanks again for your advice!
slow server when page have mysql
slow server when page have mysql
my server now works very fast in non mysql requests , example:
http://download.saqafa.com/
but when it come to more mysql requests it be very slow and take more time
to load , i don't know the reason , my server is I5 with 12 GB rams
example of slow page :
http://www.saqafa.com/article/8434
my server now works very fast in non mysql requests , example:
http://download.saqafa.com/
but when it come to more mysql requests it be very slow and take more time
to load , i don't know the reason , my server is I5 with 12 GB rams
example of slow page :
http://www.saqafa.com/article/8434
Notation confusion in the Wikipedia article on the Law of Large Numbers
Notation confusion in the Wikipedia article on the Law of Large Numbers
In my infamous attempt at mastering (at my humble level) the "art" of
probability and statistical theory, I was reading the Wikipedia article on
the Law of Large Number and got confused by a couple of notations.
1 - mean vs expected value
First it is written:
$\bar X \rightarrow \mu$ for $n \rightarrow \infty$
For me $\mu$ is the "population" mean and not the expected value. The
definition of the law is that the sample mean converges to the random
variable expected value as the sample size approaches infinity (not its
population mean). I realize the population mean and the expected value are
equal but they are not computed the same way and I found this notation
misleading (because it doesn't follow directly the definition). What do
you think?
2 - random variable vs observation
Second it is written:
$\bar X = {1 \over n}(X_1 + X_2 + ... + X_n)$
"where X1, X2, ... is an infinite sequence of i.i.d. integrable random
variables with expected value $E(X1) = E(X2) = ...= \mu$."
Why I am confused is that for me the sample mean is computed as the
average of n observation where the observations are produced by a random
variable X. So it would be for me at least less misleading to use x lower
case (observation, realization) instead of X uppercase. Or is correct here
to use X and if so why?
EDIT: I understand you need to write $E[X_1]$ and can't write $E[x_1]$.
The expected value of an observation wouldn't make much sense. But that
what's the meaning really of $X_n$ in $\bar X = {1 \over n}(X_1 + X_2 +
... + X_n)$. For me a random variable is a function not really a number?
An average of functions?
But I am not an expert so there might be an explanation to both notations?
Thank you.
In my infamous attempt at mastering (at my humble level) the "art" of
probability and statistical theory, I was reading the Wikipedia article on
the Law of Large Number and got confused by a couple of notations.
1 - mean vs expected value
First it is written:
$\bar X \rightarrow \mu$ for $n \rightarrow \infty$
For me $\mu$ is the "population" mean and not the expected value. The
definition of the law is that the sample mean converges to the random
variable expected value as the sample size approaches infinity (not its
population mean). I realize the population mean and the expected value are
equal but they are not computed the same way and I found this notation
misleading (because it doesn't follow directly the definition). What do
you think?
2 - random variable vs observation
Second it is written:
$\bar X = {1 \over n}(X_1 + X_2 + ... + X_n)$
"where X1, X2, ... is an infinite sequence of i.i.d. integrable random
variables with expected value $E(X1) = E(X2) = ...= \mu$."
Why I am confused is that for me the sample mean is computed as the
average of n observation where the observations are produced by a random
variable X. So it would be for me at least less misleading to use x lower
case (observation, realization) instead of X uppercase. Or is correct here
to use X and if so why?
EDIT: I understand you need to write $E[X_1]$ and can't write $E[x_1]$.
The expected value of an observation wouldn't make much sense. But that
what's the meaning really of $X_n$ in $\bar X = {1 \over n}(X_1 + X_2 +
... + X_n)$. For me a random variable is a function not really a number?
An average of functions?
But I am not an expert so there might be an explanation to both notations?
Thank you.
Monday, 30 September 2013
How exactly is Skorohod's Representation Theorem applied here?
How exactly is Skorohod's Representation Theorem applied here?
I have a question about applying the Skorohod Representation Theorem. Let
$(\Omega,\mathcal{F},Q)$ be a probability space and $F_n\subset
\mathbb{R}_+$ such that $\lim_n F_n = \mathbb{R}_+$. Assume we have a
continuous real-valued function $g:\mathbb{R}_+\to\mathbb{R}$ with
$|g(x)|\le C(1+x^p)$ for $p>2$ and a constant $C$. Let $X$ be a random
variable and define $f_n:=g|_{F_n}$ the restriction to $F_n$. $f_n$ has
the property that $\sup_{x\in F_n}\frac{|f_n(x)|}{(1+x^p)}\le n$ (maybe
this is not needed). Since $g$ is continuous we have that for $x_n\ge 0$,
$x\ge 0$ with $x_n\to x$ then $g(x)=\lim_nf_n(x_n)$.
After all we have a tight sequence $(P_n)$ of probability measures given,
hence there is a subsequence again denoted by $(P_n)$ which converges
weakly to a measure $P$. Now using the Skorohod Representation Theorem we
should establish the following equality:
$$E_P[g(X)]=\lim_nE_{P_n}[f_n(X)]$$
where $E_p[\cdot]$ denotes the expectation w.r.t the measure $P$, and
similaryly for $E_{P_n}[\cdot]$ w.r.t the measure $P_n$. How exactly is in
this setting the Skorohod Repesentation Theorem applied?
I have a question about applying the Skorohod Representation Theorem. Let
$(\Omega,\mathcal{F},Q)$ be a probability space and $F_n\subset
\mathbb{R}_+$ such that $\lim_n F_n = \mathbb{R}_+$. Assume we have a
continuous real-valued function $g:\mathbb{R}_+\to\mathbb{R}$ with
$|g(x)|\le C(1+x^p)$ for $p>2$ and a constant $C$. Let $X$ be a random
variable and define $f_n:=g|_{F_n}$ the restriction to $F_n$. $f_n$ has
the property that $\sup_{x\in F_n}\frac{|f_n(x)|}{(1+x^p)}\le n$ (maybe
this is not needed). Since $g$ is continuous we have that for $x_n\ge 0$,
$x\ge 0$ with $x_n\to x$ then $g(x)=\lim_nf_n(x_n)$.
After all we have a tight sequence $(P_n)$ of probability measures given,
hence there is a subsequence again denoted by $(P_n)$ which converges
weakly to a measure $P$. Now using the Skorohod Representation Theorem we
should establish the following equality:
$$E_P[g(X)]=\lim_nE_{P_n}[f_n(X)]$$
where $E_p[\cdot]$ denotes the expectation w.r.t the measure $P$, and
similaryly for $E_{P_n}[\cdot]$ w.r.t the measure $P_n$. How exactly is in
this setting the Skorohod Repesentation Theorem applied?
How to make a fragment be in the exact same way I left it when I return to it from another fragment?
How to make a fragment be in the exact same way I left it when I return to
it from another fragment?
I have a few fragments in my app, but my code opens a new fragment every
time I click the button.
I want to know how can I change this, and make the fragment return to the
exact same state I left it in.
The code im using right now:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragments);
MainActivity fragment = new MainActivity();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.add(R.id.fragment_place, fragment);
transaction.commit();
turnGPSOn();
}
public void onSelectFragment(View view) {
if (view == findViewById(R.id.add))
{
newFragment = new Add();
}
else if (view == findViewById(R.id.map))
{
newFragment = new MainActivity();
}
else
{
newFragment = new Add();
}
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.fragment_place, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
Thanks!
it from another fragment?
I have a few fragments in my app, but my code opens a new fragment every
time I click the button.
I want to know how can I change this, and make the fragment return to the
exact same state I left it in.
The code im using right now:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragments);
MainActivity fragment = new MainActivity();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.add(R.id.fragment_place, fragment);
transaction.commit();
turnGPSOn();
}
public void onSelectFragment(View view) {
if (view == findViewById(R.id.add))
{
newFragment = new Add();
}
else if (view == findViewById(R.id.map))
{
newFragment = new MainActivity();
}
else
{
newFragment = new Add();
}
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.fragment_place, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
Thanks!
Textbox and Select list position
Textbox and Select list position
Project Name :<div style="position:absolute" id="project_list">
<select style='width:220px;height:25px;' class='createNewSelect'
name='list_project_name' id='list_project_name'
onchange='javascript:getProjectName()'><option value='0'>Create New
Project</option><option value=2>new_project</option><option
value=3>new_project</option><option value=5>new_project</option><option
value=8>new_project</option><option value=7>my_project_1</option><option
value=6>my_project</option></select>
</div><input id="project_name" class="createNew" type="text" />
<input type="button" value="Create New" id="getChecked" class="createNew" />
<button value="Cancel" class="createNew" onclick="cancelCreate()"
>Cancel</button>
Above use to display project list or textbox with two button to create new
project. I'm facing problem with their position.
and you can also check here
Project Name :<div style="position:absolute" id="project_list">
<select style='width:220px;height:25px;' class='createNewSelect'
name='list_project_name' id='list_project_name'
onchange='javascript:getProjectName()'><option value='0'>Create New
Project</option><option value=2>new_project</option><option
value=3>new_project</option><option value=5>new_project</option><option
value=8>new_project</option><option value=7>my_project_1</option><option
value=6>my_project</option></select>
</div><input id="project_name" class="createNew" type="text" />
<input type="button" value="Create New" id="getChecked" class="createNew" />
<button value="Cancel" class="createNew" onclick="cancelCreate()"
>Cancel</button>
Above use to display project list or textbox with two button to create new
project. I'm facing problem with their position.
and you can also check here
Sunday, 29 September 2013
I need to convert timestamp to double precision without using EPOCH in postgresql
I need to convert timestamp to double precision without using EPOCH in
postgresql
I need to convert timestamp into string or anything at one place and
convert it back to timestamp at another place. So itried the following.
but i'm not getting a slight difference. When i convert it back to
timestamp last digit gets missing.
SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2013-09-27
13:51:02.809501+05:30'); SELECT TIMESTAMP WITH TIME ZONE 'epoch' +
1380270062809.5 * INTERVAL '1 millisecond'; result is..."2013-09-27
13:51:02.8095+05:30"
postgresql
I need to convert timestamp into string or anything at one place and
convert it back to timestamp at another place. So itried the following.
but i'm not getting a slight difference. When i convert it back to
timestamp last digit gets missing.
SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2013-09-27
13:51:02.809501+05:30'); SELECT TIMESTAMP WITH TIME ZONE 'epoch' +
1380270062809.5 * INTERVAL '1 millisecond'; result is..."2013-09-27
13:51:02.8095+05:30"
Pagination showing more page links than there should be
Pagination showing more page links than there should be
Im using this query:
$sql = "SELECT * FROM {$table} ";
$sql .= "WHERE gallery_name='pancakes' ";
$sql .= "ORDER BY id DESC ";
$sql .= "LIMIT {$per_page} ";
$sql .= "OFFSET {$pagination->offset()}";
$pages = Photograph::find_by_sql($sql);
This is my pagination class:
class Pagination extends DatabaseObject{
public $page;
public $current_page;
public $per_page;
public $total_count;
public function __construct($page=1, $per_page=20, $total_count=0){
$this->current_page = (int)$page;
$this->per_page = (int)$per_page;
$this->total_count = (int)$total_count;
}
public function offset() {
//assuming 20 items per page:
//page 1 has an offset of 0 (1-1) * 20
//page 2 has an offset of 20 (2-1) * 20
//in other words, page 2 starts with item 21
return($this->current_page - 1) * $this->per_page;
}
public function total_pages(){
return ceil($this->total_count/$this->per_page);
}
public function previous_page(){
global $blog;
return $this->current_page - 1;
}
public function next_page(){
global $blog;
return $this->current_page + 1;
}
public function has_previous_page(){
return $this->previous_page() >= 1 ? true : false;
}
public function has_next_page() {
return $this->next_page() <= $this->total_pages() ? true : false;
}
}
$pagination = new Pagination();
This is my pagination function:
public function pagination(){
global $address;
global $selected_page;
global $pagination;
global $page;
$min = max($selected_page - 2, 1);
$max = min($selected_page + 2, $pagination->total_pages());
for($i = $min; $i <= $max; ++$i){
if(static::$table_name == "pages"){
if($i == $this->page){
echo "\n <span class=\"selected_page\">{$i}</span> ";
}else{
echo "\n <a href=" . $address . "{$i}>{$i}</a> ";
}
}elseif(static::$table_name == "cakes"){
if($i == $selected_page){
echo "\n <span class=\"selected_page\">{$i}</span> ";
}else{
echo "\n <a href=" . $address . "{$i}>{$i}</a> ";
}
}
}
}
I wanted to divide my photo gallery into sub-galleries so I added a column
"gallery_name" into the table called "photographs". It worked, but the
pagination still shows the same number of pages as before, I'm guessing
because it still counts all the photos instead of just the ones with the
given name in the gallery_name column. The first few links of the selected
sub-gallery pagination work, depending on the number of photos selected by
the query, and the rest are dead links. How do I get rid of the dead links
in pagination and display just the ones that reflect the values of the
query?
Im using this query:
$sql = "SELECT * FROM {$table} ";
$sql .= "WHERE gallery_name='pancakes' ";
$sql .= "ORDER BY id DESC ";
$sql .= "LIMIT {$per_page} ";
$sql .= "OFFSET {$pagination->offset()}";
$pages = Photograph::find_by_sql($sql);
This is my pagination class:
class Pagination extends DatabaseObject{
public $page;
public $current_page;
public $per_page;
public $total_count;
public function __construct($page=1, $per_page=20, $total_count=0){
$this->current_page = (int)$page;
$this->per_page = (int)$per_page;
$this->total_count = (int)$total_count;
}
public function offset() {
//assuming 20 items per page:
//page 1 has an offset of 0 (1-1) * 20
//page 2 has an offset of 20 (2-1) * 20
//in other words, page 2 starts with item 21
return($this->current_page - 1) * $this->per_page;
}
public function total_pages(){
return ceil($this->total_count/$this->per_page);
}
public function previous_page(){
global $blog;
return $this->current_page - 1;
}
public function next_page(){
global $blog;
return $this->current_page + 1;
}
public function has_previous_page(){
return $this->previous_page() >= 1 ? true : false;
}
public function has_next_page() {
return $this->next_page() <= $this->total_pages() ? true : false;
}
}
$pagination = new Pagination();
This is my pagination function:
public function pagination(){
global $address;
global $selected_page;
global $pagination;
global $page;
$min = max($selected_page - 2, 1);
$max = min($selected_page + 2, $pagination->total_pages());
for($i = $min; $i <= $max; ++$i){
if(static::$table_name == "pages"){
if($i == $this->page){
echo "\n <span class=\"selected_page\">{$i}</span> ";
}else{
echo "\n <a href=" . $address . "{$i}>{$i}</a> ";
}
}elseif(static::$table_name == "cakes"){
if($i == $selected_page){
echo "\n <span class=\"selected_page\">{$i}</span> ";
}else{
echo "\n <a href=" . $address . "{$i}>{$i}</a> ";
}
}
}
}
I wanted to divide my photo gallery into sub-galleries so I added a column
"gallery_name" into the table called "photographs". It worked, but the
pagination still shows the same number of pages as before, I'm guessing
because it still counts all the photos instead of just the ones with the
given name in the gallery_name column. The first few links of the selected
sub-gallery pagination work, depending on the number of photos selected by
the query, and the rest are dead links. How do I get rid of the dead links
in pagination and display just the ones that reflect the values of the
query?
Pipe not working with executable
Pipe not working with executable
I have put together a program that gathers data from an html/php UI and
sends it via a pipe to a Python application (it is one way only - read
from Python script). Up until now I have been running and de-bugging the
code using IDLE, however, now is the time to make the python script
executable so it can be run from the command line. The problem is that
although the pipe works fine when run in IDLE i get a strange response
when running from the command line. The pipe is set up as follows:
pipe_name = 'testpipe'
pipein = os.open(pipe_name, os.O_RDWR)
if not os.path.exists(pipe_name):
os.mkfifo(pipe_name)
I then use the select.select command to detect input on the pipe:
inputdata,outputdata,exceptions = select.select([tcpCliSock,pipein],[],[])
If data is detected on the pipe I read it by:
line = os.read(pipein,BUFSIZ)
The strange thing is that if there is already data on the pipe when the
executable is first run it reads in ok and displays as expected which
suggests the pipe can be read from the executable. However, if there isn't
and I submit data to the pipe via the UI the command window is unable to
read it and returns an empty array and then errors because the rest of the
code can't operate on the array that should be there. I don't really
understand what could be the issue so any clues would be helpful.
I have put together a program that gathers data from an html/php UI and
sends it via a pipe to a Python application (it is one way only - read
from Python script). Up until now I have been running and de-bugging the
code using IDLE, however, now is the time to make the python script
executable so it can be run from the command line. The problem is that
although the pipe works fine when run in IDLE i get a strange response
when running from the command line. The pipe is set up as follows:
pipe_name = 'testpipe'
pipein = os.open(pipe_name, os.O_RDWR)
if not os.path.exists(pipe_name):
os.mkfifo(pipe_name)
I then use the select.select command to detect input on the pipe:
inputdata,outputdata,exceptions = select.select([tcpCliSock,pipein],[],[])
If data is detected on the pipe I read it by:
line = os.read(pipein,BUFSIZ)
The strange thing is that if there is already data on the pipe when the
executable is first run it reads in ok and displays as expected which
suggests the pipe can be read from the executable. However, if there isn't
and I submit data to the pipe via the UI the command window is unable to
read it and returns an empty array and then errors because the rest of the
code can't operate on the array that should be there. I don't really
understand what could be the issue so any clues would be helpful.
Saturday, 28 September 2013
ios app freezes after uitableview search
ios app freezes after uitableview search
I am a beginner to ios development and am having trouble finding the cause
for this issue.
I have a simple app with a Master and DetailView controllers. The Master
View contains an UITableView with a SearchController. Selecting any row on
the tableview will transition to the detailview.
The app freezes when I perform the following sequence
1) Launch app 2) Pull down the search bar 3) Enter text 4) Select a row
from the search results 5) Select back from the detail view
Now the app freezes after the ViewDidLoad method of the MasterView is
loaded. I can't find anything in the system.log.
Here's the code from the MasterViewController
- (void)viewWillAppear:(BOOL)animated {
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0f,
0.0f, 320.0f, 44.0f)];
[self.tableView setContentOffset:CGPointMake(0,40)];
self.tableView.tableHeaderView = self.searchBar;
// Create and configure the search controller
self.searchController = [[UISearchDisplayController alloc]
initWithSearchBar:self.searchBar contentsController:self];
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *months = @"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";
feeds = [months componentsSeparatedByString:@","];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self
action:@selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
self.detailViewController = (DetailViewController
*)[[self.splitViewController.viewControllers lastObject]
topViewController];
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
NSLog(@"numberOfRowsInSection");
if(tableView == self.tableView)
{
return feeds.count;
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like
%@", self.searchBar.text];
self.filteredFeeds = [feeds filteredArrayUsingPredicate:predicate];
return feeds.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
cell.textLabel.text = [feeds objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[UIDevice currentDevice] userInterfaceIdiom] ==
UIUserInterfaceIdiomPad) {
NSDate *object = _objects[indexPath.row];
self.detailViewController.detailItem = object;
}
[self performSegueWithIdentifier: @"showDetail" sender: self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSDate *object = _objects[indexPath.row];
[[segue destinationViewController] setDetailItem:object];
}
}
I have uploaded the entire project at the location below.
https://www.dropbox.com/s/yok9vngzv143npa/search.zip
Any kind of assistance is appreciated.
I am a beginner to ios development and am having trouble finding the cause
for this issue.
I have a simple app with a Master and DetailView controllers. The Master
View contains an UITableView with a SearchController. Selecting any row on
the tableview will transition to the detailview.
The app freezes when I perform the following sequence
1) Launch app 2) Pull down the search bar 3) Enter text 4) Select a row
from the search results 5) Select back from the detail view
Now the app freezes after the ViewDidLoad method of the MasterView is
loaded. I can't find anything in the system.log.
Here's the code from the MasterViewController
- (void)viewWillAppear:(BOOL)animated {
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0f,
0.0f, 320.0f, 44.0f)];
[self.tableView setContentOffset:CGPointMake(0,40)];
self.tableView.tableHeaderView = self.searchBar;
// Create and configure the search controller
self.searchController = [[UISearchDisplayController alloc]
initWithSearchBar:self.searchBar contentsController:self];
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *months = @"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";
feeds = [months componentsSeparatedByString:@","];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self
action:@selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
self.detailViewController = (DetailViewController
*)[[self.splitViewController.viewControllers lastObject]
topViewController];
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
NSLog(@"numberOfRowsInSection");
if(tableView == self.tableView)
{
return feeds.count;
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like
%@", self.searchBar.text];
self.filteredFeeds = [feeds filteredArrayUsingPredicate:predicate];
return feeds.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
cell.textLabel.text = [feeds objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[UIDevice currentDevice] userInterfaceIdiom] ==
UIUserInterfaceIdiomPad) {
NSDate *object = _objects[indexPath.row];
self.detailViewController.detailItem = object;
}
[self performSegueWithIdentifier: @"showDetail" sender: self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSDate *object = _objects[indexPath.row];
[[segue destinationViewController] setDetailItem:object];
}
}
I have uploaded the entire project at the location below.
https://www.dropbox.com/s/yok9vngzv143npa/search.zip
Any kind of assistance is appreciated.
Whats Wrong with My C# Code?
Whats Wrong with My C# Code?
My program needs to:
a. Generate an array of 20 random integers from zero to nine. Search for
the first occurrence, if any, of the number 7, and report its position in
the array.
b. Repeat the computation of part a 1000 times, and for each position in
the array, report the number of times that the first occurrence of a 7 in
the array is at that position
However whenever I run the program I get strange results (different every
time) such as:
No sevens found at any position
1000 sevens found at one position and no sevens found anywhere else
Hundreds of sevens found in 2 positions, and none found anywhere else.
Does anyone have an idea what is wrong with my program?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Week_6_Project_2
{
class Program
{
static int intArrayLength = 20;
static int[] resultsArray = new int[intArrayLength];
public static Array generateRandomArray() {
int[] randomNumberArray = new int[intArrayLength];
Random random = new Random();
int popcounter = 0;
while (popcounter < intArrayLength) {
randomNumberArray[popcounter] = random.Next(0, 10);
popcounter += 1;
}
return randomNumberArray;
}
public static void searchForSevens()
{
int counter = 0;
int[] randomArray = (int[])generateRandomArray();
while (counter < intArrayLength)
{
if (randomArray[counter] == 7)
{
resultsArray[counter] += 1;
counter = intArrayLength;
}
counter += 1;
}
}
static void Main()
{
int searchCounter = 0;
while (searchCounter < 1000)
{
searchForSevens();
searchCounter += 1;
}
int displayCounter = 0;
while (displayCounter < intArrayLength)
{
Console.WriteLine("Number of first occurrence of 7 at position
{0} = {1}", displayCounter, resultsArray[displayCounter]);
displayCounter += 1;
}
Console.ReadLine();
}
}
}
My program needs to:
a. Generate an array of 20 random integers from zero to nine. Search for
the first occurrence, if any, of the number 7, and report its position in
the array.
b. Repeat the computation of part a 1000 times, and for each position in
the array, report the number of times that the first occurrence of a 7 in
the array is at that position
However whenever I run the program I get strange results (different every
time) such as:
No sevens found at any position
1000 sevens found at one position and no sevens found anywhere else
Hundreds of sevens found in 2 positions, and none found anywhere else.
Does anyone have an idea what is wrong with my program?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Week_6_Project_2
{
class Program
{
static int intArrayLength = 20;
static int[] resultsArray = new int[intArrayLength];
public static Array generateRandomArray() {
int[] randomNumberArray = new int[intArrayLength];
Random random = new Random();
int popcounter = 0;
while (popcounter < intArrayLength) {
randomNumberArray[popcounter] = random.Next(0, 10);
popcounter += 1;
}
return randomNumberArray;
}
public static void searchForSevens()
{
int counter = 0;
int[] randomArray = (int[])generateRandomArray();
while (counter < intArrayLength)
{
if (randomArray[counter] == 7)
{
resultsArray[counter] += 1;
counter = intArrayLength;
}
counter += 1;
}
}
static void Main()
{
int searchCounter = 0;
while (searchCounter < 1000)
{
searchForSevens();
searchCounter += 1;
}
int displayCounter = 0;
while (displayCounter < intArrayLength)
{
Console.WriteLine("Number of first occurrence of 7 at position
{0} = {1}", displayCounter, resultsArray[displayCounter]);
displayCounter += 1;
}
Console.ReadLine();
}
}
}
Deleting Backbone.js models with cid
Deleting Backbone.js models with cid
I am trying to delete a model that I create in backbone. I am not trying
to do away with the model itself.
this is what I have: A jasmine unit test to the code first
it("should delete the current Box ", function () {
var myContainer = new App.Container();
var myBox = new App.Box();
myBox.setTitle("The First Box");
expect(myBox.attributes.title).toBeDefined();
**myContainer.deleteBox(myBox);**
expect(myBox.attributes.title).toBeUndefined();
console.log(mySlide);
});
Now the code:
App.Container = Backbone.Model.extend({
defaults: {
type: "1.0",
selectedBox: 0,
boxes: [],
labels: [],
},
deleteBox: function (box) {
this.destroy({
success: function() {
console.log("the box has been removed");
//Array reindexed
}
});
}
});
It does not work. the jasmine unit test fails and I think I have to some
how delete the object at the cid given by backbone. Im not sure how to go
about it. any suggestions?
I am trying to delete a model that I create in backbone. I am not trying
to do away with the model itself.
this is what I have: A jasmine unit test to the code first
it("should delete the current Box ", function () {
var myContainer = new App.Container();
var myBox = new App.Box();
myBox.setTitle("The First Box");
expect(myBox.attributes.title).toBeDefined();
**myContainer.deleteBox(myBox);**
expect(myBox.attributes.title).toBeUndefined();
console.log(mySlide);
});
Now the code:
App.Container = Backbone.Model.extend({
defaults: {
type: "1.0",
selectedBox: 0,
boxes: [],
labels: [],
},
deleteBox: function (box) {
this.destroy({
success: function() {
console.log("the box has been removed");
//Array reindexed
}
});
}
});
It does not work. the jasmine unit test fails and I think I have to some
how delete the object at the cid given by backbone. Im not sure how to go
about it. any suggestions?
How I can fill an activity programatically with elements
How I can fill an activity programatically with elements
my question is not how to fill the screen, actually my question is what is
the best way to do this?. I want to fill an activity with a lot of
imageviews (small), many images as will fit on each screen (resolution).
What do you think that is the best way to do this?
Example
1 Device Another Resolution Device
______________ _______________________________________
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
______________ _______________________________________
I don't know If I explained me well. Thank you.
my question is not how to fill the screen, actually my question is what is
the best way to do this?. I want to fill an activity with a lot of
imageviews (small), many images as will fit on each screen (resolution).
What do you think that is the best way to do this?
Example
1 Device Another Resolution Device
______________ _______________________________________
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
|************| |*************************************|
______________ _______________________________________
I don't know If I explained me well. Thank you.
Friday, 27 September 2013
How to use javascript to communicate with backend code?
How to use javascript to communicate with backend code?
Is it possible to use javascript on a web page to get information from
backend code written in C#?
If this is possible, can I please be provided with some links or searching
terms for my learning? The person I am doing this for wants a straight up
HTML5 page (plus C# backend code), meaning not using ASP.NET models or
having things on .aspx pages, etc. I am by no means a web developer, but I
am really not sure this is possible.
Example of something I might need to do:
// C# code
class BackendProgram {
void backendUpdateWebpage() { // might return a bool instead
// does some calculation to decide if
// element "ShowAndHide" should be visible or not
}
}
...
<!--HTML/Javascript-->
<script>
function updateVisibility() {
// contacts backend code
// sets "ShowAndHide" visibility to "none" or
// block/inline depending on result from backend
}
</script>
<div id="ShowAndHide">
<p>This is an element.<p>
</div>
<script>updateVisibility();</script>
Is it possible to use javascript on a web page to get information from
backend code written in C#?
If this is possible, can I please be provided with some links or searching
terms for my learning? The person I am doing this for wants a straight up
HTML5 page (plus C# backend code), meaning not using ASP.NET models or
having things on .aspx pages, etc. I am by no means a web developer, but I
am really not sure this is possible.
Example of something I might need to do:
// C# code
class BackendProgram {
void backendUpdateWebpage() { // might return a bool instead
// does some calculation to decide if
// element "ShowAndHide" should be visible or not
}
}
...
<!--HTML/Javascript-->
<script>
function updateVisibility() {
// contacts backend code
// sets "ShowAndHide" visibility to "none" or
// block/inline depending on result from backend
}
</script>
<div id="ShowAndHide">
<p>This is an element.<p>
</div>
<script>updateVisibility();</script>
How can I create an array from two models that have different keys in a Rails 3.2 app?
How can I create an array from two models that have different keys in a
Rails 3.2 app?
I want to combine the results of two tables into one array so that I can
sort the array on the term alphabetically.
In my controller:
@defs = []
definitions = Definition.all
definitions.each do |d|
... # set the value of @term and @definition based on conditions
@defs << {:term => @term, :definition => @definition}
end
definitions = Definition2.all
definitions.each do |d|
... # set the value of @term and @definition based on conditions
@defs << {:term => @term, :definition => @definition}
end
Then I was hoping to display each item in the view:
@defs.each do |d|
...
<%= d.term %>
<%= d.definition %>
...
end
But I get the following error.
undefined method `definition' for #<Hash:0x007fb0cf109118>
Thanks for your help.
Rails 3.2 app?
I want to combine the results of two tables into one array so that I can
sort the array on the term alphabetically.
In my controller:
@defs = []
definitions = Definition.all
definitions.each do |d|
... # set the value of @term and @definition based on conditions
@defs << {:term => @term, :definition => @definition}
end
definitions = Definition2.all
definitions.each do |d|
... # set the value of @term and @definition based on conditions
@defs << {:term => @term, :definition => @definition}
end
Then I was hoping to display each item in the view:
@defs.each do |d|
...
<%= d.term %>
<%= d.definition %>
...
end
But I get the following error.
undefined method `definition' for #<Hash:0x007fb0cf109118>
Thanks for your help.
How get parametrs from json?
How get parametrs from json?
Json:
{
"server":9458,
"photo":
"[{\"photo\":\"0d6a293fad:x\",\"sizes\":
[[\"s\",\"9458927\",\"1cb7\",\"PX_xDNKIyYY\",75,64],
[\"m\",\"9458927\",\"1cb8\",\"GvDZr0Mg5zs\",130,111],
[\"x\",\"9458927\",\"1cb9\",\"sRb1abTcecY\",420,360],
[\"o\",\"9458927\",\"1cba\",\"J0WLr9heJ64\",130,111],
[\"p\",\"9458927\",\"1cbb\",\"yb3kCdI-Mlw\",200,171],
[\"q\",\"9458927\",\"1cbc\",\"XiS0fMy-QqI\",320,274],
[\"r\",\"9458927\",\"1cbd\",\"pU4VFIPRU0k\",420,360]],
\"kid\":\"7bf1820e725a4a9baea4db56472d76b4\"}]",
"hash":"f030356e0d096078dfe11b706289b80a"
}
I would like get parametrs server and photo[photo]
for this i use:
var Server = data.server;
var Photo = data.photo;
console.log(Server);
console.log(Photo);
but in concole i get undefined
Than i use code:
var Server = data.response.server;
var Photo = data.response.photo;
console.log(Server);
console.log(Photo);
But now in console i see:
Uncaught TypeError: Cannot read property 'server' of undefined
Why i get errors and how get parametrs?
Json:
{
"server":9458,
"photo":
"[{\"photo\":\"0d6a293fad:x\",\"sizes\":
[[\"s\",\"9458927\",\"1cb7\",\"PX_xDNKIyYY\",75,64],
[\"m\",\"9458927\",\"1cb8\",\"GvDZr0Mg5zs\",130,111],
[\"x\",\"9458927\",\"1cb9\",\"sRb1abTcecY\",420,360],
[\"o\",\"9458927\",\"1cba\",\"J0WLr9heJ64\",130,111],
[\"p\",\"9458927\",\"1cbb\",\"yb3kCdI-Mlw\",200,171],
[\"q\",\"9458927\",\"1cbc\",\"XiS0fMy-QqI\",320,274],
[\"r\",\"9458927\",\"1cbd\",\"pU4VFIPRU0k\",420,360]],
\"kid\":\"7bf1820e725a4a9baea4db56472d76b4\"}]",
"hash":"f030356e0d096078dfe11b706289b80a"
}
I would like get parametrs server and photo[photo]
for this i use:
var Server = data.server;
var Photo = data.photo;
console.log(Server);
console.log(Photo);
but in concole i get undefined
Than i use code:
var Server = data.response.server;
var Photo = data.response.photo;
console.log(Server);
console.log(Photo);
But now in console i see:
Uncaught TypeError: Cannot read property 'server' of undefined
Why i get errors and how get parametrs?
Android SOAP wsdl
Android SOAP wsdl
I'm trying to connect to a Webservice from SOAP. I developed the SOAP
Webservice in PHP and it's working fine (tried in Visual Studio).
First of all, this is the error:
09-27 06:28:07.724: E/AndroidRuntime(2057): FATAL EXCEPTION: main 09-27
06:28:07.724: E/AndroidRuntime(2057): java.lang.RuntimeException: Unable
to start activity
ComponentInfo{com.example.FirstExample/com.example.inforlider.CategoriesActivity}:
android.os.NetworkOnMainThreadException 09-27 06:28:07.724:
The full error you can view here: http://pastebin.com/cRQ66vrj
And this is my code in Java:
private final String NAMESPACE = "http://10.0.0.20/soap/test_wsdl";
private final String URL = "http://10.0.0.20/info_send/encode.php?wsdl";
private final String SOAP_ACTION =
"http://10.0.0.20/info_send/encode.php/select_data";
private final String METHOD_NAME = "select_data";
private String Webresponse = "";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new
SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response;
response = (SoapPrimitive)envelope.getResponse();
Webresponse = response.toString();
} catch (SoapFault e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
Log.e("VALUE: ", Webresponse);
I've been following several tutorials, but none of them adapt to my needs.
So I'm trying to create a method which does what I want. Also, I added to
Manifest:
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"/>
What Am I doing wrong? Thanks.
I'm trying to connect to a Webservice from SOAP. I developed the SOAP
Webservice in PHP and it's working fine (tried in Visual Studio).
First of all, this is the error:
09-27 06:28:07.724: E/AndroidRuntime(2057): FATAL EXCEPTION: main 09-27
06:28:07.724: E/AndroidRuntime(2057): java.lang.RuntimeException: Unable
to start activity
ComponentInfo{com.example.FirstExample/com.example.inforlider.CategoriesActivity}:
android.os.NetworkOnMainThreadException 09-27 06:28:07.724:
The full error you can view here: http://pastebin.com/cRQ66vrj
And this is my code in Java:
private final String NAMESPACE = "http://10.0.0.20/soap/test_wsdl";
private final String URL = "http://10.0.0.20/info_send/encode.php?wsdl";
private final String SOAP_ACTION =
"http://10.0.0.20/info_send/encode.php/select_data";
private final String METHOD_NAME = "select_data";
private String Webresponse = "";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new
SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response;
response = (SoapPrimitive)envelope.getResponse();
Webresponse = response.toString();
} catch (SoapFault e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
Log.e("VALUE: ", Webresponse);
I've been following several tutorials, but none of them adapt to my needs.
So I'm trying to create a method which does what I want. Also, I added to
Manifest:
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"/>
What Am I doing wrong? Thanks.
Thursday, 26 September 2013
Salesforce trigger to update a field based on a picklist value on a visualforce page
Salesforce trigger to update a field based on a picklist value on a
visualforce page
I'm trying to find a way to have a trigger update a picklist field based
on a picklist selection from another field. I want the trigger to update
on the insert of the record.
For example, I have a field called Address__c that is a picklist field and
I want the trigger to select the appropriate location based on the address
selected.
Address_c 123 Main Street selected, updates Location_c "Main St."
Address_c 321 Elm Street selected, updates Location_c "Elm St"
I've done an extensive search on this topic but haven't found anything
that will update a picklist field from a picklist. Any suggestions?
visualforce page
I'm trying to find a way to have a trigger update a picklist field based
on a picklist selection from another field. I want the trigger to update
on the insert of the record.
For example, I have a field called Address__c that is a picklist field and
I want the trigger to select the appropriate location based on the address
selected.
Address_c 123 Main Street selected, updates Location_c "Main St."
Address_c 321 Elm Street selected, updates Location_c "Elm St"
I've done an extensive search on this topic but haven't found anything
that will update a picklist field from a picklist. Any suggestions?
Wednesday, 25 September 2013
Substr from character until character php
Substr from character until character php
I have a problem is how substring from character until character in php.
I try this :
<?php
$str = "I love my family";
echo substr($str, 'm', strpos($str, 'y'));
?>
It will show error that :
A PHP Error was encountered
Severity: Warning
Message: substr() expects parameter 2 to be long, string given
Filename: pos_system/sale_detail.php
Line Number: 13
What I need is result : my family
I have a problem is how substring from character until character in php.
I try this :
<?php
$str = "I love my family";
echo substr($str, 'm', strpos($str, 'y'));
?>
It will show error that :
A PHP Error was encountered
Severity: Warning
Message: substr() expects parameter 2 to be long, string given
Filename: pos_system/sale_detail.php
Line Number: 13
What I need is result : my family
Thursday, 19 September 2013
Reading and writing files in order - Python
Reading and writing files in order - Python
Sorry Quite new to python as a language.
So I have 5 files lets say. item1.txt, item2.txt, item3.txt, item4.txt and
item5.txt. I am trying to call on the directory so that it picks out the
first file (item1.txt) and print its content, then when I call on that
function again (item2.txt) and its content within the file is printed...
then (item3.txt) and then (item4.txt).
The order is important and the system must know what file has been printed
so that the next file in line can print after the first eg. the content of
item1.txt prints first then item2.txt.
Trying to use:
for infile in sorted(glob.glob('*.txt')):
print "Current File Being Processed is: " + infile
But the problem is the directory needs to be added and the system needs to
know what file and its content was printed before it.
Sorry if this was confusing.
Help appreciated.
Sorry Quite new to python as a language.
So I have 5 files lets say. item1.txt, item2.txt, item3.txt, item4.txt and
item5.txt. I am trying to call on the directory so that it picks out the
first file (item1.txt) and print its content, then when I call on that
function again (item2.txt) and its content within the file is printed...
then (item3.txt) and then (item4.txt).
The order is important and the system must know what file has been printed
so that the next file in line can print after the first eg. the content of
item1.txt prints first then item2.txt.
Trying to use:
for infile in sorted(glob.glob('*.txt')):
print "Current File Being Processed is: " + infile
But the problem is the directory needs to be added and the system needs to
know what file and its content was printed before it.
Sorry if this was confusing.
Help appreciated.
ideas for service acount name?
ideas for service acount name?
I am trying to setup a service account for our build automation,i am
trying find a suitable service account name with jumbling the following
words,does anyone have any ideas?
CN(connectivity) ,BT(Bluetooth),FM,NFC(near field communication)
I am trying to setup a service account for our build automation,i am
trying find a suitable service account name with jumbling the following
words,does anyone have any ideas?
CN(connectivity) ,BT(Bluetooth),FM,NFC(near field communication)
RBL lookup for IP on multiple servers
RBL lookup for IP on multiple servers
Does anyone know how to check an IP if is blacklisted (RBL) on multiple
servers? Ex: b.barracudacentral.org
Should it be some DNS query for that?
I tried with IP.b.barracudacentral.org but didn't work.
Does anyone know how to check an IP if is blacklisted (RBL) on multiple
servers? Ex: b.barracudacentral.org
Should it be some DNS query for that?
I tried with IP.b.barracudacentral.org but didn't work.
PHP exponential growth by certain factor in given steps
PHP exponential growth by certain factor in given steps
I can't figure out how to do this in PHP.
What I have is:
$loops=10; $factor=5; $start=20; $end=80;
So I want to start the loop at 20 and reach the exact number 80 by doing
10 loops and the difference between the output-number per loop should
somehow be influenced by the factor 5 or whatever number. So all together
these numbers would be an exponential curve.
Thanks
I can't figure out how to do this in PHP.
What I have is:
$loops=10; $factor=5; $start=20; $end=80;
So I want to start the loop at 20 and reach the exact number 80 by doing
10 loops and the difference between the output-number per loop should
somehow be influenced by the factor 5 or whatever number. So all together
these numbers would be an exponential curve.
Thanks
Interface-level isolation
Interface-level isolation
In my console application I have the class that incapsulates performing
long-continued work and I need show the progress to user. Do I need put
into object of this class a delegate for interaction with console or to
write from class right to screen is ok from the standpoint of application
structure?
In my console application I have the class that incapsulates performing
long-continued work and I need show the progress to user. Do I need put
into object of this class a delegate for interaction with console or to
write from class right to screen is ok from the standpoint of application
structure?
Error occurred when changing the database name
Error occurred when changing the database name
I needed to change my database name so i executed this query
So first i just right clicked on the database and selected the option Rename
It showed a dialogue box as
TITLE: Microsoft SQL Server Management Studio
Unable to rename Faculty. (ObjectExplorer)
ADDITIONAL INFORMATION:
Rename failed for Database 'Project'. (Microsoft.SqlServer.Smo)
For help, click:
http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.0.1600.22+((SQL_PreRelease).080709-1414+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Rename+Database&LinkId=20476
An exception occurred while executing a Transact-SQL statement or batch.
(Microsoft.SqlServer.ConnectionInfo)
Database 'Project' is in transition. Try the statement later. (Microsoft
SQL Server, Error: 952)
For help, click:
http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.00.1600&EvtSrc=MSSQLServer&EvtID=952&LinkId=20476
BUTTONS:
OK
Then i executed this query ALTER DATABASE [Project] MODIFY NAME = [Faculty]
But its giving an error as Msg 952, Level 16, State 1, Line 1 Database
'Project' is in transition. Try the statement later.
Is there any other ways that i can change my name.?
I needed to change my database name so i executed this query
So first i just right clicked on the database and selected the option Rename
It showed a dialogue box as
TITLE: Microsoft SQL Server Management Studio
Unable to rename Faculty. (ObjectExplorer)
ADDITIONAL INFORMATION:
Rename failed for Database 'Project'. (Microsoft.SqlServer.Smo)
For help, click:
http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.0.1600.22+((SQL_PreRelease).080709-1414+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Rename+Database&LinkId=20476
An exception occurred while executing a Transact-SQL statement or batch.
(Microsoft.SqlServer.ConnectionInfo)
Database 'Project' is in transition. Try the statement later. (Microsoft
SQL Server, Error: 952)
For help, click:
http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.00.1600&EvtSrc=MSSQLServer&EvtID=952&LinkId=20476
BUTTONS:
OK
Then i executed this query ALTER DATABASE [Project] MODIFY NAME = [Faculty]
But its giving an error as Msg 952, Level 16, State 1, Line 1 Database
'Project' is in transition. Try the statement later.
Is there any other ways that i can change my name.?
Can any of my consumer take the messages from queue?
Can any of my consumer take the messages from queue?
I am developing an app. and I am using activemq. Is there any way to do
that one producer always send messages to one broker but on the opposite
side there 3 consumers.Each consumer listens broker and can take any of
message from queue.Is this possible?
I am using activemq for writing my app. logs to db.As u know writing logs
to db is time taking process.That's why consumer is more and more slow
than producer.For ex. I send 100.000 message(huge objects).Producer
finishes sending messages in 20 mins.But When the producer finished,
consumer has finished 4.000 message processing yet.
I am developing an app. and I am using activemq. Is there any way to do
that one producer always send messages to one broker but on the opposite
side there 3 consumers.Each consumer listens broker and can take any of
message from queue.Is this possible?
I am using activemq for writing my app. logs to db.As u know writing logs
to db is time taking process.That's why consumer is more and more slow
than producer.For ex. I send 100.000 message(huge objects).Producer
finishes sending messages in 20 mins.But When the producer finished,
consumer has finished 4.000 message processing yet.
Wednesday, 18 September 2013
Warn against all unreported exceptions (including exceptions which super classes of declared exceptions)
Warn against all unreported exceptions (including exceptions which super
classes of declared exceptions)
Consider the following scenario
public class A extends Throwable {}
public class B extends A {}
public class C
{
public void f() throws A, B
{
// Some condition
throw new A();
// Some condition
throw new B();
}
void g()
{
f();
}
}
With the above code, the compiler will warn against not catching (or not
declaring as throws)
C.java:17: unreported exception A; must be caught or declared to be thrown
f();
^
If I fix this with changing g to
void g() throws A
then I get no more warnings (B gets implicitly caught by catching A)
Is there a way to make the compiler report all uncaught exceptions
including the base class ones (like B here).
One way is to change g() and declare it as
public void f() throws B, A
In which case, the compiler will first report B & once I add B to the
throw spec of g, it will report A.
But this is painful because
This is a 2 step process
I may not have control of function f to change it's throw specs.
Is there a better way to make compiler report all exceptions?
classes of declared exceptions)
Consider the following scenario
public class A extends Throwable {}
public class B extends A {}
public class C
{
public void f() throws A, B
{
// Some condition
throw new A();
// Some condition
throw new B();
}
void g()
{
f();
}
}
With the above code, the compiler will warn against not catching (or not
declaring as throws)
C.java:17: unreported exception A; must be caught or declared to be thrown
f();
^
If I fix this with changing g to
void g() throws A
then I get no more warnings (B gets implicitly caught by catching A)
Is there a way to make the compiler report all uncaught exceptions
including the base class ones (like B here).
One way is to change g() and declare it as
public void f() throws B, A
In which case, the compiler will first report B & once I add B to the
throw spec of g, it will report A.
But this is painful because
This is a 2 step process
I may not have control of function f to change it's throw specs.
Is there a better way to make compiler report all exceptions?
Unicode charactersitcs don't work
Unicode charactersitcs don't work
My unicode charactersitcs don't work for Google Chrome and Safari. Here is
the site I am working on, any help? The unicode works on Firefox but not
on google chrome and
http://floboating.com
My unicode charactersitcs don't work for Google Chrome and Safari. Here is
the site I am working on, any help? The unicode works on Firefox but not
on google chrome and
http://floboating.com
asset:precompile - incompatible encoding regexp match (ASCII-8BIT regexp with UTF-8 string)
asset:precompile - incompatible encoding regexp match (ASCII-8BIT regexp
with UTF-8 string)
Getting a weird error when trying to deploy a Rails app:
...
* executing "cd -- /rails/myapp/releases/20130919002235 &&
RAILS_ENV=production RAILS_GROUPS=assets bundle exec rake
assets:precompile"
[persephone] executing command
...
** [out :: persephone] rake aborted!
** [out :: persephone] Caught Encoding::CompatibilityError at
'["ok","(function() {': incompatible encoding regexp match (ASCII-8BIT
regexp with UTF-8 string)
** [out :: persephone] (in
/rails/myapp/releases/20130919002235/app/assets/javascripts/disk_files.js.coffee)
...
Thing is there's no regex patterns in that file.
I do have a few lines that contain backslashes in my coffeescript that
might be confusing the parser, but I don't believe this will be the
problem because .coffee should be compiled before .js:
#/app/assets/javascripts/disk_files.js.coffee
...
$('.hover-folder').hover \
(-> $(@).find('.show-on-hover').show()), \
(-> $(@).find('.show-on-hover').hide())
...
Anyone have any thoughts or know how to troubleshoot this?
with UTF-8 string)
Getting a weird error when trying to deploy a Rails app:
...
* executing "cd -- /rails/myapp/releases/20130919002235 &&
RAILS_ENV=production RAILS_GROUPS=assets bundle exec rake
assets:precompile"
[persephone] executing command
...
** [out :: persephone] rake aborted!
** [out :: persephone] Caught Encoding::CompatibilityError at
'["ok","(function() {': incompatible encoding regexp match (ASCII-8BIT
regexp with UTF-8 string)
** [out :: persephone] (in
/rails/myapp/releases/20130919002235/app/assets/javascripts/disk_files.js.coffee)
...
Thing is there's no regex patterns in that file.
I do have a few lines that contain backslashes in my coffeescript that
might be confusing the parser, but I don't believe this will be the
problem because .coffee should be compiled before .js:
#/app/assets/javascripts/disk_files.js.coffee
...
$('.hover-folder').hover \
(-> $(@).find('.show-on-hover').show()), \
(-> $(@).find('.show-on-hover').hide())
...
Anyone have any thoughts or know how to troubleshoot this?
How can I make the image change based on the domain name visited? Using location.hostname
How can I make the image change based on the domain name visited? Using
location.hostname
I have one website and two domain names. I want image "A" to appear if the
visitor goes to a page on www.SampleSiteA.com but image "B" should appear
if on a page from www.SampleSiteB.com.
Unfortunately the result of my code below is blank, with no image
appearing at all. Any ideas?
content for file: welcome.html
<html>
<head>
<script src="resources/js/domain.js" type="text/javascript"></script>
</head>
<body>
<div class="welcomepic"></div>
</body>
</html>
Content for file: styles.css
.picForA{
background-image: url('../img/A.png');
}
.picForB{
background-image: url('../img/B.png');
}
.welcomepic{
background-position:left center;
background-repeat: no-repeat;
padding-left:160px;
width:225px;
float:left;
height:100px;
display: block;
}
Content of file: domain.js
function welcomepic() {
if (location.hostname == 'www.SampleSiteA.com') {
$('.welcomepic').addClass('picForA');
} else {
$('.welcomepic').addClass('picForB');
}
}
location.hostname
I have one website and two domain names. I want image "A" to appear if the
visitor goes to a page on www.SampleSiteA.com but image "B" should appear
if on a page from www.SampleSiteB.com.
Unfortunately the result of my code below is blank, with no image
appearing at all. Any ideas?
content for file: welcome.html
<html>
<head>
<script src="resources/js/domain.js" type="text/javascript"></script>
</head>
<body>
<div class="welcomepic"></div>
</body>
</html>
Content for file: styles.css
.picForA{
background-image: url('../img/A.png');
}
.picForB{
background-image: url('../img/B.png');
}
.welcomepic{
background-position:left center;
background-repeat: no-repeat;
padding-left:160px;
width:225px;
float:left;
height:100px;
display: block;
}
Content of file: domain.js
function welcomepic() {
if (location.hostname == 'www.SampleSiteA.com') {
$('.welcomepic').addClass('picForA');
} else {
$('.welcomepic').addClass('picForB');
}
}
How do you return a copy from a static member function?
How do you return a copy from a static member function?
What's wrong with my static topStock method? It takes in a reference to
Stock s and Stock t. Shouldn't it return a copy of s or t?
error: expected primary-expression before '.' token|
#include <iostream>
using namespace std;
class Stock {
public:
Stock() : x(0){ }
Stock(int val) : x(val){}
void display() const;
static Stock topStock(const Stock& s, const Stock& t) {
if (s.x > t.x)
return s;
else
return t;
}
int x;
};
void Stock::display() const
{
std::cout << this->x;
}
int main()
{
Stock s(9);
Stock y(8);
Stock z = Stock.topStock(s, y);
return 0;
}
What's wrong with my static topStock method? It takes in a reference to
Stock s and Stock t. Shouldn't it return a copy of s or t?
error: expected primary-expression before '.' token|
#include <iostream>
using namespace std;
class Stock {
public:
Stock() : x(0){ }
Stock(int val) : x(val){}
void display() const;
static Stock topStock(const Stock& s, const Stock& t) {
if (s.x > t.x)
return s;
else
return t;
}
int x;
};
void Stock::display() const
{
std::cout << this->x;
}
int main()
{
Stock s(9);
Stock y(8);
Stock z = Stock.topStock(s, y);
return 0;
}
Java JQuery javascript Galleria IO
Java JQuery javascript Galleria IO
i have a serie of galleries using Galleria IO plugin over JQuery using Zk
Framework i load the galleries when i enter fullscreen mode everything is
smoothly the problem arises when i reload the galleria using the same code
when i load the galleria the first time. and when i click on the galleria
the galleria enters in fullscreen mode but the size of the galleria is the
same in the normal view and the sizes of the images is the same as the
normal view this issue is in Chrome in Mozilla works perfect...
here is the code i am using to enter full screen mode..
Galleria.run('#galleriaID',{extend:function()
{
var
gallery=this;gallery.attachKeyboard({left:gallery.prev,right:gallery.next,});
$('#fullScreenMode').click(function(event)
{
event.preventDefault();
gallery.enterFullscreen();
});
}});
i hope somebody can help me
i have a serie of galleries using Galleria IO plugin over JQuery using Zk
Framework i load the galleries when i enter fullscreen mode everything is
smoothly the problem arises when i reload the galleria using the same code
when i load the galleria the first time. and when i click on the galleria
the galleria enters in fullscreen mode but the size of the galleria is the
same in the normal view and the sizes of the images is the same as the
normal view this issue is in Chrome in Mozilla works perfect...
here is the code i am using to enter full screen mode..
Galleria.run('#galleriaID',{extend:function()
{
var
gallery=this;gallery.attachKeyboard({left:gallery.prev,right:gallery.next,});
$('#fullScreenMode').click(function(event)
{
event.preventDefault();
gallery.enterFullscreen();
});
}});
i hope somebody can help me
How to show tooltips in struts2-jquery pie charts
How to show tooltips in struts2-jquery pie charts
I am implementing struts2 Jquery pie chart. I don't know how to show the
tooltip while mouse over on the struts2-jquery pie chart.
Thanks in advance
I am implementing struts2 Jquery pie chart. I don't know how to show the
tooltip while mouse over on the struts2-jquery pie chart.
Thanks in advance
celerybeat set to crontab(day_of_month=1) sends task multiple times in a month
celerybeat set to crontab(day_of_month=1) sends task multiple times in a
month
I have this task which is set to crontab(day_of_month=1). But then when it
perform the tasks in continues to send task minutely which is supposed to
perform once.
from my tasks.py
from celery.task.schedules import crontab
@periodic_task(run_every=crontab(day_of_month=1))
def Sample():
...
Am I missing something?
month
I have this task which is set to crontab(day_of_month=1). But then when it
perform the tasks in continues to send task minutely which is supposed to
perform once.
from my tasks.py
from celery.task.schedules import crontab
@periodic_task(run_every=crontab(day_of_month=1))
def Sample():
...
Am I missing something?
How to create a user account with specific permissions
How to create a user account with specific permissions
I want to create unix user account with specific perms. This user, can
install software, but can't remove, and when the user logs on, root
receives a notification in the mail. It is possible?
I want to create unix user account with specific perms. This user, can
install software, but can't remove, and when the user logs on, root
receives a notification in the mail. It is possible?
Tuesday, 17 September 2013
Separating Digits from a Phone Number
Separating Digits from a Phone Number
I have a problem from my AP Java class that I'm not able to figure out.
Here it is:
Pull Phone Number Apart Write a program that: Prompts the user for their
phone number (no dashes), displays the phone number, the area code, the
middle three digits, and the last four digits.
Remember, the greatest allowable value for an integer number is
2,147,483,647, so you cannot do a 262 number
And here's my code:
import java.util.Scanner; public class PhoneNumber {
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
System.out.println("Enter your phone number");
int number = input.nextInt();
int digit1 = number / 10000000000;
digit1 = digit1 % 1000000000;
int digit2 = number / 10000000000;
digit2 = digit2 % 1000000000;
int digit3 = number / 10000000000;
digit3 = digit3 % 1000000000;
int digit4 = number / 1000000000;
digit4 = digit4 % 1000000000;
int digit5 = number / 10000000000;
digit5 = digit5 % 1000000000;
int digit6 = number / 1000000000;
digit6 = digit6 % 100000000;
int digit7 = number / 100000000;
digit7 = digit7 % 10000000;
int digit8 = number / 100000000;
digit8 = digit8 % 10000000;
int digit9 = number / 10000000;
digit9 = digit9 % 1000000;
int digit10 = number / 1000000;
digit10 = digit10 % 100000;
System.out.println("Phone number = " + number);
System.out.println("Area code = " + digit1 + digit2 + digit3);
System.out.println("Middle digits = " + digit4 + digit5 + digit6);
System.out.println("Last four digits = " + digit7 + digit8 + digit9);
}
}
Here is the error I'm getting: The literal 10000000000 of type int is out
of range
Can anyone help me fix this? Thanks in advance! :)
I have a problem from my AP Java class that I'm not able to figure out.
Here it is:
Pull Phone Number Apart Write a program that: Prompts the user for their
phone number (no dashes), displays the phone number, the area code, the
middle three digits, and the last four digits.
Remember, the greatest allowable value for an integer number is
2,147,483,647, so you cannot do a 262 number
And here's my code:
import java.util.Scanner; public class PhoneNumber {
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
System.out.println("Enter your phone number");
int number = input.nextInt();
int digit1 = number / 10000000000;
digit1 = digit1 % 1000000000;
int digit2 = number / 10000000000;
digit2 = digit2 % 1000000000;
int digit3 = number / 10000000000;
digit3 = digit3 % 1000000000;
int digit4 = number / 1000000000;
digit4 = digit4 % 1000000000;
int digit5 = number / 10000000000;
digit5 = digit5 % 1000000000;
int digit6 = number / 1000000000;
digit6 = digit6 % 100000000;
int digit7 = number / 100000000;
digit7 = digit7 % 10000000;
int digit8 = number / 100000000;
digit8 = digit8 % 10000000;
int digit9 = number / 10000000;
digit9 = digit9 % 1000000;
int digit10 = number / 1000000;
digit10 = digit10 % 100000;
System.out.println("Phone number = " + number);
System.out.println("Area code = " + digit1 + digit2 + digit3);
System.out.println("Middle digits = " + digit4 + digit5 + digit6);
System.out.println("Last four digits = " + digit7 + digit8 + digit9);
}
}
Here is the error I'm getting: The literal 10000000000 of type int is out
of range
Can anyone help me fix this? Thanks in advance! :)
BCP IN getting failed in SQL SERVER 2008
BCP IN getting failed in SQL SERVER 2008
While trying to BCP IN from text to table, I am facing below mentioned error:
Starting copy...
SQLState = 22005, NativeError = 0
Error = [Microsoft][SQL Server Native Client 10.0]Invalid character value
for cast specification
SQLState = S1000, NativeError = 0
Error = [Microsoft][SQL Server Native Client 10.0]Unexpected EOF
encountered in BCP data-file
0 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.) Total : 47
Format file: Please find the format file here
Input File: Please find the input file here
Table Structure:
CREATE TABLE [dbo].[Insert_record_mpr](
[RPT_DT] [date] NOT NULL,
[RECORD_TYPE] [char](1) NOT NULL,
[MCO_CONTRACT] [char](5) NOT NULL,
[PBP_ID] [char](3) NOT NULL,
[PLAN_SEGMENT_ID] [char](3) NOT NULL,
[HICN] [char](12) NOT NULL,
[LAST_NAME] [char](7) NOT NULL,
[FIRST_INITIAL] [char](1) NOT NULL,
[SEX] [char](1) NOT NULL,
[BIRTH_DT] [date] NOT NULL,
[PAYMENT_OPTION] [char](3) NOT NULL,
[FILLER1] [char](1) NOT NULL,
[PERIOD_START_DT] [date] NOT NULL,
[PERIOD_END_DT] [date] NOT NULL,
[NUMBER_OF_MONTHS] [int] NOT NULL,
[PARTC_PREMIUMS] [money] NOT NULL,
[PARTD_PREMIUMS] [money] NOT NULL,
[PARTD_LEP] [money] NOT NULL,
[FILLER2] [char](80) NOT NULL,
[PRCS_STS] [char](5) NULL,
[TOTAL_PREMIUM] [money] NULL,
[PREMIUM_PER_MONTH] [money] NULL
) ON [PRIMARY]
While trying to BCP IN from text to table, I am facing below mentioned error:
Starting copy...
SQLState = 22005, NativeError = 0
Error = [Microsoft][SQL Server Native Client 10.0]Invalid character value
for cast specification
SQLState = S1000, NativeError = 0
Error = [Microsoft][SQL Server Native Client 10.0]Unexpected EOF
encountered in BCP data-file
0 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.) Total : 47
Format file: Please find the format file here
Input File: Please find the input file here
Table Structure:
CREATE TABLE [dbo].[Insert_record_mpr](
[RPT_DT] [date] NOT NULL,
[RECORD_TYPE] [char](1) NOT NULL,
[MCO_CONTRACT] [char](5) NOT NULL,
[PBP_ID] [char](3) NOT NULL,
[PLAN_SEGMENT_ID] [char](3) NOT NULL,
[HICN] [char](12) NOT NULL,
[LAST_NAME] [char](7) NOT NULL,
[FIRST_INITIAL] [char](1) NOT NULL,
[SEX] [char](1) NOT NULL,
[BIRTH_DT] [date] NOT NULL,
[PAYMENT_OPTION] [char](3) NOT NULL,
[FILLER1] [char](1) NOT NULL,
[PERIOD_START_DT] [date] NOT NULL,
[PERIOD_END_DT] [date] NOT NULL,
[NUMBER_OF_MONTHS] [int] NOT NULL,
[PARTC_PREMIUMS] [money] NOT NULL,
[PARTD_PREMIUMS] [money] NOT NULL,
[PARTD_LEP] [money] NOT NULL,
[FILLER2] [char](80) NOT NULL,
[PRCS_STS] [char](5) NULL,
[TOTAL_PREMIUM] [money] NULL,
[PREMIUM_PER_MONTH] [money] NULL
) ON [PRIMARY]
'position: fixed' won't let me scroll. 'position: relative' won't stretch the div. Which to use/how to fix?
'position: fixed' won't let me scroll. 'position: relative' won't stretch
the div. Which to use/how to fix?
thanks for helping out. I have a site with a container div that I'd like
to stretch to the bottom of the page. Using position: fixed I'm able to
achieve this, but the footer text on the bottom is cutoff and you are
unable to scroll down.
Using position: relative I'm able to scroll, but the container div does
not stretch to the bottom of the page.
My code is as follows:
<div class="container">
<div class="header"></div>
<div class="body">
content content content
</div>
<div class="footer"></div>
</div>
And the CSS:
.container {
position: relative;
bottom: 0;
top: 0;
left: 50%;
margin-left: -480px;
width: 960px;
height: auto;
background-color: #1b1a1a;
}
.body {
width: 703px;
min-height: 340px;
margin: auto;
background-color: #f2f2f2;
padding: 20px;
overflow: hidden;
}
the div. Which to use/how to fix?
thanks for helping out. I have a site with a container div that I'd like
to stretch to the bottom of the page. Using position: fixed I'm able to
achieve this, but the footer text on the bottom is cutoff and you are
unable to scroll down.
Using position: relative I'm able to scroll, but the container div does
not stretch to the bottom of the page.
My code is as follows:
<div class="container">
<div class="header"></div>
<div class="body">
content content content
</div>
<div class="footer"></div>
</div>
And the CSS:
.container {
position: relative;
bottom: 0;
top: 0;
left: 50%;
margin-left: -480px;
width: 960px;
height: auto;
background-color: #1b1a1a;
}
.body {
width: 703px;
min-height: 340px;
margin: auto;
background-color: #f2f2f2;
padding: 20px;
overflow: hidden;
}
inline-block anchor tags out of place can someone tell me why?
inline-block anchor tags out of place can someone tell me why?
building a new site, and working on a news ticker, it has hash marks below
it for navigation. The hash marks reside in an absolute div at the bottom
of the ticker module. Inside the div are the anchor tags and some spacers,
they are renderring below where they should and I cant seem to identify
why, can someone take a look and help me out?
http://race.3drexstaging.com/Home is the link.
Thanks for any help
building a new site, and working on a news ticker, it has hash marks below
it for navigation. The hash marks reside in an absolute div at the bottom
of the ticker module. Inside the div are the anchor tags and some spacers,
they are renderring below where they should and I cant seem to identify
why, can someone take a look and help me out?
http://race.3drexstaging.com/Home is the link.
Thanks for any help
In CSS is .a.b different than .a .b?
In CSS is .a.b different than .a .b?
In my css file is .a.b different than .a .b?
It's a simple question but it's always annoyed me. I tried it, but figured
I would post it here in case this was useful as a reference.
In my css file is .a.b different than .a .b?
It's a simple question but it's always annoyed me. I tried it, but figured
I would post it here in case this was useful as a reference.
How to delete a row from GridView and set the remaining values to the controls?
How to delete a row from GridView and set the remaining values to the
controls?
Ok,http://www.aspsnippets.com/Articles/Adding-Dynamic-Rows-in-ASP.Net-GridView-Control-with-TextBoxes.aspx">CLICK
ME ! THis is what i have right now... but i want to add a delete
functionality. I have added a delete command button column and on its
click event i am deleting the particular row. But my problem is that i am
unable to retain the remaining row's values in the controls.
protected void Gridview1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
{
DataTable dtCurrentTable=new DataTable();
int RowIndex = e.RowIndex;
dtCurrentTable = (DataTable)ViewState["CurrentTable"];
dtCurrentTable.Rows.RemoveAt(e.RowIndex);
SetPreviousData1(dtCurrentTable);
}
private void SetPreviousData1(DataTable dtCurrentTable)
{
int rowIndex = 0;
if (dtCurrentTable != null)
{
DataTable dt = dtCurrentTable;
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox box1 =
(TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 =
(TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 =
(TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
rowIndex++;
}
}
}
}
Please note i am not fetching anything from database.
controls?
Ok,http://www.aspsnippets.com/Articles/Adding-Dynamic-Rows-in-ASP.Net-GridView-Control-with-TextBoxes.aspx">CLICK
ME ! THis is what i have right now... but i want to add a delete
functionality. I have added a delete command button column and on its
click event i am deleting the particular row. But my problem is that i am
unable to retain the remaining row's values in the controls.
protected void Gridview1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
{
DataTable dtCurrentTable=new DataTable();
int RowIndex = e.RowIndex;
dtCurrentTable = (DataTable)ViewState["CurrentTable"];
dtCurrentTable.Rows.RemoveAt(e.RowIndex);
SetPreviousData1(dtCurrentTable);
}
private void SetPreviousData1(DataTable dtCurrentTable)
{
int rowIndex = 0;
if (dtCurrentTable != null)
{
DataTable dt = dtCurrentTable;
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox box1 =
(TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 =
(TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 =
(TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
rowIndex++;
}
}
}
}
Please note i am not fetching anything from database.
Sunday, 15 September 2013
Add color indication to my application
Add color indication to my application
I found this post: Red-Green light indicators in C# .NET Form downloaded 2
icons and add to my solution (right click --> add --> existing item) now
how to add to my code this icon in order to show and switch between them
on my form ?
I found this post: Red-Green light indicators in C# .NET Form downloaded 2
icons and add to my solution (right click --> add --> existing item) now
how to add to my code this icon in order to show and switch between them
on my form ?
Constructing a histogram using a TI83/84
Constructing a histogram using a TI83/84
I am trying to complete a project for my 11th grade statistics class. I
have these following class boundaries of the unweighted GPAs of graduating
seniors: 2.00-2.49, 2.50-2.99, 3.00-3.49, 3.50-3.74 and 3.75-4.00. This
the frequency for each group: 98, 52, 184,32 and 8.
On my Window screen I punched in these values:
Xmin = 2
Xmax = 4
Xscl = 0.50
Ymin = 0
Ymax = 184
Yscl = 50
Xres = 1
However when I press graph after setting up the statplot to histogram and
selecting Xlist as L1, Freq as L2, I only get 4 bars. I want 5 bars.
I am trying to complete a project for my 11th grade statistics class. I
have these following class boundaries of the unweighted GPAs of graduating
seniors: 2.00-2.49, 2.50-2.99, 3.00-3.49, 3.50-3.74 and 3.75-4.00. This
the frequency for each group: 98, 52, 184,32 and 8.
On my Window screen I punched in these values:
Xmin = 2
Xmax = 4
Xscl = 0.50
Ymin = 0
Ymax = 184
Yscl = 50
Xres = 1
However when I press graph after setting up the statplot to histogram and
selecting Xlist as L1, Freq as L2, I only get 4 bars. I want 5 bars.
String to Time, but without the limitations of strtotime()
String to Time, but without the limitations of strtotime()
In my (non-public) applications, I like for my users to be able to enter
the date/time in whatever format and then use strtotime() along with
date() to translate it to YYYY-MM-DD for DB storage. I know this has a
couple of drawbacks (such as how 1/1/13 vs. 1-1-13 might be handled based
on locale and such), but over the years these have never been an issue
given my user base.
However, there is one issue that I may have to resolve, and that's with
handling dates prior to 1970 in one particular application. For obvious
reasons, strtotime() doesn't work so well. I know I could use a
date-picker, but was wonder if there is a more proper way of handling this
that would allow me to do what I've been doing but to handle a wider range
of dates.
In my (non-public) applications, I like for my users to be able to enter
the date/time in whatever format and then use strtotime() along with
date() to translate it to YYYY-MM-DD for DB storage. I know this has a
couple of drawbacks (such as how 1/1/13 vs. 1-1-13 might be handled based
on locale and such), but over the years these have never been an issue
given my user base.
However, there is one issue that I may have to resolve, and that's with
handling dates prior to 1970 in one particular application. For obvious
reasons, strtotime() doesn't work so well. I know I could use a
date-picker, but was wonder if there is a more proper way of handling this
that would allow me to do what I've been doing but to handle a wider range
of dates.
Blackberry (BBOS) Webworks error: java.io.FileNotFoundException initialization.log
Blackberry (BBOS) Webworks error: java.io.FileNotFoundException
initialization.log
I developed a basic Hello World application. When trying to launch the app
on the simulator I got this error:
config.xml
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
initialization.log
I developed a basic Hello World application. When trying to launch the app
on the simulator I got this error:
config.xml
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
setting .prop() value programatically of select control in j-Query mobile radio button (Data-Native-Menu ="true") not updated in android 4.2...
setting .prop() value programatically of select control in j-Query mobile
radio button (Data-Native-Menu ="true") not updated in android 4.2...
Please find the code below.
// fired when user selects on drop down list
$(#idSelectControl).live("change", function (event) {
var selectedItem = $("#idSelectControl option:selected").val();
console.log("merchant subscription" + self.merchant());
self.lastSelected = $('#idSelectControl').prop('selectedIndex');
$('#idSelectControl').prop('selectedIndex', self.lastSelected);
//$("select").selectmenu("refresh");
var myselect = $("#idSelectControl");
myselect[0].selectedIndex =0;
myselect.selectmenu("refresh",true);
$('select').selectmenu('refresh', true);
$("select").selectmenu("close");
//$("#idSelectControl").val(selectedItem ).selectmenu("refresh");
if (selectedItem ) {
self.item((selectedItem);
}
else {
self.item("");
}
});
I have tried below also
$("input[type='radio']").prop("checked",true).checkboxradio("refresh");
$('input[value='+$(this).find("HomeStatus").text()+']')
.attr('checked',true).checkboxradio('refresh');
radio button (Data-Native-Menu ="true") not updated in android 4.2...
Please find the code below.
// fired when user selects on drop down list
$(#idSelectControl).live("change", function (event) {
var selectedItem = $("#idSelectControl option:selected").val();
console.log("merchant subscription" + self.merchant());
self.lastSelected = $('#idSelectControl').prop('selectedIndex');
$('#idSelectControl').prop('selectedIndex', self.lastSelected);
//$("select").selectmenu("refresh");
var myselect = $("#idSelectControl");
myselect[0].selectedIndex =0;
myselect.selectmenu("refresh",true);
$('select').selectmenu('refresh', true);
$("select").selectmenu("close");
//$("#idSelectControl").val(selectedItem ).selectmenu("refresh");
if (selectedItem ) {
self.item((selectedItem);
}
else {
self.item("");
}
});
I have tried below also
$("input[type='radio']").prop("checked",true).checkboxradio("refresh");
$('input[value='+$(this).find("HomeStatus").text()+']')
.attr('checked',true).checkboxradio('refresh');
Update requires a valid UpdateCommand need assistance
Update requires a valid UpdateCommand need assistance
Hi folks I am getting this error "Update requires a valid UpdateCommand
when passed DataRow collection with modified rows"
My code is
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = " + AppDomain.CurrentDomain.BaseDirectory +
"Database1.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM tbl_image"
da = New OleDb.OleDbDataAdapter(Sql, con)
da.Fill(ds, "database1")
'MsgBox("Database is now open")
con.Close()
MaxRows = ds.Tables("database1").Rows.Count
'here I just have a load of other stough
da.Update(ds, "database1")
MsgBox("Data updated")
con.Close()
If you need more info please let me know. Thanks
Hi folks I am getting this error "Update requires a valid UpdateCommand
when passed DataRow collection with modified rows"
My code is
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = " + AppDomain.CurrentDomain.BaseDirectory +
"Database1.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM tbl_image"
da = New OleDb.OleDbDataAdapter(Sql, con)
da.Fill(ds, "database1")
'MsgBox("Database is now open")
con.Close()
MaxRows = ds.Tables("database1").Rows.Count
'here I just have a load of other stough
da.Update(ds, "database1")
MsgBox("Data updated")
con.Close()
If you need more info please let me know. Thanks
what's wrong with my variable, it's undefined
what's wrong with my variable, it's undefined
my variable todoHtmlLi is undefined, really can't get it why.. I had
declared it early before assign it to some html. I use console.log() to
check the priority value, it work just fine..
$(document).on('click', '#addTodoBtn', function (){
var todoDialog = {
state0: {
html: dialogContent,
buttons: {Cancel:-1 , Add:0},
focus: 1,
submit:function(e,v,m,f){
e.preventDefault();
var todoHtmlLi;
var todoNameVal;
var todoNoteVal;
//Task Name
todoNameVal = $("#todoName").val();
todoNameVal.trim();
//Note
todoNoteVal = $("#todoNote").val();
todoNoteVal.trim();
//Priority
priority = $("#priority").val();
if($(priority) === 1){
todoHtmlLi = "<li style='background:red'><a href='#'>"
+ todoNameVal + "<input type='checkbox'></a></li>"
}else if($(priority) === 2){
todoHtmlLi = "<li style='background:green'><a
href='#'>" + todoNameVal + "<input
type='checkbox'></a></li>"
}else if($(priority) === 3){
todoHtmlLi = "<li style='background:blue'><a
href='#'>" + todoNameVal + "<input
type='checkbox'></a></li>"
}
if(v == 0){
if(todoNameVal !== ""){
$("div#tab").find('#todoUl').prepend(todoHtmlLi);
$.prompt.close();
}else{
$("#todoName").focus();
}
}else{
$.prompt.close();
}
}
}
}
$.prompt(todoDialog);
});
if(v == 0){ mean the 'yes' button is clicked
my variable todoHtmlLi is undefined, really can't get it why.. I had
declared it early before assign it to some html. I use console.log() to
check the priority value, it work just fine..
$(document).on('click', '#addTodoBtn', function (){
var todoDialog = {
state0: {
html: dialogContent,
buttons: {Cancel:-1 , Add:0},
focus: 1,
submit:function(e,v,m,f){
e.preventDefault();
var todoHtmlLi;
var todoNameVal;
var todoNoteVal;
//Task Name
todoNameVal = $("#todoName").val();
todoNameVal.trim();
//Note
todoNoteVal = $("#todoNote").val();
todoNoteVal.trim();
//Priority
priority = $("#priority").val();
if($(priority) === 1){
todoHtmlLi = "<li style='background:red'><a href='#'>"
+ todoNameVal + "<input type='checkbox'></a></li>"
}else if($(priority) === 2){
todoHtmlLi = "<li style='background:green'><a
href='#'>" + todoNameVal + "<input
type='checkbox'></a></li>"
}else if($(priority) === 3){
todoHtmlLi = "<li style='background:blue'><a
href='#'>" + todoNameVal + "<input
type='checkbox'></a></li>"
}
if(v == 0){
if(todoNameVal !== ""){
$("div#tab").find('#todoUl').prepend(todoHtmlLi);
$.prompt.close();
}else{
$("#todoName").focus();
}
}else{
$.prompt.close();
}
}
}
}
$.prompt(todoDialog);
});
if(v == 0){ mean the 'yes' button is clicked
Saturday, 14 September 2013
display icon in the grid using extjs4
display icon in the grid using extjs4
I work with extjs4
I have a grid and I want to add icon related to condition in the gride
I have a css class
but the probleme that the icon displays several times
my code css :
.contactIcon80 {
background-image: url(/UrbanPlanning/theme/images/delete.png);
width:80px!important;
height:80px!important;
margin-right: auto !important;
margin-left: auto !important;
}
my code extjs :
function showUpdated(value, metaData, record, rowIndex, colIndex, store) {
if(record.get("statut_reqUPReliance")=="WaitingAccept") {
metaData.css = ' contactIcon80';
}
return value;
}
var RequestUPRelianceListGrid1 = Ext.create('Ext.grid.Panel', {
id:'RequestUPRelianceListGrid1',
store: RequestUPRelianceListGridStore,
collapsible:true,
title:'title',
columns: [
{xtype: 'checkcolumn', header: 'test',dataIndex: 'checked',
width: 60,listeners:{'checkchange':
RequestUPRelianceGridSelectionChanged}},
{text: 'numero', flex: 1, sortable: true, hidden:true, dataIndex:
'num_reqUPReliance'},
{text: 'statut', flex: 1, sortable: true, dataIndex:
'statut_reqUPReliance', renderer: showUpdated}
],
columnLines: true,
anchor: '100%',
frame: true,
height: 250,
margin: '5 5 5 5',
dockedItems: [{
xtype: 'toolbar',
dock: 'bottom',
ui: 'footer',
layout: {
pack: 'center'
},
items: [
{
xtype: 'button',
text: 'new',
id:'new_R',
handler: function() {
}
}
]
}]
});
I work with extjs4
I have a grid and I want to add icon related to condition in the gride
I have a css class
but the probleme that the icon displays several times
my code css :
.contactIcon80 {
background-image: url(/UrbanPlanning/theme/images/delete.png);
width:80px!important;
height:80px!important;
margin-right: auto !important;
margin-left: auto !important;
}
my code extjs :
function showUpdated(value, metaData, record, rowIndex, colIndex, store) {
if(record.get("statut_reqUPReliance")=="WaitingAccept") {
metaData.css = ' contactIcon80';
}
return value;
}
var RequestUPRelianceListGrid1 = Ext.create('Ext.grid.Panel', {
id:'RequestUPRelianceListGrid1',
store: RequestUPRelianceListGridStore,
collapsible:true,
title:'title',
columns: [
{xtype: 'checkcolumn', header: 'test',dataIndex: 'checked',
width: 60,listeners:{'checkchange':
RequestUPRelianceGridSelectionChanged}},
{text: 'numero', flex: 1, sortable: true, hidden:true, dataIndex:
'num_reqUPReliance'},
{text: 'statut', flex: 1, sortable: true, dataIndex:
'statut_reqUPReliance', renderer: showUpdated}
],
columnLines: true,
anchor: '100%',
frame: true,
height: 250,
margin: '5 5 5 5',
dockedItems: [{
xtype: 'toolbar',
dock: 'bottom',
ui: 'footer',
layout: {
pack: 'center'
},
items: [
{
xtype: 'button',
text: 'new',
id:'new_R',
handler: function() {
}
}
]
}]
});
Keep background image CENTERED and UNSCALED regardless of browser window size
Keep background image CENTERED and UNSCALED regardless of browser window size
I'm trying to edit the background so it stays centered. However everytime
I resize the window to say a smaller size to test it out, the image shifts
more and more to the left. I tried other codes but they wind up scaling
down the background. If I view my page on another computer, the image is
off center as well. :(
<style>
html, body {
margin: 0px;
background-color: #000000;
background-image: url('http://i.imgur.com/zwbnaPk.jpg');
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
}
</style>
I'd like it to look centered like this regardless of the window size.
Although it's slightly off in this photo, you get what I mean.
http://i.stack.imgur.com/iN5BR.jpg
I'm trying to edit the background so it stays centered. However everytime
I resize the window to say a smaller size to test it out, the image shifts
more and more to the left. I tried other codes but they wind up scaling
down the background. If I view my page on another computer, the image is
off center as well. :(
<style>
html, body {
margin: 0px;
background-color: #000000;
background-image: url('http://i.imgur.com/zwbnaPk.jpg');
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
}
</style>
I'd like it to look centered like this regardless of the window size.
Although it's slightly off in this photo, you get what I mean.
http://i.stack.imgur.com/iN5BR.jpg
Asynchronous chat
Asynchronous chat
I was following a PHP-MySQL shoutbox tutorial that covered just sending
and storing messages in the database. After I finished it, temporarily I
chose to refresh the list of messages every 5 seconds or every time you
send a new one using AJAX. But this would be too inefficient and server
consuming(practically a low-intensity DDOS) in real life applications. So
how do I refresh the list of new messages just when necessary? More
precisely, how do I get notified that a new message was sent exactly when
this happens so that I can display it?
I was following a PHP-MySQL shoutbox tutorial that covered just sending
and storing messages in the database. After I finished it, temporarily I
chose to refresh the list of messages every 5 seconds or every time you
send a new one using AJAX. But this would be too inefficient and server
consuming(practically a low-intensity DDOS) in real life applications. So
how do I refresh the list of new messages just when necessary? More
precisely, how do I get notified that a new message was sent exactly when
this happens so that I can display it?
Not able to bind the records using knockout
Not able to bind the records using knockout
By using the following article :
http://www.dotnetcurry.com/ShowArticle.aspx?ID=847, I tried to develop the
sample app. In order to keep things separate I tried to move the
javascript code to a separate js file : EmployeeInfo.js and referenced the
js file in the head section of the Create.cshtml as mentioned below:
<head>
<script src="~/Scripts/EmployeeInfo.js"></script>
</head>
But I am not able to display the existing records from the database. On
debugging the code I found that the GetEmployees() method is invoked and
data.length is also greater than 0 but the data is not able to bind with
the table to display all the records. Any help on this is appreciated.
<tbody data-bind="foreach: Employees">
<tr style="border: solid"
data-bind="click:
$root.getselectedemployee" id="updtr">
<td><span data-bind="text:
EmpNo"></span></td>
<td><span data-bind="text:
EmpName"></span></td>
<td><span data-bind="text:
Salary"></span></td>
<td><span data-bind="text:
DeptName"></span></td>
<td><span data-bind="text:
Designation"></span></td>
<td>
<button data-bind="click:
$root.deleterec">Delete</button></td>
</tr>
</tbody>
Can anyone help me to understand the problem.
Thanks & Regards, Santosh Kumar Patro
By using the following article :
http://www.dotnetcurry.com/ShowArticle.aspx?ID=847, I tried to develop the
sample app. In order to keep things separate I tried to move the
javascript code to a separate js file : EmployeeInfo.js and referenced the
js file in the head section of the Create.cshtml as mentioned below:
<head>
<script src="~/Scripts/EmployeeInfo.js"></script>
</head>
But I am not able to display the existing records from the database. On
debugging the code I found that the GetEmployees() method is invoked and
data.length is also greater than 0 but the data is not able to bind with
the table to display all the records. Any help on this is appreciated.
<tbody data-bind="foreach: Employees">
<tr style="border: solid"
data-bind="click:
$root.getselectedemployee" id="updtr">
<td><span data-bind="text:
EmpNo"></span></td>
<td><span data-bind="text:
EmpName"></span></td>
<td><span data-bind="text:
Salary"></span></td>
<td><span data-bind="text:
DeptName"></span></td>
<td><span data-bind="text:
Designation"></span></td>
<td>
<button data-bind="click:
$root.deleterec">Delete</button></td>
</tr>
</tbody>
Can anyone help me to understand the problem.
Thanks & Regards, Santosh Kumar Patro
Query Mongo collection for all documents with empty array nested in an array
Query Mongo collection for all documents with empty array nested in an array
I have documents that look like this in a collection called movies:
{
"_id" : ObjectId("51c272623021490007000001"),
"movies": [
{
"name": "Booty Call"
"play_times": []
},
{
"name": "Bulletproof"
"play_times": [{...},{...}]
}
]
}
I would like to query for documents where "play_times" is not empty or
null. Basically I only care about movies with play times.
I have documents that look like this in a collection called movies:
{
"_id" : ObjectId("51c272623021490007000001"),
"movies": [
{
"name": "Booty Call"
"play_times": []
},
{
"name": "Bulletproof"
"play_times": [{...},{...}]
}
]
}
I would like to query for documents where "play_times" is not empty or
null. Basically I only care about movies with play times.
Setting custom class/attributes c#
Setting custom class/attributes c#
little forward: I wasn't sure on exactly what I'm looking for, I know it's
possible and I know there's a name for it, but I wasn't sure of what to
search to find it. The answer to this may be as simple as directing me to
the right place, which would be much appreciated! Anyway here's what I'm
trying to do. I'd like to set up a new class, say "class1" then I'd like
to have an attribute, lets say "dead" randomly selected, so that I can
create an instance of the class and the following code will work class1
player1 = new class1(); if (player1.dead == true) { //do whatever }
I apologize if I've used the wrong words in my explanation, again I'm not
sure exactly what I"m looking for. Thanks!
little forward: I wasn't sure on exactly what I'm looking for, I know it's
possible and I know there's a name for it, but I wasn't sure of what to
search to find it. The answer to this may be as simple as directing me to
the right place, which would be much appreciated! Anyway here's what I'm
trying to do. I'd like to set up a new class, say "class1" then I'd like
to have an attribute, lets say "dead" randomly selected, so that I can
create an instance of the class and the following code will work class1
player1 = new class1(); if (player1.dead == true) { //do whatever }
I apologize if I've used the wrong words in my explanation, again I'm not
sure exactly what I"m looking for. Thanks!
mPDF - Correct permissions on UNIX
mPDF - Correct permissions on UNIX
Today I had to reinstall my OS (Ubuntu) and apache server (Lamp), now I
forgot how was my permissions set up for mPDF. I can't create PDF file
because server doesn't allow me so. My code is ok since everything worked
before reinstallation of OS. I tried using chmod +r+w location/to/folder
but that doesn't work. Also I tried to give all permissions to www-data
but still no luck. Can someone tell me what permissions I need to set so
mPDF can create PDF files with no problem
Today I had to reinstall my OS (Ubuntu) and apache server (Lamp), now I
forgot how was my permissions set up for mPDF. I can't create PDF file
because server doesn't allow me so. My code is ok since everything worked
before reinstallation of OS. I tried using chmod +r+w location/to/folder
but that doesn't work. Also I tried to give all permissions to www-data
but still no luck. Can someone tell me what permissions I need to set so
mPDF can create PDF files with no problem
Friday, 13 September 2013
Why NVPROF and Nsight not profiling one of the kernels?
Why NVPROF and Nsight not profiling one of the kernels?
I have this CFD program in cuda, which when I execute using block of
dimension 16 * 16 and profile it, it gets profiled perfectly and shows a
kernel "NLMMNT" to be taking most of the GPU time. But I execute the same
program using block dimension 32 * 32, the program accelerates upto 5
times faster than before, and the results of the program are correct, but
now the profiler is not showing the profiling output for NLMMNT. When I
see the log of Nsight, there also its not showing the profiling of NLMMNT
to be complete. I can figure what may be the reason, I tried running that
application for hours but still NLMMNT's profile info is absent from the
profiler's output.
Log of Nsight can be seen in this screenshot...
http://s23.postimg.org/hbaect7uz/profoutput.png
By the way I am facing the same problem in Nvprof in Nsight eclipse
edition as well .
I have also cross checked that the kernel is getting launched finished
succesfully by checking the cudaError_t status before and after launching
the kernel. I am facing the same problem in both Nsight on Visual Studio
Editon 2010, cuda toolkit 5.0, Geforce GT 520MX and Nvprof on Ubuntu
studio 12.10, Nsight Eclipse Edition, nvprof v 4.0 , cuda toolkit 5.5
Geforce GTX 480.
I have this CFD program in cuda, which when I execute using block of
dimension 16 * 16 and profile it, it gets profiled perfectly and shows a
kernel "NLMMNT" to be taking most of the GPU time. But I execute the same
program using block dimension 32 * 32, the program accelerates upto 5
times faster than before, and the results of the program are correct, but
now the profiler is not showing the profiling output for NLMMNT. When I
see the log of Nsight, there also its not showing the profiling of NLMMNT
to be complete. I can figure what may be the reason, I tried running that
application for hours but still NLMMNT's profile info is absent from the
profiler's output.
Log of Nsight can be seen in this screenshot...
http://s23.postimg.org/hbaect7uz/profoutput.png
By the way I am facing the same problem in Nvprof in Nsight eclipse
edition as well .
I have also cross checked that the kernel is getting launched finished
succesfully by checking the cudaError_t status before and after launching
the kernel. I am facing the same problem in both Nsight on Visual Studio
Editon 2010, cuda toolkit 5.0, Geforce GT 520MX and Nvprof on Ubuntu
studio 12.10, Nsight Eclipse Edition, nvprof v 4.0 , cuda toolkit 5.5
Geforce GTX 480.
CMS to use in creating a native android or ios app
CMS to use in creating a native android or ios app
Help needed
I need to know what is the proper way to create a native android and IOS
apps. Is it possible to use CMS' like Drupal, Wordpress or Joomla if not
Is PHP compatible in building apps using framework CODEIGNITER?
My skills: Client side: HTML5 CSS3 Javascript
Server side: PHP Codeigniter framework - beginner
Help needed
I need to know what is the proper way to create a native android and IOS
apps. Is it possible to use CMS' like Drupal, Wordpress or Joomla if not
Is PHP compatible in building apps using framework CODEIGNITER?
My skills: Client side: HTML5 CSS3 Javascript
Server side: PHP Codeigniter framework - beginner
How to connect Xcode and iTunes Connect
How to connect Xcode and iTunes Connect
I have completed my first app. iTunes Connect is waiting for its upload
and has designed the app "Waiting for Upload". I started the process of
archiving. When complete, I clicked the Validate button and received this:
"No identities available for signing". I tried to download identities and
received the warning sign and message " An administrator must request
identities before they can be downloaded".
The validation provided the following warning "warning: Application failed
codesign verification. The signature was invalid, contains disallowed
entitlements, or it was not signed with an iPhone Distribution
Certificate. (-19011)".
I have researched these messages through the forum and though there are
several sightings, I cannot for the life of me figure out what to do. I
assume there is some sort of breakdown in communication between Xcode and
iTunes Connect. My roles in iTunes connect are "admin" and "legal". I am a
team of one. Assistance would be greatly appreciated, for I have come far
and find defeat near at hand.
I have completed my first app. iTunes Connect is waiting for its upload
and has designed the app "Waiting for Upload". I started the process of
archiving. When complete, I clicked the Validate button and received this:
"No identities available for signing". I tried to download identities and
received the warning sign and message " An administrator must request
identities before they can be downloaded".
The validation provided the following warning "warning: Application failed
codesign verification. The signature was invalid, contains disallowed
entitlements, or it was not signed with an iPhone Distribution
Certificate. (-19011)".
I have researched these messages through the forum and though there are
several sightings, I cannot for the life of me figure out what to do. I
assume there is some sort of breakdown in communication between Xcode and
iTunes Connect. My roles in iTunes connect are "admin" and "legal". I am a
team of one. Assistance would be greatly appreciated, for I have come far
and find defeat near at hand.
php : storing reference to other class object
php : storing reference to other class object
I come from a java background and m trying a hand at php. Right now I m
trying to pass a object to constructor of a class and trying to store a
reference to it inside the class and upon a function call to this call
execute a method from the stored reference.
$phpBook = new Book("Php Book", 500);
$vihaan = new Person("Vihaan", $phpBook);
Person.php
class Person
{
private $_book;
private $_name;
public function __construct($name, $book)
{
$_this->_book = $book;
$_this->_name = $name;
}
on this line
$_this->_book = $book;
I get a warning.
PHP Warning: Creating default object from empty value in
/home/vihaan/workspace/AdapterPattern1/Person.php on line 12
and this function call never enter the if block as $_book seems to be empty.
public function openBook($pageNumber = 0)
{
if(!empty($_book))
{
$_book->open($pageNumber);
}
}
I come from a java background and m trying a hand at php. Right now I m
trying to pass a object to constructor of a class and trying to store a
reference to it inside the class and upon a function call to this call
execute a method from the stored reference.
$phpBook = new Book("Php Book", 500);
$vihaan = new Person("Vihaan", $phpBook);
Person.php
class Person
{
private $_book;
private $_name;
public function __construct($name, $book)
{
$_this->_book = $book;
$_this->_name = $name;
}
on this line
$_this->_book = $book;
I get a warning.
PHP Warning: Creating default object from empty value in
/home/vihaan/workspace/AdapterPattern1/Person.php on line 12
and this function call never enter the if block as $_book seems to be empty.
public function openBook($pageNumber = 0)
{
if(!empty($_book))
{
$_book->open($pageNumber);
}
}
Save Appointment task dows not fire the Grids focus Event
Save Appointment task dows not fire the Grids focus Event
I am working on saving Appointments But if I do A (new
SaveAppointmentTask()).Show()
Then it doesnot fire the Grids OnFocus event when doing a save or a
Cancel. Please Direct me to a proper step of detecting that the Xaml page
is In Focus ie the current Page.
Here's The XAML and the CS
<Grid OnFocus="Grid_Focus"></Grid>
Cs
private void OnFocus(args args){
//if I put a break point here then it does not hit
}
Please look into it.
I am working on saving Appointments But if I do A (new
SaveAppointmentTask()).Show()
Then it doesnot fire the Grids OnFocus event when doing a save or a
Cancel. Please Direct me to a proper step of detecting that the Xaml page
is In Focus ie the current Page.
Here's The XAML and the CS
<Grid OnFocus="Grid_Focus"></Grid>
Cs
private void OnFocus(args args){
//if I put a break point here then it does not hit
}
Please look into it.
Mobile first approach using LESS and nested media queries - looking for an IE10 alternative to conditional comments
Mobile first approach using LESS and nested media queries - looking for an
IE10 alternative to conditional comments
I'm using this great feature in LESS called nested media queries that
allows me to keep styles related to each "module" in one place. My media
queries are defined in a variables file as follows:
// Breakpoints
@breakpoint-medium: "600px";
....
// Queries
@mq-medium-and-up: ~"only screen and (min-width: @{breakpoint-medium})";
....
I can then use the media queries throughout my stylesheets in the
following way:
.module {
background: green;
@media @mq-medium-and-up {
background: yellow;
}
}
I take a mobile first approach to my CSS where I work my way up from small
screens (no media queries) to larger and larger breakpoints (using media
queries). Obviously media queries aren't supported in IE <= 8, so I would
like those browsers to fallback to having the "desktop styling".
In order to do so, I currently keep a separate less file (IE.less) where I
redefine the media queries as follows:
@mq-medium-and-up: ~"all";
@mq-large-and-up: ~"all";
which results in a media rule that older versions of IE will understand
@media all ...
So far all is good. I now have a separate IE stylesheet containing the
"desktop" styles. The problematic part of this is when it comes to how I
should include these two separate stylesheets in order to prevent older IE
versions from requesting both stylesheets (which are basically the same).
Currently I do it like this:
<link rel="stylesheet" href="site.css" />
<!--[if (lt IE 9) & (!IEMobile)]>
<link rel="stylesheet" href="ie.css" />
<![endif]-->
Would it be possible to prevent IE < 9 to download the site.css, but still
make it visible to other browsers? My initial thought was to wrap the
site.css file in another conditional comment using the NOT opeartor, but
since IE10 has dropped the support for conditional comments I guess that
is out of the question.
Any ideas?
IE10 alternative to conditional comments
I'm using this great feature in LESS called nested media queries that
allows me to keep styles related to each "module" in one place. My media
queries are defined in a variables file as follows:
// Breakpoints
@breakpoint-medium: "600px";
....
// Queries
@mq-medium-and-up: ~"only screen and (min-width: @{breakpoint-medium})";
....
I can then use the media queries throughout my stylesheets in the
following way:
.module {
background: green;
@media @mq-medium-and-up {
background: yellow;
}
}
I take a mobile first approach to my CSS where I work my way up from small
screens (no media queries) to larger and larger breakpoints (using media
queries). Obviously media queries aren't supported in IE <= 8, so I would
like those browsers to fallback to having the "desktop styling".
In order to do so, I currently keep a separate less file (IE.less) where I
redefine the media queries as follows:
@mq-medium-and-up: ~"all";
@mq-large-and-up: ~"all";
which results in a media rule that older versions of IE will understand
@media all ...
So far all is good. I now have a separate IE stylesheet containing the
"desktop" styles. The problematic part of this is when it comes to how I
should include these two separate stylesheets in order to prevent older IE
versions from requesting both stylesheets (which are basically the same).
Currently I do it like this:
<link rel="stylesheet" href="site.css" />
<!--[if (lt IE 9) & (!IEMobile)]>
<link rel="stylesheet" href="ie.css" />
<![endif]-->
Would it be possible to prevent IE < 9 to download the site.css, but still
make it visible to other browsers? My initial thought was to wrap the
site.css file in another conditional comment using the NOT opeartor, but
since IE10 has dropped the support for conditional comments I guess that
is out of the question.
Any ideas?
Thursday, 12 September 2013
How can I fix these errors for this program?
How can I fix these errors for this program?
CSCI-15 Assignment #2, String processing. (60 points) Due 9/23/13
You MAY NOT use C++ string objects for anything in this program.
Write a C++ program that reads lines of text from a file using the
ifstream getline() method, tokenizes the lines into words ("tokens") using
strtok(), and keeps statistics on the data in the file. Your input and
output file names will be supplied to your program on the command line,
which you will access using argc and argv[].
You need to count the total number of words, the number of unique words,
the count of each individual word, and the number of lines. Also, remember
and print the longest and shortest words in the file. If there is a tie
for longest or shortest word, you may resolve the tie in any consistent
manner (e.g., use either the first one or the last one found, but use the
same method for both longest and shortest). You may assume the lines
comprise words (contiguous lower-case letters [a-z]) separated by spaces,
terminated with a period. You may ignore the possibility of other
punctuation marks, including possessives or contractions, like in "Jim's
house". Lines before the last one in the file will have a newline ('\n')
after the period. In your data files, omit the '\n' on the last line. You
may assume that the lines will be no longer than 100 characters, the
individual words will be no longer than 15 letters and there will be no
more than 100 unique words in the file.
Read the lines from the input file, and echo-print them to the output
file. After reaching end-of-file on the input file (or reading a line of
length zero, which you should treat as the end of the input data), print
the words with their occurrence counts, one word/count pair per line, and
the collected statistics to the output file. You will also need to create
other test files of your own. Also, your program must work correctly with
an EMPTY input file – which has NO statistics.
My test file looks like this (exactly 4 lines, with NO NEWLINE on the last
line):
the quick brown fox jumps over the lazy dog.
now is the time for all good men to come to the aid of their party.
all i want for christmas is my two front teeth.
the quick brown fox jumps over a lazy dog.
Copy and paste this into a small file for one of your tests.
Hints:
Use a 2-dimensional array of char, 100 rows by 16 columns (why not 15?),
to hold the unique words, and a 1-dimensional array of ints with 100
elements to hold the associated counts. For each word, scan through the
occupied lines in the array for a match (use strcmp()), and if you find a
match, increment the associated count, otherwise (you got past the last
word), add the word to the table and set its count to 1.
The separate longest word and the shortest word need to be saved off in
their own C-strings. (Why can't you just keep a pointer to them in the
tokenized data?)
Remember – put NO NEWLINE at the end of the last line, or your test for
end-of-file might not work correctly. (This may cause the program to read
a zero-length line before seeing end-of-file.)
This is not a long program – no more than about 2 pages of code.
Here is my solution:
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
using namespace std;
int main(int argc, char *argv[])
{
ifstream inputFile;
ofstream outputFile;
char inFile[12] = "string1.txt";
char outFile[16] = "word result.txt";
char words[100][16]; // Hods the unique words.
int counter[100]; // Holds associated counts.
char *longest[16]; // Holds longest words.
char *shortest[16]; // Holds shortest words.
int totalCount = 0; // Counts the total number of words.
int lineCount = 0; // Counts the number of lines.
totalCount = strtok(words, "."); // Tokenizes each word and removes
period.
// Get the name of the file from the user.
cout << "Enter the name of the file: ";
getline(cin, inFile);
// Open the input file.
inputFile.open(inFile);
// If successfully opened, process the data.
if(inputFile)
{
while(!inputFile.eof())
{
lineCount++; // Increment each line.
// Read every word in each line.
while(getline(inFile, words[100][16]))
{
// If there is a match, increment the associated count.
if(strcmp(words[100][16], counter[100]) == 0)
{
counter[100]++;
totalCount++; // Increment the total number of words;
totalCount = strtok(NULL, " "); // Removes the
whitespace.
// If there is a tie for longest word, get the first
or last word found.
if(strcmp(inFile, longest) == 0)
{
longest[16] = "";
}
// If there is a tie for shortest word, get the first
or last word found.
else if(strcmp(inputFile, shortest) == 0)
{
shortest[16] = "";
}
}
// Otherwise, add the word to the table and increment by 1.
else
{
words[100][16] += 1;
}
}
}
// Close the file.
inputFile.close();
}
// Otherwise, print error message.
else
{
cout << "Cannot open the file" << endl;
}
// Open the output file.
outputFile.open(outFile);
// Print the table to the output file.
outputFile << "List of words: " << endl;
outputFile << "---------------------" << endl;
// Print each word/count pair per line.
for(int i = 0; i < words[100][16]; i++)
{
outputFile << setw(10) << words[i][16] << endl;
outputFile << setw(10) << words[100][i] << endl;
}
outputFile << endl;
// Print the stats to the output file.
outputFile << "Number of Lines: " << lineCount << endl;
outputFile << "Total number of Words: " << totalCount << endl;
outputFile << "Number of Unique Words: " << words[100][16] << endl;
// Close the output file.
outputFile.close();
return 0;
}
Right now, my code has a few errors and I'm not sure how to fix them. Is
there anything I need to change?
Here are the errors:
line 20: cannot convert char[][16] to char for argument 1 to char
strtok[char, const char)
line 24: no matching function for call to getline[std:istream&, char[12]]
line 36: no matching function to call to getline[char[12], char&]
line 39: invalid conversion from char to const char
line 39: invalid conversion from int to const char
line 43: invalid conversion from char to int
line 45: cannot convert char to const char for argument 2 to int
strcmp[const char, const char]
line 50: cannot convert std:ifstream to const char for argument 1 to int
strcmp[const char, const char
CSCI-15 Assignment #2, String processing. (60 points) Due 9/23/13
You MAY NOT use C++ string objects for anything in this program.
Write a C++ program that reads lines of text from a file using the
ifstream getline() method, tokenizes the lines into words ("tokens") using
strtok(), and keeps statistics on the data in the file. Your input and
output file names will be supplied to your program on the command line,
which you will access using argc and argv[].
You need to count the total number of words, the number of unique words,
the count of each individual word, and the number of lines. Also, remember
and print the longest and shortest words in the file. If there is a tie
for longest or shortest word, you may resolve the tie in any consistent
manner (e.g., use either the first one or the last one found, but use the
same method for both longest and shortest). You may assume the lines
comprise words (contiguous lower-case letters [a-z]) separated by spaces,
terminated with a period. You may ignore the possibility of other
punctuation marks, including possessives or contractions, like in "Jim's
house". Lines before the last one in the file will have a newline ('\n')
after the period. In your data files, omit the '\n' on the last line. You
may assume that the lines will be no longer than 100 characters, the
individual words will be no longer than 15 letters and there will be no
more than 100 unique words in the file.
Read the lines from the input file, and echo-print them to the output
file. After reaching end-of-file on the input file (or reading a line of
length zero, which you should treat as the end of the input data), print
the words with their occurrence counts, one word/count pair per line, and
the collected statistics to the output file. You will also need to create
other test files of your own. Also, your program must work correctly with
an EMPTY input file – which has NO statistics.
My test file looks like this (exactly 4 lines, with NO NEWLINE on the last
line):
the quick brown fox jumps over the lazy dog.
now is the time for all good men to come to the aid of their party.
all i want for christmas is my two front teeth.
the quick brown fox jumps over a lazy dog.
Copy and paste this into a small file for one of your tests.
Hints:
Use a 2-dimensional array of char, 100 rows by 16 columns (why not 15?),
to hold the unique words, and a 1-dimensional array of ints with 100
elements to hold the associated counts. For each word, scan through the
occupied lines in the array for a match (use strcmp()), and if you find a
match, increment the associated count, otherwise (you got past the last
word), add the word to the table and set its count to 1.
The separate longest word and the shortest word need to be saved off in
their own C-strings. (Why can't you just keep a pointer to them in the
tokenized data?)
Remember – put NO NEWLINE at the end of the last line, or your test for
end-of-file might not work correctly. (This may cause the program to read
a zero-length line before seeing end-of-file.)
This is not a long program – no more than about 2 pages of code.
Here is my solution:
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
using namespace std;
int main(int argc, char *argv[])
{
ifstream inputFile;
ofstream outputFile;
char inFile[12] = "string1.txt";
char outFile[16] = "word result.txt";
char words[100][16]; // Hods the unique words.
int counter[100]; // Holds associated counts.
char *longest[16]; // Holds longest words.
char *shortest[16]; // Holds shortest words.
int totalCount = 0; // Counts the total number of words.
int lineCount = 0; // Counts the number of lines.
totalCount = strtok(words, "."); // Tokenizes each word and removes
period.
// Get the name of the file from the user.
cout << "Enter the name of the file: ";
getline(cin, inFile);
// Open the input file.
inputFile.open(inFile);
// If successfully opened, process the data.
if(inputFile)
{
while(!inputFile.eof())
{
lineCount++; // Increment each line.
// Read every word in each line.
while(getline(inFile, words[100][16]))
{
// If there is a match, increment the associated count.
if(strcmp(words[100][16], counter[100]) == 0)
{
counter[100]++;
totalCount++; // Increment the total number of words;
totalCount = strtok(NULL, " "); // Removes the
whitespace.
// If there is a tie for longest word, get the first
or last word found.
if(strcmp(inFile, longest) == 0)
{
longest[16] = "";
}
// If there is a tie for shortest word, get the first
or last word found.
else if(strcmp(inputFile, shortest) == 0)
{
shortest[16] = "";
}
}
// Otherwise, add the word to the table and increment by 1.
else
{
words[100][16] += 1;
}
}
}
// Close the file.
inputFile.close();
}
// Otherwise, print error message.
else
{
cout << "Cannot open the file" << endl;
}
// Open the output file.
outputFile.open(outFile);
// Print the table to the output file.
outputFile << "List of words: " << endl;
outputFile << "---------------------" << endl;
// Print each word/count pair per line.
for(int i = 0; i < words[100][16]; i++)
{
outputFile << setw(10) << words[i][16] << endl;
outputFile << setw(10) << words[100][i] << endl;
}
outputFile << endl;
// Print the stats to the output file.
outputFile << "Number of Lines: " << lineCount << endl;
outputFile << "Total number of Words: " << totalCount << endl;
outputFile << "Number of Unique Words: " << words[100][16] << endl;
// Close the output file.
outputFile.close();
return 0;
}
Right now, my code has a few errors and I'm not sure how to fix them. Is
there anything I need to change?
Here are the errors:
line 20: cannot convert char[][16] to char for argument 1 to char
strtok[char, const char)
line 24: no matching function for call to getline[std:istream&, char[12]]
line 36: no matching function to call to getline[char[12], char&]
line 39: invalid conversion from char to const char
line 39: invalid conversion from int to const char
line 43: invalid conversion from char to int
line 45: cannot convert char to const char for argument 2 to int
strcmp[const char, const char]
line 50: cannot convert std:ifstream to const char for argument 1 to int
strcmp[const char, const char
COMPARE 2 COLUMNS IN 2 TABLES WITH DISTINCT VALUE
COMPARE 2 COLUMNS IN 2 TABLES WITH DISTINCT VALUE
I am now creating a reporting service with visual business intelligent.
i try to count how many users have been created under an org_id.
but the report consist of multiple org_id. and i have difficulties on
counting how many has been created under that particular org_id.
TBL_USER
USER_ID
0001122 0001234 ABC9999
DEF4545 DEF7676
TBL_ORG
ORG_ID
000 ABC DEF
EXPECTED OUTPUT
TBL_RESULT
USER_CREATED
000 - 2 ABC - 1 DEF - 2
in my understanding, i need nested SELECT, but so far i have come to nothing.
SELECT COUNT(TBL_USER.USER_ID) AS Expr1 FROM TBL_USER INNER JOIN TBL_ORG
WHERE TBL_USER.USER_ID LIKE 'TBL_ORG.ORG_ID%')
this is totally wrong. but i hope it might give us clue.
I am now creating a reporting service with visual business intelligent.
i try to count how many users have been created under an org_id.
but the report consist of multiple org_id. and i have difficulties on
counting how many has been created under that particular org_id.
TBL_USER
USER_ID
0001122 0001234 ABC9999
DEF4545 DEF7676
TBL_ORG
ORG_ID
000 ABC DEF
EXPECTED OUTPUT
TBL_RESULT
USER_CREATED
000 - 2 ABC - 1 DEF - 2
in my understanding, i need nested SELECT, but so far i have come to nothing.
SELECT COUNT(TBL_USER.USER_ID) AS Expr1 FROM TBL_USER INNER JOIN TBL_ORG
WHERE TBL_USER.USER_ID LIKE 'TBL_ORG.ORG_ID%')
this is totally wrong. but i hope it might give us clue.
Using Facebook Connect to initiate a connection request
Using Facebook Connect to initiate a connection request
Here's what I'd like to be able to do, if it's allowed by Facebook:
Have users of my website authenticate using Facebook Connect
Access the list of their friends
Allow the user on my site to select any number of their FB friends
Fire off connection requests for my site using the FB interface.
I know that FB won't give my 3rd party application access to someone
else's email address without their permission, but does it allow me to
send 3rd party app requests in the Facebook UI?
Pinterest, Spotify, and other services will allow you to follow FB friends
that are already on these respective services, but they don't have a way
for me to invite people who aren't yet on Pinterest or Spotify.
What's the best way for me to leverage my existing FB network to drive new
member acquisition for a 3rd party app?
Here's what I'd like to be able to do, if it's allowed by Facebook:
Have users of my website authenticate using Facebook Connect
Access the list of their friends
Allow the user on my site to select any number of their FB friends
Fire off connection requests for my site using the FB interface.
I know that FB won't give my 3rd party application access to someone
else's email address without their permission, but does it allow me to
send 3rd party app requests in the Facebook UI?
Pinterest, Spotify, and other services will allow you to follow FB friends
that are already on these respective services, but they don't have a way
for me to invite people who aren't yet on Pinterest or Spotify.
What's the best way for me to leverage my existing FB network to drive new
member acquisition for a 3rd party app?
Change displayed view in a UIPopoverView
Change displayed view in a UIPopoverView
So I'm presenting a UIPopoverView like so:
if (self.BStatePopoverViewController == nil) {
RedStatePopoverViewController *settings =
[[RedStatePopoverViewController alloc]
initWithNibName:@"RedState"
bundle:[NSBundle mainBundle]];
UIPopoverController *popover =
[[UIPopoverController alloc] initWithContentViewController:settings];
popover.delegate = self;
self.BStatePopoverViewController = popover;
}
[BStatePopoverViewController setPopoverContentSize:CGSizeMake(320, 445)];
[self.BStatePopoverViewController presentPopoverFromRect:[sender
bounds] inView:sender
permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
Once the view is loaded in the popover, I have a button which I'd like to
use to present a new UIViewController within the popover. I tried just
presenting it as a modal view but this changes the parent view as opposed
to the one in the popover:
PopupDischargeViewController * dischargeview =
[[PopupDischargeViewController alloc]
initWithNibName:@"PopupDischargeViewController" bundle:nil];
[self presentModalViewController:dischargeview animated:NO];
Any help as to how I do this would be much appreciated.
Thanks!
So I'm presenting a UIPopoverView like so:
if (self.BStatePopoverViewController == nil) {
RedStatePopoverViewController *settings =
[[RedStatePopoverViewController alloc]
initWithNibName:@"RedState"
bundle:[NSBundle mainBundle]];
UIPopoverController *popover =
[[UIPopoverController alloc] initWithContentViewController:settings];
popover.delegate = self;
self.BStatePopoverViewController = popover;
}
[BStatePopoverViewController setPopoverContentSize:CGSizeMake(320, 445)];
[self.BStatePopoverViewController presentPopoverFromRect:[sender
bounds] inView:sender
permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
Once the view is loaded in the popover, I have a button which I'd like to
use to present a new UIViewController within the popover. I tried just
presenting it as a modal view but this changes the parent view as opposed
to the one in the popover:
PopupDischargeViewController * dischargeview =
[[PopupDischargeViewController alloc]
initWithNibName:@"PopupDischargeViewController" bundle:nil];
[self presentModalViewController:dischargeview animated:NO];
Any help as to how I do this would be much appreciated.
Thanks!
PHP merge multidimensional array if certain values are duplicate
PHP merge multidimensional array if certain values are duplicate
I have the following PHP multidimensional array. I'd like to somehow go
though the array and see if any have 3 matching criteria and if so,
combine those into one. Any fields that are unique would use the info from
the first in the array. So in the example below, I'd like to look for
[action], [on] and [media][id]. If all three match, they would be combined
into one. However, I'd like to be able to have a count of the original
before the merge, and keep track of the [seen] values too. In the example
below I show what the original would look like, followed by the finished
array. I would really appreciate any help on this.
ORIGINAL LIKE THIS:
[0] => Array //HAS DUPLICATE
(
[action] => like
[seen] => false
[on] => photos
[from_user_id] => 2
[media] => Array
(
[id] => 3688
[path] => f2892213.jpg
[med_type] => pic
)
)
[1] => Array //HAS DUPLICATE
(
[action] => like
[seen] => true
[on] => photos
[from_user_id] => 13
[media] => Array
(
[id] => 3688
[path] => f2892213.jpg
[med_type] => pic
)
)
[2] => Array
(
[action] => like
[seen] => false
[on] => photos
[from_user_id] => 21
[media] => Array
(
[id] => 6372
[path] => H9384yhds
[med_type] => vid
)
)
[3] => Array //HAS DUPLICATE
(
[action] => like
[seen] => false
[on] => photos
[from_user_id] => 11
[media] => Array
(
[id] => 3688
[path] => f2892213.jpg
[med_type] => pic
)
)
FINISHED ARRAY SOMETHING LIKE THIS:
[0] => Array
(
[action] => like
[on] => photos
[from_user_id] => 2
[media] => Array
(
[id] => 3688
[path] => f2892213.jpg
[med_type] => pic
)
[count_before_merge] => 3
[seen_before_merge] => 1
)
[1] => Array
(
[action] => like
[seen] => false
[on] => photos
[from_user_id] => 21
[media] => Array
(
[id] => 6372
[path] => H9384yhds
[med_type] => vid
)
)
I have the following PHP multidimensional array. I'd like to somehow go
though the array and see if any have 3 matching criteria and if so,
combine those into one. Any fields that are unique would use the info from
the first in the array. So in the example below, I'd like to look for
[action], [on] and [media][id]. If all three match, they would be combined
into one. However, I'd like to be able to have a count of the original
before the merge, and keep track of the [seen] values too. In the example
below I show what the original would look like, followed by the finished
array. I would really appreciate any help on this.
ORIGINAL LIKE THIS:
[0] => Array //HAS DUPLICATE
(
[action] => like
[seen] => false
[on] => photos
[from_user_id] => 2
[media] => Array
(
[id] => 3688
[path] => f2892213.jpg
[med_type] => pic
)
)
[1] => Array //HAS DUPLICATE
(
[action] => like
[seen] => true
[on] => photos
[from_user_id] => 13
[media] => Array
(
[id] => 3688
[path] => f2892213.jpg
[med_type] => pic
)
)
[2] => Array
(
[action] => like
[seen] => false
[on] => photos
[from_user_id] => 21
[media] => Array
(
[id] => 6372
[path] => H9384yhds
[med_type] => vid
)
)
[3] => Array //HAS DUPLICATE
(
[action] => like
[seen] => false
[on] => photos
[from_user_id] => 11
[media] => Array
(
[id] => 3688
[path] => f2892213.jpg
[med_type] => pic
)
)
FINISHED ARRAY SOMETHING LIKE THIS:
[0] => Array
(
[action] => like
[on] => photos
[from_user_id] => 2
[media] => Array
(
[id] => 3688
[path] => f2892213.jpg
[med_type] => pic
)
[count_before_merge] => 3
[seen_before_merge] => 1
)
[1] => Array
(
[action] => like
[seen] => false
[on] => photos
[from_user_id] => 21
[media] => Array
(
[id] => 6372
[path] => H9384yhds
[med_type] => vid
)
)
Subscribe to:
Comments (Atom)