Thursday, 3 October 2013

Android start service on boot, can't receive the broadcast

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.

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.

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?

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.

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.

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!

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

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.

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?

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!

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

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"

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?

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.

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.

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();
}
}
}

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?

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.

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>

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.