Saturday, 31 August 2013

AngularJS - Why select drop down doesn't have $event on change

AngularJS - Why select drop down doesn't have $event on change

I am newbie to AngularJS. I have a question, why does select doesn't
passes the $event?
HTML
<div ng-controller="foo">
<select ng-model="item" ng-options="opts as opts.name for opts in
sels" ng-change="lstViewChange($event)"
ng-click="listViewClick($event)"></select>
</div>
Script
var myApp = angular.module('myApp', []);
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
function foo($scope) {
$scope.sels = [{id: 1, name: 'a'}, {id: 2, name: 'b'}];
$scope.lstViewChange = function($event){
console.log('change', $event);
}
$scope.listViewClick = function($event){
console.log('click', $event);
}
}
Have a look at this fiddle http://jsfiddle.net/dkrotts/BtrZH/7/. Click
passes a event but change doesn't.

what python package is needed to create a virus or worm? no harm intended

what python package is needed to create a virus or worm? no harm intended

what python package is needed to create a virus or worm? I want to create
a simple virus to study ho viruses can be detected even if it is FUD and
eventually create a program for that.

How can I download a file from Google Drive?

How can I download a file from Google Drive?

I have been searching non-stop for this and have not found the answer. I
have a text file uploaded to Google Drive and want my VB application to
download it. I have tried the 'My.Computer.Network.DownloadFile' method
which downloads the html file of the file which says you are being
redirected (as google drive download link redirects you to a unique link
which expires after a period of time) and I have tried the WebClient
method which does not download the file at all. The url is along the basis
of: https://docs.google.com/uc?export=download&id=THEfileID. When I search
for the way to download from google drive on Google people say to look at
the Google drive api but I do not understand that at all. If you need any
additional information please ask. Thanks, zacy5000
Additional information: The link is not a direct download link but a link
that will redirect you to a temporary download link. I need it to download
WITHOUT being logged in to a account (the file is set to 'With url only'
in the sharing properties and it is a plain txt file.

Using exceptions for control flow

Using exceptions for control flow

I have read that using exceptions for control flow is not good, but how
can I achieve the following easily without throwing exceptions? So if user
enters username that is already in use, I want to show error message next
to the input field. Here is code from my sign up page:
public String signUp() {
User user = new User(username, password, email);
try {
if ( userService.save(user) != null ) {
// ok
}
else {
// not ok
}
}
catch ( UsernameInUseException e ) {
// notify user that username is already in use
}
catch ( EmailInUseException e ) {
// notify user that email is already in use
}
catch ( DataAccessException e ) {
// notify user about db error
}
return "index";
}
save method of my userService:
@Override
@Transactional
public User save(User user) {
if ( userRepository.findByUsername(user.getUsername()) != null ) {
LOGGER.debug("Username '{}' is already in use", user.getUsername());
throw new UsernameInUseException();
}
else if ( userRepository.findByEmail(user.getEmail()) != null ) {
LOGGER.debug("Email '{}' is already in use", user.getEmail());
throw new EmailInUseException();
}
user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
user.setRegisteredOn(DateTime.now(DateTimeZone.UTC));
return userRepository.save(user);
}

Script to detect and record network statistics?

Script to detect and record network statistics?

I am new to scripting, I have a requirement to write scripts to be used on
my MacBook pro to record data usage on my broadband connection.
My Requirements
The script should detect Internet connection is via dongle or wifi
If via dongle then record number of bytes sent and received upon every
connection
It should log to a file at regular interval
If possible summarise total number of bytes sent and received may be once
in a day from 6 am to 6am. (it can also summarise upon next start of the
system ..next start of the system could be at 10am...but once summarised
should not be considered for next run)....Or Once a month
Able to figure out total bandwidth usage ....for a month...
My question is... On Mac...which script language would be better?...Apple
script's, or shell script or using python...etc...
If possible please provide pointers for the same. Thanks in Advance

How to create Android Tabs without setContent

How to create Android Tabs without setContent

I want to have a tabbar with tabs. And I want just to catch tab pressing
to update single view. I attempt to set setContent of TabHost to null but
I've got error. How to implement this feature?

FFT returns large values which become NaN

FFT returns large values which become NaN

I'm using a FFT class to get the fundamental frequency. I'm passing an
array of some double values. Array is like queue. when add a new values
array will be updated. But my problem is output array will become large
numbers time to time. Its become E to the power value and finally returns
NaN. Im using below FFT class and I'm confused in where is the problem.
Its a big help if anyone can give a help by figuring out the cause.
here is my FFT class
public class FFT {
int n, m;
// Lookup tables. Only need to recompute when size of FFT changes.
double[] cos;
double[] sin;
double[] window;
public FFT(int n) {
this.n = n;
this.m = (int)(Math.log(n) / Math.log(2));
// Make sure n is a power of 2
if(n != (1<<m))
throw new RuntimeException("FFT length must be power of 2");
// precompute tables
cos = new double[n/2];
sin = new double[n/2];
// for(int i=0; i<n/4; i++) {
// cos[i] = Math.cos(-2*Math.PI*i/n);
// sin[n/4-i] = cos[i];
// cos[n/2-i] = -cos[i];
// sin[n/4+i] = cos[i];
// cos[n/2+i] = -cos[i];
// sin[n*3/4-i] = -cos[i];
// cos[n-i] = cos[i];
// sin[n*3/4+i] = -cos[i];
// }
for(int i=0; i<n/2; i++) {
cos[i] = Math.cos(-2*Math.PI*i/n);
sin[i] = Math.sin(-2*Math.PI*i/n);
}
makeWindow();
}
protected void makeWindow() {
// Make a blackman window:
// w(n)=0.42-0.5cos{(2*PI*n)/(N-1)}+0.08cos{(4*PI*n)/(N-1)};
window = new double[n];
for(int i = 0; i < window.length; i++)
window[i] = 0.42 - 0.5 * Math.cos(2*Math.PI*i/(n-1))
+ 0.08 * Math.cos(4*Math.PI*i/(n-1));
}
public double[] getWindow() {
return window;
}
/***************************************************************
* fft.c
* Douglas L. Jones
* University of Illinois at Urbana-Champaign
* January 19, 1992
* http://cnx.rice.edu/content/m12016/latest/
*
* fft: in-place radix-2 DIT DFT of a complex input
*
* input:
* n: length of FFT: must be a power of two
* m: n = 2**m
* input/output
* x: double array of length n with real part of data
* y: double array of length n with imag part of data
*
* Permission to copy and use this program is granted
* as long as this header is included.
****************************************************************/
public void fft(double[] x, double[] y)
{
int i,j,k,n1,n2,a;
double c,s,e,t1,t2;
// Bit-reverse
j = 0;
n2 = n/2;
for (i=1; i < n - 1; i++) {
n1 = n2;
while ( j >= n1 ) {
j = j - n1;
n1 = n1/2;
}
j = j + n1;
if (i < j) {
t1 = x[i];
x[i] = x[j];
x[j] = t1;
t1 = y[i];
y[i] = y[j];
y[j] = t1;
}
}
// FFT
n1 = 0;
n2 = 1;
for (i=0; i < m; i++) {
n1 = n2;
n2 = n2 + n2;
a = 0;
for (j=0; j < n1; j++) {
c = cos[a];
s = sin[a];
a += 1 << (m-i-1);
for (k=j; k < n; k=k+n2) {
t1 = c*x[k+n1] - s*y[k+n1];
t2 = s*x[k+n1] + c*y[k+n1];
x[k+n1] = x[k] - t1;
y[k+n1] = y[k] - t2;
x[k] = x[k] + t1;
y[k] = y[k] + t2;
}
}
}
}
// Test the FFT to make sure it's working
public static void main(String[] args) {
int N = 8;
FFT fft = new FFT(N);
double[] window = fft.getWindow();
double[] re = new double[N];
double[] im = new double[N];
// Impulse
re[0] = 1; im[0] = 0;
for(int i=1; i<N; i++)
re[i] = im[i] = 0;
beforeAfter(fft, re, im);
// Nyquist
for(int i=0; i<N; i++) {
re[i] = Math.pow(-1, i);
im[i] = 0;
}
beforeAfter(fft, re, im);
// Single sin
for(int i=0; i<N; i++) {
re[i] = Math.cos(2*Math.PI*i / N);
im[i] = 0;
}
beforeAfter(fft, re, im);
// Ramp
for(int i=0; i<N; i++) {
re[i] = i;
im[i] = 0;
}
beforeAfter(fft, re, im);
long time = System.currentTimeMillis();
double iter = 30000;
for(int i=0; i<iter; i++)
fft.fft(re,im);
time = System.currentTimeMillis() - time;
System.out.println("Averaged " + (time/iter) + "ms per iteration");
}
protected static void beforeAfter(FFT fft, double[] re, double[] im) {
System.out.println("Before: ");
printReIm(re, im);
fft.fft(re, im);
System.out.println("After: ");
printReIm(re, im);
}
protected static void printReIm(double[] re, double[] im) {
System.out.print("Re: [");
for(int i=0; i<re.length; i++)
System.out.print(((int)(re[i]*1000)/1000.0) + " ");
System.out.print("]\nIm: [");
for(int i=0; i<im.length; i++)
System.out.print(((int)(im[i]*1000)/1000.0) + " ");
System.out.println("]");
}
}
Below is my main activity class in android which uses the FFT instance
public class MainActivity extends Activity implements
SensorEventListener{
static final float ALPHA = 0.15f;
private int count=0;
private static GraphicalView view;
private LineGraph line = new LineGraph();
private static Thread thread;
private SensorManager mSensorManager;
private Sensor mAccelerometer;
TextView title,tv,tv1,tv2,tv3,tv4,tv5,tv6;
RelativeLayout layout;
private double a;
private double m = 0;
private float p,q,r;
public long[] myList;
public double[] myList2;
public double[] gettedList;
static String k1,k2,k3,k4;
int iniX=0;
public FFT fft;
public myArray myArrayQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fft=new FFT(128);
myList=new long[128];
myList2=new double[128];
gettedList=new double[128];
myArrayQueue=new myArray(128);
//get the sensor service
mSensorManager = (SensorManager)
getSystemService(Context.SENSOR_SERVICE);
//get the accelerometer sensor
mAccelerometer =
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//get layout
layout = (RelativeLayout)findViewById(R.id.relative);
LinearLayout layout = (LinearLayout) findViewById(R.id.layoutC);
view= line.getView(this);
layout.addView(view);
//get textviews
title=(TextView)findViewById(R.id.name);
//tv=(TextView)findViewById(R.id.xval);
//tv1=(TextView)findViewById(R.id.yval);
//tv2=(TextView)findViewById(R.id.zval);
tv3=(TextView)findViewById(R.id.TextView04);
tv4=(TextView)findViewById(R.id.TextView01);
tv5=(TextView)findViewById(R.id.TextView02);
tv6=(TextView)findViewById(R.id.TextView03);
for (int i = 0; i < myList2.length; i++){
myList2[i] =0;
}
}
public final void onAccuracyChanged(Sensor sensor, int accuracy)
{
// Do something here if sensor accuracy changes.
}
@Override
public final void onSensorChanged(SensorEvent event)
{
count=+1;
// Many sensors return 3 values, one for each axis.
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
//float[] first={x,y,z};
// float[] larst={p,q,r};
//larst= lowPass(first,larst);
//double FY= b.Filter(y);
//double FZ= b.Filter(z);
//get merged value
// m = (float)
Math.sqrt(larst[0]*larst[0]+larst[1]*larst[1]+larst[2]*larst[2]);
m=(double)Math.sqrt(x*x+y*y+z*z);
//display values using TextView
//title.setText(R.string.app_name);
//tv.setText("X axis" +"\t\t"+x);
//tv1.setText("Y axis" + "\t\t" +y);
//tv2.setText("Z axis" +"\t\t" +z);
//myList[iniX]=m*m;
//myList[iniX+1]=myList[iniX];
iniX=+1;
//myList[3]=myList[2];
//myList[2]=myList[1];
//myList[1]=myList[0];
myArrayQueue.insert(m*m);
gettedList=myArrayQueue.getMyList();
/* for(int a = myList.length-1;a>0;a--)
{
myList[a]=myList[a-1];
}
myList[0]=m*m;
*/
fft.fft(gettedList, myList2);
k1=Double.toString(myList2[0]);
k2=Double.toString(myList2[1]);
k3=Double.toString(myList2[2]);
k4=Double.toString(myList2[3]);
tv3.setText("[0]= "+k1);
tv4.setText("[1]= "+k2);
tv5.setText("[2]= "+k3);
tv6.setText("[3]= "+k4);
line.addNewPoint(iniX,(float) m);
view.repaint();
}
@Override
protected void onResume()
{
super.onResume();
mSensorManager.registerListener(this, mAccelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause()
{
super.onPause();
mSensorManager.unregisterListener(this);
}
public void LineGraphHandler(View view){
}
//Low pass filter
protected float[] lowPass( float[] input, float[] output ) {
if ( output == null ) return input;
for ( int i=0; i<input.length; i++ ) {
output[i] = output[i] + ALPHA * (input[i] - output[i]);
}
return output;
}
/*@Override
public void onStart(){
super.onStart();
view= line.getView(this);
setContentView(view);
}*/
}

Friday, 30 August 2013

java.net.ProtocolException: Connection already established ( Not Found Proper Solution in existing Post )

java.net.ProtocolException: Connection already established ( Not Found
Proper Solution in existing Post )

In one of my android app, i am getting error "java.net.ProtocolException:
Connection already established" during call the API. (I refered
"Connection already established" exception in HttpsURLConnection for
solution but not useful)
Below is my code to call API. Code is working for all the API except the
one. That API is the same way developed as the Others and still below code
throwing error for that API.
HttpURLConnection con = null;
BufferedReader in = null;
StringBuilder sb = new StringBuilder();
try {
URL uri = null;
uri = new URL(url);
LogUtil.v("~~URL - "+url);
con = (HttpURLConnection) uri.openConnection();
System.setProperty("http.keepAlive", "false");
con.setRequestMethod(requestType); //type: POST, PUT,
DELETE, GET
con.setDoOutput(true);
// con.setDoInput(true);
con.setConnectTimeout(TIMEOUT); //20 secs
con.setReadTimeout(TIMEOUT); //20 secs
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
String authorizationString = "Basic " +
Base64.encodeToString((myAuthString).getBytes(),
Base64.DEFAULT);
con.setRequestProperty("Authorization",
authorizationString);
if( body != null){
LogUtil.v("~~BODY - "+body);
DataOutputStream out = new
DataOutputStream(con.getOutputStream());
out.writeBytes(body);
out.flush();
out.close();
}
con.connect();
InputStream inst = con.getInputStream();
in = new BufferedReader(new InputStreamReader(inst));
String temp = null;
while((temp = in.readLine()) != null){
sb.append(temp).append(" ");
}
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(cb!=null){
if (sb.toString().length() >0) {
LogUtil.v("~~ RESPONSE - "+ sb.toString());
cb.onResponse(sb.toString(), actionCode);
}else{
LogUtil.v("~~ RESPONSE - null");
cb.onResponse(null, actionCode);
}
}
if(con!=null)
con.disconnect();
}
Please don't suggest to use DefaultHttpClient here.
I want to solve the problem using above BECAUSE IT IS WORKING FOR ALL
OTHER APIS.
FYI: API CALL IS ALREADY CHECKED USING BROWSER AND IT IS RETURNING
RETURNING DATA. IT IS JUST THROWING ERROR WHEN CALLING FROM ANDROID.

Find date after a particular word

Find date after a particular word

I would like to find the date in a string after a particular word (key).
My string is dynamic and the date format also not same from one string to
another string.
$data = "Balance- 0.30,Val-Aug 29 2013, Free Bal- 0.00";
or
$data = "Bal: 96.27.Valid Sep 26 2013.Toll Free Dial 578785";
or
$data = "BalanceRs.0.00,Expiry date: Apr 04 20141 Live Scores";
or
$data = "Your current balance is 0.20.Your account expires on 2013-11-23
23:59:59.";
or
$data = "Main Bal Rs.87.850 Val 09-07-2014,More";
$key = array('Val-','Val','Valid','Expiry date:','expires on');
$result=preg_match_all("/(?<=(".$key."))(\s\w*)/i",$data,$networkID);
$myanswer = @$networkID[0][0];
Here I am getting the output of only the first word.
Anyone please guide me to get the date. Thanks.

Thursday, 29 August 2013

Book Review Required for Drupal for Education and E-Learning - Second Edition

Book Review Required for Drupal for Education and E-Learning - Second Edition

Packt is looking for people interested in reviewing the book Drupal for
Education and E-Learning - Second Edition Drupal for Education and
E-Learning - Second Edition on their blog/ amazon The book is written by
James G. Robertson and Bill Fitzgerald
If interested, please let me know at – sabyasachir@packtpub.com or leave a
comment below with your email ID, I will provide you with the e-copy of
the book. Note : Limited copies available. Thanks and regards

Wednesday, 28 August 2013

Pythonic way to specify comparison operators?

Pythonic way to specify comparison operators?

I am looking for some advice for the most pythonic (readable,
straightforward, etc) way to specify comparison operators for later use in
comparisons (to be executed via javascript). Something like (this is just
one example implementation that comes to mind - there are lots of other
possible formats):
comparisons = (('a', '>', 'b'), ('b', '==', 'c'))
which would later be evaluated like: (EDIT: this actually not how it will
get evaluated. It will be evaluated in Javascript, not python - read on
for details.)
if a > b:
do something...
if b == c:
do another thing...
The context is that I am working on a Django app (ultimately for
distribution as a plugin) which will require users to write comparisons in
whatever syntax I choose (hence the question about making it pythonic).
The comparisons will reference form fields, and will ultimately be
converted to javascript conditional form display. I suppose an example is
in order:
class MyModel(models.Model):
yes_or_no = models.SomeField...choices are yes or no...
why = models.SomeField...text, but only relevant if yes_or_no == yes...
#here i am inventing some syntax...open to suggestions!!
why.show_if = ('yes_or_no','==','yes')
(hand waving...convert MyModel to ModelForm using
model_form_factory()...gather all "field.show_if" conditions in a
dictionary and attach to ModelForm as MyModelForm.conditions or
something...)
Now in a chunk of javascript in a template, each condition in
MyModelForm.condtions will become a function that listens for a change in
the value of a field, and shows or hides another field in response.
Basically (in pseudo-Javascript/Jquery):
when yes_or_no changes...
if (yes_or_no.value == 'yes'){
$('#div that contains *why* field).show(); }
else {
$('#div that contains *why* field).hide(); }
The goal here is to let the end user specify the conditional display logic
in a straightforward, pythonic way inside the model definition (there may
be an option to specify the conditions on the form class instead, which I
think is more "Djangonic"(??), but for my use case they need to go in the
models). Then my plugin behind the scenes turns that into Javascript in a
template. So you get conditional form display without having to write any
Javascript. Since this will be in the hands of python/django developers, I
am looking for suggestions for the most native, comfortable way to specify
those conditions.

SQL join table to self to find difference

SQL join table to self to find difference

Consider the below table
CREATE TABLE `temp` (
`id` int(11) NOT NULL,
`lang` char(2) COLLATE utf8_unicode_ci NOT NULL,
`channel` char(2) COLLATE utf8_unicode_ci NOT NULL,
`name` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`,`lang`,`channel`)
)
insert into `temp` (`id`, `lang`, `channel`, `name`)
values('1','fr','ds','Jacket');
insert into `temp` (`id`, `lang`, `channel`, `name`)
values('1','en','ds','Jacket');
insert into `temp` (`id`, `lang`, `channel`, `name`)
values('2','en','ds','Jeans');
insert into `temp` (`id`, `lang`, `channel`, `name`)
values('3','en','ds','Sweater');
insert into `temp` (`id`, `lang`, `channel`, `name`)
values('1','de','ds','Jacket');
The question is how can I find which entries with lang en do not exist for
fr? My head is stuck and I believe this to be a trivial query but I am
having one of these days.

What happens when we close the script two times?

What happens when we close the script two times?

This might be a silly question but i want to clarify this. what happens
when we close a javascript two times.
<script type="text/javascript">
alert("hello");
</script>
</script>
i did this but am not getting any error.its like we closed the script so
there wont be any execution so no error will trigger i believe. will this
create trouble under any situation?
why am asking this is i would like to insert a </script> at the end of a
plugin where user submits their script.

Sencha touch 2 segmented control check which button pressed

Sencha touch 2 segmented control check which button pressed

I have checked this out over the sencha touch examples that the items in
the segmented button can be handled programmatically. The issue that i am
facing currently is how to get the button that is pressed.
I need to store the index of the button that is pressed in my stores for
further references so that when i launch the screen again I am able to
select the buttons over the segmented control based on the selection.
I am handling the toggle event of the segmented button which takes three
arguments: - segmentedbutton - button that is pressed - pressed state.
I have access to the button when the event is generated but I am not able
to find out how to get the index of the button.
Can someone provide some light on this ?
Thanks J

Tuesday, 27 August 2013

How can I create a duration slider using seconds as raw value in jQuery?

How can I create a duration slider using seconds as raw value in jQuery?

Let's say I have an input that is a text field.
If I typed 3600 then the value would be 60 minutes. I'm tracking the value
of duration based on seconds.
How could I dynamically display a slider that showed seconds if under 1
minute, and over 1 minute it would say 1 minute and x seconds, etc... and
if over a hour it would go 1 hour and 30 minutes and 5 seconds, and so on.
Limited to hours/minutes/seconds.
This slider is just a UI wrapper for seconds as the real value for the input.

Decrypt Feistel Cipher in PostgreSQL

Decrypt Feistel Cipher in PostgreSQL

I updated a bunch of fields in my db using this Feistel Cipher. According
to the documentation, the cipher can be undone to get the original value.
How can I undo the values if need be?
Here is the original cipher function:
CREATE OR REPLACE FUNCTION pseudo_encrypt(VALUE int) returns bigint AS $$
DECLARE
l1 int;
l2 int;
r1 int;
r2 int;
i int:=0;
BEGIN
l1:= (VALUE >> 16) & 65535;
r1:= VALUE & 65535;
WHILE i < 3 LOOP
l2 := r1;
r2 := l1 # ((((1366.0 * r1 + 150889) % 714025) / 714025.0) * 32767)::int;
l1 := l2;
r1 := r2;
i := i + 1;
END LOOP;
RETURN ((l1::bigint << 16) + r1);
END;
$$ LANGUAGE plpgsql strict immutable;

Disable input language switching shortcut

Disable input language switching shortcut

I'm not sure what the issue is on my Windows computer but I can't seem to
determine what triggers the input language switcher that I seem to
accidentally press too often.
I have three inputs set up:
English - US Keyboard
French - US Keyboard
French - Canadian Multilingual Standard Keyboard
I know that Windows + Space triggers a menu to choose a language but I
know that is not what I accidentally hit because 1) the menu doesn't show
up and 2) it is rare to press Windows + Space accidentally.
I've heard that Alt + Shift is also another combination and it seems
plausible that that's triggering the behaviour but it isn't because I just
tried to replicate the problem and have tried all combinations of Ctrl,
Shift, and Alt.
The thing is, my input preferences have no keyboard shortcuts configured:
How do I disable it?

Retrofit GSON serialize Date from json string into java.util.date

Retrofit GSON serialize Date from json string into java.util.date

I am using the Retrofit library for my REST calls. Most of what I have
done has been smooth as butter but for some reason I am having issues
converting json timestamp strings into java.util.date objects. The json
that is coming in looks like this.
{
"date": "2013-07-16",
"created_at": "2013-07-16T22:52:36Z",
}
How can I tell Retrofit or GSON to convert these strings into
java.util.date objects?

Plesk, Email with localy established domain where the mail server is external

Plesk, Email with localy established domain where the mail server is external

i have a big problem with the setup for an Domain.
The Webservices are established on our Server but the Mail functions are
on a Server of an other Company when we now want send an Email over our
Server he tried to send it localy insted of sending it to an other server
so he give back an no account here error.
Thanks for helping me out and friendly greetings.

hide element without setting the display to none in jquery

hide element without setting the display to none in jquery

I want to fold a section of the form without setting its display to none.
If i set the display to none, the validation is bypassed that is why I
don't want to set the display to none. I know I can set the visibility to
hidden and visible but this solution is not feasible for rendering the
view as the space for the folded section stays there. This results in a
very odd look of the view with an empty white space with no content on it.
So my question is to hide a section of the html form (without intacting a
placeholder for it) without setting its display to none, so that I could
still perform the validation.

How to get the value of id and message seperately

How to get the value of id and message seperately

i have a NSString response
{"id":"44","message":"1"} ,
i want to get the value of
"id"
and
"message"
seperately. it is the response nsstring from the server.
Thanks in advance

Monday, 26 August 2013

Nunit tests fails when running continuous integration build on team foundation service

Nunit tests fails when running continuous integration build on team
foundation service

I have followed a couple of guides on how to get nunit to work on TFS (the
cloud version)
http://www.mytechfinds.com/articles/software-testing/6-test-automation/72-running-nunit-tests-from-team-foundation-server-2012-continuous-integration-build
http://walkingthestack.blogspot.sg/2013/04/using-nunit-for-your-tests-in-team.html
However, after setting up everything, I'm still getting this error message:
Exception Message: The path '$/Plan.Ess.sln' could not be converted to a
local path. Make sure this path is relative to the 'src' folder on the
build machine or specify a full server path. (type ArgumentException)
Exception Stack Trace: at
Microsoft.TeamFoundation.Build.Activities.Core.LocalPathProvider.GetLocalPath(String
incomingPath)
at System.Activities.CodeActivity`1.InternalExecute(ActivityInstance
instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
at
System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor
executor, BookmarkManager bookmarkManager, Location resultLocation)
TF270003: Failed to copy. Ensure the source directory C:\a\bin exists and
that you have the appropriate permissions.
1) $/Plan.Ess.sln is what I keyed in my Build Definitions > Edit Build
Definition > Process > 1. Solution to build
2) I'm not sure why it's refering to C:\a\bin
I'm not sure if I have "Make sure that installed test discoverers &
executors, platform & framework settings are appropiate and try again"
(Solution from the 2nd link) But I have already pointed the build
controller to the folder containing the nunit test adapters & dlls

ASCII subset for readable random keys (no O, 0, 1, I or l confusion)?

ASCII subset for readable random keys (no O, 0, 1, I or l confusion)?

Every so often you have to enter a product activation code or similar.
If it's badly designed you end up trying to guess if you're looking at
zeroes or capital Os, or at ones, lowercase Ls or uppercase Is.
Such characters can often only be distinguished by humans by context, i.e.
their use in real words, and so shouldn't be used in random sequences.
Has anyone done any work to determine the subset of letters that most
people can uniquely distinguish in most reasonable fonts irrespective of
context (and assuming reasonable print quality)?
E.g. characters suitable for use in keys sent by plain text email - one
cannot know what font the end user will use to read the email - but it's
likely not too unusual. For printed material one obviously has more
control.
I'll point out before anyone else does that this question is similar to
(some might consider it a duplicate of) "OCR - most "different" or
"recognizable" ASCII characters?"

Puppet ssl errors " SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed"

Puppet ssl errors " SSL_connect returned=1 errno=0 state=SSLv3 read server
certificate B: certificate verify failed"

I am trying to setup puppet master and puppetdb on same node using
puppetdb module.
When I try to run puppet agent -t, I see following erorr
notice: Unable to connect to puppetdb server
(ip-10-172-161-25.us-west-1.compute.internal:8081): SSL_connect returned=1
errno=0 state=SSLv3 read server certificate B: certificate verify failed
notice: Failed to connect to puppetdb; sleeping 2 seconds before retry
[root@ip-10-172-161-25 modules]# puppet cert --list --all
+ "ip-10-172-161-25.us-west-1.compute.internal"
(66:37:02:AB:98:C5:CD:28:1C:D3:68:53:13:CC:A1:E5)
+ "ip-10-196-99-56.us-west-1.compute.internal"
(99:C9:7C:A1:1A:FD:3C:27:85:76:C7:5A:6A:D5:F9:79)
+ "puppettest.eng.com"
(17:4A:B9:D1:48:F2:82:73:7D:7F:1D:55:E4:A1:A6:A0) (alt names:
"DNS:ip-10-172-161-25.us-west-1.compute.internal", "DNS:puppet",
"DNS:puppettest.eng.com")
[root@ip-10-172-161-25 modules]# cat /etc/puppet/puppet.conf
[main]
# The Puppet log directory.
# The default value is '$vardir/log'.
logdir = /var/log/puppet
# Where Puppet PID files are kept.
# The default value is '$vardir/run'.
rundir = /var/run/puppet
# Where SSL certificates are kept.
# The default value is '$confdir/ssl'.
ssldir = $vardir/ssl
server = puppettest.eng.com
[agent]
# The file in which puppetd stores a list of the classes
# associated with the retrieved configuratiion. Can be loaded in
# the separate ``puppet`` executable using the ``--loadclasses``
# option.
# The default value is '$confdir/classes.txt'.
classfile = $vardir/classes.txt
# Where puppetd caches the local configuration. An
# extension indicating the cache format is added automatically.
# The default value is '$confdir/localconfig'.
localconfig = $vardir/localconfig
[master]
certname=puppettest.eng.com
dns_alt_names =
ip-10-172-161-25.us-west-1.compute.internal,puppettest.eng.com,puppet
Puppetdb.conf
[root@ip-10-172-161-25 modules]# cat /etc/puppet/puppetdb.conf
[main]
server = ip-10-172-161-25.us-west-1.compute.internal
#server = puppettest.eng.com
port = 8081
jetty.in
[jetty]
# Hostname or IP address to listen for clear-text HTTP. Default is localhost
# host = <host>
#host = localhost
host = localhost
# Port to listen on for clear-text HTTP.
port = 8080
# The following are SSL specific settings. They can be configured
# automatically with the tool puppetdb-ssl-setup, which is normally
# ran during package installation.
# The host or IP address to listen on for HTTPS connections
#ssl-host = ip-10-172-161-25.us-west-1.compute.internal
ssl-host = ip-10-172-161-25.us-west-1.compute.internal
# The port to listen on for HTTPS connections
ssl-port = 8081
# Private key path
ssl-key = /etc/puppetdb/ssl/private.pem
# Public certificate path
ssl-cert = /etc/puppetdb/ssl/public.pem
# Certificate authority path
ssl-ca-cert = /etc/puppetdb/ssl/ca.pem
certificate-whitelist = /etc/puppetdb/whitelist.txt
whitelist.txt
[root@ip-10-172-161-25 modules]# cat /etc/puppetdb/whitelist.txt
ip-10-172-161-25.us-west-1.compute.internal
puppettest.eng.com
localhost
[root@ip-10-172-161-25 modules]# rpm -qa | grep -i puppet
puppet-server-2.7.22-1.0.amzn1.x86_64
puppetlabs-release-5-7.noarch
puppetdb-terminus-1.4.0-1.el5.noarch
puppet-2.7.22-1.0.amzn1.x86_64
puppetdb-1.4.0-1.el5.noarch
[root@ip-10-172-161-25 modules]# rpm -qa | grep -i ruby
ruby-libs-1.8.7.374-1.0.amzn1.x86_64
ruby-1.8.7.374-1.0.amzn1.x86_64
ruby-augeas-0.4.1-1.3.amzn1.x86_64
[root@ip-10-172-161-25 modules]#
I tired multiple times revoke master cert and created new, no luck

Salted Password Validation in PHP

Salted Password Validation in PHP

On crackstation.net it is stated:
To Validate a Password
Retrieve the user's salt and hash from the database.
Prepend the salt to the given password and hash it using the same hash
function.
Compare the hash of the given password with the hash from the
database. If they match, the password is correct. Otherwise, the
password is incorrect.
However in the source code listed at the bottom of the page, I can't
figure out how the validate_password function takes into account the salt.
I mean where is the salt prepended to the given password?

Puppet: could not retrieve catalog from remote server

Puppet: could not retrieve catalog from remote server

Running sudo puppet agent -t from host: host.internaltest.com
err: Could not retrieve catalog from remote server: Error 400 on SERVER:
Another local or imported resource exists with the type and title
Host[host.internaltest.com] on node host.internaltest.com
This machine had its ssl certs messed with so I cleaned it off the master
and then using autosign (bad bad i know!) I ran sudo puppet agent -t which
regenerated the ssl cert but also threw this error. Let me know if you
need more information, I haven't delete with this aspect of puppet too
much.

Convert TIMEDIFF to hours plus minutes

Convert TIMEDIFF to hours plus minutes

time1: 2013-08-26 16:33:00
time2: 2013-08-26 15:10:00
$query="UPDATE `FlightSchedule`
SET delay = MINUTE(TIMEDIFF(time1, time2))
WHERE `flightNum_arr`='".$flightNum_arr."';";
It saves the value 23 as the delay. Instead the correct answer should be
83 minutes. How to get it?

ProxyPass for https not working

ProxyPass for https not working

I'm having set of codes in tomcat (port:8080) and another set of codes in
apache (port:80). Now the default port I have set is apache (document
root: /var/www/html) and for tomcat (/usr/.../webapps/ROOT)
Now tomcat codebase is running in https:// www.example.com and apache
codebase is running in http://ww.example.com
I have written proxy as
ProxyPass /req https://example.com/req
ProxyPassreverse /req https://example/req
All the request from http, which contains /req will go to
https://example.com/req.
But the problem is, it is redirected into http://example.com/req
what can I do to redirect to https or what can I do to run tomcat in "http"

Grabbing a part of a string using regex in python 3.x

Grabbing a part of a string using regex in python 3.x

So what i am trying to do is to have an input field named a. Then have a
line of regex which checks a for 'i am ' (note something could be a chain
of words.) and then prints How long have you been ?
This is my code so far:
if re.findall(r"i am", a):
print('How long have you been {}'.format(re.findall(r"i am", a)))
But this returns me a list of [i, am] not the . How do i get it to return me
Thanks,
A n00b at Python

Sunday, 25 August 2013

How do I make a button stay pressed in XCode?

How do I make a button stay pressed in XCode?

Okay so I have an app I'm building that is almost complete. I'm just
having one problem, when I press my button it makes a sound and the
button's image changes. However the image on changes when it is being
touched or "highlighted" and I would like the buttons image to remain
changed through the duration of the sound effect then after the sound
effect I would like it to revert back to the original image. Is there
anyway I can set up a UIButton "set time" or something for the
"highlighted" option?
I feel so embarrassed sometimes, because I seem to get tripped up by these
most trivial things, when I handle the core coding exceptionally well and
near finish a full app in a days time, but this is my first app and I'm
still a newbie to XCode. I really appreciate this community's help any
answer that pushes me forward is always appreciated!
I further apologize for my questions formatting I typed this on my iPhone
I hope it's not too awkward or lacking in detail. If anyone needs more
detail just ask!

scaling equation within margin

scaling equation within margin

I have split an equation across several lines but I couldn't remain
perfectly within the margin.

The input is
\begin{equation*}
\begin{split}
& \ddot\phi_3+\phi_3+sin(\tau+\alpha)[p_1\Delta \alpha+2 \nabla p_1
\nabla \alpha] \\
& \qquad -\cos(\tau+ \alpha)[\Delta p_1 -p_1 (\nabla
\alpha)^2+\frac{5}{6}g_2^2p_1^3- \frac{3}{4}g_3p_1^3-p_1 +\omega_2
p_1]
+\frac{ p_1^3}{12}(2g_2^2+3g_3)\cos3(\tau + \alpha) \\
& \qquad +g_2 p_1 [p_2+ p_2 cos2(\tau +\alpha)+q_2 \sin2(\tau+\alpha)] =0
\end{split}
\end{equation*}
\begin{equation}\label{eq10}
\begin{split}
& \ddot\phi_3+\phi_3+\sin(\tau+\alpha)[p_1\Delta \alpha+2 \nabla p_1
\nabla \alpha] \\
& \qquad -\cos(\tau+ \alpha)[\Delta p_1-p_1 (\nabla \alpha)^2 + \lambda
p_1^3-p_1+\omega_2 p_1] +\frac{p_1^3}{12}(2g_2^2+3g_3)\cos3(\tau + \alpha)
\\
& \qquad +g_2 p_1 [p_2+ p_2 \cos2(\tau +\alpha)+q_2 \sin2(\tau+\alpha)]=0
\end{split}
\end{equation}

Saturday, 24 August 2013

How do i install my built in web cam drivers

How do i install my built in web cam drivers

How do I install drivers for my built in web cam? Ubuntu 12.04

Complex polynomial identity with norm condition

Complex polynomial identity with norm condition

In this question, the following was shown:
If $R(z)=\dfrac{P(z)}{Q(z)}$, where $P,Q$ are polynomials in a complex
variable $z$, satisfies the condition that $|R(z)|=1$ whenever $|z|=1$,
then the identity $R(z)\overline{R(1/\overline{z})}=1$ holds for all
complex $z$.
The proof given there uses the identity theorem. Since I'm not familiar
with the theorem yet, I would like to find an easier approach.
So I try direct substitution. Writing
$P(z)=a_nz^n+a_{n-1}z^{n-1}+\ldots+a_0$ and
$Q(z)=b_mx^m+b_{m-1}x^{m-1}+\ldots+b_0$, we find that
$$R(z)=\frac{P(z)}{Q(z)}=\frac{a_nz^n+a_{n-1}z^{n-1}+\ldots+a_0}{b_mz^m+b_{m-1}z^{m-1}+\ldots+b_0}$$
and $$\overline{R(1/\overline{z})} =
\frac{\overline{P(1/\overline{z})}}{\overline{Q(1/\overline{z})}} =
\frac{\overline{a_n}+\overline{a_{n-1}}z+\ldots+\overline{a_0}z^n}{\overline{b_m}+\overline{b_{m-1}}z+\ldots+\overline{b_0}z^m}\cdot
z^{m-n}$$
So the identity $R(z)\overline{R(1/\overline{z})}=1$ that we wants to
prove can be turned into
$$z^{m-n}(a_nz^n+a_{n-1}z^{n-1}+\ldots+a_0)(\overline{a_0}z^n + \ldots +
\overline{a_{n-1}}z + \overline{a_n}) =
(b_mz^m+b_{m-1}z^{m-1}+\ldots+b_0)(\overline{b_0}z^m+\ldots+\overline{b_{m-1}}z+\overline{b_m}).$$
where we have the condition that for any $|z|=1$,
$$|a_nz^n+a_{n-1}z^{n-1}+\ldots+a_0| =
|b_mz^m+b_{m-1}z^{m-1}+\ldots+b_0|.$$
How can we proceed from here?

Django slow at creating objects?

Django slow at creating objects?

How long should this take to run?
query = Contact.objects.filter(contact_owner=batch.user, subscribed=True)
objs = [
Message(
recipient_number=e.mobile,
content=content,
sender=e.contact_owner,
billee=user,
sender_name=sender,
)
for e in query
Just this code nothing else (not saving to db I'm only running above i.e.
create the objects). It takes 15 mins for 5000 messages objects to be
created in the query. Is this right? Why is Django so slow?
This is the model it creates, again I'm not saving here. I think there ahs
to be an issue in the model when an object is created, that or Django is
just too slow for my needs.
Model message
from django.db import models
from django.contrib.contenttypes import generic
from django.utils.translation import ugettext as _
from django.conf import settings
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
import uuidfield.fields
import picklefield
import jsonfield
if 'timezones' in settings.INSTALLED_APPS:
from timezones.utils import adjust_datetime_to_timezone
else:
def adjust_datetime_to_timezone(a, b, c):
return a
from gateway import Gateway
class MessageManager(models.Manager):
def get_matching_message(self, datadict):
for gateway in Gateway.objects.all():
try:
return Message.objects.get(
gateway_message_id=datadict.get(gateway.status_msg_id),
gateway=gateway,
)
except Message.DoesNotExist:
pass
def get_original_for_reply(self, datadict):
for gateway in Gateway.objects.all():
try:
return Message.objects.get(
uuid=datadict.get(gateway.uuid_keyword),
gateway=gateway
)
except Message.DoesNotExist:
pass
# This may have been a message sent from another phone, but
# there may be a reply-code that was added in.
return self.custom_reply_matcher(datadict)
def custom_reply_matcher(self, datadict):
# Designed to be overridden.
return None
def get_last_rate_for(self, recipient_number):
m =
Message.objects.filter(recipient_number=recipient_number).exclude(
gateway_charge=None).order_by('-send_date')[0]
return m.gateway_charge / m.length
def get_message(self, gateway_message_id):
try:
return
Message.objects.get(gateway_message_id=gateway_message_id,)
except Message.DoesNotExist:
pass
MESSAGE_STATUSES = (
('Unsent', 'Unsent'),
('Sent', 'Sent'),
('Delivered', 'Delivered'),
('Failed', 'Failed'),
)
class Message(models.Model):
"""
A Message.
We have a uuid, which is our reference. We also have a
gateway_message_id,
which is their reference. This is required by some systems so we can
pass in a unique value that will allow us to match up replies to
original
messages.
"""
content = models.TextField(help_text=_(u'The body of the message.'))
recipient_number = models.CharField(max_length=32,
help_text=_(u'The international number of the recipient'
', without the leading +'))
sender = models.ForeignKey('auth.User',
related_name='sent_sms_messages')
sender_name = models.CharField(max_length=11)
send_date = models.DateTimeField(null=True, blank=True,
editable=False)
delivery_date = models.DateTimeField(null=True, blank=True,
editable=False,
help_text="The date the
message was sent.")
uuid = uuidfield.fields.UUIDField(auto=True,
help_text=_(u'Used for associating replies.'))
status = models.CharField(max_length=16, choices=MESSAGE_STATUSES,
default="Unsent",
)
status_message = models.CharField(max_length=128, null=True,
blank=True)
billed = models.BooleanField(default=False)
content_type = models.ForeignKey('contenttypes.ContentType')
object_id = models.PositiveIntegerField()
billee = generic.GenericForeignKey()
gateway = models.ForeignKey('sms.Gateway',
null=True, blank=True, editable=False)
gateway_message_id = models.CharField(max_length=128,
blank=True, null=True, editable=False)
reply_callback = picklefield.PickledObjectField(null=True,
blank=True)
gateway_charge = models.DecimalField(max_digits=10, decimal_places=5,
null=True, blank=True)
charge = models.DecimalField(max_digits=10, decimal_places=5,
null=True, blank=True)
objects = MessageManager()
class Meta:
app_label = 'sms'
permissions = (
('view_message', 'Can view message'),
)
ordering = ('send_date',)
def send(self, gateway):
gateway.send(self)
@property
def length(self):
"""Unicode messages are limited to 70 chars/message segment."""
# try:
# return len(str(self.content)) / 160 + 1
# except UnicodeEncodeError:
# return len(self.content) / 70 + 1
return len(self.content) / 160 + 1
@property
def local_send_time(self):
# TODO: Get this from UserProfile?
if getattr(self.billee, 'timezone', None):
return adjust_datetime_to_timezone(
self.send_date,
settings.TIME_ZONE,
self.billee.timezone
)
return self.send_date
@property
def local_send_date(self):
return self.local_send_time.date()
def __unicode__(self):
return "[%s] Sent to %s by %s at %s [%i]" % (
self.status,
self.recipient_number,
self.sender,
self.send_date,
self.length
)
@receiver(pre_save, sender=Message)
def my_handler(sender, **kwargs):
instance = kwargs['instance']
if not instance.charge:
instance.charge = instance.length
# No need to save, as we're slipping the value in
# before we hit the database.
contact model
import os
import datetime
from uuid import uuid4
from datetime import date
from django.db import models
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from django.utils import timezone
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver
from adaptor.fields import *
from adaptor.model import CsvModel
def path_and_rename(path):
"""
Callable function for renaming the file being uploaded.
"""
def wrapper(instance, filename):
ext = filename.split('.')[-1]
# get filename
if instance.pk:
filename = '{}.{}'.format(instance.pk, ext)
else:
# set filename as random string
filename = '{}.{}'.format(uuid4().hex, ext)
# return the whole path to the file
return os.path.join(path, filename)
return wrapper
class GroupManager(models.Manager):
def for_user(self, user):
return self.get_query_set().filter(user=user, )
class Group(models.Model):
"""
Stores all groups.
"""
name = models.CharField(max_length=60)
modified = models.DateTimeField(null=True, auto_now=True,
help_text="Shows when object was modified.")
created = models.DateTimeField(auto_now_add=True, help_text="Shows
when object was created.")
#FK
user = models.ForeignKey(User, related_name="user")
objects = GroupManager()
def __unicode__(self):
return self.name
def get_absolute_url(self):
return reverse('contacts.views.group', args=[str(self.id)])
def get_delete_url(self):
return reverse('contacts.views.group_delete_confirm',
args=[str(self.id)])
class ContactManager(models.Manager):
"""
Custom Manager for keyword.
"""
def unsorted_contacts(self, user):
"""
Manager that will list all records for a user where group is 'None'.
"""
return self.get_query_set().filter(contact_owner=user, group=None)
def for_user_and_group(self, user, group):
"""
Manager that will list all records for a user where group is 'group'.
"""
return self.get_query_set().filter(contact_owner=user, group=group)
def for_user(self, user):
"""
Manager that will list all records for a user they own.
"""
return self.get_query_set().filter(contact_owner=user)
class Contact(models.Model):
"""
Stores all contacts.
"""
first_name = models.CharField(max_length=60, blank=True)
last_name = models.CharField(max_length=60, blank=True)
company = models.CharField(max_length=100, blank=True)
mobile = models.CharField(max_length=15)
email = models.EmailField(max_length=100, blank=True)
subscribed = models.NullBooleanField(default=1, help_text="Shows if
contact is unsubscribed to SMS/Email.")
modified = models.DateTimeField(null=True, auto_now=True,
help_text="Shows when object was modified.")
created = models.DateTimeField(auto_now_add=True, help_text="Shows
when object was created.")
objects = ContactManager()
#FK
group = models.ForeignKey(Group, related_name='contacts', blank=True,
null=True)
contact_owner = models.ForeignKey(User)
def __unicode__(self):
return self.first_name
def full_name(self):
return "%s %s" % (self.first_name, self.last_name)
def get_delete_url(self):
return reverse('contacts.views.contact_delete',
args=[str(self.id), str(self.group_id)])
def get_group_absolute_url(self):
return reverse('contacts.views.group', args=[str(self.group_id)])
@property
def user(self):
return self.contact_owner
@receiver(pre_delete, sender=Contact)
def contact_cleanup(sender, instance, **kwargs):
"""
Do a bit of tidying up when deleting a Contact.
Sent at the beginning of a model's delete() method and a queryset's
delete() method.
"""
# Remove any FK's not done by cascade delete like generic relationships.
from unsubscribe.models import Unsubscribe
unsubscribe_list = Unsubscribe.objects.filter(object_id=instance.id,
content_type__model='contact')
unsubscribe_list.delete()
class Upload(models.Model):
"""
Stores jobs and status uploads of file uploads for CSV import.
"""
filepath = models.FileField(upload_to=path_and_rename('uploadsCSV'),
help_text="It can take several minutes for
contacts to appear.")
# Upload audit information
uploaded_by = models.ForeignKey(User)
date_uploaded = models.DateTimeField(auto_now_add=True)
# Processing audit information
PENDING, PROCESSED, FAILED = 'Pending', 'Processed', 'Failed'
STATUSES = (
(PENDING, _(PENDING)),
(PROCESSED, _(PROCESSED)),
(FAILED, _(FAILED)),
)
status = models.CharField(max_length=64, choices=STATUSES,
default=PENDING)
processing_description = models.TextField(blank=True, null=True)
num_records = models.PositiveIntegerField()
num_columns = models.PositiveIntegerField()
date_start_processing = models.DateTimeField(null=True)
date_end_processing = models.DateTimeField(null=True)
#FKs
group = models.ForeignKey(Group)
def get_configurator_url(self):
return reverse('contacts.views.upload_configurator',
args=[str(self.id)])
def process(self, cleaned_data):
self.date_start_processing = timezone.now()
try:
group_position = self.num_columns + 1
upload_id_position = self.num_columns + 1
# Try and import CSV
import_this(data=self.filepath, extra_fields=[
{'value': self.group_id, 'position': group_position},
{'value': self.uploaded_by.id, 'position':
upload_id_position}], cleaned_data=cleaned_data)
self._mark_processed(self.num_records)
except Exception as e:
self._mark_failed(unicode(e))
def was_processing_successful(self):
return self.status == self.PROCESSED
def was_processing_successful(self):
return self.status == self.PROCESSED
def _mark_processed(self, num_records, description=None):
self.status = self.PROCESSED
self.date_end_processing = date.today()
self.num_records = num_records
self.processing_description = description
self.save()
def _mark_failed(self, description):
self.status = self.FAILED
self.processing_description = description
self.save()
def import_this(cleaned_data, *args, **kw):
# make custom ContactCSVModel
class ContactCSVModel(CsvModel):
for k, v in cleaned_data.items():
if not v == '':
# print("---------------------------------")
# print(str(v))
# print("---")
# print(k[3:])
# print("---------------------------------")
setattr(CsvModel, v, CharField(row_num=k[3:]))
group = DjangoModelField(Group, row_num="5")
contact_owner = DjangoModelField(User, row_num="6")
class Meta:
delimiter = ","
dbModel = Contact
update = {'keys': ["mobile", "group"]}
return ContactCSVModel.import_data(*args, **kw)

Combine multiple rows into one row

Combine multiple rows into one row

I'm trying different JOIN queries, but I'm not getting result I'm looking
for.
I've got 2 tables:
Table 1: **StockItemShort**
ItemID | Code | Name
432724 | CK002-16-09 | Green Daisy Pearl Earrings
432759 | CK002-16-149 | Emerald Crystal Centre Daisy Earrings
Table 2: **StockItemCatSearchValueShort**
ItemID | SearchValueID
432724 | 388839
432724 | 389061
432724 | 390269
432724 | 389214
432759 | 388839
432759 | 389051
432759 | 390269
432759 | 389214
I can't get result I'm looking for.
I'd like to get following result:
ItemID | Code | Name | SearchValueID | SearchValueID | SearchValueID |
SearchValueID
432724 | CK002-16-09 | Green Daisy Pearl Earrings | 388839 |
389061 | 390269 | 389214
432759 | CK002-16-149 | Emerald Crystal Centre Daisy Earrings | 388839
| 389051 | 390269 | 389214

Wordpress loadin jquery and jquery-migrate, how do I stop it?

Wordpress loadin jquery and jquery-migrate, how do I stop it?

Wordpress is loading the following 2 files in wp_head...
<script type='text/javascript'
src='http://www.mywebsite.co.uk/wp-includes/js/jquery/jquery.js?ver=1.10.2'></script>
<script type='text/javascript'
src='http://www.mywebsite.co.uk/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.2.1'></script>
To try and stop this from happening I have tried deactivating all plugins
and deregistering jquery in functions.php but nothing seems to get rid of
it.
Wordpress version 3.6

com.apple.finder AppleShowAllFiles updates automatically [duplicate]

com.apple.finder AppleShowAllFiles updates automatically [duplicate]

This question already has an answer here:
AppleShowAllFiles does not show hidden files 5 answers
I have been trying to write a shell script which could toggle visibility
of hidden files
CURRENT_STATUS=`defaults read com.apple.Finder AppleShowAllFiles`
NEW_STATUS="YES"
if [ "$CURRENT_STATUS" = "YES" ]; then
NEW_STATUS="NO"
fi
defaults write com.apple.Finder AppleShowAllFiles $NEW_STATUS
sudo killall Finder
Something really weird happens when I run this script. After I have
updated the Status using the write command sometimes (not always) the
value reverts back. So say for example if I set the value as YES after
sometime on restarting the Finder app the value will turn back to NO. Can
someone help in figuring out why this happens?
Update: I found the solution here: AppleShowAllFiles does not show hidden
files

Git .gitignore not working

Git .gitignore not working

I am having some problems with my GIT repo ... I have a few folders added
in my ".gitignore" file. They contain over 100k files. Mainly images, tmp
and cache stuff. What I need is to be able to commit changes to my code
with out commiting what happens in those folders. I thought adding them
into the ".gitignore" would do the trick but for some reason it's not
working at all... I havant been abble to commit anything to the repo in
days because every time I try the push command it trys sending 100k files
then it frozes and times out.
root@serveur [/home/***/***]# git push origin master
Password:
Counting objects: 110300, done.
How can I force GIT to reindex the tree while taking in consideration the
ignored folders so I can finaly commit all the changes I made to the code.
A merge is planed today !

Javascript: function associated with create element not working

Javascript: function associated with create element not working

I have a select element from createElement which I want to have replaced
with a text input element with an onchange event, but my code for it
doesn't work. Here's the code (the select element itself is appended to
other div elements that are also created):
<script>
var countess = 0;
function adadd(){
var child = document.getElementById("geneadd");
if (child.value === "add")
{countess++;
if (countess < 2)
{
var divi=document.createElement("div");
divi.name = "diviena";
divi.id = "divienid";
divi.class = "table";
var elemdivi = document.getElementById("fieldsetid");
elemdivi.appendChild(divi);
}
var divii=document.createElement("div");
divii.name = "divienaa" + countess;
divii.id = "divienidd" + countess;
var elemdivii = document.getElementById("divienid");
elemdivii.appendChild(divii);
var sell=document.createElement("select");
sell.id = "den3erw" + countess;
sell.name = "oute3erw" + countess;
sell.onchange = "lechangefinal()";
var har = document.getElementById(divii.id);
har.appendChild(sell);
var opt=document.createElement("option");
opt.id = "disept" + countess/*<?php echo $varia; ?>*/;
opt.value = "";
var nar = document.getElementById(sell.id);
sell.appendChild(opt);
document.getElementById(opt.id).innerHTML="Select Gene...";
...more options in between...
var opta=document.createElement("option");
opta.id = "other" + countess/*<?php echo $varia; ?>*/;
opta.value = "other";
var nari = document.getElementById(sell.id);
sell.appendChild(opta);
document.getElementById(opta.id).innerHTML="other...";
}}
And this is the function that I want to be working on the create element:
function lechangefinal(){
for (var iii = 0; iii <= 100; iii++){
var childi = document.getElementById("den3erw" + iii);
if (childi.value === "other")
{parent.removeChild(childi);
var inpuat=document.createElement("input");
inpuat.type = "text";
inpuat.name = "2";
var elemi=document.getElementById("divienidd" + iii);
elemi.appendChild(inpuat);}}}

PHP Chaining: how to get data from a mysql table?

PHP Chaining: how to get data from a mysql table?

I am trying to implement PHP chaining method in my web development
project. But I seem can't get it right.
class foo extends base{
public $query = null;
public $item = array();
public function __construct($connection){
parent::__construct($connection);
}
public function select($query){
$this->query = $query;
return $this;
}
public function where($query){
$this->query = $query;
return $this;
}
public function __toString()
{
$this->item = $this->connection->fetch_assoc($this->query);
return var_export($this->item, true);
}
}
$connection = new db($dsn = 'mysql:host=localhost;dbname=xxx',$username =
'xxx',$password = 'xxx');
$foo = new foo($connection);
$select = $foo->select("SELECT * FROM page")->where("page_id = 10 ");
print_r($select->item);
the result I get,
Array
(
)
But I should get a row of data. Just like I normally do it in this way,
class boo extends base{
...
public function select() {
$sql = "
SELECT *
FROM page
WHERE page_id = ?
";
$item = $connection->fetch_assoc($sql,array(1));
return $item;
}
}
What have I missed in my chaining method?

Friday, 23 August 2013

Accordion active don't work on first load

Accordion active don't work on first load

when it loads first time i am trying to active first div but it makes all
div active except of first. here it is on jsfiddle.
$(".accordion > span").click(function(){
$('.accordion > span').removeClass('active');
$(this).addClass('active');
if(false == $(this).next().is(':visible')) {
$('.accordion > div').slideUp(300);
}
$(this).next().slideToggle(300);
});
var animationIsOff = $.fx.off;
$.fx.off = true;
$('.accordion > span:eq(0)').click()
$.fx.off = animationIsOff;
here is HTML
<div class="accordion">
<span>Accor 1</span>
<div>
Content here
</div>
</div>
<div class="accordion">
<span>Accor 2</span>
<div>
Content here
</div>
</div>
<div class="accordion">
<span>Accor 2</span>
<div>
Content here
</div>
</div>
any help will be highly appreciated.

Save SingnalR Chat data and Only show speifice meber in chat room

Save SingnalR Chat data and Only show speifice meber in chat room

I have found nice article on Signal R Chat, http://www.chatjs.net/. I want
to show only those people who are registered with us and or show friend
list like facebook and save chat data into database. Anyone any idea how
to do that will appreciate and thanks in advance.

Loading shared libraries with ssh framework

Loading shared libraries with ssh framework

Hi there I'am using sshxcute framework to access a Linux server. The idea
is to execute an application compiled with gcc from a java project. This
gcc applications has the next dependency:
libdl.so.2 => /lib64/libdl.so.2 (0x000000300ca00000)
libocci.so.11.1 => /e01/demov7/lib/libocci.so.11.1 (0x00002ac507b33000)
libclntsh.so.11.1 =>
/u01/app/oracle/product/11gR2/lib/libclntsh.so.11.1
(0x00002ac507e2e000)
libnnz11.so => /u01/app/oracle/product/11gR2/lib/libnnz11.so
(0x00002ac50a459000)
libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x000000301ec00000)
libm.so.6 => /lib64/libm.so.6 (0x000000300c600000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x000000301ac00000)
libc.so.6 => /lib64/libc.so.6 (0x000000300c200000)
/lib64/ld-linux-x86-64.so.2 (0x000000300be00000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x000000300ce00000)
libnsl.so.1 => /lib64/libnsl.so.1 (0x000000300fa00000)
libaio.so.1 => /usr/lib64/libaio.so.1 (0x0000003a92800000)
But when I try to execute my application I have the next error
error while loading shared libraries: libocci.so.11.1: cannot open shared
object file: No such file or directory
Do I need to execute somme command or configure some environment variables
to allow access to the server libraries ?
I attached my code here.
SSHExec ssh = null;
ConnBean cb = new ConnBean("127.0.0.1", "user", "password");
ssh = SSHExec.getInstance(cb);
CustomTask ct1 = new ExecCommand("./myapplication");
ssh.connect();
Result res = ssh.exec(ct1);
if (res.isSuccess) {
response = res.sysout;
} else {
response = res.error_msg;
}
ssh.disconnect() ;

Recipe from Python Cookbook

Recipe from Python Cookbook

I'm trying to implement a recipe from O'Reilly's Python Cookbook (2nd ed.)
and a small portion of the recipe doesn't work as it should. I was hoping
someone could help me figure out why.
The recipe is "5.14: Enhancing the Dictionary Type with Ratings
Functionality." I've got most of the code working, but I get an error when
trying to change the 'ranking' of a key. I've left in all the comments as
the author's so as anyone trying to help will have a good idea about what
the "unders" and "dunders" are for. Especially the "_rating" aspect, which
I believe is somehow causing the error.
ERROR:
File "rating.py", line 119, in <module>
r["john"]=20
File "rating.py", line 40, in __setitem__
del self._rating[self.rating(k)] ##
AttributeError: 'Ratings' object has no attribute 'rating'
CODE:
class Ratings(UserDict.DictMixin, dict):
'''The implementation carefully mixes inheritance and delegation
to achieve reasonable performance while minimizing boilerplate,
and, of course, to ensure semantic correctness as above. All
mappings' methods not implemented below get inherited, mostly
from DictMixin, but, crucially!, __getitem__ from dict. '''
def __init__(self, *args, **kwds):
''' This class gets instantiated just like 'dict' '''
dict.__init__(self, *args, **kwds)
# self._rating is the crucial auxiliary data structure: a list
# of all (value, key) pairs, kept in "natural"ly-sorted order
self._rating = [ (v, k) for k, v in dict.iteritems(self) ]
self._rating.sort()
def copy(self):
''' Provide an identical but independent copy '''
return Ratings(self)
def __setitem__(self, k, v):
''' besides delegating to dict, we maintain self._rating '''
if k in self:
del self._rating[self.rating(k)] ##
dict.__setitem__(self, k, v)
insort_left(self._rating, (v, k))
def __delitem__(self, k):
''' besides delegating to dict, we maintain self._rating '''
del self._rating[self.rating(k)]
dict.__delitem__(self, k)
''' delegate some methods to dict explicitly to avoid getting
DictMixin's slower (though correct) implementations instead '''
__len__ = dict.__len__
__contains__ = dict.__contains__
has_key = __contains__
''' the key semantic connection between self._rating and the order
of self.keys( ) -- DictMixin gives us all other methods 'for
free', although we could implement them directly for slightly
better performance. '''
def __iter__(self):
for v, k in self._rating:
yield k
iterkeys = __iter__
def keys(self):
return list(self)
#the three ratings-related methods
def rating(self, key):
item = self[key], key
i = bisect_left(self._rating, item)
if item == self._rating[i]:
return i
raise LookUpError, "item not found in rating"
def getValueByRating(self, rating):
return self._rating[rating][0]
def getKeyByRating(self, rating):
return self._rating[rating][1]
def _test( ):
''' we use doctest to test this module, which must be named
rating.py, by validating all the examples in docstrings. '''
import doctest, rating
doctest.testmod(rating)
print "doc test?"
if __name__ == "__main__":
r = Ratings({"bob":30, "john":30})
print "r is"
print r
print "\n"
print "len(r) is"
print len(r)
print "\n"
print "updating with {'paul': 20, 'tom': 10} "
r.update({"paul": 20, "tom": 10})
print "\n"
print "now r is"
print r
print "\n"
print "r.has_key('paul') is"
print r.has_key("paul")
print "\n"
print " 'paul' in r is"
print ("paul" in r)
print "\n"
print "r.has_key('alex') is"
print r.has_key("alex")
print "\n"
print " 'alex' in r is"
print ("alex" in r)
print '\n'
print 'r is'
print r
print "changing john to '20' with 'r['john']= 20' doesn't work. "
r["john"]=20

wordpress: remove duplicate phrases in a foreach loop

wordpress: remove duplicate phrases in a foreach loop

I have the following problem:
In my wordpres 3.6 I have for posts a custom field called: "topics". The
field is automaticlly filled with phrases from another website by RSS, and
it adds multiple criteria. It is filled in like this:
"Cars,Bikes,Stuff,Gadget"
When I query wordpress with get_posts I get in my foreach loop this:
Cars,Bikes,Stuff,Gadget
Cars,Bikes
Bikes,Stuff
Gadget
I put this into a string and replace some stuff:
$topic_filter = get_posts(
array(
'numberposts' => -1,
'post_status' => 'private',
)
);
$search_topic = array(' ', '-&-', '-|-', '-/-', '---');
$replace_topic = array("-", "-", "-", "-", "-", "");
foreach ($topic_filter as $post_topic) {
$str = str_replace($search_topic, $replace_topic,
get_post_meta($post_topic->ID, 'topic', true));
echo $str;
}
final echo putput is then:
Cars,Bikes,Stuff,Gadget,Cars,Bikes,Bikes,Stuff,Gadget
So far so good. But how to remove the duplicates now?
I tried implode / explode, but it doesn't do anything, because the items
are in a foreach loop I think, and it only apply inside for each post.
But I need the foreach loop, because in the end the goal is to get this
cleaned string as a list in an html output something like this:
<input
type="button"
value="Cars"
class="filter-button"
data-control-type="button-filter"
data-control-action="filter"
data-control-name="Cars-btn"
data-path=".Cars"
/>
<input
type="button"
value="Bikes"
class="filter-button"
data-control-type="button-filter"
data-control-action="filter"
data-control-name="Bikes-btn"
data-path=".Bikes"
/>
<input
type="button"
value="Gadget"
class="filter-button"
data-control-type="button-filter"
data-control-action="filter"
data-control-name="Gadget-btn"
data-path=".Gadget"
/>
seems pretty complicated to me :-(
any ideas? I would be really happy for your help!
Thanks!

Netbeans. Code auto-formatting - Swing layouts section

Netbeans. Code auto-formatting - Swing layouts section

Do you know if is it possible to turn off the auto-code-formatting
(ALT+SHIFT+F) for some particular code fragments in Netbeans? I found some
similar questions, so I see I'm not alone:
Post on netbeans-org
NetBeans, Turn off **ANY** auto indentation / auto formatting
Auto code formatting is excellent and I use it very often, but there are
some cases in which I would like to turn it off. The most frequent case
is, when I have code with Swing's GroupLayout. Example:
inputPanelLayout.setHorizontalGroup(inputPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(inputPanelLayout.createSequentialGroup()
.addGroup(inputPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl1, labelWidth1, labelWidth1, 100)
.addComponent(lbl2, labelWidth1, labelWidth1, 100)
.addComponent(lbl3, labelWidth1, labelWidth1, 100)
.addComponent(lbl4, labelWidth1, labelWidth1, 100)
.addComponent(lbl5, labelWidth1, labelWidth1, 100)
.addComponent(lbl6, labelWidth1, labelWidth1, 100)
.addComponent(lbl6, labelWidth1, labelWidth1, 100))
.addGap(10, 10, 10)
.addGroup(inputPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(inputPanelLayout.createSequentialGroup()
.addComponent(getTxtSomeField(), 50, 100, 150)
.addGap(EDIT_BTN_GAP)
.addComponent(lbl12))
.addComponent(txt5, 50, 122, 150)
.addComponent(txt3, 50, 122, 150)
.addComponent(txt6, 50, 122, 150)
.addComponent(txt7, 50, 122, 150)
.addComponent(txt3, 50, 122, 150)
.addComponent(txt4, 50, 122, 150))
.addGap(16, 16, 16) ... etc
Everything is aligned to left and it's a horror when I have to add
something inside existing layout when it has, for instance, 50 components.
Question: Have you ever came across any solution, which enables to turn
auto-formatting for some particular code fragment?

Thursday, 22 August 2013

When hovering over link, website randomly changes the hover background size

When hovering over link, website randomly changes the hover background size

While working on my website, I have decided to incorporate PHP just to
play around with. I figure I'm paying for it in hosting (sort of), so
might as well use it. The problem I am having is when I hover over a link
in the nav bar I have made, the hover "decoration" that I am using changes
the hover background height. Problem is, it does it on every page BUT not
all the time. Seems random. For some reason it seems to be doing it more
on my about page but I have seen it do it on others. I haven't made any
changes to the others to make them stop nor any changes to the about to
make it start more.
The site in question http://www.journeytomyoasis.com
Since I can't post images yet, here is a link to a screenshot
http://journeytomyoasis.com/images/common/hover_error.png
Code that is in the top of about page
<?php $page_title = "About | Journey to my Oasis"; ?>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=15681725508";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<?php include("includes/header.php");?>
<?php include("includes/navigation.php");?>
code in the navigation.php
<!-- Begin Navigation -->
<nav>
<div id="nav_container">
<div id="menu">
<a href="http://www.journeytomyoasis.com/about.php">ABOUT</a>
<a href="http://www.journeytomyoasis.com/blog">BLOG</a>
<a href="http://www.journeytomyoasis.com/portfolio.php">PORTFOLIO</a>
<a href="http://www.journeytomyoasis.com/blog/journey/">JOURNEY</a>
<a href="http://www.journeytomyoasis.com">HOME</a>
</div>
</div>
At the top of the about page I included the Facebook code that I am using
so that you all know it is there in case you all might think that is it. I
have poured over the code a lot but I cant see an error. The fact that it
is the same php file used on all pages and every page has had issue at
least once but not always confuses me.
I have tested on Firefox and IE 10
Thank you all.

Clientaccesspolicy.xml File Garbled When Accessed from Silverlight App

Clientaccesspolicy.xml File Garbled When Accessed from Silverlight App

I'm stumped. I have created a WCF service for serving up Telerik reports
to a Silverlight 4 application (actually a VS LightSwitch 2010 app). The
service is on a different subdomain (let's call it reports.mydomain.com)
from the Silverlight application (say app.mydomain.com) so I have placed a
clientaccesspolicy.xml file in the root of the IIS7.5-hosted service site
that looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*" http-methods="*">
<domain uri="http://app.mydomain.com">
</domain>
</allow-from>
<grant-to>
<resource path="/">
</resource>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
When I browse to the clientaccesspolicy.xml file in Firefox, I see the XML
just fine. However, when my Telerik Silverlight report viewer control
attempts to access it (I'm verifying this with FireBug), the response it
gets is garbled.
Here's the Firebug output:

And here:

I tried turning off compression in IIS for the WCF site but this had no
effect. Still garbled.
Finally, here's the XML file when accessed in the browser:

Any ideas?

Where do I find C++ source code for some small business applications?

Where do I find C++ source code for some small business applications?



Pleased help me. I'm a student and I want to know real world projects more
than examples that lied in the text book. So please help me how do I find
some websites that can teach me real world C++ projects with source.

Thank you.

Column-Width and Image Wrapping in Firefox

Column-Width and Image Wrapping in Firefox

Using the CSS3 column-width property in Firefox seems to not work as
expected. When an image that is taller than it's container exists, the
image does not wrap onto a new column as expected:
Example in JSFiddle
<div id="container">
<img src="http://placehold.it/300x600" alt="" />
</div>
and
#container {
border: 1px solid #000;
width: 1200px;
height: 300px;
-moz-column-width: 300px;
-webkit-column-width: 300px;
}
One would expect two columns with the top half on the left followed by the
bottom half of the image. This works as expected on Chrome, however with
Firefox, it seems to simply overflow. Is there an additional CSS style
that needs to be applied in this case, or is this something that is
broken/not implemented in Firefox?

gcc c error: expected ')' before numeric constant

gcc c error: expected ')' before numeric constant

Hi I have been trying to port LWIP to a new arm device. When compiling the
code i get the error message:
"lwip/lwip-1.4.0/src/include/lwip/memp_std.h:35:23: error: expected ')'
before numeric constant"
When I go to this file this and below this several similar macros is what
I find on that line:
LWIP_MEMPOOL(RAW_PCB, MEMP_NUM_RAW_PCB, sizeof(struct raw_pcb),
"RAW_PCB")
If I remove the need for this macro with a define to deactivate the RAW
functionality the erorr.
The define it seems to want to put a ')' in front of is defined as this:
#define MEMP_NUM_RAW_PCB 1
The RAW_PCB is not defined but is "combined with MEMP_" to create an
element in an enum.
I have tried to complie the whole ting with the -E option to get human
redable object files and see if i can find any open '(' around the areas
where MEMP_RAW_PCB apears and the substitution of MEMP_NUM_RAW_PCB to 1
but I have not found any by manual inspection yet.
Are there any suggestions on what can be going on here or what more I can
do or look for to find the cause of the error?
I should maybe add that so far I don't call on any of the LWIP code from
main() or any of the functions used in main().

Send RadGrid as quotation to the Gmail

Send RadGrid as quotation to the Gmail

i have created a web page and send this page by email on Gmail. and on
gmail it doesn't pick up any css classes there. but when i send this email
on yahoo or any other professional email it is working very fine.
i am using the css class as below
.tb_head
{
background-color: #da2526;
border: 1px solid #71250a;
border-top: 0;
color: #fff;
text-align: left;
padding: 5px 8px;
}
<HeaderStyle CssClass="tb_head" />
<ItemStyle CssClass="tb_cell" />
these class are embedded inside the page.
and it render on the gmail as
<th scope="col">Location</th>
same is the case for the table rows...
So any help please?

Wednesday, 21 August 2013

how to set selecteditems to listpicker and make sure selected in fullmode?

how to set selecteditems to listpicker and make sure selected in fullmode?

i was used listpicker control set selectmode to Multiple. and define a
list of object collection to selecteditems at phoneapplicationpage loaded
event.
but when i tap listpicker goto the fullmode. i found selecteditems does't
be selected .
how to set selecteditems and make sure get selected in fullmode?

Codemirror editor cursor set to the right

Codemirror editor cursor set to the right

I have to align my textarea on the right of the page. So I have my
textarea code as follows.
<td align="right" >
<textarea style="align:left" id="scriptevalresult"
name="scriptevalresult" cols="64" rows="4"></textarea>
</td>
Because I have align="right" for the , my codemirror editor is set to the
right of the editor.
how to resolve this.

Use CreateThread with a lambda

Use CreateThread with a lambda

Just experimenting, but I was wondering if it's possible to make this code
work:
void main() {
int number = 5;
DWORD(*dontThreadOnMe)(PVOID) = [](PVOID data) {
int value = *(int*) data;
cout << value << endl;
cout << "This callback executed successsfully" << endl;
};
CreateThread(NULL, NULL, dontThreadOnMe, &number, NULL, NULL);
cin.get();
}
I have this nagging suspicion that because the standard signature for a
LPTHREAD_START_ROUTINE callback is DWORD WINAPI Callback(PVOID) I won't be
able to get this to compile without the added (but grammatically illegal)
WINAPI tag. Speaking of which, what exactly are the WINAPI and CALLBACK
(for say WndProc) attributes? I've never really understood why in certain
circumstances you could have multiple attributes on a function.

Switch scope between the browser and dev tools (normal pane and mini console) with keyboard

Switch scope between the browser and dev tools (normal pane and mini
console) with keyboard

In Chrome, when using the dev tools, I sometimes want to switch between
the actual bowser window, and the dev tools window. What keyboard shortcut
exists if at all? Currently I have to click on on window to switch scope.

How do i use Apache for Upload and Nginx for Secure Download

How do i use Apache for Upload and Nginx for Secure Download

I have a website, for file sharing which is in perl, now there is file
index.dl which is used for download request. In apache it creates a very
high load, the load goes almost at 100.
Now i can not use nginx proxy.
I want to set apache to handle all the uploads, and nginx to handle the
download requests.
I have checked there is a module "http-secure-link-module" so i have
installed that as well.
Now our site generates the file download link like
xyz.com/d/$hash/filename.xyz
now this is the code that generates the link
sub genDirectLink
{
my ($file,$mode,$mins,$fname)=@_;
require HCE_MD5;
my $hce = HCE_MD5->new($c->{dl_key},"mysecret");
my $usr_id = $ses->getUser ? $ses->getUserId : 0;
my $dx =
sprintf("%d",($file->{file_real_id}||$file->{file_id})/$c->{files_per_folder});
my $hash = &encode32( $hce->hce_block_encrypt(pack("SLLSA12ASC4L",
$file->{srv_id},
$file->{file_id},
$usr_id,
$dx,
$file->{file_real},
$mode||'f',
$c->{down_speed},
split(/\./,$ses->getIP),
time+60*$mins)) );
#$file->{file_name}=~s/%/%25/g;
#$file->{srv_htdocs_url}=~s/\/files//;
my ($url) = $file->{srv_htdocs_url}=~/(http:\/\/.+?)\//i;
$fname||=$file->{file_name};
return "$url:182/d/$hash/$fname";
}
sub encode32
{
$_=shift;
my($l,$e);
$_=unpack('B*',$_);
s/(.....)/000$1/g;
$l=length;
if($l & 7)
{
$e=substr($_,$l & ~7);
$_=substr($_,0,$l & ~7);
$_.="000$e" . '0' x (5-length $e);
}
$_=pack('B*', $_);
tr|\0-\37|A-Z2-7|;
lc($_);
}
and i have setup my nginx config as
server {
listen 182;
server_name myhost.com www.myhost.com;
location / {
root /home/user/domains/hostname.com/public_html/files;
}
location /d/ {
secure_link_secret mysecret;
if ($secure_link = "") {
return 403;
}
rewrite ^ /files/$secure_link;
}
location /files/ {
internal;
}
So now the problem is, when i tried to visit any link, it gives 404 error.
how do i get file download working?

How to automatically create a cart for a customer in prestashop?

How to automatically create a cart for a customer in prestashop?

I would like to create automatically a cart for a customer with a product.
Then the customer can login on the site and validate the cart.
I saw how to create a cart in my module but i don't understand how to
affect the cart to a customer?

Python multiprocessing exiting cleanly

Python multiprocessing exiting cleanly

I've got a daemon that runs a number of child processes intended to
maintain a telnet connection to collect data from a bunch of weather
stations. I've set it up so that these child processes read from that
telnet connection forever, passing the weather readings back to the parent
process via a multiprocessing.Queue. I can't seem to get these child
processes to exit cleanly when I stop the daemon with ./test.py stop. Is
there an easy way to close the child processes on exit? A quick google
mentioned someone using multiprocessing.Event, what's the best way to set
this event on exit to ensure the processes exit? Here's our current code:
from daemon import runner
from multiprocessing import Process, Queue
import telnetlib
from django.utils.encoding import force_text
from observations.weather.models import WeatherStation
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
def read_weather_data(name, ip_address, port, queue):
print "Started process to get data for", name
client = telnetlib.Telnet(ip_address, port)
while True:
response = client.read_until('\r\n'.encode('utf8'))
queue.put((name, force_text(response)))
client.close()
class App(object):
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/tmp/process_weather.pid'
self.pidfile_timeout = 5
def run(self):
queue = Queue()
for station in WeatherStation.objects.filter(active=True):
p = Process(target=read_weather_data,
args=(station.name, station.ip_address, station.port,
queue,))
p.start()
while True:
name, data = queue.get()
print "Received data from ", name
print data
app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()