is my working correct? Vector equations and planes.
Is my working correct with regards to the following question? Any feedback
is appreciated.
Question: Find a vector equation for the plane that passes through the
points $A(1, 1,a),B(2, 0,−1)$ and $C(−2, 1,−1)$. If a
has the value $−1$, what can you say about the plane?
Is my working correct?
Vector $BA = <-1 , 1, 1+a>$ and vector $CA=<3, 0, 1+a>$
A normal vector to the plane $ABC$ is the vector product
$$n=BA x CA =<1+a, 4(1+a), - 3> $$
A vector equation for the plane is
$$r.n = (2,0,-1).(1+a, 4(1+a), -3) =5+2a$$
If $a=-1$ the plane has equation $r.(0,0,-3) = 3$
which has Cartesian equation $z=-1$ and this is a plane parallel to the
$x-y$ plane.
Monday, 30 September 2013
Derivatives and tangent to the line of a curve
Derivatives and tangent to the line of a curve
Find the equations of all tangent lines to the curve y=x/(x+1) that
intersect the point (1,2). Note that the point (1,2) does not lie on the
curve. Please simplify your final answer as much as possible.
This is what I have done so far. I don't know if it is correct.
1/(x+1)= -x-2/(x-1) [cross-multiplied] to get, x-1=-x^2 -3x -2
I made it equal to zero to get a quadratic equation of x^2 + 4x + 1 = 0 to
solve for x I got x = -2 +- root 3
I dont know what to do next.
Find the equations of all tangent lines to the curve y=x/(x+1) that
intersect the point (1,2). Note that the point (1,2) does not lie on the
curve. Please simplify your final answer as much as possible.
This is what I have done so far. I don't know if it is correct.
1/(x+1)= -x-2/(x-1) [cross-multiplied] to get, x-1=-x^2 -3x -2
I made it equal to zero to get a quadratic equation of x^2 + 4x + 1 = 0 to
solve for x I got x = -2 +- root 3
I dont know what to do next.
php preg_match_all get string between two same element
php preg_match_all get string between two same element
please, i want to get every string between two same element (only strong,
not between strong and /strong).
Example string:
<strong>NAME1</strong><br />Some text, some text<br />
<strong>NAME2</strong><br />Some text2, some text2<br />
<strong>NAME3</strong><br />Some text3, some text3<br />
I try this one:
preg_match_all("'<strong>(.*?)<strong>'si", $text, $match);
but result is:
<strong>NAME1</strong><br />Some text, some text<br /><strong>
<strong>NAME3</strong><br />Some text3, some text3<br />
,,NAME2" with ,,some text2" missing, why?
Thank's a lot, Regards, Lukas
please, i want to get every string between two same element (only strong,
not between strong and /strong).
Example string:
<strong>NAME1</strong><br />Some text, some text<br />
<strong>NAME2</strong><br />Some text2, some text2<br />
<strong>NAME3</strong><br />Some text3, some text3<br />
I try this one:
preg_match_all("'<strong>(.*?)<strong>'si", $text, $match);
but result is:
<strong>NAME1</strong><br />Some text, some text<br /><strong>
<strong>NAME3</strong><br />Some text3, some text3<br />
,,NAME2" with ,,some text2" missing, why?
Thank's a lot, Regards, Lukas
center bootstraps nav items
center bootstraps nav items
I add a new class to ul and try to style it with margin: 0 auto and
text-align: center but doesn't work..
<section class="navbar navbar-default">
<ul class="nav navbar-nav">
<li class="active"><a href="index.php">Home</a></li>
<li><a href="venue.php">Venue</a></li>
<li><a href="schedule.php">Schedule</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle"
data-toggle="dropdown">Artists <span
class="caret"></span></a>
<ul class="dropdown-menu" role="menu"
aria-labelledby="dropdownMenu">
<li><a href="artists.php" tabindex="-1">All
Artists</a></li>
<li class="divider"></li>
<li><a href="#" tabindex="-1">1st</a></li>
<li><a href="#" tabindex="-1">2nd</a></li>
<li><a href="#" tabindex="-1">3rd</a></li>
</ul>
</li>
<li><a href="Register.php">Register</a></li>
</ul>
</section>
I add a new class to ul and try to style it with margin: 0 auto and
text-align: center but doesn't work..
<section class="navbar navbar-default">
<ul class="nav navbar-nav">
<li class="active"><a href="index.php">Home</a></li>
<li><a href="venue.php">Venue</a></li>
<li><a href="schedule.php">Schedule</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle"
data-toggle="dropdown">Artists <span
class="caret"></span></a>
<ul class="dropdown-menu" role="menu"
aria-labelledby="dropdownMenu">
<li><a href="artists.php" tabindex="-1">All
Artists</a></li>
<li class="divider"></li>
<li><a href="#" tabindex="-1">1st</a></li>
<li><a href="#" tabindex="-1">2nd</a></li>
<li><a href="#" tabindex="-1">3rd</a></li>
</ul>
</li>
<li><a href="Register.php">Register</a></li>
</ul>
</section>
Sunday, 29 September 2013
jQuery Waypoint: FadeIn - FadeOut effect on scroll
jQuery Waypoint: FadeIn - FadeOut effect on scroll
I'm trying to create a fadeIn and fadeOut effect with elements on scroll.
I'm told this can be done with WayPoint. I've tried a variety of things,
but nothing seems to work, no fade in, no fade out, and no errors in the
console. Here is what I'm currently using:
<script type='text/javascript'>
$(window).load(function(){
$("#top-section").waypoint(function(){
$(this).fadeIn('slow');
},{
offset: 'bottom-in-view'
});
$(this).fadeOut('slow');
},{
offset: 'top-in-view'
});
});
</script>
I'm trying to create a fadeIn and fadeOut effect with elements on scroll.
I'm told this can be done with WayPoint. I've tried a variety of things,
but nothing seems to work, no fade in, no fade out, and no errors in the
console. Here is what I'm currently using:
<script type='text/javascript'>
$(window).load(function(){
$("#top-section").waypoint(function(){
$(this).fadeIn('slow');
},{
offset: 'bottom-in-view'
});
$(this).fadeOut('slow');
},{
offset: 'top-in-view'
});
});
</script>
Pass a generic Object to a list in a method - JAVA
Pass a generic Object to a list in a method - JAVA
I've two question, They may be silly questions but it got me confused now.
QUESTION 1:
I've this code:
private List<Car> carList;
public void setData(List<Object> list)
{
this.carListist = list;
}
But on this.carList = list I get a compiling error: incompatible types,
required: List<Car> but found List<Object>
My question is, why this error? Isn't List a list of objects type Car? So
why doesn't it accept an Object there?
QUESTION 2: I change the above code to the following and the error goes away:
private List<Object> carList;
public void setData(List<Object> list)
{
this.carListist = list;
}
public Object getValueAt(int row, int column) {
Car car = carList.get(row); //Compiling error here
switch(column)
{
(...)
}
(..)
Ther compiling error (signed in the code comment) is incompatible types,
required Car but found Object What I don't understand is, now list is
defined as an object list. Car is an object. Why car, as being an object,
is not accepted?
Anyway to fix this for both question 1 and 2?
I've two question, They may be silly questions but it got me confused now.
QUESTION 1:
I've this code:
private List<Car> carList;
public void setData(List<Object> list)
{
this.carListist = list;
}
But on this.carList = list I get a compiling error: incompatible types,
required: List<Car> but found List<Object>
My question is, why this error? Isn't List a list of objects type Car? So
why doesn't it accept an Object there?
QUESTION 2: I change the above code to the following and the error goes away:
private List<Object> carList;
public void setData(List<Object> list)
{
this.carListist = list;
}
public Object getValueAt(int row, int column) {
Car car = carList.get(row); //Compiling error here
switch(column)
{
(...)
}
(..)
Ther compiling error (signed in the code comment) is incompatible types,
required Car but found Object What I don't understand is, now list is
defined as an object list. Car is an object. Why car, as being an object,
is not accepted?
Anyway to fix this for both question 1 and 2?
Control RTMP chunk size - AWS Cloudfront
Control RTMP chunk size - AWS Cloudfront
I am developing a website where I am using flow player flash as my video
player. I am using AWS(EC2 + S3 + Cloudfront) to manage and store my
files. Using cloudfront RTMP I have setup my video streaming.
But the streaming is bit slow, like the buffer takes too long to play
small size of video, I have tested my internet speed, and rather then my
website other websites like youtube, vimeo works perfectly fine.
I have enabled cache on cloudfront and also the locations are set for best
performance.
Some how is it possible to control chunks size delivered from cloudfront?
I am developing a website where I am using flow player flash as my video
player. I am using AWS(EC2 + S3 + Cloudfront) to manage and store my
files. Using cloudfront RTMP I have setup my video streaming.
But the streaming is bit slow, like the buffer takes too long to play
small size of video, I have tested my internet speed, and rather then my
website other websites like youtube, vimeo works perfectly fine.
I have enabled cache on cloudfront and also the locations are set for best
performance.
Some how is it possible to control chunks size delivered from cloudfront?
My first app can't inlate xml file error
My first app can't inlate xml file error
My first android app is according "Building a Simple User Interface". but
when I run it on my device, it gave me out errors,
E/AndroidRuntime(30660): FATAL EXCEPTION: main
E/AndroidRuntime(30660): java.lang.RuntimeException: Unable to start
activity
ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.MainActivity}:
android.view.InflateException: Binary XML file line #7: Error inflating
class ViewText
E/AndroidRuntime(30660): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(30660): Caused by: android.view.InflateException: Binary
XML file line #7: Error inflating class ViewText
but, when I look into the loaded xml, it don't have any TextView element
in my layout file. my layout file is all as following,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText android:id="@+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/edit_message"
/>
<Button android:id="@+id/send_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
I am confused, what's the problem? thanks your help.
My first android app is according "Building a Simple User Interface". but
when I run it on my device, it gave me out errors,
E/AndroidRuntime(30660): FATAL EXCEPTION: main
E/AndroidRuntime(30660): java.lang.RuntimeException: Unable to start
activity
ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.MainActivity}:
android.view.InflateException: Binary XML file line #7: Error inflating
class ViewText
E/AndroidRuntime(30660): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(30660): Caused by: android.view.InflateException: Binary
XML file line #7: Error inflating class ViewText
but, when I look into the loaded xml, it don't have any TextView element
in my layout file. my layout file is all as following,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText android:id="@+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/edit_message"
/>
<Button android:id="@+id/send_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
I am confused, what's the problem? thanks your help.
Saturday, 28 September 2013
inline-block divs next divs containing images being pushed down
inline-block divs next divs containing images being pushed down
Pleas look at my fiddle:
http://jsfiddle.net/2uJKR/70/
The divs containing text are being pushed down, I want all 4 to be aligned
horizontally.
What is missing?
HTML
<div class="bar">
<div class="element image">
<img src="http://www.itsalif.info/blogfiles/video-play/vthumb.jpg"/>
</div>
<div class="element image">
<img src="http://www.itsalif.info/blogfiles/video-play/vthumb.jpg"/>
</div>
<div class="element">
TEXT 1
</div>
<div class="element ">
TEXT 2
</div>
</div>
CSS
.bar {
position:relative;
margin:1px auto 1px auto;
width:425px;
height:50px;
border:1px solid red;
}
.element {
display:inline-block;
width:100px;
height:50px;
border:1px solid blue;
}
.image img {
display:block;
margin:0 auto;
margin-top:10px;
width:30px;
height:30px;
}
Pleas look at my fiddle:
http://jsfiddle.net/2uJKR/70/
The divs containing text are being pushed down, I want all 4 to be aligned
horizontally.
What is missing?
HTML
<div class="bar">
<div class="element image">
<img src="http://www.itsalif.info/blogfiles/video-play/vthumb.jpg"/>
</div>
<div class="element image">
<img src="http://www.itsalif.info/blogfiles/video-play/vthumb.jpg"/>
</div>
<div class="element">
TEXT 1
</div>
<div class="element ">
TEXT 2
</div>
</div>
CSS
.bar {
position:relative;
margin:1px auto 1px auto;
width:425px;
height:50px;
border:1px solid red;
}
.element {
display:inline-block;
width:100px;
height:50px;
border:1px solid blue;
}
.image img {
display:block;
margin:0 auto;
margin-top:10px;
width:30px;
height:30px;
}
Wordpress 3 parent pages are showing posts not their page content.
Wordpress 3 parent pages are showing posts not their page content.
I have a Wordpress 3.6.1 site at: http://ileap.org/
My top level pages (except the home page ) are showing posts not their
given page content. In the backend the content is right. The weird thing
is that the child pages work fine. Clicking around the nav to any child
page you get the appropriate content, its just the parents. Permalinks are
set to just Post Name, and I have changed the setting saved and then reset
to make sure its not that.
This has stumped me for 2 days now. any ideas?
I am running the metrovibes theme.
I have a Wordpress 3.6.1 site at: http://ileap.org/
My top level pages (except the home page ) are showing posts not their
given page content. In the backend the content is right. The weird thing
is that the child pages work fine. Clicking around the nav to any child
page you get the appropriate content, its just the parents. Permalinks are
set to just Post Name, and I have changed the setting saved and then reset
to make sure its not that.
This has stumped me for 2 days now. any ideas?
I am running the metrovibes theme.
this.parentNode.parentNode.removeChild is removing the parent
this.parentNode.parentNode.removeChild is removing the parent
In my code the function displayUserTable appends some divs called
tUserBlock to the main div called centralWindow. When you click on a
tUserBlock a div pops up from the tUserBlock.onclick function called
userTableClickListener. I want to be able to close that popup when you
click on it so I've added an onclick function called userPopupClick with
the following code inside:
this.parentNode.parentNode.removeChild(this.parentNode);
But when it's clicked the centralWindow div (the main div) disappears
along with all the contents. But I just want to hide the popup div. I'm
not sure what I'm doing wrong?
Here's the code, the popup part is towards the bottom:
function displayUserTable() {
var tTop = 15;
var tUserBlock = [];
for (var z = 0; z < (UserData.length); z++) {
tUserBlock[z] = document.createElement('div');
tUserBlock[z].className = 'usertable_item';
tUserBlock[z].id = ('userblock' + z);
tUserBlock[z].style.width = "388px";
tUserBlock[z].style.height = "35px";
tUserBlock[z].style.top = tTop + "px";
tUserBlock[z].style.left = "25px";
tUserBlock[z].userID = z;
tUserBlock[z].onclick = userTableClickListener;
centerWindow.appendChild(tUserBlock[z]);
}
}
function userTableClickListener() {
var tID = this.userID;
var tPopup = document.createElement('div');
tPopup.className = 'usertable_popup';
tPopup.id = 'usertable_popup';
tPopup.onclick = userPopupClick;
centerWindow.appendChild(tPopup);
}
function userPopupClick() {
this.parentNode.parentNode.removeChild(this.parentNode);
}
In my code the function displayUserTable appends some divs called
tUserBlock to the main div called centralWindow. When you click on a
tUserBlock a div pops up from the tUserBlock.onclick function called
userTableClickListener. I want to be able to close that popup when you
click on it so I've added an onclick function called userPopupClick with
the following code inside:
this.parentNode.parentNode.removeChild(this.parentNode);
But when it's clicked the centralWindow div (the main div) disappears
along with all the contents. But I just want to hide the popup div. I'm
not sure what I'm doing wrong?
Here's the code, the popup part is towards the bottom:
function displayUserTable() {
var tTop = 15;
var tUserBlock = [];
for (var z = 0; z < (UserData.length); z++) {
tUserBlock[z] = document.createElement('div');
tUserBlock[z].className = 'usertable_item';
tUserBlock[z].id = ('userblock' + z);
tUserBlock[z].style.width = "388px";
tUserBlock[z].style.height = "35px";
tUserBlock[z].style.top = tTop + "px";
tUserBlock[z].style.left = "25px";
tUserBlock[z].userID = z;
tUserBlock[z].onclick = userTableClickListener;
centerWindow.appendChild(tUserBlock[z]);
}
}
function userTableClickListener() {
var tID = this.userID;
var tPopup = document.createElement('div');
tPopup.className = 'usertable_popup';
tPopup.id = 'usertable_popup';
tPopup.onclick = userPopupClick;
centerWindow.appendChild(tPopup);
}
function userPopupClick() {
this.parentNode.parentNode.removeChild(this.parentNode);
}
How would i append the text file into my contenteditable div?
How would i append the text file into my contenteditable div?
Process only .txt files
Format if not properly formatted (apple-tab-span must be converted into
if possible)
Append to my contenteditable div
I know no.2 is way far from this question, just tell me how would i
process something like it. I've already finished the IDE-like system and
im about to add the Open and Save functions.
$('#open').addEventListener('change', getTextFile, false);
function getTextFile (e) {
var files = e.target.files;
var file = files[0];
var reader = new FileReader();
reader.onload = function() {
console.log(this.result);
}
reader.readAsText(file)
}
http://jsfiddle.net/3veCE/7/
Process only .txt files
Format if not properly formatted (apple-tab-span must be converted into
if possible)
Append to my contenteditable div
I know no.2 is way far from this question, just tell me how would i
process something like it. I've already finished the IDE-like system and
im about to add the Open and Save functions.
$('#open').addEventListener('change', getTextFile, false);
function getTextFile (e) {
var files = e.target.files;
var file = files[0];
var reader = new FileReader();
reader.onload = function() {
console.log(this.result);
}
reader.readAsText(file)
}
http://jsfiddle.net/3veCE/7/
Friday, 27 September 2013
Excluding hasMany models in CakePHP
Excluding hasMany models in CakePHP
Here's my basic setup... Families hasMany Students hasMany Enrollment
Is there a way to exclude a student if enrollment is empty? Here is my
find method.
$options = array(
'order' => array('Family.family_last_name'),
'group' => 'Family.id',
'contain' => array(
'Student', 'Student.Enrollment'
),
'joins' => array(
array(
'table' => 'students',
'alias' => 'Student',
'type' => 'left',
'conditions' => array(
'Family.id = Student.family_id'
)
),
array(
'table' => 'enrollment',
'alias' => 'Enrollment',
'type' => 'left',
'conditions' => array(
'Enrollment.student_id = Student.id'
)
)
),
'conditions' => array(
'Enrollment.status =' => 'withdrawn'
)
);
$enrollment = $this->Family->find( 'all', $options);
Here is the array that it is returning. How can I remove Jack?
[Student] => Array
(
[0] => Array
(
[id] => 92
[first_name] => Jack
[Enrollment] => Array
(
)
)
[1] => Array
(
[id] => 93
[first_name] => Jill
[Enrollment] => Array
(
[0] => Array
(
[id] => 99
[student_id] => 93
[grade] => 4
)
)
)
)
Here's my basic setup... Families hasMany Students hasMany Enrollment
Is there a way to exclude a student if enrollment is empty? Here is my
find method.
$options = array(
'order' => array('Family.family_last_name'),
'group' => 'Family.id',
'contain' => array(
'Student', 'Student.Enrollment'
),
'joins' => array(
array(
'table' => 'students',
'alias' => 'Student',
'type' => 'left',
'conditions' => array(
'Family.id = Student.family_id'
)
),
array(
'table' => 'enrollment',
'alias' => 'Enrollment',
'type' => 'left',
'conditions' => array(
'Enrollment.student_id = Student.id'
)
)
),
'conditions' => array(
'Enrollment.status =' => 'withdrawn'
)
);
$enrollment = $this->Family->find( 'all', $options);
Here is the array that it is returning. How can I remove Jack?
[Student] => Array
(
[0] => Array
(
[id] => 92
[first_name] => Jack
[Enrollment] => Array
(
)
)
[1] => Array
(
[id] => 93
[first_name] => Jill
[Enrollment] => Array
(
[0] => Array
(
[id] => 99
[student_id] => 93
[grade] => 4
)
)
)
)
Java Regex pattern to match string with apostrophes
Java Regex pattern to match string with apostrophes
I need to match a pattern to strip the 's as well as the ending ' from
words. I've used the regex pattern (\w+)('s$|s'$|'$). I need the first
group. However what is happening with this pattern is a word like cats'
matches with the third pattern i.e '$. Hence my group(1) still has cats. I
tried using the pattern (\w+)('s$|s'$|([^s] & '$).But here what happens is
for a word abc' group 1 has just ab and group 2 has c'. Any suggestions on
how to handle this.
I need to match a pattern to strip the 's as well as the ending ' from
words. I've used the regex pattern (\w+)('s$|s'$|'$). I need the first
group. However what is happening with this pattern is a word like cats'
matches with the third pattern i.e '$. Hence my group(1) still has cats. I
tried using the pattern (\w+)('s$|s'$|([^s] & '$).But here what happens is
for a word abc' group 1 has just ab and group 2 has c'. Any suggestions on
how to handle this.
Inline conditional statement clarification
Inline conditional statement clarification
I am sorry for the vague question title. I'm not sure what the actual name
of this shorthand method is. If someone wants to help clarify how I should
refer to this, I'll be glad to change the question title.
In the following code snippet:
$account = $value->uid ? user_load($value->uid) : '';
I am a little confused on what this code does. Here is what I think it
does: if $value->uid exists then $account = user_load($value->uid) else
$account = ''
Is that correct?
I am sorry for the vague question title. I'm not sure what the actual name
of this shorthand method is. If someone wants to help clarify how I should
refer to this, I'll be glad to change the question title.
In the following code snippet:
$account = $value->uid ? user_load($value->uid) : '';
I am a little confused on what this code does. Here is what I think it
does: if $value->uid exists then $account = user_load($value->uid) else
$account = ''
Is that correct?
Weird issue with jQueryUI modal
Weird issue with jQueryUI modal
I'm having a weird issue with the jQueryUI modal (the dialog plugin that
can include modal functionality). I have a dropdown list that is a <span>
with a <ul> that only opens when you click on the <span>. The modal is set
to pop up when the second <li> in the <ul> is clicked. Now, the modal
opens up just fine, however for some reason the link the user has to click
on to get to the modal is somehow transferred to the modal, and when the
modal is closed, it disappears from the <ul>. Also, no text shows up, even
though I put text there. Here is the HTML portion:
<span class="dropdown" id="loggedInDropdown">
<i class="spriteIcons iconArrowUp"></i>
<ul class="zebraRows">
<li><a id="accountSettings"
href="/stuff/settings" title="">Account
Settings</a></li>
<li><a id="addFunds" class="no-close" href=""
title="Add Funds to Your Account">Add
Funds</a></li>
<li><a id="signOut" href="/users/logout"
title="">Sign Out</a></li>
</ul>
</span>
Here is the jQuery:
$('#loggedInDropdown').on('click', '#addFunds', function(e) {
e.preventDefault();
$('#addFunds').dialog({
modal: true,
// other stuff
text: 'Whatever'
});
});
I'm having a weird issue with the jQueryUI modal (the dialog plugin that
can include modal functionality). I have a dropdown list that is a <span>
with a <ul> that only opens when you click on the <span>. The modal is set
to pop up when the second <li> in the <ul> is clicked. Now, the modal
opens up just fine, however for some reason the link the user has to click
on to get to the modal is somehow transferred to the modal, and when the
modal is closed, it disappears from the <ul>. Also, no text shows up, even
though I put text there. Here is the HTML portion:
<span class="dropdown" id="loggedInDropdown">
<i class="spriteIcons iconArrowUp"></i>
<ul class="zebraRows">
<li><a id="accountSettings"
href="/stuff/settings" title="">Account
Settings</a></li>
<li><a id="addFunds" class="no-close" href=""
title="Add Funds to Your Account">Add
Funds</a></li>
<li><a id="signOut" href="/users/logout"
title="">Sign Out</a></li>
</ul>
</span>
Here is the jQuery:
$('#loggedInDropdown').on('click', '#addFunds', function(e) {
e.preventDefault();
$('#addFunds').dialog({
modal: true,
// other stuff
text: 'Whatever'
});
});
domain / padding in d3.js linear scales
domain / padding in d3.js linear scales
Folks-
I've been trying to set the d3.scale.linear.domain x axis value manually,
using Mike Bostock's simple bar chart:
http://bl.ocks.org/mbostock/raw/2368837/
var x = d3.scale.linear()
.domain([-100, 200]) //this line added
.range([0, width])
I would expect this to yield a an x axis with values -100 to 200. Instead
it yields -30 to 10, as before, and the chart doesn't change. Any ideas?
Thanks,
RL
Folks-
I've been trying to set the d3.scale.linear.domain x axis value manually,
using Mike Bostock's simple bar chart:
http://bl.ocks.org/mbostock/raw/2368837/
var x = d3.scale.linear()
.domain([-100, 200]) //this line added
.range([0, width])
I would expect this to yield a an x axis with values -100 to 200. Instead
it yields -30 to 10, as before, and the chart doesn't change. Any ideas?
Thanks,
RL
selected item of listbox inserted into sql database using classic asp
selected item of listbox inserted into sql database using classic asp
I am having asp form that contains 10 list boxes in 10 rows.The user may
select 5 list boxes out of 10...if they submit that form.it needs to
insert that selected 5 rows instead it insert all the 10 list boxes even
if the remaining text boxes are not selected by the user.
Kindly help me to insert the selected list boxes.
I am having asp form that contains 10 list boxes in 10 rows.The user may
select 5 list boxes out of 10...if they submit that form.it needs to
insert that selected 5 rows instead it insert all the 10 list boxes even
if the remaining text boxes are not selected by the user.
Kindly help me to insert the selected list boxes.
Thursday, 26 September 2013
Eclipse is not recognizing my GIF animation file
Eclipse is not recognizing my GIF animation file
I am trying to use a GIF (animated) file as Splash screen for my
application. I use Eclipse IDE.
I created the GIF using 6 JPEG images. It works perfectly fine if I open
it in IE.
But Eclipse is not recognizing the file.
The following code returns 'null'.
SplashScreen splash = SplashScreen.getSplashScreen();
if(splash==null)
System.out.println("It was null!!");
else
System.out.println("It wasn't null!!!");
If I replace my GIF file (180kb) with another GIF (150kb), Eclipse is
recognizing it.
Are there any conditions that a GIF file should meet to be compatible with
Eclipse?
I am trying to use a GIF (animated) file as Splash screen for my
application. I use Eclipse IDE.
I created the GIF using 6 JPEG images. It works perfectly fine if I open
it in IE.
But Eclipse is not recognizing the file.
The following code returns 'null'.
SplashScreen splash = SplashScreen.getSplashScreen();
if(splash==null)
System.out.println("It was null!!");
else
System.out.println("It wasn't null!!!");
If I replace my GIF file (180kb) with another GIF (150kb), Eclipse is
recognizing it.
Are there any conditions that a GIF file should meet to be compatible with
Eclipse?
Thursday, 19 September 2013
Runtime.getruntime.exec will not return anything when executing sesearch command
Runtime.getruntime.exec will not return anything when executing sesearch
command
This is a common problem from what I see, but I tried to incorporate some
of the suggestions provided. None worked for me. Am I making a mistake
here? This is what I am trying to do.
String[] comd1 = { "/bin/sh", "-c", "sesearch", "--allow -s "+tokens[1],"
-t "+tokens[2].split(":")[0]," -c "+tokens[2].split(":")[1]," -p
"+tokens[3].replace(";","")," sepolicy" };
Process pp = Runtime.getRuntime().exec(comd1);
stdInput = new BufferedReader(new InputStreamReader(pp.getInputStream()));
String temp, status = null;
boolean flag = false;
while ((temp = stdInput.readLine()) != null)
{
if(temp.contains("Found ") || temp.equals("")
|| temp.contains("Usage"))
{
}
else
flag = true;
}
if(flag) status="Yes"; else status="No";
The flag which is initially set to false, is always false. It never sets
to true. I have tried nearly every combination of the comd1 string array.
Please help.
command
This is a common problem from what I see, but I tried to incorporate some
of the suggestions provided. None worked for me. Am I making a mistake
here? This is what I am trying to do.
String[] comd1 = { "/bin/sh", "-c", "sesearch", "--allow -s "+tokens[1],"
-t "+tokens[2].split(":")[0]," -c "+tokens[2].split(":")[1]," -p
"+tokens[3].replace(";","")," sepolicy" };
Process pp = Runtime.getRuntime().exec(comd1);
stdInput = new BufferedReader(new InputStreamReader(pp.getInputStream()));
String temp, status = null;
boolean flag = false;
while ((temp = stdInput.readLine()) != null)
{
if(temp.contains("Found ") || temp.equals("")
|| temp.contains("Usage"))
{
}
else
flag = true;
}
if(flag) status="Yes"; else status="No";
The flag which is initially set to false, is always false. It never sets
to true. I have tried nearly every combination of the comd1 string array.
Please help.
how to connect to server with eclipse like dreamweaver (site)
how to connect to server with eclipse like dreamweaver (site)
The only think dreamweaver has over eclipse is the ability to connect to
your server to download files to dreamweaver, edit it and then upload back
to the server. I want to be able to do the same in eclipse(Eclipse
Standard/SDK,Version: Kepler Release, Build id: 20130614-0229). Is it
possible?
The only think dreamweaver has over eclipse is the ability to connect to
your server to download files to dreamweaver, edit it and then upload back
to the server. I want to be able to do the same in eclipse(Eclipse
Standard/SDK,Version: Kepler Release, Build id: 20130614-0229). Is it
possible?
Getting PIVOT using GroupBy
Getting PIVOT using GroupBy
I have this table:
Person Job Day EndDay
1 101 1 12
1 102 2 11
1 103 3 11
3 101 1 11
3 102 2 11
3 JobOff 3 11
2 101 1 11
2 102 2 11
2 103 3 11
2 JobOff 4 11
And I need to change it to this form:
Day (Columns)
Person (Rows)
Person 1 2 3 4
1 101 102 103 N/A
2 101 102 103 JobOff
3 101 102 JobOff N/A
Any help would be appreciated. I am very new in SQL.
I have this table:
Person Job Day EndDay
1 101 1 12
1 102 2 11
1 103 3 11
3 101 1 11
3 102 2 11
3 JobOff 3 11
2 101 1 11
2 102 2 11
2 103 3 11
2 JobOff 4 11
And I need to change it to this form:
Day (Columns)
Person (Rows)
Person 1 2 3 4
1 101 102 103 N/A
2 101 102 103 JobOff
3 101 102 JobOff N/A
Any help would be appreciated. I am very new in SQL.
Is it possible to refresh a DIV without another page inside the DIV?
Is it possible to refresh a DIV without another page inside the DIV?
as the title says, is it possible to refresh a div without another html or
php page inside of the div?
for example this is what can be done using jquery and ajax:
$(document).ready(function () {
$('#mydiv').delay(10000).load('page.php');
});
My Div shows/holds a data which is pulled from the mysql database and it
doesn't have page.php inside it.
I've searched for this and all the results were similar to the one i
posted above!
is this even possible and if so how?
as the title says, is it possible to refresh a div without another html or
php page inside of the div?
for example this is what can be done using jquery and ajax:
$(document).ready(function () {
$('#mydiv').delay(10000).load('page.php');
});
My Div shows/holds a data which is pulled from the mysql database and it
doesn't have page.php inside it.
I've searched for this and all the results were similar to the one i
posted above!
is this even possible and if so how?
NServiceBus with Oracle Tables transport
NServiceBus with Oracle Tables transport
Is it possible to replace MSMQ with Oracle tables as a transport
mechanism? if so, can someone point me to info on configuring nsb as such.
Thanks.
Is it possible to replace MSMQ with Oracle tables as a transport
mechanism? if so, can someone point me to info on configuring nsb as such.
Thanks.
Getting CakePHP HtmlHelper to generate a "date" input
Getting CakePHP HtmlHelper to generate a "date" input
I've been making some basic CRUD pages for my cakePHP app using the
HtmlHelper for the views. This is handy for building forms but for date
inputs the helper, by default generates 3 select boxes for the date which
is quite cumbersome to use.
HTML5 introduces the input[type=date] and most browsers now incorporate
some nice native interfaces to deal with it; e.g. Chrome produces a nice
date-picker for date inputs.
I know it is possible to make the HtmlHelper just make the input a text
box instead of the 3 dropdown by doing the following:
echo $this->Form->input('my_date', array('type' => 'text'));
But when I do
echo $this->Form->input('my_date', array('type' => 'date'));
it ignores the 2nd arguement and goes back to the 3 selects.
Is there a way to get the helper to make a date input?
I've been making some basic CRUD pages for my cakePHP app using the
HtmlHelper for the views. This is handy for building forms but for date
inputs the helper, by default generates 3 select boxes for the date which
is quite cumbersome to use.
HTML5 introduces the input[type=date] and most browsers now incorporate
some nice native interfaces to deal with it; e.g. Chrome produces a nice
date-picker for date inputs.
I know it is possible to make the HtmlHelper just make the input a text
box instead of the 3 dropdown by doing the following:
echo $this->Form->input('my_date', array('type' => 'text'));
But when I do
echo $this->Form->input('my_date', array('type' => 'date'));
it ignores the 2nd arguement and goes back to the 3 selects.
Is there a way to get the helper to make a date input?
Implementing the Algorithm X with Dancing links to solve pentomino tiling
Implementing the Algorithm X with Dancing links to solve pentomino tiling
http://en.wikipedia.org/wiki/Exact_cover#Pentomino_tiling
How are we constructing the matrix for algorithm X. The columns have to be
the constraint imposed on the problem i.e. 12 pentomino to be used exactly
once + each of the 60 square have to be filled exactly once. This gives
(12+60=72) constraints hence the 72 columns. The question is how are the
rows generated?
http://en.wikipedia.org/wiki/Exact_cover#Pentomino_tiling
How are we constructing the matrix for algorithm X. The columns have to be
the constraint imposed on the problem i.e. 12 pentomino to be used exactly
once + each of the 60 square have to be filled exactly once. This gives
(12+60=72) constraints hence the 72 columns. The question is how are the
rows generated?
Wednesday, 18 September 2013
how to search in Youtube and play Video in Windows Phone
how to search in Youtube and play Video in Windows Phone
I am beginner in windows phone.
And i have to search in you tube for the video.. and bind that videos in
to the list box and when the user clicks on any video.
The video is played in windows phone.
Please suggest me any blog or msdn documentation for this.
I am beginner in windows phone.
And i have to search in you tube for the video.. and bind that videos in
to the list box and when the user clicks on any video.
The video is played in windows phone.
Please suggest me any blog or msdn documentation for this.
Anyone get the chromecast android examples working in android studio?
Anyone get the chromecast android examples working in android studio?
I've had a terrible time trying to get these to load without errors.
Either the support frameworks fail or the cast api. Anyone have a
repeatable method?
The github examples say 'coming soon' for loading into android studio.
I've had a terrible time trying to get these to load without errors.
Either the support frameworks fail or the cast api. Anyone have a
repeatable method?
The github examples say 'coming soon' for loading into android studio.
Kendo Grid Calendar Filter for Certain Days
Kendo Grid Calendar Filter for Certain Days
I have a date field in a Kendo grid and when a user edits the record, I
would like it to be so that they are only allowed to select Monday on the
calendar. Has anyone tried to do such a thing?
I have a date field in a Kendo grid and when a user edits the record, I
would like it to be so that they are only allowed to select Monday on the
calendar. Has anyone tried to do such a thing?
Entity Framework - Possible to have part of compound primary key used in foreign key
Entity Framework - Possible to have part of compound primary key used in
foreign key
I am trying to fit Entity Framework 5 to a legacy database where 2 tables
both define a compound primary key.
Product(ProductId, VersionId, Name, StrengthId) <- ProductId and VersionId
form the PK
Strength(StrengthId, VersionId, Description) <- StrengthId and VersionId
form the PK
There is a foreign key between the 2 tables defined as Product.StrengthId
and Product.VersionID relates to Strength.StrengthId and
Strength.VersionId which means that the foreign key uses part of the
compound primary key of both tables.
I set up my mappings as follows:
public ProductConfiguraton()
{
ToTable("t_Product");
HasKey(p => new { p.Id, p.VersionId });
HasRequired(p => p.Strength)
.WithMany(b => b.Products)
.Map(m => m.MapKey("iStrengthID", "iVersionID"));
Property(p => p.Id).HasColumnName("iProductId");
Property(p => p.Name).HasColumnName("sName");
//Property(p => p.VersionId).HasColumnName("iVersionID");
}
public StrengthConfiguration()
{
ToTable("t_Strength");
HasKey(p => new { p.Id, p.VersionId });
Property(p => p.Id).HasColumnName("iStrengthID");
Property(p => p.VersionId).HasColumnName("iVersionID");
Property(p => p.Description).HasColumnName("sStrengthText");
}
That produces the following create table script fragments:
CREATE TABLE IF NOT EXISTS t_LIVE_Product (
iD INTEGER NOT NULL,
VersionId INTEGER NOT NULL,
sName text NULL,
iStrengthID INTEGER NOT NULL,
iVersionID INTEGER NOT NULL,
PRIMARY KEY (iD, VersionId),
FOREIGN KEY (iStrengthID, iVersionID) REFERENCES t_LIVE_Strength
(iStrengthID, iVersionID) ON DELETE CASCADE
);
-- Index for foreign key FK_Product_Strength
CREATE INDEX IX_FK_Product_Strength ON t_LIVE_Product (iStrengthID,
iVersionID);
CREATE TABLE IF NOT EXISTS t_LIVE_Strength (
iStrengthID INTEGER NOT NULL,
iVersionID INTEGER NOT NULL,
sStrengthText text NULL,
PRIMARY KEY (iStrengthID, iVersionID)
);
The Product table has created 2 columns for VersionId (VersionId and
iVersionID), which is not what I want. If I uncomment the last line in my
ProductConfiguration which I get the following error:
error 0019: Each property name in a type must be unique. Property name
'iVersionID' was already defined.
This makes sense, but leaves me no closer to solving my problem.
Is what I am attempting to do possible or does anyone know of any
workarounds to try and fit this schema into EF?
foreign key
I am trying to fit Entity Framework 5 to a legacy database where 2 tables
both define a compound primary key.
Product(ProductId, VersionId, Name, StrengthId) <- ProductId and VersionId
form the PK
Strength(StrengthId, VersionId, Description) <- StrengthId and VersionId
form the PK
There is a foreign key between the 2 tables defined as Product.StrengthId
and Product.VersionID relates to Strength.StrengthId and
Strength.VersionId which means that the foreign key uses part of the
compound primary key of both tables.
I set up my mappings as follows:
public ProductConfiguraton()
{
ToTable("t_Product");
HasKey(p => new { p.Id, p.VersionId });
HasRequired(p => p.Strength)
.WithMany(b => b.Products)
.Map(m => m.MapKey("iStrengthID", "iVersionID"));
Property(p => p.Id).HasColumnName("iProductId");
Property(p => p.Name).HasColumnName("sName");
//Property(p => p.VersionId).HasColumnName("iVersionID");
}
public StrengthConfiguration()
{
ToTable("t_Strength");
HasKey(p => new { p.Id, p.VersionId });
Property(p => p.Id).HasColumnName("iStrengthID");
Property(p => p.VersionId).HasColumnName("iVersionID");
Property(p => p.Description).HasColumnName("sStrengthText");
}
That produces the following create table script fragments:
CREATE TABLE IF NOT EXISTS t_LIVE_Product (
iD INTEGER NOT NULL,
VersionId INTEGER NOT NULL,
sName text NULL,
iStrengthID INTEGER NOT NULL,
iVersionID INTEGER NOT NULL,
PRIMARY KEY (iD, VersionId),
FOREIGN KEY (iStrengthID, iVersionID) REFERENCES t_LIVE_Strength
(iStrengthID, iVersionID) ON DELETE CASCADE
);
-- Index for foreign key FK_Product_Strength
CREATE INDEX IX_FK_Product_Strength ON t_LIVE_Product (iStrengthID,
iVersionID);
CREATE TABLE IF NOT EXISTS t_LIVE_Strength (
iStrengthID INTEGER NOT NULL,
iVersionID INTEGER NOT NULL,
sStrengthText text NULL,
PRIMARY KEY (iStrengthID, iVersionID)
);
The Product table has created 2 columns for VersionId (VersionId and
iVersionID), which is not what I want. If I uncomment the last line in my
ProductConfiguration which I get the following error:
error 0019: Each property name in a type must be unique. Property name
'iVersionID' was already defined.
This makes sense, but leaves me no closer to solving my problem.
Is what I am attempting to do possible or does anyone know of any
workarounds to try and fit this schema into EF?
Nested quotes bash
Nested quotes bash
I want to imbricate multiple strings like this :
sudo ssh server "awk "/pattern/{print "hello"}1" file > file.tmp"
With 2 nested quotes I managed to make my command works :
awk "/pattern/{print \"hello\"}1" file > file.tmp
I cannot use single quote (') because there are variables in my command.
Can someone help me ?
Thanks in advance.
I want to imbricate multiple strings like this :
sudo ssh server "awk "/pattern/{print "hello"}1" file > file.tmp"
With 2 nested quotes I managed to make my command works :
awk "/pattern/{print \"hello\"}1" file > file.tmp
I cannot use single quote (') because there are variables in my command.
Can someone help me ?
Thanks in advance.
multiple file view like DB-view
multiple file view like DB-view
Is it possible, using bash, to create a view/virtual file that when opened
combines 2 files into 1?
example:
FILE_META_1.txt
FILE_META_2.txt
combines into
FILE_META.txt
Is it possible, using bash, to create a view/virtual file that when opened
combines 2 files into 1?
example:
FILE_META_1.txt
FILE_META_2.txt
combines into
FILE_META.txt
Jquery sound auto play without button
Jquery sound auto play without button
I have a setInterval that moves bulldozer from the right to the left.
If the car doesn't jump, the setInterval must stop itself after 5 seconds.
(used a setTimeout and clearInterval for that) but it's not working. can
anyone help me?
http://jsfiddle.net/B5MKj/8/
var gameover;
gameover = setInterval(function () {
if //the condition is true right now in the example..
{
setTimeout(function () {
clearInterval(movingbulldozer);
}, 5000);
}
}, 10);
I have a setInterval that moves bulldozer from the right to the left.
If the car doesn't jump, the setInterval must stop itself after 5 seconds.
(used a setTimeout and clearInterval for that) but it's not working. can
anyone help me?
http://jsfiddle.net/B5MKj/8/
var gameover;
gameover = setInterval(function () {
if //the condition is true right now in the example..
{
setTimeout(function () {
clearInterval(movingbulldozer);
}, 5000);
}
}, 10);
about android: custom listview using activity or listfragment
about android: custom listview using activity or listfragment
i create a custom listview that contain 3 items
my question is how come when i used activity if you want to create custom
listview you create 1st a layout for a single row and and inflate it
inside other layout container
and when i used listfragment i dont need a parent layout container i just
directly used only the single row layout and i dont have to use any parent
of it
i need explaination of it, i have no problem running it but i need info
how it runs without parent layout to put in single row layout of the
listview?
i create a custom listview that contain 3 items
my question is how come when i used activity if you want to create custom
listview you create 1st a layout for a single row and and inflate it
inside other layout container
and when i used listfragment i dont need a parent layout container i just
directly used only the single row layout and i dont have to use any parent
of it
i need explaination of it, i have no problem running it but i need info
how it runs without parent layout to put in single row layout of the
listview?
Tuesday, 17 September 2013
Unit testing levels of classes with Nunit and Nmock
Unit testing levels of classes with Nunit and Nmock
I have a levels of classes and interfaces namely Level1, Level2 and
Level3. Class Level1 depends on class Level2 and class Level2 depends on
class Level3.
Here is the code for that design:
public interface ILevel1
{
string GetData();
}
public class Level1 : ILevel1
{
ILevel2 level2;
public Level1(ILevel2 level2)
{
this.level2 = level2;
}
public string GetData()
{
// some more process on data.
var data = level2.GetDataAndProc();
data = data + ",Proc at Level1";
return data;
}
}
public interface ILevel2
{
string GetDataAndProc();
}
public class Level2 : ILevel2
{
ILevel3 level3;
public Level2(ILevel3 level3)
{
this.level3=level3;
}
public string GetDataAndProc()
{
var data=level3.GetDataFromDB();
// processing on the data from db.
data=data+ " Processed at level2";
return data;
}
}
public interface ILevel3
{
string GetDataFromDB();
}
public class Level3 : ILevel3
{
public string GetDataFromDB()
{
// Functionalities to get data from db.
return "DB Data";
}
}
Now, i can unit test class Level1 in isolation mocking Level2 interface
and unit test class Level2 in isolation mocking Level3 interface. I am
using Nunit as testing framework and NMock as mocking framework.
So far so good.
But, can i unit test First two levels of code only mocking Level3
interface without mocking Level2? I mean i want to unit test class Level1
without mocking Level2 but mocking Level3. I wanted to do this because
Level3 class gets data from DB and i want to mock only this DB layer so
that my whole project works just with mock db not with real db.
I have a levels of classes and interfaces namely Level1, Level2 and
Level3. Class Level1 depends on class Level2 and class Level2 depends on
class Level3.
Here is the code for that design:
public interface ILevel1
{
string GetData();
}
public class Level1 : ILevel1
{
ILevel2 level2;
public Level1(ILevel2 level2)
{
this.level2 = level2;
}
public string GetData()
{
// some more process on data.
var data = level2.GetDataAndProc();
data = data + ",Proc at Level1";
return data;
}
}
public interface ILevel2
{
string GetDataAndProc();
}
public class Level2 : ILevel2
{
ILevel3 level3;
public Level2(ILevel3 level3)
{
this.level3=level3;
}
public string GetDataAndProc()
{
var data=level3.GetDataFromDB();
// processing on the data from db.
data=data+ " Processed at level2";
return data;
}
}
public interface ILevel3
{
string GetDataFromDB();
}
public class Level3 : ILevel3
{
public string GetDataFromDB()
{
// Functionalities to get data from db.
return "DB Data";
}
}
Now, i can unit test class Level1 in isolation mocking Level2 interface
and unit test class Level2 in isolation mocking Level3 interface. I am
using Nunit as testing framework and NMock as mocking framework.
So far so good.
But, can i unit test First two levels of code only mocking Level3
interface without mocking Level2? I mean i want to unit test class Level1
without mocking Level2 but mocking Level3. I wanted to do this because
Level3 class gets data from DB and i want to mock only this DB layer so
that my whole project works just with mock db not with real db.
Boost Regex - Stopping after first character
Boost Regex - Stopping after first character
So I'm currently having trouble with my regex where it is stopping after
reading the first character on a regex_search.
The line is in the following format:
transition (0,1)->(1)
transition (0,b)->(300)
etc etc
iss >> w[1];
boost::regex reg("([[:alnum:]])");
boost::smatch x1;
boost::regex_search(w[1], x1, reg);
//string text(x1[0]);
cout << x1[1] << " " << x1[2] << " " << x1[3] << endl;
This prints:
0
0
I want it to print out:
0 1 1
0 b 300
Would appreciate any help. Thanks.
So I'm currently having trouble with my regex where it is stopping after
reading the first character on a regex_search.
The line is in the following format:
transition (0,1)->(1)
transition (0,b)->(300)
etc etc
iss >> w[1];
boost::regex reg("([[:alnum:]])");
boost::smatch x1;
boost::regex_search(w[1], x1, reg);
//string text(x1[0]);
cout << x1[1] << " " << x1[2] << " " << x1[3] << endl;
This prints:
0
0
I want it to print out:
0 1 1
0 b 300
Would appreciate any help. Thanks.
How to show all the errors and get a JSHint report in JavaScript?
How to show all the errors and get a JSHint report in JavaScript?
I have the following code that validates JavaScript code:
var jsCode = "....."; // JavaScript code here
var success = JSHint(jsCode); //
alert(success); // Shows whether 'true' or 'false'
How can I show the list of all errors in the code instead of just 'true'
or 'false'? In the documentation, it says, "In that case, you can use
JSHINT.errors to retrieve the errors or request a complete report by
calling the JSHINT.data() method."
I have the following code that validates JavaScript code:
var jsCode = "....."; // JavaScript code here
var success = JSHint(jsCode); //
alert(success); // Shows whether 'true' or 'false'
How can I show the list of all errors in the code instead of just 'true'
or 'false'? In the documentation, it says, "In that case, you can use
JSHINT.errors to retrieve the errors or request a complete report by
calling the JSHINT.data() method."
Can Eclipse use .so files from NDK compilation on another platform?
Can Eclipse use .so files from NDK compilation on another platform?
On a mac OS X I run ndk which generates some .so libraries which in theory
should be reusable on windows. However, when I eclipse recompile my
Android project on windows I get different apk size and it runs
differently than when the whole eclipse build is done on Mac. Only
building on the mac works. Not taking the .so files from the mac ndk
build, and reusing them in the windows build. Its either that or something
different about how macs and windows builds apk files that I don't
understand. The problem with the windows generated apk is that it has
memory over consumption not seen on the apk generated solely on osx.
So to clarify this (ON MAC OS X) works:
1) run ndk on ios generate .so files 2) OS X eclipse compile android app
and deploy on device. 3) OS X eclipse run apk on device.
the generated apk of course runs on all devices.
This (ON WINDOWS) does NOT work: 1) on windows use .so generated on ios
ndk build. 2) windows eclipse compile android apps using the .so files
generated by ndk on OS X. 3) eclipse run apk on device. The apk is of a
different byte count and although it loads, it now generates memory errors
unlike the apk developed solely on the OS X.
Thanks!
On a mac OS X I run ndk which generates some .so libraries which in theory
should be reusable on windows. However, when I eclipse recompile my
Android project on windows I get different apk size and it runs
differently than when the whole eclipse build is done on Mac. Only
building on the mac works. Not taking the .so files from the mac ndk
build, and reusing them in the windows build. Its either that or something
different about how macs and windows builds apk files that I don't
understand. The problem with the windows generated apk is that it has
memory over consumption not seen on the apk generated solely on osx.
So to clarify this (ON MAC OS X) works:
1) run ndk on ios generate .so files 2) OS X eclipse compile android app
and deploy on device. 3) OS X eclipse run apk on device.
the generated apk of course runs on all devices.
This (ON WINDOWS) does NOT work: 1) on windows use .so generated on ios
ndk build. 2) windows eclipse compile android apps using the .so files
generated by ndk on OS X. 3) eclipse run apk on device. The apk is of a
different byte count and although it loads, it now generates memory errors
unlike the apk developed solely on the OS X.
Thanks!
Microsoft Sync Framework through USB between Windows CE Device and Windows PC
Microsoft Sync Framework through USB between Windows CE Device and Windows PC
How can we use the MS Sync Framework to synchronize a text file located on
a Windows CE 6.0 device with a text file located on a Windows PC when the
device and the PC are connected through USB?
We already know how to do this when...
the two text files to sync are located on the same PC,
the device and the PC are connected through ethernet, and
the device and the PC are connected through Internet.
Our current hack is as follows:
The user connects the device cradle to the PC using USB.
The user docks the device in its cradle.
The user opens the desktop app on the PC.
The user clicks the sync button in the desktop app.
The desktop app uses the Remote API (RAPI2) to copy the text file from the
device to the PC.
The desktop app uses the MS Sync framework to sync the two files.
The desktop app uses RAPI2 to copy the synced text file back to the device.
This could run into problems, we think, as the target text file becomes
large. That is why we want to sync across the USB connection instead of
copying the file twice across the USB connection.
Do we need to write a driver to do this? What approach can we use?
How can we use the MS Sync Framework to synchronize a text file located on
a Windows CE 6.0 device with a text file located on a Windows PC when the
device and the PC are connected through USB?
We already know how to do this when...
the two text files to sync are located on the same PC,
the device and the PC are connected through ethernet, and
the device and the PC are connected through Internet.
Our current hack is as follows:
The user connects the device cradle to the PC using USB.
The user docks the device in its cradle.
The user opens the desktop app on the PC.
The user clicks the sync button in the desktop app.
The desktop app uses the Remote API (RAPI2) to copy the text file from the
device to the PC.
The desktop app uses the MS Sync framework to sync the two files.
The desktop app uses RAPI2 to copy the synced text file back to the device.
This could run into problems, we think, as the target text file becomes
large. That is why we want to sync across the USB connection instead of
copying the file twice across the USB connection.
Do we need to write a driver to do this? What approach can we use?
How capture compilation errors from an include script?
How capture compilation errors from an include script?
I want to include a file inside a function and using ob_start(),
ob_get_contents(), etc save the output to a file.
But if there's an error in that included file, I want:
For my function to know that and capture it (so it can handle it gracefully)
To not output the error
Will set_error_handler allow this?
I want to include a file inside a function and using ob_start(),
ob_get_contents(), etc save the output to a file.
But if there's an error in that included file, I want:
For my function to know that and capture it (so it can handle it gracefully)
To not output the error
Will set_error_handler allow this?
Sunday, 15 September 2013
Reading a file in ARM assembly
Reading a file in ARM assembly
I'm brand new to ARM assembly and I'm trying to open a file, namely
'udp.dat' to read values and add them up.
I've been to
http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001l/QRC0001_UAL.pdf
Yet I still cannot locate the proper command to read values from a file.
Any help would be appreciated.
I'm brand new to ARM assembly and I'm trying to open a file, namely
'udp.dat' to read values and add them up.
I've been to
http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001l/QRC0001_UAL.pdf
Yet I still cannot locate the proper command to read values from a file.
Any help would be appreciated.
Largest item in an array
Largest item in an array
I have the following code from another answer here on Stackoverflow:
var myarray = ['a','abcde','ab'];
var maxlen = 0;
for (i=0; i<myarray.length; i++) {
if (myarray[i].length>maxlen) {
maxlen = myarray[i].length;
}
}
I understand everything about this, apart from why creating a maxlen = 0
and then using the if operator selects the largest length.
Surely because ab is also larger than 0, that could also become the
variable maxlen? Why was abcde chosen instead?
I have the following code from another answer here on Stackoverflow:
var myarray = ['a','abcde','ab'];
var maxlen = 0;
for (i=0; i<myarray.length; i++) {
if (myarray[i].length>maxlen) {
maxlen = myarray[i].length;
}
}
I understand everything about this, apart from why creating a maxlen = 0
and then using the if operator selects the largest length.
Surely because ab is also larger than 0, that could also become the
variable maxlen? Why was abcde chosen instead?
Mixed data types in one column (int and decimal): separate or get together?
Mixed data types in one column (int and decimal): separate or get together?
In my Rails app (with PostgreSQL) I'm importing some metrics from Google
Analytics:
Visitors - int
Goal 1 Completions - int
Goal 2 Completions - int
Goal N Completions - int
Transactions Amount - int
Transactions Revenue - decimal
Here's the table with data, if all of them were int:
id - int
date - date
metric_id - int
metric_amount - int
But Transactions Revenue is decimal, so I have 2 options.
Option 1. Make all of them decimal
id - int
date - date
metric_id - int
metric_amount - decimal
Option 2. Create additional nullable column for Revenue
id - int
date - date
metric_id - int
metric_amount - int
metric_revenue - decimal
Which one is better?
In my Rails app (with PostgreSQL) I'm importing some metrics from Google
Analytics:
Visitors - int
Goal 1 Completions - int
Goal 2 Completions - int
Goal N Completions - int
Transactions Amount - int
Transactions Revenue - decimal
Here's the table with data, if all of them were int:
id - int
date - date
metric_id - int
metric_amount - int
But Transactions Revenue is decimal, so I have 2 options.
Option 1. Make all of them decimal
id - int
date - date
metric_id - int
metric_amount - decimal
Option 2. Create additional nullable column for Revenue
id - int
date - date
metric_id - int
metric_amount - int
metric_revenue - decimal
Which one is better?
Sorting a list of tuples on multiple keys
Sorting a list of tuples on multiple keys
I want to sort a list of tuples where the tuples are of type (a, b) where
a and b are integers. The key for sorting the list should be the
difference between a and b i.e a - b and to break the ties, it should sort
on a, both in descending order.
I tried using this:
def sort(list):
scores = sorted(list, key=lambda list: list[0], reverse=True)
scores = sorted(list, key=lambda list: (a - b), reverse=True)
But this seems to sort on the difference and reorder the elements sorted
on the first element of the tuple.
For example:
The input:
[(75, 10), (88, 4), (93, 9), (80, 5), (94, 10)]
The expected output:
[(94, 10), (93, 9), (88, 4), (80, 5), (75, 10)]
The obtained output:
[(93, 9), (88, 4), (94, 10), (80, 5), (75, 10)]
I want to sort a list of tuples where the tuples are of type (a, b) where
a and b are integers. The key for sorting the list should be the
difference between a and b i.e a - b and to break the ties, it should sort
on a, both in descending order.
I tried using this:
def sort(list):
scores = sorted(list, key=lambda list: list[0], reverse=True)
scores = sorted(list, key=lambda list: (a - b), reverse=True)
But this seems to sort on the difference and reorder the elements sorted
on the first element of the tuple.
For example:
The input:
[(75, 10), (88, 4), (93, 9), (80, 5), (94, 10)]
The expected output:
[(94, 10), (93, 9), (88, 4), (80, 5), (75, 10)]
The obtained output:
[(93, 9), (88, 4), (94, 10), (80, 5), (75, 10)]
facebook : Get public status in php
facebook : Get public status in php
I want to fetch some random public status from the facebook. For this type
of stuff Twitter provides the Streaming API. Is facebook platform provide
such king of API or any method. Thanks for ur time and interest.
I want to fetch some random public status from the facebook. For this type
of stuff Twitter provides the Streaming API. Is facebook platform provide
such king of API or any method. Thanks for ur time and interest.
Looking for NFC emulator on Android
Looking for NFC emulator on Android
I'm looking for a NFC emulator on Android, I always lose my card and can't
get into my University campus. It would be easier if i could just emulate
my card with my phone. I understand the danger of an app like it but I'm
sure it exists.
I'm looking for a NFC emulator on Android, I always lose my card and can't
get into my University campus. It would be easier if i could just emulate
my card with my phone. I understand the danger of an app like it but I'm
sure it exists.
AS3 InputTextField Component size change
AS3 InputTextField Component size change
I want to use text input component and I drag it on the stage, I give it a
instance name. Now from code I'm trying to change the size of it by
instance name , because I expand a little bit and the text size remain
like it was. Here is my code:
userLog.size = 30;
I receive this error: 1119:Access of possibly undefined property size
through a reference with static type fl.controls:TextInput. Thank you!
I want to use text input component and I drag it on the stage, I give it a
instance name. Now from code I'm trying to change the size of it by
instance name , because I expand a little bit and the text size remain
like it was. Here is my code:
userLog.size = 30;
I receive this error: 1119:Access of possibly undefined property size
through a reference with static type fl.controls:TextInput. Thank you!
Saturday, 14 September 2013
Embedded hulu video after not available
Embedded hulu video after not available
If I embed a hulu episode on my site, what happens after the video is not
longer available on hulu? Will it stop working on my site as well?
If I embed a hulu episode on my site, what happens after the video is not
longer available on hulu? Will it stop working on my site as well?
What could cause fwrite() function so slow
What could cause fwrite() function so slow
I'm writing chucks of chat *ptr into file, but it takes me so long to
finish. I don't know why.
for(int i = 1; i < 64048; i++){
if(ptr[i] != NULL){
fwrite(ptr[i], 1, strlen(ptr[i])-6, file);
free(ptr[i]);
}
}
there is array of char pointers storing 8186 bytes, and I want to write
into file, but the time is so long.
I have 64048 chunks of string need to write into file.
What could cause the slowing fwrite() ??
thank you
I'm writing chucks of chat *ptr into file, but it takes me so long to
finish. I don't know why.
for(int i = 1; i < 64048; i++){
if(ptr[i] != NULL){
fwrite(ptr[i], 1, strlen(ptr[i])-6, file);
free(ptr[i]);
}
}
there is array of char pointers storing 8186 bytes, and I want to write
into file, but the time is so long.
I have 64048 chunks of string need to write into file.
What could cause the slowing fwrite() ??
thank you
Pattern to synchronize access to chrome.storage across multiple background and content scripts
Pattern to synchronize access to chrome.storage across multiple background
and content scripts
I am writing a chrome extension with multiple background scripts and
content scripts.
They all share data across chrome.storage, using structures like:
chrome.storage.sync.get("objectname", function(result){
result.object.manipulateObject();
chrome.storage.sync.set({"pendingOrders" : result.pendingOrders});
});
Now this is a textbook case for concurrency problems. Consider the
following scenario:
background.js gets object from storage
background.js manipulates object
content.js gets the same object from storage
background.js writes manipulated object back to storage
content.js manipulates object and writes it back to storage
As a result, the work of background.js is lost.
What is the best pattern to avoid this?
and content scripts
I am writing a chrome extension with multiple background scripts and
content scripts.
They all share data across chrome.storage, using structures like:
chrome.storage.sync.get("objectname", function(result){
result.object.manipulateObject();
chrome.storage.sync.set({"pendingOrders" : result.pendingOrders});
});
Now this is a textbook case for concurrency problems. Consider the
following scenario:
background.js gets object from storage
background.js manipulates object
content.js gets the same object from storage
background.js writes manipulated object back to storage
content.js manipulates object and writes it back to storage
As a result, the work of background.js is lost.
What is the best pattern to avoid this?
Footer up/down on click
Footer up/down on click
I have a problem regarding my footer position on a click event. I'm
working with bootstrap css and I have a collapsible element (accordion in
bootstrap) that when collapse it has a class named
.accordion-toggle.collapsed and when not his class is .accordion-toggle.
Well, I'm trying to slidedown the footer when this element is collapsed
(because it's overwriting the footer) and my code is:
<script>
$(function() {
var collapsed = $('.accordion-toggle.collapsed');
$('#links').click(function(){
if (collapsed)
{
$(".footer").css({'margin-top':'320px'});
}else{
$(".footer").css({'margin-top':'150px'});
}
});
});
</script>
Well the problem is that when I click on the collapsible element the
footer slidedown, but when I click again (and his class change to
(accordion-toggle) it doesn't return to his original position that is:
150px margin top.
Thanks for the help!!!
I have a problem regarding my footer position on a click event. I'm
working with bootstrap css and I have a collapsible element (accordion in
bootstrap) that when collapse it has a class named
.accordion-toggle.collapsed and when not his class is .accordion-toggle.
Well, I'm trying to slidedown the footer when this element is collapsed
(because it's overwriting the footer) and my code is:
<script>
$(function() {
var collapsed = $('.accordion-toggle.collapsed');
$('#links').click(function(){
if (collapsed)
{
$(".footer").css({'margin-top':'320px'});
}else{
$(".footer").css({'margin-top':'150px'});
}
});
});
</script>
Well the problem is that when I click on the collapsible element the
footer slidedown, but when I click again (and his class change to
(accordion-toggle) it doesn't return to his original position that is:
150px margin top.
Thanks for the help!!!
Is it acceptable to open and then close the session for an external module?
Is it acceptable to open and then close the session for an external module?
I'm writing a small reusable user manager for my projects that will use
services as facebook, persona.org for login. From the point of view of
each web, it's an include and a couple of echoes. However, it uses
$_SESSION, so I need it initialized. For that I use this code in
'include.php':
<?php
if(session_id() == '') {
if (headers_sent()) {
throw new Exception ("You must include this file before sending any
header.");
}
session_start();
$NoSession = 1; // Leave everything as it was before
}
// MAIN CODE HERE
if ($NoSession) {
session_destroy();
}
Is it a good idea to destroy the session with session_destroy() or is it
acceptable to leave the session opened?
I'm writing a small reusable user manager for my projects that will use
services as facebook, persona.org for login. From the point of view of
each web, it's an include and a couple of echoes. However, it uses
$_SESSION, so I need it initialized. For that I use this code in
'include.php':
<?php
if(session_id() == '') {
if (headers_sent()) {
throw new Exception ("You must include this file before sending any
header.");
}
session_start();
$NoSession = 1; // Leave everything as it was before
}
// MAIN CODE HERE
if ($NoSession) {
session_destroy();
}
Is it a good idea to destroy the session with session_destroy() or is it
acceptable to leave the session opened?
.sh file processing gave an error message
.sh file processing gave an error message
I regularly use a .sh file for processing some files. It failed to open a
file for processing yesterday and gave an error message mentioning the
same. The process is being executed using git bash. What could be the
possible causes and how can I debug this ?
I regularly use a .sh file for processing some files. It failed to open a
file for processing yesterday and gave an error message mentioning the
same. The process is being executed using git bash. What could be the
possible causes and how can I debug this ?
Codeigniter .htaccess: Give public access to all files but not the folder
Codeigniter .htaccess: Give public access to all files but not the folder
my file format like
application
- controllers
- views etc...
assetes
- Images
- Css etc...
and my .htaccess file are below:
#Deny from all
RewriteEngine on
RewriteCond $1 !^(index\.php|assets|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]
My probleb is that assets folder access to every one any user veiw all
images and all css file but needed is only user access file not the access
entire folder
please help me thanks!
my file format like
application
- controllers
- views etc...
assetes
- Images
- Css etc...
and my .htaccess file are below:
#Deny from all
RewriteEngine on
RewriteCond $1 !^(index\.php|assets|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]
My probleb is that assets folder access to every one any user veiw all
images and all css file but needed is only user access file not the access
entire folder
please help me thanks!
Friday, 13 September 2013
chromedriver doesn't run in debian wheezy
chromedriver doesn't run in debian wheezy
This question is very similar to Error running chromedriver, except that
question is about older debian versions.
Here is the info about my system:
$ uname -a
Linux host 3.2.0-4-686-pae #1 SMP Debian 3.2.46-1+deb7u1 i686 GNU/Linux
$ lsb_release -d
Description: Debian GNU/Linux 7.1 (wheezy)
$ chromedriver
chromedriver: /lib/i386-linux-gnu/libc.so.6: version `GLIBC_2.15' not
found (required by chromedriver)
I am sure I got the right 32bit chromedriver binary from
http://code.google.com/p/chromedriver/downloads/list, I am also sure it's
in PATH, as the command above shows.
How do I get chromedriver to work properly? Is there a working Debian
package of chromedriver like there's one for chromium browser in the
Debian repository?
This question is very similar to Error running chromedriver, except that
question is about older debian versions.
Here is the info about my system:
$ uname -a
Linux host 3.2.0-4-686-pae #1 SMP Debian 3.2.46-1+deb7u1 i686 GNU/Linux
$ lsb_release -d
Description: Debian GNU/Linux 7.1 (wheezy)
$ chromedriver
chromedriver: /lib/i386-linux-gnu/libc.so.6: version `GLIBC_2.15' not
found (required by chromedriver)
I am sure I got the right 32bit chromedriver binary from
http://code.google.com/p/chromedriver/downloads/list, I am also sure it's
in PATH, as the command above shows.
How do I get chromedriver to work properly? Is there a working Debian
package of chromedriver like there's one for chromium browser in the
Debian repository?
How to create a skydome with HTML5
How to create a skydome with HTML5
I'd like to create a skydome with html5 so I can look around and display
contents that surrounds me such as pictures and videos. What's the easiest
way to tackle this problem. I can not use 3D engines such as three or
webGL because I need to see the html file in a browser on my iPhone
(preferably sth supported on Safari and Chrome).
Any tips and hints is much appreciated. Cyrus
I'd like to create a skydome with html5 so I can look around and display
contents that surrounds me such as pictures and videos. What's the easiest
way to tackle this problem. I can not use 3D engines such as three or
webGL because I need to see the html file in a browser on my iPhone
(preferably sth supported on Safari and Chrome).
Any tips and hints is much appreciated. Cyrus
How do I set an SNTP server through the Windows API?
How do I set an SNTP server through the Windows API?
I'd like to configure Windows programmatically to use a user-specified
SNTP server. Is there a function in the Windows API for that?
I'd like to configure Windows programmatically to use a user-specified
SNTP server. Is there a function in the Windows API for that?
boost-python: How do I provide a custom constructor wrapper function?
boost-python: How do I provide a custom constructor wrapper function?
I'm using boost-python to create python bindings for a C++ class named
CppClass. When necessary, I can route calls to "normal" member functions
through little wrapper functions that preprocess the arguments (e.g.
extract C++ types from the python args), like so:
class CppClass
{
CppClass(SpecialParameters p);
void doSomething(int x, float y);
};
using namespace boost::python; // For extract, tuple, init, class_, etc.
class WrapperFuncs
{
static void doSomething(CppClass & c, tuple t)
{
int x = extract<int>(t.attr("__getitem__")(0));
float y = extract<float>(t.attr("__getitem__")(1));
c.doSomething(x,y);
}
};
class_<CppClass, boost::shared_ptr<CppClass> >
("CppClass", init<SpecialParameters>())
.def("doSomething", &WrapperFuncs::doSomething, (arg("t")))
But how do I do the same for the CppClass constructor?
I'm using boost-python to create python bindings for a C++ class named
CppClass. When necessary, I can route calls to "normal" member functions
through little wrapper functions that preprocess the arguments (e.g.
extract C++ types from the python args), like so:
class CppClass
{
CppClass(SpecialParameters p);
void doSomething(int x, float y);
};
using namespace boost::python; // For extract, tuple, init, class_, etc.
class WrapperFuncs
{
static void doSomething(CppClass & c, tuple t)
{
int x = extract<int>(t.attr("__getitem__")(0));
float y = extract<float>(t.attr("__getitem__")(1));
c.doSomething(x,y);
}
};
class_<CppClass, boost::shared_ptr<CppClass> >
("CppClass", init<SpecialParameters>())
.def("doSomething", &WrapperFuncs::doSomething, (arg("t")))
But how do I do the same for the CppClass constructor?
In C# / .NET, how to parse a decimal out of a currency amount stored in a string, and NOT lose precision or do rounding?
In C# / .NET, how to parse a decimal out of a currency amount stored in a
string, and NOT lose precision or do rounding?
I have code like
private static decimal ParseAmountFrom(string amount)
{
decimal amount;
if (!Decimal.TryParse(amount, NumberStyles.Currency,
CultureInfo.InvariantCulture, out amount))
{
throw new AmountNotADecimalException(unParsed.Amount);
}
return amount;
}
If I call ParseAmountFrom("234.256") I get back a value 234.25m. I've lost
the 0.006.
How can I parse the strings so no precision is lost, and no rounding occurs?
string, and NOT lose precision or do rounding?
I have code like
private static decimal ParseAmountFrom(string amount)
{
decimal amount;
if (!Decimal.TryParse(amount, NumberStyles.Currency,
CultureInfo.InvariantCulture, out amount))
{
throw new AmountNotADecimalException(unParsed.Amount);
}
return amount;
}
If I call ParseAmountFrom("234.256") I get back a value 234.25m. I've lost
the 0.006.
How can I parse the strings so no precision is lost, and no rounding occurs?
How to update/add name and score in database
How to update/add name and score in database
I m making a Quiz based app in Android. And I want to make Submit score
button at the last of the game if user want to do so. If user click on
that button it will ask to Enter the name and then the name with the score
will be saved in the database. So, now my question is how to perform this
task. I have managed a Separate Database class for all database Queries.
So, please tell me according to this situation..
Here is my Database Class which I have created till now..
public class DBAdapter
{
public static final String KEY_id = "id";
public static final String KEY_ques = "ques";
public static final String KEY_correctans = "correctans";
public static final String KEY_wrongans1 = "wrongans1";
public static final String KEY_wrongans2 = "wrongans2";
public static final String KEY_wrongans3 = "wrongans3";
public static final String KEY_scoreid = "scoreid";
public static final String KEY_name = "name";
public static final String KEY_score = "score";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "quiz";
private static final String DATABASE_TABLE = "quiz_ques";
private static final String DATABASE_TABLE1 = "scores";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "create table quiz_ques (id
integer primary key autoincrement,"
+ "ques TEXT " + "correctans TEXT " + "wrongans1 TEXT" +
"wrongans2 TEXT" + "wrongans3 TEXT"
+ ");";
private static final String DATABASE_CREATE1 = "create table scores
(scoreid integer primary key autoincrement,"
+ "name TEXT" + "score NUMERIC"
+ ");";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(DATABASE_CREATE);
db.execSQL(DATABASE_CREATE1);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS quiz_ques");
onCreate(db);
}
}
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
// ---closes the database---
public void close()
{
DBHelper.close();
}
public Cursor getText(long rowId) throws SQLException
{
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_id,
KEY_ques,KEY_correctans,KEY_wrongans1,KEY_wrongans2,KEY_wrongans3
}, KEY_id + "="
+ rowId, null,null,null, null,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor addscore(long rowid) throws SQLException
{
**//What to write here..**
}
}
I m making a Quiz based app in Android. And I want to make Submit score
button at the last of the game if user want to do so. If user click on
that button it will ask to Enter the name and then the name with the score
will be saved in the database. So, now my question is how to perform this
task. I have managed a Separate Database class for all database Queries.
So, please tell me according to this situation..
Here is my Database Class which I have created till now..
public class DBAdapter
{
public static final String KEY_id = "id";
public static final String KEY_ques = "ques";
public static final String KEY_correctans = "correctans";
public static final String KEY_wrongans1 = "wrongans1";
public static final String KEY_wrongans2 = "wrongans2";
public static final String KEY_wrongans3 = "wrongans3";
public static final String KEY_scoreid = "scoreid";
public static final String KEY_name = "name";
public static final String KEY_score = "score";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "quiz";
private static final String DATABASE_TABLE = "quiz_ques";
private static final String DATABASE_TABLE1 = "scores";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "create table quiz_ques (id
integer primary key autoincrement,"
+ "ques TEXT " + "correctans TEXT " + "wrongans1 TEXT" +
"wrongans2 TEXT" + "wrongans3 TEXT"
+ ");";
private static final String DATABASE_CREATE1 = "create table scores
(scoreid integer primary key autoincrement,"
+ "name TEXT" + "score NUMERIC"
+ ");";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(DATABASE_CREATE);
db.execSQL(DATABASE_CREATE1);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS quiz_ques");
onCreate(db);
}
}
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
// ---closes the database---
public void close()
{
DBHelper.close();
}
public Cursor getText(long rowId) throws SQLException
{
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_id,
KEY_ques,KEY_correctans,KEY_wrongans1,KEY_wrongans2,KEY_wrongans3
}, KEY_id + "="
+ rowId, null,null,null, null,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor addscore(long rowid) throws SQLException
{
**//What to write here..**
}
}
CakePHP translate behavior : using alias for locale
CakePHP translate behavior : using alias for locale
how can use aliases for locales in i18n cakePHP i used,
Configure::write('Config.languages',array('eng'=>'English','fra'=>'France'))
;
but it will save Englis as locale in i18n table and only 6 chars for
locale. I don't want change the locale with aliases. locale been in
standard (eng) in table but in show time print English as alias. It will
be useful when print language title on calling loops or making badges. i
can override the i18n table and change the max chars of locale field, but
is there any standard or general solution?
how can use aliases for locales in i18n cakePHP i used,
Configure::write('Config.languages',array('eng'=>'English','fra'=>'France'))
;
but it will save Englis as locale in i18n table and only 6 chars for
locale. I don't want change the locale with aliases. locale been in
standard (eng) in table but in show time print English as alias. It will
be useful when print language title on calling loops or making badges. i
can override the i18n table and change the max chars of locale field, but
is there any standard or general solution?
Thursday, 12 September 2013
Post http python
Post http python
The below python script, when run, produces an HTML file. When the user
clicks on "submit your request", the big textarea below it is filled with
parameters that I want to send to another python script. Currently the
only way I can get it to work is to paste the textarea to the textbox at
the bottom, and press Enter.
I would like to kill the bottom texbox, and get the "submit your request"
to send the content of the area box.
Please help, I have spent countless hours today and its driving me crazy.
#!/Python27/python
import cgi, os
import cgitb; cgitb.enable() # for troubleshooting
print "Content-type: text/html"
print
print """
<!DOCTYPE html>
<html>
<head>
<title>Order Form</title>
<font size="11"><b>Order Form</b></font><img border="0" src="cross.bmp"
width="70" height="70" align="right">
<br>
</br>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map_canvas{
height:400px;
width:800px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/JavaScript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/JavaScript">
</script>
<script>
var marker, myCircle, map;
var geocoder;
function initialize() {
var myLatlng = new google.maps.LatLng(43.651975,-79.378967);
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
google.maps.event.addListener(map, 'click', function(event){
var x=document.getElementById("mySelect").selectedIndex;
var y=document.getElementById("mySelect").options;
addMarker(event.latLng,Number(y[x].text));
document.getElementById("lat").value =event.latLng.lat();
document.getElementById("lon").value =event.latLng.lng();
});
}
//////////////////////////////////
function codeAddress() {
var address = document.getElementById('autocomplete').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
//var myLatlng1 = new google.maps.LatLng(43.651975,-79.378967);
addMarker(results[0].geometry.location,250)
} else {
alert('Geocode was not successful for the following reason: ' +
status);
}
});
}
///////////////
function addMarker(latLng,givenRadval){
document.getElementById("lat").value =latLng.lat();
document.getElementById("lon").value =latLng.lng();
//clear the previous marker and circle.
if(marker != null){
marker.setMap(null);
myCircle.setMap(null);
}
marker = new google.maps.Marker({
position: latLng,
map: map,
draggable:true,
icon:"logo.bmp"
});
//circle options.
var circleOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0,
map: map,
center: latLng,
radius: givenRadval
};
//create circle
myCircle = new google.maps.Circle(circleOptions);
//when marker has completed the drag event
//recenter the circle on the marker.
google.maps.event.addListener(marker, 'dragend', function(){
myCircle.setCenter(this.position);
document.getElementById("lat").value =this.position.lat();
document.getElementById("lon").value =this.position.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize)
function Submit_For_Proccessing(){
document.getElementById("Request_Details").value=
"'"+document.getElementById("lat").value
+"' '"+
document.getElementById("lon").value
+"' '"+
document.getElementById("mySelect").value+"'
'"+
document.getElementById("street_number").value+"'
'"+
document.getElementById("street_name").value+"'
'"+
document.getElementById("city").value+"'
'"+
document.getElementById("Postal_Code").value+"'
'"+
document.getElementById("province").value+"'
'"+
document.getElementById("country").value+"'
'"+
document.getElementById("Site_Name").value+"'
'"+
document.getElementById("reference_number").value+"'
'"+
document.getElementById("Your_name").value+"'
'"+
document.getElementById("email_address").value+"'";
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:auto;height:400px;"></div>
<form method="post" action="index.cgi">
<fieldset style="float:left;width :300px;padding : 10px;margin: 1em
0.7em 0.3em;display : inline-block;height: 210px;">
<legend><b>1. Define your Area of Interest:</b></legend>
<table>
<tr><input id="autocomplete" name="auto" size="24"
type="textbox" value="" color="green" ><input type="button"
value="Zoom" onclick="codeAddress()">
<tr><td align="left">Study Radius:</td><td><select width="120"
style="width: 120px" id="mySelect"><option>200</option><option
selected="true">250</option><option>300</option></select>
Meters</td></tr>
<tr><td align="left"><a
href="http://en.wikipedia.org/wiki/Latitude">Latitude</a>:</td><td><input
size="18" type="text" id="lat" value="" disabled></td></tr>
<tr><td align="left"><a
href="http://en.wikipedia.org/wiki/Longitude">Longitude</a>:</td><td><input
size="18" type="text" id="lon" value="" disabled></td></tr>
</table>
</fieldset>
<fieldset style="float:left;width :300px;padding : 10px;margin: 1em
0.7em 0.3em;display : inline-block;height: 210px;">
<legend><b>2. Define Address Details:</b></legend>
<table>
<tr><td align="left">Street Number</a>:</td><td><input
size="18" type="text" id="street_number" value="3504"
></td></tr>
<tr><td align="left">Street Name</a>:</td><td><input size="18"
type="text" id="street_name" value="Hurontario" ></td></tr>
<tr><td align="left">City</a>:</td><td><input size="18"
type="text" id="city" value="Mississuaga" ></td></tr>
<tr><td align="left">Postal Code</a>:</td><td><input size="18"
type="text" id="Postal_Code" value="L5B0B9" ></td></tr>
<tr><td align="left">Province</a>:</td><td><input size="18"
type="text" id="province" value="Ontario" disabled ></td></tr>
<tr><td align="left">Country</a>:</td><td><input size="18"
type="text" id="country" value="Canada" disabled ></td></tr>
</table>
</fieldset>
<fieldset style="float:left;width :300px;padding : 10px;margin: 1em
0.7em 0.3em;display : inline-block;height: 210px;">
<legend><b>3. Define Report details</b></legend>
<table>
<tr><td align="left">Site Name</a>:</td><td><input size="22"
type="text" id="Site_Name" value="Contaminated site 01"
></td></tr>
<tr><td align="left">Reference Number</a>:</td><td><input
size="22" type="text" id="reference_number" value="Order001"
></td></tr>
<tr><td align="left">Your Name</a>:</td><td><input size="22"
type="text" id="Your_name" value="Adel Hallak" ></td></tr>
<tr><td align="left">Email Address</a>:</td><td><input
size="22" type="text" id="email_address"
value="adel.elhallak@gmail.com" ></td></tr>
</table>
</fieldset>
<fieldset style="float:left;width :150px;padding : 10px;margin: 1em
0.7em 0.3em;display : inline-block;height: 210px;">
<legend><b>4. Submit Request</b></legend>
<input align="center" type="button" value=" Submit your
request " id="Send_coordinates" width="148" height="148"
onclick="Submit_For_Proccessing()">
<textarea rows="4" cols="50" style="width:145px;
height:150px;font-size:8pt;" id="Request_Details"
name="Request_Details" value="Initial"></textarea>
</fieldset>
</form>
"""
form = cgi.FieldStorage()
Request_Details = form.getvalue("Request_Details", "(no Request_Details)")
print """
<p>%s</p>
<form method="post" action="Thankyou.py">
<p><input type="text" name="Request_Details"/></p>
</form>
</body>
</html>
""" % cgi.escape(Request_Details)
The below python script, when run, produces an HTML file. When the user
clicks on "submit your request", the big textarea below it is filled with
parameters that I want to send to another python script. Currently the
only way I can get it to work is to paste the textarea to the textbox at
the bottom, and press Enter.
I would like to kill the bottom texbox, and get the "submit your request"
to send the content of the area box.
Please help, I have spent countless hours today and its driving me crazy.
#!/Python27/python
import cgi, os
import cgitb; cgitb.enable() # for troubleshooting
print "Content-type: text/html"
print """
<!DOCTYPE html>
<html>
<head>
<title>Order Form</title>
<font size="11"><b>Order Form</b></font><img border="0" src="cross.bmp"
width="70" height="70" align="right">
<br>
</br>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map_canvas{
height:400px;
width:800px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/JavaScript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/JavaScript">
</script>
<script>
var marker, myCircle, map;
var geocoder;
function initialize() {
var myLatlng = new google.maps.LatLng(43.651975,-79.378967);
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
google.maps.event.addListener(map, 'click', function(event){
var x=document.getElementById("mySelect").selectedIndex;
var y=document.getElementById("mySelect").options;
addMarker(event.latLng,Number(y[x].text));
document.getElementById("lat").value =event.latLng.lat();
document.getElementById("lon").value =event.latLng.lng();
});
}
//////////////////////////////////
function codeAddress() {
var address = document.getElementById('autocomplete').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
//var myLatlng1 = new google.maps.LatLng(43.651975,-79.378967);
addMarker(results[0].geometry.location,250)
} else {
alert('Geocode was not successful for the following reason: ' +
status);
}
});
}
///////////////
function addMarker(latLng,givenRadval){
document.getElementById("lat").value =latLng.lat();
document.getElementById("lon").value =latLng.lng();
//clear the previous marker and circle.
if(marker != null){
marker.setMap(null);
myCircle.setMap(null);
}
marker = new google.maps.Marker({
position: latLng,
map: map,
draggable:true,
icon:"logo.bmp"
});
//circle options.
var circleOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0,
map: map,
center: latLng,
radius: givenRadval
};
//create circle
myCircle = new google.maps.Circle(circleOptions);
//when marker has completed the drag event
//recenter the circle on the marker.
google.maps.event.addListener(marker, 'dragend', function(){
myCircle.setCenter(this.position);
document.getElementById("lat").value =this.position.lat();
document.getElementById("lon").value =this.position.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize)
function Submit_For_Proccessing(){
document.getElementById("Request_Details").value=
"'"+document.getElementById("lat").value
+"' '"+
document.getElementById("lon").value
+"' '"+
document.getElementById("mySelect").value+"'
'"+
document.getElementById("street_number").value+"'
'"+
document.getElementById("street_name").value+"'
'"+
document.getElementById("city").value+"'
'"+
document.getElementById("Postal_Code").value+"'
'"+
document.getElementById("province").value+"'
'"+
document.getElementById("country").value+"'
'"+
document.getElementById("Site_Name").value+"'
'"+
document.getElementById("reference_number").value+"'
'"+
document.getElementById("Your_name").value+"'
'"+
document.getElementById("email_address").value+"'";
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:auto;height:400px;"></div>
<form method="post" action="index.cgi">
<fieldset style="float:left;width :300px;padding : 10px;margin: 1em
0.7em 0.3em;display : inline-block;height: 210px;">
<legend><b>1. Define your Area of Interest:</b></legend>
<table>
<tr><input id="autocomplete" name="auto" size="24"
type="textbox" value="" color="green" ><input type="button"
value="Zoom" onclick="codeAddress()">
<tr><td align="left">Study Radius:</td><td><select width="120"
style="width: 120px" id="mySelect"><option>200</option><option
selected="true">250</option><option>300</option></select>
Meters</td></tr>
<tr><td align="left"><a
href="http://en.wikipedia.org/wiki/Latitude">Latitude</a>:</td><td><input
size="18" type="text" id="lat" value="" disabled></td></tr>
<tr><td align="left"><a
href="http://en.wikipedia.org/wiki/Longitude">Longitude</a>:</td><td><input
size="18" type="text" id="lon" value="" disabled></td></tr>
</table>
</fieldset>
<fieldset style="float:left;width :300px;padding : 10px;margin: 1em
0.7em 0.3em;display : inline-block;height: 210px;">
<legend><b>2. Define Address Details:</b></legend>
<table>
<tr><td align="left">Street Number</a>:</td><td><input
size="18" type="text" id="street_number" value="3504"
></td></tr>
<tr><td align="left">Street Name</a>:</td><td><input size="18"
type="text" id="street_name" value="Hurontario" ></td></tr>
<tr><td align="left">City</a>:</td><td><input size="18"
type="text" id="city" value="Mississuaga" ></td></tr>
<tr><td align="left">Postal Code</a>:</td><td><input size="18"
type="text" id="Postal_Code" value="L5B0B9" ></td></tr>
<tr><td align="left">Province</a>:</td><td><input size="18"
type="text" id="province" value="Ontario" disabled ></td></tr>
<tr><td align="left">Country</a>:</td><td><input size="18"
type="text" id="country" value="Canada" disabled ></td></tr>
</table>
</fieldset>
<fieldset style="float:left;width :300px;padding : 10px;margin: 1em
0.7em 0.3em;display : inline-block;height: 210px;">
<legend><b>3. Define Report details</b></legend>
<table>
<tr><td align="left">Site Name</a>:</td><td><input size="22"
type="text" id="Site_Name" value="Contaminated site 01"
></td></tr>
<tr><td align="left">Reference Number</a>:</td><td><input
size="22" type="text" id="reference_number" value="Order001"
></td></tr>
<tr><td align="left">Your Name</a>:</td><td><input size="22"
type="text" id="Your_name" value="Adel Hallak" ></td></tr>
<tr><td align="left">Email Address</a>:</td><td><input
size="22" type="text" id="email_address"
value="adel.elhallak@gmail.com" ></td></tr>
</table>
</fieldset>
<fieldset style="float:left;width :150px;padding : 10px;margin: 1em
0.7em 0.3em;display : inline-block;height: 210px;">
<legend><b>4. Submit Request</b></legend>
<input align="center" type="button" value=" Submit your
request " id="Send_coordinates" width="148" height="148"
onclick="Submit_For_Proccessing()">
<textarea rows="4" cols="50" style="width:145px;
height:150px;font-size:8pt;" id="Request_Details"
name="Request_Details" value="Initial"></textarea>
</fieldset>
</form>
"""
form = cgi.FieldStorage()
Request_Details = form.getvalue("Request_Details", "(no Request_Details)")
print """
<p>%s</p>
<form method="post" action="Thankyou.py">
<p><input type="text" name="Request_Details"/></p>
</form>
</body>
</html>
""" % cgi.escape(Request_Details)
Get largest width of a textblock in a stackpanel
Get largest width of a textblock in a stackpanel
On a button click, I am reading through a CSV file, replacing ',' with
'\t' and writing it out to a stackpanel.
private void Button_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < r.variables.Count; i++)
{
_people.Add(new TextBlock() { Text = r.variables[i],
HorizontalAlignment = System.Windows.HorizontalAlignment.Right
});//.ToString() });
StackPanel stp = new StackPanel() { Orientation =
Orientation.Vertical };
TextBlock tb = new TextBlock() {Text = r.variables[i]};
stp.Children.Add(tb);
_secondStack.Children.Add(stp);
}
foreach (StackPanel sp in _secondStack.Children)
{
List<double> maxWidth = new List<double>();
foreach (TextBlock tb in sp.Children)
{
Size desiredSize = new Size();
tb.Measure(this.availableSize);
desiredSize = tb.DesiredSize;
}
}
}
From the file, some contain strings that are longer than others, thus the
TextBlocks in the header are wider than those TextBlocks below. How do I
get the width of the widest TextBlock in the embedded StackPanel and set
the width of all TextBlocks inside the embedded StackPanel to that?
On a button click, I am reading through a CSV file, replacing ',' with
'\t' and writing it out to a stackpanel.
private void Button_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < r.variables.Count; i++)
{
_people.Add(new TextBlock() { Text = r.variables[i],
HorizontalAlignment = System.Windows.HorizontalAlignment.Right
});//.ToString() });
StackPanel stp = new StackPanel() { Orientation =
Orientation.Vertical };
TextBlock tb = new TextBlock() {Text = r.variables[i]};
stp.Children.Add(tb);
_secondStack.Children.Add(stp);
}
foreach (StackPanel sp in _secondStack.Children)
{
List<double> maxWidth = new List<double>();
foreach (TextBlock tb in sp.Children)
{
Size desiredSize = new Size();
tb.Measure(this.availableSize);
desiredSize = tb.DesiredSize;
}
}
}
From the file, some contain strings that are longer than others, thus the
TextBlocks in the header are wider than those TextBlocks below. How do I
get the width of the widest TextBlock in the embedded StackPanel and set
the width of all TextBlocks inside the embedded StackPanel to that?
Created a new empty project in XCode and added a View Controller but it wont compile
Created a new empty project in XCode and added a View Controller but it
wont compile
Just like the title says, I created a new empty project in xcode that just
gave me the AppDelegate header and compile files. I then added a view
controller to it and then changed the Main Interface to the name of the
viewcontroller xib file. I went ahead and ran the project without adding
anything else. I've done this before and it has ran, but this time it is
not.
The error message is
'NSUnknownKeyException', reason: 'setValue:forUndefinedKey:]: this class
is not key value coding-compliant for the key view.'
I have didn't write any code or changed anything other than what I
explained above. The only code in the AppDelegate is the following:
.h
#import <UIKit/UIKit.h>
#import "PopOverViewController.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
.m
#import "AppDelegate.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen]
bounds]];
// Override point for customization after application launch.
[self.window makeKeyAndVisible];
return YES;
}
@end
ViewController.h
#import <UIKit/UIKit.h>
@interface PopOverViewController : UIViewController
@end
ViewController.m
#import "PopOverViewController.h"
@interface PopOverViewController ()
@end
@implementation PopOverViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle
*)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
I've searched through this site but couldn't find anything similar. Every
post is about checking the IBOutlets and IBActions and connections but I
havent done anything. All I did was like the View to the FileOwner, that's
it.
wont compile
Just like the title says, I created a new empty project in xcode that just
gave me the AppDelegate header and compile files. I then added a view
controller to it and then changed the Main Interface to the name of the
viewcontroller xib file. I went ahead and ran the project without adding
anything else. I've done this before and it has ran, but this time it is
not.
The error message is
'NSUnknownKeyException', reason: 'setValue:forUndefinedKey:]: this class
is not key value coding-compliant for the key view.'
I have didn't write any code or changed anything other than what I
explained above. The only code in the AppDelegate is the following:
.h
#import <UIKit/UIKit.h>
#import "PopOverViewController.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
.m
#import "AppDelegate.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen]
bounds]];
// Override point for customization after application launch.
[self.window makeKeyAndVisible];
return YES;
}
@end
ViewController.h
#import <UIKit/UIKit.h>
@interface PopOverViewController : UIViewController
@end
ViewController.m
#import "PopOverViewController.h"
@interface PopOverViewController ()
@end
@implementation PopOverViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle
*)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
I've searched through this site but couldn't find anything similar. Every
post is about checking the IBOutlets and IBActions and connections but I
havent done anything. All I did was like the View to the FileOwner, that's
it.
What's the LinqToXML xaml equivalent of .Distinct()?
What's the LinqToXML xaml equivalent of .Distinct()?
Here's the DisplayMemberPath property binding for my ListBox (I'm binding
to an ObservableCollection of XElements):
DisplayMemberPath="Element[Shape].Value"
I've used linq many times for parsing Entity Framework and Sql data, in
which case I would write the analogous binding:
DisplayMemberPath="PropertyName.Distinct()"
I don't want to filter my actual collection to only return Distinct
values--I want my full collection and only display distinct values to
mitigate collection building and PropertyChanged notifications.
Alternative thought: Could I use my ObservablecCollection "getter" to grab
the distinct values of the full list set in the setter? (Not sure if that
makes sense...) so the true collection remains non-distinct and the
displayed collection becomes distinct?
Here's the DisplayMemberPath property binding for my ListBox (I'm binding
to an ObservableCollection of XElements):
DisplayMemberPath="Element[Shape].Value"
I've used linq many times for parsing Entity Framework and Sql data, in
which case I would write the analogous binding:
DisplayMemberPath="PropertyName.Distinct()"
I don't want to filter my actual collection to only return Distinct
values--I want my full collection and only display distinct values to
mitigate collection building and PropertyChanged notifications.
Alternative thought: Could I use my ObservablecCollection "getter" to grab
the distinct values of the full list set in the setter? (Not sure if that
makes sense...) so the true collection remains non-distinct and the
displayed collection becomes distinct?
Rollover image has unwanted grey bar under it
Rollover image has unwanted grey bar under it
My rollover image is 350 by 250 transparent .png with a circular image
inside. The rollover image seems to have an unwanted grey bar appear at
the bottom...
I used basic rollover code I applied using Dreamweaver, by clicking
"Insert" - "Image Objects" - "Rollover Image"
My rollover image is 350 by 250 transparent .png with a circular image
inside. The rollover image seems to have an unwanted grey bar appear at
the bottom...
I used basic rollover code I applied using Dreamweaver, by clicking
"Insert" - "Image Objects" - "Rollover Image"
How to drag and drop form element contents
How to drag and drop form element contents
I have a table with form elements (inputs, selects etc.) I want to copy
the content (or part of content) from one field to another: ex: 'flowers'
from row 4 to row 6. How to preceed to drag the content and NOT the whole
element?
This examplel will drag the entire input element using jQuery ui:
html:
<input type="text" />
jQuery:
$("input").draggable({
cancel: null
});
but I have no clue if there is a possibility to drag/drop the content (or
value)?
I have a table with form elements (inputs, selects etc.) I want to copy
the content (or part of content) from one field to another: ex: 'flowers'
from row 4 to row 6. How to preceed to drag the content and NOT the whole
element?
This examplel will drag the entire input element using jQuery ui:
html:
<input type="text" />
jQuery:
$("input").draggable({
cancel: null
});
but I have no clue if there is a possibility to drag/drop the content (or
value)?
Wednesday, 11 September 2013
phpbb forum setup on nginx
phpbb forum setup on nginx
I am trying to setup phpbb forum on nginx server. The home page opens fine
but whenever i click on any forum, it gives me 404 error. This is what i
tried in my nginx server configuration:
1
2 server{
3 server_name studentshelp.info;
4 return 301 $scheme://www.studentshelp.info$request_uri;
5 }
6
7
8 server {
9
10 server_name www.studentshelp.info;
11 access_log /home/logs/studentshelp.info/access.log;
12 error_log /home/logs/studentshelp.info/error.log;
13 root /home/studentshelp;
14
15 location / {
16 rewrite sitemap.xml /sitemap.php;
17 if (!-e $request_filename){ rewrite ^/(.+)/$ /$1 redirect; }
18 try_files $uri $uri/ /index.php;
19 index index.php;
20 }
21 location ~ \.php$ {
22 include fastcgi_params;
23 fastcgi_pass 127.0.0.1:9000;
24 fastcgi_index index.php;
25 fastcgi_param SCRIPT_FILENAME
/home/studentshelp$fastcgi_script_name;
26 }
27 }
28
The home page of the forum works just fine. The problem occurs whenever a
user clicks on any of the topics/forums. It throws a 404 page. My belief
is that its somewhat due to nginx confguration.
I am trying to setup phpbb forum on nginx server. The home page opens fine
but whenever i click on any forum, it gives me 404 error. This is what i
tried in my nginx server configuration:
1
2 server{
3 server_name studentshelp.info;
4 return 301 $scheme://www.studentshelp.info$request_uri;
5 }
6
7
8 server {
9
10 server_name www.studentshelp.info;
11 access_log /home/logs/studentshelp.info/access.log;
12 error_log /home/logs/studentshelp.info/error.log;
13 root /home/studentshelp;
14
15 location / {
16 rewrite sitemap.xml /sitemap.php;
17 if (!-e $request_filename){ rewrite ^/(.+)/$ /$1 redirect; }
18 try_files $uri $uri/ /index.php;
19 index index.php;
20 }
21 location ~ \.php$ {
22 include fastcgi_params;
23 fastcgi_pass 127.0.0.1:9000;
24 fastcgi_index index.php;
25 fastcgi_param SCRIPT_FILENAME
/home/studentshelp$fastcgi_script_name;
26 }
27 }
28
The home page of the forum works just fine. The problem occurs whenever a
user clicks on any of the topics/forums. It throws a 404 page. My belief
is that its somewhat due to nginx confguration.
KD_XMLRPC.PHP pass by reference depricated
KD_XMLRPC.PHP pass by reference depricated
I am getting the error like "Call-time pass-by-reference has been
deprecated in C:\wamp\www\testing\kd_xmlrpc.php on line 83"
I have also tried to replace the &$this to $this by removing the & but at
that time the xmlrpc file was not working.
So please guide me where i am wrong in these? or do i need to update my
xmlrpc.php file? If yes let me know from where i can get the latest one..
I am getting the error like "Call-time pass-by-reference has been
deprecated in C:\wamp\www\testing\kd_xmlrpc.php on line 83"
I have also tried to replace the &$this to $this by removing the & but at
that time the xmlrpc file was not working.
So please guide me where i am wrong in these? or do i need to update my
xmlrpc.php file? If yes let me know from where i can get the latest one..
sql group by acting like facebook messaging (mssql sp)
sql group by acting like facebook messaging (mssql sp)
im trying to group messages like conversations, user1 is @user (logged in
user) UserName, UserFullName is always non logged in user (who the
conversation is with) Message, Date will be whoever has the last message
example 1:
FromUser | ToUser | Message | Date
User2 | User1 | hi | 01/01/2013 20:00
User1 | User2 | hi back | 01/01/2013 21:00
userfullname and username will be from touser (non logged)
message and date from fromuser (logged in @user, as last message in group)
example 2:
FromUser | ToUser | Message | Date
User1 | User2 | hi | 01/01/2013 20:00
User2 | User1 | hi back | 01/01/2013 21:00
userfullname and username will be from fromuser (non logged in)
message and date from fromuser (logged in @user as its the last message in
group)
This will show just like facebook conversations, if any of you have used
their messaging system. thanks all! :) fries my brain just thinking about
sql
SELECT
CM.FromUser, CM.ToUser, CM.Message, CM.Date,
U.UserId, U.UserFullName, U.UserName, U.UserPhoto
FROM
ConversationMessages AS CM
INNER JOIN
Users AS U ON U.UserName = CM.FromUser
WHERE
CM.ToUser = @user
ORDER BY
CM.Date DESC
im trying to group messages like conversations, user1 is @user (logged in
user) UserName, UserFullName is always non logged in user (who the
conversation is with) Message, Date will be whoever has the last message
example 1:
FromUser | ToUser | Message | Date
User2 | User1 | hi | 01/01/2013 20:00
User1 | User2 | hi back | 01/01/2013 21:00
userfullname and username will be from touser (non logged)
message and date from fromuser (logged in @user, as last message in group)
example 2:
FromUser | ToUser | Message | Date
User1 | User2 | hi | 01/01/2013 20:00
User2 | User1 | hi back | 01/01/2013 21:00
userfullname and username will be from fromuser (non logged in)
message and date from fromuser (logged in @user as its the last message in
group)
This will show just like facebook conversations, if any of you have used
their messaging system. thanks all! :) fries my brain just thinking about
sql
SELECT
CM.FromUser, CM.ToUser, CM.Message, CM.Date,
U.UserId, U.UserFullName, U.UserName, U.UserPhoto
FROM
ConversationMessages AS CM
INNER JOIN
Users AS U ON U.UserName = CM.FromUser
WHERE
CM.ToUser = @user
ORDER BY
CM.Date DESC
Concatenate strings if they have an overlapping region
Concatenate strings if they have an overlapping region
I am trying to write a script that will find strings that share an
overlapping region of 5 letters at the beginning or end of each string
(shown in example below).
facgakfjeakfjekfzpgghi
zpgghiaewkfjaekfjkjakjfkj
kjfjjaejfaefkajewf
I am trying to create a new string which concatenates all three, so the
output would be:
facgakfjeakfjekfzpgghiaewkfjaekfjkjakjfkjaejfaefkajewf
Edit:
This is the input:
x = ('facgakfjeakfjekfzpgghi', 'kjfjjaejfaefkajewf',
'zpgghiaewkfjaekfjkjakjfkj')
**the list is not ordered
I am trying to write a script that will find strings that share an
overlapping region of 5 letters at the beginning or end of each string
(shown in example below).
facgakfjeakfjekfzpgghi
zpgghiaewkfjaekfjkjakjfkj
kjfjjaejfaefkajewf
I am trying to create a new string which concatenates all three, so the
output would be:
facgakfjeakfjekfzpgghiaewkfjaekfjkjakjfkjaejfaefkajewf
Edit:
This is the input:
x = ('facgakfjeakfjekfzpgghi', 'kjfjjaejfaefkajewf',
'zpgghiaewkfjaekfjkjakjfkj')
**the list is not ordered
automatically change org.mysql to org.sqlite
automatically change org.mysql to org.sqlite
Connection Class:
public class ConectaSiscart {
static Connection connection = null;
Statement stm = null;
static String serverName = "192.168.0.222"; //caminho do
servidor do BD
static String mydatabase ="risabel"; //nome do seu banco de
dados
static String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
static String username = "siscart"; //nome de um usuário de
seu BD
static String password = "progsis"; //sua senha de acesso
public static Connection getConexao() {
try {
// Carregando o JDBC Driver padrão
Class.forName("com.mysql.jdbc.Driver");
// Configurando a nossa conexão com um banco de dados//
ResultSet results = null;
// connection =
DriverManager.getConnection("jdbc:mysql://192.168.0.222/risabel?user=siscart&password=progsis");
connection = DriverManager.getConnection(url, username,
password);
System.out.println("Connection é " + connection);
return connection;
} catch (ClassNotFoundException e) { //Driver não encontrado
System.out.println("O driver especificado nao foi
encontrado.");
return null;
} catch (SQLException e) {
//Não conseguindo se conectar ao banco
System.out.println("Nao foi possivel conectar ao Banco de
Dados.");
e.printStackTrace();
return null;
}
}
}
Method to do the connection, this method is attached a mouse lostfocus
event, and return the item from database that i want:
private void puxaemailsiscart() {
ConectaSiscart puxaemail = new ConectaSiscart();
Connection conectadomysql = ConectaSiscart.getConexao();
String servico = null;
if(cboxservico.getSelectedItem() == "Registro de
Imóveis") {
servico = "reg_cab";
}
Statement stm = null;
ResultSet results = null;
try {
stm = conectadomysql.createStatement ();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
System.out.println();
results = stm.executeQuery ("SELECT * FROM " +
servico + " WHERE protocolo =" +
tfProtocolo.getText());
if(results.next()) {
tfEmailParte.setText(results.getString("Email").toString());
} else {
System.out.println("Protocolo nao encontrado");
}
results.close();
stm.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println("Closing the connection.");
if (conectadomysql != null) try { conectadomysql.close(); } catch
(SQLException ignore) {}
}
}
});
but for some reason, in second try, it change the org.mysql, to
org.sqlite.JDBC
java.sql.SQLException: invalid database address:
jdbc:mysql://192.168.0.222/risabel at
org.sqlite.JDBC.createConnection(JDBC.java:110) at
org.sqlite.JDBC.connect(JDBC.java:87) at
java.sql.DriverManager.getConnection(Unknown Source) at
java.sql.DriverManager.getConnection(Unknown Source) at
ConectaSiscart.getConexao(ConectaSiscart.java:30) at
telaprincipal$3.puxaemailsiscart(telaprincipal.java:359) at
telaprincipal$3.focusLost(telaprincipal.java:350) at
java.awt.AWTEventMulticaster.focusLost(Unknown Source) at
java.awt.Component.processFocusEvent(Unknown Source) at
java.awt.Component.processEvent(Unknown Source) at
java.awt.Container.processEvent(Unknown Source) at
java.awt.Component.dispatchEventImpl(Unknown Source) at
java.awt.Container.dispatchEventImpl(Unknown Source) at
java.awt.Component.dispatchEvent(Unknown Source) at
java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source) at
java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source) at
java.awt.Component.dispatchEventImpl(Unknown Source) at
java.awt.Container.dispatchEventImpl(Unknown Source) at
java.awt.Component.dispatchEvent(Unknown Source) at
java.awt.EventQueue.dispatchEventImpl(Unknown Source) at
java.awt.EventQueue.access$200(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown
Source) at java.awt.EventQueue$4.run(Unknown Source) at
java.awt.EventQueue$4.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source) at
java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at
java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at
java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at
java.awt.EventDispatchThread.pumpEvents(Unknown Source) at
java.awt.EventDispatchThread.pumpEvents(Unknown Source) at
java.awt.EventDispatchThread.run(Unknown Source) Exception in thread
"AWT-EventQueue-0" java.lang.NullPointerException at
telaprincipal$3.puxaemailsiscart(telaprincipal.java:367) at
telaprincipal$3.focusLost(telaprincipal.java:350) at
java.awt.AWTEventMulticaster.focusLost(Unknown Source) at
java.awt.Component.processFocusEvent(Unknown Source) at
java.awt.Component.processEvent(Unknown Source) at
java.awt.Container.processEvent(Unknown Source) at
java.awt.Component.dispatchEventImpl(Unknown Source) at
java.awt.Container.dispatchEventImpl(Unknown Source) at
java.awt.Component.dispatchEvent(Unknown Source) at
java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source) at
java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source) at
java.awt.Component.dispatchEventImpl(Unknown Source) at
java.awt.Container.dispatchEventImpl(Unknown Source) at
java.awt.Component.dispatchEvent(Unknown Source) at
java.awt.EventQueue.dispatchEventImpl(Unknown Source) at
java.awt.EventQueue.access$200(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown
Source) at java.awt.EventQueue$4.run(Unknown Source) at
java.awt.EventQueue$4.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source) at
java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at
java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at
java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at
java.awt.EventDispatchThread.pumpEvents(Unknown Source) at
java.awt.EventDispatchThread.pumpEvents(Unknown Source) at
java.awt.EventDispatchThread.run(Unknown Source)
whyyyy i cant understand, i have another class in another .java file to do
a connection with a sql lite database, but in this moment its not called
in any moment, why the eclipse do this mistake?!?!! from where he thinks
"First i worked fine with the org.mysql, now in the second i will try with
the org.sqlite"
:|
Connection Class:
public class ConectaSiscart {
static Connection connection = null;
Statement stm = null;
static String serverName = "192.168.0.222"; //caminho do
servidor do BD
static String mydatabase ="risabel"; //nome do seu banco de
dados
static String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
static String username = "siscart"; //nome de um usuário de
seu BD
static String password = "progsis"; //sua senha de acesso
public static Connection getConexao() {
try {
// Carregando o JDBC Driver padrão
Class.forName("com.mysql.jdbc.Driver");
// Configurando a nossa conexão com um banco de dados//
ResultSet results = null;
// connection =
DriverManager.getConnection("jdbc:mysql://192.168.0.222/risabel?user=siscart&password=progsis");
connection = DriverManager.getConnection(url, username,
password);
System.out.println("Connection é " + connection);
return connection;
} catch (ClassNotFoundException e) { //Driver não encontrado
System.out.println("O driver especificado nao foi
encontrado.");
return null;
} catch (SQLException e) {
//Não conseguindo se conectar ao banco
System.out.println("Nao foi possivel conectar ao Banco de
Dados.");
e.printStackTrace();
return null;
}
}
}
Method to do the connection, this method is attached a mouse lostfocus
event, and return the item from database that i want:
private void puxaemailsiscart() {
ConectaSiscart puxaemail = new ConectaSiscart();
Connection conectadomysql = ConectaSiscart.getConexao();
String servico = null;
if(cboxservico.getSelectedItem() == "Registro de
Imóveis") {
servico = "reg_cab";
}
Statement stm = null;
ResultSet results = null;
try {
stm = conectadomysql.createStatement ();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
System.out.println();
results = stm.executeQuery ("SELECT * FROM " +
servico + " WHERE protocolo =" +
tfProtocolo.getText());
if(results.next()) {
tfEmailParte.setText(results.getString("Email").toString());
} else {
System.out.println("Protocolo nao encontrado");
}
results.close();
stm.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println("Closing the connection.");
if (conectadomysql != null) try { conectadomysql.close(); } catch
(SQLException ignore) {}
}
}
});
but for some reason, in second try, it change the org.mysql, to
org.sqlite.JDBC
java.sql.SQLException: invalid database address:
jdbc:mysql://192.168.0.222/risabel at
org.sqlite.JDBC.createConnection(JDBC.java:110) at
org.sqlite.JDBC.connect(JDBC.java:87) at
java.sql.DriverManager.getConnection(Unknown Source) at
java.sql.DriverManager.getConnection(Unknown Source) at
ConectaSiscart.getConexao(ConectaSiscart.java:30) at
telaprincipal$3.puxaemailsiscart(telaprincipal.java:359) at
telaprincipal$3.focusLost(telaprincipal.java:350) at
java.awt.AWTEventMulticaster.focusLost(Unknown Source) at
java.awt.Component.processFocusEvent(Unknown Source) at
java.awt.Component.processEvent(Unknown Source) at
java.awt.Container.processEvent(Unknown Source) at
java.awt.Component.dispatchEventImpl(Unknown Source) at
java.awt.Container.dispatchEventImpl(Unknown Source) at
java.awt.Component.dispatchEvent(Unknown Source) at
java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source) at
java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source) at
java.awt.Component.dispatchEventImpl(Unknown Source) at
java.awt.Container.dispatchEventImpl(Unknown Source) at
java.awt.Component.dispatchEvent(Unknown Source) at
java.awt.EventQueue.dispatchEventImpl(Unknown Source) at
java.awt.EventQueue.access$200(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown
Source) at java.awt.EventQueue$4.run(Unknown Source) at
java.awt.EventQueue$4.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source) at
java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at
java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at
java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at
java.awt.EventDispatchThread.pumpEvents(Unknown Source) at
java.awt.EventDispatchThread.pumpEvents(Unknown Source) at
java.awt.EventDispatchThread.run(Unknown Source) Exception in thread
"AWT-EventQueue-0" java.lang.NullPointerException at
telaprincipal$3.puxaemailsiscart(telaprincipal.java:367) at
telaprincipal$3.focusLost(telaprincipal.java:350) at
java.awt.AWTEventMulticaster.focusLost(Unknown Source) at
java.awt.Component.processFocusEvent(Unknown Source) at
java.awt.Component.processEvent(Unknown Source) at
java.awt.Container.processEvent(Unknown Source) at
java.awt.Component.dispatchEventImpl(Unknown Source) at
java.awt.Container.dispatchEventImpl(Unknown Source) at
java.awt.Component.dispatchEvent(Unknown Source) at
java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source) at
java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source) at
java.awt.Component.dispatchEventImpl(Unknown Source) at
java.awt.Container.dispatchEventImpl(Unknown Source) at
java.awt.Component.dispatchEvent(Unknown Source) at
java.awt.EventQueue.dispatchEventImpl(Unknown Source) at
java.awt.EventQueue.access$200(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown
Source) at java.awt.EventQueue$4.run(Unknown Source) at
java.awt.EventQueue$4.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source) at
java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at
java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at
java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at
java.awt.EventDispatchThread.pumpEvents(Unknown Source) at
java.awt.EventDispatchThread.pumpEvents(Unknown Source) at
java.awt.EventDispatchThread.run(Unknown Source)
whyyyy i cant understand, i have another class in another .java file to do
a connection with a sql lite database, but in this moment its not called
in any moment, why the eclipse do this mistake?!?!! from where he thinks
"First i worked fine with the org.mysql, now in the second i will try with
the org.sqlite"
:|
regex - match brackets but exclude them from results
regex - match brackets but exclude them from results
I have this example string
[can be anything here %+^-_][can be anything here %+^-_][can be anything
here %+^-_][can be anything here %+^-_][can be anything here %+^-_][can be
anything here %+^-_][can be anything here %+^-_][can be anything here
%+^-_]
My pattern is (\[[^\]]+\])
An I get this as a result
(
[0] => Array
(
[0] => [can be anything here %+^-_]
[1] => [can be anything here %+^-_]
[2] => [can be anything here %+^-_]
[3] => [can be anything here %+^-_]
[4] => [can be anything here %+^-_]
[5] => [can be anything here %+^-_]
[6] => [can be anything here %+^-_]
[7] => [can be anything here %+^-_]
)
[1] => Array
(
[0] => [can be anything here %+^-_]
[1] => [can be anything here %+^-_]
[2] => [can be anything here %+^-_]
[3] => [can be anything here %+^-_]
[4] => [can be anything here %+^-_]
[5] => [can be anything here %+^-_]
[6] => [can be anything here %+^-_]
[7] => [can be anything here %+^-_]
)
)
Problem 1
Why result has two array? Anyway it's not a big deal but I wonder.
Problem 2
How can I get rid of brackets at the beginning and at the end of each
array value, using only regex. Like this.
[0] => Array
(
[0] => can be anything here %+^-_
[1] => can be anything here %+^-_
[2] => can be anything here %+^-_
[3] => can be anything here %+^-_
[4] => can be anything here %+^-_
[5] => can be anything here %+^-_
[6] => can be anything here %+^-_
[7] => can be anything here %+^-_
)
I have this example string
[can be anything here %+^-_][can be anything here %+^-_][can be anything
here %+^-_][can be anything here %+^-_][can be anything here %+^-_][can be
anything here %+^-_][can be anything here %+^-_][can be anything here
%+^-_]
My pattern is (\[[^\]]+\])
An I get this as a result
(
[0] => Array
(
[0] => [can be anything here %+^-_]
[1] => [can be anything here %+^-_]
[2] => [can be anything here %+^-_]
[3] => [can be anything here %+^-_]
[4] => [can be anything here %+^-_]
[5] => [can be anything here %+^-_]
[6] => [can be anything here %+^-_]
[7] => [can be anything here %+^-_]
)
[1] => Array
(
[0] => [can be anything here %+^-_]
[1] => [can be anything here %+^-_]
[2] => [can be anything here %+^-_]
[3] => [can be anything here %+^-_]
[4] => [can be anything here %+^-_]
[5] => [can be anything here %+^-_]
[6] => [can be anything here %+^-_]
[7] => [can be anything here %+^-_]
)
)
Problem 1
Why result has two array? Anyway it's not a big deal but I wonder.
Problem 2
How can I get rid of brackets at the beginning and at the end of each
array value, using only regex. Like this.
[0] => Array
(
[0] => can be anything here %+^-_
[1] => can be anything here %+^-_
[2] => can be anything here %+^-_
[3] => can be anything here %+^-_
[4] => can be anything here %+^-_
[5] => can be anything here %+^-_
[6] => can be anything here %+^-_
[7] => can be anything here %+^-_
)
close an activity after some time
close an activity after some time
I'm trying to make a dice rolling app and I want to run an activity which
displays an image of the result when a button is pressed and close it
after a few seconds. So how can I do this?
Maybe there's another way to display an image on top of my activity
without calling a new activity? I'm not sure.
I've read some things about timers but I don't really get it. And I know
people will tell me to let the user tap to dismiss the window but for this
app I'm sure I want it gone automatically.
I'm trying to make a dice rolling app and I want to run an activity which
displays an image of the result when a button is pressed and close it
after a few seconds. So how can I do this?
Maybe there's another way to display an image on top of my activity
without calling a new activity? I'm not sure.
I've read some things about timers but I don't really get it. And I know
people will tell me to let the user tap to dismiss the window but for this
app I'm sure I want it gone automatically.
Updating a user that doesn't exist on database
Updating a user that doesn't exist on database
I'm developing a WCF REST service that uses Entity Framework CodeFirst.
I have this method to insert or update a user:
private User InsertOrUpdateUser(User user)
{
OutgoingWebResponseContext ctx =
WebOperationContext.Current.OutgoingResponse;
// Check if user parameter is null
ParameterCheck.CheckUser(user);
// If user.UserId is not set (its value is less than 1), we are
// creating a new user.
bool isPost = (user.UserId == 0);
// Check if user has all its required fields, filled
if (isPost)
ParameterCheck.CheckUserData(user);
try
{
using (var context = new AdnLineContext())
{
context.Entry(user).State = user.UserId == 0 ?
EntityState.Added :
EntityState.Modified;
context.SaveChanges();
// If is POST, we are creating a new resource
if (isPost)
ctx.SetStatusAsCreated(CreateUserUri(user));
else
ctx.StatusCode = System.Net.HttpStatusCode.OK;
}
}
catch (Exception ex)
{
ctx.StatusCode = System.Net.HttpStatusCode.InternalServerError;
ctx.SuppressEntityBody = true;
}
return user;
}
But I get an error when I'm trying to update a user that it isn't on
database.
I think I can check first if that user exists with this code:
var users = from u in context.Users
where u.UserId == userId
select u;
if ((users != null) &&
(users.Count() == 1))
{
user = users.First();
But, do you know another fastest method to check if that user exists?
Maybe I can use context.Entry but I'm very new on Entity Framework.
I'm developing a WCF REST service that uses Entity Framework CodeFirst.
I have this method to insert or update a user:
private User InsertOrUpdateUser(User user)
{
OutgoingWebResponseContext ctx =
WebOperationContext.Current.OutgoingResponse;
// Check if user parameter is null
ParameterCheck.CheckUser(user);
// If user.UserId is not set (its value is less than 1), we are
// creating a new user.
bool isPost = (user.UserId == 0);
// Check if user has all its required fields, filled
if (isPost)
ParameterCheck.CheckUserData(user);
try
{
using (var context = new AdnLineContext())
{
context.Entry(user).State = user.UserId == 0 ?
EntityState.Added :
EntityState.Modified;
context.SaveChanges();
// If is POST, we are creating a new resource
if (isPost)
ctx.SetStatusAsCreated(CreateUserUri(user));
else
ctx.StatusCode = System.Net.HttpStatusCode.OK;
}
}
catch (Exception ex)
{
ctx.StatusCode = System.Net.HttpStatusCode.InternalServerError;
ctx.SuppressEntityBody = true;
}
return user;
}
But I get an error when I'm trying to update a user that it isn't on
database.
I think I can check first if that user exists with this code:
var users = from u in context.Users
where u.UserId == userId
select u;
if ((users != null) &&
(users.Count() == 1))
{
user = users.First();
But, do you know another fastest method to check if that user exists?
Maybe I can use context.Entry but I'm very new on Entity Framework.
Tuesday, 10 September 2013
MySQL C# Query trouble - Updating table
MySQL C# Query trouble - Updating table
I'am having trouble with this function I'm creating to Update my database.
The Update faculty member seems to work perfectly while the Updating of
the person tables does not . I'm presuming that the MySQL Query isn't
correct for updating the person table.
Additional INFO: My code is hooked to an GUI mock as of right now for
testing purposes . the Update string with @Id.. its just to select which
ID I wish to change..
public static void Update(string update,string fName, string lName, string
DOB, string postCode, string address, string phoneNumber,
bool isTenured, string
qualifications, string
previousEmployment)
{
MySqlConnection conn;
MySqlCommand cmd;
string sql = "UPDATE person SET firstName = @FirstName ,
lastName = @LastName, DOB = @DOB, phoneNumber =
@PhoneNumber, address = @Address, postCode = @PostCode
WHERE ID =@Id;";
GetConnection(out conn, out cmd, sql);
try
{
cmd.Parameters.AddWithValue("@Id", update);
cmd.Parameters.AddWithValue("@FirstName", fName);
cmd.Parameters.AddWithValue("@LastName", lName);
cmd.Parameters.AddWithValue("@DOB", DOB);
cmd.Parameters.AddWithValue("@PhoneNumber", phoneNumber);
cmd.Parameters.AddWithValue("@Address", address);
cmd.Parameters.AddWithValue("@PostCode", postCode);
long id = (long)cmd.LastInsertedId;
sql = "UPDATE facultymember SET isTenured =
@IsTenured, qualifications = @Qualifications,
previousEmployment = @PreviousEmployment WHERE
Person_personID=@Id";
cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@IsTenured", isTenured);
cmd.Parameters.AddWithValue("@Qualifications",
qualifications);
cmd.Parameters.AddWithValue("@PreviousEmployment",
previousEmployment);
cmd.ExecuteNonQuery();
}
catch (NullReferenceException nre)
{
MessageBox.Show(nre.Message);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
try
{
MessageBox.Show("Updated");
cmd.Connection.Close();
conn.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
I'am having trouble with this function I'm creating to Update my database.
The Update faculty member seems to work perfectly while the Updating of
the person tables does not . I'm presuming that the MySQL Query isn't
correct for updating the person table.
Additional INFO: My code is hooked to an GUI mock as of right now for
testing purposes . the Update string with @Id.. its just to select which
ID I wish to change..
public static void Update(string update,string fName, string lName, string
DOB, string postCode, string address, string phoneNumber,
bool isTenured, string
qualifications, string
previousEmployment)
{
MySqlConnection conn;
MySqlCommand cmd;
string sql = "UPDATE person SET firstName = @FirstName ,
lastName = @LastName, DOB = @DOB, phoneNumber =
@PhoneNumber, address = @Address, postCode = @PostCode
WHERE ID =@Id;";
GetConnection(out conn, out cmd, sql);
try
{
cmd.Parameters.AddWithValue("@Id", update);
cmd.Parameters.AddWithValue("@FirstName", fName);
cmd.Parameters.AddWithValue("@LastName", lName);
cmd.Parameters.AddWithValue("@DOB", DOB);
cmd.Parameters.AddWithValue("@PhoneNumber", phoneNumber);
cmd.Parameters.AddWithValue("@Address", address);
cmd.Parameters.AddWithValue("@PostCode", postCode);
long id = (long)cmd.LastInsertedId;
sql = "UPDATE facultymember SET isTenured =
@IsTenured, qualifications = @Qualifications,
previousEmployment = @PreviousEmployment WHERE
Person_personID=@Id";
cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@IsTenured", isTenured);
cmd.Parameters.AddWithValue("@Qualifications",
qualifications);
cmd.Parameters.AddWithValue("@PreviousEmployment",
previousEmployment);
cmd.ExecuteNonQuery();
}
catch (NullReferenceException nre)
{
MessageBox.Show(nre.Message);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
try
{
MessageBox.Show("Updated");
cmd.Connection.Close();
conn.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
Adding ssl to domain stopped the google app mail service
Adding ssl to domain stopped the google app mail service
few days before my google app mail service was working fine but when i
applied SSL certificate to my domain it stopped working(i.e. stopped
sending mails to my clients).
few days before my google app mail service was working fine but when i
applied SSL certificate to my domain it stopped working(i.e. stopped
sending mails to my clients).
Mahout minhash org.apache.hadoop.io.LongWritable cannot be cast to org.apache.hadoop.io.Text
Mahout minhash org.apache.hadoop.io.LongWritable cannot be cast to
org.apache.hadoop.io.Text
I am using :
hadoop-1.2.1 and mahout-distribution-0.8
When I try to run HASHMIN method with following command:
$MAHOUT_HOME/bin/mahout org.apache.mahout.clustering.minhash.MinHashDriver
-i tce-data/cv.vec -o tce-data/out/cv/minHashDriver/ -ow
I get this error:
tce@osy-Inspiron-N5110:~$ $MAHOUT_HOME/bin/mahout
org.apache.mahout.clustering.minhash.MinHashDriver -i tce-data/cv.vec
-o tce-data/out/cv/minHashDriver/ -ow
Warning: $HADOOP_HOME is deprecated.
Running on hadoop, using /home/tce/app/hadoop-1.2.1/bin/hadoop and
HADOOP_CONF_DIR=
MAHOUT-JOB: /home/tce/app/mahout-distribution-0.8/mahout-examples-0.8-job.jar
Warning: $HADOOP_HOME is deprecated.
13/09/10 18:17:46 WARN driver.MahoutDriver: No
org.apache.mahout.clustering.minhash.MinHashDriver.props found on
classpath, will use command-line arguments only
13/09/10 18:17:46 INFO common.AbstractJob: Command line arguments:
{--endPhase=[2147483647], --hashType=[MURMUR], --input=[tce-data/cv.vec],
--keyGroups=[2], --minClusterSize=[10], --minVectorSize=[5],
--numHashFunctions=[10], --numReducers=[2],
--output=[tce-data/out/cv/minHashDriver/], --overwrite=null,
--startPhase=[0], --tempDir=[temp], --vectorDimensionToHash=[value]}
13/09/10 18:17:48 INFO input.FileInputFormat: Total input paths to process
: 1
13/09/10 18:17:50 INFO mapred.JobClient: Running job: job_201309101645_0031
13/09/10 18:17:51 INFO mapred.JobClient: map 0% reduce 0%
13/09/10 18:18:27 INFO mapred.JobClient: Task Id :
attempt_201309101645_0031_m_000000_0, Status : FAILED
java.lang.ClassCastException: org.apache.hadoop.io.LongWritable cannot be
cast to org.apache.hadoop.io.Text
at
org.apache.mahout.clustering.minhash.MinHashMapper.map(MinHashMapper.java:30)
at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:145)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:764)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:364)
at org.apache.hadoop.mapred.Child$4.run(Child.java:255)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at
org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1190)
at org.apache.hadoop.mapred.Child.main(Child.java:249)
I appreciate any idea
org.apache.hadoop.io.Text
I am using :
hadoop-1.2.1 and mahout-distribution-0.8
When I try to run HASHMIN method with following command:
$MAHOUT_HOME/bin/mahout org.apache.mahout.clustering.minhash.MinHashDriver
-i tce-data/cv.vec -o tce-data/out/cv/minHashDriver/ -ow
I get this error:
tce@osy-Inspiron-N5110:~$ $MAHOUT_HOME/bin/mahout
org.apache.mahout.clustering.minhash.MinHashDriver -i tce-data/cv.vec
-o tce-data/out/cv/minHashDriver/ -ow
Warning: $HADOOP_HOME is deprecated.
Running on hadoop, using /home/tce/app/hadoop-1.2.1/bin/hadoop and
HADOOP_CONF_DIR=
MAHOUT-JOB: /home/tce/app/mahout-distribution-0.8/mahout-examples-0.8-job.jar
Warning: $HADOOP_HOME is deprecated.
13/09/10 18:17:46 WARN driver.MahoutDriver: No
org.apache.mahout.clustering.minhash.MinHashDriver.props found on
classpath, will use command-line arguments only
13/09/10 18:17:46 INFO common.AbstractJob: Command line arguments:
{--endPhase=[2147483647], --hashType=[MURMUR], --input=[tce-data/cv.vec],
--keyGroups=[2], --minClusterSize=[10], --minVectorSize=[5],
--numHashFunctions=[10], --numReducers=[2],
--output=[tce-data/out/cv/minHashDriver/], --overwrite=null,
--startPhase=[0], --tempDir=[temp], --vectorDimensionToHash=[value]}
13/09/10 18:17:48 INFO input.FileInputFormat: Total input paths to process
: 1
13/09/10 18:17:50 INFO mapred.JobClient: Running job: job_201309101645_0031
13/09/10 18:17:51 INFO mapred.JobClient: map 0% reduce 0%
13/09/10 18:18:27 INFO mapred.JobClient: Task Id :
attempt_201309101645_0031_m_000000_0, Status : FAILED
java.lang.ClassCastException: org.apache.hadoop.io.LongWritable cannot be
cast to org.apache.hadoop.io.Text
at
org.apache.mahout.clustering.minhash.MinHashMapper.map(MinHashMapper.java:30)
at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:145)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:764)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:364)
at org.apache.hadoop.mapred.Child$4.run(Child.java:255)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at
org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1190)
at org.apache.hadoop.mapred.Child.main(Child.java:249)
I appreciate any idea
php xml xpath how to extract desired match
php xml xpath how to extract desired match
I have question on how to access SourceUrl for image with width=400
images/di/47/6b/77/454430384d6d324b413332544a695675313851-400x400-0-0.jpg?p=p2.7f19fe93a466ae45afab&a=1&c=1&l=7000610&r=1&pr=1&lks=43998&fks=35198
By default it is showing me image with width=100 and somehow my zpath
syntax is not picking up 400
<?php
$string = <<<XML
<imageList>
<image available="true" height="100" width="100">
<sourceURL>images/di/47/6b/77/454430384d6d324b413332544a695675313851-100x100-0-0.jpg?p=p2.7f19fe93a466ae45afab&a=1&c=1&l=7000610&r=1&pr=1&lks=43998&fks=35198</sourceURL>
</image>
<image available="true" height="200"
width="200"><sourceURL>images/di/47/6b/77/454430384d6d324b413332544a695675313851-200x200-0-0.jpg?p=p2.7f19fe93a466ae45afab&a=1&c=1&l=7000610&r=1&pr=1&lks=43998&fks=35198</sourceURL></image>
<image available="true" height="300"
width="300"><sourceURL>images/di/47/6b/77/454430384d6d324b413332544a695675313851-300x300-0-0.jpg?p=p2.7f19fe93a466ae45afab&a=1&c=1&l=7000610&r=1&pr=1&lks=43998&fks=35198</sourceURL></image>
<image available="true" height="400"
width="400"><sourceURL>images/di/47/6b/77/454430384d6d324b413332544a695675313851-400x400-0-0.jpg?p=p2.7f19fe93a466ae45afab&a=1&c=1&l=7000610&r=1&pr=1&lks=43998&fks=35198</sourceURL></image>
<image available="true" height="569"
width="500"><sourceURL>images/di/47/6b/77/454430384d6d324b413332544a695675313851-500x569-0-0.jpg?p=p2.7f19fe93a466ae45afab&a=1&c=1&l=7000610&r=1&pr=1&lks=43998&fks=35198</sourceURL></image></imageList>
XML;
$xml = simplexml_load_string($string);
$result = $xml->xpath("//image[@height='400']/sourceURL");
?>
I have question on how to access SourceUrl for image with width=400
images/di/47/6b/77/454430384d6d324b413332544a695675313851-400x400-0-0.jpg?p=p2.7f19fe93a466ae45afab&a=1&c=1&l=7000610&r=1&pr=1&lks=43998&fks=35198
By default it is showing me image with width=100 and somehow my zpath
syntax is not picking up 400
<?php
$string = <<<XML
<imageList>
<image available="true" height="100" width="100">
<sourceURL>images/di/47/6b/77/454430384d6d324b413332544a695675313851-100x100-0-0.jpg?p=p2.7f19fe93a466ae45afab&a=1&c=1&l=7000610&r=1&pr=1&lks=43998&fks=35198</sourceURL>
</image>
<image available="true" height="200"
width="200"><sourceURL>images/di/47/6b/77/454430384d6d324b413332544a695675313851-200x200-0-0.jpg?p=p2.7f19fe93a466ae45afab&a=1&c=1&l=7000610&r=1&pr=1&lks=43998&fks=35198</sourceURL></image>
<image available="true" height="300"
width="300"><sourceURL>images/di/47/6b/77/454430384d6d324b413332544a695675313851-300x300-0-0.jpg?p=p2.7f19fe93a466ae45afab&a=1&c=1&l=7000610&r=1&pr=1&lks=43998&fks=35198</sourceURL></image>
<image available="true" height="400"
width="400"><sourceURL>images/di/47/6b/77/454430384d6d324b413332544a695675313851-400x400-0-0.jpg?p=p2.7f19fe93a466ae45afab&a=1&c=1&l=7000610&r=1&pr=1&lks=43998&fks=35198</sourceURL></image>
<image available="true" height="569"
width="500"><sourceURL>images/di/47/6b/77/454430384d6d324b413332544a695675313851-500x569-0-0.jpg?p=p2.7f19fe93a466ae45afab&a=1&c=1&l=7000610&r=1&pr=1&lks=43998&fks=35198</sourceURL></image></imageList>
XML;
$xml = simplexml_load_string($string);
$result = $xml->xpath("//image[@height='400']/sourceURL");
?>
PHP Array to solve space issue
PHP Array to solve space issue
I have this PHP code
case "category": {
// CHECK IF THE CATEGORY ALREADY EXISTS
if ( is_term( $val, THEME_TAXONOMY ) ){
$term = get_term_by('name', str_replace("_"," ",$val),
THEME_TAXONOMY);
$catID = $term->term_id;
}else{
$args = array('cat_name' => str_replace("_"," ",$val) );
$term = wp_insert_term(str_replace("_"," ",$val), THEME_TAXONOMY,
$args);
if(is_array($term) && isset($term['term_id']) &&
!isset($term['errors'][0]) ){
$catID = $term['term_id'];
}elseif(isset($term->term_id)){
$catID = $term->term_id;
}
}
$my_post['post_category'] = array($catID);
} break;
it was used to import categories in wordpress but issue is as code is
showing it is replace _ with so I want to import multiple categories so
how can I use an array to do it?
I'm importing multiple categories name like abs,test,test12 . So it was
just importing as it is then I did this abs_test_test12 . And it just
removed _ with space and imported. However each name is different
category. It should import each name after a comma or underscore as a new
category name. –
I have this PHP code
case "category": {
// CHECK IF THE CATEGORY ALREADY EXISTS
if ( is_term( $val, THEME_TAXONOMY ) ){
$term = get_term_by('name', str_replace("_"," ",$val),
THEME_TAXONOMY);
$catID = $term->term_id;
}else{
$args = array('cat_name' => str_replace("_"," ",$val) );
$term = wp_insert_term(str_replace("_"," ",$val), THEME_TAXONOMY,
$args);
if(is_array($term) && isset($term['term_id']) &&
!isset($term['errors'][0]) ){
$catID = $term['term_id'];
}elseif(isset($term->term_id)){
$catID = $term->term_id;
}
}
$my_post['post_category'] = array($catID);
} break;
it was used to import categories in wordpress but issue is as code is
showing it is replace _ with so I want to import multiple categories so
how can I use an array to do it?
I'm importing multiple categories name like abs,test,test12 . So it was
just importing as it is then I did this abs_test_test12 . And it just
removed _ with space and imported. However each name is different
category. It should import each name after a comma or underscore as a new
category name. –
Subscribe to:
Posts (Atom)