setcontext always starts from function line
I am implementing a userthread library. When I try to swap the context
when the yield is called, the swapped function is always starting from the
first line. The program counter is not updated I guess. For Example,
consider there are two Threads, say
T1: {
printf("Inside T1. Yielding to Other \n");
ThreadYield();
MyThreadExit();
}
T2: {
ThreadCreate(t1, 0);
printf("Inside T2. Yielding to Other \n");
ThreadYield();
}
In this case, when I use the setcontext/swapcontext, always the thread
starts from the line 1. So many threads are created and it goes to a
infinite loop. Can anyone tell me what is going wrong
Saturday, 31 August 2013
Java Comparator compareToIgnoreCase
Java Comparator compareToIgnoreCase
I am trying to sort an array of strings using compareToIgnoreCase.
The string contain names ex: Billy Jean
When I try to compare them I get a null pointer exception. I think this is
because of the space between the first and last name. How can I compare
whole name?
Thanks
class CompareStudentNames implements Comparator{
//Sorts the students by name ignoring case.
@Override
public int compare(Object o1, Object o2) {
String name1 = ((Student)o1).getName();
String name2 = ((Student)o2).getName();
return (name1.compareToIgnoreCase(name2));
}
}
I am trying to sort an array of strings using compareToIgnoreCase.
The string contain names ex: Billy Jean
When I try to compare them I get a null pointer exception. I think this is
because of the space between the first and last name. How can I compare
whole name?
Thanks
class CompareStudentNames implements Comparator{
//Sorts the students by name ignoring case.
@Override
public int compare(Object o1, Object o2) {
String name1 = ((Student)o1).getName();
String name2 = ((Student)o2).getName();
return (name1.compareToIgnoreCase(name2));
}
}
Generating a dynamic 3D matrix
Generating a dynamic 3D matrix
I need to generate dynamically a 3D matrix like this:
float vCube[8][3] = {
{1.0f, -1.0f, -1.0f}, {1.0f, -1.0f, 1.0f},
{-1.0f, -1.0f, 1.0f}, {-1.0f, -1.0f, -1.0f},
{1.0f, -1.0f, -1.0f}, {1.0f, 1.0f, 1.0f},
{-1.0f, 1.0f, 1.0f}, {-1.0f, 1.0f, -1.0f}
};
I mean, to take a value and put it inside the matrix on running time. I
tried to make a pointer to float, then adding 3D elements by new, but the
results were not what I want.
Note that I don't want to use STL like vector and so on, just a plane matrix.
I need to generate dynamically a 3D matrix like this:
float vCube[8][3] = {
{1.0f, -1.0f, -1.0f}, {1.0f, -1.0f, 1.0f},
{-1.0f, -1.0f, 1.0f}, {-1.0f, -1.0f, -1.0f},
{1.0f, -1.0f, -1.0f}, {1.0f, 1.0f, 1.0f},
{-1.0f, 1.0f, 1.0f}, {-1.0f, 1.0f, -1.0f}
};
I mean, to take a value and put it inside the matrix on running time. I
tried to make a pointer to float, then adding 3D elements by new, but the
results were not what I want.
Note that I don't want to use STL like vector and so on, just a plane matrix.
cakePHP unique email username
cakePHP unique email username
I just need a bit of help with identifying the email of the user which is
also the username in the database, I used the 'isUnique' in the model but
for some reason it is not giving an error message and it still registers
the user please can someone give me a bit of help here is the code...
MODEL
App::uses('AuthComponent','Controller/Component');
class User extends AppModel
{
var $name = 'User';
public $validate = array(
'email' => 'email',
'email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please enter a valid email address for username',
'unique' => array(
'rule' => 'isUnique',
'message' => 'Please enter another email, this one is already taken'
)
)
),
'password' => array(
'required'=> array(
'rule' => array('notEmpty'),
'message' => 'Please enter a valid password',
'rule' => array('minLength','8'),
'message' => 'Please enter minimum 8 characters'
)
)
);
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] =
AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
}
**CONTROLLER**
<?php
class usersController extends AppController
{
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add');
}
var $name = 'Users';
public function add()
{
if (!empty($this ->data))
{
$this->User->create();
if ($this->User->save($this->data))
{
$this->Session->setFlash('Thank you for registering');
$this->redirect(array('action'=>'index'));
}
else
{
// Make the password fields blank
unset($this->data['User']['password']);
unset($this->data['User']['confirm_password']);
$this->Session->setFlash('An error occurred, try again!');
}
}
}
function index()
{
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}
$this->Session->setFlash(__('Invalid username or password, try
again'));
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
}
VIEW
<h2>End a problem registration</h2>
<p>Please fill out details to register</p>
<?php
echo $this->Form->Create('User',array('action' => 'add'));
echo $this->Form->input('title');
echo $this->Form->input('name');
echo $this->Form->input('surname');
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->input('password');
echo $this->Form->end('Register');
I just need a bit of help with identifying the email of the user which is
also the username in the database, I used the 'isUnique' in the model but
for some reason it is not giving an error message and it still registers
the user please can someone give me a bit of help here is the code...
MODEL
App::uses('AuthComponent','Controller/Component');
class User extends AppModel
{
var $name = 'User';
public $validate = array(
'email' => 'email',
'email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please enter a valid email address for username',
'unique' => array(
'rule' => 'isUnique',
'message' => 'Please enter another email, this one is already taken'
)
)
),
'password' => array(
'required'=> array(
'rule' => array('notEmpty'),
'message' => 'Please enter a valid password',
'rule' => array('minLength','8'),
'message' => 'Please enter minimum 8 characters'
)
)
);
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] =
AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
}
**CONTROLLER**
<?php
class usersController extends AppController
{
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add');
}
var $name = 'Users';
public function add()
{
if (!empty($this ->data))
{
$this->User->create();
if ($this->User->save($this->data))
{
$this->Session->setFlash('Thank you for registering');
$this->redirect(array('action'=>'index'));
}
else
{
// Make the password fields blank
unset($this->data['User']['password']);
unset($this->data['User']['confirm_password']);
$this->Session->setFlash('An error occurred, try again!');
}
}
}
function index()
{
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}
$this->Session->setFlash(__('Invalid username or password, try
again'));
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
}
VIEW
<h2>End a problem registration</h2>
<p>Please fill out details to register</p>
<?php
echo $this->Form->Create('User',array('action' => 'add'));
echo $this->Form->input('title');
echo $this->Form->input('name');
echo $this->Form->input('surname');
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->input('password');
echo $this->Form->end('Register');
Android alertdialogue returning boolean
Android alertdialogue returning boolean
I am wring a simple script where there is a confirmation box of two
options. I need to cal it more than one time in an activity. So i made a
method to do that. Based on the returning boolean i want to write the
conditional statements.
private void showConfirmation() {
// UserFunctions userFunctions = null;
// TODO Auto-generated methodastub
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(ProfileActivity.this);
// set title
alertDialogBuilder.setTitle("Mobile Gullak");
// set dialog message
alertDialogBuilder.setMessage("Please update the unfilled
fields.").setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
return false;
}
}).setNegativeButton("Later on", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
return true;
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
return false;
}
if(showConfirmation()){
// do something.
}
I am wring a simple script where there is a confirmation box of two
options. I need to cal it more than one time in an activity. So i made a
method to do that. Based on the returning boolean i want to write the
conditional statements.
private void showConfirmation() {
// UserFunctions userFunctions = null;
// TODO Auto-generated methodastub
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(ProfileActivity.this);
// set title
alertDialogBuilder.setTitle("Mobile Gullak");
// set dialog message
alertDialogBuilder.setMessage("Please update the unfilled
fields.").setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
return false;
}
}).setNegativeButton("Later on", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
return true;
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
return false;
}
if(showConfirmation()){
// do something.
}
My cart give a wrong total after severalupdates
My cart give a wrong total after severalupdates
1. 6.if($_SESSION['cart'][$f]['id']==$id){
$_SESSION['cart'][$f]['qty']=$qty; $f=$k;}//GET QTY 7. $f++;}
8.$query="SELECT price FROM computer_shop.product WHERE pid='$id'";
//QUERIES TO RETRIVE //PRICE FEOM DB 9.$run=mysql_query($query) or die
('Query error'); 10.$result=mysql_fetch_array($run);
$price=$result['price']; // PRICE OBTAINED 11.//FORMULA TO UPDATE CART 12.
//$sumUp=$_SESSION['cart'][$k]['qty']*$price; 13.
//$_SESSION['total']=$_SESSION['total']+$sumUp-$price; 14.
$_SESSION['total']=$_SESSION['total']+($_SESSION['cart'][$k]['qty']+1)*$price;
25.header('location: viewCart.php'); } ?>
1. 6.if($_SESSION['cart'][$f]['id']==$id){
$_SESSION['cart'][$f]['qty']=$qty; $f=$k;}//GET QTY 7. $f++;}
8.$query="SELECT price FROM computer_shop.product WHERE pid='$id'";
//QUERIES TO RETRIVE //PRICE FEOM DB 9.$run=mysql_query($query) or die
('Query error'); 10.$result=mysql_fetch_array($run);
$price=$result['price']; // PRICE OBTAINED 11.//FORMULA TO UPDATE CART 12.
//$sumUp=$_SESSION['cart'][$k]['qty']*$price; 13.
//$_SESSION['total']=$_SESSION['total']+$sumUp-$price; 14.
$_SESSION['total']=$_SESSION['total']+($_SESSION['cart'][$k]['qty']+1)*$price;
25.header('location: viewCart.php'); } ?>
Get Flash video uri from webview in android
Get Flash video uri from webview in android
Recently i made a app that can download flash video from webview because
of the webview calls the onShowCustomView() but when the device run on
android 3.0 + then the webview does not call the method instead webview
calls some class to handle the video. so i want to force the webview to
use CustomView to play the video. But i have not any idea how can do this
. Please help me.
Recently i made a app that can download flash video from webview because
of the webview calls the onShowCustomView() but when the device run on
android 3.0 + then the webview does not call the method instead webview
calls some class to handle the video. so i want to force the webview to
use CustomView to play the video. But i have not any idea how can do this
. Please help me.
Friday, 30 August 2013
Python Code-complete System
Python Code-complete System
I'm working on a Python Autocomplete/Code-complete system. I'm already
able to parse my own source files with import ast to access my own defined
classes + functions.
Now I'd like to know, how to access the signatures of system-classes,
functions, constants etc..
How am I able to access this information? Is it also possible with
python's ast module?
I'm working on a Python Autocomplete/Code-complete system. I'm already
able to parse my own source files with import ast to access my own defined
classes + functions.
Now I'd like to know, how to access the signatures of system-classes,
functions, constants etc..
How am I able to access this information? Is it also possible with
python's ast module?
Thursday, 29 August 2013
ImageButton added to webview won't resize
ImageButton added to webview won't resize
I have a WebView that I want to add my own back button to, The webview is
one that has been set up specifically for viewing pdfs in app. I have
added the button and it works but I am unable to resize it or move it
around the screen, and as a result the pdf controls are underneath the
button and unusable. The button layout parameters seem to be something
along these lines (this is not in the code anywhere this is just what it
appears to be )
<ImageButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
/>
Here is the activity
public class PDFview extends Activity {
ImageButton im;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Intent intent = getIntent();
String LinkTo = intent.getExtras().getString("link");
WebView mWebView= new WebView(this);
im = new ImageButton(this);
im.setImageResource(R.drawable.back);
im.setLayoutParams(new LayoutParams(100,100));
im.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
exitPDF();
}
});
im.setLeft(0);
im.setTop(200);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url="+LinkTo);
mWebView.addView(im);
setContentView(mWebView);
}
I have a WebView that I want to add my own back button to, The webview is
one that has been set up specifically for viewing pdfs in app. I have
added the button and it works but I am unable to resize it or move it
around the screen, and as a result the pdf controls are underneath the
button and unusable. The button layout parameters seem to be something
along these lines (this is not in the code anywhere this is just what it
appears to be )
<ImageButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
/>
Here is the activity
public class PDFview extends Activity {
ImageButton im;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Intent intent = getIntent();
String LinkTo = intent.getExtras().getString("link");
WebView mWebView= new WebView(this);
im = new ImageButton(this);
im.setImageResource(R.drawable.back);
im.setLayoutParams(new LayoutParams(100,100));
im.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
exitPDF();
}
});
im.setLeft(0);
im.setTop(200);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url="+LinkTo);
mWebView.addView(im);
setContentView(mWebView);
}
Wednesday, 28 August 2013
how to use wso2 esb with cxf?
how to use wso2 esb with cxf?
Is it possible to deploy CXF Web Services in wso2 ESB ?
Currently I have started referring documentation of wso2 from WSO2 User
Guide and I want to deploy an existing CXF Web Service to ESB. So any
information on this will be very helpful.
Is it possible to deploy CXF Web Services in wso2 ESB ?
Currently I have started referring documentation of wso2 from WSO2 User
Guide and I want to deploy an existing CXF Web Service to ESB. So any
information on this will be very helpful.
li menu links going back when page loads + css
li menu links going back when page loads + css
Hi I have a menu formed using
<ui>
<li>Configuiration<li/>
<li>Reporting<li/>
<ui>
<li>Pipeline</li>
<li>D2C OBI Reports</li>
<li>Device Utilization</li>
<li>Display Audit</li>
<li>True Reports</li>
</ui>
<li>Admin<li/>
<ui/>
When I clikc on a link example -- Display Audit -- when the page gets
loaded -- the menu link goes back... that is as seen in image last two
links go back of the page..... how can I display the menu link above the
page ??
I am using IE7, CSS 2.1
Hi I have a menu formed using
<ui>
<li>Configuiration<li/>
<li>Reporting<li/>
<ui>
<li>Pipeline</li>
<li>D2C OBI Reports</li>
<li>Device Utilization</li>
<li>Display Audit</li>
<li>True Reports</li>
</ui>
<li>Admin<li/>
<ui/>
When I clikc on a link example -- Display Audit -- when the page gets
loaded -- the menu link goes back... that is as seen in image last two
links go back of the page..... how can I display the menu link above the
page ??
I am using IE7, CSS 2.1
Keyboard pushing layout elements "up" along with it
Keyboard pushing layout elements "up" along with it
I have an app with ListView in it and I added search functionality to it.
When I press on EditText and it opens keyboard, it pushes everything in
the layout along with it.
Normal layout:
With keyboard:
As you can see; the ad, play button, seekbar are all pushed up along with
the keyboard, but I don't want that. Is there a way I can avoid this?
I tried adding this to Manifest file:
android:windowSoftInputMode="stateUnchanged"
But that doesn't work.
I have an app with ListView in it and I added search functionality to it.
When I press on EditText and it opens keyboard, it pushes everything in
the layout along with it.
Normal layout:
With keyboard:
As you can see; the ad, play button, seekbar are all pushed up along with
the keyboard, but I don't want that. Is there a way I can avoid this?
I tried adding this to Manifest file:
android:windowSoftInputMode="stateUnchanged"
But that doesn't work.
How to add a custom function in a xaf application
How to add a custom function in a xaf application
In my XAF application I have 1 business object called KeyWord and have 4
fields: Content, CPC, SearchAmmount and Competition. Well I need to add
custom function in my application and a button on toolbar. this function
should obtain adwords info and insert into database. Well my question is
how to add such function (or any other function) in a xaf web/desktop
application.
In my XAF application I have 1 business object called KeyWord and have 4
fields: Content, CPC, SearchAmmount and Competition. Well I need to add
custom function in my application and a button on toolbar. this function
should obtain adwords info and insert into database. Well my question is
how to add such function (or any other function) in a xaf web/desktop
application.
Put File path on file browser Android
Put File path on file browser Android
I have file path "sdcard/pic.jpg" now i want to put this path when user
choose any file for upload from internet browser.I done intent filters on
android mainfest. So when user want to upload some file from internet
browser it ask action using with : Filemanager Gallery -MyApp-
All this done
Now i want to put "/sdcard/pic.jpg" path when -Myapp- was clicked.... Can
anybody understand my problem if yes than please please help me how i do
this.please provide me working code...thanks
I have file path "sdcard/pic.jpg" now i want to put this path when user
choose any file for upload from internet browser.I done intent filters on
android mainfest. So when user want to upload some file from internet
browser it ask action using with : Filemanager Gallery -MyApp-
All this done
Now i want to put "/sdcard/pic.jpg" path when -Myapp- was clicked.... Can
anybody understand my problem if yes than please please help me how i do
this.please provide me working code...thanks
WP8 check SQL Azure values and perform task
WP8 check SQL Azure values and perform task
I have a plan to set up a SQL Azure database and then let my windows phone
application check some values and then if the values are good the perform
a task in the application.
My thought is that I have a database containing firstname, lastname,
signature, code1 and code2. In my application I sign in with
first,lastname and signature. Here I am thinking that the app will check
the database for first and last name and signature.
Then if firstname, lastname and a signature is a match then it get the
code1 and code2 and save it in isolated storage to be used on some needed
places in the app.
I have a plan to set up a SQL Azure database and then let my windows phone
application check some values and then if the values are good the perform
a task in the application.
My thought is that I have a database containing firstname, lastname,
signature, code1 and code2. In my application I sign in with
first,lastname and signature. Here I am thinking that the app will check
the database for first and last name and signature.
Then if firstname, lastname and a signature is a match then it get the
code1 and code2 and save it in isolated storage to be used on some needed
places in the app.
Tuesday, 27 August 2013
Readable row key cassandra
Readable row key cassandra
We are investigating migrating a system from a RDBMS to Cassandra and are
having trouble finding a way to convert auto-increment column to
Cassandra. We actually have no need for this to be sequential at all, it
can even contain characters, but it must be short (ideally under 8 chars)
and globally unique. Ideal value would look something like
AB123456
First part of the question is should we be generating this key in
application code or in Cassandra?
Second part: If Cassandra, how?
If Application code, is it an acceptable pattern to generate a candidate
code then attempt an insert, if collision occurs then regenerate key
candidate and retry?
We are investigating migrating a system from a RDBMS to Cassandra and are
having trouble finding a way to convert auto-increment column to
Cassandra. We actually have no need for this to be sequential at all, it
can even contain characters, but it must be short (ideally under 8 chars)
and globally unique. Ideal value would look something like
AB123456
First part of the question is should we be generating this key in
application code or in Cassandra?
Second part: If Cassandra, how?
If Application code, is it an acceptable pattern to generate a candidate
code then attempt an insert, if collision occurs then regenerate key
candidate and retry?
InputStreamReader don't limit returned length
InputStreamReader don't limit returned length
I am working on learning Java and am going through the examples on the
Android website. I am getting remote contents of an XML file. I am able to
get the contents of the file, but then I need to convert the InputStream
into a String.
public String readIt(InputStream stream, int len) throws IOException,
UnsupportedEncodingException {
InputStreamReader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
The issue I am having is I don't want the string to be limited by the len
var. But, I don't know java well enough to know how to change this.
How can I create the char without a length?
I am working on learning Java and am going through the examples on the
Android website. I am getting remote contents of an XML file. I am able to
get the contents of the file, but then I need to convert the InputStream
into a String.
public String readIt(InputStream stream, int len) throws IOException,
UnsupportedEncodingException {
InputStreamReader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
The issue I am having is I don't want the string to be limited by the len
var. But, I don't know java well enough to know how to change this.
How can I create the char without a length?
List the bounce back email ids - .net
List the bounce back email ids - .net
I am sending a mail to bunch of email ids.
once send the emails, i need to display the notification - saying how many
successful mails sent and how many to which mail ids the email was bounced
back.
Can I do this using .net code? if so, Can any one guide me through a .net
code to do this?
I am sending a mail to bunch of email ids.
once send the emails, i need to display the notification - saying how many
successful mails sent and how many to which mail ids the email was bounced
back.
Can I do this using .net code? if so, Can any one guide me through a .net
code to do this?
Collection property not properly added to parent on save
Collection property not properly added to parent on save
Look at the following code example.
What it does:
Iterates a bunch of customers. If it already knows the customer, it
retrieves the existing database object for that customer (this is the
problem-ridden part). Otherwise, it creates a new object (this works
fine).
All loans where the social security number matches (CPR) will be added to
the new or existing customer.
The problem: it works for new customer objects, but when I retrieve an
existing customer object, the loans lose their relation to the customer
when saved (CustomerID = null). They are still saved to the database.
Any ideas?
protected void BuildCustomerData()
{
Console.WriteLine(" Starting the customer build.");
var counter = 0;
var recycleCount = 100;
var reportingCount = 100;
var sTime = DateTime.Now;
var q = from c in db.IntermediaryRkos
select c.CPR;
var distincts = q.Distinct().ToArray();
var numbersToProcess = distincts.Count();
Console.WriteLine(" Identified " + numbersToProcess + " customers. "
+ (DateTime.Now - sTime).TotalSeconds);
foreach (var item in distincts)
{
var loans = from c in db.IntermediaryRkos
where c.CPR == item
select c;
var existing = db.Customers.Where(x => x.CPR ==
item).FirstOrDefault();
if (existing != null)
{
this.GenerateLoanListFor(existing, loans);
db.Entry(existing).State = System.Data.EntityState.Modified;
}
else
{
var customer = new Customer
{
CPR = item,
};
this.GenerateLoanListFor(customer, loans);
db.Customers.Add(customer);
db.Entry(customer).State = System.Data.EntityState.Added;
}
counter++;
if (counter % recycleCount == 0)
{
this.SaveAndRecycleContext();
}
if (counter % reportingCount == 0)
{
Console.WriteLine(" Processed " + counter + " customers of
" + numbersToProcess + ".");
}
}
db.SaveChanges();
}
protected void GenerateLoanListFor(Customer customer,
IQueryable<IntermediaryRko> loans)
{
customer.Loans = new List<Loan>();
foreach (var item in loans.Where(x => x.DebtPrefix ==
"SomeCategory").ToList())
{
var transformed = StudentLoanMap.CreateFrom(item);
customer.Loans.Add(transformed);
db.Entry(transformed).State = System.Data.EntityState.Added;
}
}
Look at the following code example.
What it does:
Iterates a bunch of customers. If it already knows the customer, it
retrieves the existing database object for that customer (this is the
problem-ridden part). Otherwise, it creates a new object (this works
fine).
All loans where the social security number matches (CPR) will be added to
the new or existing customer.
The problem: it works for new customer objects, but when I retrieve an
existing customer object, the loans lose their relation to the customer
when saved (CustomerID = null). They are still saved to the database.
Any ideas?
protected void BuildCustomerData()
{
Console.WriteLine(" Starting the customer build.");
var counter = 0;
var recycleCount = 100;
var reportingCount = 100;
var sTime = DateTime.Now;
var q = from c in db.IntermediaryRkos
select c.CPR;
var distincts = q.Distinct().ToArray();
var numbersToProcess = distincts.Count();
Console.WriteLine(" Identified " + numbersToProcess + " customers. "
+ (DateTime.Now - sTime).TotalSeconds);
foreach (var item in distincts)
{
var loans = from c in db.IntermediaryRkos
where c.CPR == item
select c;
var existing = db.Customers.Where(x => x.CPR ==
item).FirstOrDefault();
if (existing != null)
{
this.GenerateLoanListFor(existing, loans);
db.Entry(existing).State = System.Data.EntityState.Modified;
}
else
{
var customer = new Customer
{
CPR = item,
};
this.GenerateLoanListFor(customer, loans);
db.Customers.Add(customer);
db.Entry(customer).State = System.Data.EntityState.Added;
}
counter++;
if (counter % recycleCount == 0)
{
this.SaveAndRecycleContext();
}
if (counter % reportingCount == 0)
{
Console.WriteLine(" Processed " + counter + " customers of
" + numbersToProcess + ".");
}
}
db.SaveChanges();
}
protected void GenerateLoanListFor(Customer customer,
IQueryable<IntermediaryRko> loans)
{
customer.Loans = new List<Loan>();
foreach (var item in loans.Where(x => x.DebtPrefix ==
"SomeCategory").ToList())
{
var transformed = StudentLoanMap.CreateFrom(item);
customer.Loans.Add(transformed);
db.Entry(transformed).State = System.Data.EntityState.Added;
}
}
Combo box binding in mvvm
Combo box binding in mvvm
I am not able to find out Why is combo box binding not working?
I have a view model which looks like (2 properties)
public ProcessMaintenanceDataObject CurrentProcess
{
get
{
return _CurrentProcess;
}
set
{
_CurrentProcess = value;
OnPropertyChanged("CurrentProcess");
}
}
public ProcessMaintenanceCollection Processes
{
get
{
return _Processes;
}
set
{
_Processes = value;
OnPropertyChanged("Processes");
}
}
public FolderCollection Folders
{
get
{
return _folders;
}
set
{
_folders = value;
OnPropertyChanged("Folders");
}
}
The following is the ProcessMaintenanceDataObject definition
[DataMember]
public string ProcessName
{
get
{
return _ProcessName;
}
set
{
_ProcessName = value;
OnPropertyChanged("ProcessName");
}
}
[DataMember]
public string Id
{
get
{
return _Id;
}
set
{
_Id = value;
OnPropertyChanged("Id");
}
}
[DataMember]
public string FolderId
{
get
{
return _FolderId;
}
set
{
_FolderId = value;
OnPropertyChanged("FolderId");
}
}
[DataMember]
public FolderInfo Folder
{
get
{
return _Folder;
}
set
{
_Folder = value;
if (_Folder != null)
FolderId = _Folder.FolderId;
OnPropertyChanged("Folder");
}
}
The FolderInfo class has FolderName and FolderId Property.
I have a method in viewmodel which fills the Processes. In my view I have
structure something like, I have a treeview which will be bound to
Processes and while selecting any of the item from the treeview, i need to
allow user to edit that entity.
I the view the combo box binding is as:
<ComboBox ItemsSource="{Binding Path=Folders, Mode=OneWay}"
DisplayMemberPath="FolderName"
SelectedItem="{Binding Source={StaticResource viewModel},
Path=CurrentProcess.Folder, Mode=TwoWay}">
...
This binding doesn't work I mean when I select any object from the tree it
fills other information like ProcesName in the textBox but it doesn't make
the Folder object as the selected item in combobox, however the combo box
will be filled.
Any suggestion.
I am not able to find out Why is combo box binding not working?
I have a view model which looks like (2 properties)
public ProcessMaintenanceDataObject CurrentProcess
{
get
{
return _CurrentProcess;
}
set
{
_CurrentProcess = value;
OnPropertyChanged("CurrentProcess");
}
}
public ProcessMaintenanceCollection Processes
{
get
{
return _Processes;
}
set
{
_Processes = value;
OnPropertyChanged("Processes");
}
}
public FolderCollection Folders
{
get
{
return _folders;
}
set
{
_folders = value;
OnPropertyChanged("Folders");
}
}
The following is the ProcessMaintenanceDataObject definition
[DataMember]
public string ProcessName
{
get
{
return _ProcessName;
}
set
{
_ProcessName = value;
OnPropertyChanged("ProcessName");
}
}
[DataMember]
public string Id
{
get
{
return _Id;
}
set
{
_Id = value;
OnPropertyChanged("Id");
}
}
[DataMember]
public string FolderId
{
get
{
return _FolderId;
}
set
{
_FolderId = value;
OnPropertyChanged("FolderId");
}
}
[DataMember]
public FolderInfo Folder
{
get
{
return _Folder;
}
set
{
_Folder = value;
if (_Folder != null)
FolderId = _Folder.FolderId;
OnPropertyChanged("Folder");
}
}
The FolderInfo class has FolderName and FolderId Property.
I have a method in viewmodel which fills the Processes. In my view I have
structure something like, I have a treeview which will be bound to
Processes and while selecting any of the item from the treeview, i need to
allow user to edit that entity.
I the view the combo box binding is as:
<ComboBox ItemsSource="{Binding Path=Folders, Mode=OneWay}"
DisplayMemberPath="FolderName"
SelectedItem="{Binding Source={StaticResource viewModel},
Path=CurrentProcess.Folder, Mode=TwoWay}">
...
This binding doesn't work I mean when I select any object from the tree it
fills other information like ProcesName in the textBox but it doesn't make
the Folder object as the selected item in combobox, however the combo box
will be filled.
Any suggestion.
Monday, 26 August 2013
Eclipse download ftp files
Eclipse download ftp files
How do I cope files/directories from the Remote Systems panel in Eclipse
to my hard-drive using FTP? I'm already logged in and can view/edit the
files.
I'm using Eclipse 3.8.1 on Ubuntu 13.04.
How do I cope files/directories from the Remote Systems panel in Eclipse
to my hard-drive using FTP? I'm already logged in and can view/edit the
files.
I'm using Eclipse 3.8.1 on Ubuntu 13.04.
Specific URL If statement in PHP
Specific URL If statement in PHP
I'm trying to add an if statement that only executes the mobile redirect
in this wordpress plugin if the url equals a certain location. I assume it
would be placed in the location that determines whether or not the browser
is mobile or not. I've tried a few different pieces of code with no
success. Any help would be much appreciated.
<?php
/*
Plugin Name: Mobile Redirect
Description: Select a URL to point mobile users to
Author: Ozette Plugins
Version: 1.4.1
Author URI: http://ozette.com/
*/
/* Copyright 2013 Ozette Plugins (email : plugins@ozette.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
$ios_mobile_redirect = new IOS_Mobile_Redirect();
register_uninstall_hook( __FILE__, 'uninstall_mobile_redirect' );
function uninstall_mobile_redirect() {
delete_option( 'mobileredirecturl' );
delete_option( 'mobileredirecttoggle' );
delete_option( 'mobileredirectmode' );
delete_option( 'mobileredirecttablet' );
}
class IOS_Mobile_Redirect{
function __construct() { //init function
add_action( 'admin_init', array( &$this, 'admin_init' ) );
add_action( 'admin_menu', array( &$this, 'admin_menu' ) );
add_action( 'template_redirect', array( &$this,
'template_redirect' ) );
// upgrade option from 1.1 to 1.2
if ( get_option( 'mobileredirecttoggle' ) == 'true' )
update_option( 'mobileredirecttoggle', true );
}
function admin_init() {
add_filter( 'plugin_action_links_'. plugin_basename( __FILE__ ),
array( &$this, 'plugin_action_links' ), 10, 4 );
}
function plugin_action_links( $actions, $plugin_file, $plugin_data,
$context ) {
if ( is_plugin_active( $plugin_file ) )
$actions[] = '<a href="' .
admin_url('options-general.php?page=simple-mobile-url-redirect/mobile-redirect.php')
. '">Configure</a>';
return $actions;
}
function admin_menu() {
add_submenu_page( 'options-general.php', __( 'Mobile Redirect',
'mobile-redirect' ), __( 'Mobile Redirect', 'mobile-redirect' ),
'administrator', __FILE__, array( &$this, 'page' ) );
}
function page() { //admin options page
//do stuff if form is submitted
if ( isset( $_POST['mobileurl'] ) ) {
update_option( 'mobileredirecturl', esc_url_raw(
$_POST['mobileurl'] ) );
update_option( 'mobileredirecttoggle', isset(
$_POST['mobiletoggle'] ) ? true : false );
update_option( 'mobileredirectmode', intval(
$_POST['mobilemode'] ) );
update_option( 'mobileredirecttablet', isset(
$_POST['mobileredirecttablet'] ) );
update_option( 'mobileredirectonce', isset(
$_POST['mobileredirectonce'] ) ? true : false );
update_option( 'mobileredirectoncedays', intval(
$_POST['mobileredirectoncedays'] ) );
echo '<div class="updated"><p>' . __( 'Updated',
'mobile-redirect' ) . '</p></div>';
}
?>
<div class="wrap"><h2><?php _e( 'Mobile Redirect',
'mobile-redirect' ); ?></h2>
<p>
<?php _e( 'If the checkbox is checked, and a valid URL is
inputted, this site will redirect to the specified URL when
visited by a mobile device.', 'mobile-redirect' ); ?>
<?php // _e( 'This does not include the iPad, but will include
most other mobile devices.', 'mobile-redirect' ); ?>
</p>
<form method="post">
<p>
<label for="mobiletoggle"><?php _e( 'Enable Redirect:',
'mobile-redirect' ); ?>
<input type="checkbox" value="1" name="mobiletoggle"
id="mobiletoggle" <?php checked(
get_option('mobileredirecttoggle', ''), 1 ); ?> /></label>
</p>
<p>
<label for="mobileurl"><?php _e( 'Redirect URL:',
'mobile-redirect' ); ?>
<input type="text" name="mobileurl" id="mobileurl"
value="<?php echo esc_url( get_option('mobileredirecturl', '')
); ?>" /></label>
</p>
<p>
<label for="mobilemode"><?php _e( 'Redirect Mode:',
'mobile-redirect' ); ?>
<select id="mobilemode" name="mobilemode">
<option value="301" <?php selected(
get_option('mobileredirectmode', 301 ), 301 );
?>>301</option>
<option value="302" <?php selected(
get_option('mobileredirectmode'), 302 ); ?>>302</option>
</select>
</label>
</p>
<p>
<label for="mobileredirecttablet"><?php _e( 'Redirect
Tablets:', 'mobile-redirect' ); ?>
<input type="checkbox" value="1" name="mobileredirecttablet"
id="mobileredirecttablet" <?php checked(
get_option('mobileredirecttablet', ''), 1 ); ?> /></label>
</p>
<p>
<label for="mobileredirectonce"><?php _e( 'Redirect Once:',
'mobile-redirect' ); ?>
<input type="checkbox" value="1" name="mobileredirectonce"
id="mobileredirectonce" <?php checked(
get_option('mobileredirectonce', ''), 1 ); ?> /></label>
</p>
<p>
<label for="mobileredirectoncedays"><?php _e( 'Redirect Once
Cookie Expiry:', 'mobile-redirect' ); ?>
<input type="text" name="mobileredirectoncedays"
id="mobileredirectoncedays" value="<?php echo esc_attr(
get_option('mobileredirectoncedays', 7 ) ); ?>" />
days.</label>
<span class="description">If <em>Redirect Once</em> is
checked, a cookie will be set for the user to prevent them
from being continually redirected to the same page. This
cookie will expire by default after 7 days. Setting to zero or
less is effectively the same as unchecking Redirect
Once</span>
</p>
<?php submit_button(); ?>
</form>
</div>
<div class="copyFooter">Plugin written by <a
href="http://ozette.com">Ozette Plugins</a>.</div>
<?php
}
function is_mobile() {
$mobile_browser = '0';
if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone)/i',
strtolower($_SERVER['HTTP_USER_AGENT']))) {
$mobile_browser++;
}
if((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml')>0)
or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or
isset($_SERVER['HTTP_PROFILE'])))) {
$mobile_browser++;
}
$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));
$mobile_agents = array(
'w3c
','acs-','alav','alca','amoi','audi','avan','andr','benq','bird','blac',
'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
'newt','noki','palm','pana','pant','phil','play','port','prox',
'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
'wapr','webc','winw','winw','xda','xda-');
if(in_array($mobile_ua,$mobile_agents)) {
$mobile_browser++;
}
if (isset($_SERVER['ALL_HTTP']) &&
strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini')>0) {
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'mobile
safari')>0) {
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows')>0) {
$mobile_browser=0;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'android')>0) {
//if
(strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'gecko')>0) {
$mobile_browser++;
//}
}
if($mobile_browser>0) { return true; }
else { return false; }
}
function template_redirect() {
//check if tablet box is checked
if( get_option('mobileredirecttablet') == 0){
//redirect non-tablets
if(!self::is_mobile() )
return;
} else {
// not mobile
if ( ! wp_is_mobile() )
return;
}
// not enabled
if ( ! get_option('mobileredirecttoggle') )
return;
$mr_url = esc_url( get_option('mobileredirecturl', '') );
// empty url
if ( empty( $mr_url ) )
return;
$cur_url = esc_url("http://". $_SERVER["HTTP_HOST"] .
$_SERVER["REQUEST_URI"] );
$cookiedays = intval( get_option( 'mobileredirectoncedays', 7 ) );
// cookie can be expired by setting to a negative number
// but it's better just to uncheck the redirect once option
if ( $cookiedays <= 0 || ! get_option( 'mobileredirectonce' ) ) {
setcookie( 'mobile_single_redirect', true, time()-(60*60), '/' );
unset($_COOKIE['mobile_single_redirect']);
}
// make sure we don't redirect to ourself
if ( $mr_url != $cur_url ) {
if ( isset( $_COOKIE['mobile_single_redirect'] ) ) return;
if ( get_option( 'mobileredirectonce', '' ) )
setcookie( 'mobile_single_redirect', true,
time()+(60*60*24*$cookiedays ), '/' );
wp_redirect( $mr_url, get_option('mobileredirectmode', '301' ) );
exit;
}
}
}
// eof
I'm trying to add an if statement that only executes the mobile redirect
in this wordpress plugin if the url equals a certain location. I assume it
would be placed in the location that determines whether or not the browser
is mobile or not. I've tried a few different pieces of code with no
success. Any help would be much appreciated.
<?php
/*
Plugin Name: Mobile Redirect
Description: Select a URL to point mobile users to
Author: Ozette Plugins
Version: 1.4.1
Author URI: http://ozette.com/
*/
/* Copyright 2013 Ozette Plugins (email : plugins@ozette.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
$ios_mobile_redirect = new IOS_Mobile_Redirect();
register_uninstall_hook( __FILE__, 'uninstall_mobile_redirect' );
function uninstall_mobile_redirect() {
delete_option( 'mobileredirecturl' );
delete_option( 'mobileredirecttoggle' );
delete_option( 'mobileredirectmode' );
delete_option( 'mobileredirecttablet' );
}
class IOS_Mobile_Redirect{
function __construct() { //init function
add_action( 'admin_init', array( &$this, 'admin_init' ) );
add_action( 'admin_menu', array( &$this, 'admin_menu' ) );
add_action( 'template_redirect', array( &$this,
'template_redirect' ) );
// upgrade option from 1.1 to 1.2
if ( get_option( 'mobileredirecttoggle' ) == 'true' )
update_option( 'mobileredirecttoggle', true );
}
function admin_init() {
add_filter( 'plugin_action_links_'. plugin_basename( __FILE__ ),
array( &$this, 'plugin_action_links' ), 10, 4 );
}
function plugin_action_links( $actions, $plugin_file, $plugin_data,
$context ) {
if ( is_plugin_active( $plugin_file ) )
$actions[] = '<a href="' .
admin_url('options-general.php?page=simple-mobile-url-redirect/mobile-redirect.php')
. '">Configure</a>';
return $actions;
}
function admin_menu() {
add_submenu_page( 'options-general.php', __( 'Mobile Redirect',
'mobile-redirect' ), __( 'Mobile Redirect', 'mobile-redirect' ),
'administrator', __FILE__, array( &$this, 'page' ) );
}
function page() { //admin options page
//do stuff if form is submitted
if ( isset( $_POST['mobileurl'] ) ) {
update_option( 'mobileredirecturl', esc_url_raw(
$_POST['mobileurl'] ) );
update_option( 'mobileredirecttoggle', isset(
$_POST['mobiletoggle'] ) ? true : false );
update_option( 'mobileredirectmode', intval(
$_POST['mobilemode'] ) );
update_option( 'mobileredirecttablet', isset(
$_POST['mobileredirecttablet'] ) );
update_option( 'mobileredirectonce', isset(
$_POST['mobileredirectonce'] ) ? true : false );
update_option( 'mobileredirectoncedays', intval(
$_POST['mobileredirectoncedays'] ) );
echo '<div class="updated"><p>' . __( 'Updated',
'mobile-redirect' ) . '</p></div>';
}
?>
<div class="wrap"><h2><?php _e( 'Mobile Redirect',
'mobile-redirect' ); ?></h2>
<p>
<?php _e( 'If the checkbox is checked, and a valid URL is
inputted, this site will redirect to the specified URL when
visited by a mobile device.', 'mobile-redirect' ); ?>
<?php // _e( 'This does not include the iPad, but will include
most other mobile devices.', 'mobile-redirect' ); ?>
</p>
<form method="post">
<p>
<label for="mobiletoggle"><?php _e( 'Enable Redirect:',
'mobile-redirect' ); ?>
<input type="checkbox" value="1" name="mobiletoggle"
id="mobiletoggle" <?php checked(
get_option('mobileredirecttoggle', ''), 1 ); ?> /></label>
</p>
<p>
<label for="mobileurl"><?php _e( 'Redirect URL:',
'mobile-redirect' ); ?>
<input type="text" name="mobileurl" id="mobileurl"
value="<?php echo esc_url( get_option('mobileredirecturl', '')
); ?>" /></label>
</p>
<p>
<label for="mobilemode"><?php _e( 'Redirect Mode:',
'mobile-redirect' ); ?>
<select id="mobilemode" name="mobilemode">
<option value="301" <?php selected(
get_option('mobileredirectmode', 301 ), 301 );
?>>301</option>
<option value="302" <?php selected(
get_option('mobileredirectmode'), 302 ); ?>>302</option>
</select>
</label>
</p>
<p>
<label for="mobileredirecttablet"><?php _e( 'Redirect
Tablets:', 'mobile-redirect' ); ?>
<input type="checkbox" value="1" name="mobileredirecttablet"
id="mobileredirecttablet" <?php checked(
get_option('mobileredirecttablet', ''), 1 ); ?> /></label>
</p>
<p>
<label for="mobileredirectonce"><?php _e( 'Redirect Once:',
'mobile-redirect' ); ?>
<input type="checkbox" value="1" name="mobileredirectonce"
id="mobileredirectonce" <?php checked(
get_option('mobileredirectonce', ''), 1 ); ?> /></label>
</p>
<p>
<label for="mobileredirectoncedays"><?php _e( 'Redirect Once
Cookie Expiry:', 'mobile-redirect' ); ?>
<input type="text" name="mobileredirectoncedays"
id="mobileredirectoncedays" value="<?php echo esc_attr(
get_option('mobileredirectoncedays', 7 ) ); ?>" />
days.</label>
<span class="description">If <em>Redirect Once</em> is
checked, a cookie will be set for the user to prevent them
from being continually redirected to the same page. This
cookie will expire by default after 7 days. Setting to zero or
less is effectively the same as unchecking Redirect
Once</span>
</p>
<?php submit_button(); ?>
</form>
</div>
<div class="copyFooter">Plugin written by <a
href="http://ozette.com">Ozette Plugins</a>.</div>
<?php
}
function is_mobile() {
$mobile_browser = '0';
if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone)/i',
strtolower($_SERVER['HTTP_USER_AGENT']))) {
$mobile_browser++;
}
if((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml')>0)
or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or
isset($_SERVER['HTTP_PROFILE'])))) {
$mobile_browser++;
}
$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));
$mobile_agents = array(
'w3c
','acs-','alav','alca','amoi','audi','avan','andr','benq','bird','blac',
'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
'newt','noki','palm','pana','pant','phil','play','port','prox',
'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
'wapr','webc','winw','winw','xda','xda-');
if(in_array($mobile_ua,$mobile_agents)) {
$mobile_browser++;
}
if (isset($_SERVER['ALL_HTTP']) &&
strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini')>0) {
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'mobile
safari')>0) {
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows')>0) {
$mobile_browser=0;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'android')>0) {
//if
(strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'gecko')>0) {
$mobile_browser++;
//}
}
if($mobile_browser>0) { return true; }
else { return false; }
}
function template_redirect() {
//check if tablet box is checked
if( get_option('mobileredirecttablet') == 0){
//redirect non-tablets
if(!self::is_mobile() )
return;
} else {
// not mobile
if ( ! wp_is_mobile() )
return;
}
// not enabled
if ( ! get_option('mobileredirecttoggle') )
return;
$mr_url = esc_url( get_option('mobileredirecturl', '') );
// empty url
if ( empty( $mr_url ) )
return;
$cur_url = esc_url("http://". $_SERVER["HTTP_HOST"] .
$_SERVER["REQUEST_URI"] );
$cookiedays = intval( get_option( 'mobileredirectoncedays', 7 ) );
// cookie can be expired by setting to a negative number
// but it's better just to uncheck the redirect once option
if ( $cookiedays <= 0 || ! get_option( 'mobileredirectonce' ) ) {
setcookie( 'mobile_single_redirect', true, time()-(60*60), '/' );
unset($_COOKIE['mobile_single_redirect']);
}
// make sure we don't redirect to ourself
if ( $mr_url != $cur_url ) {
if ( isset( $_COOKIE['mobile_single_redirect'] ) ) return;
if ( get_option( 'mobileredirectonce', '' ) )
setcookie( 'mobile_single_redirect', true,
time()+(60*60*24*$cookiedays ), '/' );
wp_redirect( $mr_url, get_option('mobileredirectmode', '301' ) );
exit;
}
}
}
// eof
Capture rate issue and video rendering of silent audio frames
Capture rate issue and video rendering of silent audio frames
I'm new to video processing and I'm having a hard time with it. In my
application, an animation that lasts 8 seconds (more precisely, the video
contains 262 frames) should be mixed frame by frame (via OpenCV) with a
video recorded by the user (code snippets below).
The animation runs at 30 frames per second (the FrameGrabber for the
animation has a frame rate of 29.97002997002997 fps). Both the
MediaRecorder (that records the user video) and the FFmpegFrameRecorder
(that composes the animation with the user video) are set to run at 30fps
(MediaRecorder.setCaptureRate(30), FFmpegFrameRecorder.setFrameRate(30)).
As investigated by a call to
Camera.getParameters().getSupportedPreviewFpsRange(), the front camera of
my Samsung Galaxy S3 supports a range of 5-31 fps.
After the user video is ready, I check the frame rate of the FrameGrabber
for that recording (FrameGrabber.getFrameRate()), which returns 30. But
the MediaRecorder seems to work at around 15 fps: at least twice as much
time has to be recorded so as to keep the audio from the animation running
as expected, without being silenced at the end of the resulting video.
Because my MediaRecorder setting is not working and the Camera does not
support 60 fps, a workaround was inserted in the recording phase: now the
user has to record at least 16 seconds to produce around the same amount
of frames contained in the animation file. That works, but I feel there is
something wrong with this. I wonder if Camera resolution has a role in all
this, too (the animation will always be 720x480), and I have printed some
values about picture sizes supported, dimension setting for pictures and
preview pictures, info about preview size. I tried to dynamically change
resolution, but it didn't work out well, few configuration options from
CamcorderProfile, used to set the MediaRecorder (nothing exactly like
720x480, the best was to do:
MediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P))
).
The big problem is to discover how to include silent audio frames in the
beginning of the user video, because that animation will have to start not
in the beginning of the final video, but a few seconds later. I see
FFmpegFrameRecorder does not record a null Frame, not trivial.
I will appreciate any clue. Thank you!
private boolean prepareMediaRecorder() {
m_camera = getCameraInstance();
m_mediaRecorder = new MediaRecorder();
m_camera.unlock();
m_mediaRecorder.setCamera(m_camera);
m_mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
m_mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// CamcorderProfile.QUALITY_720P = "Quality level corresponding to the
720p (1280 x 720) resolution"
// NOT GOOD: CamcorderProfile.QUALITY_480P,
CamcorderProfile.QUALITY_TIME_LAPSE_480P, CamcorderProfile.QUALITY_LOW
m_mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P));
// FROM THE METHOD JAVADOC:
// "Note that the recorder cannot guarantee that frames will be
captured at the given rate due
// to camera/encoder limitations. However it tries to be as close as
possible."
m_mediaRecorder.setCaptureRate(FPS_30);
File outDir = new File(S_APP_FOLDER);
int numVids = outDir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return filename.startsWith("myVideo");
}
}).length;
m_mediaRecorder.setOutputFile(outDir.getAbsolutePath() + "/" +
"myvideo" + numVids + ".mp4");
m_mediaRecorder.setMaxDuration(MEDIA_RECORDER_MAX_DURATION);
// mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M
m_mediaRecorder.setPreviewDisplay(m_cameraSurfaceView.getHolder().getSurface());
try {
m_mediaRecorder.prepare();
} catch (IllegalStateException e) {
releaseMediaRecorder();
return false;
} catch (IOException e) {
releaseMediaRecorder();
return false;
}
return true;
}
// Create a frame recorder to encode resulting video
private FFmpegFrameRecorder createFrameRecorder(String outFilePath) {
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outFilePath,
grabberOrig.getImageWidth(),
grabberOrig.getImageHeight(), grabberAudio.getAudioChannels());
// Set audio params
recorder.setAudioCodec(com.googlecode.javacv.cpp.avcodec.AV_CODEC_ID_AAC);
recorder.setSampleFormat(grabberAudio.getSampleFormat());
recorder.setSampleRate(grabberAudio.getSampleRate());
// Set video params
recorder.setVideoCodec(com.googlecode.javacv.cpp.avcodec.AV_CODEC_ID_MPEG4);
recorder.setPixelFormat(com.googlecode.javacv.cpp.avutil.AV_PIX_FMT_YUV420P);
recorder.setFrameRate(FPS_30);
recorder.setVideoBitrate(716800); // PREVIOUSLY USED: 20000000
//recorder.setVideoQuality(2); // 0 means best
recorder.setFormat("mp4");
return recorder;
}
I'm new to video processing and I'm having a hard time with it. In my
application, an animation that lasts 8 seconds (more precisely, the video
contains 262 frames) should be mixed frame by frame (via OpenCV) with a
video recorded by the user (code snippets below).
The animation runs at 30 frames per second (the FrameGrabber for the
animation has a frame rate of 29.97002997002997 fps). Both the
MediaRecorder (that records the user video) and the FFmpegFrameRecorder
(that composes the animation with the user video) are set to run at 30fps
(MediaRecorder.setCaptureRate(30), FFmpegFrameRecorder.setFrameRate(30)).
As investigated by a call to
Camera.getParameters().getSupportedPreviewFpsRange(), the front camera of
my Samsung Galaxy S3 supports a range of 5-31 fps.
After the user video is ready, I check the frame rate of the FrameGrabber
for that recording (FrameGrabber.getFrameRate()), which returns 30. But
the MediaRecorder seems to work at around 15 fps: at least twice as much
time has to be recorded so as to keep the audio from the animation running
as expected, without being silenced at the end of the resulting video.
Because my MediaRecorder setting is not working and the Camera does not
support 60 fps, a workaround was inserted in the recording phase: now the
user has to record at least 16 seconds to produce around the same amount
of frames contained in the animation file. That works, but I feel there is
something wrong with this. I wonder if Camera resolution has a role in all
this, too (the animation will always be 720x480), and I have printed some
values about picture sizes supported, dimension setting for pictures and
preview pictures, info about preview size. I tried to dynamically change
resolution, but it didn't work out well, few configuration options from
CamcorderProfile, used to set the MediaRecorder (nothing exactly like
720x480, the best was to do:
MediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P))
).
The big problem is to discover how to include silent audio frames in the
beginning of the user video, because that animation will have to start not
in the beginning of the final video, but a few seconds later. I see
FFmpegFrameRecorder does not record a null Frame, not trivial.
I will appreciate any clue. Thank you!
private boolean prepareMediaRecorder() {
m_camera = getCameraInstance();
m_mediaRecorder = new MediaRecorder();
m_camera.unlock();
m_mediaRecorder.setCamera(m_camera);
m_mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
m_mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// CamcorderProfile.QUALITY_720P = "Quality level corresponding to the
720p (1280 x 720) resolution"
// NOT GOOD: CamcorderProfile.QUALITY_480P,
CamcorderProfile.QUALITY_TIME_LAPSE_480P, CamcorderProfile.QUALITY_LOW
m_mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P));
// FROM THE METHOD JAVADOC:
// "Note that the recorder cannot guarantee that frames will be
captured at the given rate due
// to camera/encoder limitations. However it tries to be as close as
possible."
m_mediaRecorder.setCaptureRate(FPS_30);
File outDir = new File(S_APP_FOLDER);
int numVids = outDir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return filename.startsWith("myVideo");
}
}).length;
m_mediaRecorder.setOutputFile(outDir.getAbsolutePath() + "/" +
"myvideo" + numVids + ".mp4");
m_mediaRecorder.setMaxDuration(MEDIA_RECORDER_MAX_DURATION);
// mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M
m_mediaRecorder.setPreviewDisplay(m_cameraSurfaceView.getHolder().getSurface());
try {
m_mediaRecorder.prepare();
} catch (IllegalStateException e) {
releaseMediaRecorder();
return false;
} catch (IOException e) {
releaseMediaRecorder();
return false;
}
return true;
}
// Create a frame recorder to encode resulting video
private FFmpegFrameRecorder createFrameRecorder(String outFilePath) {
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outFilePath,
grabberOrig.getImageWidth(),
grabberOrig.getImageHeight(), grabberAudio.getAudioChannels());
// Set audio params
recorder.setAudioCodec(com.googlecode.javacv.cpp.avcodec.AV_CODEC_ID_AAC);
recorder.setSampleFormat(grabberAudio.getSampleFormat());
recorder.setSampleRate(grabberAudio.getSampleRate());
// Set video params
recorder.setVideoCodec(com.googlecode.javacv.cpp.avcodec.AV_CODEC_ID_MPEG4);
recorder.setPixelFormat(com.googlecode.javacv.cpp.avutil.AV_PIX_FMT_YUV420P);
recorder.setFrameRate(FPS_30);
recorder.setVideoBitrate(716800); // PREVIOUSLY USED: 20000000
//recorder.setVideoQuality(2); // 0 means best
recorder.setFormat("mp4");
return recorder;
}
Overloading two functions with object and list parameter stackoverflow.com
Overloading two functions with object and list parameter – stackoverflow.com
Consider this code: static void Main(string[] args) { Log("Test");//Call
Log(object obj) Log(new List<string>{"Test","Test2"});;//Also Call
Log(object obj) } public …
Consider this code: static void Main(string[] args) { Log("Test");//Call
Log(object obj) Log(new List<string>{"Test","Test2"});;//Also Call
Log(object obj) } public …
StatET: No folder specified
StatET: No folder specified
Installed: R 3.0.1, Eclipse and StatET. Worked brilliantly for a while.
Problem: Can't save files or navigate through workspace.
Detail: R Console loads apparently as it should, BUT -Navigator pane is
blank -Outline is not available -Can't save files. When I try "save as" on
a script file it says: "No folder specified"
Is there a problem that I have my workspace originally on a network drive?
I'm hoping this is a "simple" beginner-error.
Obviously I have - to the best of my knowledge - scouted for solutions but
didn't find it, so please serious answers.
Thanks, Calle
Installed: R 3.0.1, Eclipse and StatET. Worked brilliantly for a while.
Problem: Can't save files or navigate through workspace.
Detail: R Console loads apparently as it should, BUT -Navigator pane is
blank -Outline is not available -Can't save files. When I try "save as" on
a script file it says: "No folder specified"
Is there a problem that I have my workspace originally on a network drive?
I'm hoping this is a "simple" beginner-error.
Obviously I have - to the best of my knowledge - scouted for solutions but
didn't find it, so please serious answers.
Thanks, Calle
i have already root my nexus4=?iso-8859-1?Q?=2Cbut_why_it_shows_=22shell@mako:/_$_=22when_i_enter_comm?=andadb sh=?iso-8859-1?Q?command=93adb_shell=94?=
i have already root my nexus4,but why it shows "shell@mako:/ $ "when i
enter command"adb shell"
Should not shell@mako:/ $ be shell@mako:/ #? Or I haven't root
successfully yet? How to check whether my nexus4 have root successfully?
Thanks!
enter command"adb shell"
Should not shell@mako:/ $ be shell@mako:/ #? Or I haven't root
successfully yet? How to check whether my nexus4 have root successfully?
Thanks!
Sunday, 25 August 2013
what kind of filter has the following property?
what kind of filter has the following property?
suppose the input signal f(x) = a0+a1*x+a2*x^2+a3*x^3+..., after
filtering, g(x)=h(x)*f(x). g(x) = a0+a2*x^2+a4*x^4+..., i.e. the filter
removes the odd polynomial components of the input signal f(x).
suppose the input signal f(x) = a0+a1*x+a2*x^2+a3*x^3+..., after
filtering, g(x)=h(x)*f(x). g(x) = a0+a2*x^2+a4*x^4+..., i.e. the filter
removes the odd polynomial components of the input signal f(x).
Update featured image before present post
Update featured image before present post
Site leases images therefore they need to be replaced once they expired.
We are planing to include the purchase date and expiration term (in days)
within the name of the image. For instance: 20130801_7_CoolBeans.png. This
says on Aug 8 2013 the image was leased and can be shown within the next
seven days. I'm new with wordpress, I have no idea where to place this
code, but yeah, the idea is to read the image name and if the post is
requested out of the image lease term we need to replace the featured
image with a default image and present the post.
Help is appreciated
Site leases images therefore they need to be replaced once they expired.
We are planing to include the purchase date and expiration term (in days)
within the name of the image. For instance: 20130801_7_CoolBeans.png. This
says on Aug 8 2013 the image was leased and can be shown within the next
seven days. I'm new with wordpress, I have no idea where to place this
code, but yeah, the idea is to read the image name and if the post is
requested out of the image lease term we need to replace the featured
image with a default image and present the post.
Help is appreciated
[ Movies ] Open Question : Is the oracle correct all the time? Clarice?
[ Movies ] Open Question : Is the oracle correct all the time? Clarice?
Obeying the oracle and having a chance to change the oracle's prediction
is okay? Is Clarice in The Sea of monsters supposed to have completed the
quest by herself without help? Because she got help means that she is not
always perfect? Is the oracle always correct or can change its
predictions? Was Percy supposed to have won and tarnish Clarice's winning
streak? Was Percy supposed to help his friend dangling from the rope? Is
it fate for Percy to help his friend and disobey the oracle? Changing the
oracles predictions means that things can change and one's destiny can
change regardless of the oracle?
Obeying the oracle and having a chance to change the oracle's prediction
is okay? Is Clarice in The Sea of monsters supposed to have completed the
quest by herself without help? Because she got help means that she is not
always perfect? Is the oracle always correct or can change its
predictions? Was Percy supposed to have won and tarnish Clarice's winning
streak? Was Percy supposed to help his friend dangling from the rope? Is
it fate for Percy to help his friend and disobey the oracle? Changing the
oracles predictions means that things can change and one's destiny can
change regardless of the oracle?
[ Polls & Surveys ] Open Question : -poll- Would u rather go to Walmart (5 minutes away) or your favorite supermarket that's 15 min away?
[ Polls & Surveys ] Open Question : -poll- Would u rather go to Walmart (5
minutes away) or your favorite supermarket that's 15 min away?
minutes away) or your favorite supermarket that's 15 min away?
finding sequences from small length sequences
finding sequences from small length sequences
I want to generate a space by using some events in a specific format. Let
me explain the problem on a small example.
Assume that I have the events a,b,c,d,e,f. I will have 3-length sequences
as an input consisting of these events. From these sequences I want to
generate 6-length (number of events) sequences and there will be no
repeated elements in the sequence, i.e. every event will be used exactly
once. 6-length sequences need to satisfy some rules.(explained on example)
Example:
Input:
list1:['a','b','c']
list2:['c','d','e']
list3:['b','c','d']
list4:['a','c','g']
list5:['f','g','e']
List1 describes that, b and c will come after a, and c will come after b
in the 6-length sequence, i.e, when the order changes sequence also
changes. In the same manner List2 describes that d and e will come after
c, and e will come after d. All of the lists will be taken and rules are
recorded. After all rules extracted from these sequences, I need to
generate 6-length sequence that obeys rules. As an example;
Lets say in our case(for simplicity) inputs are List1,List2 and List3
Input:
list1:['a','b','c']
list2:['c','d','e']
list3:['b','c','d']
Then some results for these lists are;
['a','b','c','d','e']: it obeys all of the rules from extracted these 3
lists, like b and c comes after a, d and e comes after c, c and d comes
after b. Ýmportant note from here, if c needs to come after a, they do not
need to be adjacent in the output sequence(6-length)
It is not guaranteed that 6-length sequence will always exist. Firstly, it
needs to be checked that there is at least one such sequence. If not,
algorithm should return false. As an example; lets assume our inputs are
Lis1, Lis2, Lis3, Lis4 and Lis5.
Input:
list1:['a','b','c']
list2:['c','d','e']
list3:['b','c','d']
list4:['a','c','g']
list5:['e','g','b']
a => b => c => g => b it is not possible since b can not come after itself.
I need an algorithm to generate these sequences in Python. I do not have
any code for now, because so far I could not think any efficient
algorithm. It needs to be very efficient in finding longer length
sequences, too.
If the question is not clear, please let me now.
Thanks
I want to generate a space by using some events in a specific format. Let
me explain the problem on a small example.
Assume that I have the events a,b,c,d,e,f. I will have 3-length sequences
as an input consisting of these events. From these sequences I want to
generate 6-length (number of events) sequences and there will be no
repeated elements in the sequence, i.e. every event will be used exactly
once. 6-length sequences need to satisfy some rules.(explained on example)
Example:
Input:
list1:['a','b','c']
list2:['c','d','e']
list3:['b','c','d']
list4:['a','c','g']
list5:['f','g','e']
List1 describes that, b and c will come after a, and c will come after b
in the 6-length sequence, i.e, when the order changes sequence also
changes. In the same manner List2 describes that d and e will come after
c, and e will come after d. All of the lists will be taken and rules are
recorded. After all rules extracted from these sequences, I need to
generate 6-length sequence that obeys rules. As an example;
Lets say in our case(for simplicity) inputs are List1,List2 and List3
Input:
list1:['a','b','c']
list2:['c','d','e']
list3:['b','c','d']
Then some results for these lists are;
['a','b','c','d','e']: it obeys all of the rules from extracted these 3
lists, like b and c comes after a, d and e comes after c, c and d comes
after b. Ýmportant note from here, if c needs to come after a, they do not
need to be adjacent in the output sequence(6-length)
It is not guaranteed that 6-length sequence will always exist. Firstly, it
needs to be checked that there is at least one such sequence. If not,
algorithm should return false. As an example; lets assume our inputs are
Lis1, Lis2, Lis3, Lis4 and Lis5.
Input:
list1:['a','b','c']
list2:['c','d','e']
list3:['b','c','d']
list4:['a','c','g']
list5:['e','g','b']
a => b => c => g => b it is not possible since b can not come after itself.
I need an algorithm to generate these sequences in Python. I do not have
any code for now, because so far I could not think any efficient
algorithm. It needs to be very efficient in finding longer length
sequences, too.
If the question is not clear, please let me now.
Thanks
Saturday, 24 August 2013
profiling tools for mvc app with very high cpu
profiling tools for mvc app with very high cpu
I am currently running an asp.net mvc application and under high load I am
seeing the site maxing out at 100%. This should not be the case and I
believe there may be an issue with the application that is degrading
performance. This application communicates directly to wcf services layer
which communicates to a sql server database. Neither the wcf layer or
database layer have any performance issues as the 100% CPU can be directly
apportioned to the MVC app.
Therefore I am looking at profiling where the issue may be in the MVC app
- preferably without changing any code. The server is a windows server
2008 R2 with IIS 7.5.
What tools are available to be to assist with this? For starters I have
been looking setting some performance counters.
I am currently running an asp.net mvc application and under high load I am
seeing the site maxing out at 100%. This should not be the case and I
believe there may be an issue with the application that is degrading
performance. This application communicates directly to wcf services layer
which communicates to a sql server database. Neither the wcf layer or
database layer have any performance issues as the 100% CPU can be directly
apportioned to the MVC app.
Therefore I am looking at profiling where the issue may be in the MVC app
- preferably without changing any code. The server is a windows server
2008 R2 with IIS 7.5.
What tools are available to be to assist with this? For starters I have
been looking setting some performance counters.
SQL INSERT INTO SELECT Statement Invalid use of group function
SQL INSERT INTO SELECT Statement Invalid use of group function
I've the following query:
INSERT INTO StatisticalConsultationAgreement VALUES (
queryType, entityCode, entityType, queryClass,queryTables,period,
COUNT(queryClass), SUM(numberRecords), SUM(recordsFound),
SUM(NorecordsFound), NOW(), 'system');
SELECT
MONTH(EndDateTimeProcessing),YEAR(EndDateTimeProcessing),
entityType,
entityCode,
queryType,
queryClass,
EndDateTimeProcessing as period
FROM agreementFile
WHERE
MONTH(EndDateTimeProcessing)=MONTH(DATE_SUB( CURDATE(), INTERVAL 1 MONTH ))
AND YEAR(EndDateTimeProcessing)=YEAR(CURDATE())
GROUP BY entityType,entitycode,queryType, queryClass;
When I run the query I get the next mistake:
Error code 1111, SQL state HY000: Invalid use of group function
Line 1, column 1
Executed successfully in 0,002 s.
Line 2, column 2
why ocurre this?
how to fix it?
I've the following query:
INSERT INTO StatisticalConsultationAgreement VALUES (
queryType, entityCode, entityType, queryClass,queryTables,period,
COUNT(queryClass), SUM(numberRecords), SUM(recordsFound),
SUM(NorecordsFound), NOW(), 'system');
SELECT
MONTH(EndDateTimeProcessing),YEAR(EndDateTimeProcessing),
entityType,
entityCode,
queryType,
queryClass,
EndDateTimeProcessing as period
FROM agreementFile
WHERE
MONTH(EndDateTimeProcessing)=MONTH(DATE_SUB( CURDATE(), INTERVAL 1 MONTH ))
AND YEAR(EndDateTimeProcessing)=YEAR(CURDATE())
GROUP BY entityType,entitycode,queryType, queryClass;
When I run the query I get the next mistake:
Error code 1111, SQL state HY000: Invalid use of group function
Line 1, column 1
Executed successfully in 0,002 s.
Line 2, column 2
why ocurre this?
how to fix it?
Malformed IP Address, new ubuntu installation
Malformed IP Address, new ubuntu installation
I am installing a Ubuntu 13.04 from virtual disc over IPMI, yet when I
come to manually configuring my network it tells me my IP address is
malformed and should be in the format 'x.x.x.x' when it is.
My IP address is 192.186.137.050 (will remove if against regulations).
Why is this error appearing?
I am installing a Ubuntu 13.04 from virtual disc over IPMI, yet when I
come to manually configuring my network it tells me my IP address is
malformed and should be in the format 'x.x.x.x' when it is.
My IP address is 192.186.137.050 (will remove if against regulations).
Why is this error appearing?
Stay on the same page after edit
Stay on the same page after edit
I'm trying to follow the RailsTutorial guide, but by doing my own
application instead. I have trouble with section 7, with the forms.
My controller :
def update
d = Deck.find(params[:id])
d.title = params[:deck][:title]
d.slug = params[:deck][:slug]
d.category = params[:deck][:category]
if d.save
redirect_to deck_path(d), notice: "Deck saved successfully"
else
render :edit
end
end
I know it's very, very far from good code, but I will refactor it later
(if you have a suggestion I'm all ears, but I use Rails 3, so I guess the
strong parameters of Rails 4 are out).
The problem is when the d.save does not work (due to validation), with the
render :edit.
Right now, when I enter invalid data, it tries to redirect to the show
action, and crashes because it does not have any data to display.
If I add @deck = d above the render, it works, but the url still is the
show action.
If my validation fail, how can I stay on the same URL and display my error
messages ? Is the "change URL but render the same page" behavior accepted
as valid ?
Thanks !
If you're interested in looking at the rest of the code, it's here :
https://github.com/cosmo0/TeachMTG/tree/remodel-decks
I'm trying to follow the RailsTutorial guide, but by doing my own
application instead. I have trouble with section 7, with the forms.
My controller :
def update
d = Deck.find(params[:id])
d.title = params[:deck][:title]
d.slug = params[:deck][:slug]
d.category = params[:deck][:category]
if d.save
redirect_to deck_path(d), notice: "Deck saved successfully"
else
render :edit
end
end
I know it's very, very far from good code, but I will refactor it later
(if you have a suggestion I'm all ears, but I use Rails 3, so I guess the
strong parameters of Rails 4 are out).
The problem is when the d.save does not work (due to validation), with the
render :edit.
Right now, when I enter invalid data, it tries to redirect to the show
action, and crashes because it does not have any data to display.
If I add @deck = d above the render, it works, but the url still is the
show action.
If my validation fail, how can I stay on the same URL and display my error
messages ? Is the "change URL but render the same page" behavior accepted
as valid ?
Thanks !
If you're interested in looking at the rest of the code, it's here :
https://github.com/cosmo0/TeachMTG/tree/remodel-decks
Whatsapp on emulator - Can't setup the recorder now, please try again later
Whatsapp on emulator - Can't setup the recorder now, please try again later
I have Whatsapp on my emulator (2.3.3 version). I got the latest update -
voice messaging. However, when I try to record a message, this is what
occurs.
I have no idea how to get this diagnosed. Can anything be done to help?
Any audio codecs need to be installed?
Tried adding Audio Recording Support, in vain.
UPDATE: Tried with ICS (4.0 version). It doesn't show the error, but it
doesn't send the audio message either. (The clock symbol in the
right-bottom corner never turns into a tick)
I have Whatsapp on my emulator (2.3.3 version). I got the latest update -
voice messaging. However, when I try to record a message, this is what
occurs.
I have no idea how to get this diagnosed. Can anything be done to help?
Any audio codecs need to be installed?
Tried adding Audio Recording Support, in vain.
UPDATE: Tried with ICS (4.0 version). It doesn't show the error, but it
doesn't send the audio message either. (The clock symbol in the
right-bottom corner never turns into a tick)
Friday, 23 August 2013
How to connect MySQL with C# 2008?
How to connect MySQL with C# 2008?
I have Visual studio 2008 express edition and MySQL server 5.5 installed
on my machine. When I try to connect MySQL using server explorer, I could
not get MySQL database in list of datasource. Then I installed MySQL
connector. Now I am getting Oracle listed as a datasource. But when I
connect using Oracle as a data source, I get an error saying : 8.1.7 or
higher version of Oracle client required. Do I need to install MySQL
workbench as well?
Please let me know if any way is available to connect MySQL with C# 2008 ?
I have Visual studio 2008 express edition and MySQL server 5.5 installed
on my machine. When I try to connect MySQL using server explorer, I could
not get MySQL database in list of datasource. Then I installed MySQL
connector. Now I am getting Oracle listed as a datasource. But when I
connect using Oracle as a data source, I get an error saying : 8.1.7 or
higher version of Oracle client required. Do I need to install MySQL
workbench as well?
Please let me know if any way is available to connect MySQL with C# 2008 ?
Returning count of child in json.rabl
Returning count of child in json.rabl
I have a Location model that I render in json format using Rabl. My
index.json.rabl looks that way :
object false
collection @locations
attributes :id, :name, :address, :rating
:rating is an integer calculated from records in the Rating model (a
Location has_many Rating, a Rating belongs_to a Location). But now I would
like to retrieve also in the Rabl file the number of line of the Rating
model used to calculate this value.
I tried :
child :ratings do
attributes :count
end
and
node(:ratings_count) { |m| @ratings.count }
But obviously it doesn't work... Could anyone help me there ?
Thanks !
I have a Location model that I render in json format using Rabl. My
index.json.rabl looks that way :
object false
collection @locations
attributes :id, :name, :address, :rating
:rating is an integer calculated from records in the Rating model (a
Location has_many Rating, a Rating belongs_to a Location). But now I would
like to retrieve also in the Rabl file the number of line of the Rating
model used to calculate this value.
I tried :
child :ratings do
attributes :count
end
and
node(:ratings_count) { |m| @ratings.count }
But obviously it doesn't work... Could anyone help me there ?
Thanks !
How to add widgets into the GWT Datagrid
How to add widgets into the GWT Datagrid
I need to render the html table using GWT DataGrid.How can put the GWT
anchor widget datagrid column cell.I need to add a listener to the anchor.
The html prototype row:" < TR> < g:anhcor class="icon-button delete"
$GT TR> "
My current code is not working properly the style adding to the entire cell :
ButtonCell deletebutton = new ButtonCell();
Column<KeywordData, String> deleteColumn = new Column<KeywordData,
String>(deletebutton) {
@Override
public String getValue(KeywordData keyword) {
return "";
}
};
deleteColumn.setCellStyleNames("icon-button delete");
keywordsGrid.addColumn(deleteColumn,"Delete");
I need to render the html table using GWT DataGrid.How can put the GWT
anchor widget datagrid column cell.I need to add a listener to the anchor.
The html prototype row:" < TR> < g:anhcor class="icon-button delete"
$GT TR> "
My current code is not working properly the style adding to the entire cell :
ButtonCell deletebutton = new ButtonCell();
Column<KeywordData, String> deleteColumn = new Column<KeywordData,
String>(deletebutton) {
@Override
public String getValue(KeywordData keyword) {
return "";
}
};
deleteColumn.setCellStyleNames("icon-button delete");
keywordsGrid.addColumn(deleteColumn,"Delete");
Logic challenge: sorting arrays alphabetically in C
Logic challenge: sorting arrays alphabetically in C
I'm new to programming, currently learning C. I've been working at this
problem for a week now, and I just can't seem to get the logic straight.
This is straight from the book I'm using:
Build a program that uses an array of strings to store the following names:
- "Florida" - "Oregon" - "Califoria" - "Georgia"
Using the preceding array of strings, write your own sort() function to
display each state's name in alphabetical order using the strcmp()
function.
Should I do nested for loops, like strcmp(string[x], string[y])...? I've
hacked and hacked away. I just can't wrap my head around the algorithm
required to solve this even somewhat efficiently. Help MUCH appreciated!!!
I'm new to programming, currently learning C. I've been working at this
problem for a week now, and I just can't seem to get the logic straight.
This is straight from the book I'm using:
Build a program that uses an array of strings to store the following names:
- "Florida" - "Oregon" - "Califoria" - "Georgia"
Using the preceding array of strings, write your own sort() function to
display each state's name in alphabetical order using the strcmp()
function.
Should I do nested for loops, like strcmp(string[x], string[y])...? I've
hacked and hacked away. I just can't wrap my head around the algorithm
required to solve this even somewhat efficiently. Help MUCH appreciated!!!
Pentaho Report with Kettle as Data source
Pentaho Report with Kettle as Data source
I am trying to call a kettle transformation using a pentaho report. My
transformation will retrieve a resultset from table based on a command
line argument. The report generates the correct output if i remove the
command line argument from the ktr and run the hard coded SELECT sql. but
it retrieves empty when we pass command line arguments/parameters.
The report works good when i click preview with arguments, but not working
after i publish it.
My parameters are not getting passed to the kettle transformation.
Report Parameter: ondate Kettle Named parameter: ONDATE (I have mapped
both in my report)
did i miss something?
I am trying to call a kettle transformation using a pentaho report. My
transformation will retrieve a resultset from table based on a command
line argument. The report generates the correct output if i remove the
command line argument from the ktr and run the hard coded SELECT sql. but
it retrieves empty when we pass command line arguments/parameters.
The report works good when i click preview with arguments, but not working
after i publish it.
My parameters are not getting passed to the kettle transformation.
Report Parameter: ondate Kettle Named parameter: ONDATE (I have mapped
both in my report)
did i miss something?
Multi-monitor: spaces thumbnails on external monitor missing
Multi-monitor: spaces thumbnails on external monitor missing
I've been having the following issue since about two weeks:
My external monitor, containing the OS X title bar, does not show the
thumbnails for my three spaces when in mission control. My retina's
monitor (secondary) does show them as before.
[ Nice, this question need a screenshot, but I don't have enough
reputation. :( ]
External (primary) monitor:
No grey border in mission control. The outermost bg is the wallpaper for
that space on the Retina display. It will change as well when moving to
another space using ^left/^right
I can still move an app to another space by drag 'n dropping them to the
place where the thumbnail should be. So it's not that they're gone;
they're just invisible!
Retina display (secondary)
As it should be in mission control: Zoomed out bg image, grey border
containing three thumbnails for the three spaces I have.
Has anyone experienced these symptoms as well?
I've been having the following issue since about two weeks:
My external monitor, containing the OS X title bar, does not show the
thumbnails for my three spaces when in mission control. My retina's
monitor (secondary) does show them as before.
[ Nice, this question need a screenshot, but I don't have enough
reputation. :( ]
External (primary) monitor:
No grey border in mission control. The outermost bg is the wallpaper for
that space on the Retina display. It will change as well when moving to
another space using ^left/^right
I can still move an app to another space by drag 'n dropping them to the
place where the thumbnail should be. So it's not that they're gone;
they're just invisible!
Retina display (secondary)
As it should be in mission control: Zoomed out bg image, grey border
containing three thumbnails for the three spaces I have.
Has anyone experienced these symptoms as well?
Thursday, 22 August 2013
Simplify a proposition of logic
Simplify a proposition of logic
I'm trying to come up with some concrete simplification for the following
proposition:
p É (p È (Êp È q É r È (p È r)))
Any ideas on what is the resulting form?
I'm trying to come up with some concrete simplification for the following
proposition:
p É (p È (Êp È q É r È (p È r)))
Any ideas on what is the resulting form?
Titanium SDK: The Google Play services resources were not found
Titanium SDK: The Google Play services resources were not found
I'm currently working on getting an old Titanium SDK 1.x app working in
the modern era on Titanium SDK 3.1.2. One of the challenges I've managed
to find myself stuck on is after upgrading from Google Android Maps API v1
to v2 I'm consistently getting this error:
The Google Play services resources were not found. Check your project
configuration to ensure that the resources are included.
I have installed in the ADK the 18.0.1 build tools as well as the required
Google Play Services extras package. Uninstalling/reinstalling does
nothing useful, and as far as I can tell there's no way to manually
include the Play Store Services library in Titanium.
For reference I followed the instructions here to set up the Maps API v2
in the app. The following is what is in my tiapp.xml file (I replaced the
actual package names):
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
<permission android:name="com.example.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<application>
<meta-data android:name="com.google.android.maps.v2.API_KEY"
android:value="###"/>
<uses-sdk android:minSdkVersion="10" android:targetSdkVersion="10"/>
</application>
Note that the correct certificates and correct API have been used within
the Google API Console.
Does anyone have any idea why I might be unable to load the Google Play
Services in my Titanium app?
Thanks in advance!
I'm currently working on getting an old Titanium SDK 1.x app working in
the modern era on Titanium SDK 3.1.2. One of the challenges I've managed
to find myself stuck on is after upgrading from Google Android Maps API v1
to v2 I'm consistently getting this error:
The Google Play services resources were not found. Check your project
configuration to ensure that the resources are included.
I have installed in the ADK the 18.0.1 build tools as well as the required
Google Play Services extras package. Uninstalling/reinstalling does
nothing useful, and as far as I can tell there's no way to manually
include the Play Store Services library in Titanium.
For reference I followed the instructions here to set up the Maps API v2
in the app. The following is what is in my tiapp.xml file (I replaced the
actual package names):
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
<permission android:name="com.example.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<application>
<meta-data android:name="com.google.android.maps.v2.API_KEY"
android:value="###"/>
<uses-sdk android:minSdkVersion="10" android:targetSdkVersion="10"/>
</application>
Note that the correct certificates and correct API have been used within
the Google API Console.
Does anyone have any idea why I might be unable to load the Google Play
Services in my Titanium app?
Thanks in advance!
Validate a textbox to accept numbers thats between 0 to 100 only
Validate a textbox to accept numbers thats between 0 to 100 only
I have a textbox labeled "score". I want the user to enter a value between
0 and 100. How can I validate the value provided by the user?
HTML:
<div class="editor-label"> Score </div>
<div class="editor-field">
<input type="text" name="Score" id="Score" maxlength="25" />
<span id="ScoreError" class="error"></span>
</div>
What I tried so far:
var num = document.getElementById("Score").value;
if (num < 0 || num > 100){
document.getElementById("ScoreError").innerHTML = "- Score is required.";
alert("Enter a Score thats between 0 to 100")
isValidForm = false;
}
I have a textbox labeled "score". I want the user to enter a value between
0 and 100. How can I validate the value provided by the user?
HTML:
<div class="editor-label"> Score </div>
<div class="editor-field">
<input type="text" name="Score" id="Score" maxlength="25" />
<span id="ScoreError" class="error"></span>
</div>
What I tried so far:
var num = document.getElementById("Score").value;
if (num < 0 || num > 100){
document.getElementById("ScoreError").innerHTML = "- Score is required.";
alert("Enter a Score thats between 0 to 100")
isValidForm = false;
}
stability of a linear system
stability of a linear system
The linear system:
$y''(t)+4y'(t)=4(\lambda -1)y(t)+z(t)$
$z'(t)=(\lambda -3)z(t)$
Determine the stability of the system as a function of the parameter
$\lambda\in\mathbb{R}$.
How do i get started on this exercise? I am not asking for the solution,
just anything that can help me on my way?
Should i rewrite the system as a system of first order equations? If so,
how can i do this?
The linear system:
$y''(t)+4y'(t)=4(\lambda -1)y(t)+z(t)$
$z'(t)=(\lambda -3)z(t)$
Determine the stability of the system as a function of the parameter
$\lambda\in\mathbb{R}$.
How do i get started on this exercise? I am not asking for the solution,
just anything that can help me on my way?
Should i rewrite the system as a system of first order equations? If so,
how can i do this?
LINQ GroupBy() only if true
LINQ GroupBy() only if true
I need to group data using a custom condition, which returns true or
false. The complexity is, I need to group only the items which return true
and do not group the others.
If I use:
var result = data.GroupBy(d => new { Condition = d.SomeValue > 1 });
all the items get grouped by true/false.
Now I have this statement that works:
var result = data.GroupBy(d => new { Condition = d.SomeValue > 1 ? "true"
: FunctionToGetUniqueString() });
UPDATE: Note, the other items (which are false) must also be in the
grouping, but go separately (one per group).
But I think it is a bit dirty solution, so I though that maybe there is
something more elegant?
I need to group data using a custom condition, which returns true or
false. The complexity is, I need to group only the items which return true
and do not group the others.
If I use:
var result = data.GroupBy(d => new { Condition = d.SomeValue > 1 });
all the items get grouped by true/false.
Now I have this statement that works:
var result = data.GroupBy(d => new { Condition = d.SomeValue > 1 ? "true"
: FunctionToGetUniqueString() });
UPDATE: Note, the other items (which are false) must also be in the
grouping, but go separately (one per group).
But I think it is a bit dirty solution, so I though that maybe there is
something more elegant?
Load files from resource beans?
Load files from resource beans?
I want to load some fonts and use them with Itext.
I saved the font in the /resources/font/ folder. I tried to load them this
was
BaseFont verdana_bf = BaseFont.createFont("../resources/font/Calibri.ttf",
BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
but it does not work, I get following error:
java.io.IOException: ../resources/font/Calibri.ttf not found as file or
resource.
How can I load fonts, images from the resource folder in my beans? I need
to load some images aswell.
I want to load some fonts and use them with Itext.
I saved the font in the /resources/font/ folder. I tried to load them this
was
BaseFont verdana_bf = BaseFont.createFont("../resources/font/Calibri.ttf",
BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
but it does not work, I get following error:
java.io.IOException: ../resources/font/Calibri.ttf not found as file or
resource.
How can I load fonts, images from the resource folder in my beans? I need
to load some images aswell.
Wednesday, 21 August 2013
Jgraph in JavaFx
Jgraph in JavaFx
Is it possible to use jgraphx with JavaFx 2.0?
I have tried using the below code, but i could not add the graph component
to the JavaFx component.
mxGraph graph = new mxGraph();
Object parent = graph.getDefaultParent();
graph.getModel().beginUpdate();
try {
Object v1 = graph.insertVertex(parent, null, "Hello", 20, 20, 80,
30);
Object v2 = graph.insertVertex(parent, null, "World!", 240, 150,
80, 30);
graph.insertEdge(parent, null, "Edge", v1, v2);
} finally {
graph.getModel().endUpdate();
}
mxGraphComponent graphComponent = new mxGraphComponent(graph);
TitledPane tPane = new TitledPane();
tPane.setAnimated(false);
tPane.setExpanded(false);
tPane.setMaxWidth(1040);
tPane.setText("Load Module " + i);
tPane.setAnimated(true);
tPane.setContent(graphComponent); // Error here. setContent() does
not accept graph
How can i use/add jgraph to the JavaFX component? Any ideas ?
Is it possible to use jgraphx with JavaFx 2.0?
I have tried using the below code, but i could not add the graph component
to the JavaFx component.
mxGraph graph = new mxGraph();
Object parent = graph.getDefaultParent();
graph.getModel().beginUpdate();
try {
Object v1 = graph.insertVertex(parent, null, "Hello", 20, 20, 80,
30);
Object v2 = graph.insertVertex(parent, null, "World!", 240, 150,
80, 30);
graph.insertEdge(parent, null, "Edge", v1, v2);
} finally {
graph.getModel().endUpdate();
}
mxGraphComponent graphComponent = new mxGraphComponent(graph);
TitledPane tPane = new TitledPane();
tPane.setAnimated(false);
tPane.setExpanded(false);
tPane.setMaxWidth(1040);
tPane.setText("Load Module " + i);
tPane.setAnimated(true);
tPane.setContent(graphComponent); // Error here. setContent() does
not accept graph
How can i use/add jgraph to the JavaFX component? Any ideas ?
Java : Hibernate is too much slow
Java : Hibernate is too much slow
I'm working on a a swing application, to handle the data I chose Hibernate
because of its performance. now that I did 80% of the work. I found out
that the application is too slow, like forever waiting. I googled it and
found that if there are many data Hibernate is not the best choice. I
didn't know that and the problem is that my database is complicated many
associations, joins , sets ... I don't have the time to start all over
again ! Help please
I'm working on a a swing application, to handle the data I chose Hibernate
because of its performance. now that I did 80% of the work. I found out
that the application is too slow, like forever waiting. I googled it and
found that if there are many data Hibernate is not the best choice. I
didn't know that and the problem is that my database is complicated many
associations, joins , sets ... I don't have the time to start all over
again ! Help please
Taining LIBSVM with time series data
Taining LIBSVM with time series data
I am working time series problem for several months and still unable to
figure it. Here is the question. I have data collected for 6 days, and the
collection starts from 8:00 am to 11:00. So the data looks something like
this
var1 | var2 | var3
1 2.2 UT1
2 3 UT2
3 1.2 UT3
1 2.2 UT4
2 3 UT5
3 1.2 UT6
1 2.2 UT7
2 3 UT8
3 1.2 UT9
UT represents unixtimestamp. So I converted the var3 into tow columns day
and time. So now the table looks like this
var1 | var2 | var3 | var4
1 2.2 12 8.0
2 3 12 8.25
3 1.2 12 8.5
1 2.2 13 8.0
2 3 13 8.25
3 1.2 13 8.5
1 2.2 14 8.0
2 3 14 8.25
3 1.2 14 8.5
var3 is the day of the month I collected the data and I collected the data
for 6days from 12 to 17. and var4 is time which I collected starting from
8:00 to 11:00 AM for every 20 minutes. The output I am having is a
dependent variable on these variables. So if I need to perform regression
using LIBSVM how can I do that with these?? Do I need to input var3 and
var4 differently? or how does LIBSVM treat this data? DO I need to
normalize the data? I would really appreciate your help.
I am working time series problem for several months and still unable to
figure it. Here is the question. I have data collected for 6 days, and the
collection starts from 8:00 am to 11:00. So the data looks something like
this
var1 | var2 | var3
1 2.2 UT1
2 3 UT2
3 1.2 UT3
1 2.2 UT4
2 3 UT5
3 1.2 UT6
1 2.2 UT7
2 3 UT8
3 1.2 UT9
UT represents unixtimestamp. So I converted the var3 into tow columns day
and time. So now the table looks like this
var1 | var2 | var3 | var4
1 2.2 12 8.0
2 3 12 8.25
3 1.2 12 8.5
1 2.2 13 8.0
2 3 13 8.25
3 1.2 13 8.5
1 2.2 14 8.0
2 3 14 8.25
3 1.2 14 8.5
var3 is the day of the month I collected the data and I collected the data
for 6days from 12 to 17. and var4 is time which I collected starting from
8:00 to 11:00 AM for every 20 minutes. The output I am having is a
dependent variable on these variables. So if I need to perform regression
using LIBSVM how can I do that with these?? Do I need to input var3 and
var4 differently? or how does LIBSVM treat this data? DO I need to
normalize the data? I would really appreciate your help.
How to select a TabItem based off of it's Header
How to select a TabItem based off of it's Header
In my program I have a tabItem that gets selected when a TreeViewItem with
an equivalent header is selected.
This is what I currently have (It works):
(parent_TreeViewItem.Items.Contains(SelectedItem))
{
tabControl1.SelectedItem = tabControl1.Items //Changes tab
according to TreeView
.OfType<TabItem>().SingleOrDefault(n =>
n.Header.ToString() == SelectedItem.Header.ToString());
}
The difference with what I'm doing this time is that the tabItem's header
that I'm selecting is composed of a string and an integer.
For example: The TreeViewItem selected will always have a header named
"Arrival", but the tabItem's header will have a form like "Arrival" +
integer. The integer value will come from the parent node's header.
For this process I'm thinking that I'll first need to get the header value
of the parent node, since it contains that integer value I need. Then I'll
need to modify my code above in someway to query for a node with a header
like, "Arrival" + parentHeader.
How would I do something like this?
Thank you.
In my program I have a tabItem that gets selected when a TreeViewItem with
an equivalent header is selected.
This is what I currently have (It works):
(parent_TreeViewItem.Items.Contains(SelectedItem))
{
tabControl1.SelectedItem = tabControl1.Items //Changes tab
according to TreeView
.OfType<TabItem>().SingleOrDefault(n =>
n.Header.ToString() == SelectedItem.Header.ToString());
}
The difference with what I'm doing this time is that the tabItem's header
that I'm selecting is composed of a string and an integer.
For example: The TreeViewItem selected will always have a header named
"Arrival", but the tabItem's header will have a form like "Arrival" +
integer. The integer value will come from the parent node's header.
For this process I'm thinking that I'll first need to get the header value
of the parent node, since it contains that integer value I need. Then I'll
need to modify my code above in someway to query for a node with a header
like, "Arrival" + parentHeader.
How would I do something like this?
Thank you.
jquery .on() only works once
jquery .on() only works once
I have a table with multiple checkbox inputs:
<form>
<table id="table">
<tr>
<td><input type="checkbox" value="1" class="someClass"></td>
<td><input type="checkbox" value="1" class="someClass"></td>...
And some jquery that refreshes the table from another file when the box is
checked/unchecked:
$(".someClass").on("change", function() {
$('#edit').ajaxSubmit(); //Submitting the form with id "edit"
$("#table").load("tablerefresh");
});
My problem is that when I check/uncheck a box, the table will refresh only
once, and it should do it every time I check/uncheck the box, I've looked
everywhere and can't seem to find a solution. Any ideas?
I have a table with multiple checkbox inputs:
<form>
<table id="table">
<tr>
<td><input type="checkbox" value="1" class="someClass"></td>
<td><input type="checkbox" value="1" class="someClass"></td>...
And some jquery that refreshes the table from another file when the box is
checked/unchecked:
$(".someClass").on("change", function() {
$('#edit').ajaxSubmit(); //Submitting the form with id "edit"
$("#table").load("tablerefresh");
});
My problem is that when I check/uncheck a box, the table will refresh only
once, and it should do it every time I check/uncheck the box, I've looked
everywhere and can't seem to find a solution. Any ideas?
extjs 4.1 download file using ajax
extjs 4.1 download file using ajax
i want to download a file using extjs 4.1.
The file name is "wsnDataModel.xml".
I've tryed with all things suggested in other posts:
//function invoked clicking a button
DwDataModel : function(th, h, items) {
//direct method that build in file in the location calculated below
with "certurl" (I've verified)
Utility.GetDataModel(function(e, z, x) {
if (z.message) {
//the server method should give an error message
Ext.create('AM.view.notification.toast', {
title : 'Error',
html : z.message,
isError : true
}).show();
} else {
// navigate to get data
var certurl = 'http://' + window.location.host
+ '/AdminConsole3/' + e;
Ext.Ajax.request({
method : 'GET',
url : 'http://' + window.location.host
+ '/AdminConsole3/' + e,
success : function(response, opts) {
//the following navigate and openthe file in the current browser page.
//I don't want to change the current browser page
//window.location.href = certurl;
//the same behaviour with
//document.location = certurl;
//and this don't work at all
window.open(certurl,'download');
},
failure : function(response, opts) {
console
.log('server-side failure with status
code '
+ response.status);
console.log('tried to fetch ' + url);
}
}, this, [certurl]);
}
}, th);
}
the "navigation" redirect the application (i don't want to redirect the
application) like this:
and I'would like to download the file like this image:
I think it's very simple. How to do that?
thank you
i want to download a file using extjs 4.1.
The file name is "wsnDataModel.xml".
I've tryed with all things suggested in other posts:
//function invoked clicking a button
DwDataModel : function(th, h, items) {
//direct method that build in file in the location calculated below
with "certurl" (I've verified)
Utility.GetDataModel(function(e, z, x) {
if (z.message) {
//the server method should give an error message
Ext.create('AM.view.notification.toast', {
title : 'Error',
html : z.message,
isError : true
}).show();
} else {
// navigate to get data
var certurl = 'http://' + window.location.host
+ '/AdminConsole3/' + e;
Ext.Ajax.request({
method : 'GET',
url : 'http://' + window.location.host
+ '/AdminConsole3/' + e,
success : function(response, opts) {
//the following navigate and openthe file in the current browser page.
//I don't want to change the current browser page
//window.location.href = certurl;
//the same behaviour with
//document.location = certurl;
//and this don't work at all
window.open(certurl,'download');
},
failure : function(response, opts) {
console
.log('server-side failure with status
code '
+ response.status);
console.log('tried to fetch ' + url);
}
}, this, [certurl]);
}
}, th);
}
the "navigation" redirect the application (i don't want to redirect the
application) like this:
and I'would like to download the file like this image:
I think it's very simple. How to do that?
thank you
Tuesday, 20 August 2013
Is it Better practice to Declare individual objects or loop Annonymous objects into ArrayList?
Is it Better practice to Declare individual objects or loop Annonymous
objects into ArrayList?
I am learning programming with Java through a textbook. A programming
exercise asks you to:
(Swing common features) Display a frame that contains six labels. Set the
background of the labels to white. Set the foreground of the labels to
black, blue, cyan, green, magenta, and orange, respectively, as shown in
Figure 12.28a. Set the border of each label to a line border with the
color yellow. Set the font of each label to Times Roman, bold, and 20
pixels. Set the text and tool tip text of each label to the name of its
foreground color.
I have two answers to the problem. My answer and the books answer. Both
answers work fine.
I use an Array and populate it with anonymous objects by using a loop (as
shown in class Sixlabels extends JFrame{}):
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class TWELVE_point_8 {
public static void main(String[] args) {
JFrame frame = new SixLabels();
frame.setTitle("Six Labels");
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class SixLabels extends JFrame {
public SixLabels() {
setLayout(new GridLayout(2, 3));
JLabel[] list = {
new JLabel("Black"),
new JLabel("Blue"),
new JLabel("Cyan"),
new JLabel("Green"),
new JLabel("Magenta"),
new JLabel("Orange")};
// set foreground colors
list[0].setForeground(Color.black);
list[1].setForeground(Color.blue);
list[2].setForeground(Color.cyan);
list[3].setForeground(Color.green);
list[4].setForeground(Color.magenta);
list[5].setForeground(Color.orange);
// set background colors
for (int i = 0; i < list.length; i++)
list[i].setBackground(Color.white);
// set fonts
Font font = new Font("TimesRoman", Font.BOLD, 20);
for (int i = 0; i < list.length; i++)
list[i].setFont(font);
// set borders
Border lineBorder = new LineBorder(Color.yellow, 1);
for (int i = 0; i < list.length; i++)
list[i].setBorder(lineBorder);
// set tooltip
for (int i = 0; i < list.length; i++)
list[i].setToolTipText(list[i].getText());
// add all labels to container
for (int i = 0; i < list.length; i++)
add(list[i]);
}
}
And the book answer does not use an array list (as shown in public
Exercise12_8 extends JFrame{});:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class Exercise12_8 extends JFrame {
private JLabel jlblBlack = new JLabel("black");
private JLabel jlblBlue = new JLabel("blue");
private JLabel jlblCyan = new JLabel("cyan");
private JLabel jlblGreen = new JLabel("green");
private JLabel jlblMagenta = new JLabel("magenta");
private JLabel jlblOrange = new JLabel("orange");
public Exercise12_8() {
setLayout(new GridLayout(2, 3));
this.add(jlblBlack);
this.add(jlblBlue);
this.add(jlblCyan);
this.add(jlblGreen);
this.add(jlblMagenta);
this.add(jlblOrange);
jlblBlack.setBackground(Color.WHITE);
jlblBlue.setBackground(Color.WHITE);
jlblCyan.setBackground(Color.WHITE);
jlblGreen.setBackground(Color.WHITE);
jlblMagenta.setBackground(Color.WHITE);
jlblOrange.setBackground(Color.WHITE);
jlblBlack.setForeground(Color.BLACK);
jlblBlue.setForeground(Color.BLUE);
jlblCyan.setForeground(Color.CYAN);
jlblGreen.setForeground(Color.GREEN);
jlblMagenta.setForeground(Color.MAGENTA);
jlblOrange.setForeground(Color.ORANGE);
Font font = new Font("TImesRoman", Font.BOLD, 20);
jlblBlack.setFont(font);
jlblBlue.setFont(font);
jlblCyan.setFont(font);
jlblGreen.setFont(font);
jlblMagenta.setFont(font);
jlblOrange.setFont(font);
Border border = new LineBorder(Color.YELLOW);
jlblBlack.setBorder(border);
jlblBlue.setBorder(border);
jlblCyan.setBorder(border);
jlblGreen.setBorder(border);
jlblMagenta.setBorder(border);
jlblOrange.setBorder(border);
jlblBlack.setToolTipText("black");
jlblBlue.setToolTipText("blue");
jlblCyan.setToolTipText("cyan");
jlblGreen.setToolTipText("green");
jlblMagenta.setToolTipText("magenta");
jlblOrange.setToolTipText("orange");
}
public static void main(String[] args) {
Exercise12_8 frame = new Exercise12_8();
frame.setTitle("Exercise12_8");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // Center the frame
frame.setVisible(true);
}
}
My question is: is it better practice to declare the JLabel object
individually (as the book has) or to populate the Array (or ArrayList)
annonymously as I have? The only benefit I see in doing it the book's way
is readability and having a variable name (which may be used in future
programs, but not in this particular one).
objects into ArrayList?
I am learning programming with Java through a textbook. A programming
exercise asks you to:
(Swing common features) Display a frame that contains six labels. Set the
background of the labels to white. Set the foreground of the labels to
black, blue, cyan, green, magenta, and orange, respectively, as shown in
Figure 12.28a. Set the border of each label to a line border with the
color yellow. Set the font of each label to Times Roman, bold, and 20
pixels. Set the text and tool tip text of each label to the name of its
foreground color.
I have two answers to the problem. My answer and the books answer. Both
answers work fine.
I use an Array and populate it with anonymous objects by using a loop (as
shown in class Sixlabels extends JFrame{}):
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class TWELVE_point_8 {
public static void main(String[] args) {
JFrame frame = new SixLabels();
frame.setTitle("Six Labels");
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class SixLabels extends JFrame {
public SixLabels() {
setLayout(new GridLayout(2, 3));
JLabel[] list = {
new JLabel("Black"),
new JLabel("Blue"),
new JLabel("Cyan"),
new JLabel("Green"),
new JLabel("Magenta"),
new JLabel("Orange")};
// set foreground colors
list[0].setForeground(Color.black);
list[1].setForeground(Color.blue);
list[2].setForeground(Color.cyan);
list[3].setForeground(Color.green);
list[4].setForeground(Color.magenta);
list[5].setForeground(Color.orange);
// set background colors
for (int i = 0; i < list.length; i++)
list[i].setBackground(Color.white);
// set fonts
Font font = new Font("TimesRoman", Font.BOLD, 20);
for (int i = 0; i < list.length; i++)
list[i].setFont(font);
// set borders
Border lineBorder = new LineBorder(Color.yellow, 1);
for (int i = 0; i < list.length; i++)
list[i].setBorder(lineBorder);
// set tooltip
for (int i = 0; i < list.length; i++)
list[i].setToolTipText(list[i].getText());
// add all labels to container
for (int i = 0; i < list.length; i++)
add(list[i]);
}
}
And the book answer does not use an array list (as shown in public
Exercise12_8 extends JFrame{});:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class Exercise12_8 extends JFrame {
private JLabel jlblBlack = new JLabel("black");
private JLabel jlblBlue = new JLabel("blue");
private JLabel jlblCyan = new JLabel("cyan");
private JLabel jlblGreen = new JLabel("green");
private JLabel jlblMagenta = new JLabel("magenta");
private JLabel jlblOrange = new JLabel("orange");
public Exercise12_8() {
setLayout(new GridLayout(2, 3));
this.add(jlblBlack);
this.add(jlblBlue);
this.add(jlblCyan);
this.add(jlblGreen);
this.add(jlblMagenta);
this.add(jlblOrange);
jlblBlack.setBackground(Color.WHITE);
jlblBlue.setBackground(Color.WHITE);
jlblCyan.setBackground(Color.WHITE);
jlblGreen.setBackground(Color.WHITE);
jlblMagenta.setBackground(Color.WHITE);
jlblOrange.setBackground(Color.WHITE);
jlblBlack.setForeground(Color.BLACK);
jlblBlue.setForeground(Color.BLUE);
jlblCyan.setForeground(Color.CYAN);
jlblGreen.setForeground(Color.GREEN);
jlblMagenta.setForeground(Color.MAGENTA);
jlblOrange.setForeground(Color.ORANGE);
Font font = new Font("TImesRoman", Font.BOLD, 20);
jlblBlack.setFont(font);
jlblBlue.setFont(font);
jlblCyan.setFont(font);
jlblGreen.setFont(font);
jlblMagenta.setFont(font);
jlblOrange.setFont(font);
Border border = new LineBorder(Color.YELLOW);
jlblBlack.setBorder(border);
jlblBlue.setBorder(border);
jlblCyan.setBorder(border);
jlblGreen.setBorder(border);
jlblMagenta.setBorder(border);
jlblOrange.setBorder(border);
jlblBlack.setToolTipText("black");
jlblBlue.setToolTipText("blue");
jlblCyan.setToolTipText("cyan");
jlblGreen.setToolTipText("green");
jlblMagenta.setToolTipText("magenta");
jlblOrange.setToolTipText("orange");
}
public static void main(String[] args) {
Exercise12_8 frame = new Exercise12_8();
frame.setTitle("Exercise12_8");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // Center the frame
frame.setVisible(true);
}
}
My question is: is it better practice to declare the JLabel object
individually (as the book has) or to populate the Array (or ArrayList)
annonymously as I have? The only benefit I see in doing it the book's way
is readability and having a variable name (which may be used in future
programs, but not in this particular one).
Fancybox Video continues to play when closed
Fancybox Video continues to play when closed
Just implemented Fancybox to pop up on the page load — however, when the
user clicks out of the fancybox back to the website, the song will begin
to play again. Any ideas on what could cause this?
LINK: People Like Us Website
<!-- FANCYBOX POPUP -->
<a class="popupLink" href="#popup"></a>
<div id="popup">
<iframe width="853" height="480"
src="http://www.youtube.com/embed/Qw7k_erTgow?autoplay=1"
frameborder="0" allowfullscreen></iframe>
</div>
<!-- .popup -->
<script type="text/javascript">
$(document).ready(function() {
$(".popupLink").fancybox();
window.setTimeout('$(".popupLink").trigger("click")', 100);
});
</script>
<script type="text/javascript">
$("a.more").click(function() {
$.fancybox({
'padding' : 0,
'autoScale' : false,
'transitionIn' : 'none',
'transitionOut' : 'none',
'title' : this.title,
'width' : 680,
'height' : 495,
'href' : this.href.replace(new RegExp("watch\\?v=", "i"),
'v/'),
'type' : 'swf',
'swf' : {
'wmode' : 'transparent',
'allowfullscreen' : 'true'
}
});
Just implemented Fancybox to pop up on the page load — however, when the
user clicks out of the fancybox back to the website, the song will begin
to play again. Any ideas on what could cause this?
LINK: People Like Us Website
<!-- FANCYBOX POPUP -->
<a class="popupLink" href="#popup"></a>
<div id="popup">
<iframe width="853" height="480"
src="http://www.youtube.com/embed/Qw7k_erTgow?autoplay=1"
frameborder="0" allowfullscreen></iframe>
</div>
<!-- .popup -->
<script type="text/javascript">
$(document).ready(function() {
$(".popupLink").fancybox();
window.setTimeout('$(".popupLink").trigger("click")', 100);
});
</script>
<script type="text/javascript">
$("a.more").click(function() {
$.fancybox({
'padding' : 0,
'autoScale' : false,
'transitionIn' : 'none',
'transitionOut' : 'none',
'title' : this.title,
'width' : 680,
'height' : 495,
'href' : this.href.replace(new RegExp("watch\\?v=", "i"),
'v/'),
'type' : 'swf',
'swf' : {
'wmode' : 'transparent',
'allowfullscreen' : 'true'
}
});
Fastest way to determine the lowest available key in JAVA HashMap?
Fastest way to determine the lowest available key in JAVA HashMap?
Imagine a situation like this: I have a HashMap<Integer, String>, in which
I store the connected clients. It is HashMap, because the order does not
matter and I need speed. It looks like this:
{
3: "John",
528: "Bob",
712: "Sue"
}
Most of the clients disconnected, so this is why I have the large gap. If
I want to add a new client, I need a key and obviously the usage of
_map.size() to get a key is incorrect.
So, currently I use this function to get he lowest available key:
private int lowestAvailableKey(HashMap<?, ?> _map) {
if (_map.isEmpty() == false) {
for (int i = 0; i <= _map.size(); i++) {
if (_map.containsKey(i) == false) {
return i;
}
}
}
return 0;
}
In some cases, this is really slow. Is there any faster or more
professional way to get the lowest free key of a HashMap?
Imagine a situation like this: I have a HashMap<Integer, String>, in which
I store the connected clients. It is HashMap, because the order does not
matter and I need speed. It looks like this:
{
3: "John",
528: "Bob",
712: "Sue"
}
Most of the clients disconnected, so this is why I have the large gap. If
I want to add a new client, I need a key and obviously the usage of
_map.size() to get a key is incorrect.
So, currently I use this function to get he lowest available key:
private int lowestAvailableKey(HashMap<?, ?> _map) {
if (_map.isEmpty() == false) {
for (int i = 0; i <= _map.size(); i++) {
if (_map.containsKey(i) == false) {
return i;
}
}
}
return 0;
}
In some cases, this is really slow. Is there any faster or more
professional way to get the lowest free key of a HashMap?
Why am I getting these remnants after animations in Raphael.js?
Why am I getting these remnants after animations in Raphael.js?
The "A" in this image was animated using raphael.js on an HTML5 Canvas,
but sometimes it leaves this ugly trail after it animates. Does anyone
know why this happens or how to fix it?
The "A" in this image was animated using raphael.js on an HTML5 Canvas,
but sometimes it leaves this ugly trail after it animates. Does anyone
know why this happens or how to fix it?
How to use effectively radio buttons in a button group MATLAB GUI
How to use effectively radio buttons in a button group MATLAB GUI
I have 5 different filters as 5 different radio buttons in MATLAB GUI. I
made them into a button group and now when i click the each button the
noise image is shown through the axes. But i want to set the button group
in such a way to show only one filter (one image). So, I followed this
(How to pass function to radio button in a button group created using
guide in MATLAB?) which is given here at stackoverflow. But how do we
"set" image in an axes. I have attached the figure of my GUI.enter image
description here
Thanks in advance
I have 5 different filters as 5 different radio buttons in MATLAB GUI. I
made them into a button group and now when i click the each button the
noise image is shown through the axes. But i want to set the button group
in such a way to show only one filter (one image). So, I followed this
(How to pass function to radio button in a button group created using
guide in MATLAB?) which is given here at stackoverflow. But how do we
"set" image in an axes. I have attached the figure of my GUI.enter image
description here
Thanks in advance
how to verify insert & delete & update are done in single stored procedure of Ms Sql server
how to verify insert & delete & update are done in single stored procedure
of Ms Sql server
I am trying to write stored procedure test case. I need to check that are
there insert and/or delete operation done with update operation. I tried
with BINARY_CHECKSUM(*) for update but how can I know that whether table
is inserted or deleted with update operation.
Thanking You.
of Ms Sql server
I am trying to write stored procedure test case. I need to check that are
there insert and/or delete operation done with update operation. I tried
with BINARY_CHECKSUM(*) for update but how can I know that whether table
is inserted or deleted with update operation.
Thanking You.
C# How to Keep User From leaving Program in Windows
C# How to Keep User From leaving Program in Windows
I'm writing a full-screen program for children (using C# and WinForms),
and it is important that they (the users) are not able to move the mouse
around and end up in another program in Windows or on the desktop -- in
other words, once the teacher puts this program on the screen, the
children must remain there, and the teacher can only exit the program
using a password).
Is there any way to do this?
Many thanks in advance!
Jon
I'm writing a full-screen program for children (using C# and WinForms),
and it is important that they (the users) are not able to move the mouse
around and end up in another program in Windows or on the desktop -- in
other words, once the teacher puts this program on the screen, the
children must remain there, and the teacher can only exit the program
using a password).
Is there any way to do this?
Many thanks in advance!
Jon
Monday, 19 August 2013
im having problems with nstimer in Xcode
im having problems with nstimer in Xcode
im making a simple game on Xcode and i decided to use a nstimer in my .m
xcode found 3 problems with my code it says Assigning to 'CGPoint' (aka
'struct CGPoint') from in compatable 'int' twice and it says use of
undeclared game loop. Any help is great
enter code here
@implementation ViewController @synthesize bg, rock, platform1, platform2,
platform3, platform4, platform5, platform6, platform7; @synthesize
gameState; @synthesize rockVelocity, gravity;
// Implement viewDidLoad to do additional setup after loading the view,
typically from a nib.
(void)viewDidLoad { [super viewDidLoad]; gameState = kStateRunning;
rockVelocity = CGpointMake (0, 0); gravity = CGpointMake (0, kGravity);
[NSTimer scheduledTimerWithTimeInterval: 1.0/60 target:self
selector:@selector(gameLoop) userInfo:nil repeats:YES];
(void)gameLoop { if (gameState == kStateRunning) { [self
gameStatePlayNormal]; } else if (gameState == kStateGameOver) {
} }
im making a simple game on Xcode and i decided to use a nstimer in my .m
xcode found 3 problems with my code it says Assigning to 'CGPoint' (aka
'struct CGPoint') from in compatable 'int' twice and it says use of
undeclared game loop. Any help is great
enter code here
@implementation ViewController @synthesize bg, rock, platform1, platform2,
platform3, platform4, platform5, platform6, platform7; @synthesize
gameState; @synthesize rockVelocity, gravity;
// Implement viewDidLoad to do additional setup after loading the view,
typically from a nib.
(void)viewDidLoad { [super viewDidLoad]; gameState = kStateRunning;
rockVelocity = CGpointMake (0, 0); gravity = CGpointMake (0, kGravity);
[NSTimer scheduledTimerWithTimeInterval: 1.0/60 target:self
selector:@selector(gameLoop) userInfo:nil repeats:YES];
(void)gameLoop { if (gameState == kStateRunning) { [self
gameStatePlayNormal]; } else if (gameState == kStateGameOver) {
} }
Python unicode.splitlines() triggers at non-EOL character
Python unicode.splitlines() triggers at non-EOL character
Triyng to make this in Python 2.7:
>>> s = u"some\u2028text"
>>> s
u'some\u2028text'
>>> l = s.splitlines(True)
>>> l
[u'some\u2028', u'text']
\u2028 is Left-To-Right Embedding character, not \r or \n, so that line
should not be splitted. Is there a bug or just my misunderstanding?
Triyng to make this in Python 2.7:
>>> s = u"some\u2028text"
>>> s
u'some\u2028text'
>>> l = s.splitlines(True)
>>> l
[u'some\u2028', u'text']
\u2028 is Left-To-Right Embedding character, not \r or \n, so that line
should not be splitted. Is there a bug or just my misunderstanding?
Debugging jQuery Animation
Debugging jQuery Animation
I am using a page flipping plugin called "bookblock" (demo can be found
here).
I have put images on each page, which I am adding dynamically. The problem
is when I flip the page, the previous and next divs are suddenly squished
together on each side of the book. The following screenshot is taken
mid-animation of a page flip.
As you can see each page in the book is "item1", "item2", etc. All of the
display properties are set to "none", but for some reason they can be
seen.
A live version of this site can be found here. I have tried adding
$(".bb-item").hide();
Right before the animation sequence, which appears to begin on line 259 of
js/jquery.bookblock.js, but no luck. How else could I go about debugging
this problem?
UPDATE: I am very sorry, I should have mentioned that you can access the
flipbook by clicking on the "expand" icon, in the bottom right of each
div.
I am using a page flipping plugin called "bookblock" (demo can be found
here).
I have put images on each page, which I am adding dynamically. The problem
is when I flip the page, the previous and next divs are suddenly squished
together on each side of the book. The following screenshot is taken
mid-animation of a page flip.
As you can see each page in the book is "item1", "item2", etc. All of the
display properties are set to "none", but for some reason they can be
seen.
A live version of this site can be found here. I have tried adding
$(".bb-item").hide();
Right before the animation sequence, which appears to begin on line 259 of
js/jquery.bookblock.js, but no luck. How else could I go about debugging
this problem?
UPDATE: I am very sorry, I should have mentioned that you can access the
flipbook by clicking on the "expand" icon, in the bottom right of each
div.
How do I track who uses my Excel spreadsheet?
How do I track who uses my Excel spreadsheet?
I created an Excel spreadsheet that my boss wants to put on the company's
internal website. The spreadsheet contains some seldom-used, esoteric, but
handy functions that only certain employees within the company will find
really useful.
The problem is that I don't know who the future users are, and my boss
wants me to identify who uses my spreadsheet.
He asked that I password-protect the Excel spreadsheet in such a way that
one password does NOT unlock all of the copies that people can download
from the site. For example, I can't just make the password "stackoverflow"
because once a user legitimately gets the password from me, and is shared
with other people, it can be used by anyone within the company to unlock
all subsequently downloaded spreadsheets. I will never be able to
ascertain who is using the spreadsheet. Also, I cannot modify the website,
so I hope to achieve this tracking of users through Excel and email.
Is there a way to have Excel randomly generate a string, which the user
emails me, and then I respond with the appropriate password that will
unlock the file (based off the generated string)? This requires the user
to check in with me before using the spreadsheet (the ideal situation).
Is such an arrangement possible in Excel 2010 Professional Plus?
I created an Excel spreadsheet that my boss wants to put on the company's
internal website. The spreadsheet contains some seldom-used, esoteric, but
handy functions that only certain employees within the company will find
really useful.
The problem is that I don't know who the future users are, and my boss
wants me to identify who uses my spreadsheet.
He asked that I password-protect the Excel spreadsheet in such a way that
one password does NOT unlock all of the copies that people can download
from the site. For example, I can't just make the password "stackoverflow"
because once a user legitimately gets the password from me, and is shared
with other people, it can be used by anyone within the company to unlock
all subsequently downloaded spreadsheets. I will never be able to
ascertain who is using the spreadsheet. Also, I cannot modify the website,
so I hope to achieve this tracking of users through Excel and email.
Is there a way to have Excel randomly generate a string, which the user
emails me, and then I respond with the appropriate password that will
unlock the file (based off the generated string)? This requires the user
to check in with me before using the spreadsheet (the ideal situation).
Is such an arrangement possible in Excel 2010 Professional Plus?
How to implement the two dynamic in C++ language features
How to implement the two dynamic in C++ language features
How to implement the two dynamic in C++ language features (as far as
possible use of the existing C++ features, and can be appropriate to
rewrite the compiler) :
According to the name of the class a object to obtain it, and what inherit
from class.
Dynamic class function call, the function without explicit declaration in
the header file.
Such as allowing the following code execution.
//A.h :
class A {};
// A.cpp
A::UnDeclaredFunctionB () {}
//main.cpp
void main () {
A *a = new A ();
a - > UnDeclaredFunction ();
Delete a;
}
How to implement the two dynamic in C++ language features (as far as
possible use of the existing C++ features, and can be appropriate to
rewrite the compiler) :
According to the name of the class a object to obtain it, and what inherit
from class.
Dynamic class function call, the function without explicit declaration in
the header file.
Such as allowing the following code execution.
//A.h :
class A {};
// A.cpp
A::UnDeclaredFunctionB () {}
//main.cpp
void main () {
A *a = new A ();
a - > UnDeclaredFunction ();
Delete a;
}
Sunday, 18 August 2013
Pull from Heroku to my computer (mac)
Pull from Heroku to my computer (mac)
I am very new to Rails, Heroku, Github and all the other stuff. My problem
is that locally on my Mac and unfortunately on Github i do have a "bad"
version of the application. Luckily i didn´t push it to Heroku. So on
Heroku i do have a good version of my application. Since i spend days
trying to find a bug in my application and got very upset, i want to go
the easy way and download the Heroku version to my Mac and replace the bad
one. And afterwards push it to Github. So that somehow possible? Already
tried $ git pull heroku master and got this error Your key with
fingerprint .... is not authorized to access myapp.
Getting really upset here. Haha. Thanks for the help in advance.
I am very new to Rails, Heroku, Github and all the other stuff. My problem
is that locally on my Mac and unfortunately on Github i do have a "bad"
version of the application. Luckily i didn´t push it to Heroku. So on
Heroku i do have a good version of my application. Since i spend days
trying to find a bug in my application and got very upset, i want to go
the easy way and download the Heroku version to my Mac and replace the bad
one. And afterwards push it to Github. So that somehow possible? Already
tried $ git pull heroku master and got this error Your key with
fingerprint .... is not authorized to access myapp.
Getting really upset here. Haha. Thanks for the help in advance.
Qt 5 - How to send data back from child dialog in real time
Qt 5 - How to send data back from child dialog in real time
I have a settings dialog that has some settings that require another
dialog to fully configure. My window shows a preview of the data as it's
being tweaked by these settings. Upon clicking on the configuration button
I launch another modal dialog with some knobs to twist to fine tune the
particular setting.
I wish to send the result of the twisting of the knobs on the child dialog
back to the parent dialog so that it can show the new preview data as the
knobs on the child are being played with. The way I imagine it is I have a
"refresh preview" function in the parent that is called after modification
of it's data preview member variables. The question is, how do I do this?
How can I access getters/setters from the parent dialog as a modal child
dialog? If I do access them will the preview change or will it be blocked
because of the modality of the child?
Thank you!
I have a settings dialog that has some settings that require another
dialog to fully configure. My window shows a preview of the data as it's
being tweaked by these settings. Upon clicking on the configuration button
I launch another modal dialog with some knobs to twist to fine tune the
particular setting.
I wish to send the result of the twisting of the knobs on the child dialog
back to the parent dialog so that it can show the new preview data as the
knobs on the child are being played with. The way I imagine it is I have a
"refresh preview" function in the parent that is called after modification
of it's data preview member variables. The question is, how do I do this?
How can I access getters/setters from the parent dialog as a modal child
dialog? If I do access them will the preview change or will it be blocked
because of the modality of the child?
Thank you!
CORS XMLHTTPRequest not working in Chromium 28
CORS XMLHTTPRequest not working in Chromium 28
I am trying to send CORS Ajax requests but it seems to fail :
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://enable-cors.org");
xhr.addEventListener("load", function() { console.log(this.response); });
xhr.withCredentials = true;
xhr.send();
I am making this request from the console, while browsing html5rocks.com.
I get this error message :
XMLHttpRequest cannot load http://enable-cors.org/. Origin
http://www.html5rocks.com is not allowed by Access-Control-Allow-Origin.
I believe enable-cors.org should send back correct
Access-Control-Allow-Origin headers :) But this holds true for any other
website. Also the console tells me an Origin header has been properly sent
in my request. What do I do wrong ?
I am trying to send CORS Ajax requests but it seems to fail :
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://enable-cors.org");
xhr.addEventListener("load", function() { console.log(this.response); });
xhr.withCredentials = true;
xhr.send();
I am making this request from the console, while browsing html5rocks.com.
I get this error message :
XMLHttpRequest cannot load http://enable-cors.org/. Origin
http://www.html5rocks.com is not allowed by Access-Control-Allow-Origin.
I believe enable-cors.org should send back correct
Access-Control-Allow-Origin headers :) But this holds true for any other
website. Also the console tells me an Origin header has been properly sent
in my request. What do I do wrong ?
replacing , with / in javascript
replacing , with / in javascript
I am trying to replace comma with / in javascript and written below code.
There are multiple text box available in the form. I want to write a
single function and call them on all the text fields.
The issue that I am experiencing is that I am not able to send the current
ID to javascript method. How to achieve this? thank you.
function removeComma(val)
{
var values = document.getElementById('val').value; //Object Required
Error
var n=values.replace(/,/, "/");
document.getElementById('val').value=n;
}
<input type="text" id="one" name="one" onkeypress="removeComma(this)">
<input type="text" id="two" name="two" onkeypress="removeComma(this)">
<input type="text" id="three" name="three" onkeypress="removeComma(this)">
Ther error that I am getting from above code is "OBJECT REQUIRED" at first
line.
I am trying to replace comma with / in javascript and written below code.
There are multiple text box available in the form. I want to write a
single function and call them on all the text fields.
The issue that I am experiencing is that I am not able to send the current
ID to javascript method. How to achieve this? thank you.
function removeComma(val)
{
var values = document.getElementById('val').value; //Object Required
Error
var n=values.replace(/,/, "/");
document.getElementById('val').value=n;
}
<input type="text" id="one" name="one" onkeypress="removeComma(this)">
<input type="text" id="two" name="two" onkeypress="removeComma(this)">
<input type="text" id="three" name="three" onkeypress="removeComma(this)">
Ther error that I am getting from above code is "OBJECT REQUIRED" at first
line.
Auto Increment Id in stored procedure not working
Auto Increment Id in stored procedure not working
I am trying to get company id like "Cp-00001". If data exists in table
then the id should be "Cp-00001" + 1 = "Cp=00002" and do on...
Here's what I have so far:
CREATE PROCEDURE [dbo].[sp_AutoGenerateCustomerCode]
AS
DECLARE @id VARCHAR(10)
BEGIN
SELECT @id = 'Cp-' + CAST(MAX(CAST(SUBSTRING(CompanyCode,4,5) AS
INTEGER))+1 AS VARCHAR) FROM [Beauty Saloon
Project].[dbo].[tbl_Company];
IF @id IS NULL
BEGIN
SET @id = 'Cp-00001';
END
RETURN @id;
END
but when i call it here
datatable DT = new datatable
DT = ExecuteSpDataTable("sp_AutoGenerateCustomerCode");
This returns null.
If I don't have data then it should return Cp-00001, but I have one data
row in which company code is saloon is it the reason for null ???
I am trying to get company id like "Cp-00001". If data exists in table
then the id should be "Cp-00001" + 1 = "Cp=00002" and do on...
Here's what I have so far:
CREATE PROCEDURE [dbo].[sp_AutoGenerateCustomerCode]
AS
DECLARE @id VARCHAR(10)
BEGIN
SELECT @id = 'Cp-' + CAST(MAX(CAST(SUBSTRING(CompanyCode,4,5) AS
INTEGER))+1 AS VARCHAR) FROM [Beauty Saloon
Project].[dbo].[tbl_Company];
IF @id IS NULL
BEGIN
SET @id = 'Cp-00001';
END
RETURN @id;
END
but when i call it here
datatable DT = new datatable
DT = ExecuteSpDataTable("sp_AutoGenerateCustomerCode");
This returns null.
If I don't have data then it should return Cp-00001, but I have one data
row in which company code is saloon is it the reason for null ???
Taking ResultSet and displaying results in a graph
Taking ResultSet and displaying results in a graph
Is it possible to create a graph based on a ResultSet taken from a
database? For example if I selected the ages of men in a database and
wanted to plot them versus their average annual income, how would I go
about plotting it on a table in java?
Is it possible to create a graph based on a ResultSet taken from a
database? For example if I selected the ages of men in a database and
wanted to plot them versus their average annual income, how would I go
about plotting it on a table in java?
Saturday, 17 August 2013
HorizontalScrollView pushes my widgets to the left side
HorizontalScrollView pushes my widgets to the left side
I am trying to make my layout to be horizontally scrollable, but when I do
that, it pushes my widgets to the left side.
This is my original XML where the layout is exactly what I want:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/btnBack"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Main Screen" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnBack"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="Coordinate Calculator"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/num2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/num1"
android:layout_below="@+id/num1"
android:imeOptions="flagNoExtractUi"
android:ems="5"
android:hint=" y"
android:inputType="numberSigned|numberDecimal"
android:maxLength="4" />
<EditText
android:id="@+id/num3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/num2"
android:layout_below="@+id/num2"
android:ems="5"
android:imeOptions="flagNoExtractUi"
android:hint=" r"
android:inputType="numberSigned|numberDecimal"
android:maxLength="4" />
<EditText android:imeOptions="flagNoExtractUi"
android:id="@+id/num1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="19dp"
android:ems="5"
android:hint=" x"
android:inputType="numberSigned|numberDecimal"
android:maxLength="4" />
<Button
android:id="@+id/btnCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/num2"
android:layout_alignRight="@+id/textView1"
android:layout_alignTop="@+id/num1"
android:text="Calculate" />
<Button
android:id="@+id/btnClear"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btnCalculate"
android:layout_alignRight="@+id/btnCalculate"
android:layout_below="@+id/btnCalculate"
android:text="Clear All" />
<TextView
android:id="@+id/display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/btnClear"
android:layout_marginLeft="20dp"
android:layout_marginTop="27dp"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
</ScrollView>
This is the layout for the XML above:
This is the XML for the horizontally scrollable layout:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- all the same widgets -->
</RelativeLayout>
</HorizontalScrollView>
</ScrollView>
Now here is the layout for this XML:
This is usually how I modify my XML to make it horizontally scrollable,
but this time it's not working.
How can I make this horizontally scrollable without changing the layout at
all?
I am trying to make my layout to be horizontally scrollable, but when I do
that, it pushes my widgets to the left side.
This is my original XML where the layout is exactly what I want:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/btnBack"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Main Screen" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnBack"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="Coordinate Calculator"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/num2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/num1"
android:layout_below="@+id/num1"
android:imeOptions="flagNoExtractUi"
android:ems="5"
android:hint=" y"
android:inputType="numberSigned|numberDecimal"
android:maxLength="4" />
<EditText
android:id="@+id/num3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/num2"
android:layout_below="@+id/num2"
android:ems="5"
android:imeOptions="flagNoExtractUi"
android:hint=" r"
android:inputType="numberSigned|numberDecimal"
android:maxLength="4" />
<EditText android:imeOptions="flagNoExtractUi"
android:id="@+id/num1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="19dp"
android:ems="5"
android:hint=" x"
android:inputType="numberSigned|numberDecimal"
android:maxLength="4" />
<Button
android:id="@+id/btnCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/num2"
android:layout_alignRight="@+id/textView1"
android:layout_alignTop="@+id/num1"
android:text="Calculate" />
<Button
android:id="@+id/btnClear"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btnCalculate"
android:layout_alignRight="@+id/btnCalculate"
android:layout_below="@+id/btnCalculate"
android:text="Clear All" />
<TextView
android:id="@+id/display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/btnClear"
android:layout_marginLeft="20dp"
android:layout_marginTop="27dp"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
</ScrollView>
This is the layout for the XML above:
This is the XML for the horizontally scrollable layout:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- all the same widgets -->
</RelativeLayout>
</HorizontalScrollView>
</ScrollView>
Now here is the layout for this XML:
This is usually how I modify my XML to make it horizontally scrollable,
but this time it's not working.
How can I make this horizontally scrollable without changing the layout at
all?
Unix: how to read line's original content from file
Unix: how to read line's original content from file
I have a data file, the content is as follows:
department: customer service section: A
department: marketing section: A
department: finance section: A
When I read each line, I would extract the department name using cut
command. Unfortunately, the program will automatically trim all redundant
space and thus I cut the department name incorrectly.
cat dept.dat | while read line
do
echo $line
echo $line | cut -c 12-29
done
e.g. the original line is:
department: marketing section: A
While the program treats this line as:
department: marketing section: A
How can I read the line without trimming all the redundant space?
I have a data file, the content is as follows:
department: customer service section: A
department: marketing section: A
department: finance section: A
When I read each line, I would extract the department name using cut
command. Unfortunately, the program will automatically trim all redundant
space and thus I cut the department name incorrectly.
cat dept.dat | while read line
do
echo $line
echo $line | cut -c 12-29
done
e.g. the original line is:
department: marketing section: A
While the program treats this line as:
department: marketing section: A
How can I read the line without trimming all the redundant space?
How to add trailing zeros to an integer in python? or How to add ZEROS after any integer in python?
How to add trailing zeros to an integer in python? or How to add ZEROS
after any integer in python?
I'm without clues on how to do this in Python. The problem is the
following: I have for example an orders numbers like:
1
2
...
10
The output should be
1000
2000
...
10000
That is I want to add 3 extra zeros after the integer
after any integer in python?
I'm without clues on how to do this in Python. The problem is the
following: I have for example an orders numbers like:
1
2
...
10
The output should be
1000
2000
...
10000
That is I want to add 3 extra zeros after the integer
Braces in FOR type loop code changed result unexpectedly
Braces in FOR type loop code changed result unexpectedly
I'm learning JS. In book is some exercise to make same code by using for
keyword instead of while as it was original example of loop of printing #
sign into lines to look like triangle:
#
##
###
####
#####
######
This was original example of doing it by using while keyword:
var line = "";
var counter = 0;
while (counter < 10) {
line = line + "#";
print(line);
counter = counter + 1;
}
I was did same using for without braces, because in this other example it
is not in need:
I'm learning JS. In book is some exercise to make same code by using for
keyword instead of while as it was original example of loop of printing #
sign into lines to look like triangle:
#
##
###
####
#####
######
This was original example of doing it by using while keyword:
var line = "";
var counter = 0;
while (counter < 10) {
line = line + "#";
print(line);
counter = counter + 1;
}
I was did same using for without braces, because in this other example it
is not in need:
ContentProvider, multi-tables and the correct OOP code (good practice)
ContentProvider, multi-tables and the correct OOP code (good practice)
I thought much time wondering how to constract ContentProvider class to be
convenient working with many tables (about 10 tables and 60
methods:delete, query, insert..) because I didn't want to have them all in
1 method (delete, query, insert) with 1 switch clause. So I use this
patern, for example:
in ContentProvider class:
public int delete(Uri uri, String where, String[] whereArgs) {
switch (sUriMatcher.match(uri)) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
...
switch (sUriMatcher.match(uri)) {
...
case EXAMPLE_ID:
id = Integer.parseInt(uri.getPathSegments().get(1));
count = tblExample.deleteRaw(db, id);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
I constract 1 class for each table, where I wrote static methods, which I
call from ContentProvider class, they are like this (each method much more
complex in reality):
public class tblExample {
public static final Uri CONTENT_URI = Uri.parse("content://" +
DBContentProvider.AUTHORITY + "/example");
public static final String KEY_ROWID = "_id";
public static final String ROW_ID_EXAMPLE = "id_example";
...
public static int deleteRaw(SQLiteDatabase mDb, int id_example) {
return mDb.delete("tblExample", tblExample.ROW_ID_EXAMPLE +
" = "+ id_example, null);
}
...
}
I see that this is convenient to use my pattern, but the question is ...
is this not a very ugly code from the point of oop or memory management?
I thought much time wondering how to constract ContentProvider class to be
convenient working with many tables (about 10 tables and 60
methods:delete, query, insert..) because I didn't want to have them all in
1 method (delete, query, insert) with 1 switch clause. So I use this
patern, for example:
in ContentProvider class:
public int delete(Uri uri, String where, String[] whereArgs) {
switch (sUriMatcher.match(uri)) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
...
switch (sUriMatcher.match(uri)) {
...
case EXAMPLE_ID:
id = Integer.parseInt(uri.getPathSegments().get(1));
count = tblExample.deleteRaw(db, id);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
I constract 1 class for each table, where I wrote static methods, which I
call from ContentProvider class, they are like this (each method much more
complex in reality):
public class tblExample {
public static final Uri CONTENT_URI = Uri.parse("content://" +
DBContentProvider.AUTHORITY + "/example");
public static final String KEY_ROWID = "_id";
public static final String ROW_ID_EXAMPLE = "id_example";
...
public static int deleteRaw(SQLiteDatabase mDb, int id_example) {
return mDb.delete("tblExample", tblExample.ROW_ID_EXAMPLE +
" = "+ id_example, null);
}
...
}
I see that this is convenient to use my pattern, but the question is ...
is this not a very ugly code from the point of oop or memory management?
Subscribe to:
Comments (Atom)