Friday, 27 September 2013

Read text lines using QDataStream or QTextStream or neither from tcpsocket?

Read text lines using QDataStream or QTextStream or neither from tcpsocket?

I am creating a simple TCP server, and have a slot/function built which
reads incoming text from a client (telnet connection) on a TCP socket.
I've used the Fortune code examples to help me, but had to remove
QDataStream since it didn't work as expected.
I want my readCommand function to collect incoming characters from a
telnet client connection, and once it finds a newline or return to remove
the typed command from the input buffer, remove /n and /r, add it to my
string list (commandList), and then echo the commands (seperate function).
Here's what I've got so far:
void MyServer::readCommand()
{
inBuffer += tcpSocketPtr->readAll();
// While newline is present, extract the command
int nextNewlinePos;
while ((nextNewlinePos = inBuffer.indexOf('\n')) > -1) {
commandList << inBuffer.left(nextNewlinePos);
inBuffer.remove(0,nextNewlinePos);
// Get rid of /n /r if present somehow
}
if (commandList.size() > 0)
{
echoCommand();
}
}
Before I start stripping /n and /r etc. manually, my gut is telling me
there is a better way to do this. Is QTextStream the way to go? Can
someone provide a simple(r) alternative to what I am trying to achieve?

Escape colon in url string

Escape colon in url string

I have a string:
$fonts = "Arial:400";
When I use that in a URL, the colon prints as %3A. How can I escape the
colon so that it prints as :? I have tried preg_replace and url_encode
with no luck. I'm sure its simple but I have searched.

why did Joshua Bloch decrement the "size" value of stack in the pop method in effective java?

why did Joshua Bloch decrement the "size" value of stack in the pop method
in effective java?

here is the code from Item 6, pg 24, chapter 2 of effective java 2nd
edition, by Joshua Bloch. In the pop method he defines, he uses
elements[--size]. I am wondering why he used --size, instead
elements[size--] should return the same correct?
public class Stack {
private Object[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() {
elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size == 0)
throw new EmptyStackException();
return elements[--size];
}
/**
* Ensure space for at least one more element, roughly
* doubling the capacity each time the array needs to grow.
*/
private void ensureCapacity() {
if (elements.length == size)
elements = Arrays.copyOf(elements, 2 * size + 1);
} }

External PHP file returning error with the result?

External PHP file returning error with the result?

I have an external PHP file which updates mysql database (this file is
connected with the main theme with jquery and ajax).
This is the simplified code from the ext file
<?php
$file = dirname(__FILE__);
$file = substr($file, 0, stripos($file, "wp-content") );
require( $file . "/wp-load.php");
if (something){echo ($var);}
else {echo ('eg97');}
?>
This is the result I get (when condition not met):
<!--
function add_jquery()
{
wp_enqueue_script( 'jquery' );
}
add_action('wp_enqueue_scripts', 'add_jquery');
?>
function open_mysql_db()
{
$mysqli = new mysqli('address of database', 'username', 'password',
'database name');
// check connection
if (!$mysqli)
throw new Exception('Could not connect to database');
else
return $mysqli;
};
--> 97
All I want to get is 97 (or $var).
Any ideas?

How to stop timer on killing app android

How to stop timer on killing app android

How do I stop my timer when I close my App (Using the Return/exit
button((Not home button)))?
When I close my App using the back button it's not in the task messenger,
but the timer (Sending notifications on events) is still running and
sending me notifications..
I thought as it is not in the tasks, and I use the return button to close
the timer would also stop.. When I open the app again after closing it it
does restart on it's mainactivity unlike opening it when I used the "home"
button..

Thursday, 26 September 2013

How send content file on url in javascript?

How send content file on url in javascript?

Good day.
var photo = 'http://cs323230.vk.me/u172317140/d_5828c26f.jpg';
var upload_url = 'http://cs9458.vk.com/upload.php?act=do_add&mid=62..';
Anyone know how send content file photo on url upload_url in JavaScript?

Thursday, 19 September 2013

After editing a destination path, editing motion tween no longer affects whole curve

After editing a destination path, editing motion tween no longer affects
whole curve

I created a motion tween, and at the final frame moved the symbol to its
destination. I was then able to manipulate the curve by dragging the
points, or using the subselection tool to invoke the bezier handles, and
everything looks smooth. However, if I then move the object, even a tiny
bit, future changes to the curve now no longer smoothly affect the whole
curve, but will bend and contort it in tiny subsections, resulting in a
very knotted curve, and the only way to get back there is to undo my way
up the stack to where I dragged the object in the destination frame and
redo my desired curve.
Clicking on the object and moving it is doing something to my editing
mode, but for the life of me I cannot see what it is. Might anyone be able
to tell me what it is, and what I would have to do (I am using Mac OS X
CS6) to return myself to being able to smoothly tweak the whole curve and
not just subsections?

Find the first non repetitive character in a string

Find the first non repetitive character in a string

I was asked this question in an interview. My answer: "create an array of
size 26. Traverse the string by each character and make counts of
characters in the array. Check the first non repetitive character by
traversing again in the string and checking the array if the character is
not repeated." What if the string contains large set of characters like
10000 types of characters instead of 26 types of alphabets.

While loop assignment

While loop assignment

# Finicky Counter
# Demonstrates the break and continue statements
count = 0
while True:
count += 1
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print(count)
input("\n\nPress the enter key to exit.")
Why does the while True loop apply to count in this circumstance? I dont
understand why the boolean is gauging the result of count. Wouldn't the
correct syntax be:
while count:
Any help clarifying this would be appreciated.

Invalid argument supplied for foreach(); Array not being set properly

Invalid argument supplied for foreach(); Array not being set properly

Here is my code:
class Subscriber extends DatabaseObject {
protected static $table_name = "email_list";
protected static $db_fields = array('id', 'email');
public $id;
public $email;
function __construct() {
self::$object = new Subscriber;
}
}
In the parent class, DatabaseObject, is the problem:
class DatabaseObject {
protected static $object;
protected static $db_fields;
protected function attributes() {
$attributes = array();
foreach (self::$db_fields as $field) {
// edited
}
return $attributes;
}
However, I get Warning: Invalid argument supplied for foreach() because of
the line:
foreach (self::$db_fields as $field) {
Why isn't the array being set? I tried setting it in the constructor
manually but it did not work either.

Records are repeated in a table

Records are repeated in a table

Good morning, I have the following table with the following records
Mov Descip Correlativo Total
25558 AAAAAAAA 1 540
25558 AAAAAAAA 2 540
25559 BBBBBBBBB 3 40
25560 CCCCCCCCC 4 50
25561 DDDDDDDD 5 120
25561 DDDDDDDD 6 120
25561 DDDDDDDD 7 120
Do not know how to do a query to show me but without repeating records, I
have tried with DISTINCT does not work.

why notation pat ... means zero or more expressions in scheme macro pattern

why notation pat ... means zero or more expressions in scheme macro pattern

When I'm reading the macro part of The Scheme Programming Language, it
mentions that when you are trying to define a syntax extension using
define-syntax, you should use pat ... to specify zero or more expression
in the pattern. Why don't just use ... for zero or more expression, in
which case pat ... means one or more expressions?
Also, when the author gives definition of and as follows:
(define-syntax and
(syntax-rules ()
[(_) #t]
[(_ e) e]
[(_ e1 e2 e3 ...)
(if e1 (and e2 e3 ...) #f)]))
Why don't just write it like this:
(define-syntax and
(syntax-rules ()
[(_) #t]
[(_ e) e]
[(_ e1 e2 ...)
(if e1 (and e2 ...) #f)]))
I have tested this definition with some cases, and I didn't find any
problem with it.

Column name in two lines DOJO

Column name in two lines DOJO

I have a DOJO table. How can I write the column name in two lines?
{classes: "title", name: "I/P Voltage (V)", field:
"mainsVoltage",styles: 'text-align: center;', width: "100px" }
I want the I/P Voltage in one line and (V) in next line and in the center.
How can I do that?

Refresh page from server's cache and server meanwhile crashes and is up & running again

Refresh page from server's cache and server meanwhile crashes and is up &
running again

If you have a page that is remaining inactive for a long time and because
you want NOT to lose the session with server let's say refresh the page
every 8 minute. Meanwhile the server crashes let's for 20 minutes. The
question is what type of refresh I have to do into the page so that after
an hour if I come back and want to navigate to the page. I assume that
server is live again. Is there any type of refresh do that?

Wednesday, 18 September 2013

Can available json response be reused in tritium to paint new mobile home page?

Can available json response be reused in tritium to paint new mobile home
page?

I am trying to use moovweb to transform existing desktop site to mobile
version. I already have so many ajax response available in the desktop
version. We also have a new wire frame for the mobile version.Is there any
way to reuse the ajax response and dynamically paint the page as per the
new wireframe [by making use of tritium]?

Need help setting up a logic behind a Facebook notification system style

Need help setting up a logic behind a Facebook notification system style

I want build a notification system to my website, similar to Facebook. The
notifications don't need to be in real time.
This is what I have in mind:
User create an event (upload a new photo, add a new comment, like a photo,
or even an administration alert to all users)
Run a cronjob every 5 minutes to add the notifications into the
notifications table:
id|id_content|type_of_content_enum|affected_user_id|date|seen_bool
The cronjob, will run several functions for each type of notification, for
example:
add_photos_notification() // This function will check all photos added in
the past 5 minutes, and insert a row in the notification table, for each
user following this person. The function will group all photos added into
the past 5 minutes, so the follower don't get many notifications for the
same type of content. Resulting in a notification like: User X added Y
photos in his profile.
add_admin_notification() // This function will check all news added by the
administration of the site in the past 5 minutes, and insert a row in the
notification table, for each user on the system ...
Is this a correct approach to build a notification system?
Is it possible to miss an event, running a cron every 5 minutes where
functions retrieve the past 5 minutes events?
To be safe, do you think an alternative could be checking all events where
a field 'notified' is not true? The same function that will grab the
events where 'notified' = false, update it to true after adding that
notification into the notifications table.
Thanks,

Android - Getting activity object from startActivity

Android - Getting activity object from startActivity

Folks,
I need to get the instance of the Activity that was created when
startActivity() is called. However, startActivity() returns a void value.
I guess startActivity() doesn't wait until the Activity is created.
Is there a different way for me to get hold of the activity that was just
created on the call to startActivity? Or, perhaps I can create an Activity
instance myself and register it somewhere so that startActivity can find
it.
Thank you in advance for your help.
Regards,
Peter

Rails validate model with attribute

Rails validate model with attribute

I need to do a custom validation that checks if the attribute being
updated is less than another attribute on that record. I tried doing this:
validates :team_size, :numericality => { :greater_than_or_equal_to =>
self.users.count }
But it comes back with the error:
NoMethodError (undefined method `users' for #<Class:0x007fcda9a548e8>):
I also tried doing a before_save hook with a method like this:
def validate_team_size
if self.team_size < self.users.count
errors[:base] << "Custom message."
end
end
But it just ignores it - I'm assuming because the team_size attribute
hasn't been updated yet so I'm checking the old value. Also tried using
after_save which is just before it commits but no luck either.

How to query for unique pages views by date, IP

How to query for unique pages views by date, IP

Table
--------
Date CreatedOn
varchar(25) IP
From this table, I want to selected the number of unique IP addresses, by
Day.
June 1, 2013 25
June 2, 2013 35
What is the Sql Server 2008R2 SQL for this?
Greg

Android App and Blue Screen

Android App and Blue Screen

I want your help, I created an android application it was working well on
device with Android version 2.2.2 when I installed the app on other device
with Android version 2.3.6 when I restart it, it randomly gets blue screen
and to end this situation I have to remove the battery and put it again.
Any Help??
Thanks

Angular $event undefined in Firefox

Angular $event undefined in Firefox

As said in the angular api docs, ng-mouseenter makes event object
available as $event.
HTML:
<div ng-mouseenter="enter('test', $event)">Enter mouse over here</div>
JS:
$scope.enter = function(data, $event) {
console.log($event.x);
};
Use this fiddle and notice that...
in chrome the log gives: 77 (or another number)
And firefox gives the log: undefined.
Am I using $event the wrong way or does $event not work in Firefox?

PHP Upload image,rename image with date timestamp

PHP Upload image,rename image with date timestamp

When i do this for this part here:
$ran = time();
$ran2 = $ran.".";
It is able to set the image name as this:
The file has been uploaded as 1379496233.67485,10.jpg
where by *1379496233 refers to the time();
But when i do this:
$ran = date("g:i:s A D, d/m/y"); date_default_timezone_set('Singapore');
$ran2 = $ran.".";

Error code such as this "Warning: move_uploaded_file(images/9:28:13 AM
Wed, 18/09/13.1185810_10201356273602710_1568954903_n.jpg)
[function.move-uploaded-file]: failed to open stream: Invalid argument in
C:\wamp\www\zzzzzzzzzzzzzzzzzzzzzz\v.php on line 35" & this occurs
"Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to
move 'C:\wamp\tmp\php3E46.tmp' to 'images/9:28:13 AM Wed,
18/09/13.1185810_10201356273602710_1568954903_n.jpg' in
C:\wamp\www\zzzzzzzzzzzzzzzzzzzzzz\v.php on line 35"
<?php
//This function separates the extension from the rest of the file
name and returns it
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = explode("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
//This applies the function to our file
$ext = findexts ($_FILES['uploaded']['name']) ;
$ran = time();
$ran2 = $ran.".";
//This assigns the subdirectory you want to save into... make sure it
exists!
$target = "images/";
//This combines the directory, the random file name, and the extension
$target = $target . $ran2.$ext;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file has been uploaded as ".$ran2.$ext;
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
?>

What is the use of structure having only one element?

What is the use of structure having only one element?

Example:
struct dummy
{
int var;
};
Why structures like this are used? Mostly I have seen them in some header
files.
The atomic_t type is also defined like this. Can't it be defined simply
using:
typedef int atomic_t;

Tuesday, 17 September 2013

Why are my instance variables not existing across methods of the same class in ruby?

Why are my instance variables not existing across methods of the same
class in ruby?

I am doing the ruby koans and I am on the DiceSet project. I've made the
DiceSet class but my instance variables don't seem to persist with the
instance like I thought they would. My code is
class DiceSet
attr_reader :values
@values = []
puts @values.class
def roll(number_of_rolls)
(1..number_of_rolls).each do |roll|
puts @values.class
@values << (1..6).to_a.sample
end
return @values
end
end
The koan then uses my DiceSet class with
dice = DiceSet.new
dice.roll(5)
puts dice.values.class
assert dice.values.is?(Array)
I put the puts commands in there to follow whats happening with the
@values instance variable and only the first puts @values.class says its
an Array class. All the others are returning NilClass. Am I using instance
variables incorrectly or is there something else I am missing? Do instance
variables get deallocated after a method call?

Specify locale in string resource identifier

Specify locale in string resource identifier

Is it possible to reference a string resource by locale, in XML?
For example, what if I want to read the French version of a string
resource no matter what locale I'm currently in. This can be done in Java
but can it be done in XML?
In other words, is there anything like this? @string-fr/my_string

Attribute duplication importing HoloEverywhere and ActionbarSherlock in Eclipse

Attribute duplication importing HoloEverywhere and ActionbarSherlock in
Eclipse

I have been struggling with this problem for hours now. I have tried all
tips I found at StackOverflow, but they did not help me.
The problem:
I have imported HoloEverywhere in Eclipse. I then imported
ActionbarSherlock into HoloEverywhere, as is said here only to get a bunch
of errors. Also, R.java is not being generated for the HoloEverywhere
project (I tried cleaning all projects, didn't work).
Judging by the log output, I'd say there are repeating attribute names in
the ActionbarSherlock and HoloEverywhere projects. How do I fix that?
Here is part of the log:
[2013-09-18 02:34:22 - library]
D:\HoloEverywhere-master\library\res\values-v11\themes.xml:28: error:
Error: No resource found that matches the given name: attr
'android:textAppearanceLargePopupMenu'. [2013-09-18 02:34:22 - library]
D:\HoloEverywhere-master\library\res\values-v11\themes.xml:29: error:
Error: No resource found that matches the given name: attr
'android:textAppearanceSmallPopupMenu'. [2013-09-18 02:34:22 - library]
D:\HoloEverywhere-master\library\res\values-v11\themes.xml:30: error:
Error: No resource found that matches the given name: attr
'android:windowMinWidthMajor'. [2013-09-18 02:34:22 - library]
D:\HoloEverywhere-master\library\res\values-v11\themes.xml:31: error:
Error: No resource found that matches the given name: attr
'android:windowMinWidthMinor'. [2013-09-18 02:34:22 - library]
D:\HoloEverywhere-master\library\res\values\themes.xml:152: error: Error:
No resource found that matches the given name: attr
'android:listChoiceBackgroundIndicator'. [2013-09-18 02:34:22 - library]
D:\HoloEverywhere-master\library\res\values-v11\themes.xml:43: error:
Error: No resource found that matches the given name: attr
'android:activatedBackgroundIndicator'. [2013-09-18 02:34:22 - library]
D:\HoloEverywhere-master\library\res\values-v11\themes.xml:44: error:
Error: No resource found that matches the given name: attr
'android:dialogTheme'. [2013-09-18 02:34:22 - library]
D:\HoloEverywhere-master\library\res\values-v11\themes.xml:45: error:
Error: No resource found that matches the given name: attr
'android:dividerHorizontal'. [2013-09-18 02:34:22 - library]
D:\HoloEverywhere-master\library\res\values-v11\themes.xml:46: error:
Error: No resource found that matches the given name: attr
'android:dividerVertical'. [2013-09-18 02:34:22 - library]
D:\HoloEverywhere-master\library\res\values-v11\themes.xml:47: error:
Error: No resource found that matches the given name: attr
'android:textAppearanceLargePopupMenu'. [2013-09-18 02:34:22 - library]
D:\HoloEverywhere-master\library\res\values-v11\themes.xml:48: error:
Error: No resource found that matches the given name: attr
'android:textAppearanceSmallPopupMenu'. [2013-09-18 02:34:22 - library]
D:\HoloEverywhere-master\library\res\values-v11\themes.xml:49: error:
Error: No resource found that matches the given name: attr
'android:windowMinWidthMajor'. [2013-09-18 02:34:22 - library]
D:\HoloEverywhere-master\library\res\values-v11\themes.xml:50: error:
Error: No resource found that matches the given name: attr
'android:windowMinWidthMinor'. [2013-09-18 02:34:22 - library]
D:\HoloEverywhere-master\library\res\values\themes.xml:188: error: Error:
No resource found that matches the given name: attr
'android:windowActionBar'. [2013-09-18 02:34:22 - library]
D:\HoloEverywhere-master\library\res\values\themes.xml:238: error: Error:
No resource found that matches the given name: attr
'android:windowActionBar'. [2013-09-18 02:34:22 - library]
D:\HoloEverywhere-master\library\res\values\themes.xml:274: error: Error:
No resource found that matches the given name: attr
'android:windowActionBar'.
Any help is much appreciated.

Andorid: Changing fragments by button inside ViewPager (PagerSlidingTabStrip )

Andorid: Changing fragments by button inside ViewPager
(PagerSlidingTabStrip )

I'm using PagerSlidingTabStrip library for ViewPager
https://github.com/astuetz/PagerSlidingTabStrip.
I want to change the fragment when i press button to specific fragment.
MainActivity.java:
package com.astuetz.viewpager.extensions.sample;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends FragmentActivity {
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
private int currentColor = 0xFF96AA39;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
final int pageMargin = (int)
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4,
getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
tabs.setIndicatorColor(currentColor);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_contact:
QuickContactFragment dialog = new QuickContactFragment();
dialog.show(getSupportFragmentManager(), "QuickContactFragment");
return true;
}
return super.onOptionsItemSelected(item);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { "Categories", "Home", "Top Paid",
"Top Free", "Top Grossing", "Top New Paid",
"Top New Free", "Trending" };
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
@Override
public int getCount() {
return TITLES.length;
}
@Override
public Fragment getItem(int position) {
return SuperAwesomeCardFragment.newInstance(position);
}
}
}
fragment.java:
public class SuperAwesomeCardFragment extends Fragment {
private static final String ARG_POSITION = "position";
private int position;
public static SuperAwesomeCardFragment newInstance(int position) {
SuperAwesomeCardFragment f = new SuperAwesomeCardFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
FrameLayout fl = new FrameLayout(getActivity());
fl.setLayoutParams(params);
final int margin = (int)
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8,
getResources()
.getDisplayMetrics());
TextView v = new TextView(getActivity());
params.setMargins(margin, margin, margin, margin);
v.setLayoutParams(params);
v.setLayoutParams(params);
v.setGravity(Gravity.CENTER);
v.setBackgroundResource(R.drawable.background_card);
if(position==0){
v.setText("dddd");
Button bb=new Button(getActivity());
bb.setText("goo");
**bb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
}**
});
}else
v.setText("CARD " + (position + 1));
fl.addView(v);
return fl;
}
}

How can I combine these jQuery .on() functions?

How can I combine these jQuery .on() functions?

Here is my code. The swipes are for anywhere in the document, the click is
for the close img, but they execute the same code. Any advice? It's not an
overly big deal, but I would like smaller, cleaner code if I can. This is
for a modal type window.
$(document).on("click", "#close", function () {
ttl.html(docTitle + air);
window.history.pushState({}, docTitle + air, docURL);
}).on("swipeleft swiperight", function () {
ttl.html(docTitle + air);
window.history.pushState({}, docTitle + air, docURL);
});

EAR generated using ANT doesn't work on Websphere 8.5

EAR generated using ANT doesn't work on Websphere 8.5

The object is to build .ear by using ANT then deploy it on Websphere 8.5
with wsadmin.
Manually, the ear file is generated from a jar file and after deployment,
the web application works very well.
But if I use the ear generated by ANT, after deployment (by hand or by
wsadmin), I always have this error :
SRVE0255E: A WebGroup/Virtual Host to handle /WebApp$%7Blogout.url%7D has
not been defined.
SRVE0255E: A WebGroup/Virtual Host to handle localhost:9080 has not been
defined.
Someone knows which might invoke this problem. I met this message before
while my colleague deploy on websphere with a war file directly from a
Tomcat server.
Thanks in advance.

Sunday, 15 September 2013

Java While-Loop issue

Java While-Loop issue

I am trying to read a .txt file which contains this
lollipops 10 0.50 5.00
dietsoda 3 1.25 3.75
chocolatebar 20 0.75 15.00
What it will do is make 4 columns one for name, quantity, price, total and
read them from the txt file. Then calculate subtotal, sales tax and then
total. I'm having a problem trying to use a while loop to read each line,
I keep getting an infinite loop.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class CatalogTester
{
public static double SALESTAX = 0.0625;
public static void main(String[] args) throws FileNotFoundException
{
String name ="";
int quantity = 0;
double price =0;
double total = 0;
double subtotal = 0;
double tax = 0;
double total_all = 0;
File inFile = new File("Catalog.txt");
Scanner in = new Scanner(inFile);
String line = in.nextLine();
while(in.hasNextLine()){
int i = 0;
while(!Character.isDigit(line.charAt(i))) {i++;}
name = line.substring(0,i);
int j = line.length()-i;
while(Character.isDigit(line.charAt(j))) {j++;}
String quantityVal = line.substring(i, j);
quantity = Integer.parseInt(quantityVal);
int k = j;
while(Character.isDigit(line.charAt(k))) {k++;}
int x = k+4;
while(Character.isWhitespace(line.charAt(x))) {x++;}
String priceVal = line.substring(k,x);
price = Double.parseDouble(priceVal);
int z = x;
while(Character.isDigit(line.charAt(z))) {z++;}
String totalVal = line.substring(z,line.length());
total = Double.parseDouble(totalVal);
}
System.out.printf("%-30s %-10s %-10s %-10s\n", "Item",
"Quantity","Price", "Total");
System.out.println();
System.out.println("Expected:Item
Quantity Price Total");
System.out.printf("%-30s %-10d %-10.2f %-10.2f\n", name, quantity,
price, total);
System.out.println("Expected:lollipops 10
0.50 5.00");
System.out.printf("%-52s %-10.2f\n", "SubTotal", subtotal);
System.out.println("Expected:SubTotal
23.75");
System.out.printf("%-52s %-10.2f\n", SALESTAX * 100 + "% Sales
Tax",tax);
System.out.println("Expected:6.25% Sales Tax
1.48");
System.out.printf("%-52s %-10.2f\n", "Total", total_all);
System.out.println("Expected:Total
25.23");
}
}

How do I plot a number of categorical variables on a graph in R?

How do I plot a number of categorical variables on a graph in R?

I have about 10 categorical variables - pay1, pay2, ... , pay10 each
having values either 'Yes' or 'No'. I would like to plot the count of each
of these variables on a graph. For example - bar1 on the chart should
refer to the variable 'pay1' reflecting the total number of observations
divided between 'Yes' and 'No'('Yes' on top of 'No' or vice versa) This
scheme should be consistent with all the 10 variables on the chart. If I
am able to display the percentage of 'Yes' and 'No' for each bar, even
better. Would someone be able to help out on this?
TIA.

Form not going to the #

Form not going to the #

I have this code
echo '<form
action="?id='.$topic_id.'&part=9&num='.$_GET['num'].'#commenting "
method="POST" style="border: none; margin: 0;">';
echo '<textarea style="display: none; margin: 0;"
name="old_comment">' . $row['comment'] .
'</textarea>';
echo '<textarea style="width: 90%;"
name="new_comment">' . $row['comment'] .
'</textarea>';
echo '<input type="submit" value="Save Edit &raquo;"
class="button">';
echo '</form>';
The form seems to ignore the #. I dug into the displayed code in chrome.
It shows...
<form action="?id=28&part=1" method="POST" class="comment">
<textarea name='comment'></textarea>
<input type="submit" value="Post Comment &raquo;" class="button">
</form>
#commenting just disappeared.....
Does # have some other meaning or am I doing it wrong?

Center to right by parent

Center to right by parent

I'm working at my new intranet page.
Currently I have something like that :

I want to have :

Is there any way to center my text to right by it parent (image) ?
That is my code, but it doesn't work :
<body style="background-color:#FFCC66"><br/><a href="/" title="PrzejdŸ
do strony g³ównej"><img
style="display:block;margin-left:auto;margin-right:auto"
src="/logointra.png" alt="Logo Intranetu" /></a>
<br/><span style="display:block; position:relative;
text-align:right">I wanna be centered to right by my parent -
image</span>

What happens when you change a reference inside a method?

What happens when you change a reference inside a method?

What happens when you change a reference inside a method?
public void reverseX(int[] nums) {
int[] nums2 = new int[nums.length] ;
for( int i=0 ; i < nums.length ; i++ )
nums2[i] = nums[nums.length-(i+1)] ;
nums = nums2 ;
};
Objects, reference types are suppose to be immutable. What happens here
when nums is set to nums2.
This compiles fine.
Code is from here, and shown as an example of what not to do.
http://www.cs.nyu.edu/~cconway/teaching/cs1007/notes/arrays.pdf

PHP wildcard redirection script?

PHP wildcard redirection script?

So I just moved my site from /blog to / (root) directory. Now for those
people who know previous /blog URL, I want to redirect them to new URL
(/).
So I have put this index.php file in /blog dir:
<?php
header( 'Location: http://www.abc.com' ) ;
?>
and it works. But I want this: When a user visits any blog post from old
url like http://abc.com/blog/sample-post then instead of redirecting to
abc. com, it should redirect to abc. com/sample-post
I think it may also be done by .htaccess redirection but I dont know
htaccess method.
Please give me code for this :)

Can't install or deploy h2-console for JBoss

Can't install or deploy h2-console for JBoss

I've been working through the instructions here:
http://www.jboss.org/jdf/quickstarts/jboss-as-quickstart/h2-console/#deploy_the_h2_console/
However, I can't figure out what is meant by this line of the
instructions: "Deploy the console by copying the
QUICKSTART_HOME/h2-console/h2console.war to the
$JBOSS_HOME/standalone/deployments directory."
After installing the greeter quickstart, I did not have an "h2console.war"
anywhere. So I downloaded all of the quickstarts from here:
http://www.jboss.org/jdf/quickstarts/jboss-as-quickstart/ after which I
had that file.
I then copied that file to the suggested folder, but that didn't seem to
do anything as the suggested localhost does not load the console.
I've searched high and low but the documentation on h2-console
installation seems sketchy at best. What am I missing?

How to filter which attributes I want to delete in Python class?

How to filter which attributes I want to delete in Python class?

There are certain attributes from the class I allow to be deleted. But,
others are forbidden to be deleted.
class klass:
a = 1
b = 2
def __delattr__(cls, attr):
if attr=='a':
pass # go ahead, delete attribute a
elif attr=='b':
raise TypeError("Bad boy/girl, you shouldn't delete attribute b")
del klass.a
del klass.b
This code does not work. What's wrong with the code? Both attributes are
still being deleted. I am using Python 3 by the way. __delattr__ does not
seem to work. Please note, I don't want to instantiate the class (I don't
want foo = klass(); del foo.a; / I want del klass.a;). Thanks.

Saturday, 14 September 2013

Hartl's RoR Chapter 8.2.5 - UsersController sign_in undefined

Hartl's RoR Chapter 8.2.5 - UsersController sign_in undefined

I'm going through Hartl's RoR Tutorial, Chapter 8.2.5
(http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec-signin_upon_signup)
and I couldn't get the "User Pages signup with valid information should
create a user" test to past, with the following messages:
1) User Pages signup with valid information should create a user
Failure/Error: expect {click_button submit}.to change(User, :count).by(1)
NoMethodError:
undefined method `sign_in' for #<UsersController:0x007fcdb3b066d8>
I was able to solve this by using
include SessionsHelper
in the users_controller.rb. I want to make sure that this was what was
implied, and that I am not doing something wrong as I couldn't find the
instructions for including SessionsHelper in the text.

Safari/touchscreen issue with jQuery custom sliding function

Safari/touchscreen issue with jQuery custom sliding function

I am using a premade short jQuery code for a slider to use a special
offer. Here is the jQuery code for the slider:
$(function() {
$(".slider").draggable({
axis: 'x',
containment: 'parent',
drag: function(event, ui) {
if (ui.position.left > 170) {
$well = $(this).closest('.well'); //Select only the
respective well element.
$well.fadeOut(500, function(){
$well.delay(1000).addClass( "disappear" );
$well.prev(".showup").delay(500).removeClass( "disappear" );
});
} else {
// Apparently Safari isn't allowing partial opacity on text
with background clip? Not sure.
// $("h2 span").css("opacity", 100 - (ui.position.left / 5))
}
},
stop: function(event, ui) {
if (ui.position.left < 171) {
$(this).animate({
left: 0
})
}
}
});
$('.slider')[0].addEventListener('touchmove', function(event) {
event.preventDefault();
var el = event.target;
var touch = event.touches[0];
curX = touch.pageX - this.offsetLeft - 40;
if(curX <= 0) return;
if(curX > 200){
$well = $(this).closest('.well'); //Select only the respective
well element.
$well.fadeOut();
$well.addClass( "disappear" );
$well.add('<h2>Erbjudandet använt</h2>');
}
el.style.webkitTransform = 'translateX(' + curX + 'px)';
}, false);
$('.slider')[0].addEventListener('touchend', function(event) {
this.style.webkitTransition = '-webkit-transform 0.3s ease-in';
this.addEventListener( 'webkitTransitionEnd', function( event ) {
this.style.webkitTransition = 'none'; }, false );
this.style.webkitTransform = 'translateX(0px)';
}, false);
});
The HTML for displaying the slider is as such:
return "<link rel='stylesheet'
href='http://www.infid.se/wp-content/themes/simplemarket/anvandstyle.css'>
<script
src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'></script>
<script
src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js'></script>
<script
src='http://www.infid.se/wp-content/themes/simplemarket/slidetounlock.js'></script>
<div id='page-wrap'>
<div class='showup disappear'><h2>Erbjudande använt</h2></div>
<div class='well'>
<h2><strong class='slider'></strong> <span>Använd
erbjudande</span></h2>
</div>
</div>";
And here is the relevant CSS:
.disappear:before {content: "<h2 style='color:#101010;'>Erbjudande
använt</h2>";}
.disappear{display:none;}
The problem with this code is when I add multiple instances of the slider.
It works fine on my computer (1440px width), but when I use it on my
iPhone I can only select one. Just any point in the right direction would
be good, for example if the problem is with the slider or the device. A
working instance can be found here: http://infid.se/mandag/.

GUI - when I try to stop my program, starts to get Not Responding error and then continues to run the program

GUI - when I try to stop my program, starts to get Not Responding error
and then continues to run the program


it's making running an updated version of the program impossible. I
restarted my computer the first time it happened but I'm getting fed up
now.

HTML, CSS, Jquery help needed

HTML, CSS, Jquery help needed

Hey in my last topic I made a mistake by not putting the css and Jquery in
it. So i've tyed a little more and build a menu in CodePen.
Now the problem i've is that still it doesnt work. I searched but coudn't
find it so thats why i put it here.
http://codepen.io/anon/pen/djwih
HTML is good, css probely not and i'm almost sure that the jquery is good.
Can someone check this for me and correct my mistakes?
On the top i've a logo on the left side and menu has to be on the right
side. The menu has in the correct html an width of 1200px and is margin:0
auto;. But the logo is on the same height as the menu so that's why i've
put #menu ul float:right;.
Thanks in advance for your help!!

The google cloud datastore server fails

The google cloud datastore server fails

This worked well, but now fails me. Maybe is an error because it's a beta.
POST
https://www.googleapis.com/datastore/v1beta1/datasets/gaep81me/beginTransaction?key={YOUR_API_KEY}
Content-Type
: application/json
Authorization: Bearer ya29.AHES6ZRouAaPjnnEuWGc0jjVtisvb08ZD9qKUajtIj_7N7qT
X-JavaScript-User-Agent: Google APIs Explorer
{
"isolationLevel": "serializable"
}
"gaep81me" is a correct ID. I've tried with a lot of projects ID; and in
diferent accounts. And using each account for their projects.
The token is correct: was produced by the Api explorer
https://developers.google.com/apis-explorer/#p/datastore/v1beta1/datastore.datasets.beginTransaction
including the scopes www.googleapis.com/auth/userinfo.email and
www.googleapis.com/auth/datastore
I receive this
503 Service Unavailable
... (headers)...
{
"error": {
"errors": [
{
"domain": "global",
"reason": "backendError",
"message": "Backend Error"
}
],
"code": 503,
"message": "Backend Error"
}
}
My python application (using auth2 + json api) fails too... is not a
problem with the Api explorer page. I think that datastore is down. An
status page for cloud datastore will be fine. Another good thing is to
rename this service to distinguish it from the appengine version. Thanks.

AngularJS application hosted on Github pages (gh-pages) ajax crawling

AngularJS application hosted on Github pages (gh-pages) ajax crawling

anyone knows if is possible to make an AngularJS with client-side
navigation crawlable by search engines if it is hosted on Github?
Let's say, my application has 3 client-side urls:
http : //my-example-application.com/#!/home
http : //my-example-application.com/#!/documentation
http : //my-example-application.com/#!/download
These URL's will not be seen by the search engines because they are served
on the client side, but according to Google Ajax applications
recommendations to help search engines the dynamic content generated by a
javascript application could be cached previously, so the crawlers would
search for a cached version of the previous pages on these URL's:
http : //my-example-application.com/?_escaped_fragment_=/home
http : //my-example-application.com/?_escaped_fragment_=/documentation
http : //my-example-application.com/?_escaped_fragment_=/download
This could be accomplished via url rewriting on a web server, but do we
have any alternative if we are hosting the dynamic page on Github?

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Failed to load resource: the server responded with a status of 500
(Internal Server Error)

I published my project and loaded to server. However I get exception
Failed to load resource: the server responded with a status of 500
(Internal Server Error)

Friday, 13 September 2013

Google speech api through wget, stuck at "HTTP request sent, awaiting response"

Google speech api through wget, stuck at "HTTP request sent, awaiting
response"

I am attempting to send a .flac file to Google, to use their speech to
text application. I am using information based of this Gist.
I started off by recording my .wav and converting it to a .flac:
arecord -D hw:1,0 -f cd -t wav -d 4 -r 16000 -c1 | flac - -f --best
--sample-rate 16000 -o /dev/shm/out.flac 1>/dev/shm/voice.log
2>/dev/shm/voice.log;
Then I attempted to send that new file, out.flac, to Google via wget:
wget -O 'recognized.json' -o /dev/null --post-file /dev/shm/out.flac
--header="Content-Type: audio/x-flac; rate=16000"
http://www.google.com/speech-api/v1/recognize?lang="en-US"
I cant seem to get any response from Google's api:
Connecting to www.google.com (www.google.com)|173.194.115.191:80...
connected.
HTTP request sent, awaiting response... No data received..
Retrying.
I am not sure what I have done wrong at this point.

Animation Using To Much Memory iOS7

Animation Using To Much Memory iOS7

I have a series of .png images loaded into an animation, which works fine,
but when I switch to another view, the memory that the animation uses is
not freed up. Which takes up more and more memory every time you return to
that view until eventually the app quits due to too much memory pressure.
Is there anything I can put in view diddisappear or another method to free
this memory from the animation when the view is changed?
Also this only seems to happen in with my 4S running iOs 7. On my 4S with
6.1.2 it runs smoothly.

HTML Symbol Entity - How to Float

HTML Symbol Entity - How to Float

How do you allow for a HTML symbol entity to float fixed to the browser
screen. It is for a Sign-In page and I want to have a down arrow float
next to a sign in link roughly 25px from left and 10 px from top in the
corner of the page. Thank you

ForkJoinPool.getActiveThreadCount() overestimating thread count

ForkJoinPool.getActiveThreadCount() overestimating thread count

Why ForkJoinPool.getActiveThreadCount() can overestimate the number of
threads? While the ForkjoinPool itself doesnt describe the real reason, it
appears that the rest state of the computing thread (while waiting for the
forked one to join) may be causing it. Not sure why this occurs.

How do I print just the even or odd chars in an array?

How do I print just the even or odd chars in an array?

Lets say I have string: 'firetruck'. And I split that string up into the
individual letters and put them into an array called T for example. So now
T[] looks like {f,i,r,e,t,r,u,c,k}. How can I just print the even chars so
my print statement looks like 'frtuk' and the odd looks like 'ierc'. This
is what I got so far:
import java.util.Scanner;
import java.util.Arrays;
public class StringFun {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String even_odd = sc.next();
char[] t = even_odd.toCharArray();
System.out.println(Arrays.toString(t));
//I can't get this next part to work.
for(int i = t[0]; i < t.length; i = i + 2){
System.out.println(Arrays.toString(t[i]));
}
}
}

Thursday, 12 September 2013

Operations with cell array

Operations with cell array

I have 1153 cells that have different values. I was wondering how should I
take for instance the log,sum for the cells separately. I was trying
something lile: S=cellfun(@log,price) but is not working.

Logic In Random Generation

Logic In Random Generation

<?php
$gender = array(
'Male'=>30,
'Female'=>50,
'U' =>20);
$total = array_sum(array_values($gender));
$current = 0;
$rand = rand(1,$total);
foreach ($gender as $key=>$value)
{
$current += $value;
if ($current > $rand)
{
echo $key;
break;
}
}
?>
At the moment I am trying to generate a random value based on a weighted
percentage. In this example, Male has a 30% chance, female 50 and U 20%
chance. I had a feeling that the logic in the code was wrong, so I ran
script a 100 times, and normally you would get 30 Males, however that
wasn't the case. Is there a smarter way to do this?

Creating child records with Ember-Model

Creating child records with Ember-Model

I've been wrestling with what should be a simple task, using Ember-Model +
Ember.js + Ember-Model-Firebase-Adapter to create child records of a
parent record.
Can anyone provide a quick example of creating a Post and creating related
Comment too boot? Currently on mobile so I can't provide the code I've
been toying with, but later I can. I've been receiving a can't call save
on undefined error when attempting
post. get('comments').save();
I've tried defining post by
var post = App.Post.find();
But this is incorrect. I'm overlooking something simple, any insight or
quick examples out there? Would really appreciate some help.
[EDIT]
Thanks for the help so far. Currently getting an error which I'm looking
into:
Uncaught TypeError: Object [object Object] has no method 'create'
Here's my current controller:
App.PostController = Ember.ObjectController.extend({
newMessage: null,
actions: {
saveComment: function() {
var post = App.Post.create();
var comment = post.get('comments').create({message:
this.get('newMessage')});
comments.save();
post.save();
this.set('newMessage', null);
}
}
});
Should I be setting it as an array controller?
Here are my models:
App.Post = Ember.Model.extend({
id: attr(),
name: attr(),
comments: Ember.hasMany("App.Comment", {key: 'comment_ids'})
});
App.Game.url = "/posts";
App.Comment = Ember.Model.extend({
id: attr(),
message: attr(),
post: Ember.belongsTo('App.Post', {key: 'post_id'})
});
App.Comment.url = "/comments";

How to use JFileChooser to find a file location

How to use JFileChooser to find a file location

Is there a method that i can use to simply find a file location? I'm
trying allow the user to choose a file and open it, but I have to have the
JFileChooser just choose the file and send the location to another method.
What's the best way to do this?

Shared Preferences not passing data between activities

Shared Preferences not passing data between activities

I've had this issue for a few days now. It would seem that my shared
preferences is not working for when I set my data. The user starts at
main, which displays "oncreate" and then goes to the settings page(Where
the data is automatically set(for now)), when they return to the main
Activity, the data doesn't seem to want to come over. I am using the joda
Time library and I'm trying to calculate the difference between two dates
in time.
Main:(The onCreate Code and onResume code are the same)
public class MainActivity extends Activity {
TextView tv;
Button set;
//CONST
final static long MILLIS_IN_DAY = 86400000;
final static long MILLIS_IN_HOUR = 3600000;
final static long MILLIS_IN_MINUTE = 60000;
long day, hour, minute;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textViewx);
set = (Button) findViewById(R.id.setting);
tv.setText("ONCREATE!");
//LOAD DATA
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
long loadedTime = prefs.getLong("quitDate", 0); //Load Settings Data
boolean test = prefs.getBoolean("test", false);
//get Comparison Data
DateTime newDate = new DateTime();
long updateTime = newDate.getMillis();
long diffInMillis = (updateTime-loadedTime);
//Calculate
minute = (diffInMillis/MILLIS_IN_MINUTE)%60;
hour = (diffInMillis/MILLIS_IN_HOUR)%24;
day = (diffInMillis/MILLIS_IN_DAY);
tv.setText(""+Long.toString(loadedTime));
if(test==true){
tv.setText("" + "\nDay|Hour|Minute: " + Long.toString(day)
+":" + Long.toString(hour) + ":" + Long.toString(minute));
}
set.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent x = new Intent(MainActivity.this, Settings.class);
startActivity(x);
}
});
Settings:
import org.joda.time.DateTime;
import android.content.SharedPreferences;
public class Settings extends Activity implements View.OnClickListener {
Button bAbout,bSettings,bFacebook;
//(5000);
final long MILLIS_IN_DAY = 86400000;
final long MILLIS_IN_HOUR = 3600000;
final long MILLIS_IN_MINUTE = 60000;
//Variables
long loadedTime;
int packs;
float cost;
long day, hour, minute, second;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Settings");
setContentView(R.layout.activity_settings);
setUpButtons();
DateTime d1 = new DateTime(2013,9,11,0,0);
long today = d1.getMillis();
//SAVE DATA
SharedPreferences.Editor editor =
getPreferences(MODE_PRIVATE).edit();
editor.putLong("quitDate", today);
editor.putBoolean("test", true);
editor.commit();
minute = (today/MILLIS_IN_MINUTE)%60;
hour = (today/MILLIS_IN_HOUR)%24;
day = (today/MILLIS_IN_DAY);
TextView tv = (TextView) findViewById(R.id.TEMPDATE);
TextView tv2 = (TextView) findViewById(R.id.todayis);
tv2.setText("Today is: " + Long.toString(today));
}

ActionMailer sending incorrect mimetype

ActionMailer sending incorrect mimetype

I'm using ActionMailer without rails to send multipart emails, but the
html component is being sent with the mimetype "text/plain".
I have templates/mailer/welcome.html.erb and
templates/mailer/welcome.text.erb, and if I run the following code it
raises the error (ie. it has no text/html part)
What am I doing wrong?
require 'action_mailer'
ActionMailer::Base.view_paths = "templates"
class Mailer < ActionMailer::Base
default :from => "me@example.com"
def welcome(variables = {})
@variables = variables
mail(
:to => variables['to'],
:subject => variables['subject'] || "Welcome!"
)
end
end
email = Mailer.welcome({'to' => 'you@example.com'})
raise RuntimeError, "There is no HTML part!" unless email.to_s =~
/text\/html/

facebook open graph second attempt after editing the object

facebook open graph second attempt after editing the object

I use facebook open graph to publish. If the object is modified. Let's say
the image of the object and the story is published again the action is
published on facebook but appear the image from the first published story.
Any ideea? Thx Radu B.

Intellij IDEA can't generate WSDL from JAVA

Intellij IDEA can't generate WSDL from JAVA

I'm trying to generate wsdl from java class in Intellij IDEA.
But i get the following error:
Error: Could not find or load main class org.apache.axis.wsdl.Java2WSDL
Could anyone help me solve this issue please?

Wednesday, 11 September 2013

ios7 view height error

ios7 view height error

Im playing with ios7 now, find that my view bounds became full screen eg.
before 320*460 now 320*480 with 20px status bar over my view, I know ios7
starts to support full screen layout, and has a
self.edgesForExtendedLayout = UIRectEdgeNone;
to set, but, this line seems work only when the navigation bar is shown,
i cant upload screenshots, and in ios6 view seems normal, and 320*460, in
ios7 its 320*480, status bar covers view contents, if I use a navigation
bar and set self.edgesForExtendedLayout = UIRectEdgeNone; view frame
became 320*416, leaves 20 for status bar and 44 for nav bar, but my app is
a custom top bar, not using navigation bar here.
if change the frame of window, window moves down by 20 px, but status bar
seems clipped and a black 320*20 bar is shown,
any method to make both iOS 6 and ios7 happy?

Horizontal UIScrollView in a UITableViewCell

Horizontal UIScrollView in a UITableViewCell

I'm trying to create a simple scrollView inside a tableview cell. Just
like on app store, but with simpler scrolling.
The scrollview is showing up but its not scrolling at all. I've tried
whole first page on google and many stackoverflow questions, can't seem to
find what I'm doing wrong.
if (indexPath.row==0) {
// Clearing out cell background
[cell setBackgroundColor:[UIColor clearColor]];
[cell.contentView setBackgroundColor:[UIColor clearColor]];
// Imageviews for scrollview
UIImageView *imageview1 = [[UIImageView alloc]
initWithFrame:CGRectMake(0,0,320,123)];
UIImageView *imageview2 = [[UIImageView alloc]
initWithFrame:CGRectMake(320,0,320,123)];
imageview1.image = [UIImage imageNamed:@"flash2.png"];
imageview2.image = [UIImage imageNamed:@"IMG_2458.JPG"];
// setting up scrollview
self.scrollViewHeader = [[UIScrollView alloc]
initWithFrame:CGRectMake(0,0,320, 123)];
self.scrollViewHeader.scrollEnabled = YES;
self.scrollViewHeader.delegate = self;
[self.scrollViewHeader setUserInteractionEnabled:YES];
[self.scrollViewHeader setContentSize:CGSizeMake(320, 123)];
[self.scrollViewHeader addSubview:imageview1];
[self.scrollViewHeader addSubview:imageview2];
[cell.contentView addSubview:self.scrollViewHeader];
}
else{
// Normal table cells.
...
}
Thanks in advance for your answers.

Multiple dates picker that allows for weekday selection

Multiple dates picker that allows for weekday selection

I'd like to have a datepicker widget that allows for:
multiple date selection
weekday selection, i.e. click "monday" in the calendar and have all
mondays highlighted.
unselecting days that have been highlighted by using the weekday selection
I've looked into Keith Wood's jQuery datepicker and into MultiDatesPickr,
but my JavaScript is very weak and I'm not completely sure of what I have
to do next to extend one of these datepickers and implement this kind of
functionality.
One other option would be to have standard checkboxes outside the input
field, each labeled as a day of the week, and clicking them would
highlight the relevant days in the calendar.
Not sure if it's entirely relevant or useful information, but I'm using
Django 1.5 as the backend and trying to use this as a custom Admin Form
widget.

How to add CSS if element has more than one child?

How to add CSS if element has more than one child?

I have td tags and a several div inside td:
<td>
<div class='test'></div>
<div class='test'></div>
</td>
<td>
<div class='test'></div>
</td>
I want to add margin-bottom to div if there are more than one in the td.
How can I do this with the css?

Tuesday, 10 September 2013

Rails server doesn't work, won't be visited, and won't stop

Rails server doesn't work, won't be visited, and won't stop

It just happened today, after I fired up rails s, it can't be visited, and
I also can't stop rails server with Ctrl-C. It displays Stoping... but
just stays like that?
After fired up rails s server it looks really correct.
¨ rails s
WARNING: Nokogiri was built against LibXML version 2.8.0, but has
dynamically loaded 2.9.1
=> Booting Thin
=> Rails 3.2.14 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
>> Thin web server (v1.5.1 codename Straight Razor)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:3000, CTRL+C to stop
But when I try to visit 127.0.0.1:3000, this browser keeps loading and
nothing happens in the console, it seems that the rails process hasn't get
the request.
I tried the port, it's opened:
¨ telnet 127.0.0.1 3000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'
And when I tried to stop rails server with Ctrl-C, it just won't stop!
¨ rails s
WARNING: Nokogiri was built against LibXML version 2.8.0, but has
dynamically loaded 2.9.1
=> Booting Thin
=> Rails 3.2.14 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
>> Thin web server (v1.5.1 codename Straight Razor)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:3000, CTRL+C to stop
^C>> Stopping ...
^C>> Stopping ...
^C>> Stopping ...
^C>> Stopping ...
^C>> Stopping ...
^C>> Stopping ...
Why is that, and how should I trouble shoot this.
I am on Mac OSX Mountain Lion, 10.8.4 Build 12E55, ruby 1.9.3-p327-falcon,
rails 3.2.14
Need help..

Java Scanner Error : Exception in thread "main" java.util.NoSuchElementException: No line found

Java Scanner Error : Exception in thread "main"
java.util.NoSuchElementException: No line found

I am trying to get user input but I keep getting the error: No Line Found
The line number is referencing "input = fileS.nextLine();" as the source
of the error
System.out.print("Is this table a simple table? Please check document to
confirm, If YES please Enter Y If NO please Enter N \n");
Scanner fileS = new Scanner(System.in);
input = fileS.nextLine();
input = input.trim();
input = input.toLowerCase();
tableCount ++;
fileS.close();
That is my code, I understand that if I used fileS.hasNextLine() it would
avoid this error But this skips the user input all together.
What am I missing here?
The scanner is in a public function
Thanks in advance!

How to get Java to return an exact value to a calculation as opposed to a decimal form?

How to get Java to return an exact value to a calculation as opposed to a
decimal form?

How would I return an exact value to a calculation, ie: 4*sqrt(3) as
opposed to the decimal form?

Displaying and Uploading an image in MVC

Displaying and Uploading an image in MVC

I have an MVC application and I want to create a page that lets me upload
an image to it. In the same page I also want the image to be displayed.
I have read tutorials/resources online and not a solution yet of yet and
not to sure on a solution,
Any help would be greatly appreciated,
Nick

Visual studio 2010: Break when memory address has changed

Visual studio 2010: Break when memory address has changed

I'm debugging using visual studio 2010. I want to break when a memory
address has changed. It means, I have a memory address, which can be
changed in hundreds of places in the code. I want to find the place in the
code when it is actually changed. How can I do it?
Thanks

how to change the color of listview in android

how to change the color of listview in android

Hi guys I need a little help here , I want to change the color of the
listview in my android application , the default color is white with black
text , I need the listview in black with text color white , I have tried
so many methods but it was not working , can anybody help me for a working
solution....

#EANF#

#EANF#

I'm trying to get rid of a certificate warning. I have the following code
that executes before anything else, and forces the user to the https
version of the URL:
if((!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "") &&
($_SERVER['REMOTE_ADDR'] != '127.0.0.1')){
$redirect = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
header("Location: $redirect");
exit();
}
This redirects to the correct URL, but it seems to leave an SSL warning in
its wake:

In the console I get this:
(The page at https://mysite.com/special-offer/ displayed insecure content
from http://mysite.com/special-offer/.)

However if I visit the url ($redirect) directly, no SSL warning is given.
All resources are being served over https.

Monday, 9 September 2013

How to determine similarity between source and mutliple strings in python?

How to determine similarity between source and mutliple strings in python?

Assuming I have the following source string:
Humpty dumpty <span id="1">sat</span> on a wall, humpty dumpty had a great
fall. All of <span id="two">the kings</span> horses and all the kings men.
and a few other strings in a list, each string is separated by a new line:
Humpty dumpty sat on a wall, humpty dumpty had a great fall. All of the
kings horses and all the kings men.
Humpty dumpty sat on the wall, all of the kings horses and all the kings men.
There is a humpty dumpty who had sat on the wall, and all of the kings
horses and all the kings men.
Humpty dumpty sat on some wall, humpty dumpty had a great fall. All of the
kings horses and all the kings men couldn't put him together again.
Humpty dumpty this is a completely related sentence.
I want to be able to starting with the target string, find out which of
the "other strings in the list" that most closely match the source string
using python. Is there some best way to come up with some "score" in the
comparison between the source string and target string pairs and based on
some criteria be able to determine which string is most closely matched to
the source string? (In this case, the string most similar should be the
1st string, as it is the source string without any of the "".

AS3 Is there a simple way of creating this array?

AS3 Is there a simple way of creating this array?

I'll have some task for the user to do, so I'll make an Array(false,
false, false, ... number of tasks) and each element will become true when
completed, so I'll know when all will be completed and witch one is still
incomplete. Usually I create an int to count the tasks when created, and
that decrease, but I need to control each item this time (you didn't
complete this one...), not only the global progress.
So, I got only the number of tasks:
var Ctrl:Array = new Array();
for(var i=0; i<numberOfTasks; i++){ Ctrl.push(false); }
If I have a lot of tasks, this way may take a while freezing the
execution. Is there some "automatic" way?

scala pattern matching nested cases

scala pattern matching nested cases

I try to match after some case applied. Kind of nested cases/matches:
val x1 = 1
val str = x1 match { // scala.MatchError: 1 (of class java.lang.Integer)
case x if(x > 1) => "x"+x match {case "x1" => "yes"}
}
println (str)
It fails with scala.MatchError exception.
Is it possible? It seems I've seen something similar.

Is the use of records the solution to all latch problems in VHDL

Is the use of records the solution to all latch problems in VHDL

I was recently told that the solution to all (most) problems with
unintended latches during VHDL synthesis is to put whatever the
problematic signal is in a record.
This seems like it's a little bit too good to be true, but I'm not that
experienced with VHDL so there could be something else that I'm not
considering.
Should I put all my signals in records?

Android: ListView Multiple Selection

Android: ListView Multiple Selection

Problem:
When i click on the 2nd checkbox item in the listview then automatically
10th item is checked. I can not understand what's happen?
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TextView;
public class ItemAdapter extends ArrayAdapter<MyItem> {
private int resId;
Context context;
private ArrayList<MyItem> itemList;
public ItemAdapter(Context context, int textViewResourceId,
List<MyItem> objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.resId = textViewResourceId;
this.itemList = new ArrayList<MyItem>();
this.itemList.addAll(objects);
}
private class ViewHolder {
public boolean needInflate;
public TextView txtItemName;
public CheckBox chkItem;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
MyItem cell = (MyItem) getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem, null);
holder = new ViewHolder();
holder.txtItemName = (TextView) convertView
.findViewById(R.id.tvItemName);
holder.chkItem = (CheckBox) convertView.findViewById(R.id.chkItem);
holder.chkItem
.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
//Log.i("Pos", "" + position);
//cell.setSelected(buttonView.isChecked());
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtItemName.setText(cell.getName());
return convertView;
}
}
"MyItem" is my pojo Class.
OnCreate Code:
lvItemName = (ListView) findViewById(R.id.lvItemName);
List<MyItem> myItemsList = new ArrayList<MyItem>();
for (int i = 0; i < items.length; i++) {
MyItem item = new MyItem(items[i], false);
myItemsList.add(item);
}
ItemAdapter adapter = new ItemAdapter(this, R.layout.listitem,
myItemsList);
lvItemName.setAdapter(adapter);
lvItemName.setOnItemClickListener(this);
"items" is my String Array.
Thanks in Advance.

Sqlite table creation does not allow to create table

Sqlite table creation does not allow to create table

@Override
public void onCreate(SQLiteDatabase db) {
final String CREATE_IMAGE_TABLE = "CREATE TABLE " + TABLE_IMG + "("
+ KEY_ID + " INTEGER PRIMARY KEY autoincrement," +
KEY_IMAGE_NAME + " TEXT,"
+ KEY_PATH + " TEXT" + ")";
final String CREATE_TAG_TABLE = "CREATE TABLE " + TABLE_TAG + "("
+ KEY_ID + " INTEGER PRIMARY KEY autoincrement," +
KEY_TAG_NAME + " TEXT,"
+ KEY_TAG_DATE + " INTEGER" + ")";
final String CREATE_IMAGE_TAG_TABLE = "CREATE TABLE " +
TABLE_IMAGE_TAG + "("
+ IMAGE_ID + " INTEGER REFERENCES CREATE_IMAGE_TABLE(id)," +
TAG_ID + " INTEGER REFERENCES CREATE_TAG_TABLE(id),"
+ IMG_TAG + " PRIMARY KEY (IMAGE_ID, TAG_ID) " + ")";
db.execSQL(CREATE_IMAGE_TABLE);
db.execSQL(CREATE_TAG_TABLE);
db.execSQL(CREATE_IMAGE_TAG_TABLE);
Log.i("TAG", "TABLES CREATED" + CREATE_IMAGE_TAG_TABLE);
}
Hello All
I am trying to create 3 tables with image data, tag data and 3rd having
the id's of image and tag data into it. I want to create 3rd table with
the references of image table's Id and tag table's Id which are both
primary key's in their own table. Now if i want to add id's values of
these tables into my third table i have fired the query as above but it
does not let me create it. It gives me syntax error:
09-09 13:12:48.520: E/Database(3944): Failure 1 (near "(": syntax error)
on 0x220680 when preparing 'CREATE TABLE img_tag(img_id INTEGER REFERENCES
CREATE_IMAGE_TABLE(id),tag_id INTEGER REFERENCES
CREATE_TAG_TABLE(id),img_tag PRIMARY KEY (IMAGE_ID, TAG_ID) )'.

Sunday, 8 September 2013

Getting the Information about folder of alfresco using java application

Getting the Information about folder of alfresco using java application

I have a my web appliacation which run on one server and alfresco
application on another server.Now we are opening the alfresco share page
using single-sign on.I want that if user click on particular folder then
the information about that folder should be avilble to my web
application.Is it possible to do so? Yes then how? and No then Why?
Please if any body have any idea then reply as early as possible.

Excel find similar cells from another sheet and copy and paste those rows under first sheet cell

Excel find similar cells from another sheet and copy and paste those rows
under first sheet cell

I have two excel sheets with a lot of rows.. This is what I need.
**A B C E F G**
abc test1 123 dfg 369 258
adf test2 345 mmm 896 147
mmm test3 256 mmm 852 951
**Sheet 1 Sheet 2**
What I need
**A B C F G**
abc test1 123
adf test2 345
mmm test3 256
mmm 896 147
mmm 852 951
Hope I don't have to explain in word.. can someone tell me how to do this???

Add a table to existing pdf itextsharp with pdfStamper and vb or c#

Add a table to existing pdf itextsharp with pdfStamper and vb or c#

I want to use a function to insert a table to a existing pdf like:
Private Shared Function wTable(ByVal cols As Integer) As
iTextSharp.text.Table
Dim table As New iTextSharp.text.Table(cols)
With table
.WidthPercentage = 100
.BorderWidth = 0
.Cellpadding = 1
.Cellspacing = 0
.TableFitsPage = False
.CellsFitPage = True
.AutoFillEmptyCells = True
.Widths = New Single() {20, 80}
End With
Dim font As iTextSharp.text.Font = font8
Dim fontBold As iTextSharp.text.Font = font8Bold
Dim c As Cell = New Cell(New Phrase("Allacci Sparsi", fontBold))
c.SetHorizontalAlignment("center")
table.AddCell(c, 0, 0)
Dim str As String = "Il termine di esecuzione dei lavori è
stabilito all'art. 14 del Foglio Condizioni e di seguito definiti
in Tabella 1. " _
& "All'art. 16 del 'Foglio Condizioni' sono
definiti i riferimenti per l'applicazione
delle penali in caso di ritardo
nell'esecuzione delle opere richieste. " _
& " All'art. 17 del 'Foglio Condizioni'
sono definiti i criteri per l'incentivo
sulla celerità di intervento."
c = New Cell(New Phrase(str, font))
c.SetHorizontalAlignment("left")
table.AddCell(c, 0, 1)
Return table
End Function
then call it using stamper like:
Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
Dim stamper As iTextSharp.text.pdf.PdfStamper = Nothing
Dim cb As iTextSharp.text.pdf.PdfContentByte = Nothing
Dim rect As iTextSharp.text.Rectangle = Nothing
Dim pageCount As Integer = 0
Try
reader = New iTextSharp.text.pdf.PdfReader(sourcePdf)
rect = reader.GetPageSizeWithRotation(1)
stamper = New iTextSharp.text.pdf.PdfStamper(reader, New
System.IO.FileStream(outputPdf, IO.FileMode.Create))
cb = stamper.GetOverContent(1)
Dim ct = New ColumnText(cb)
ct.Alignment = Element.ALIGN_CENTER
ct.SetSimpleColumn(36, 36, PageSize.A4.Width - 36, PageSize.A4.Height
- 300)
ct.AddElement(wTable(2))
ct.Go()
stamper.Close()
reader.Close()
Catch ex As Exception
Throw ex
End Try
However program throws exepction saying: "Element is not allowed".
I have seen an example inserting table, but they do not use pdfstamper
here they use
doc.Open()
...
doc.Add(table)
...
doc.Close()
How to add a table using pdfstamper with itextsharp, in c# or even in vb?

How do you create an index on the tables themselves in a database?

How do you create an index on the tables themselves in a database?

I'm using APSW to wrap my SQL code in python, like so:
connection=apsw.Connection("dbfile"); cursor=connection.cursor()
cursor.execute("create table foo(x,y,z)")
cursor.execute("create table bar(a,b,c)")
cursor.execute("create table baz(one,two,three)")
I plan on using a gui framework to display these table names (and
subsequently their columns and rows). I would also like to sort these
table names by different criteria.
Is there a way to create an index on the tables themselves to be used for
sorting--e.g.:
cursor.execute("CREATE INDEX index_name ON foo")
Thanks in advance.

2D array isn't created as expected in C#

2D array isn't created as expected in C#

In a simple C# console application I have the following:
class Program
public static void Main()
{
string s = Console.ReadLine(); //User enters the string: "integer,
space, integer". Eg., "3 3"
string[,] myArray = new string[s[0], s[0]];
..
..
..
}
Upon debugging, the value of myArray will show string[53, 53], but I'm
expecting string[3, 3]. However, if I Console.WriteLine(s[0]), it prints
"3".
I've tried
string[,] myArray = new string[(int)s[0], (int)s[0]];
with the same result.
Where are the 53's coming from?

std::tr1::bind compile error binding to gluDeleteQuadric()

std::tr1::bind compile error binding to gluDeleteQuadric()

I'm using VS2008 with std::tr1 installed. Here's a stripped down program
that's not compiling:
#include <functional>
#include <windows.h>
#include <GL/glu.h>
void takeQuadric(GLUquadric* obj) {}
int main()
{
std::tr1::bind(&takeQuadric,std::tr1::placeholders::_1);
std::tr1::bind(&gluDeleteQuadric,std::tr1::placeholders::_1); // error
C2825: '_Fty': must be a class or namespace when followed by '::'
return 0;
}
The second bind call fails, probably because the function is declared with
APIENTRY:
void APIENTRY gluDeleteQuadric (
GLUquadric *state);
My WinDef.h says that APIENTRY is WINAPI and that WINAPI is __stdcall

#define WINAPI __stdcall
...
#define APIENTRY WINAPI
Anyone know why it fails to bind and if there is a way I can bind directly
to gluDeleteQuadric?

How to group by seconds without the ISODate decimal part in MongoDB

How to group by seconds without the ISODate decimal part in MongoDB

I wanted to query the database in order to find the number of post per
second to feed into a graph to show activity trend. I use
spring-data-mongo but for now, the first step is to do this in the mongo
shell before worrying about how to do from java.
I used the aggregation framework on it as shown below:
db.post.group({
key:{dateCreated: 1},
cond: { dateCreated:
{
"$gt": new ISODate("2013-08-09T05:51:15Z"),
"$lt": new ISODate("2013-08-09T05:51:20Z")
}
},
reduce: function(cur, result){
result.count += 1
},
initial: {count:0}
})
The result is encouraging but is seems because of the decimal part of the
ISODate, the count seems wrong as it does group per seconds with the
decimal making each count 1.
[
{
"dateCreated" : ISODate("2013-08-09T05:51:15.332Z"),
"count" : 1
},
{
"dateCreated" : ISODate("2013-08-09T05:51:15.378Z"),
"count" : 1
},
{
"dateCreated" : ISODate("2013-08-09T05:51:15.377Z"),
"count" : 1
},
// many more here
]
Is there a way to just consider only the seconds part as in result like
below:
[
{
"dateCreated" : ISODate("2013-08-09T05:51:15Z"),
"count" : 5
},
{
"dateCreated" : ISODate("2013-08-09T05:51:16Z"),
"count" : 8
},
{
"dateCreated" : ISODate("2013-08-09T05:51:17Z"),
"count" : 3
},
{
"dateCreated" : ISODate("2013-08-09T05:51:18Z"),
"count" : 10
},
{
"dateCreated" : ISODate("2013-08-09T05:51:19Z"),
"count" : 2
},
{
"dateCreated" : ISODate("2013-08-09T05:51:20Z"),
"count" : 13
}
]
Thank for reading this.

Saturday, 7 September 2013

How can I find unknown number x between specific numbers?

How can I find unknown number x between specific numbers?

Given Values
Min number=2
Max Number=50
increment number=7
x=? needs to be find.
If the correct answer is one of below...How can I find the correct number
that guessed. using given values...
(2,9,16,23,30,37,44)
If this question is hard than, answer below question... :) it is same thing
I would just like to know if it is possible to truncate a sequence to
reset back to its original starting number? in Oracle
Query:
select DBMS_METADATA.GET_DDL('SEQUENCE','SEQ') from dual
Result doesnt give me the original start with value, it only gives the
current value
CREATE SEQUENCE "SEQ" MINVALUE 2 MAXVALUE 50 INCREMENT BY 7 START WITH
9 CACHE 20 NOORDER NOCYCLE

How to set position for dialog created via JavaScript

How to set position for dialog created via JavaScript

HTML:
<a href="www.google.com">Link</a>
JavaScript
$(document).ready(function() {
$(document.body).on('click',"a",function(event){
if ($(this).hasClass('ui-dialog-titlebar-close')) return;
event.preventDefault();
var data = '<div id="dialog" title="Basic dialog">';
data += '<p>Hello.</p></div>';
$(data).dialog();
});
});
I want to set a position for this dialog. I've tried changing
$(data).dialog(); to $(data).dialog('option', 'position', [200,300]);, but
it doesn't work. How can I set it?
jsFiddle: http://jsfiddle.net/fcTcf/

Dynamic Routing with two Dashes in path AngularJS

Dynamic Routing with two Dashes in path AngularJS

I have an interesting problem, I have this rule for routing
'/upload_image/:lat-:lng' , where lat and lng are geo-coordinates
when i try to access with a path like this
(/upload_image/42.04648822804604--71.65695190429688" where the first dash
is the separator between lat and lng as defined in the rule above, but
what happens actually when i try to access $routeParams lat =
42.04648822804604- and lng = 71.65695190429688, this is false coordinates,
angularjs took the second dash as separator between two parameters
according to the rule above, any solution to make it pick up the first
dash always? ( i know i can use other separator than dash but interested
to know if there is a solution + dash is nicer although).

Creating Java Proxy MITM

Creating Java Proxy MITM

I'm trying to create a Java program as a proxy to view packets from an
incoming source to debug. To do this, I have created a simple Java server
application and have edited my host file on the device. Everything works
fine as of now, (even my Relay class file) but I am trying to make it into
a full fledged proxy. How could I incorporate elements to send data to the
server, and send the response back to the client? Sort of like a
Man-In-The-Middle type of thing.
import java.net.*;
import java.io.*;
import org.ini4j.Ini;
public class RelayMultiClient extends Thread {
private Socket socket = null;
Socket relay = null;
public RelayMultiClient(Socket socket) {
super("RelayMultiClient");
this.socket = socket;
}
public void run() {
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
if(Relay.max_clients == Relay.connected_clients) {
//There are too many clients on the server.
System.out.println("Connection refused from " +
socket.getRemoteSocketAddress() + ": Too many clients
connected!");
out.close();
in.close();
socket.close();
}
else {
Ini ini = new Ini(new File("settings.ini"));
Relay.connected_clients++;
System.out.println("Connection from client " +
socket.getRemoteSocketAddress() + " established. Clients
Connected: " + Relay.connected_clients);
while (in.readLine() != null) {
//Send data to the server
//Receive data from server and send back to client
}
System.out.println("Connection from client " +
socket.getRemoteSocketAddress() + " lost.");
Relay.connected_clients--;
out.close();
in.close();
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks, Chris

copying structure into array

copying structure into array

I am new in coding and facing problem in copying float value of structure
element and passing in the int transmit_buffer[12]. please help with this.
#include <stdio.h>
#include <string.h>
int i;
main(){
int transmit_buffer[12];
struct TX_REPORT{
int variable1;
float variable2;
int variable3;
int variable4;
int variable5;
int variable6;
};
struct TX_REPORT transmit_report = {1, 1.5, 40, 1, 45, 7};
memcpy(transmit_buffer, &transmit_report, sizeof transmit_buffer);
for(i=0;i<6;i++){
printf("%d\n",transmit_buffer[i]);
}
}

Stripe_ruby Unable to store card_last4 and card_type after successful customer creation

Stripe_ruby Unable to store card_last4 and card_type after successful
customer creation

After creating a customer successfully, I can inspect the object with:
Rails.logger.debug("single card object has:
#{customer.cards.data.card.inspect}")
which returns a json like this:
#<Stripe: : Customer: 0x2801284>JSON: {
"id": "cus_2WXxmvhBJgSmNY",
"object": "customer",
"cards": {
"object": "list",
"data": [
{
"id": "card_2WXxcCsdY0Jjav",
"object": "card",
"last4": "4242",
"type": "Visa",
"exp_month": 1,
"exp_year": 2014,
}
]
},
"default_card": "card_2WXxcCsdY0Jjav"
}
But I will do Customer.cards.data.last4 it gives a NOMethodError.
If I remove the last4 and just call Customer.cards.data, it gives
#<Stripe: : Card: 0x1ed7dc0>JSON: {
"id": "card_2Wmd80yQ76XZKH",
"object": "card",
"last4": "4242",
"type": "Visa",
"exp_month": 1,
"exp_year": 2015,
}
Now I seem to have the direct card object but if I do
card = Customer.cards.data
self.last4 = card.last4
I still get a noMethodError
Here is shortened version of my model:
class Payment < ActiveRecord::Base
def create_customer_in_stripe(params)
if self.user.stripe_card_token.blank?
user_email = self.user.email
customer = Stripe::Customer.create(email: user_email, card:
params[:token])
card = customer.cards.data
self.card_last4 = card.last4
self.card_type = card.type
self.card_exp_month = card.exp_month
self.card_exp_year = card.exp_year
self.user.save
end
self.save!
end
end

Friday, 6 September 2013

Ruby on Rails - adding a string in front of a parameter for a from

Ruby on Rails - adding a string in front of a parameter for a from

I want to add a string in front of a paramemter on my form so that when
the user submits something on the form my client will get an email saying
Hello from [:username]
so ive tried this in my view
= f.text_field "Hello From, #{:username}"
but it does not work
i;ve also tried to use a value
= f.text_field :subject, value: "Hello From, #{:username}"
but that doesent work either

Django getting lots of SuspiciousOperation: Invalid HTTP_HOST header

Django getting lots of SuspiciousOperation: Invalid HTTP_HOST header

I'm using Django 1.5, Apache, mod_wsgi and python 2.7, debian hosted on
linode.
Since I upgraded from django 1.3 to django 1.5, I started receive some
error messages, for example: "ERROR (EXTERNAL IP): Internal Server Error:
/feed/". With this traceback:
Traceback (most recent call last):
File
"/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py",
line 92, in get_response
response = middleware_method(request)
File
"/usr/local/lib/python2.7/dist-packages/django/middleware/common.py",
line 57, in process_request
host = request.get_host()
File "/usr/local/lib/python2.7/dist-packages/django/http/request.py",
line 72, in get_host
"Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): %s" %
host)
SuspiciousOperation: Invalid HTTP_HOST header (you may need to set
ALLOWED_HOSTS): tadjenanet.montadamoslim.com
But, a few days ago, the volume of this errors increased greatly, and for
a lot of url's that I don't even have in my website.
I saw the answers here(Django's SuspiciousOperation Invalid HTTP_HOST
header) and I understand why I'm getting this, but I need to know how to
avoid this increasing my server security.

Django passing view url variables inside a template

Django passing view url variables inside a template

I feel like this is going to be an embarrassing question but I can't find
the answer I've tried google but I am getting fairly frustrated so I just
decided to ask here. I've got this code snippet inside a template file in
django
{% url cal.views.month year month "next" %}
I run the code and get this error Reverse for 'courseCalendar.views.month'
with arguments '(2013, 9, u'next')' not found
Why is it that when I try to pass variables in a string it puts the u in
there as well. This is very frustrating and I would really appreciate
someones two cents.
Edit: Everything works fine if I don't include the string "next" and use a
variable instead like the year and month variables so it's not a url
problem or template problem.
url pattern
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'', 'courseCalendar.views.month', name='month'),
url(r'^month$', 'courseCalendar.views.month', name='month'),
)
Views
# Create your views here.
import time
import calendar
from datetime import date, datetime, timedelta
#from django.contrib.auth.decorators import login_required For login
requirements.
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from courseCalendar.models import *
monthNames = "Jan Feb Mar Apr May Jun Jly Aug Sep Oct Nov Dec"
monthNames = monthNames.split()
#@login_required This should be uncommented in the future but for now we
don't want to deal with it. Default set to 2013 for now.
def main(request, year="None"):
if year == "None":
year = time.localtime()[0]
else:
year = int(year)
currentYear,currentMonth = time.localtime()[:2]
totalList = []
for y in [year]:
monthList = []
for n, month in enumerate(monthNames):
course = current = False
courses = Course.objects.filter(courseDate__year=y,
courseDate__month=n+1)
if courses:
course = True
if y==currentYear and n+1 == currentMonth:
current = True
monthList.append(dict(n=n+1, name=month, course=course,
current=current))
totalList.append((y,monthList))
#return render_to_response("courseCalendar/Templates/main.html",
dict(years=totalList, user=request.user, year=year,
reminders=reminders(request))) <-- Later in the build
return render_to_response("main.html", dict(years=totalList,
user=request.user, year=year))
def month(request, year=1, month=1, change="None"):
if year == "None":
year = time.localtime()[0]
else:
year = int(year)
if month == "None":
month = time.localtime()[1]
else:
month = int(month)
if change in ("next", "prev"):
todaysDate, mdelta = date(year, month, 15), timedelta(days=31)
if change == "next":
mod = mdelta
elif change == "prev":
mod = -mdelta
year, month = (todaysDate+mod).timertuple()[:2]
cal = calendar.Calendar()
month_days = cal.itermonthdays(year, month)
nyear, nmonth, nday = time.localtime()[:3]
lst = [[]]
week = 0
for day in month_days:
courses = current = False
if day:
courses = Course.objects.filter(courseDate__year=year,
courseDate__month=month, courseDate__day=day)
if day == nday and year == nyear and month == nmonth:
current = True
lst[week].append((day, courses, current))
if len(lst[week]) == 7:
lst.append([])
week += 1
return render_to_response("month.html", dict(year=year, month=month,
user=request.user, month_days=lst, monthNames=monthNames[month-1]))
main.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Need to figure out how to pass the year variable properly in the url
arguements. The way it was originally written didn't work and adding
quotes appended a "u" to the areguements-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Year View</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
{% load staticfiles %}
<link rel="stylesheet" href="{% static "courseCalendar/css/layout.css" %}"
type="text/css" />
</head>
<body>
<div id="wrapper">
<a href="{% url "courseCalendar.views.main" %}">&lt;&lt; Prev</a>
<a href="{% url "courseCalendar.views.main" %}">Next &gt;&gt;</a>
{% for year, months in years %}
<div class="clear"></div>
<h4>{{ year }}</h4>
{% for month in months %}
<div class=
{% if month.current %}"month current"{% endif %}
{% if not month.current %}"month"{% endif %}
>
{% if month.entry %}<b>{% endif %}
<a href="{% url "courseCalendar.views.month" year month
"next"">{{ month.name }}</a>
{% if month.entry %}</b>{% endif %}
</div>
{% endfor %}
{% endfor %}
</div>
</body>
</html>
month.html
<a href="{% url "courseCalendar.views.month" %}">&lt;&lt; Prev</a>
<a href="{% url "courseCalendar.views.month" %}">Next &gt;&gt;</a>
<h4>{{ month }} {{ year }}</h4>
<div class="month">
<table>
<tr>
<td class="empty">Mon</td>
<td class="empty">Tue</td>
<td class="empty">Wed</td>
<td class="empty">Thu</td>
<td class="empty">Fri</td>
<td class="empty">Sat</td>
<td class="empty">Sun</td>
</tr>
{% for week in month_days %}
<tr>
{% for day, courses, current in week %}
<td class= {% if day == 0 %}"empty"{% endif %}
{% if day != 0 and not current %}"day"{% endif %}
{% if day != 0 and current %}"current"{% endif %}
{% if day != 0 %}"Add day click code here"{% endif %} >
{% if day != 0 %}
{{ day }}
{% for course in courses %}
<br />
<b>{{ course.courseCreator }}</b>
{% endfor %}
{% endif %}
{% endfor %}
</td>
{% endfor %}
</table>
<div class="clear"></div>
</div>