Tinymce url needs to be versatile
I need relative path in links which don't have full url and i don't need
relative path in url which have full url.
When i insert in tinymce: 1. I need full url(non-relative path) in:
"http://dignepal.com/images/logo.png" 2. But i don't need full url
(relative path) in: "javascript:"
While initializing tinymce i am currently using relative_urls as false and
it is causing problem in number 2 problem as mentioned above. And main
problem is i need it in same page and in same textarea.
Saturday, August 31, 2013
Can i chain hash table data in python
Can i chain hash table data in python
I have a hash table in python and I have a lot of data and some are the
same but I need to chain them.
I want to make a music database which if i search some numeric values
called HZ i could find the name of the song.
So lets say i hava a song Called Song 1 I measure it HZ values but their
are countless 10 to be specific.
What I want to make is to have the ability to search any HZ value and have
the same result.
Song 1
10 HZ
20 HZ
30 HZ
40 HZ
50 HZ
60 HZ
70 HZ
80 HZ
90 HZ
100 HZ
So if I input any of these 10 values i would get the name Song 1 as results
I have a hash table in python and I have a lot of data and some are the
same but I need to chain them.
I want to make a music database which if i search some numeric values
called HZ i could find the name of the song.
So lets say i hava a song Called Song 1 I measure it HZ values but their
are countless 10 to be specific.
What I want to make is to have the ability to search any HZ value and have
the same result.
Song 1
10 HZ
20 HZ
30 HZ
40 HZ
50 HZ
60 HZ
70 HZ
80 HZ
90 HZ
100 HZ
So if I input any of these 10 values i would get the name Song 1 as results
Stack traces vs. TCO: Do non-tail recursive languages generally have efficient stack frames?
Stack traces vs. TCO: Do non-tail recursive languages generally have
efficient stack frames?
One reason I have heard for some languages to not support tail-call
optimization (TCO) is that this optimization comes at the cost of
obfuscating the call stack if/when debugging should require one to look at
a stack trace. (I have heard other reasons such as "The virtual machine
does not support it", but let's disregard Java for now.)
It seems then that for some set of languages where TCO would be possible,
but one does not perform it, the only purpose of stack frames is to
maintain meta-data for any eventual stack trace to be generated. I.e., the
stack frame could be minimal, containing only enough information to
generate the stack trace.
Question(s): Would it not make sense to minimize the size of such stack
frames? Would it not minimize the use of stack space, thus allowing deeper
levels of recursion before running out of space? Is this attempted in
languages where this thought applies? (I'm thinking in particular of
Python.) Or is this a lost effort with regards to actual space saved? (I
imagine that the meta-data necessary for generating nice stack traces is
actually quite a lot compared to what's normally in a stack frame.)
Idea in short: Minimize size of stack frames as an alternative to TCO.
PS. My thoughts are not based on any actual benchmarks. I could be way off
here.
efficient stack frames?
One reason I have heard for some languages to not support tail-call
optimization (TCO) is that this optimization comes at the cost of
obfuscating the call stack if/when debugging should require one to look at
a stack trace. (I have heard other reasons such as "The virtual machine
does not support it", but let's disregard Java for now.)
It seems then that for some set of languages where TCO would be possible,
but one does not perform it, the only purpose of stack frames is to
maintain meta-data for any eventual stack trace to be generated. I.e., the
stack frame could be minimal, containing only enough information to
generate the stack trace.
Question(s): Would it not make sense to minimize the size of such stack
frames? Would it not minimize the use of stack space, thus allowing deeper
levels of recursion before running out of space? Is this attempted in
languages where this thought applies? (I'm thinking in particular of
Python.) Or is this a lost effort with regards to actual space saved? (I
imagine that the meta-data necessary for generating nice stack traces is
actually quite a lot compared to what's normally in a stack frame.)
Idea in short: Minimize size of stack frames as an alternative to TCO.
PS. My thoughts are not based on any actual benchmarks. I could be way off
here.
swapImage {src: image2.jpg} doesn't respond in Rails 3.1
swapImage {src: 'image2.jpg'} doesn't respond in Rails 3.1
I'm in the midst of upgrading my Rails app from 2.3 to 3.2, but I'm stuck
on 3.1 at the moment.
I'm currently struggling with converting references to image filenames
into a syntax that works with the asset pipeline. The main place I need
with help with this issue is with my button rollover swapImage statements.
Here's an example:
<%= image_submit_tag "signin.jpg", {:class => "swapImage { src:
'#{image_path('signinHover.jpg')}' }" %>
This works in development. But when I deploy this code to production, the
rollover still doesn't work. I get no apparent rollover response at all.
Also, the single quote still appears escaped when I view source:
<input class="swapImage {src: '/assets/signinHover.jpg'}"
src="/assets/signin.jpg" type="image" />
I'm guessing this might be part of my problem.
I'm also wondering if perhaps I'm not loading my javascript/jquery assets
correctly using the asset pipeline. But when I check
https://staging.genlighten.com/assets/application.js, I see the swapImage
code appearing just fine.
I'd appreciate advice on how to implement swapImage correctly in Rails
3.1, with the proper syntax for images served by the asset pipeline.
Alternatively, is there a better approach to rollover button images that I
should use instead?
Thanks very much,
Dean Richardson Genlighten.com
I'm in the midst of upgrading my Rails app from 2.3 to 3.2, but I'm stuck
on 3.1 at the moment.
I'm currently struggling with converting references to image filenames
into a syntax that works with the asset pipeline. The main place I need
with help with this issue is with my button rollover swapImage statements.
Here's an example:
<%= image_submit_tag "signin.jpg", {:class => "swapImage { src:
'#{image_path('signinHover.jpg')}' }" %>
This works in development. But when I deploy this code to production, the
rollover still doesn't work. I get no apparent rollover response at all.
Also, the single quote still appears escaped when I view source:
<input class="swapImage {src: '/assets/signinHover.jpg'}"
src="/assets/signin.jpg" type="image" />
I'm guessing this might be part of my problem.
I'm also wondering if perhaps I'm not loading my javascript/jquery assets
correctly using the asset pipeline. But when I check
https://staging.genlighten.com/assets/application.js, I see the swapImage
code appearing just fine.
I'd appreciate advice on how to implement swapImage correctly in Rails
3.1, with the proper syntax for images served by the asset pipeline.
Alternatively, is there a better approach to rollover button images that I
should use instead?
Thanks very much,
Dean Richardson Genlighten.com
PHP SimpleXML doesn't output anything
PHP SimpleXML doesn't output anything
I'm trying to read an XML file that I created. I'm using this code, but
getting nothing out except 'the file was loaded successfully'. I've tried
xpath and many others, but it just doesn't output. It is possible there is
something wrong with my XML because I created the file by hand and I've
never made an XML file before.
Ultimately, my goal is to be able to read an extension attribute and get
the description, class, and icon.
<?php
if(!$xml = simplexml_load_file('formats.xml')) {
echo 'the file was loaded successfully';
print_r($xml);
}
else {
echo 'the file was not loaded';
}
?>
Here is the XML:
<?xml version="1.0"?>
<group class="doc" icon="./.images/doc.png" />
<type extension="doc" description="Legacy Word Document" />
<type extension="docx" description="XML Word Document" />
<type extension="ppt" description="Legacy PowerPoint" />
<type extension="pptx" description="XML PowerPoint" />
<type extension="pps" description="Legacy PowerPoint Show" />
<type extension="ppsx" description="XML PowerPoint Show" />
<type extension="docm" description="Macro Enabled Word Document" />
<type extension="dot" description="Legacy Word Template" />
<type extension="dotx" description="XML Word Template" />
<type extension="dotm" description="Macro Enabled Word Template" />
<type extension="log" description="A Log File" />
<type extension="msg" description="A Message File" />
<type extension="odt" description="OpenOffice Document" />
<type extension="pages" description="Apple Pages Document" />
<type extension="rtf" description="Rich Text Format" />
<type extension="tex" description="LaTeX Document" />
<type extension="wpd" description="Word Perfect Document" />
<type extension="ini" description="Settings File" />
<type extension="cfg" description="Config File" />
<type extension="conf" description="Config File" />
<type extension="nfo" description="Information File" />
<type extension="inf" description="Autorun File" />
<type extension="wps" description="Works Document" />
</group>
<group class="video" icon="./.images/video.png" />
<type extension="asf" description="Advanced Streaming Format" />
<type extension="asx" description="Windows Media Playlist" />
<type extension="avi" description="Audio-Video Interleave" />
<type extension="flv" description="Flash Player Video" />
<type extension="mkv" description="Matroska Video" />
<type extension="mov" description="Apple Movie" />
<type extension="mp4" description="MPEG 4 Video" />
<type extension="mpg" description="MPEG Video" />
<type extension="rm" description="RealMedia Video" />
<type extension="srt" description="Subtitles File" />
<type extension="swf" description="Flash Animation" />
<type extension="vob" description="DVD Video File" />
<type extension="wmv" description="Windows Media Video" />
<type extension="mpeg" description="Motion Picture Experts Video" />
</group>
I'm trying to read an XML file that I created. I'm using this code, but
getting nothing out except 'the file was loaded successfully'. I've tried
xpath and many others, but it just doesn't output. It is possible there is
something wrong with my XML because I created the file by hand and I've
never made an XML file before.
Ultimately, my goal is to be able to read an extension attribute and get
the description, class, and icon.
<?php
if(!$xml = simplexml_load_file('formats.xml')) {
echo 'the file was loaded successfully';
print_r($xml);
}
else {
echo 'the file was not loaded';
}
?>
Here is the XML:
<?xml version="1.0"?>
<group class="doc" icon="./.images/doc.png" />
<type extension="doc" description="Legacy Word Document" />
<type extension="docx" description="XML Word Document" />
<type extension="ppt" description="Legacy PowerPoint" />
<type extension="pptx" description="XML PowerPoint" />
<type extension="pps" description="Legacy PowerPoint Show" />
<type extension="ppsx" description="XML PowerPoint Show" />
<type extension="docm" description="Macro Enabled Word Document" />
<type extension="dot" description="Legacy Word Template" />
<type extension="dotx" description="XML Word Template" />
<type extension="dotm" description="Macro Enabled Word Template" />
<type extension="log" description="A Log File" />
<type extension="msg" description="A Message File" />
<type extension="odt" description="OpenOffice Document" />
<type extension="pages" description="Apple Pages Document" />
<type extension="rtf" description="Rich Text Format" />
<type extension="tex" description="LaTeX Document" />
<type extension="wpd" description="Word Perfect Document" />
<type extension="ini" description="Settings File" />
<type extension="cfg" description="Config File" />
<type extension="conf" description="Config File" />
<type extension="nfo" description="Information File" />
<type extension="inf" description="Autorun File" />
<type extension="wps" description="Works Document" />
</group>
<group class="video" icon="./.images/video.png" />
<type extension="asf" description="Advanced Streaming Format" />
<type extension="asx" description="Windows Media Playlist" />
<type extension="avi" description="Audio-Video Interleave" />
<type extension="flv" description="Flash Player Video" />
<type extension="mkv" description="Matroska Video" />
<type extension="mov" description="Apple Movie" />
<type extension="mp4" description="MPEG 4 Video" />
<type extension="mpg" description="MPEG Video" />
<type extension="rm" description="RealMedia Video" />
<type extension="srt" description="Subtitles File" />
<type extension="swf" description="Flash Animation" />
<type extension="vob" description="DVD Video File" />
<type extension="wmv" description="Windows Media Video" />
<type extension="mpeg" description="Motion Picture Experts Video" />
</group>
Google maps navigation to a particular place using latitude and lingitude
Google maps navigation to a particular place using latitude and lingitude
I am a newbie to Android development, I am working on Google maps. I am
trying to navigate to particular location by using latitude and longitude.
I have give required permissions in manifest file, but I couldn't do
navigation, please help me.
MainActivity,java
package com.examp.nowmap;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
@SuppressLint("NewApi")
public class MainActivity extends Activity {
static final LatLng GOA = new LatLng(15.193588,73.942366);
private GoogleMap mapn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapn = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
Marker hamburg = mapn.addMarker(new MarkerOptions().position(GOA)
.title(LOCATION_SERVICE));
mapn.moveCamera(CameraUpdateFactory.newLatLngZoom(GOA,
BIND_ALLOW_OOM_MANAGEMENT));
mapn.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.examp.nowmap"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<permission
android:name="com.examp.nowmap.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission
android:name="com.examp.nowmap.package.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"
/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.examp.nowmap.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBZ2omuN7djk6R8eUNLkIrn13DEvnN-q58" />
</application>
</manifest>
I am a newbie to Android development, I am working on Google maps. I am
trying to navigate to particular location by using latitude and longitude.
I have give required permissions in manifest file, but I couldn't do
navigation, please help me.
MainActivity,java
package com.examp.nowmap;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
@SuppressLint("NewApi")
public class MainActivity extends Activity {
static final LatLng GOA = new LatLng(15.193588,73.942366);
private GoogleMap mapn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapn = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
Marker hamburg = mapn.addMarker(new MarkerOptions().position(GOA)
.title(LOCATION_SERVICE));
mapn.moveCamera(CameraUpdateFactory.newLatLngZoom(GOA,
BIND_ALLOW_OOM_MANAGEMENT));
mapn.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.examp.nowmap"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<permission
android:name="com.examp.nowmap.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission
android:name="com.examp.nowmap.package.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"
/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.examp.nowmap.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBZ2omuN7djk6R8eUNLkIrn13DEvnN-q58" />
</application>
</manifest>
how to modify/update database row using wcf http json
how to modify/update database row using wcf http json
I am looking for way to update the database record. I am using android
client to take input from user. Android client is communicating with sql
database through wcf json written in c#.
I googled and also search through stackoverflow, finally come to know that
I can use http PUT to update the record. I tried to implement the http PUT
method in my android client and c#. Its working fine in c# (checked by
fiddler).
I want to use json http method not xml. hence searched and didn't find any
good working example.
Please help how can I implement Http Put json method in android.
I am looking for way to update the database record. I am using android
client to take input from user. Android client is communicating with sql
database through wcf json written in c#.
I googled and also search through stackoverflow, finally come to know that
I can use http PUT to update the record. I tried to implement the http PUT
method in my android client and c#. Its working fine in c# (checked by
fiddler).
I want to use json http method not xml. hence searched and didn't find any
good working example.
Please help how can I implement Http Put json method in android.
hide and show layout based on conditions in android
hide and show layout based on conditions in android
i am new to android.i want to hide and show Linearlayout based on if else
conditions.in my application i have taken 1 spinner. baesd on selected
spinner values i want my next layout hide or visible. but if it is once
gone .it not comes visible again please help me guys...
my code is...
public class Expense extends Activity{
Spinner datype;
public void onCreate(Bundle b){
super.onCreate(b);
setContentView(R.layout.expense);
mainlayout=(LinearLayout)this.findViewById(R.id.layout1);
datype=(Spinner)findViewById(R.id.da_type);
List<String>data1=new ArrayList<String>();
data1.add("Local");
data1.add("Ex-Station Double Side");
data1.add("Ex-Station Single Side");
data1.add("Out-Station Double Side");
data1.add("Out-Station Single Side");
ArrayAdapter<String>adapter=new
ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,data1);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
datype.setAdapter(adapter);
if(datype.getSelectedItem().toString().equals("Local")){
mainlayout.setVisibility(LinearLayout.GONE);
}
else
mainlayout.setVisibility(LinearLayout.VISIBLE);
}
}
if any one tell me proper solution for my problem..... it is urgent
i am new to android.i want to hide and show Linearlayout based on if else
conditions.in my application i have taken 1 spinner. baesd on selected
spinner values i want my next layout hide or visible. but if it is once
gone .it not comes visible again please help me guys...
my code is...
public class Expense extends Activity{
Spinner datype;
public void onCreate(Bundle b){
super.onCreate(b);
setContentView(R.layout.expense);
mainlayout=(LinearLayout)this.findViewById(R.id.layout1);
datype=(Spinner)findViewById(R.id.da_type);
List<String>data1=new ArrayList<String>();
data1.add("Local");
data1.add("Ex-Station Double Side");
data1.add("Ex-Station Single Side");
data1.add("Out-Station Double Side");
data1.add("Out-Station Single Side");
ArrayAdapter<String>adapter=new
ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,data1);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
datype.setAdapter(adapter);
if(datype.getSelectedItem().toString().equals("Local")){
mainlayout.setVisibility(LinearLayout.GONE);
}
else
mainlayout.setVisibility(LinearLayout.VISIBLE);
}
}
if any one tell me proper solution for my problem..... it is urgent
Friday, August 30, 2013
Print flowdocument scroll viewer on multiple pages
Print flowdocument scroll viewer on multiple pages
I'm trying to print my FlowDocument (which is wrapped into a
FlowDocumentScrollViewer) because I have a lot of texts/Textbox/combobox
and the page height can become high !
I'm using this :
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == true)
{
Scrollvvv.Document.ColumnWidth =
printDialog.PrintableAreaWidth;
Scrollvvv.Document.ColumnGap = 0;
printDialog.PrintDocument(((IDocumentPaginatorSource)Scrollvvv.Document).DocumentPaginator,
ServicesLangue.RM.GetString("TITRE_MODIFIER_SALON_EXPOSANT"));
}
My xaml looks like :
<FlowDocumentScrollViewer Name="Scrollvvv"
VerticalScrollBarVisibility="Auto">
<FlowDocument Name="flowDoc" PagePadding="10">
<Section>
<BlockUIContainer>
<Grid Name="grid_principale">
<!-- Lot of stuffs here -->
</Grid>
</BlockUIContainer>
</Section>
</FlowDocument>
</FlowDocumentScrollViewer>
The thing is : It prints all my data in 1 page, the width is ok (i might
add some margin but that's ok) but it compresses all my controls to fit in
one page in height.
How to fix this ? I'd just want to disable this auto Height and keep the
original size.
Thanks !
I'm trying to print my FlowDocument (which is wrapped into a
FlowDocumentScrollViewer) because I have a lot of texts/Textbox/combobox
and the page height can become high !
I'm using this :
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == true)
{
Scrollvvv.Document.ColumnWidth =
printDialog.PrintableAreaWidth;
Scrollvvv.Document.ColumnGap = 0;
printDialog.PrintDocument(((IDocumentPaginatorSource)Scrollvvv.Document).DocumentPaginator,
ServicesLangue.RM.GetString("TITRE_MODIFIER_SALON_EXPOSANT"));
}
My xaml looks like :
<FlowDocumentScrollViewer Name="Scrollvvv"
VerticalScrollBarVisibility="Auto">
<FlowDocument Name="flowDoc" PagePadding="10">
<Section>
<BlockUIContainer>
<Grid Name="grid_principale">
<!-- Lot of stuffs here -->
</Grid>
</BlockUIContainer>
</Section>
</FlowDocument>
</FlowDocumentScrollViewer>
The thing is : It prints all my data in 1 page, the width is ok (i might
add some margin but that's ok) but it compresses all my controls to fit in
one page in height.
How to fix this ? I'd just want to disable this auto Height and keep the
original size.
Thanks !
Thursday, August 29, 2013
php convert png to svg [on hold]
php convert png to svg [on hold]
Any one suggest code for php. I want to create svg zoom-able image from
png images regarding for PDF highly zoom-able like 6000%. please give me
idea about php code or php command line code.
Thanks, Pushparaj
Any one suggest code for php. I want to create svg zoom-able image from
png images regarding for PDF highly zoom-able like 6000%. please give me
idea about php code or php command line code.
Thanks, Pushparaj
Creating arrays with size as a variable
Creating arrays with size as a variable
I am trying to create a new array in this way:
final boolean[] arr = new boolean[list.size()];
This line is throwing a null pointer in my code in some cases. Under what
situations can this happen? Can it happen when the list has zero elements?
I am sure the list is not null at this stage.
I am trying to create a new array in this way:
final boolean[] arr = new boolean[list.size()];
This line is throwing a null pointer in my code in some cases. Under what
situations can this happen? Can it happen when the list has zero elements?
I am sure the list is not null at this stage.
Wednesday, August 28, 2013
How do I use values from a tuple whic is in a list of tuples as arguments for a function?
How do I use values from a tuple whic is in a list of tuples as arguments
for a function?
I'm trying to construct a simple tilemap thingy, as part of a larger
project, and one of the solutions I came out with was to use a function
like so:
def tile((value, X, Y)):
if value == 1:
pygame.draw.rect(screen, (0, 0, 0) (X, Y, 64, 64), 0)
The idea being that I set the level out as a list of tuples that contain a
value which denotes the tile to be drawn there, and then the coordinates
of that tile.
This, of course, doesn't work since you can't use a tuple as an argument.
My solution to this was to instead get the values out of the tuple in the
list:
def tile(value, X, Y):
if value == 1:
pygame.draw.rect(screen, (0, 0, 0) (X, Y, 64, 64), 0)
level = [(1, 0, 0), (rest of list)]
tile(level[0[0]], level[0[1]], level[0[2]])
Which didn't work, and gave me
Traceback (most recent call last):
tile(level[0[0]], level[0[1]], level[0[2]])
TypeError: 'int' object has no attribute '__getitem__'
Does anyone have a workaround for this? Some way I can feed a tuple into a
function as a series of arguments? Or am I just using a completely
idiosyncratic method that won't ever work ever? I'm guessing this is just
due to my blinding incompetence, although I would like to be told
otherwise.
Python 2.7, pygame 1.9
for a function?
I'm trying to construct a simple tilemap thingy, as part of a larger
project, and one of the solutions I came out with was to use a function
like so:
def tile((value, X, Y)):
if value == 1:
pygame.draw.rect(screen, (0, 0, 0) (X, Y, 64, 64), 0)
The idea being that I set the level out as a list of tuples that contain a
value which denotes the tile to be drawn there, and then the coordinates
of that tile.
This, of course, doesn't work since you can't use a tuple as an argument.
My solution to this was to instead get the values out of the tuple in the
list:
def tile(value, X, Y):
if value == 1:
pygame.draw.rect(screen, (0, 0, 0) (X, Y, 64, 64), 0)
level = [(1, 0, 0), (rest of list)]
tile(level[0[0]], level[0[1]], level[0[2]])
Which didn't work, and gave me
Traceback (most recent call last):
tile(level[0[0]], level[0[1]], level[0[2]])
TypeError: 'int' object has no attribute '__getitem__'
Does anyone have a workaround for this? Some way I can feed a tuple into a
function as a series of arguments? Or am I just using a completely
idiosyncratic method that won't ever work ever? I'm guessing this is just
due to my blinding incompetence, although I would like to be told
otherwise.
Python 2.7, pygame 1.9
Windows 8 - how to disable close application gesture?
Windows 8 - how to disable close application gesture?
I'm writing app in Metro UI that will be used in stand with touch screen.
This application must be protected against the possibility of its closure.
How disable close gesture (drag finger down)?
I'm writing app in Metro UI that will be used in stand with touch screen.
This application must be protected against the possibility of its closure.
How disable close gesture (drag finger down)?
jquery counter reset issue
jquery counter reset issue
I have the following code and even after a page refresh, the counter is
not getting a reset. Please help me out in resetting the "counter". Also
excuse me if there are any typo(s) or dirty coding.
<script type='text/javascript'>
$(window).load(function(){
$(document).ready(function() {
$('p').click(function() {
$(this).animate({
'color': 'rgb(' + (Math.floor(Math.random() * 256)) + ',' +
(Math.floor(Math.random() * 256)) + ',' +
(Math.floor(Math.random() * 256)) + ')'
}, 500);
});
$('#counter').data('count', 0);
$("#fl1").click(function() {
$('#counter').val(function(i, val) {
return val == '0' ? 1 : val + 1;
});
});
$('#counter').data('count', 0);
$("#fl2").click(function() {
$('#counter').val(function(i, val) {
return val == '0' ? 2 : val + 2;
});
});
});
});
</script>
</head>
<body>
<div id="fl1" style="float:left; margin: 20px 0 0 0; font-weight: bold;
display: inline; cursor: pointer;"><p>(1)</p></div>
<div id="fl2" style="float:left; margin: 20px 0 0 40px; font-weight:
bold; display: inline; cursor: pointer;"><p>(2)</p></div>
<br />
<form method=POST name="test" action="test.php">
<input type="hidden" name="counter" id="counter">
<input type="submit" value="Send" >
</form>
</body>
I have the following code and even after a page refresh, the counter is
not getting a reset. Please help me out in resetting the "counter". Also
excuse me if there are any typo(s) or dirty coding.
<script type='text/javascript'>
$(window).load(function(){
$(document).ready(function() {
$('p').click(function() {
$(this).animate({
'color': 'rgb(' + (Math.floor(Math.random() * 256)) + ',' +
(Math.floor(Math.random() * 256)) + ',' +
(Math.floor(Math.random() * 256)) + ')'
}, 500);
});
$('#counter').data('count', 0);
$("#fl1").click(function() {
$('#counter').val(function(i, val) {
return val == '0' ? 1 : val + 1;
});
});
$('#counter').data('count', 0);
$("#fl2").click(function() {
$('#counter').val(function(i, val) {
return val == '0' ? 2 : val + 2;
});
});
});
});
</script>
</head>
<body>
<div id="fl1" style="float:left; margin: 20px 0 0 0; font-weight: bold;
display: inline; cursor: pointer;"><p>(1)</p></div>
<div id="fl2" style="float:left; margin: 20px 0 0 40px; font-weight:
bold; display: inline; cursor: pointer;"><p>(2)</p></div>
<br />
<form method=POST name="test" action="test.php">
<input type="hidden" name="counter" id="counter">
<input type="submit" value="Send" >
</form>
</body>
Tuesday, August 27, 2013
Convert two vectors of int with the same length into one vector of pairs of int in C++
Convert two vectors of int with the same length into one vector of pairs
of int in C++
In C++, if I have two vectors of int A = [1, 2, 3 ,4] and B = [1, 2, 3,
4], how can I merge them into one vector of pairs as [(1,1), (2,2), (3,3),
(4, 4)]? Of course I can do that with a loop. But can we do that using
suitable STL functions and iterators?
Thanks!
of int in C++
In C++, if I have two vectors of int A = [1, 2, 3 ,4] and B = [1, 2, 3,
4], how can I merge them into one vector of pairs as [(1,1), (2,2), (3,3),
(4, 4)]? Of course I can do that with a loop. But can we do that using
suitable STL functions and iterators?
Thanks!
statnet network missing vertexes
statnet network missing vertexes
I am using network claas from statnet in R.
They have some tutorials in statistical software journal. So I founf
information about 'na' attribute for vertexes and edges. But I can not
find any information in manual or the Internet about this for vertexes (
it still some about edges ). This attribute is logical and if TRUE then
vertex is unobserved. And when I print network class vertexes and edges do
not have that attribute, but tutorial says that it is default attribute.
Does anybode know what happend to this attribute or it just me can not
find info.
I am using network claas from statnet in R.
They have some tutorials in statistical software journal. So I founf
information about 'na' attribute for vertexes and edges. But I can not
find any information in manual or the Internet about this for vertexes (
it still some about edges ). This attribute is logical and if TRUE then
vertex is unobserved. And when I print network class vertexes and edges do
not have that attribute, but tutorial says that it is default attribute.
Does anybode know what happend to this attribute or it just me can not
find info.
Masonry not working with dynamic content
Masonry not working with dynamic content
Masonry is not working with my dynamic content, I don't know why. I don't
think it's a bug on my side, at least I've looked at the code for a few
hours now and I can't find anything that isn't working.
//reads listbox.php and cycles through the array calling createbox
function listboxs(){
$.ajax({
url: '_php/listbox.php',
success: function(output){
var jsonArray = $.parseJSON(output);
$.each( jsonArray, function(i, box ) {
createbox(box.id, box.name, box.link, box.description, box.tags);
});
}
});
}
//create the code for 1 box
function createbox(id, name, link, description, tags){
var boxHtml = "",
tagsHtml = "",
descriptionHtml = "";
boxHtml = '' +
'<div class="box" id="'+id+'">' +
'<div class="boxinfo">' +
'<label class="boxname"><a href="'+link+'" class="boxlink"
target="_blank">'+name+'</a></label>';
$.each(tags, function( i, tag ) {
tagsHtml += '<label class="boxtag">'+ ((!tag.name) ? tags[i] : tag.name)
+'</label>';
});
//if(description.trim().length > 0){
descriptionHtml = '<textarea class="boxdescription" readonly
rows="1">'+description+'</textarea>';
//}
boxHtml += tagsHtml +
'</div>' +
descriptionHtml +
'</div>';
$content.html($content.html() + boxHtml);
}
Below is the simplified HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="_css/index.css" />
<link href='http://fonts.googleapis.com/css?family=Marck+Script'
rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Rosario'
rel='stylesheet' type='text/css'>
<script src="_resources/jquery-2.0.3.min.js" type="text/javascript"
language="javascript"></script >
<script src="_resources/masonry.pkgd.min.js"></script>
<script type="text/javascript" language="javascript">
$('#content').masonry();
</script >
</head>
<body>
<div id="content" class="js-masonry">
</div>
</body>
</html>
I know that I don't need the inline javascript calling masonry on content
but it's one of my many tests...
Below is part of the CSS:
#content{
padding: 15px;
min-height: 400px;
}
/*
################################
box
*/
.box{
border: 1px solid black;
float: left;
padding: 5px;
background: #F0F0F0;
margin-left: 5px;
margin-bottom: 5px;
}
.boxinfo{
border-bottom: 1px solid black;
}
.boxname{
font-weight: bold;
}
.boxdescription{
border: none;
outline: none;
background: white;
overflow: hidden;
}
.boxtag{
margin-left: 5px;
}
#boxdecoy{
height: 45px;
}
.boxname, .boxtag, .boxdescription{
font-family: 'Rosario', sans-serif;
font-size: 12px;
}
.boxlink{
text-decoration: none;
color: black;
}
.boxlink:hover{
text-decoration: underline;
}
I'm really going crazy with all of it because I tested creating boxes by
hand (this means writting in the html) in content, and if i do masonry
works fine. If i create them through the function that you see there it
doesn't work... i call listboxs right in the begining of the javascript
file after I declare all my vars...
Hope I was clear and you can help me.
Masonry is not working with my dynamic content, I don't know why. I don't
think it's a bug on my side, at least I've looked at the code for a few
hours now and I can't find anything that isn't working.
//reads listbox.php and cycles through the array calling createbox
function listboxs(){
$.ajax({
url: '_php/listbox.php',
success: function(output){
var jsonArray = $.parseJSON(output);
$.each( jsonArray, function(i, box ) {
createbox(box.id, box.name, box.link, box.description, box.tags);
});
}
});
}
//create the code for 1 box
function createbox(id, name, link, description, tags){
var boxHtml = "",
tagsHtml = "",
descriptionHtml = "";
boxHtml = '' +
'<div class="box" id="'+id+'">' +
'<div class="boxinfo">' +
'<label class="boxname"><a href="'+link+'" class="boxlink"
target="_blank">'+name+'</a></label>';
$.each(tags, function( i, tag ) {
tagsHtml += '<label class="boxtag">'+ ((!tag.name) ? tags[i] : tag.name)
+'</label>';
});
//if(description.trim().length > 0){
descriptionHtml = '<textarea class="boxdescription" readonly
rows="1">'+description+'</textarea>';
//}
boxHtml += tagsHtml +
'</div>' +
descriptionHtml +
'</div>';
$content.html($content.html() + boxHtml);
}
Below is the simplified HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="_css/index.css" />
<link href='http://fonts.googleapis.com/css?family=Marck+Script'
rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Rosario'
rel='stylesheet' type='text/css'>
<script src="_resources/jquery-2.0.3.min.js" type="text/javascript"
language="javascript"></script >
<script src="_resources/masonry.pkgd.min.js"></script>
<script type="text/javascript" language="javascript">
$('#content').masonry();
</script >
</head>
<body>
<div id="content" class="js-masonry">
</div>
</body>
</html>
I know that I don't need the inline javascript calling masonry on content
but it's one of my many tests...
Below is part of the CSS:
#content{
padding: 15px;
min-height: 400px;
}
/*
################################
box
*/
.box{
border: 1px solid black;
float: left;
padding: 5px;
background: #F0F0F0;
margin-left: 5px;
margin-bottom: 5px;
}
.boxinfo{
border-bottom: 1px solid black;
}
.boxname{
font-weight: bold;
}
.boxdescription{
border: none;
outline: none;
background: white;
overflow: hidden;
}
.boxtag{
margin-left: 5px;
}
#boxdecoy{
height: 45px;
}
.boxname, .boxtag, .boxdescription{
font-family: 'Rosario', sans-serif;
font-size: 12px;
}
.boxlink{
text-decoration: none;
color: black;
}
.boxlink:hover{
text-decoration: underline;
}
I'm really going crazy with all of it because I tested creating boxes by
hand (this means writting in the html) in content, and if i do masonry
works fine. If i create them through the function that you see there it
doesn't work... i call listboxs right in the begining of the javascript
file after I declare all my vars...
Hope I was clear and you can help me.
Set CSS class from one page to another - WordPress, jQuery AJAX
Set CSS class from one page to another - WordPress, jQuery AJAX
In WP theme I have post.php (for single post item) and blog.php (for blog
layout). On single post, CSS classes are added to post div via jQuery (on
click).
How to get that classes (strings)from single post (post.php) and use them
in blog.php?
EG. Single post (post.php) print this html
<article class="single-post post-1">
<p>sometext</p>
<a>click</a>
</article>
<script>
jQuery("a").click(function(){
jQuery("article").addClass("singleClass");
});
</script>
Blog posts (blog.php)
<article class="blog-post post-1">
<p>sometext</p>
</article>
<article class="blog-post post-2">
<p>sometext</p>
</article>
And also to get class from single post 1 and add it to blog post 1, post 2
to post 2, etc. First time trying AJAX, so I'm not sure what to do. jQuery
in post.php
var postClass = voteText+'-'+voteNumber; //some variables declared earlier
jQuery.ajax({
type: "POST",
url: "ajax-class.php", //or /wp-admin/admin-ajax.php? This mean that
data is posted to this file?
data: { 'dataString': postClass },
cache: false,
success: function() {
alert("Classes: "+postClass); // alert goes fine
}
});
now I need to GET data from ajax-class.php?
<?php echo 'Classes: '. $_POST['postClass']; ?>
This is not working. If someone could just point me to right direction.
Documentation and stuff. Thanx
In WP theme I have post.php (for single post item) and blog.php (for blog
layout). On single post, CSS classes are added to post div via jQuery (on
click).
How to get that classes (strings)from single post (post.php) and use them
in blog.php?
EG. Single post (post.php) print this html
<article class="single-post post-1">
<p>sometext</p>
<a>click</a>
</article>
<script>
jQuery("a").click(function(){
jQuery("article").addClass("singleClass");
});
</script>
Blog posts (blog.php)
<article class="blog-post post-1">
<p>sometext</p>
</article>
<article class="blog-post post-2">
<p>sometext</p>
</article>
And also to get class from single post 1 and add it to blog post 1, post 2
to post 2, etc. First time trying AJAX, so I'm not sure what to do. jQuery
in post.php
var postClass = voteText+'-'+voteNumber; //some variables declared earlier
jQuery.ajax({
type: "POST",
url: "ajax-class.php", //or /wp-admin/admin-ajax.php? This mean that
data is posted to this file?
data: { 'dataString': postClass },
cache: false,
success: function() {
alert("Classes: "+postClass); // alert goes fine
}
});
now I need to GET data from ajax-class.php?
<?php echo 'Classes: '. $_POST['postClass']; ?>
This is not working. If someone could just point me to right direction.
Documentation and stuff. Thanx
How to select only specific columns from a DataFrame with MultiIndex columns?
How to select only specific columns from a DataFrame with MultiIndex columns?
I have DataFrame with MultiIndex columns that looks like this:
# sample data
col = pd.MultiIndex.from_arrays([['one', 'one', 'one', 'two', 'two', 'two'],
['a', 'b', 'c', 'a', 'b', 'c']])
data = pd.DataFrame(np.random.randn(4, 6), columns=col)
data
What is the proper, simple way of selecting only specific columns (e.g.
['a', 'c'], not a range) from the second level?
Currently I am doing it like this:
import itertools
tuples = [i for i in itertools.product(['one', 'two'], ['a', 'c'])]
new_index = pd.MultiIndex.from_tuples(tuples)
print(new_index)
data.reindex_axis(new_index, axis=1)
It doesn't feel like a good solution, however, because I have to bust out
itertools, build another MultiIndex by hand and then reindex (and my
actual code is even messier, since the column lists aren't so simple to
fetch). I am pretty sure there has to be some ix or xs way of doing this,
but everything I tried resulted in errors.
I have DataFrame with MultiIndex columns that looks like this:
# sample data
col = pd.MultiIndex.from_arrays([['one', 'one', 'one', 'two', 'two', 'two'],
['a', 'b', 'c', 'a', 'b', 'c']])
data = pd.DataFrame(np.random.randn(4, 6), columns=col)
data
What is the proper, simple way of selecting only specific columns (e.g.
['a', 'c'], not a range) from the second level?
Currently I am doing it like this:
import itertools
tuples = [i for i in itertools.product(['one', 'two'], ['a', 'c'])]
new_index = pd.MultiIndex.from_tuples(tuples)
print(new_index)
data.reindex_axis(new_index, axis=1)
It doesn't feel like a good solution, however, because I have to bust out
itertools, build another MultiIndex by hand and then reindex (and my
actual code is even messier, since the column lists aren't so simple to
fetch). I am pretty sure there has to be some ix or xs way of doing this,
but everything I tried resulted in errors.
Whitespace/margin around last item on navigation list
Whitespace/margin around last item on navigation list
Can anyone give me a pointer on a site I've inherited. I'm more of an SEO
guy than raw code and I'm not making any headway on this.
Have a look at http://www.edwardjackson.co.uk and you'll see whitespace
around the last item in the left hand navigation list "Home Condition
reports".
Can anyone give me a steer as to what's causing this & what to do about it?
What I think is the relevant part of css is:
.nav li ul li a {
display: block;
list-style-type: none;
height: 18px;
text-transform: uppercase;
color: #504c40;
margin-left: -80px;
padding-left: 10px;
text-decoration: none;
background-image: none;
padding-top: 0px;
padding-bottom: 0px;
margin-bottom: 10px;
font-size: 11px;
}
.nav li ul li a:hover {
display: block;
list-style-type: none;
height: 18px;
text-transform: uppercase;
color: #504c40;
margin-left: -80px;
padding-left: 10px;
background-image: none;
padding-top: 0px;
padding-bottom: 0px;
margin-bottom: 10px;
text-decoration: underline;
Many Thanks - Dunc.
Can anyone give me a pointer on a site I've inherited. I'm more of an SEO
guy than raw code and I'm not making any headway on this.
Have a look at http://www.edwardjackson.co.uk and you'll see whitespace
around the last item in the left hand navigation list "Home Condition
reports".
Can anyone give me a steer as to what's causing this & what to do about it?
What I think is the relevant part of css is:
.nav li ul li a {
display: block;
list-style-type: none;
height: 18px;
text-transform: uppercase;
color: #504c40;
margin-left: -80px;
padding-left: 10px;
text-decoration: none;
background-image: none;
padding-top: 0px;
padding-bottom: 0px;
margin-bottom: 10px;
font-size: 11px;
}
.nav li ul li a:hover {
display: block;
list-style-type: none;
height: 18px;
text-transform: uppercase;
color: #504c40;
margin-left: -80px;
padding-left: 10px;
background-image: none;
padding-top: 0px;
padding-bottom: 0px;
margin-bottom: 10px;
text-decoration: underline;
Many Thanks - Dunc.
Filecontents and newenvironment issue tex.stackexchange.com
Filecontents and newenvironment issue – tex.stackexchange.com
I need to write some inlined code on an external file, then load it with
listings. I would like to define a new environment, but if I do,
filecontents does not save the first line of code (see MWE): …
I need to write some inlined code on an external file, then load it with
listings. I would like to define a new environment, but if I do,
filecontents does not save the first line of code (see MWE): …
Python matplotlib pcolor some labels are missing if the plot is not square
Python matplotlib pcolor some labels are missing if the plot is not square
I am trying to create a heatmap with pcolor using the example from Heatmap
in matplotlib with pcolor? but I run into trouble.
First the example from the accepted anwser doesnt work for me and I get
the following error message:
Traceback (most recent call last):
File "/home/knorrs/temp/HeatMapTest.py", line 22, in <module>
heatmap = ax.pcolor(nba_sort, cmap=plt.cm.Blues, alpha=0.8)
File
"/home/martin/pybin/lib/python2.7/site-packages/matplotlib/axes.py",
line 7309, in pcolor
X, Y, C = self._pcolorargs('pcolor', *args)
File
"/home/martin/pybin/lib/python2.7/site-packages/matplotlib/axes.py",
line 7132, in _pcolorargs
numRows, numCols = C.shape
AttributeError: 'NoneType' object has no attribute 'shape'
Creating the plot "my" way leads to a good result with one exception: the
labels / ticks on the y-axis stop after a while. It seems that the number
of labels on the y-axis has to be of the same size as the number of labels
on the x-axis.
Here is the part of my code responsible for the creation of the heatmap.
Note that data is a two dimensional array (data.shape yields (20, 13)).
AA = ['G', 'A', 'V', 'S', 'T', 'C', 'M', 'L', 'I', 'K', 'R', 'E', 'D',
'Q', 'N', 'F', 'Y', 'W', 'P', 'H']
def plot_heatmap(data):
x_min = ((data.shape[1]-1)/2)*-1 #if the shape is for example 13
(has to be odd) we set the x_min to -6
x_max = (data.shape[1]-1)/2 #and the x_max to +6
x_labels = range(x_min,x_max+1,1) #this way we create the x_labels
going from -6 over 0 to +6
fig = pl.figure(figsize=(24,18))
ax = fig.add_subplot(1,1,1)
plot = ax.pcolor(data, cmap=pl.cm.Blues, edgecolors='k')
# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)
ax.set_ybound(lower = 0, upper = data.shape[0])
ax.set_xbound(lower = 0, upper = data.shape[1])
# want a more natural, table-like display
ax.invert_yaxis()
#ax.xaxis.tick_top()
ax.set_xticklabels(x_labels, minor=False)
ax.set_yticklabels(AA, minor=False)
fig.colorbar(plot)
pl.show()
You can find the resulting figure at
http://picload.org/view/oaidpww/heatmap.png.html
If you could tell me the reason for this behaviour and the way to change
it, I would be very happy.
I am trying to create a heatmap with pcolor using the example from Heatmap
in matplotlib with pcolor? but I run into trouble.
First the example from the accepted anwser doesnt work for me and I get
the following error message:
Traceback (most recent call last):
File "/home/knorrs/temp/HeatMapTest.py", line 22, in <module>
heatmap = ax.pcolor(nba_sort, cmap=plt.cm.Blues, alpha=0.8)
File
"/home/martin/pybin/lib/python2.7/site-packages/matplotlib/axes.py",
line 7309, in pcolor
X, Y, C = self._pcolorargs('pcolor', *args)
File
"/home/martin/pybin/lib/python2.7/site-packages/matplotlib/axes.py",
line 7132, in _pcolorargs
numRows, numCols = C.shape
AttributeError: 'NoneType' object has no attribute 'shape'
Creating the plot "my" way leads to a good result with one exception: the
labels / ticks on the y-axis stop after a while. It seems that the number
of labels on the y-axis has to be of the same size as the number of labels
on the x-axis.
Here is the part of my code responsible for the creation of the heatmap.
Note that data is a two dimensional array (data.shape yields (20, 13)).
AA = ['G', 'A', 'V', 'S', 'T', 'C', 'M', 'L', 'I', 'K', 'R', 'E', 'D',
'Q', 'N', 'F', 'Y', 'W', 'P', 'H']
def plot_heatmap(data):
x_min = ((data.shape[1]-1)/2)*-1 #if the shape is for example 13
(has to be odd) we set the x_min to -6
x_max = (data.shape[1]-1)/2 #and the x_max to +6
x_labels = range(x_min,x_max+1,1) #this way we create the x_labels
going from -6 over 0 to +6
fig = pl.figure(figsize=(24,18))
ax = fig.add_subplot(1,1,1)
plot = ax.pcolor(data, cmap=pl.cm.Blues, edgecolors='k')
# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)
ax.set_ybound(lower = 0, upper = data.shape[0])
ax.set_xbound(lower = 0, upper = data.shape[1])
# want a more natural, table-like display
ax.invert_yaxis()
#ax.xaxis.tick_top()
ax.set_xticklabels(x_labels, minor=False)
ax.set_yticklabels(AA, minor=False)
fig.colorbar(plot)
pl.show()
You can find the resulting figure at
http://picload.org/view/oaidpww/heatmap.png.html
If you could tell me the reason for this behaviour and the way to change
it, I would be very happy.
Monday, August 26, 2013
Is there a way to add items from server under and keep ul ID as i want?
Is there a way to add items from server under and keep ul ID as i want?
First, note that im using C#.
Basically, i know i can add server controls under a ul tag which is
runat=server:
HTML:
<ul id="myID" runat="server"></ul>
C#:
myId.Controls.Add(...);
but the issue is that once i add these items, the ul item has now a new
generated id (such as: id=ctl00_cphMainContainer_ctl00_myID) which ruins
my javascript code and also my css.
I was wondering, is there a clean way i could add my li items and keep my
ul as it is?
First, note that im using C#.
Basically, i know i can add server controls under a ul tag which is
runat=server:
HTML:
<ul id="myID" runat="server"></ul>
C#:
myId.Controls.Add(...);
but the issue is that once i add these items, the ul item has now a new
generated id (such as: id=ctl00_cphMainContainer_ctl00_myID) which ruins
my javascript code and also my css.
I was wondering, is there a clean way i could add my li items and keep my
ul as it is?
Function With Multiple Values JavaScript+JSP+Servlet
Function With Multiple Values JavaScript+JSP+Servlet
I have a project in Java with JSP+JavaScript+Servlets, with a function in
JavaScript to find some record in my database. When this record is found,
my function returns some value, and when it's not, my function returns a
message. Now I need another function to return several fields from my
database, and I don't know who. I'm not very familiar with JavaScript and
JSP.
This is part from my JSP code:
<tr>
<td>
<input type='text' id="noeco" name="noeco" size=5 maxlength=5
onkeyup="find_noeco_s(noeco,exists);">
<span name="exists" id="exists" readonly="readonly" style="width:
200px" value="{exists}"></span></input>
</td>
</tr>
<tr>
<td>
<input type='text' id="matric" name="matric" readonly="readonly"
value="{matric}"></input>
</td>
</tr>
<tr>
<td>
<input type='text' id="marca" name="marca" readonly="readonly"
value="{marca}"></input>
</td>
</tr>
<tr>
<td>
<input type='text' id="submarca" name="submarca" readonly="readonly"
value="{submarca}"></input>
</td>
</tr>
This is my JavaScript function "find_noeco_s":
function find_noeco_s(noeco,exists){
objsal = exists;
if(window.XMLHttpRequest)
ajax = new XMLHttpRequest();
else
ajax = new ActiveXObject("Microsoft.XMLHTTP");
ajax.onreadystatechange = funcionCallback;
ajax.open("GET", "/processEco.jsp?noeco="+noeco.value, true);
ajax.send("");
}
And this is my JSP processEco:
String noeco = request.getParameter("noeco");
String exists="";
String matri= "";
try{
PreparedStatement ps = PV.prepareStatement("select * from vehicles
where econom=?");
ps.setString(1, noeco);
ResultSet rs = ps.executeQuery();
if(rs.next()){
exists= rs.getString("dstipveh");
}else{
exists= "DOES NOT EXISTS";
}
%>
<%=exists%>
<%
}finally{}
%>
This function returns just one value (exists), but I need to return
several values. I tried to do this:
try{
PreparedStatement ps = PV.prepareStatement("select * from vehicles
where econom=?");
ps.setString(1, noeco);
ResultSet rs = ps.executeQuery();
if(rs.next()){
exists= rs.getString("dstipveh");
matri = rs.getString("matr");
marca= rs.getString("marca");
}else{
exists= "DOES NOT EXISTS";
}
%>
<%=exists%>
<%=matri%>
<%=marca%>
<%
}finally{}
%>
But I get just one value (exists). Like I said, I'm not very familiar with
JavaScript and JSP. So, how can I return several values and display this
values in my JSP like I do with just one value?
I have a project in Java with JSP+JavaScript+Servlets, with a function in
JavaScript to find some record in my database. When this record is found,
my function returns some value, and when it's not, my function returns a
message. Now I need another function to return several fields from my
database, and I don't know who. I'm not very familiar with JavaScript and
JSP.
This is part from my JSP code:
<tr>
<td>
<input type='text' id="noeco" name="noeco" size=5 maxlength=5
onkeyup="find_noeco_s(noeco,exists);">
<span name="exists" id="exists" readonly="readonly" style="width:
200px" value="{exists}"></span></input>
</td>
</tr>
<tr>
<td>
<input type='text' id="matric" name="matric" readonly="readonly"
value="{matric}"></input>
</td>
</tr>
<tr>
<td>
<input type='text' id="marca" name="marca" readonly="readonly"
value="{marca}"></input>
</td>
</tr>
<tr>
<td>
<input type='text' id="submarca" name="submarca" readonly="readonly"
value="{submarca}"></input>
</td>
</tr>
This is my JavaScript function "find_noeco_s":
function find_noeco_s(noeco,exists){
objsal = exists;
if(window.XMLHttpRequest)
ajax = new XMLHttpRequest();
else
ajax = new ActiveXObject("Microsoft.XMLHTTP");
ajax.onreadystatechange = funcionCallback;
ajax.open("GET", "/processEco.jsp?noeco="+noeco.value, true);
ajax.send("");
}
And this is my JSP processEco:
String noeco = request.getParameter("noeco");
String exists="";
String matri= "";
try{
PreparedStatement ps = PV.prepareStatement("select * from vehicles
where econom=?");
ps.setString(1, noeco);
ResultSet rs = ps.executeQuery();
if(rs.next()){
exists= rs.getString("dstipveh");
}else{
exists= "DOES NOT EXISTS";
}
%>
<%=exists%>
<%
}finally{}
%>
This function returns just one value (exists), but I need to return
several values. I tried to do this:
try{
PreparedStatement ps = PV.prepareStatement("select * from vehicles
where econom=?");
ps.setString(1, noeco);
ResultSet rs = ps.executeQuery();
if(rs.next()){
exists= rs.getString("dstipveh");
matri = rs.getString("matr");
marca= rs.getString("marca");
}else{
exists= "DOES NOT EXISTS";
}
%>
<%=exists%>
<%=matri%>
<%=marca%>
<%
}finally{}
%>
But I get just one value (exists). Like I said, I'm not very familiar with
JavaScript and JSP. So, how can I return several values and display this
values in my JSP like I do with just one value?
Wordpress: search error message in several languages
Wordpress: search error message in several languages
I am building a multilanguage Wordpress website, is it possible to display
a different error message for each language when a search returns no
results and how?
Thank you :)
I am building a multilanguage Wordpress website, is it possible to display
a different error message for each language when a search returns no
results and how?
Thank you :)
best way to load data from a website/server to iPhone
best way to load data from a website/server to iPhone
I have an own website and I want to write an app that loads data
(strings/texts) from it to fill a tableview on the iPhone (like a
to-do-list). I want to change the content of my app (of the tableview) all
the time without doing an update in the App Store. When the app starts it
should grab the content from my website...
Should I use FTP for doing things like that or are there better ways to
load and manipulate data?
I have an own website and I want to write an app that loads data
(strings/texts) from it to fill a tableview on the iPhone (like a
to-do-list). I want to change the content of my app (of the tableview) all
the time without doing an update in the App Store. When the app starts it
should grab the content from my website...
Should I use FTP for doing things like that or are there better ways to
load and manipulate data?
OpenX: Deactivated Banners to shown in Zone
OpenX: Deactivated Banners to shown in Zone
I have created one Compaign (Ad1_Compaign), and i have put two banners to
that Compaign (Ad1_Compaign). And I have linked these 2 banners(Banner1
and Banner2) to one Zone under one Website.
After that, I am running the Invocation Code for that Zone, it displays
with good (both banners are displaying randomly).
I have two doubts.
Doubt I:
How many times once change the banner everytime page re-loading? How to
measure that?...
Then After I deactivated the Banner1 means, In Zone->Linked Banners shows
good with Inactive Banner.
But generating the Zone Code the Banner1 is also displayed... But it is
deactivated...
Doubt II:
How to block to show Deactivated Banner in Zone?
Anyone Please Help me...
I have created one Compaign (Ad1_Compaign), and i have put two banners to
that Compaign (Ad1_Compaign). And I have linked these 2 banners(Banner1
and Banner2) to one Zone under one Website.
After that, I am running the Invocation Code for that Zone, it displays
with good (both banners are displaying randomly).
I have two doubts.
Doubt I:
How many times once change the banner everytime page re-loading? How to
measure that?...
Then After I deactivated the Banner1 means, In Zone->Linked Banners shows
good with Inactive Banner.
But generating the Zone Code the Banner1 is also displayed... But it is
deactivated...
Doubt II:
How to block to show Deactivated Banner in Zone?
Anyone Please Help me...
Sunday, August 25, 2013
[ Words & Wordplay ] Open Question : So someone I know has 330 charges mostly theft by deception /forgery etc.. What is the sentence 38k...
[ Words & Wordplay ] Open Question : So someone I know has 330 charges
mostly theft by deception /forgery etc.. What is the sentence 38k...
mostly theft by deception /forgery etc.. What is the sentence 38k...
How to prove $n!>(\frac{n}{e})^{n}$
How to prove $n!>(\frac{n}{e})^{n}$
Prove that $n!>\left(\dfrac{n}{e}\right)^{n}$.
I used induction principle but cannot solve it for the $(m+1)$-th term
after taking the $m$th term to be true.
Prove that $n!>\left(\dfrac{n}{e}\right)^{n}$.
I used induction principle but cannot solve it for the $(m+1)$-th term
after taking the $m$th term to be true.
[ Psychology ] Open Question : Why dont I feel love?
[ Psychology ] Open Question : Why dont I feel love?
I am in my late teens and have Aspergers Syndrome. I also have social
anxiety that makes going out by myself very challenging. I also am
extremely shy(but can put on a good act when really needed, even though it
drains the life out of me and inside im a mess). When I was 15 I became
very depressed and suicidal and even now I occasionly slip into depressive
episodes which last from a few days to a week. I have a therapist who
helps me with the depressive episodes and social anxiety. I have been
bullied almost my who life and have had friends turn their back on me and
snub me without an explanation. I have also had to deal with the fact that
I have no contact with my birth father, which was a very hard time. I have
also self harmed in the past. I'm really trying hard to turn my life
around, im pushing my shyness boundaries to try to help my social anxiety,
I keep a positive diary(I know, seems very sad), and im eating better. I
should also tell you at this point that I will NEVER go on medication. I
am completely against it and nothing will change that. However, I've known
for a while now that I dont feel love. I have no friends where I live(I
did, but as usual, they ended up being idiots) and am happy being by
myself. I spend almost the whole day in my room learning about various
things and listening to music and this is what makes me happiest. I do
have a few friends where I used to live(one in particular is the most
special) but I just cant be bothered to keep in touch. I dont even miss
them. I do try to put more effort in for my most special friend as she is
important to me and I often find myself smiling when I think of our past
times together but I dont miss her. I dont know why, I just feel empty. I
think I would be sad if I lost her though, but im not sure. As for my
family, I am shy of everyone, my mum the least. I feel judged by them and
even asking them how they are is scary. I hate family trips out, they feel
fake and I feel no warmth when someone says they love me. Everything feels
like so much effort when I have to act like I care. I have never even
loved my past boyfriends before, I would just date them because they liked
me or because I was attracted to them physically. I havent had a crush on
anyone for about 4 years. However, I do feel fondness and warmth for some
people yet this is extremely rare. I feel so bad about this whole thing,
it makes me feel so cruel and heartless(which shows there may be a glimmer
of hope). Why is this? Is it Aspergers? Or could it be my social anxiety?
Its hard to feel warmth for people when youre feeling shy. How can I feel
love again? Will it just return when I no longer have social anxiety and I
no longer get deppressive episodes?
I am in my late teens and have Aspergers Syndrome. I also have social
anxiety that makes going out by myself very challenging. I also am
extremely shy(but can put on a good act when really needed, even though it
drains the life out of me and inside im a mess). When I was 15 I became
very depressed and suicidal and even now I occasionly slip into depressive
episodes which last from a few days to a week. I have a therapist who
helps me with the depressive episodes and social anxiety. I have been
bullied almost my who life and have had friends turn their back on me and
snub me without an explanation. I have also had to deal with the fact that
I have no contact with my birth father, which was a very hard time. I have
also self harmed in the past. I'm really trying hard to turn my life
around, im pushing my shyness boundaries to try to help my social anxiety,
I keep a positive diary(I know, seems very sad), and im eating better. I
should also tell you at this point that I will NEVER go on medication. I
am completely against it and nothing will change that. However, I've known
for a while now that I dont feel love. I have no friends where I live(I
did, but as usual, they ended up being idiots) and am happy being by
myself. I spend almost the whole day in my room learning about various
things and listening to music and this is what makes me happiest. I do
have a few friends where I used to live(one in particular is the most
special) but I just cant be bothered to keep in touch. I dont even miss
them. I do try to put more effort in for my most special friend as she is
important to me and I often find myself smiling when I think of our past
times together but I dont miss her. I dont know why, I just feel empty. I
think I would be sad if I lost her though, but im not sure. As for my
family, I am shy of everyone, my mum the least. I feel judged by them and
even asking them how they are is scary. I hate family trips out, they feel
fake and I feel no warmth when someone says they love me. Everything feels
like so much effort when I have to act like I care. I have never even
loved my past boyfriends before, I would just date them because they liked
me or because I was attracted to them physically. I havent had a crush on
anyone for about 4 years. However, I do feel fondness and warmth for some
people yet this is extremely rare. I feel so bad about this whole thing,
it makes me feel so cruel and heartless(which shows there may be a glimmer
of hope). Why is this? Is it Aspergers? Or could it be my social anxiety?
Its hard to feel warmth for people when youre feeling shy. How can I feel
love again? Will it just return when I no longer have social anxiety and I
no longer get deppressive episodes?
JAVA fail to convert char to utf8
JAVA fail to convert char to utf8
From wiki:
Consider a text file containing the German word f¨¹r in the ISO-8859-1
encoding. This file is now opened with a text editor that assumes the
input is UTF-8. As the first byte (0x66) is within the range 0x00¨C0x7F,
UTF-8 correctly interprets it as an f. The second byte (0xFC) is not a
legal value for the start of any UTF-8 encoded character. A text editor
could therefore replace the byte with the replacement character symbol to
warn the user that something went wrong. The last byte (0x72) is also
within the code range 0x00¨C0x7F and can be decoded correctly. The whole
string now displays like this: f�r.
I have a chinese word h, in GB3212, it is 6f22. In UTF8, it is e6bca2.
But when I try to convert it to unicode, i got EFBFBD (the replacement
char).
String correctedstring = new String(bbuf, "GB2312");//bbuf
contains 6f22
Charset charset = Charset.forName("UTF8");
CharsetDecoder decoder = charset.newDecoder();
CharsetEncoder encoder = charset.newEncoder();
ByteBuffer bb = charset.encode(correctedstring);
cbuf = decoder.decode(bb);
String utf8s = cbuf.toString();
utf8s is EFBFBD, rather than e6bca2.
I have no problem for some other chinese char, but i have problem with h.
I cant figure out the reason. If anyone know why, please kindly tell me
why and how to solve it? thanks.
From wiki:
Consider a text file containing the German word f¨¹r in the ISO-8859-1
encoding. This file is now opened with a text editor that assumes the
input is UTF-8. As the first byte (0x66) is within the range 0x00¨C0x7F,
UTF-8 correctly interprets it as an f. The second byte (0xFC) is not a
legal value for the start of any UTF-8 encoded character. A text editor
could therefore replace the byte with the replacement character symbol to
warn the user that something went wrong. The last byte (0x72) is also
within the code range 0x00¨C0x7F and can be decoded correctly. The whole
string now displays like this: f�r.
I have a chinese word h, in GB3212, it is 6f22. In UTF8, it is e6bca2.
But when I try to convert it to unicode, i got EFBFBD (the replacement
char).
String correctedstring = new String(bbuf, "GB2312");//bbuf
contains 6f22
Charset charset = Charset.forName("UTF8");
CharsetDecoder decoder = charset.newDecoder();
CharsetEncoder encoder = charset.newEncoder();
ByteBuffer bb = charset.encode(correctedstring);
cbuf = decoder.decode(bb);
String utf8s = cbuf.toString();
utf8s is EFBFBD, rather than e6bca2.
I have no problem for some other chinese char, but i have problem with h.
I cant figure out the reason. If anyone know why, please kindly tell me
why and how to solve it? thanks.
Saturday, August 24, 2013
C# Some newbie questions about collections
C# Some newbie questions about collections
I want to create an Extension. An extension is a component or a module
with default members like a name or a list of views. Component and module
inherit from extension members and implement their specific members.
public class Extension() {
public Name;
public List<View> Views;
// ...
}
public class View {
// ...
}
public class Component : Extension() {
// ...
}
public class Module : Extension() {
// ...
}
I can create a list of extensions like that :
List<Extension> Extensions = new Extensions<Extensions>() {
new Component() { Name = "Component 1" },
new Component() { Name = "Component 2" },
new Module() { Name = "Module" }
}
Now I want to create a menu. A menu can contain a view from my previous
extension :
public class MenuItem {
public string Name;
public View View;
}
List<MenuItem> Menu = new List<MenuItem>() {
new MenuItem(Name = "Menu 1", View = Extensions[0].Views[0]),
new MenuItem(Name = "Menu 2", View = Extensions[2].Views[0])
}
3 questions :
Is this the correct way (I'm newbie on c#) ?,
Is this possible with object initializer to assign an child object without
using index like that : View = Extensions[0].Views[0]
In my code, I can add in a new menu a view from a component or a module.
Is this possible to restrict only for component view ? So in my exemple,
second item is impossible to add.
Thanks
Aliza
I want to create an Extension. An extension is a component or a module
with default members like a name or a list of views. Component and module
inherit from extension members and implement their specific members.
public class Extension() {
public Name;
public List<View> Views;
// ...
}
public class View {
// ...
}
public class Component : Extension() {
// ...
}
public class Module : Extension() {
// ...
}
I can create a list of extensions like that :
List<Extension> Extensions = new Extensions<Extensions>() {
new Component() { Name = "Component 1" },
new Component() { Name = "Component 2" },
new Module() { Name = "Module" }
}
Now I want to create a menu. A menu can contain a view from my previous
extension :
public class MenuItem {
public string Name;
public View View;
}
List<MenuItem> Menu = new List<MenuItem>() {
new MenuItem(Name = "Menu 1", View = Extensions[0].Views[0]),
new MenuItem(Name = "Menu 2", View = Extensions[2].Views[0])
}
3 questions :
Is this the correct way (I'm newbie on c#) ?,
Is this possible with object initializer to assign an child object without
using index like that : View = Extensions[0].Views[0]
In my code, I can add in a new menu a view from a component or a module.
Is this possible to restrict only for component view ? So in my exemple,
second item is impossible to add.
Thanks
Aliza
Manifest Error App Crashes
Manifest Error App Crashes
I reinstalled Windows on my pc and tried to open my old project with a
newer version of android studio.
This is my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.linkr.chat"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:label="@string/app_name"
android:name=".Login" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
When i change the line android:name=".Login" to android:name=".Chat", the
activity Chat opens up and doesn't crash. But i want Login to open first,
so i use android:name=".Login", and if i then click on the button to open
the chat it crashes.
The error i got from logcat was:
Caused by: android.content.ActivityNotFoundException: Unable to find
explicit activity class {com.linkr.chat/com.linkr.chat.Chat}; have you
declared this activity in your AndroidManifest.xml?
Why does it want me to declare this?
Thanks a lot!
I reinstalled Windows on my pc and tried to open my old project with a
newer version of android studio.
This is my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.linkr.chat"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:label="@string/app_name"
android:name=".Login" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
When i change the line android:name=".Login" to android:name=".Chat", the
activity Chat opens up and doesn't crash. But i want Login to open first,
so i use android:name=".Login", and if i then click on the button to open
the chat it crashes.
The error i got from logcat was:
Caused by: android.content.ActivityNotFoundException: Unable to find
explicit activity class {com.linkr.chat/com.linkr.chat.Chat}; have you
declared this activity in your AndroidManifest.xml?
Why does it want me to declare this?
Thanks a lot!
Flip graph of point set
Flip graph of point set
Is the flip graph of every point set in $\mathbb R^3$ connected? If
not, is there a set with an isolated node?
Def: For a point set $S$, the flip graph of $S$ is a graph whose
nodes are the set of triangulations of $S$. Two nodes $T_1$ and $T_2$ of
the flip graph are connected by an arc if one diagonal of $T_1$ can
be flipped to obtain $T_2$.
Any idea would be appreciate.
These tags not available for me : flip-graph
Is the flip graph of every point set in $\mathbb R^3$ connected? If
not, is there a set with an isolated node?
Def: For a point set $S$, the flip graph of $S$ is a graph whose
nodes are the set of triangulations of $S$. Two nodes $T_1$ and $T_2$ of
the flip graph are connected by an arc if one diagonal of $T_1$ can
be flipped to obtain $T_2$.
Any idea would be appreciate.
These tags not available for me : flip-graph
Is this CentOS 6.2 system reasonably secure as described?
Is this CentOS 6.2 system reasonably secure as described?
This is a CentOS 6.2 system.
For my login with the hosting company website, I set a 20-character mixed
case, letters, numbers, symbols password and enabled two-factor
authentication.
In /etc/ssh/sshd_config I turned off remote root login and turned of
password-based login.
I'm running sshd, Apache, SSL, and MySQL on standard ports (although MySQL
should only be accessed from within the same host).
I plan to run yum update -y as a daily cron job. (should I make it hourly?)
I ran this script to configure my firewall...
*filter
-A INPUT -i lo -j ACCEPT
-A INPUT -d 127.0.0.0/8 -j REJECT
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A OUTPUT -j ACCEPT
-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 443 -j ACCEPT
-A INPUT -p tcp -m state --state NEW --dport 22 -j ACCEPT
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: "
--log-level 7
-A INPUT -j REJECT
-A FORWARD -j REJECT
COMMIT
Are there any changes that anyone would recommend?
(I realize that any apps I deploy may have their own security issues such
as SQL injection or cross site scripting). For now, I'm just talking about
the bare setup so far.)
This is a CentOS 6.2 system.
For my login with the hosting company website, I set a 20-character mixed
case, letters, numbers, symbols password and enabled two-factor
authentication.
In /etc/ssh/sshd_config I turned off remote root login and turned of
password-based login.
I'm running sshd, Apache, SSL, and MySQL on standard ports (although MySQL
should only be accessed from within the same host).
I plan to run yum update -y as a daily cron job. (should I make it hourly?)
I ran this script to configure my firewall...
*filter
-A INPUT -i lo -j ACCEPT
-A INPUT -d 127.0.0.0/8 -j REJECT
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A OUTPUT -j ACCEPT
-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 443 -j ACCEPT
-A INPUT -p tcp -m state --state NEW --dport 22 -j ACCEPT
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: "
--log-level 7
-A INPUT -j REJECT
-A FORWARD -j REJECT
COMMIT
Are there any changes that anyone would recommend?
(I realize that any apps I deploy may have their own security issues such
as SQL injection or cross site scripting). For now, I'm just talking about
the bare setup so far.)
Ember view to display a PDF
Ember view to display a PDF
In one of my views I would like to display a PDF, which is accesible via
URL. This should be done without opening an extra tab in the browser, and
without downloading the PDF (to view it outside the browser). It should be
visible embedded within the Ember application.
What I have in mind is:
Use the URL to get the PDF and make it accessible to the ember application.
Use a special "PDF view" to display the PDF.
Is this possible? What options do I have to display an embedded PDF in an
Ember application?
In one of my views I would like to display a PDF, which is accesible via
URL. This should be done without opening an extra tab in the browser, and
without downloading the PDF (to view it outside the browser). It should be
visible embedded within the Ember application.
What I have in mind is:
Use the URL to get the PDF and make it accessible to the ember application.
Use a special "PDF view" to display the PDF.
Is this possible? What options do I have to display an embedded PDF in an
Ember application?
Run custom script as part of IFTTT recipe
Run custom script as part of IFTTT recipe
Ive just stared using IFTTT and one of the things i want to do is
if
A NEW TUMBLR POST IS PUBLISHED
run
my-site.com/my-script.php
To do this it really needs to be able to ping the url
my-site.com/my-script.php is that possible with IFTTT ?
Ive just stared using IFTTT and one of the things i want to do is
if
A NEW TUMBLR POST IS PUBLISHED
run
my-site.com/my-script.php
To do this it really needs to be able to ping the url
my-site.com/my-script.php is that possible with IFTTT ?
Without searching a value it displays no record
Without searching a value it displays no record
In this below code i am searching a value.if the value is searched it
displays the result but if the value is not present it should displays no
result. In my case if i execute and not search any value it displays no
record .Please any one help me.
<form action="<?php echo site_url('search1_site/index');?>" method =
"post">
<input type="text" name = "keyword" />
<input type="submit" id="opn" value = "Search" />
</form>
<?php
if($results){
?> <div id='hideme'>
CLOSE<a href='#' class='close_notification' title='Click to Close'>
<img src="<?php echo base_url('img/close.png'); ?>" width="15"
height="15" alt="Close" onClick="hide('hideme')"/>
</a> <div style="background:#FFFFFF; width: 500px; height: 500px;
position: absolute; left: 50%; top: 50%; margin-left: -100px;
margin-top: -100px" id="modal" >
<table class="display2 table table-bordered table-striped">
<tr>
<th>course_code</th>
<th>course name</th>
</tr>
<tr><?php
foreach ($results as $row) {
?>
<td><?php echo $row->course_code;?></td>
<td><?php echo $row->course_name;?></td>
</tr>
<?php
}
}else{
echo "no results";
}
?>
</table></div></div>
<script>
$('a.modal').bind('click', function(event) {
event.preventDefault();
$('#modal').fadeIn(10);
});
function hide(obj) {
var el = document.getElementById(obj);
el.style.display = 'none';
}
</script>
In this below code i am searching a value.if the value is searched it
displays the result but if the value is not present it should displays no
result. In my case if i execute and not search any value it displays no
record .Please any one help me.
<form action="<?php echo site_url('search1_site/index');?>" method =
"post">
<input type="text" name = "keyword" />
<input type="submit" id="opn" value = "Search" />
</form>
<?php
if($results){
?> <div id='hideme'>
CLOSE<a href='#' class='close_notification' title='Click to Close'>
<img src="<?php echo base_url('img/close.png'); ?>" width="15"
height="15" alt="Close" onClick="hide('hideme')"/>
</a> <div style="background:#FFFFFF; width: 500px; height: 500px;
position: absolute; left: 50%; top: 50%; margin-left: -100px;
margin-top: -100px" id="modal" >
<table class="display2 table table-bordered table-striped">
<tr>
<th>course_code</th>
<th>course name</th>
</tr>
<tr><?php
foreach ($results as $row) {
?>
<td><?php echo $row->course_code;?></td>
<td><?php echo $row->course_name;?></td>
</tr>
<?php
}
}else{
echo "no results";
}
?>
</table></div></div>
<script>
$('a.modal').bind('click', function(event) {
event.preventDefault();
$('#modal').fadeIn(10);
});
function hide(obj) {
var el = document.getElementById(obj);
el.style.display = 'none';
}
</script>
Friday, August 23, 2013
How to write a tester for a program that writes one bit at a time?
How to write a tester for a program that writes one bit at a time?
I am trying to write a tester for the following program to see if it
functions correctly, however, I'm not sure if I implemented flush()
correctly and for some reason I don't get any output. Can someone suggest
code that will test this class to see if I implemented flush and writeBit
correctly?
#ifndef BITOUTPUTSTREAM_HPP
#define BITOUTPUTSTREAM_HPP
#include <iostream>
class BitOutputStream {
private:
char buf; // one byte buffer of bits
int nbits; // how many bits have been written to buf
std::ostream& out; // reference to the output stream to use
public:
/* Initialize a BitOutputStream that will
* use the given ostream for output.
* */
BitOutputStream(std::ostream& os) : out(os) {
buf = nbits = 0; // clear buffer and bit counter
}
/* Send the buffer to the output, and clear it */
void flush() {
out.put(buf);
flush(); // not sure if this is how I should flush the buffer?
buf = nbits = 0;
}
/* Write the least sig bit of arg into buffer */
int writeBit(int i) {
// If bit buffer is full, flush it.
if (nbits == 8)
flush();
// Write the least significant bit of i into
// the buffer at the current index.
// buf = buf << 1; this is another option I was considering
// buf |= 1 & i; but decided to go with the one below
int lb = i & 1; // extract the lowest bit
buf |= lb << nbits; // shift it nbits and put in in buf
// increment index
nbits++;
return nbits;
}
};
I am trying to write a tester for the following program to see if it
functions correctly, however, I'm not sure if I implemented flush()
correctly and for some reason I don't get any output. Can someone suggest
code that will test this class to see if I implemented flush and writeBit
correctly?
#ifndef BITOUTPUTSTREAM_HPP
#define BITOUTPUTSTREAM_HPP
#include <iostream>
class BitOutputStream {
private:
char buf; // one byte buffer of bits
int nbits; // how many bits have been written to buf
std::ostream& out; // reference to the output stream to use
public:
/* Initialize a BitOutputStream that will
* use the given ostream for output.
* */
BitOutputStream(std::ostream& os) : out(os) {
buf = nbits = 0; // clear buffer and bit counter
}
/* Send the buffer to the output, and clear it */
void flush() {
out.put(buf);
flush(); // not sure if this is how I should flush the buffer?
buf = nbits = 0;
}
/* Write the least sig bit of arg into buffer */
int writeBit(int i) {
// If bit buffer is full, flush it.
if (nbits == 8)
flush();
// Write the least significant bit of i into
// the buffer at the current index.
// buf = buf << 1; this is another option I was considering
// buf |= 1 & i; but decided to go with the one below
int lb = i & 1; // extract the lowest bit
buf |= lb << nbits; // shift it nbits and put in in buf
// increment index
nbits++;
return nbits;
}
};
Override the User.IsInRole and [Authorize(Roles = "Admin")] for MVC4 application
Override the User.IsInRole and [Authorize(Roles = "Admin")] for MVC4
application
I have created a custom role provider for my MVC4 application where I have
been successfully able to override CreateRole, GetAllRoles and RoleExists
methods and link them to my existing database as follows:
namespace Project.Providers
{
public class MyProvider : System.Web.Security.SqlRoleProvider
{
private MyContext dbcontext = new
MyContext(System.Configuration.ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString);
private Repository<User> userRepository;
private Repository<Role> roleRepository;
public MyProvider()
{
this.userRepository = new Repository<MetaLearningUser>(dbcontext);
this.roleRepository = new Repository<Role>(dbcontext);
}
public override string[] GetAllRoles()
{
IEnumerable<Role> dbRoles = roleRepository.GetAll();
int dbRolesCount = roleRepository.GetAll().Count();
string[] roles = new string[dbRolesCount];
int i = 0;
foreach(var role in dbRoles)
{
roles[i] = role.Name;
i++;
}
return roles;
}
public override bool RoleExists(string roleName)
{
string[] roles = { "Admin", "User", "BobsBusiness" };
if(roles.Contains(roleName))
return true;
else
return false;
}
public override void CreateRole(string roleName)
{
Role newRole = new Role();
newRole.Name = roleName;
roleRepository.Add(newRole);
roleRepository.SaveChanges();
}
public override bool IsUserInRole(string userName, string roleName)
{
MetaLearningUser user = userRepository.Get(u => u.Username ==
userName).FirstOrDefault();
Role role = roleRepository.Get(r => r.Name ==
roleName).FirstOrDefault();
if (user.RoleID == role.RoleID)
return true;
else
return false;
}
}
}
I tried to override the AddUserToRole method but it doesnt seem to be
available only the:
AddUsersToRoles(string[] usernames, string[] roleNames) .
Will I need to create a similar custom class for the ability to be able to
override:
AddUserToRole(string username, string roleName).
Similarly I have been able to override the IsUserInRole(string userName,
string roleName) but have been unable to find a way to override the
User.IsInRole(string roleName)
What else must I do so that When I use:
[Authorize(Roles = "Admin")]
It will be based on the role provider that I have set up and not the asp
default
application
I have created a custom role provider for my MVC4 application where I have
been successfully able to override CreateRole, GetAllRoles and RoleExists
methods and link them to my existing database as follows:
namespace Project.Providers
{
public class MyProvider : System.Web.Security.SqlRoleProvider
{
private MyContext dbcontext = new
MyContext(System.Configuration.ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString);
private Repository<User> userRepository;
private Repository<Role> roleRepository;
public MyProvider()
{
this.userRepository = new Repository<MetaLearningUser>(dbcontext);
this.roleRepository = new Repository<Role>(dbcontext);
}
public override string[] GetAllRoles()
{
IEnumerable<Role> dbRoles = roleRepository.GetAll();
int dbRolesCount = roleRepository.GetAll().Count();
string[] roles = new string[dbRolesCount];
int i = 0;
foreach(var role in dbRoles)
{
roles[i] = role.Name;
i++;
}
return roles;
}
public override bool RoleExists(string roleName)
{
string[] roles = { "Admin", "User", "BobsBusiness" };
if(roles.Contains(roleName))
return true;
else
return false;
}
public override void CreateRole(string roleName)
{
Role newRole = new Role();
newRole.Name = roleName;
roleRepository.Add(newRole);
roleRepository.SaveChanges();
}
public override bool IsUserInRole(string userName, string roleName)
{
MetaLearningUser user = userRepository.Get(u => u.Username ==
userName).FirstOrDefault();
Role role = roleRepository.Get(r => r.Name ==
roleName).FirstOrDefault();
if (user.RoleID == role.RoleID)
return true;
else
return false;
}
}
}
I tried to override the AddUserToRole method but it doesnt seem to be
available only the:
AddUsersToRoles(string[] usernames, string[] roleNames) .
Will I need to create a similar custom class for the ability to be able to
override:
AddUserToRole(string username, string roleName).
Similarly I have been able to override the IsUserInRole(string userName,
string roleName) but have been unable to find a way to override the
User.IsInRole(string roleName)
What else must I do so that When I use:
[Authorize(Roles = "Admin")]
It will be based on the role provider that I have set up and not the asp
default
Please have a look the codes
Please have a look the codes
Write a program to read a string from the command-line arguments,count the
number of occurrence for each uppercase or lowercase letter contained in
it. (Hint: define two arrays of size 26 to save the number of uppercase
letter occurrence and lowercase letter occurrence in the string
respectively).
The above is my homework, I have done it so far as:
int[]loweroccurrence={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26};
int[]upperoccurrence={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26};
String a=args[0];
String lowercase="abcdefghijklmnopqrstuvwxyz";
String uppercase="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i=0,j=0,k=0;
for(j=0;j<26;j++){
for(i=0;i<a.length();i++){
if(a.charAt(i)==lowercase.charAt(j)){
System.out.print(loweroccurrence[i]);
}
Obviously, it is wrong, as the question asks to use two arrays to store
the occurrence number for both upper and lower letter, I have no idea how
to print out the result as a number by using arrays, please help, cheers
guys!
Write a program to read a string from the command-line arguments,count the
number of occurrence for each uppercase or lowercase letter contained in
it. (Hint: define two arrays of size 26 to save the number of uppercase
letter occurrence and lowercase letter occurrence in the string
respectively).
The above is my homework, I have done it so far as:
int[]loweroccurrence={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26};
int[]upperoccurrence={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26};
String a=args[0];
String lowercase="abcdefghijklmnopqrstuvwxyz";
String uppercase="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i=0,j=0,k=0;
for(j=0;j<26;j++){
for(i=0;i<a.length();i++){
if(a.charAt(i)==lowercase.charAt(j)){
System.out.print(loweroccurrence[i]);
}
Obviously, it is wrong, as the question asks to use two arrays to store
the occurrence number for both upper and lower letter, I have no idea how
to print out the result as a number by using arrays, please help, cheers
guys!
application.android is an unexpected element/attribute - AIR android application with IntelliJ
application.android is an unexpected element/attribute - AIR android
application with IntelliJ
I have just installed Flex and AIR SDK. Then I followed the instructions
for developing AIR mobile applications on IntelliJ Idea. I let IntelliJ
create sample app. Then I tried to run the application on Android device.
But after building the project, IntelliJ gives the following error:
c:\projects\cinar-agaci-01\ari-kovani-01\flash\hello02\out\production\hello01\Hello01-android-descriptor.xml(217):
error 103: application.android is an unexpected element/attribute
ADT command line:
d:\program files\jetbrains\intellij idea 12.1.3\jre\jre\bin\java.exe
-Dapplication.home=C:\java\flex -Dfile.encoding=UTF-8
-Djava.awt.headless=true -Duser.language=en -Duser.region=en -Xmx512m -jar
C:\java\flex\lib\adt.jar -package -target apk -storetype PKCS12 -keystore
D:\Program Files\JetBrains\IntelliJ IDEA
12.1.3\plugins\flex\lib\temp_keystore.p12 -storepass keystore_password
c:\projects\cinar-agaci-01\ari-kovani-01\flash\hello01\out\production\hello01\Hello01.apk
c:\projects\cinar-agaci-01\ari-kovani-01\flash\hello01\out\production\hello01\Hello01-android-descriptor.xml
-C
c:\projects\cinar-agaci-01\ari-kovani-01\flash\hello01\out\production\hello01
Hello01.swf
There is only one file in the project which is automatically created by
Intellij. Its name is Hello02.mxml. Here is its content:
<?xml version="1.0" encoding="utf-8"?>
<s:ViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark">
<s:navigationContent>
<s:Button label="Home" click="navigator.popToFirstView()"/>
</s:navigationContent>
</s:ViewNavigatorApplication>
Unfortunately, I cannot try to run this application in Android Emulator
because somehow the ADB emulators don't work properly in my computer. But
I can build and install java based Android applications.
application with IntelliJ
I have just installed Flex and AIR SDK. Then I followed the instructions
for developing AIR mobile applications on IntelliJ Idea. I let IntelliJ
create sample app. Then I tried to run the application on Android device.
But after building the project, IntelliJ gives the following error:
c:\projects\cinar-agaci-01\ari-kovani-01\flash\hello02\out\production\hello01\Hello01-android-descriptor.xml(217):
error 103: application.android is an unexpected element/attribute
ADT command line:
d:\program files\jetbrains\intellij idea 12.1.3\jre\jre\bin\java.exe
-Dapplication.home=C:\java\flex -Dfile.encoding=UTF-8
-Djava.awt.headless=true -Duser.language=en -Duser.region=en -Xmx512m -jar
C:\java\flex\lib\adt.jar -package -target apk -storetype PKCS12 -keystore
D:\Program Files\JetBrains\IntelliJ IDEA
12.1.3\plugins\flex\lib\temp_keystore.p12 -storepass keystore_password
c:\projects\cinar-agaci-01\ari-kovani-01\flash\hello01\out\production\hello01\Hello01.apk
c:\projects\cinar-agaci-01\ari-kovani-01\flash\hello01\out\production\hello01\Hello01-android-descriptor.xml
-C
c:\projects\cinar-agaci-01\ari-kovani-01\flash\hello01\out\production\hello01
Hello01.swf
There is only one file in the project which is automatically created by
Intellij. Its name is Hello02.mxml. Here is its content:
<?xml version="1.0" encoding="utf-8"?>
<s:ViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark">
<s:navigationContent>
<s:Button label="Home" click="navigator.popToFirstView()"/>
</s:navigationContent>
</s:ViewNavigatorApplication>
Unfortunately, I cannot try to run this application in Android Emulator
because somehow the ADB emulators don't work properly in my computer. But
I can build and install java based Android applications.
Windows Small Business - centralized backup solution for network workstations
Windows Small Business - centralized backup solution for network workstations
We have a Windows domain-based small business network, about 30
workstations and 1 server. In addition we have a NAS device.
I want to make the computer system more secure and stable. I need a
solution for backup workstations and server.
Features: - central storage for backup files (NAS or Server) - when user
starts his machine, before login, an incremental backup made from
specified files (or full machine, bare metal...) to the central storage -
if needed, we can restore the backed-up data to the client machine (even
to different hardware)
Do you know any solutions, sotfware for this?
Thanks in advance!
p.s.: sorry for my bad english (I hope you understand my question)
We have a Windows domain-based small business network, about 30
workstations and 1 server. In addition we have a NAS device.
I want to make the computer system more secure and stable. I need a
solution for backup workstations and server.
Features: - central storage for backup files (NAS or Server) - when user
starts his machine, before login, an incremental backup made from
specified files (or full machine, bare metal...) to the central storage -
if needed, we can restore the backed-up data to the client machine (even
to different hardware)
Do you know any solutions, sotfware for this?
Thanks in advance!
p.s.: sorry for my bad english (I hope you understand my question)
External HDD error - data recovery Ubuntu 12.04
External HDD error - data recovery Ubuntu 12.04
I recently connected my external HDD to Ubuntu 12.04, but now it's not
working. If I try to use ntfsfix in the terminal it gives this error
message:
abcd@ubuntu:~$ sudo ntfsfix /dev/sdb1
[sudo] password for abcd:
Mounting volume... ntfs_mst_post_read_fixup_warn: magic: 0x43425355 size:
1024 usa_ofs: 1024 usa_count: 65535: Invalid argument
ntfs_mst_post_read_fixup_warn: magic: 0x43425355 size: 1024 usa_ofs:
1025 usa_count: 65535: Invalid argument
ntfs_mst_post_read_fixup_warn: magic: 0x43425355 size: 1024 usa_ofs:
1024 usa_count: 65535: Invalid argument
Record 3 has no FILE magic (0x43425355)
Failed to open inode FILE_Volume: Input/output error FAILED
Attempting to correct errors...
Processing $MFT and $MFTMirr...
Reading $MFT... ntfs_mst_post_read_fixup_warn: magic: 0x43425355 size:
1024 usa_ofs: 1024 usa_count: 65535: Invalid argument
OK
Reading $MFTMirr... ntfs_mst_post_read_fixup_warn: magic: 0x43425355
size: 1024 usa_ofs: 1025 usa_count: 65535: Invalid argument
OK
Comparing $MFTMirr to $MFT... OK
Processing of $MFT and $MFTMirr completed successfully.
Setting required flags on partition... ntfs_mst_post_read_fixup_warn:
magic: 0x43425355 size: 1024 usa_ofs: 1024 usa_count: 65535: Invalid
argument
Record 3 has no FILE magic (0x43425355)
Failed to read $Volume: Input/output error
FAILED
Error setting volume flags.
Is it possible to recover data from the disk?
I recently connected my external HDD to Ubuntu 12.04, but now it's not
working. If I try to use ntfsfix in the terminal it gives this error
message:
abcd@ubuntu:~$ sudo ntfsfix /dev/sdb1
[sudo] password for abcd:
Mounting volume... ntfs_mst_post_read_fixup_warn: magic: 0x43425355 size:
1024 usa_ofs: 1024 usa_count: 65535: Invalid argument
ntfs_mst_post_read_fixup_warn: magic: 0x43425355 size: 1024 usa_ofs:
1025 usa_count: 65535: Invalid argument
ntfs_mst_post_read_fixup_warn: magic: 0x43425355 size: 1024 usa_ofs:
1024 usa_count: 65535: Invalid argument
Record 3 has no FILE magic (0x43425355)
Failed to open inode FILE_Volume: Input/output error FAILED
Attempting to correct errors...
Processing $MFT and $MFTMirr...
Reading $MFT... ntfs_mst_post_read_fixup_warn: magic: 0x43425355 size:
1024 usa_ofs: 1024 usa_count: 65535: Invalid argument
OK
Reading $MFTMirr... ntfs_mst_post_read_fixup_warn: magic: 0x43425355
size: 1024 usa_ofs: 1025 usa_count: 65535: Invalid argument
OK
Comparing $MFTMirr to $MFT... OK
Processing of $MFT and $MFTMirr completed successfully.
Setting required flags on partition... ntfs_mst_post_read_fixup_warn:
magic: 0x43425355 size: 1024 usa_ofs: 1024 usa_count: 65535: Invalid
argument
Record 3 has no FILE magic (0x43425355)
Failed to read $Volume: Input/output error
FAILED
Error setting volume flags.
Is it possible to recover data from the disk?
Thursday, August 22, 2013
onClick input text readonly form use inline
onClick input text readonly form use inline
I have problem with onclick input form is readonly but use it inline. I
can do only onclick is disable Example:
<input type="text" onClick=this.disabled=true />
this one is work but what I need is when onClick event is readonly I try
this :
<input type="text" onClick=this.readonly=true />
but it still not work.
if it possible please help me
I am waiting for everyone.
Thank
I have problem with onclick input form is readonly but use it inline. I
can do only onclick is disable Example:
<input type="text" onClick=this.disabled=true />
this one is work but what I need is when onClick event is readonly I try
this :
<input type="text" onClick=this.readonly=true />
but it still not work.
if it possible please help me
I am waiting for everyone.
Thank
Nodejs on heavy load
Nodejs on heavy load
I am using nodejs with socket.io on my chat system. My hardware is 13.6
Ghz Cpu and 16gb ram.
When the online users count reaches 600,some users can't connect to
socket,can't send messages.And some users disconnects from chat.
How can I resolve this problem ? What is your opinion of this problem ?
I am using nodejs with socket.io on my chat system. My hardware is 13.6
Ghz Cpu and 16gb ram.
When the online users count reaches 600,some users can't connect to
socket,can't send messages.And some users disconnects from chat.
How can I resolve this problem ? What is your opinion of this problem ?
How to deploy a play framework application with MySQL database
How to deploy a play framework application with MySQL database
I have written a web application using Play Framework 2.1.0 in Java, with
an existing MySql database on my pc. Now I want to deploy the app and my
database on a server or a cloud platform like amazon ec2. But I get some
questions:
Cloud platform is easy to use, but I don't know which one should I choose.
Some cloud platform service doesn't support mysql database, like google
app engine. So I want to find one that can import mysql database easily
and can be set up easily.Can you guys give me some suggestions and some
tutorials about setting play framework on it?
I get a server without any OS on it now. But I don't know how to set it up
to run my play framework application. It seems that I have to install a
server application like apache or something else. Which one is better? And
can you give me some tutorials about how to set a play framework on an
linux system, like ubuntu?
I have written a web application using Play Framework 2.1.0 in Java, with
an existing MySql database on my pc. Now I want to deploy the app and my
database on a server or a cloud platform like amazon ec2. But I get some
questions:
Cloud platform is easy to use, but I don't know which one should I choose.
Some cloud platform service doesn't support mysql database, like google
app engine. So I want to find one that can import mysql database easily
and can be set up easily.Can you guys give me some suggestions and some
tutorials about setting play framework on it?
I get a server without any OS on it now. But I don't know how to set it up
to run my play framework application. It seems that I have to install a
server application like apache or something else. Which one is better? And
can you give me some tutorials about how to set a play framework on an
linux system, like ubuntu?
Configure Home/End key to move to start/end of line in IntelliJ
Configure Home/End key to move to start/end of line in IntelliJ
I know ctrl+right/ctrl+left will do that, but I am used to pressing
Home/End and it's frustrating when it doesn't do it in IntelliJ. I use
KeyRemap4Macbook which works great for terminal and elsewhere with the
Home/End key setting, but the settings for some reason do not work in
IntelliJ.
I am on MAC OSX, IJ 12.1.4.
I know ctrl+right/ctrl+left will do that, but I am used to pressing
Home/End and it's frustrating when it doesn't do it in IntelliJ. I use
KeyRemap4Macbook which works great for terminal and elsewhere with the
Home/End key setting, but the settings for some reason do not work in
IntelliJ.
I am on MAC OSX, IJ 12.1.4.
returning JSON values (objects) via ajax
returning JSON values (objects) via ajax
Suppose i have a json file like this:
{
"content": {
"statistics": [
{
"key": "aaaa",
"value": {
"hits": 0,
"misses": 0,
"errors": 0,
"hitRate": 0.0
}
},
{
"key": "bbbb",
"value": {
"hits": 0,
"misses": 0,
"errors": 0,
"hitRate": 0.0
}
},
{
"key": "cccc",
"value": {
"hits": 0,
"misses": 0,
"errors": 0,
"hitRate": 0.0
}
}
],
"enabled": false
},
"meta": {
"httpCode": 000
}
}
and using this ajax:
$.ajax({
type: "GET",
url: url,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
console.log(data);
var key=data["key"];
console.log(key);
}
});
}
but this code above does not work, it doesn't return keys from the json.
How do I display out all the values for keys, values, hits..etc? Many
thank for your help
Suppose i have a json file like this:
{
"content": {
"statistics": [
{
"key": "aaaa",
"value": {
"hits": 0,
"misses": 0,
"errors": 0,
"hitRate": 0.0
}
},
{
"key": "bbbb",
"value": {
"hits": 0,
"misses": 0,
"errors": 0,
"hitRate": 0.0
}
},
{
"key": "cccc",
"value": {
"hits": 0,
"misses": 0,
"errors": 0,
"hitRate": 0.0
}
}
],
"enabled": false
},
"meta": {
"httpCode": 000
}
}
and using this ajax:
$.ajax({
type: "GET",
url: url,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
console.log(data);
var key=data["key"];
console.log(key);
}
});
}
but this code above does not work, it doesn't return keys from the json.
How do I display out all the values for keys, values, hits..etc? Many
thank for your help
how to Fetch data from mysql as a json data?
how to Fetch data from mysql as a json data?
I am using this code to fetch data from database and convert into json
<?php
$username = "root";
$password = "";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password , "test")
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//json
$query = mysql_query("SELECT * FROM location");
$json_output = array();
while($row = mysql_fetch_assoc($query)){
$json_output[] = json_encode($row);
}
echo json_encode($row);
?>
but iam getting the error as Warning: mysql_fetch_assoc() expects
parameter 1 to be resource, boolean given in C:\wamp\www\js.php on line 17
the line 17 is while($row = mysql_fetch_assoc($query)).
Pls some one help me in getting this.
I am using this code to fetch data from database and convert into json
<?php
$username = "root";
$password = "";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password , "test")
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//json
$query = mysql_query("SELECT * FROM location");
$json_output = array();
while($row = mysql_fetch_assoc($query)){
$json_output[] = json_encode($row);
}
echo json_encode($row);
?>
but iam getting the error as Warning: mysql_fetch_assoc() expects
parameter 1 to be resource, boolean given in C:\wamp\www\js.php on line 17
the line 17 is while($row = mysql_fetch_assoc($query)).
Pls some one help me in getting this.
Wednesday, August 21, 2013
Clarification on how Elmah set the Logged in User Name
Clarification on how Elmah set the Logged in User Name
I was searching on how the logged in user name was set using ELmah.
The closer i came is the below link
Logging username with Elmah for WCF Webservices
Elmah take the user from Thread.CurrentPrincipal.Identity.Name and not
from HttpContext.Current.User
To get more clarity on this does the Thread takes Name from the windows
log on ?
Or will it log the name if i set HttpContext.Current.User ?
How does it work. How application architecture should be to make ELMAH
feasible to log UserName ?
Thanks
I was searching on how the logged in user name was set using ELmah.
The closer i came is the below link
Logging username with Elmah for WCF Webservices
Elmah take the user from Thread.CurrentPrincipal.Identity.Name and not
from HttpContext.Current.User
To get more clarity on this does the Thread takes Name from the windows
log on ?
Or will it log the name if i set HttpContext.Current.User ?
How does it work. How application architecture should be to make ELMAH
feasible to log UserName ?
Thanks
OOP Programming in MATLAB with stored values that also change (like an incrementer)
OOP Programming in MATLAB with stored values that also change (like an
incrementer)
I am relatively new to object-oriented programming in MATLAB, so maybe I
just don't understand the philosophy behind it, but I cannot seem to
figure this out. I want to have a set of object properties. One property
is statically created on object creation, and the other is an incrementing
value which stores information relevant to the object's use.
classdef MyClass
properties
max_inc; % Statically created cap on the incrementer
incr; % The incrementer
end
methods
% Constructor
function c = MyClass(set_max)
c.max_inc = set_max;
c.incr = 1;
end
% Function to do some stuff
function value = Next(c)
% Do some stuff
set(c, 'incr', c.incr + 1);
end
% Set function which is causing me trouble
function c = set.incr(c, value)
if(value <= c.max_inc)
c.incr = value;
else
c.incr = 1;
end
end
end
end
I was able to make a work-around which doesn't error out by getting rid of
the set function and implementing the Next(c) function as:
% Function to do some stuff
function value = Next(c)
% Do some stuff
curr_inc = c.incr;
if(curr_inc < c.max_inc)
c.incr = curr_inc + 1;
else
c.incr = 1;
end
end
While this runs, it does not actually seem to change the value of incr
when Next(c) is called (it always thinks incr is the starting value). I
don't want to make incr dependent because it does need to store its value
so I know how many times it has been incremented previously, and I cannot
make this a handle object because I need more than one to be active at the
same time (unless I am completely misunderstanding how handle objects
work). Is there not a way to do this? This seems like it should be a
really easy thing to do with an object.
incrementer)
I am relatively new to object-oriented programming in MATLAB, so maybe I
just don't understand the philosophy behind it, but I cannot seem to
figure this out. I want to have a set of object properties. One property
is statically created on object creation, and the other is an incrementing
value which stores information relevant to the object's use.
classdef MyClass
properties
max_inc; % Statically created cap on the incrementer
incr; % The incrementer
end
methods
% Constructor
function c = MyClass(set_max)
c.max_inc = set_max;
c.incr = 1;
end
% Function to do some stuff
function value = Next(c)
% Do some stuff
set(c, 'incr', c.incr + 1);
end
% Set function which is causing me trouble
function c = set.incr(c, value)
if(value <= c.max_inc)
c.incr = value;
else
c.incr = 1;
end
end
end
end
I was able to make a work-around which doesn't error out by getting rid of
the set function and implementing the Next(c) function as:
% Function to do some stuff
function value = Next(c)
% Do some stuff
curr_inc = c.incr;
if(curr_inc < c.max_inc)
c.incr = curr_inc + 1;
else
c.incr = 1;
end
end
While this runs, it does not actually seem to change the value of incr
when Next(c) is called (it always thinks incr is the starting value). I
don't want to make incr dependent because it does need to store its value
so I know how many times it has been incremented previously, and I cannot
make this a handle object because I need more than one to be active at the
same time (unless I am completely misunderstanding how handle objects
work). Is there not a way to do this? This seems like it should be a
really easy thing to do with an object.
JMenu and JMenuItem
JMenu and JMenuItem
So, I have the following code:
JMenu debug = new JMenu("Debug");
debug.add(new Debug());
And then the Debug class is:
public class Debug extends JMenuItem {
public final String TEST_DEBUG = "Test";
public Debug() {
add(TEST_DEBUG, this);
}
}
After running the application I get the following error:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException:
adding container's parent to itself
I know what it means, but I have no idea how I can make this right without
placing the container parent to itself? How would I pass the String to the
JMenu?
Any help is appreciated.
So, I have the following code:
JMenu debug = new JMenu("Debug");
debug.add(new Debug());
And then the Debug class is:
public class Debug extends JMenuItem {
public final String TEST_DEBUG = "Test";
public Debug() {
add(TEST_DEBUG, this);
}
}
After running the application I get the following error:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException:
adding container's parent to itself
I know what it means, but I have no idea how I can make this right without
placing the container parent to itself? How would I pass the String to the
JMenu?
Any help is appreciated.
meaning of description for constructor of property class
meaning of description for constructor of property class
pFor property class we have the following as one of the constructors:/p
precodeProperties(Properties default) Creates an empty property list with
the specified defaults /code/pre pWhat does it mean by empty property list
with the specified defaults/p pI wrote a demo program to test what is
happening:/p precodeimport java.util.*; import java.io.*; public class
test { private static String z; private static String i; public static
void main(String [] args) throws FileNotFoundException, IOException{ z =
a; i = b; Properties p = new Properties(); p.setProperty(z,z);
p.setProperty(i,i); p.store(new FileOutputStream(r.txt), null); Properties
pp = new Properties(p); pp.store(new FileOutputStream(random.txt), null);
pp.load(new FileInputStream(in.txt)); pp.store(new
FileOutputStream(random1.txt), null); } } /code/pre pThe result were
coderandom.txt/code was empty, coderandom1.txt/code has codez=n/code. The
newly created property has no defaults as coderandom.txt/code is empty. So
what does the constructor description mean? Please correct me if I am
wrong somewhere./p
pFor property class we have the following as one of the constructors:/p
precodeProperties(Properties default) Creates an empty property list with
the specified defaults /code/pre pWhat does it mean by empty property list
with the specified defaults/p pI wrote a demo program to test what is
happening:/p precodeimport java.util.*; import java.io.*; public class
test { private static String z; private static String i; public static
void main(String [] args) throws FileNotFoundException, IOException{ z =
a; i = b; Properties p = new Properties(); p.setProperty(z,z);
p.setProperty(i,i); p.store(new FileOutputStream(r.txt), null); Properties
pp = new Properties(p); pp.store(new FileOutputStream(random.txt), null);
pp.load(new FileInputStream(in.txt)); pp.store(new
FileOutputStream(random1.txt), null); } } /code/pre pThe result were
coderandom.txt/code was empty, coderandom1.txt/code has codez=n/code. The
newly created property has no defaults as coderandom.txt/code is empty. So
what does the constructor description mean? Please correct me if I am
wrong somewhere./p
C# initialization array
C# initialization array
Can anybody explain me, why are there code like this in msdn?
// Create the array to store the CDs.
CD[] cdLibrary = new CD[20];
// Populate the CD library with CD objects.
for (int i=0; i<20; i++)
{ cdLibrary[i] = new CD(); }
I cannot understand why the initialization of objects in an array does not
execute in the operator new. And it need additional actions. What did it
make for?
Can anybody explain me, why are there code like this in msdn?
// Create the array to store the CDs.
CD[] cdLibrary = new CD[20];
// Populate the CD library with CD objects.
for (int i=0; i<20; i++)
{ cdLibrary[i] = new CD(); }
I cannot understand why the initialization of objects in an array does not
execute in the operator new. And it need additional actions. What did it
make for?
Splitting Excel file but retaining lookup data and formulas
Splitting Excel file but retaining lookup data and formulas
I have a master expenses file that has a page for each employee
summarising their expenses. The employee sheets run off a hidden data
sheets.
I want to send each employee a copy of their expenses with the lookups etc
hidden but still in tact so that they can complete the coding etc using
lookup lists like project and expense codes from the data sheets.
What I envisage is a macro create to a set of individual employee files
with only their page but with the lookups and data in each remaining in
tact and hidden. I've been trying to create a macro to systematically work
through the file creating new files for each employee deleting each of the
other employee sheets but retaining the hidden data and related lookups -
with no success
Any help appreciated.
I have a master expenses file that has a page for each employee
summarising their expenses. The employee sheets run off a hidden data
sheets.
I want to send each employee a copy of their expenses with the lookups etc
hidden but still in tact so that they can complete the coding etc using
lookup lists like project and expense codes from the data sheets.
What I envisage is a macro create to a set of individual employee files
with only their page but with the lookups and data in each remaining in
tact and hidden. I've been trying to create a macro to systematically work
through the file creating new files for each employee deleting each of the
other employee sheets but retaining the hidden data and related lookups -
with no success
Any help appreciated.
Tuesday, August 20, 2013
how to convert string length in c#
how to convert string length in c#
i have char(10) field (it is Persian date field) in my database. my
control in c# for some date creates char(8). then i have problem in store
procedure(where date between dateFrom and DateTo). i must have char(10). i
want to write function in c# to check the string and if the it's length is
less than 10 convert it to 10. my format is yyyy/mm/dd. (yyyy has no
problem in my control) for example i want to convert 1391/1/1 to
1391/01/01 please help me how i can insert 0 and check the number after /.
i have char(10) field (it is Persian date field) in my database. my
control in c# for some date creates char(8). then i have problem in store
procedure(where date between dateFrom and DateTo). i must have char(10). i
want to write function in c# to check the string and if the it's length is
less than 10 convert it to 10. my format is yyyy/mm/dd. (yyyy has no
problem in my control) for example i want to convert 1391/1/1 to
1391/01/01 please help me how i can insert 0 and check the number after /.
Perl parsing through a file based on conditions
Perl parsing through a file based on conditions
I have a very large log file which is updated periodically. It is as follows:
commands: (List of files to be copied)
Exit time: Fri May 10 05:33:00 2013
Exit status: 2
commands: (List of files to be copied)
Exit Time: Fri May 20 05:34:00 2013
Exit status: 2
commands: (List of files to be copied)
Exit Time: Fri May 30 05:50:00 2013
Exit Status: 1
I have following code which creates a hash based on Exit Status
while ($line = <FH>) {
if ($line =~ /Exit time/) {
($exittime, $exittimeval) = split(': ',$line);
$stat{$qbsid} = {
time => $exittimeval
};
}
I now need to create a timestamp based on localtime such that the script
does not compare the log file for the time after the timestamp
(localtime). I have the code to compare the time as follows
$date1 = "$hr1:$min1:$sec1, $moy1/$dt1/$yr1";
$date2 = "$hr2:$min2:$sec2, $moy2/$dt2/$yr2";
sub to_comparable {
my ($date) = @_;
my ($H,$M,$S,$d,$m,$Y) = $date =~ m{^(\d+):(\d+):(\d+),
(\d+)/(\d+)/(\d+)\z}
or die;
return "$Y$m$d$H$M$S";
}
if (to_comparable($date2) > to_comparable($date1)) {
print "right\n";
} else {
print "wrong \n";
}
Here $hr1,$min1,$sec1,$moy1,$dt1 and $yr1 are local time variables while
$hr2,$min2,$sec2, $moy2,$dt2 and $yr2 are values obtained from hash.
Preferably while running for the first time it should compare the whole
file and a timestamp is created. Afterwards, the above idea starts.
Please correct me if anything is wrong. Thank you.
I have a very large log file which is updated periodically. It is as follows:
commands: (List of files to be copied)
Exit time: Fri May 10 05:33:00 2013
Exit status: 2
commands: (List of files to be copied)
Exit Time: Fri May 20 05:34:00 2013
Exit status: 2
commands: (List of files to be copied)
Exit Time: Fri May 30 05:50:00 2013
Exit Status: 1
I have following code which creates a hash based on Exit Status
while ($line = <FH>) {
if ($line =~ /Exit time/) {
($exittime, $exittimeval) = split(': ',$line);
$stat{$qbsid} = {
time => $exittimeval
};
}
I now need to create a timestamp based on localtime such that the script
does not compare the log file for the time after the timestamp
(localtime). I have the code to compare the time as follows
$date1 = "$hr1:$min1:$sec1, $moy1/$dt1/$yr1";
$date2 = "$hr2:$min2:$sec2, $moy2/$dt2/$yr2";
sub to_comparable {
my ($date) = @_;
my ($H,$M,$S,$d,$m,$Y) = $date =~ m{^(\d+):(\d+):(\d+),
(\d+)/(\d+)/(\d+)\z}
or die;
return "$Y$m$d$H$M$S";
}
if (to_comparable($date2) > to_comparable($date1)) {
print "right\n";
} else {
print "wrong \n";
}
Here $hr1,$min1,$sec1,$moy1,$dt1 and $yr1 are local time variables while
$hr2,$min2,$sec2, $moy2,$dt2 and $yr2 are values obtained from hash.
Preferably while running for the first time it should compare the whole
file and a timestamp is created. Afterwards, the above idea starts.
Please correct me if anything is wrong. Thank you.
Steam doesn't launch
Steam doesn't launch
I installed Steam using Ubunt Software Center, but whe tried to launch, it
showed this error in Terminal
Steam needs to install these additional packages:
libgl1-mesa-dri-lts-quantal:i386, libgl1-mesa-glx-lts-quantal:i386
sudo: unable to change to sudoers gid: Operation not permitted
sudo: setresuid() [0, 0, 0] -> [115, -1, -1]: Operation not permitted
sudo: unable to change to sudoers gid: Operation not permitted
sudo: setresuid() [0, 0, 0] -> [115, -1, -1]: Operation not permitted
Press return to continue:
What am I supposed to do?
I installed Steam using Ubunt Software Center, but whe tried to launch, it
showed this error in Terminal
Steam needs to install these additional packages:
libgl1-mesa-dri-lts-quantal:i386, libgl1-mesa-glx-lts-quantal:i386
sudo: unable to change to sudoers gid: Operation not permitted
sudo: setresuid() [0, 0, 0] -> [115, -1, -1]: Operation not permitted
sudo: unable to change to sudoers gid: Operation not permitted
sudo: setresuid() [0, 0, 0] -> [115, -1, -1]: Operation not permitted
Press return to continue:
What am I supposed to do?
Changing backslashes to forward slashes changes file size
Changing backslashes to forward slashes changes file size
I have two small to medium sized files (2k) that are for all intents and
purposes identical. The second file is the result of the first file being
duplicated and replacing backslashes with forward slashes. The new file is
bigger by 80 bytes (or one byte per line).
I did this with a simple batch script,and at first I thought the script
might have unintentionally added some spaces or other artifacts. Or maybe
the fact that their extensions are different has something to do with it
(one has a tmp extension and the other has a lst extension).
From an editor, I replaced all forward slashes in the new file with
backslashes and saved it without changing the extension.
And, hey guess what? The files were the same size again.
Now, before this is written off as a random fluke, I also see the same
behavior exhibited in three other pairs of files (in other words six
files) created in the same manner as the first. They are all one byte
bigger per line in the file. The largest is about 12k bytes, and the
smallest is about 2k.
I wouldn't think it has anything to do with escaping because I am on a
Windows box using the Windows 7 cmd.exe shell.
Also one other thing. I tried the following:
echo \\\\\ >> a.txt
echo ///// >> b.txt
The files matched in size (7 bytes)
Does anyone have an explanation for this behavior?
I have two small to medium sized files (2k) that are for all intents and
purposes identical. The second file is the result of the first file being
duplicated and replacing backslashes with forward slashes. The new file is
bigger by 80 bytes (or one byte per line).
I did this with a simple batch script,and at first I thought the script
might have unintentionally added some spaces or other artifacts. Or maybe
the fact that their extensions are different has something to do with it
(one has a tmp extension and the other has a lst extension).
From an editor, I replaced all forward slashes in the new file with
backslashes and saved it without changing the extension.
And, hey guess what? The files were the same size again.
Now, before this is written off as a random fluke, I also see the same
behavior exhibited in three other pairs of files (in other words six
files) created in the same manner as the first. They are all one byte
bigger per line in the file. The largest is about 12k bytes, and the
smallest is about 2k.
I wouldn't think it has anything to do with escaping because I am on a
Windows box using the Windows 7 cmd.exe shell.
Also one other thing. I tried the following:
echo \\\\\ >> a.txt
echo ///// >> b.txt
The files matched in size (7 bytes)
Does anyone have an explanation for this behavior?
Using local json variable for plotting d3 partition chart
Using local json variable for plotting d3 partition chart
I have a collection of objects which I have been formmated to be able to
plot this in the partion chart in the below format.
{"name":"Component 234324234","children":[{"name":"Krishna Candidate - 1
435458976766","children":[{"name":"Krishna clinical
23423424","size":23423424},{"name":"DP Componet
98989","size":98989},{"name":"KRUTI COMP,
435435454353","size":435435454353}],"size":435458976766},{"name":"Krishna
Candidate-Test 0","children":[],"size":0},{"name":"Test Candidate
5555","children":[{"name":"ADME Component
5555","size":5555}],"size":5555},{"name":"Candidate 5
37874474288","children":[{"name":"Teset Component
9898988","size":9898988},{"name":"AdmeComponent
34234324324","size":34234324324},{"name":"WPM Component
23432424","size":23432424},{"name":"WPM 1
2344324324","size":2344324324},{"name":"WPM2
234324324","size":234324324},{"name":"WPM 3
2343244","size":2343244},{"name":"WPM 4
23423432","size":23423432},{"name":"WPM 5
2323432","size":2323432},{"name":"Adme component one
989898","size":989898},{"name":"Tejas Jet Fighters
998989898","size":998989898},{"name":"Planned budget 1
100000","size":100000}],"size":37874474288},{"name":"Krishna Candidate
234324234","children":[{"name":"Test Component One
234324234","size":234324234}],"size":234324234}],"size":234324234},{"name":"undefined
4662000","children":[{"name":"Candidate Sirisha
4662000","children":[{"name":"Lead Generation
500000","size":500000},{"name":"Lead Optimization
500000","size":500000},{"name":"Lead Profiling
500000","size":500000},{"name":"BioMarker Discovery
300000","size":300000},{"name":"Target Validation
1000000","size":1000000},{"name":"BioMarker PK/PD
300000","size":300000},{"name":"Synthesize Tox Dose
250000","size":250000},{"name":"BioMarker Validation
300000","size":300000},{"name":"Rodent Tox
200000","size":200000},{"name":"Dog Tox
300000","size":300000},{"name":"Primate Tox
500000","size":500000},{"name":"Planned budget itemi
10000","size":10000},{"name":"Planned budget
1000","size":1000},{"name":"Planned budget 5
1000","size":1000}],"size":4662000}],"size":4662000}]
d3.json("flare.json", function(root) {
var g = vis.selectAll("g")
.data(partition.nodes(root))
.enter().append("svg:g")
.attr("transform", function(d) { return "translate(" + x(d.y) + ","
+ y(d.x) + ")"; })
.on("click", click);
var kx = w / root.dx,
ky = h / 1;
g.append("svg:rect")
.attr("width", root.dy * kx)
.attr("height", function(d) { return d.dx * ky; })
.attr("class", function(d) { return d.children ? "parent" : "child";
});
g.append("svg:text")
.attr("transform", transform)
.attr("dy", ".35em")
.style("opacity", function(d) { return d.dx * ky > 12 ? 1 : 0; })
.text(function(d) { return d.name; })
d3.select(window)
.on("click", function() { click(root); })
function click(d) {
if (!d.children) return;
kx = (d.y ? w - 40 : w) / (1 - d.y);
ky = h / d.dx;
x.domain([d.y, 1]).range([d.y ? 40 : 0, w]);
y.domain([d.x, d.x + d.dx]);
var t = g.transition()
.duration(d3.event.altKey ? 7500 : 750)
.attr("transform", function(d) { return "translate(" + x(d.y) +
"," + y(d.x) + ")"; });
t.select("rect")
.attr("width", d.dy * kx)
.attr("height", function(d) { return d.dx * ky; });
t.select("text")
.attr("transform", transform)
.style("opacity", function(d) { return d.dx * ky > 12 ? 1 : 0; });
d3.event.stopPropagation();
}
The partition chart expects a json object from an external url. Can anyone
help in helping me how to use the above object for plotting the chart
I have a collection of objects which I have been formmated to be able to
plot this in the partion chart in the below format.
{"name":"Component 234324234","children":[{"name":"Krishna Candidate - 1
435458976766","children":[{"name":"Krishna clinical
23423424","size":23423424},{"name":"DP Componet
98989","size":98989},{"name":"KRUTI COMP,
435435454353","size":435435454353}],"size":435458976766},{"name":"Krishna
Candidate-Test 0","children":[],"size":0},{"name":"Test Candidate
5555","children":[{"name":"ADME Component
5555","size":5555}],"size":5555},{"name":"Candidate 5
37874474288","children":[{"name":"Teset Component
9898988","size":9898988},{"name":"AdmeComponent
34234324324","size":34234324324},{"name":"WPM Component
23432424","size":23432424},{"name":"WPM 1
2344324324","size":2344324324},{"name":"WPM2
234324324","size":234324324},{"name":"WPM 3
2343244","size":2343244},{"name":"WPM 4
23423432","size":23423432},{"name":"WPM 5
2323432","size":2323432},{"name":"Adme component one
989898","size":989898},{"name":"Tejas Jet Fighters
998989898","size":998989898},{"name":"Planned budget 1
100000","size":100000}],"size":37874474288},{"name":"Krishna Candidate
234324234","children":[{"name":"Test Component One
234324234","size":234324234}],"size":234324234}],"size":234324234},{"name":"undefined
4662000","children":[{"name":"Candidate Sirisha
4662000","children":[{"name":"Lead Generation
500000","size":500000},{"name":"Lead Optimization
500000","size":500000},{"name":"Lead Profiling
500000","size":500000},{"name":"BioMarker Discovery
300000","size":300000},{"name":"Target Validation
1000000","size":1000000},{"name":"BioMarker PK/PD
300000","size":300000},{"name":"Synthesize Tox Dose
250000","size":250000},{"name":"BioMarker Validation
300000","size":300000},{"name":"Rodent Tox
200000","size":200000},{"name":"Dog Tox
300000","size":300000},{"name":"Primate Tox
500000","size":500000},{"name":"Planned budget itemi
10000","size":10000},{"name":"Planned budget
1000","size":1000},{"name":"Planned budget 5
1000","size":1000}],"size":4662000}],"size":4662000}]
d3.json("flare.json", function(root) {
var g = vis.selectAll("g")
.data(partition.nodes(root))
.enter().append("svg:g")
.attr("transform", function(d) { return "translate(" + x(d.y) + ","
+ y(d.x) + ")"; })
.on("click", click);
var kx = w / root.dx,
ky = h / 1;
g.append("svg:rect")
.attr("width", root.dy * kx)
.attr("height", function(d) { return d.dx * ky; })
.attr("class", function(d) { return d.children ? "parent" : "child";
});
g.append("svg:text")
.attr("transform", transform)
.attr("dy", ".35em")
.style("opacity", function(d) { return d.dx * ky > 12 ? 1 : 0; })
.text(function(d) { return d.name; })
d3.select(window)
.on("click", function() { click(root); })
function click(d) {
if (!d.children) return;
kx = (d.y ? w - 40 : w) / (1 - d.y);
ky = h / d.dx;
x.domain([d.y, 1]).range([d.y ? 40 : 0, w]);
y.domain([d.x, d.x + d.dx]);
var t = g.transition()
.duration(d3.event.altKey ? 7500 : 750)
.attr("transform", function(d) { return "translate(" + x(d.y) +
"," + y(d.x) + ")"; });
t.select("rect")
.attr("width", d.dy * kx)
.attr("height", function(d) { return d.dx * ky; });
t.select("text")
.attr("transform", transform)
.style("opacity", function(d) { return d.dx * ky > 12 ? 1 : 0; });
d3.event.stopPropagation();
}
The partition chart expects a json object from an external url. Can anyone
help in helping me how to use the above object for plotting the chart
Merge Outlook Profiles
Merge Outlook Profiles
I have created 2 Outlook profiles one for my Wife and one for me over 4
yrs ago on Outlook 2007. With time my wife now has her own PC and I have
now taken over her business. So the problem is that I have her business
e-mail accounts(5 accounts) on one profile and my personal and other
business accounts(4 accounts) on the other profile. I want to merge both
profiles, while keeping settings like the incoming and outgoing servers,
and port settings. I don't mind reentering passwords.
I look at the registry entry but don't know if I would be stuffing things
up by trying to merge the two profiles.
Thanks
Mark
I have created 2 Outlook profiles one for my Wife and one for me over 4
yrs ago on Outlook 2007. With time my wife now has her own PC and I have
now taken over her business. So the problem is that I have her business
e-mail accounts(5 accounts) on one profile and my personal and other
business accounts(4 accounts) on the other profile. I want to merge both
profiles, while keeping settings like the incoming and outgoing servers,
and port settings. I don't mind reentering passwords.
I look at the registry entry but don't know if I would be stuffing things
up by trying to merge the two profiles.
Thanks
Mark
Monday, August 19, 2013
Will this work? 3 Displays w/ GTX 560 Ti, 2 in DVI, 1 in HDMI
Will this work? 3 Displays w/ GTX 560 Ti, 2 in DVI, 1 in HDMI
I currently have a computer running a GTX 560 Ti with two monitors (one in
each of the DVI ports). Is it possible to add a third display (without any
extra hardware or peripherals) by plugging it into the mini HDMI port?
What if I plugged the third monitor into any of the onboard graphic ports,
what would happen?
I currently have a computer running a GTX 560 Ti with two monitors (one in
each of the DVI ports). Is it possible to add a third display (without any
extra hardware or peripherals) by plugging it into the mini HDMI port?
What if I plugged the third monitor into any of the onboard graphic ports,
what would happen?
Improve JQuery function for make it able to accept variables
Improve JQuery function for make it able to accept variables
This code is intended to be able to toggle between showing and hiding an
element depending on its ID. But in this form, only works with the ID's
that are already written in the code.
I would like to transform the code to make it possible to give it easily
the variables like in standard javascript functions. Something like
Function(id) {variable = id; actions;}
Like this, I would be able to employ this function always that I want to
hide or show an html element just calling the function and giving it a ID
as a attribute. Any idea on how to transform this code?
var x;
x=$(document);
x.ready(init);
function init(){
var x;
x=$("#check"); // Here is the ID of the control element
x.click(Qocult_most);
}
function Qocult_most(){ //Show and scrolls down till the page's end
var x;
x=$("#most"); //Here is the ID element to show
x.toggle(500);
$("html, body").animate({ scrollTop: $("#STH").offset().top },
1000);
}
This code is intended to be able to toggle between showing and hiding an
element depending on its ID. But in this form, only works with the ID's
that are already written in the code.
I would like to transform the code to make it possible to give it easily
the variables like in standard javascript functions. Something like
Function(id) {variable = id; actions;}
Like this, I would be able to employ this function always that I want to
hide or show an html element just calling the function and giving it a ID
as a attribute. Any idea on how to transform this code?
var x;
x=$(document);
x.ready(init);
function init(){
var x;
x=$("#check"); // Here is the ID of the control element
x.click(Qocult_most);
}
function Qocult_most(){ //Show and scrolls down till the page's end
var x;
x=$("#most"); //Here is the ID element to show
x.toggle(500);
$("html, body").animate({ scrollTop: $("#STH").offset().top },
1000);
}
Iterate shared_ptr
Iterate shared_ptr
Let's assume I have the following:
auto vec = std::shared_ptr<std::vector<T>>
And I want to loop through all the vec entities using C++11 Range-Based
for Loop.
The following works:
for (auto entity: *vec)
my question is there anyway to do the same without using the * operator?
Let's assume I have the following:
auto vec = std::shared_ptr<std::vector<T>>
And I want to loop through all the vec entities using C++11 Range-Based
for Loop.
The following works:
for (auto entity: *vec)
my question is there anyway to do the same without using the * operator?
mysql time between same id ticketing system
mysql time between same id ticketing system
im using ticketing system, and need to create query to check agent are
they late with their delivery
this is what i have and what i need
i have: ticket_id time_created i need select all same ticket_id where
time_created between 2 is greater then 24 hours
example
ticket_id time_created
1 2013-08-19 12:11
1 2013-08-17 12:07
1 2013-08-17 12:00
2 2013-08-19 12:11
2 2013-08-19 12:10
result
ticket_id time_difference
1 48:04
im using ticketing system, and need to create query to check agent are
they late with their delivery
this is what i have and what i need
i have: ticket_id time_created i need select all same ticket_id where
time_created between 2 is greater then 24 hours
example
ticket_id time_created
1 2013-08-19 12:11
1 2013-08-17 12:07
1 2013-08-17 12:00
2 2013-08-19 12:11
2 2013-08-19 12:10
result
ticket_id time_difference
1 48:04
Sunday, August 18, 2013
Google Play Services Location throwing NullPointerException
Google Play Services Location throwing NullPointerException
I am trying to run a service that tracks a users location using the Google
Play Location Services. I've followed the [Android Developers Google Play]
(http://developer.android.com/google/play-services/setup.html)
instructions but currently have a crashing app.
I am using the android emulator AVD with a Google API target (17).
I have
1) Installed the Google Play Services SDK
2) Made a copy of the Google Play services library project, imported it
into my Eclipse workspace, and referenced it in my current app, using
these [instructions]
(http://developer.android.com/tools/projects/projects-eclipse.html#ReferencingLibraryProject)
I am not sure whether or not I have to add anything to the Manifest
Some background on my app structure: I have created a Location Services
class with all of the error handling, and am calling that class' methods
via a service. My app is currently crashing when I call the:
GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
command which is in the servicesConnected() which is the first instance I
call anything Google Play related. So basically, where I am at: I am
trying to call the method checking if Google Play services is available,
and the app is crashing on:
08-19 03:51:19.464: E/AndroidRuntime(1112): java.lang.RuntimeException:
Unable to start service
com.scarr025.zwilio.AdventureService@40d24920 with Intent { flg=0x4
cmp=com.scarr025.zwilio/.AdventureService (has extras) }:
java.lang.NullPointerException
Please help!!
Code is below:
Google Play Services Class
public class AdventureLocator extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
protected void onCreate(Bundle savedInstanceState) {
mLocClient = new LocationClient(this, this, this);
mContext = this;
}
public void startConnection() {
mLocClient.connect();
}
public Location getLastLocation() {
return mLocClient.getLastLocation();
}
// Method that encapsulates the check for Google Play services
public boolean servicesConnected() {
// Check that Google Play services is available
int resultCode =
GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d("$$AdventureLocator$$", "In servicesConnected; Google Play
services is available (returned true).");
// Continue
return true;
// Google Play services was not available for some reason
} else {
// Get the error code
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
resultCode,
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
// Set the dialog in the DialogFragment
errorFragment.setDialog(errorDialog);
// Show the error dialog in the DialogFragment
errorFragment.show(getSupportFragmentManager(), "Location
Updates");
}
return false;
}
...
Manifest File
...
<service
android:name=".AdventureService"
android:label="@string/title_adventure_service" >
</service>
<activity
android:name=".AdventureLocator"
android:label="@string/title_adventure_locator" >
</activity>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
I am trying to run a service that tracks a users location using the Google
Play Location Services. I've followed the [Android Developers Google Play]
(http://developer.android.com/google/play-services/setup.html)
instructions but currently have a crashing app.
I am using the android emulator AVD with a Google API target (17).
I have
1) Installed the Google Play Services SDK
2) Made a copy of the Google Play services library project, imported it
into my Eclipse workspace, and referenced it in my current app, using
these [instructions]
(http://developer.android.com/tools/projects/projects-eclipse.html#ReferencingLibraryProject)
I am not sure whether or not I have to add anything to the Manifest
Some background on my app structure: I have created a Location Services
class with all of the error handling, and am calling that class' methods
via a service. My app is currently crashing when I call the:
GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
command which is in the servicesConnected() which is the first instance I
call anything Google Play related. So basically, where I am at: I am
trying to call the method checking if Google Play services is available,
and the app is crashing on:
08-19 03:51:19.464: E/AndroidRuntime(1112): java.lang.RuntimeException:
Unable to start service
com.scarr025.zwilio.AdventureService@40d24920 with Intent { flg=0x4
cmp=com.scarr025.zwilio/.AdventureService (has extras) }:
java.lang.NullPointerException
Please help!!
Code is below:
Google Play Services Class
public class AdventureLocator extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
protected void onCreate(Bundle savedInstanceState) {
mLocClient = new LocationClient(this, this, this);
mContext = this;
}
public void startConnection() {
mLocClient.connect();
}
public Location getLastLocation() {
return mLocClient.getLastLocation();
}
// Method that encapsulates the check for Google Play services
public boolean servicesConnected() {
// Check that Google Play services is available
int resultCode =
GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d("$$AdventureLocator$$", "In servicesConnected; Google Play
services is available (returned true).");
// Continue
return true;
// Google Play services was not available for some reason
} else {
// Get the error code
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
resultCode,
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
// Set the dialog in the DialogFragment
errorFragment.setDialog(errorDialog);
// Show the error dialog in the DialogFragment
errorFragment.show(getSupportFragmentManager(), "Location
Updates");
}
return false;
}
...
Manifest File
...
<service
android:name=".AdventureService"
android:label="@string/title_adventure_service" >
</service>
<activity
android:name=".AdventureLocator"
android:label="@string/title_adventure_locator" >
</activity>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Edit in place for a SugarCRM Subpanel
Edit in place for a SugarCRM Subpanel
Below is an image of a SugarCRM module I am building (actually 3 of them.
Projects, Project Tasks, and Project Files)
This image is a DetailView of the Project module. The Project Tasks and
Project Files modules are SubPanels of this module.
I am new to SugarCRM, my first week so I am still learning everything I
can. I have already added a lot of features to this but something I would
like to do is on the Project Tasks SubPanel. I would like to make it where
you can easily change the status of each record without leaving the page.
So my ideal solution would add a button on each Project Tasks record which
will let you edit in place the Status of that task, so you could mark it
completed or open, or whatever right in place.
So I am asking if this is even possible to add such a functionality to a
Subpanel and if it is, perhaps some examples of how to do such
modifications to a subpanel.
Below is an image of a SugarCRM module I am building (actually 3 of them.
Projects, Project Tasks, and Project Files)
This image is a DetailView of the Project module. The Project Tasks and
Project Files modules are SubPanels of this module.
I am new to SugarCRM, my first week so I am still learning everything I
can. I have already added a lot of features to this but something I would
like to do is on the Project Tasks SubPanel. I would like to make it where
you can easily change the status of each record without leaving the page.
So my ideal solution would add a button on each Project Tasks record which
will let you edit in place the Status of that task, so you could mark it
completed or open, or whatever right in place.
So I am asking if this is even possible to add such a functionality to a
Subpanel and if it is, perhaps some examples of how to do such
modifications to a subpanel.
When examining global error bounds for Euler method, can I rescale the domain limits?
When examining global error bounds for Euler method, can I rescale the
domain limits?
I'm looking at provable global error bounds of the Euler method for the
first time and I was surprised to find that the bound grows exponentially
in the amount of time (the domain size) propagated i.e.
$\delta_{err}\le A \;dt\; (e^{L (t_1-t_0)}-1)$
With $A$ a function of problem dependent bounds (e.g. the Lipschitz
constant, $L$). At first, I thought this was extremely bad due to the
exponential dependence on the domain size but then it occurred to me that
I could rescale the time units such that $(t_1-t_0)=1$ but this seems like
it might be problematic.
Going beyond Euler method to Runge-Kutta etc. methods doesn't help if the
error bound grows exponentially with the domain size. As ODE is a well
established field, and most references don't explicitly mention the
exponential growth with the domain size I think it must be unimportant but
I cannot see how (other than rescaling). Hence my question is:
Is there a way to be okay with this exponential dependence, either by
rescaling such that $t_1-t_0=1$ or by any other means?
domain limits?
I'm looking at provable global error bounds of the Euler method for the
first time and I was surprised to find that the bound grows exponentially
in the amount of time (the domain size) propagated i.e.
$\delta_{err}\le A \;dt\; (e^{L (t_1-t_0)}-1)$
With $A$ a function of problem dependent bounds (e.g. the Lipschitz
constant, $L$). At first, I thought this was extremely bad due to the
exponential dependence on the domain size but then it occurred to me that
I could rescale the time units such that $(t_1-t_0)=1$ but this seems like
it might be problematic.
Going beyond Euler method to Runge-Kutta etc. methods doesn't help if the
error bound grows exponentially with the domain size. As ODE is a well
established field, and most references don't explicitly mention the
exponential growth with the domain size I think it must be unimportant but
I cannot see how (other than rescaling). Hence my question is:
Is there a way to be okay with this exponential dependence, either by
rescaling such that $t_1-t_0=1$ or by any other means?
Broadcast Receiver Constantly Restarting
Broadcast Receiver Constantly Restarting
I'm making a widget which I want to update every second (It's like a
countdown/timer widget), so I'm using a AlarmManager and a broadcast
reciever to achieve this without waking the phone and using up all the
battery, but I keep getting a constant stream of errors in LogCat when
running the widget:
08-18 18:40:43.368 390-1988/system_process I/ActivityManager: Process
com.dysign.livetubecountdown (pid 9784) has died.
08-18 18:40:44.282 390-414/system_process I/ActivityManager: Start
proc com.dysign.livetubecountdown for broadcast
com.dysign.livetubecountdown/.WidgetAlarmManager: pid=9809 uid=10144
gids={50144, 3003, 1028}
08-18 18:40:44.306 9809-9809/com.dysign.livetubecountdown E/Trace:
error opening trace file: No such file or directory (2)
As you can see, the process keeps on dying and then restarting, this
happens when the phone is both awake and asleep.
Here is how I am starting the AlarmManager (This is inside the widget
provider class):
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
AlarmManager
am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, WidgetAlarmManager.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.setRepeating(AlarmManager.RTC, System.currentTimeMillis() + 1000,
1000 , pi);
}
And this is the Broadcast Receiver code:
@Override
public void onReceive(Context context, Intent intent) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_main);
DateFormat format =
SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM,
Locale.getDefault());
remoteViews.setTextViewText(R.id.widgetTextView, "TIME = " +
format.format(new Date()));
ComponentName thisWidget = new ComponentName(context, Widget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(thisWidget, remoteViews);
}
Any help would be much appreciated, thank you, SO!
I'm making a widget which I want to update every second (It's like a
countdown/timer widget), so I'm using a AlarmManager and a broadcast
reciever to achieve this without waking the phone and using up all the
battery, but I keep getting a constant stream of errors in LogCat when
running the widget:
08-18 18:40:43.368 390-1988/system_process I/ActivityManager: Process
com.dysign.livetubecountdown (pid 9784) has died.
08-18 18:40:44.282 390-414/system_process I/ActivityManager: Start
proc com.dysign.livetubecountdown for broadcast
com.dysign.livetubecountdown/.WidgetAlarmManager: pid=9809 uid=10144
gids={50144, 3003, 1028}
08-18 18:40:44.306 9809-9809/com.dysign.livetubecountdown E/Trace:
error opening trace file: No such file or directory (2)
As you can see, the process keeps on dying and then restarting, this
happens when the phone is both awake and asleep.
Here is how I am starting the AlarmManager (This is inside the widget
provider class):
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
AlarmManager
am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, WidgetAlarmManager.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.setRepeating(AlarmManager.RTC, System.currentTimeMillis() + 1000,
1000 , pi);
}
And this is the Broadcast Receiver code:
@Override
public void onReceive(Context context, Intent intent) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_main);
DateFormat format =
SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM,
Locale.getDefault());
remoteViews.setTextViewText(R.id.widgetTextView, "TIME = " +
format.format(new Date()));
ComponentName thisWidget = new ComponentName(context, Widget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(thisWidget, remoteViews);
}
Any help would be much appreciated, thank you, SO!
Toggle text, on a checkbox input change
Toggle text, on a checkbox input change
I searched and tried a lot of codes & samples but I didn't get to my
point. I have 3 checkbox inputs and 3 labels after each, and a div
including a <p> tag. I want when I check each checkbox, the next label
text to be copied in the <p> tag, and when I uncheck it, remove the text
in <p> tag. I mean toggling the label text inside the <p> tag by changing
the inputs.
my HTML code :
<div class="chbxs">
<input type="checkbox" name="country" id="Iran" rel="Iran" />
<label for="Iran">Mashad,Tehran</label>
<input type="checkbox" name="country" id="England" rel="England" />
<label for="England">London,Manchester</label>
<input type="checkbox" name="country" id="USA" rel="USA" />
<label for="USA">California,NewYork</label>
</div>
<div class="countries">
<p></p>
</div>
my jquery code :
$('.chbxs input[type="checkbox"]').click(function() {
var chkdChkbox = $(this).next('label').text();
if ($(this).prop('checked') == true) {
$('.countries > p').append('<span>' + chkdChkbox + '</span>');
}
else {
$('.countries > p').children('span').remove();
}
});
The problem is that if I uncheck an input, all spans will be removed. How
can I fix this? Tank you so much. P.S: I also want to separate texts from
each other by a comma.
I searched and tried a lot of codes & samples but I didn't get to my
point. I have 3 checkbox inputs and 3 labels after each, and a div
including a <p> tag. I want when I check each checkbox, the next label
text to be copied in the <p> tag, and when I uncheck it, remove the text
in <p> tag. I mean toggling the label text inside the <p> tag by changing
the inputs.
my HTML code :
<div class="chbxs">
<input type="checkbox" name="country" id="Iran" rel="Iran" />
<label for="Iran">Mashad,Tehran</label>
<input type="checkbox" name="country" id="England" rel="England" />
<label for="England">London,Manchester</label>
<input type="checkbox" name="country" id="USA" rel="USA" />
<label for="USA">California,NewYork</label>
</div>
<div class="countries">
<p></p>
</div>
my jquery code :
$('.chbxs input[type="checkbox"]').click(function() {
var chkdChkbox = $(this).next('label').text();
if ($(this).prop('checked') == true) {
$('.countries > p').append('<span>' + chkdChkbox + '</span>');
}
else {
$('.countries > p').children('span').remove();
}
});
The problem is that if I uncheck an input, all spans will be removed. How
can I fix this? Tank you so much. P.S: I also want to separate texts from
each other by a comma.
Confuse what is the difference between two cases?
Confuse what is the difference between two cases?
My question is related to this SO question.
My first question is as far as I can understand number of objects are 3,
s1, s3 and "abc" (I posted an answer to this question). If some one says
it is 4. How that happens there?
consider my following class.
public class ObjectCount {
static int i;
ObjectCount() {
System.out.println(++i);
}
public static void main(String args[]) {
ObjectCount obj1 = new ObjectCount(); //i=1
ObjectCount obj2 = new ObjectCount(); //i=2
ObjectCount obj3 = obj1; // obj3 is also an object refer same as obj1
}
}
How many objects are there? again I think it should be 2. So how above SO
post answer can be 4 objects?can some one help me to figure it out where I
get some point incorrect?
FYI : Now previous issue has fixed on that post. Incorrect answer has made
correct. It is 3 object there. No need to worry.
My question is related to this SO question.
My first question is as far as I can understand number of objects are 3,
s1, s3 and "abc" (I posted an answer to this question). If some one says
it is 4. How that happens there?
consider my following class.
public class ObjectCount {
static int i;
ObjectCount() {
System.out.println(++i);
}
public static void main(String args[]) {
ObjectCount obj1 = new ObjectCount(); //i=1
ObjectCount obj2 = new ObjectCount(); //i=2
ObjectCount obj3 = obj1; // obj3 is also an object refer same as obj1
}
}
How many objects are there? again I think it should be 2. So how above SO
post answer can be 4 objects?can some one help me to figure it out where I
get some point incorrect?
FYI : Now previous issue has fixed on that post. Incorrect answer has made
correct. It is 3 object there. No need to worry.
Subscribe to:
Comments (Atom)