Is there a forcing closure? – mathoverflow.net
The main theorem of forcing says that for any c.t.m of $ZFC$ like $M$ and
for all partial order $\mathbb{P}$ and $\mathbb{P}$-generic $G$ over $M$,
there is a c.t.m of $ZFC$, like $N$ such that $N$ is …
Monday, 30 September 2013
About finding the rotational volume
About finding the rotational volume
A closed area of y-axis, $y=\pi, y=x+sin(x)$ is rotated on line y=x. Find
the volume of it.
So, I think I have to do an integral looks like this.
$V=\int_{0}^{\sqrt2 \pi} \pi r^2 dt$, where r is the radius of disk and t
is a variable on line y=x.
How should I set up the integral and change the variables?
Thank you.
A closed area of y-axis, $y=\pi, y=x+sin(x)$ is rotated on line y=x. Find
the volume of it.
So, I think I have to do an integral looks like this.
$V=\int_{0}^{\sqrt2 \pi} \pi r^2 dt$, where r is the radius of disk and t
is a variable on line y=x.
How should I set up the integral and change the variables?
Thank you.
Creating a table in h2 database using sequence for primary key
Creating a table in h2 database using sequence for primary key
I am trying to create a table in an H2 database. How do I specify that the
primary key should be generated from a sequence that has been created?
The sequence is called group_seq, and I created it using this statement:
CREATE SEQUENCE GROUP_SEQ;
So when I create the table, how do I specify that I want my primary key
col (ID) to use that sequence?
I am trying to create a table in an H2 database. How do I specify that the
primary key should be generated from a sequence that has been created?
The sequence is called group_seq, and I created it using this statement:
CREATE SEQUENCE GROUP_SEQ;
So when I create the table, how do I specify that I want my primary key
col (ID) to use that sequence?
set string value into text android
set string value into text android
I have tried to get jason data just like following way,
public void jasonParser(){
// Creating JSON Parser instance
JASONParser jParser = new JASONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_RESULT);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String latitude = c.getString(TAG_LONGITUDE);
String lognitute = c.getString(TAG_LATITUDE);
String storeid = c.getString(TAG_STOREID);
String storename = c.getString(TAG_STORENAME);
String logo = c.getString(TAG_LOGO);
String city = c.getString(TAG_CITY);
String distance = c.getString(TAG_DISTANCE);
String num = c.getString(TAG_NUM);
//int distanceIntVlue=Integer.parseInt(distance);
distanceSecond=(TextView)findViewById(R.id.placesecond);
//if(distanceIntVlue<200){
distanceplace.setText(storename);
}
Jason data get. I debugged. but settext method is not debugged. Can't set
the text. pls help me.
I have tried to get jason data just like following way,
public void jasonParser(){
// Creating JSON Parser instance
JASONParser jParser = new JASONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_RESULT);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String latitude = c.getString(TAG_LONGITUDE);
String lognitute = c.getString(TAG_LATITUDE);
String storeid = c.getString(TAG_STOREID);
String storename = c.getString(TAG_STORENAME);
String logo = c.getString(TAG_LOGO);
String city = c.getString(TAG_CITY);
String distance = c.getString(TAG_DISTANCE);
String num = c.getString(TAG_NUM);
//int distanceIntVlue=Integer.parseInt(distance);
distanceSecond=(TextView)findViewById(R.id.placesecond);
//if(distanceIntVlue<200){
distanceplace.setText(storename);
}
Jason data get. I debugged. but settext method is not debugged. Can't set
the text. pls help me.
Sunday, 29 September 2013
Document.write errors because of line break?
Document.write errors because of line break?
<?php
if ( is_home() ) {
?>
<script type="text/javascript">
if ($(window).width() < 768) {
document.write("<?php echo
do_shortcode("[mobile-slider]"); ?>");
} else {
document.write("<?php echo
do_shortcode("[desktop-slider]"); ?>");
}
</script>
My homepage renders and displays "); } else { document.write(" then the
homepage slider and then "); }. Any idea why?
JS error
SyntaxError: unterminated string literal
document.write("
HTML Output - Seems to be adding a line break which I think is breaking
the script?
<script type="text/javascript">
if ($(window).width() < 768) {
document.write("
<!--slider-->
How can I get this to still run even though there is a line break after
the document.write(" opening?
<?php
if ( is_home() ) {
?>
<script type="text/javascript">
if ($(window).width() < 768) {
document.write("<?php echo
do_shortcode("[mobile-slider]"); ?>");
} else {
document.write("<?php echo
do_shortcode("[desktop-slider]"); ?>");
}
</script>
My homepage renders and displays "); } else { document.write(" then the
homepage slider and then "); }. Any idea why?
JS error
SyntaxError: unterminated string literal
document.write("
HTML Output - Seems to be adding a line break which I think is breaking
the script?
<script type="text/javascript">
if ($(window).width() < 768) {
document.write("
<!--slider-->
How can I get this to still run even though there is a line break after
the document.write(" opening?
Including libraries in c++ form
Including libraries in c++ form
I have been making console applications in c++ forever. Now i want to
switch over to making forms. So I was just wondering how I would include
other libaries. For example I wanted to make a program that had a function
involving time, in a console app i would put #include .... I want to know
what is the equivlance of this in a form. By the way, im using visual c++
2010 for windows
I have been making console applications in c++ forever. Now i want to
switch over to making forms. So I was just wondering how I would include
other libaries. For example I wanted to make a program that had a function
involving time, in a console app i would put #include .... I want to know
what is the equivlance of this in a form. By the way, im using visual c++
2010 for windows
Selenium WebDriver - Chrome Driver for Windows 8 64 bit
Selenium WebDriver - Chrome Driver for Windows 8 64 bit
I am new to Selenium and writing my test cases only for firefox. I wish to
write it also for Chrome driver. But where should I download for Widows 8
64 bit.
I am new to Selenium and writing my test cases only for firefox. I wish to
write it also for Chrome driver. But where should I download for Widows 8
64 bit.
QlineEdit -- how to enter single value -- with no spaces
QlineEdit -- how to enter single value -- with no spaces
I have made an editor in which i have to enter a Hex or decimal value in
each field. Here the field i am using is QlineEdit.
Now requirement is that each Qlineedit box accept only one value without
spaces. Then i can read this text value & convert it directly from string
to decimal.
Is it possible to make QlineEdit to accept only one value without spaces ?
Boxes in below figure are QlineEdit.
I do not want to use combo box here.
I have made an editor in which i have to enter a Hex or decimal value in
each field. Here the field i am using is QlineEdit.
Now requirement is that each Qlineedit box accept only one value without
spaces. Then i can read this text value & convert it directly from string
to decimal.
Is it possible to make QlineEdit to accept only one value without spaces ?
Boxes in below figure are QlineEdit.
I do not want to use combo box here.
Saturday, 28 September 2013
How to iterate through this matrix in matlab?
How to iterate through this matrix in matlab?
I'm new to matlab and I'm trying to do the following:
For each x in [L, a, and b] :
TxP = tx_ * ratio_x;
where I have a matrix with dimensions L,a,b and the 'x' part of tx_ refers
to the dimension L, a, or b.
I'm just unsure of the syntax to make this happen. Can anyone help me out?
I'm new to matlab and I'm trying to do the following:
For each x in [L, a, and b] :
TxP = tx_ * ratio_x;
where I have a matrix with dimensions L,a,b and the 'x' part of tx_ refers
to the dimension L, a, or b.
I'm just unsure of the syntax to make this happen. Can anyone help me out?
How to pull most recent gas price from this example page
How to pull most recent gas price from this example page
I am trying to pull the most recent gas price at a set interval...say
everyday from this website
http://www.atlantagasprices.com/index.aspx?area=Decatur&area=North%20Decatur
via php and then apply my own formatting to it. How can I go about this? I
tried to read up on simplehtmldom but I am kind of new to programming and
am a little confused. If anyone can guide me..I would appreciate it.
thanks!
I am trying to pull the most recent gas price at a set interval...say
everyday from this website
http://www.atlantagasprices.com/index.aspx?area=Decatur&area=North%20Decatur
via php and then apply my own formatting to it. How can I go about this? I
tried to read up on simplehtmldom but I am kind of new to programming and
am a little confused. If anyone can guide me..I would appreciate it.
thanks!
X.509 certificate validation proccess
X.509 certificate validation proccess
so i have been reading on x.509 certificates and i just don't quite get
how the entire process works.
so this is how i understand it: the CA is some company which produces
certificates. someone who wants to use one, like a bank website, contacts
the CA and buys a certificate containing the public key to encode the
messages for the website, which can only be decoded by the sites private
key.
this is where i get confused - how does the user (some web browser),
checks that the certificate it received is actually true and really came
from the correct site? how does it know its still valid? what kind of
checks are made to make sure everything is OK?
Thank you!
so i have been reading on x.509 certificates and i just don't quite get
how the entire process works.
so this is how i understand it: the CA is some company which produces
certificates. someone who wants to use one, like a bank website, contacts
the CA and buys a certificate containing the public key to encode the
messages for the website, which can only be decoded by the sites private
key.
this is where i get confused - how does the user (some web browser),
checks that the certificate it received is actually true and really came
from the correct site? how does it know its still valid? what kind of
checks are made to make sure everything is OK?
Thank you!
Simple python ORMapper requiring no explicit mapping in the persistent classes
Simple python ORMapper requiring no explicit mapping in the persistent
classes
I am looking for a Python ORMapper which would allow for easy,
non-intrusive persistent storage of a bunch of simple objects:
I have already a set of classes, which I wouldn't want to pollute with any
ORMapper code
once I have thing set up, I would like to be able to add new properties to
my classes and do nothing more with the ORMapper
I don't care much how are the objects stored - table names, table columns,
data types, etc. - reasonable defaults are fine
The objects contain references to other objects and basically
String/integer properties.
Do you know of anything like this?
classes
I am looking for a Python ORMapper which would allow for easy,
non-intrusive persistent storage of a bunch of simple objects:
I have already a set of classes, which I wouldn't want to pollute with any
ORMapper code
once I have thing set up, I would like to be able to add new properties to
my classes and do nothing more with the ORMapper
I don't care much how are the objects stored - table names, table columns,
data types, etc. - reasonable defaults are fine
The objects contain references to other objects and basically
String/integer properties.
Do you know of anything like this?
Friday, 27 September 2013
Is "half-byte" ever actually used as a term?
Is "half-byte" ever actually used as a term?
Okay, so if a byte is 8-bits, then a half-byte would simply 4-bits. And
you could have a quarter-byte as 2-bits (though I guess, if anything, it'd
be reffered to as a double-bit).
While this is consistent, would anyone be confused (or surprised) if I
used the term? Obviously, it would be fairly easy for them to grasp what I
was referring to, but is it actually a commonly used term?
Okay, so if a byte is 8-bits, then a half-byte would simply 4-bits. And
you could have a quarter-byte as 2-bits (though I guess, if anything, it'd
be reffered to as a double-bit).
While this is consistent, would anyone be confused (or surprised) if I
used the term? Obviously, it would be fairly easy for them to grasp what I
was referring to, but is it actually a commonly used term?
Attempt by security transparent method xxx to access security critical yy
Attempt by security transparent method xxx to access security critical yy
I posted this problem in asp.net/forums/mvc; somebody recomended I posted
here, which is more specific forum for PagedList. So I'm just going to
copy the post from asp.net/forums. Hope somebody gives a clue how to solve
this issue ...
I'm just starting to learn asp.net mvc and following one of the asp.net
site Asp.Net MVC tutorials, which are all excelent.
I'm using Visual Studio Express 2013 RC for Web and think that could be
the reason for my problem, because the tutorial for paging is written
using VS2012.
Now, everything is working fine; but when I add paging to one of the
pages, using all the instructions in the tutorial for adding
PagedList.mvc, everything compiles fine; when I get to the specific page,
I receive this error message:
Attempt by security transparent method
'PagedList.Mvc.HtmlHelper.PagedListPager(System.Web.Mvc.HtmlHelper,
PagedList.IPagedList, System.Func`2)' to access security critical type
'System.Web.Mvc.MvcHtmlString' failed.
Assembly 'PagedList.Mvc, Version=4.3.0.0, Culture=neutral,
PublicKeyToken=abbb863e9397c5e1' is marked with the
AllowPartiallyTrustedCallersAttribute, and uses the level 2 security
transparency model. Level 2 transparency causes all methods in
AllowPartiallyTrustedCallers assemblies to become security transparent by
default, which may be the cause of this exception.
Anybody can give some reason why this situation is happening? Many thanks
in advance and bye ...
I posted this problem in asp.net/forums/mvc; somebody recomended I posted
here, which is more specific forum for PagedList. So I'm just going to
copy the post from asp.net/forums. Hope somebody gives a clue how to solve
this issue ...
I'm just starting to learn asp.net mvc and following one of the asp.net
site Asp.Net MVC tutorials, which are all excelent.
I'm using Visual Studio Express 2013 RC for Web and think that could be
the reason for my problem, because the tutorial for paging is written
using VS2012.
Now, everything is working fine; but when I add paging to one of the
pages, using all the instructions in the tutorial for adding
PagedList.mvc, everything compiles fine; when I get to the specific page,
I receive this error message:
Attempt by security transparent method
'PagedList.Mvc.HtmlHelper.PagedListPager(System.Web.Mvc.HtmlHelper,
PagedList.IPagedList, System.Func`2)' to access security critical type
'System.Web.Mvc.MvcHtmlString' failed.
Assembly 'PagedList.Mvc, Version=4.3.0.0, Culture=neutral,
PublicKeyToken=abbb863e9397c5e1' is marked with the
AllowPartiallyTrustedCallersAttribute, and uses the level 2 security
transparency model. Level 2 transparency causes all methods in
AllowPartiallyTrustedCallers assemblies to become security transparent by
default, which may be the cause of this exception.
Anybody can give some reason why this situation is happening? Many thanks
in advance and bye ...
Facebook thinks my og:image is too small
Facebook thinks my og:image is too small
So I'm trying to get the og:image tag working properly on my site
(www.listingtrends.com). FB's object debugger tells me that the image
isn't big enough, but if you go to the actual image it's seeing
(http://www.listingtrends.com/Images/TrendsLogo_Facebook.png), it's
230x200. Any ideas?
Thanks.
So I'm trying to get the og:image tag working properly on my site
(www.listingtrends.com). FB's object debugger tells me that the image
isn't big enough, but if you go to the actual image it's seeing
(http://www.listingtrends.com/Images/TrendsLogo_Facebook.png), it's
230x200. Any ideas?
Thanks.
Grunt copy need suggestion for how to simplify task
Grunt copy need suggestion for how to simplify task
I am using the Grunt copy task in a Gruntfile. The project was created by
Yeoman.
I am looking for suggestions on how to simplify the task definition.
You'll notice the expand and dest fields are the same for each set of
files. Is there a way I can simplify this? Can I use options?
Here is my task
copy: {
componentsToTmp: {
files: [
{
expand: true,
cwd: '<%= yeoman.components %>/angular',
dest: '<%= yeoman.tmp %>/js',
src: ['angular.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/angular-bootstrap',
dest: '<%= yeoman.tmp %>/js',
src: ['ui-bootstrap-tpls.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/angular-cookies',
dest: '<%= yeoman.tmp %>/js',
src: ['angular-cookies.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/angular-l10n/build',
dest: '<%= yeoman.tmp %>/js',
src: ['l10n.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/angular-local-storage',
dest: '<%= yeoman.tmp %>/js',
src: ['angular-local-storage.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/angular-resource',
dest: '<%= yeoman.tmp %>/js',
src: ['angular-resource.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/angular-sanitize',
dest: '<%= yeoman.tmp %>/js',
src: ['angular-sanitize.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/angular-ui/build',
dest: '<%= yeoman.tmp %>/js',
src: ['angular-ui.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/angularjs-gravatardirective/src',
dest: '<%= yeoman.tmp %>/js',
src: ['md5-service.min.js', 'gravatar-directive.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/bootstrap/bootstrap/js',
dest: '<%= yeoman.tmp %>/js',
src: ['bootstrap.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/jquery',
dest: '<%= yeoman.tmp %>/js',
src: ['jquery.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/jquery-ui/ui/minified',
dest: '<%= yeoman.tmp %>/js',
src: ['jquery-ui.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/momentjs/min',
dest: '<%= yeoman.tmp %>/js',
src: ['moment.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/qrcode',
dest: '<%= yeoman.tmp %>/js',
src: ['qrcode.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/underscore',
dest: '<%= yeoman.tmp %>/js',
src: ['underscore-min.js']
},
{
expand: true,
cwd: '<%= yeoman.app %>/angular-local-storage-obscure',
dest: '<%= yeoman.tmp %>/js',
src: ['angular-local-storage-obscure.js']
}
]
}
}
I am using the Grunt copy task in a Gruntfile. The project was created by
Yeoman.
I am looking for suggestions on how to simplify the task definition.
You'll notice the expand and dest fields are the same for each set of
files. Is there a way I can simplify this? Can I use options?
Here is my task
copy: {
componentsToTmp: {
files: [
{
expand: true,
cwd: '<%= yeoman.components %>/angular',
dest: '<%= yeoman.tmp %>/js',
src: ['angular.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/angular-bootstrap',
dest: '<%= yeoman.tmp %>/js',
src: ['ui-bootstrap-tpls.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/angular-cookies',
dest: '<%= yeoman.tmp %>/js',
src: ['angular-cookies.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/angular-l10n/build',
dest: '<%= yeoman.tmp %>/js',
src: ['l10n.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/angular-local-storage',
dest: '<%= yeoman.tmp %>/js',
src: ['angular-local-storage.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/angular-resource',
dest: '<%= yeoman.tmp %>/js',
src: ['angular-resource.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/angular-sanitize',
dest: '<%= yeoman.tmp %>/js',
src: ['angular-sanitize.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/angular-ui/build',
dest: '<%= yeoman.tmp %>/js',
src: ['angular-ui.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/angularjs-gravatardirective/src',
dest: '<%= yeoman.tmp %>/js',
src: ['md5-service.min.js', 'gravatar-directive.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/bootstrap/bootstrap/js',
dest: '<%= yeoman.tmp %>/js',
src: ['bootstrap.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/jquery',
dest: '<%= yeoman.tmp %>/js',
src: ['jquery.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/jquery-ui/ui/minified',
dest: '<%= yeoman.tmp %>/js',
src: ['jquery-ui.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/momentjs/min',
dest: '<%= yeoman.tmp %>/js',
src: ['moment.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/qrcode',
dest: '<%= yeoman.tmp %>/js',
src: ['qrcode.min.js']
},
{
expand: true,
cwd: '<%= yeoman.components %>/underscore',
dest: '<%= yeoman.tmp %>/js',
src: ['underscore-min.js']
},
{
expand: true,
cwd: '<%= yeoman.app %>/angular-local-storage-obscure',
dest: '<%= yeoman.tmp %>/js',
src: ['angular-local-storage-obscure.js']
}
]
}
}
passing context via fragment
passing context via fragment
I am having an issue instantiating a new object from a util class into a
fragment class. the instantiation requires passing a context but I
fragment cant take context.
I have tried passing getActivity() but still getting a NULL POINTER
EXCEPTION FOR GpsAssist.getLatitude(Since this is the first one to be
called) error.
I am trying to call the methods getLatitude() and getLongitude() from the
GpsAssist
Below is my code . could use all the help.
Thank you
MapsActivity Class:
public class MapsActivity extends Fragment {
GoogleMap map;
private View view;
GpsAssist gAssist = new GpsAssist(getActivity());
double lat = gAssist.getLatitude();
double lng = gAssist.getLongitude();
private final LatLng MOUNTAIN_VIEW = new LatLng(lat, lng);
private LatLngBounds loc = new LatLngBounds(new LatLng(37, -121), new
LatLng(37,-121));
public void get(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.map_test, container, false);
if(map == null){
map = ((SupportMapFragment)
getFragmentManager().findFragmentById(R.id.map)).getMap();
map.addMarker(new
MarkerOptions().position(MOUNTAIN_VIEW).title("Marker"));
map.animateCamera(CameraUpdateFactory.newCameraPosition(posi()));
}else{
//map.moveCamera(CameraUpdateFactory.newLatLngBounds(loc, 15));
}
return view;
}
public CameraPosition posi(){
CameraPosition posi = new CameraPosition.Builder()
.target(MOUNTAIN_VIEW)
.zoom(17)
.build();
return posi;
}
@Override
public void onDestroyView() {
try{
SupportMapFragment fragment = ((SupportMapFragment)
getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft =
getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
//map.addMarker(new MarkerOptions().position(new LatLng(0,
0)).title("Marker"));
}catch(Exception e){
}
super.onDestroyView();
}
}
My GpsAssist Class:
public class GpsAssist extends Service {
//Primitive declarations
private double lat;
private double lng;
private String provider;
//Class instances
private Context context;
private Geocoder gCoder;
Location location;
public GpsAssist(Context context){
this.context = context;
}
//Checking if GPS is enabled
LocationManager lManager;
public Location gpsConnected(){
lManager = (LocationManager)
context.getSystemService(Context.LOCATION_SERVICE);
boolean gpsEnabled =
lManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean networkEnabled =
lManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(! gpsEnabled && ! networkEnabled ){
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}else {
location =
lManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null){
lat = getLatitude();
lng = getLongitude();
Toast t = Toast.makeText(context, "Your location" + lat + " "
+ lng, Toast.LENGTH_SHORT);
t.show();
String addresses = getAddress(lat, lng, 2);
Toast address = Toast.makeText(context, addresses,
Toast.LENGTH_LONG);
address.show();
}else{
Toast t = Toast.makeText(context, "Cannot get your location",
Toast.LENGTH_SHORT);
t.show();
}
}
return location;
}
//Method to find the best possible provider
public String getProvider(){
Criteria criteria = new Criteria();
//true means that only enabled providers will be returned
provider = lManager.getBestProvider(criteria, true);
return provider;
}
public double getLatitude(){
lat = location.getLatitude();
return lat;
}
public double getLongitude(){
lng = location.getLongitude();
return lng;
}
public String getAddress(double lat, double lng, int maxR){
String addres = "";
gCoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> address = gCoder.getFromLocation(lat, lng, maxR);
if(address != null){
Address adName = address.get(0);
StringBuilder str = new StringBuilder("Address: \n");
for(int i=0; i<adName.getMaxAddressLineIndex(); i++){
str.append(adName.getAddressLine(i)).append("\n");
}
addres = str.toString();
System.out.println(addres);
}else{
addres = "Address is null";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am having an issue instantiating a new object from a util class into a
fragment class. the instantiation requires passing a context but I
fragment cant take context.
I have tried passing getActivity() but still getting a NULL POINTER
EXCEPTION FOR GpsAssist.getLatitude(Since this is the first one to be
called) error.
I am trying to call the methods getLatitude() and getLongitude() from the
GpsAssist
Below is my code . could use all the help.
Thank you
MapsActivity Class:
public class MapsActivity extends Fragment {
GoogleMap map;
private View view;
GpsAssist gAssist = new GpsAssist(getActivity());
double lat = gAssist.getLatitude();
double lng = gAssist.getLongitude();
private final LatLng MOUNTAIN_VIEW = new LatLng(lat, lng);
private LatLngBounds loc = new LatLngBounds(new LatLng(37, -121), new
LatLng(37,-121));
public void get(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.map_test, container, false);
if(map == null){
map = ((SupportMapFragment)
getFragmentManager().findFragmentById(R.id.map)).getMap();
map.addMarker(new
MarkerOptions().position(MOUNTAIN_VIEW).title("Marker"));
map.animateCamera(CameraUpdateFactory.newCameraPosition(posi()));
}else{
//map.moveCamera(CameraUpdateFactory.newLatLngBounds(loc, 15));
}
return view;
}
public CameraPosition posi(){
CameraPosition posi = new CameraPosition.Builder()
.target(MOUNTAIN_VIEW)
.zoom(17)
.build();
return posi;
}
@Override
public void onDestroyView() {
try{
SupportMapFragment fragment = ((SupportMapFragment)
getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft =
getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
//map.addMarker(new MarkerOptions().position(new LatLng(0,
0)).title("Marker"));
}catch(Exception e){
}
super.onDestroyView();
}
}
My GpsAssist Class:
public class GpsAssist extends Service {
//Primitive declarations
private double lat;
private double lng;
private String provider;
//Class instances
private Context context;
private Geocoder gCoder;
Location location;
public GpsAssist(Context context){
this.context = context;
}
//Checking if GPS is enabled
LocationManager lManager;
public Location gpsConnected(){
lManager = (LocationManager)
context.getSystemService(Context.LOCATION_SERVICE);
boolean gpsEnabled =
lManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean networkEnabled =
lManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(! gpsEnabled && ! networkEnabled ){
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}else {
location =
lManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null){
lat = getLatitude();
lng = getLongitude();
Toast t = Toast.makeText(context, "Your location" + lat + " "
+ lng, Toast.LENGTH_SHORT);
t.show();
String addresses = getAddress(lat, lng, 2);
Toast address = Toast.makeText(context, addresses,
Toast.LENGTH_LONG);
address.show();
}else{
Toast t = Toast.makeText(context, "Cannot get your location",
Toast.LENGTH_SHORT);
t.show();
}
}
return location;
}
//Method to find the best possible provider
public String getProvider(){
Criteria criteria = new Criteria();
//true means that only enabled providers will be returned
provider = lManager.getBestProvider(criteria, true);
return provider;
}
public double getLatitude(){
lat = location.getLatitude();
return lat;
}
public double getLongitude(){
lng = location.getLongitude();
return lng;
}
public String getAddress(double lat, double lng, int maxR){
String addres = "";
gCoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> address = gCoder.getFromLocation(lat, lng, maxR);
if(address != null){
Address adName = address.get(0);
StringBuilder str = new StringBuilder("Address: \n");
for(int i=0; i<adName.getMaxAddressLineIndex(); i++){
str.append(adName.getAddressLine(i)).append("\n");
}
addres = str.toString();
System.out.println(addres);
}else{
addres = "Address is null";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
how to check if Cloumn B has values in Column A
how to check if Cloumn B has values in Column A
A B
8680533551839 8680533451894 8680533551815 8680533445329 8680533551860
8680533530230 8680533551877 8680533647013 8680533552270 8680533634495
8680533552287 8680533634655 8680533530315 8680533633986 8680533527971
8680533634280 8680533527988 8680533633917 8680533527964
8680533530308
8680533527995
8680533530230
8680533530223
8680533470550
8680533470529
hey guys, is there a formula to check if values in B are present in A? its
a big list!
A B
8680533551839 8680533451894 8680533551815 8680533445329 8680533551860
8680533530230 8680533551877 8680533647013 8680533552270 8680533634495
8680533552287 8680533634655 8680533530315 8680533633986 8680533527971
8680533634280 8680533527988 8680533633917 8680533527964
8680533530308
8680533527995
8680533530230
8680533530223
8680533470550
8680533470529
hey guys, is there a formula to check if values in B are present in A? its
a big list!
In Core Data, should I put the more restrictive or less restrictive predicate first?
In Core Data, should I put the more restrictive or less restrictive
predicate first?
-(NSPredicate *) predicateForExactMatch
{
enum typeOfAutocompleteNew toc = [[self class] typeOfAutoComplete];
NSPredicate * predictNameMatch=[NSPredicate
predicateWithFormat:@"%K==[cd]%@",NSStringFromSelector(@selector(strNameofPlace)),self.strCurrentKeyword];
NSPredicate * entryTypeNameMatch=[NSPredicate
predicateWithFormat:@"%K==[cd]%@",NSStringFromSelector(@selector(strEntry)),@(toc)];
NSPredicate * final = [NSCompoundPredicate
andPredicateWithSubpredicates:@[predictNameMatch,entryTypeNameMatch]];
return final;
}
Which one is better?
NSPredicate * final = [NSCompoundPredicate
andPredicateWithSubpredicates:@[predictNameMatch,entryTypeNameMatch]];
or
NSPredicate * final = [NSCompoundPredicate
andPredicateWithSubpredicates:@[entryTypeNameMatch,predictNameMatch]];
Here, predictNameMatch is definitely far more restrictive. At most 1-2 are
exact match. entryTypeNameMatch match like 25% of data.
predicate first?
-(NSPredicate *) predicateForExactMatch
{
enum typeOfAutocompleteNew toc = [[self class] typeOfAutoComplete];
NSPredicate * predictNameMatch=[NSPredicate
predicateWithFormat:@"%K==[cd]%@",NSStringFromSelector(@selector(strNameofPlace)),self.strCurrentKeyword];
NSPredicate * entryTypeNameMatch=[NSPredicate
predicateWithFormat:@"%K==[cd]%@",NSStringFromSelector(@selector(strEntry)),@(toc)];
NSPredicate * final = [NSCompoundPredicate
andPredicateWithSubpredicates:@[predictNameMatch,entryTypeNameMatch]];
return final;
}
Which one is better?
NSPredicate * final = [NSCompoundPredicate
andPredicateWithSubpredicates:@[predictNameMatch,entryTypeNameMatch]];
or
NSPredicate * final = [NSCompoundPredicate
andPredicateWithSubpredicates:@[entryTypeNameMatch,predictNameMatch]];
Here, predictNameMatch is definitely far more restrictive. At most 1-2 are
exact match. entryTypeNameMatch match like 25% of data.
Thursday, 26 September 2013
Node run security checks before uploading to s3
Node run security checks before uploading to s3
I'm working on a way to upload a file from node to s3 using Knox running
on heroku or openshift. First, since I'm trying to get a direct stream
from the users computer to s3, are security scans(like mime type) , even
important? Second, since I will have about 100 mb of space on my heroku
instance, is it even possible to run scans without the file directly on my
server? Could I scan the file once it is on s3 without entirely
downloading it? Third, if a user get's a virus from a file uploaded to my
site, could I be considared liable? Thanks for your responses!
I'm working on a way to upload a file from node to s3 using Knox running
on heroku or openshift. First, since I'm trying to get a direct stream
from the users computer to s3, are security scans(like mime type) , even
important? Second, since I will have about 100 mb of space on my heroku
instance, is it even possible to run scans without the file directly on my
server? Could I scan the file once it is on s3 without entirely
downloading it? Third, if a user get's a virus from a file uploaded to my
site, could I be considared liable? Thanks for your responses!
Wednesday, 25 September 2013
query_builder on sonataAdminBundle is ignored
query_builder on sonataAdminBundle is ignored
I am using sonataAdminBundle and symfony2
I made this script. it filter the search box candidates.
but this query_builder is ignored.
Are there any other points to check ?
public function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('user',null,
array(
'query_builder' =>
function (\Doctrine\ORM\EntityRepository $rep) {
return $rep->
createQueryBuilder('s')
->where('s.id','1');
})
I am using sonataAdminBundle and symfony2
I made this script. it filter the search box candidates.
but this query_builder is ignored.
Are there any other points to check ?
public function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('user',null,
array(
'query_builder' =>
function (\Doctrine\ORM\EntityRepository $rep) {
return $rep->
createQueryBuilder('s')
->where('s.id','1');
})
Thursday, 19 September 2013
Casting error when using strcmp function
Casting error when using strcmp function
I am trying to compare 2 arrays using a strcmp, but error shows 'passing
argument (1 and 2) of 'strcmp' makes pointer from integer without a cast'
when compiling. Does anyone know where is the mistake I make?
char file1[MAX_MAC_ADD][BIG_NUM];
char save_MAC[MAX_MAC_ADD][BIG_NUM];
int unique_MAC = 0;
char temp1[16];
char temp2[16];
for(int i= 0; i <17; i++)
{
temp1[i] = file1[2][i];
}
for(int i = 0; i < unique_MAC+1; i++)
{
for(int j = 0; j <17; j++)
{
temp2[j] = save_MAC[i][j];
}
}
//if not the same
if(strcmp(temp1, temp2 != 0))
{
//copy address into save_MAC
strcpy(save_MAC[unique_MAC], temp1);
unique_MAC++;
}
I am trying to compare 2 arrays using a strcmp, but error shows 'passing
argument (1 and 2) of 'strcmp' makes pointer from integer without a cast'
when compiling. Does anyone know where is the mistake I make?
char file1[MAX_MAC_ADD][BIG_NUM];
char save_MAC[MAX_MAC_ADD][BIG_NUM];
int unique_MAC = 0;
char temp1[16];
char temp2[16];
for(int i= 0; i <17; i++)
{
temp1[i] = file1[2][i];
}
for(int i = 0; i < unique_MAC+1; i++)
{
for(int j = 0; j <17; j++)
{
temp2[j] = save_MAC[i][j];
}
}
//if not the same
if(strcmp(temp1, temp2 != 0))
{
//copy address into save_MAC
strcpy(save_MAC[unique_MAC], temp1);
unique_MAC++;
}
Array to string conversion
Array to string conversion
looked around and everything seems to be more complex that what I am
trying to do.
I have queried an item from a previous page and brought it forward.
$varVeh=$_POST['Veh_num'];
I echo that and it show the proper number....
I then want to use the name associated with that number in a table title.
so I do another query:
$sql_vehName="select Veh_name from hc_vehicle_type where Veh_num=$varVeh";
$result_vehName = mysql_query($sql_vehName);
$vehName=mysql_fetch_assoc($result_vehName);
echo $vehName;
echo "<table border='1'>";
echo "<tr><td>Best Scores for</td><td>$vehName</td> </tr>";
Without using the fetch I get resource #6.
looked around and everything seems to be more complex that what I am
trying to do.
I have queried an item from a previous page and brought it forward.
$varVeh=$_POST['Veh_num'];
I echo that and it show the proper number....
I then want to use the name associated with that number in a table title.
so I do another query:
$sql_vehName="select Veh_name from hc_vehicle_type where Veh_num=$varVeh";
$result_vehName = mysql_query($sql_vehName);
$vehName=mysql_fetch_assoc($result_vehName);
echo $vehName;
echo "<table border='1'>";
echo "<tr><td>Best Scores for</td><td>$vehName</td> </tr>";
Without using the fetch I get resource #6.
Create a temporary container and append all body content to that container
Create a temporary container and append all body content to that container
What I am attempting to do with JavaScript (no libraries) is to create a
fragment append all the content of the body into that fragment:
var _fragment = document.createDocumentFragment(),
_children = document.body.childNodes;
for( var i=0,_clen=_children.length; i<_clen; i++ ) {
_fragment.appendChild( _children[i] );
}
This does not seem to be working for some reason.
Best, Speedy
What I am attempting to do with JavaScript (no libraries) is to create a
fragment append all the content of the body into that fragment:
var _fragment = document.createDocumentFragment(),
_children = document.body.childNodes;
for( var i=0,_clen=_children.length; i<_clen; i++ ) {
_fragment.appendChild( _children[i] );
}
This does not seem to be working for some reason.
Best, Speedy
Cannot display child context menu
Cannot display child context menu
I have something like this
QPoint globalPos = ui.lineEditA->mapToGlobal(pos);
QMenu mnumain;
mnumain.setTitle("Parent Menu");
QMenu mnuBooleanOperators;
mnuBooleanOperators.setTitle("Child Menu");
mnuBooleanOperators.addAction("Child Action A");
mnuBooleanOperators.addAction("Child Action B");
mnumain.addMenu
// ...
QAction* selectedItem = mnumain.exec(globalPos);
Now only Parent Menu shows up when I right click however I do not see the
Child Menu ? Any suggestions on what I might be missing ?
I have something like this
QPoint globalPos = ui.lineEditA->mapToGlobal(pos);
QMenu mnumain;
mnumain.setTitle("Parent Menu");
QMenu mnuBooleanOperators;
mnuBooleanOperators.setTitle("Child Menu");
mnuBooleanOperators.addAction("Child Action A");
mnuBooleanOperators.addAction("Child Action B");
mnumain.addMenu
// ...
QAction* selectedItem = mnumain.exec(globalPos);
Now only Parent Menu shows up when I right click however I do not see the
Child Menu ? Any suggestions on what I might be missing ?
CQ5 text component is removing target attribute from links
CQ5 text component is removing target attribute from links
We have using CQ5 Text component which is Rich Text Editor with link
plugin. When we create a link in a table component with target=_new param
it preservs this param in rendered html. When we use this in a para tag it
drops the target=_new from hte rendered html.
Anyone has any idea why its happening or quick fix?
Thanks Ashish
We have using CQ5 Text component which is Rich Text Editor with link
plugin. When we create a link in a table component with target=_new param
it preservs this param in rendered html. When we use this in a para tag it
drops the target=_new from hte rendered html.
Anyone has any idea why its happening or quick fix?
Thanks Ashish
How to return from AJAX wrapper function
How to return from AJAX wrapper function
var wrapper = function() {
var condition; //boolean
$.get('url', function(data) {
console.log(data); //url
condition = true/false;
});
return condition;
}
when I do wrapper() it returns always undefined because of async nature of
$.get. How to I solve this issue?
var wrapper = function() {
var condition; //boolean
$.get('url', function(data) {
console.log(data); //url
condition = true/false;
});
return condition;
}
when I do wrapper() it returns always undefined because of async nature of
$.get. How to I solve this issue?
Mime source string to object
Mime source string to object
I have a standard whole Mime source text string I need converted to either
a Java or PHP object (or both if you want to show off !) so it can be
manipulated in these platforms. I have looked everywhere but only seem to
be able to create from scratch.
I have a standard whole Mime source text string I need converted to either
a Java or PHP object (or both if you want to show off !) so it can be
manipulated in these platforms. I have looked everywhere but only seem to
be able to create from scratch.
Wednesday, 18 September 2013
jQuery Validation From Dynamic Form Not Working
jQuery Validation From Dynamic Form Not Working
I am retrieving a form with ajax, once i have received the form and added
it to the DOM, i try to append some validation to it with jQuery, the
result is not as expected.
The HTML that i insert into the page from an AJAX call is:
<form id="accept-form">
<input id="txName" type="text" value="" name="txName"
data-val-required="Please Select A Valid User" data-val="true">
<span class="field-validation-valid" data-valmsg-for="txName"
data-valmsg-replace="true"></span>
</form>
I then append this form to my page and attempt to create a jQuery
validator for it as follows:
$("#accept-form").validate({
rules: {
txName: {
required: true
}
},
messages: {
txName: {
required: "Enter your name"
}
}
});
Then when i press the submit button, i have an alert set that returns True
regardless of if the txName field is empty or not:
alert($("#accept-form").valid());
Have tried several different approaches, would appreciate any ideas as to
what I could be doing wrong.
I am retrieving a form with ajax, once i have received the form and added
it to the DOM, i try to append some validation to it with jQuery, the
result is not as expected.
The HTML that i insert into the page from an AJAX call is:
<form id="accept-form">
<input id="txName" type="text" value="" name="txName"
data-val-required="Please Select A Valid User" data-val="true">
<span class="field-validation-valid" data-valmsg-for="txName"
data-valmsg-replace="true"></span>
</form>
I then append this form to my page and attempt to create a jQuery
validator for it as follows:
$("#accept-form").validate({
rules: {
txName: {
required: true
}
},
messages: {
txName: {
required: "Enter your name"
}
}
});
Then when i press the submit button, i have an alert set that returns True
regardless of if the txName field is empty or not:
alert($("#accept-form").valid());
Have tried several different approaches, would appreciate any ideas as to
what I could be doing wrong.
Can I add methods to a Groovy base Script dynamically, from Java?
Can I add methods to a Groovy base Script dynamically, from Java?
Although it's not standard practice, I'm curious if it's possible to
inject methods into a GroovyShell compilation context.
The idea is to have something like (in Java):
GroovyShell shell = new GroovyShell();
Script script = shell.parse("test()");
script.run();
Where I'd like to dynamically add methods that are invokable, where test()
has been listed.
I've experimented a bit with messing with the Script metaClass, but I
don't see a way to actually manipulate the metaClass from Java. In
particular, calling script.getMetaClass().getMethods().add(...) throws an
UnsupportedOperationException.
In essence, I'd like to define DSL call-points that invoke Java methods
rather than Groovy-based ones. I'm willing to write this part in Groovy
(and am aware of how to do this), but I'm genuinely curious if this is a
viable alternative approach, or if it's not, what the pitfalls are.
In short: how can I dynamically define a method that GroovyShell knows about?
Although it's not standard practice, I'm curious if it's possible to
inject methods into a GroovyShell compilation context.
The idea is to have something like (in Java):
GroovyShell shell = new GroovyShell();
Script script = shell.parse("test()");
script.run();
Where I'd like to dynamically add methods that are invokable, where test()
has been listed.
I've experimented a bit with messing with the Script metaClass, but I
don't see a way to actually manipulate the metaClass from Java. In
particular, calling script.getMetaClass().getMethods().add(...) throws an
UnsupportedOperationException.
In essence, I'd like to define DSL call-points that invoke Java methods
rather than Groovy-based ones. I'm willing to write this part in Groovy
(and am aware of how to do this), but I'm genuinely curious if this is a
viable alternative approach, or if it's not, what the pitfalls are.
In short: how can I dynamically define a method that GroovyShell knows about?
Data sent to server using jquery get not requiring stings to be declared in quotations?
Data sent to server using jquery get not requiring stings to be declared
in quotations?
When using Jquery's get function I found a code snippet which I have
implemented in which data is sent to the server. the data is given to the
get function as a dictionary. In this dictionary the keys act as strings
yet are not wrapped in quotations. The values in this dictionary are
wrapped as strings. Can anyone explain what the difference is? the
variable name and time are NOT defined anywhere previously in the script.
Included is the entire script below.
<script>
$(document).ready(function () {
$.ajaxSetup({ cache: false });
$('button').click(function () {
$.get('query.php',{ name: "John", time: "2pm" },function (data) {
alert(data);
});
});
});
</script>
in quotations?
When using Jquery's get function I found a code snippet which I have
implemented in which data is sent to the server. the data is given to the
get function as a dictionary. In this dictionary the keys act as strings
yet are not wrapped in quotations. The values in this dictionary are
wrapped as strings. Can anyone explain what the difference is? the
variable name and time are NOT defined anywhere previously in the script.
Included is the entire script below.
<script>
$(document).ready(function () {
$.ajaxSetup({ cache: false });
$('button').click(function () {
$.get('query.php',{ name: "John", time: "2pm" },function (data) {
alert(data);
});
});
});
</script>
Why do I get 2 hits with different data from PayPal's IPN?
Why do I get 2 hits with different data from PayPal's IPN?
After I make a simple web transaction on my site, my IPN handler recieves
not just the one expected 'completed' hit, but 2 hits. Each with different
data. The first looks like this:
stdClass Object
(
[mc_gross] => 50.00
[invoice] => PVIFmMOZTm2xkjbs
[protection_eligibility] => Ineligible
[payer_id] => NRQL7RKB54XWY
[tax] => 0.00
[payment_date] => 12:57:41 Sep 18, 2013 PDT
[payment_status] => Completed
[charset] => windows-1252
[first_name] => Ashley
[mc_fee] => 1.90
[notify_version] => 3.7
[custom] =>
[payer_status] => unverified
[business] => me@gmail.com
[quantity] => 0
[verify_sign] => AFcWxV21C7fd0v3bYYYRCpSSRl31AJGmBkDrCSx-mp-dKf5.Wc6co3ra
[payer_email] => payer@gmail.co.uk
[memo] => SOMETHING
[txn_id] => 08B29244UF9480324
[payment_type] => instant
[last_name] => Ward
[receiver_email] => me@gmail.com
[payment_fee] =>
[receiver_id] => XSSCKHZJZRBDQ
[txn_type] => web_accept
[item_name] =>
[mc_currency] => GBP
[item_number] =>
[residence_country] => GB
[test_ipn] => 1
[receipt_id] => 2722-5250-1650-6726
[transaction_subject] =>
[payment_gross] =>
[ipn_track_id] => a503d9ea64b1e
)
the second looks like this:
stdClass Object
(
[transaction] => Array
(
[0] => stdClass Object
(
[invoiceId] => PVIFmMOZTm2xkjbs
[id_for_sender_txn] => 3M760109N8943254L
[receiver] => me@gmail.com
[is_primary_receiver] => false
[id] => 08B29244UF9480324
[status] => Completed
[paymentType] => GOODS
[status_for_sender_txn] => Completed
[pending_reason] => NONE
[amount] => GBP 50.00
)
)
[payment_request_date] => Wed Sep 18 12:55:36 PDT 2013
[return_url] => http://mysite.com/checkout/paypal-overlay-state/complete
[fees_payer] => EACHRECEIVER
[ipn_notification_url] => http://mysite.com/ipn
[sender_email] => buyer@gmail.co.uk
[verify_sign] => AFcWxV21C7fd0v3bYYYRCpSSRl31ASUp2KT0F-R3d2QqGIzfWpkS.gWz
[test_ipn] => 1
[cancel_url] => http://mysite.com/checkout/paypal-overlay-state/cancel
[pay_key] => AP-4V279017Y7501703X
[action_type] => PAY
[memo] => SOMETHING
[transaction_type] => Adaptive Payment PAY
[tracking_id] => PVIFmMOZTm2xkjbs
[status] => COMPLETED
[log_default_shipping_address_in_transaction] => false
[charset] => windows-1252
[notify_version] => UNVERSIONED
[reverse_all_parallel_payments_on_error] => false
)
How do I make sense of this data? Why are there 2 hits? and which is the
one I need to look out for?
Thanks!
After I make a simple web transaction on my site, my IPN handler recieves
not just the one expected 'completed' hit, but 2 hits. Each with different
data. The first looks like this:
stdClass Object
(
[mc_gross] => 50.00
[invoice] => PVIFmMOZTm2xkjbs
[protection_eligibility] => Ineligible
[payer_id] => NRQL7RKB54XWY
[tax] => 0.00
[payment_date] => 12:57:41 Sep 18, 2013 PDT
[payment_status] => Completed
[charset] => windows-1252
[first_name] => Ashley
[mc_fee] => 1.90
[notify_version] => 3.7
[custom] =>
[payer_status] => unverified
[business] => me@gmail.com
[quantity] => 0
[verify_sign] => AFcWxV21C7fd0v3bYYYRCpSSRl31AJGmBkDrCSx-mp-dKf5.Wc6co3ra
[payer_email] => payer@gmail.co.uk
[memo] => SOMETHING
[txn_id] => 08B29244UF9480324
[payment_type] => instant
[last_name] => Ward
[receiver_email] => me@gmail.com
[payment_fee] =>
[receiver_id] => XSSCKHZJZRBDQ
[txn_type] => web_accept
[item_name] =>
[mc_currency] => GBP
[item_number] =>
[residence_country] => GB
[test_ipn] => 1
[receipt_id] => 2722-5250-1650-6726
[transaction_subject] =>
[payment_gross] =>
[ipn_track_id] => a503d9ea64b1e
)
the second looks like this:
stdClass Object
(
[transaction] => Array
(
[0] => stdClass Object
(
[invoiceId] => PVIFmMOZTm2xkjbs
[id_for_sender_txn] => 3M760109N8943254L
[receiver] => me@gmail.com
[is_primary_receiver] => false
[id] => 08B29244UF9480324
[status] => Completed
[paymentType] => GOODS
[status_for_sender_txn] => Completed
[pending_reason] => NONE
[amount] => GBP 50.00
)
)
[payment_request_date] => Wed Sep 18 12:55:36 PDT 2013
[return_url] => http://mysite.com/checkout/paypal-overlay-state/complete
[fees_payer] => EACHRECEIVER
[ipn_notification_url] => http://mysite.com/ipn
[sender_email] => buyer@gmail.co.uk
[verify_sign] => AFcWxV21C7fd0v3bYYYRCpSSRl31ASUp2KT0F-R3d2QqGIzfWpkS.gWz
[test_ipn] => 1
[cancel_url] => http://mysite.com/checkout/paypal-overlay-state/cancel
[pay_key] => AP-4V279017Y7501703X
[action_type] => PAY
[memo] => SOMETHING
[transaction_type] => Adaptive Payment PAY
[tracking_id] => PVIFmMOZTm2xkjbs
[status] => COMPLETED
[log_default_shipping_address_in_transaction] => false
[charset] => windows-1252
[notify_version] => UNVERSIONED
[reverse_all_parallel_payments_on_error] => false
)
How do I make sense of this data? Why are there 2 hits? and which is the
one I need to look out for?
Thanks!
Jacoco Unit and Integration Tests coverage - individual and overall
Jacoco Unit and Integration Tests coverage - individual and overall
I have a project (ProjectA) which contains some unit tests and integration
tests.
Following is the structure.
ProjectA - src/java (java source code)
- test/java (Junit unit tests)
- test/resources (resources required for Junit Unit tests)
- src/java-test (Integration tests)
- conf (contains .xml files required for building/testing/compiling purposes)
I run the following commands -- All of them works but I have a doubt on
how the configurations that I have in build.gradle /
GRADLE_HOME/init.d/*.gradle files are affecting what I'm getting.
It seems like I'm missing something and not getting where I want what.
Commands:
- gradle clean build -- it works fine
- gradle clean build jacocoTestReport -- it works fine.
- gradle clean build integrationTest jacocoTestReport -- it works fine (if
I have a tomcat instance up and running in another putty window for the
same ProjectA).
After the 3rd bullet operation is complete, I see the extra folder "build"
and its subfolders (other than what's checked out from source/version
control) in my Jenkins jobs workspace.
i.e. under -- JenkinsWorkspace
/build
- classes (contains .class files for the following which are mentioned as
one of the sourceSets section)
---- integrationTest
---- main
---- test
- resources (this contains all the files .properties/.xml files which were
under "conf" folder in source control.
- reports (contains .xml/.html files for PMD/CheckStyle/Findbugs and Tests
results for either Unit or IT Tests but NOT both). ---- checkstyle
---- findbugs
---- pmd
---- jacoco
---- tests (Note: this is plural i.e. it's not "test" which is defined as
one entry in sourceSets)
- jacoco (This contains 2 .exec files i.e. test.exec and
integrationTest.exec both have different file size)
---- test.exec
---- integrationTest.exec
- jacocoHtml (This folder contains lots of folders (containing .html
files) and mainly "index.html" under it.
---- somexxxfolders
---- ---- somexxfolder's.html files
---- index.html
---- other etc files/folders
- test-results (This contains some .xml files BUT only for either Unit
tests or Integration tests - but not for both of the test types at a given
time).
i.e. if I run "gradle clean build", then you'll see Unit test related .xml
files and if I run "gradle clean build integrationTest", then Unit test
.xml files are overwritten and the .xml files I see are only related
to/generated by integrationTest task.
Following is one of the common gradle
(GRADLE_HOME/init.d/some.common.gradle file)
//
//Extra file can hold global Gradle settings so that these dont have to be
inserted in project
//specific build.gradle file.
//Filename: extraN.common<anyname>.gradle
allprojects {
apply plugin: 'java'
apply plugin: 'pmd'
apply plugin: 'findbugs'
apply plugin: 'checkstyle'
apply plugin: 'jacoco'
apply plugin: 'sonar-runner'
tasks.withType(Compile) {
options.debug = true
options.compilerArgs = ["-g"]
}
sourceSets {
main {
java {
srcDir 'src/java'
}
resources {
srcDir 'conf'
}
}
test {
java {
srcDir 'test/java'
}
resources {
srcDir 'test/resources'
srcDir 'conf'
}
}
integrationTest {
java {
srcDir 'src/java-test'
}
resources {
srcDir 'conf'
}
}
}
def sonarServerUrl = "dev.sandbox.server.com"
sonarRunner {
sonarProperties {
property "sonar.host.url", "http://$sonarServerUrl:9000"
property "sonar.jdbc.url",
"jdbc:h2:tcp://$sonarServerUrl:9092/sonar"
property "sonar.jdbc.driverClassName", "org.h2.Driver"
property "sonar.jdbc.username", "sonar"
property "sonar.jdbc.password", "sonar"
properties ["sonar.sources"] += sourceSets.main.allSource.srcDirs
//properties ["sonar.tests"] += sourceSets.test.java.srcDirs
properties ["sonar.tests"] +=
sourceSets.integrationTest.allSource.srcDirs
}
}
checkstyle {
configFile = new File(rootDir, "config/checkstyle.xml")
ignoreFailures = true
//sourceSets = [sourceSets.main, sourceSets.test,
sourceSets.integrationTest]
sourceSets = [sourceSets.main]
}
findbugs {
ignoreFailures = true
sourceSets = [sourceSets.main]
}
pmd {
ruleSets = ["basic", "braces", "design"]
ignoreFailures = true
}
jacoco {
toolVersion = "0.6.2.201302030002"
reportsDir = file("$buildDir/customJacocoReportDir")
}
task testReport(type: TestReport) {
destinationDir = file("$buildDir/reports/allTests")
}
test {
jacoco {
//destinationFile = file("$buildDir/jacoco/jacocoTest.exec")
destinationFile = file("$buildDir/jacoco/test.exec")
//classDumpFile = file("$buildDir/jacoco/classpathdumps")
classDumpFile = file("$buildDir/build/classes/test")
}
}
jacocoTestReport {
group = "Reporting"
description = "Generate Jacoco coverage reports after running
tests."
reports {
xml{
enabled true
destination "${buildDir}/reports/jacoco/jacoco.xml"
}
csv.enabled false
html{
enabled true
destination "${buildDir}/jacocoHtml"
}
}
additionalSourceDirs = files(sourceSets.main.allJava.srcDirs)
//additionalSourceDirs = files([sourceSets.main.allJava.srcDirs,
xxxx, 'xxxxyyyy' ])
}
}
build.gradle file looks like:
import com.tr.ids.gradle.CustomFileUtil
apply plugin: 'CustomSetup'
apply plugin: 'java'
apply plugin: 'customJarService'
apply plugin: 'customWarService'
sourceSets {
main {
java {
srcDir 'src/java'
}
}
test {
java {
srcDir 'test/java'
}
resources {
srcDir 'test/resources'
srcDir 'conf'
}
}
integrationTest {
java {
srcDir 'src/java-test'
}
}
}
// Read dependency lists from external files. Our custom plugin reads a
dep-xxx.txt file for compile/test/war related .jar file entries
// where each entry is like: groupid:artifactid:x.x.x
// and these artifact jars are available in Artifactory
List depListCompile = customFileUtil.readIntoList(
"$projectDir/dep-compile.txt" )
List depListTest = customFileUtil.readIntoList(
"$projectDir/dep-testArtifacts.txt" )
List depListWar = customFileUtil.readIntoList( "$projectDir/dep-war.txt" )
// Define dependencies
dependencies {
// Compilation
compile depListCompile
// Unit Tests
testCompile depListTest
// Integration tests
// Everything from compile and testCompile targets
integrationTestCompile configurations.compile
integrationTestCompile configurations.testCompile
// Output of compiling "main" files
integrationTestCompile sourceSets.main.output
// Additional dependencies from war and others
integrationTestCompile depListTest, depListWar
// All configuration files
integrationTestRuntime files( 'conf' )
}
task deployTomcat( type: Copy, dependsOn: [ jar,
compileIntegrationTestJava, warService ] ) {
from "$buildDir/customWar/${project.name}.war"
into "$projectDir/tomcat/webapps"
}
build {
dependsOn deployTomcat
}
task integrationTest( type: Test, dependsOn: cleanTest ) {
jacoco {
//destinationFile = file("$buildDir/jacoco/jacocoTest.exec")
destinationFile = file("$buildDir/jacoco/integrationTest.exec")
//classDumpFile = file("$buildDir/jacoco/classpathdumps")
classDumpFile = file("$buildDir/classes/integrationTest")
}
testClassesDir = sourceSets.integrationTest.output.classesDir
classpath = sourceSets.integrationTest.runtimeClasspath
}
apply plugin: 'eclipse'
eclipse.classpath {
// Define output directory so Eclipse does not accidentally clobber /bin
defaultOutputDir = file( 'out/classes' )
// Add integration test
plusConfigurations += configurations.integrationTestCompile
// Remove unnecessary files
file.whenMerged { classpath ->
classpath.entries.removeAll { entry -> ( entry.path.indexOf(
'/build/classes/main' ) > 0 ) }
classpath.entries.removeAll { entry -> ( entry.path.indexOf(
'/build/resources/main' ) > 0 ) }
}
}
My questions:
1) Why "gradle clean build integrationTest" -- which is working
successfully, is overwriting test results in build/reports/tests and
build/test-results folders.
2) It doesn't matter what name I give for .exec file under common gradle
file for test and in build.gradle for integrationTest task for jacoco, it
always create test.exec and integrationTest.exec file but the resultant
build/jacocoHtml folder index.html file doesn't show coverage / files
related to both Unit / Integration tests. To prove this, if I run "gradle
clean build integrationTest jacocoTestReport sonarRunner", I see the
workspace for the job, now contains, ".sonar" folder and
build/reports/sonar folder which contains another file called
"overall-xxx.exec" some file, but that file size is not close to the "sum"
of Unit test.exec and IT integrationTest.exec file size. Though its bigger
than test.exec file size by few bytes.
3) What configuration can I set to have overall coverage for both Unit and
IT tests i.e. overall...exec file gets good size (after running
sonarRunner task). During sonarRunner task, I do see SonarRunner task's
"jacocoSensor step" does see both UT and IT .exec files and the overall
.exec file as well automatically (a good feature from Sonar).
I have a project (ProjectA) which contains some unit tests and integration
tests.
Following is the structure.
ProjectA - src/java (java source code)
- test/java (Junit unit tests)
- test/resources (resources required for Junit Unit tests)
- src/java-test (Integration tests)
- conf (contains .xml files required for building/testing/compiling purposes)
I run the following commands -- All of them works but I have a doubt on
how the configurations that I have in build.gradle /
GRADLE_HOME/init.d/*.gradle files are affecting what I'm getting.
It seems like I'm missing something and not getting where I want what.
Commands:
- gradle clean build -- it works fine
- gradle clean build jacocoTestReport -- it works fine.
- gradle clean build integrationTest jacocoTestReport -- it works fine (if
I have a tomcat instance up and running in another putty window for the
same ProjectA).
After the 3rd bullet operation is complete, I see the extra folder "build"
and its subfolders (other than what's checked out from source/version
control) in my Jenkins jobs workspace.
i.e. under -- JenkinsWorkspace
/build
- classes (contains .class files for the following which are mentioned as
one of the sourceSets section)
---- integrationTest
---- main
---- test
- resources (this contains all the files .properties/.xml files which were
under "conf" folder in source control.
- reports (contains .xml/.html files for PMD/CheckStyle/Findbugs and Tests
results for either Unit or IT Tests but NOT both). ---- checkstyle
---- findbugs
---- pmd
---- jacoco
---- tests (Note: this is plural i.e. it's not "test" which is defined as
one entry in sourceSets)
- jacoco (This contains 2 .exec files i.e. test.exec and
integrationTest.exec both have different file size)
---- test.exec
---- integrationTest.exec
- jacocoHtml (This folder contains lots of folders (containing .html
files) and mainly "index.html" under it.
---- somexxxfolders
---- ---- somexxfolder's.html files
---- index.html
---- other etc files/folders
- test-results (This contains some .xml files BUT only for either Unit
tests or Integration tests - but not for both of the test types at a given
time).
i.e. if I run "gradle clean build", then you'll see Unit test related .xml
files and if I run "gradle clean build integrationTest", then Unit test
.xml files are overwritten and the .xml files I see are only related
to/generated by integrationTest task.
Following is one of the common gradle
(GRADLE_HOME/init.d/some.common.gradle file)
//
//Extra file can hold global Gradle settings so that these dont have to be
inserted in project
//specific build.gradle file.
//Filename: extraN.common<anyname>.gradle
allprojects {
apply plugin: 'java'
apply plugin: 'pmd'
apply plugin: 'findbugs'
apply plugin: 'checkstyle'
apply plugin: 'jacoco'
apply plugin: 'sonar-runner'
tasks.withType(Compile) {
options.debug = true
options.compilerArgs = ["-g"]
}
sourceSets {
main {
java {
srcDir 'src/java'
}
resources {
srcDir 'conf'
}
}
test {
java {
srcDir 'test/java'
}
resources {
srcDir 'test/resources'
srcDir 'conf'
}
}
integrationTest {
java {
srcDir 'src/java-test'
}
resources {
srcDir 'conf'
}
}
}
def sonarServerUrl = "dev.sandbox.server.com"
sonarRunner {
sonarProperties {
property "sonar.host.url", "http://$sonarServerUrl:9000"
property "sonar.jdbc.url",
"jdbc:h2:tcp://$sonarServerUrl:9092/sonar"
property "sonar.jdbc.driverClassName", "org.h2.Driver"
property "sonar.jdbc.username", "sonar"
property "sonar.jdbc.password", "sonar"
properties ["sonar.sources"] += sourceSets.main.allSource.srcDirs
//properties ["sonar.tests"] += sourceSets.test.java.srcDirs
properties ["sonar.tests"] +=
sourceSets.integrationTest.allSource.srcDirs
}
}
checkstyle {
configFile = new File(rootDir, "config/checkstyle.xml")
ignoreFailures = true
//sourceSets = [sourceSets.main, sourceSets.test,
sourceSets.integrationTest]
sourceSets = [sourceSets.main]
}
findbugs {
ignoreFailures = true
sourceSets = [sourceSets.main]
}
pmd {
ruleSets = ["basic", "braces", "design"]
ignoreFailures = true
}
jacoco {
toolVersion = "0.6.2.201302030002"
reportsDir = file("$buildDir/customJacocoReportDir")
}
task testReport(type: TestReport) {
destinationDir = file("$buildDir/reports/allTests")
}
test {
jacoco {
//destinationFile = file("$buildDir/jacoco/jacocoTest.exec")
destinationFile = file("$buildDir/jacoco/test.exec")
//classDumpFile = file("$buildDir/jacoco/classpathdumps")
classDumpFile = file("$buildDir/build/classes/test")
}
}
jacocoTestReport {
group = "Reporting"
description = "Generate Jacoco coverage reports after running
tests."
reports {
xml{
enabled true
destination "${buildDir}/reports/jacoco/jacoco.xml"
}
csv.enabled false
html{
enabled true
destination "${buildDir}/jacocoHtml"
}
}
additionalSourceDirs = files(sourceSets.main.allJava.srcDirs)
//additionalSourceDirs = files([sourceSets.main.allJava.srcDirs,
xxxx, 'xxxxyyyy' ])
}
}
build.gradle file looks like:
import com.tr.ids.gradle.CustomFileUtil
apply plugin: 'CustomSetup'
apply plugin: 'java'
apply plugin: 'customJarService'
apply plugin: 'customWarService'
sourceSets {
main {
java {
srcDir 'src/java'
}
}
test {
java {
srcDir 'test/java'
}
resources {
srcDir 'test/resources'
srcDir 'conf'
}
}
integrationTest {
java {
srcDir 'src/java-test'
}
}
}
// Read dependency lists from external files. Our custom plugin reads a
dep-xxx.txt file for compile/test/war related .jar file entries
// where each entry is like: groupid:artifactid:x.x.x
// and these artifact jars are available in Artifactory
List depListCompile = customFileUtil.readIntoList(
"$projectDir/dep-compile.txt" )
List depListTest = customFileUtil.readIntoList(
"$projectDir/dep-testArtifacts.txt" )
List depListWar = customFileUtil.readIntoList( "$projectDir/dep-war.txt" )
// Define dependencies
dependencies {
// Compilation
compile depListCompile
// Unit Tests
testCompile depListTest
// Integration tests
// Everything from compile and testCompile targets
integrationTestCompile configurations.compile
integrationTestCompile configurations.testCompile
// Output of compiling "main" files
integrationTestCompile sourceSets.main.output
// Additional dependencies from war and others
integrationTestCompile depListTest, depListWar
// All configuration files
integrationTestRuntime files( 'conf' )
}
task deployTomcat( type: Copy, dependsOn: [ jar,
compileIntegrationTestJava, warService ] ) {
from "$buildDir/customWar/${project.name}.war"
into "$projectDir/tomcat/webapps"
}
build {
dependsOn deployTomcat
}
task integrationTest( type: Test, dependsOn: cleanTest ) {
jacoco {
//destinationFile = file("$buildDir/jacoco/jacocoTest.exec")
destinationFile = file("$buildDir/jacoco/integrationTest.exec")
//classDumpFile = file("$buildDir/jacoco/classpathdumps")
classDumpFile = file("$buildDir/classes/integrationTest")
}
testClassesDir = sourceSets.integrationTest.output.classesDir
classpath = sourceSets.integrationTest.runtimeClasspath
}
apply plugin: 'eclipse'
eclipse.classpath {
// Define output directory so Eclipse does not accidentally clobber /bin
defaultOutputDir = file( 'out/classes' )
// Add integration test
plusConfigurations += configurations.integrationTestCompile
// Remove unnecessary files
file.whenMerged { classpath ->
classpath.entries.removeAll { entry -> ( entry.path.indexOf(
'/build/classes/main' ) > 0 ) }
classpath.entries.removeAll { entry -> ( entry.path.indexOf(
'/build/resources/main' ) > 0 ) }
}
}
My questions:
1) Why "gradle clean build integrationTest" -- which is working
successfully, is overwriting test results in build/reports/tests and
build/test-results folders.
2) It doesn't matter what name I give for .exec file under common gradle
file for test and in build.gradle for integrationTest task for jacoco, it
always create test.exec and integrationTest.exec file but the resultant
build/jacocoHtml folder index.html file doesn't show coverage / files
related to both Unit / Integration tests. To prove this, if I run "gradle
clean build integrationTest jacocoTestReport sonarRunner", I see the
workspace for the job, now contains, ".sonar" folder and
build/reports/sonar folder which contains another file called
"overall-xxx.exec" some file, but that file size is not close to the "sum"
of Unit test.exec and IT integrationTest.exec file size. Though its bigger
than test.exec file size by few bytes.
3) What configuration can I set to have overall coverage for both Unit and
IT tests i.e. overall...exec file gets good size (after running
sonarRunner task). During sonarRunner task, I do see SonarRunner task's
"jacocoSensor step" does see both UT and IT .exec files and the overall
.exec file as well automatically (a good feature from Sonar).
Translate CouchDB document update handler to erlang
Translate CouchDB document update handler to erlang
I have some problems to translate the Javascript Document Update Handler
to Erlang, because I can´t find any examples on google, CouchDB Markmail
or in the Mailing-Lists.
The following example is my Javascript update handler in the design
document of CouchDB:
function(doc,req) {
doc.description = req.form.description;
doc.owner = req.form.owner;
var message = "Update document successfull!";
return [doc, message];
}
but how to translate this update function into Erlang for CouchDB ? Maybe
something like:
fun({Doc}, {Req}) ->
FormValues = couch_util:get_values(<<"form">>, Req)
.......
end.
Thank you for any ideas!
Michael
I have some problems to translate the Javascript Document Update Handler
to Erlang, because I can´t find any examples on google, CouchDB Markmail
or in the Mailing-Lists.
The following example is my Javascript update handler in the design
document of CouchDB:
function(doc,req) {
doc.description = req.form.description;
doc.owner = req.form.owner;
var message = "Update document successfull!";
return [doc, message];
}
but how to translate this update function into Erlang for CouchDB ? Maybe
something like:
fun({Doc}, {Req}) ->
FormValues = couch_util:get_values(<<"form">>, Req)
.......
end.
Thank you for any ideas!
Michael
SOAP-ERROR: Parsing WSDL: Entity 'copy' not defined Magento
SOAP-ERROR: Parsing WSDL: Entity 'copy' not defined Magento
I try to use magento webservice but whene i try to call the webservice :
$proxy = new
SoapClient('http://mydomain.com/magento/index.php/api/v2_soap/?wsdl');
I get this error : Uncaught SoapFault exception: [WSDL] SOAP-ERROR:
Parsing WSDL: Couldn't load from
'http://mydomain.com/magento/index.php/api/v2_soap/?wsdl' : Entity 'copy'
not defined\n in /var/www/trunk/test.php:3\nStack trace:\n#0
/var/www/trunk/test.php(3),
So this Entity 'copy' not defined can you tell me why this exactly ,
should i add something in my server ?
I try to use magento webservice but whene i try to call the webservice :
$proxy = new
SoapClient('http://mydomain.com/magento/index.php/api/v2_soap/?wsdl');
I get this error : Uncaught SoapFault exception: [WSDL] SOAP-ERROR:
Parsing WSDL: Couldn't load from
'http://mydomain.com/magento/index.php/api/v2_soap/?wsdl' : Entity 'copy'
not defined\n in /var/www/trunk/test.php:3\nStack trace:\n#0
/var/www/trunk/test.php(3),
So this Entity 'copy' not defined can you tell me why this exactly ,
should i add something in my server ?
LINQ to XML - parent's attribute in where clause
LINQ to XML - parent's attribute in where clause
I'm having troubles with this where clause;
from item in
_documentRoot.Descendants("Level1").Descendants("Level2").Descendants("Level3")
where
_documentRoot.Descendants("Level1").Descendants("Level2").Attributes("id").First().Value
== 12345
I want a list of Level3 items from the Level2 element that has an id of
12345.
as always, many thanks
I'm having troubles with this where clause;
from item in
_documentRoot.Descendants("Level1").Descendants("Level2").Descendants("Level3")
where
_documentRoot.Descendants("Level1").Descendants("Level2").Attributes("id").First().Value
== 12345
I want a list of Level3 items from the Level2 element that has an id of
12345.
as always, many thanks
Tuesday, 17 September 2013
Why is perl known as 'the Swiss Army chainsaw of scripting languages'?
Why is perl known as 'the Swiss Army chainsaw of scripting languages'?
Why is Perl known as this? I read that it's because of it's flexibility
and power. But aren't some other languages have those features, too? Can
someone please elaborate this?
Why is Perl known as this? I read that it's because of it's flexibility
and power. But aren't some other languages have those features, too? Can
someone please elaborate this?
Is a search engine for a specific website a hadoop use-case?
Is a search engine for a specific website a hadoop use-case?
I am formalizing a plan to write a search engine for reddit, partly for
learning and partly for personal usage. I want to be able to search
through comments, users and subreddits.
On the data side of things, is Hadoop an appropriate technology for a
reddit search engine? Or is it better to use some sort of relational
database?
My main concerns:
-is there enough content to justify Hadoop? Statistics indicate that there
are thousands of posts on reddit a day and millions of users
-is the data structure of reddit well-defined enough to simply query a
database?
-the input for the search would just be a string, so I am not sure what my
database query would look like. But, I have an idea of what types of
algorithms I might choose to use if I used Hadoop
Any thoughts would be super helpful!
I am formalizing a plan to write a search engine for reddit, partly for
learning and partly for personal usage. I want to be able to search
through comments, users and subreddits.
On the data side of things, is Hadoop an appropriate technology for a
reddit search engine? Or is it better to use some sort of relational
database?
My main concerns:
-is there enough content to justify Hadoop? Statistics indicate that there
are thousands of posts on reddit a day and millions of users
-is the data structure of reddit well-defined enough to simply query a
database?
-the input for the search would just be a string, so I am not sure what my
database query would look like. But, I have an idea of what types of
algorithms I might choose to use if I used Hadoop
Any thoughts would be super helpful!
PHP Sanitising and escaping special characters
PHP Sanitising and escaping special characters
I'm new to PHP, and I've got a form where people can submit values to a
DB. Later those values will either be injected using JS, or be placed
straight inside an HTML document.
I'm using the following to sanitise my inputs:
function sanitise($str){
$string = htmlspecialchars($str);
$string = mysql_real_escape_string($str);
return $string;
}
The problem with this is that inside my DB, the inputs that have quotes
look like this: input's. This means if I insderted that value inside JS,
the quotation mark would screw everything up.
I tried doing this to avoid the quote:
function sanitise($str){
$string = htmlspecialchars($str);
$string = mysql_real_escape_string($str);
return addslashes($string);
}
This converts my DB entry to something that looks like this: input\'s.
This works within JS but if I was to inject that value directly inside
<div></div> then the backslash will still be present... I'm confused as to
what I'm doing wrong - how could I sanitize my inputs and at the same time
universally escape special characters for both HTML and JS?
I'm new to PHP, and I've got a form where people can submit values to a
DB. Later those values will either be injected using JS, or be placed
straight inside an HTML document.
I'm using the following to sanitise my inputs:
function sanitise($str){
$string = htmlspecialchars($str);
$string = mysql_real_escape_string($str);
return $string;
}
The problem with this is that inside my DB, the inputs that have quotes
look like this: input's. This means if I insderted that value inside JS,
the quotation mark would screw everything up.
I tried doing this to avoid the quote:
function sanitise($str){
$string = htmlspecialchars($str);
$string = mysql_real_escape_string($str);
return addslashes($string);
}
This converts my DB entry to something that looks like this: input\'s.
This works within JS but if I was to inject that value directly inside
<div></div> then the backslash will still be present... I'm confused as to
what I'm doing wrong - how could I sanitize my inputs and at the same time
universally escape special characters for both HTML and JS?
How can I reference an app that's not on the app store yet?
How can I reference an app that's not on the app store yet?
I have a free and pro version of my application. Inside of my app I have
an area that talks about the pro version and I would like to have a button
that links to it. Is it possible to do that before the app is on the app
store? I just want that button to link directly to the pro version on the
store.
I know it sound's like an obvious answer, no, but I don't know if there is
some special reference link that you can get prior to submitting an app on
the store.
I have a free and pro version of my application. Inside of my app I have
an area that talks about the pro version and I would like to have a button
that links to it. Is it possible to do that before the app is on the app
store? I just want that button to link directly to the pro version on the
store.
I know it sound's like an obvious answer, no, but I don't know if there is
some special reference link that you can get prior to submitting an app on
the store.
Sudo a bash script in profile.d
Sudo a bash script in profile.d
Using RedHat 6, the following script is located in
/etc/profile.d/my_custom_script.sh
function checkroot {
if [ "$(whoami)" != "root" ]; then
echo "Sorry, you are not root."
return
else
echo "You've got the powah!"
fi
}
as a normal user, and as root, the checkroot command runs as expected.
However, when running sudo checkroot either as a normal user with sudo
privileges, or as root itself, the system responds with sudo: checkroot:
command not found
The command runs successfully with sudo -i checkroot, however I don't want
to have to provide this option to sudo. What needs to change to make this
happen?
Using RedHat 6, the following script is located in
/etc/profile.d/my_custom_script.sh
function checkroot {
if [ "$(whoami)" != "root" ]; then
echo "Sorry, you are not root."
return
else
echo "You've got the powah!"
fi
}
as a normal user, and as root, the checkroot command runs as expected.
However, when running sudo checkroot either as a normal user with sudo
privileges, or as root itself, the system responds with sudo: checkroot:
command not found
The command runs successfully with sudo -i checkroot, however I don't want
to have to provide this option to sudo. What needs to change to make this
happen?
QuickBooks QBXML API Error: Failed to get an Interface ptr: Source: .\src\TimeActFilter.cpp
QuickBooks QBXML API Error: Failed to get an Interface ptr: Source:
.\src\TimeActFilter.cpp
My clients stumbled upon an issue when attempting to make a
straightforward TimeTracking query utilizing two tools: OpenSync and
QODBC. They both present the same error in the qbsdklog.txt files. Have
any QBXML developers experienced this / devised a remedy? Intuit general
support has told them the fault lies with the 3rd party developers however
I'm not sure how they came to such a conclusion.
QODBC:
20130913.095701 I 2588 QBSDKProcessRequest Application named
'FLEXquarters QODBC' starting requests (process 6920).
20130913.095701 I 2588 SpecVersion Current version of qbXML in use: 10.0
20130913.095701 I 2588 QBSDKMsgSetHandler QUERY: Time Tracking
20130913.095701 I 2588 TimeTrackingStorage::DoQuery Setting
iterator chunk size to 00001000
20130913.100310 E 2588 TimeTrackingStorage::DoQuery Failed to get
an Interface ptr: Source: .\src\TimeActFilter.cpp line #86
HRESULT=0x80004005
20130913.100310 I 2588 QBSDKMsgSetHandler Request 1 failed.
20130913.100310 I 2588 MsgSetHandler Finished.
OpenSync:
20130913.142336 I 2588 QBSDKProcessRequest Application named
'OpenSync' starting requests (process 700).
20130913.142336 I 2588 SpecVersion Current version of qbXML in use: 10.0
20130913.142336 I 2588 QBSDKMsgSetHandler QUERY: Time Tracking
20130913.142336 I 2588 TimeTrackingStorage::DoQuery Setting
iterator chunk size to 2147483647
20130913.142337 E 2588 TimeTrackingStorage::DoQuery Failed to get
an Interface ptr: Source: .\src\TimeActFilter.cpp line #86
HRESULT=0x80004005
20130913.142337 I 2588 QBSDKMsgSetHandler Request failed.
20130913.142337 I 2588 MsgSetHandler Finished.
Any information is appreciated
.\src\TimeActFilter.cpp
My clients stumbled upon an issue when attempting to make a
straightforward TimeTracking query utilizing two tools: OpenSync and
QODBC. They both present the same error in the qbsdklog.txt files. Have
any QBXML developers experienced this / devised a remedy? Intuit general
support has told them the fault lies with the 3rd party developers however
I'm not sure how they came to such a conclusion.
QODBC:
20130913.095701 I 2588 QBSDKProcessRequest Application named
'FLEXquarters QODBC' starting requests (process 6920).
20130913.095701 I 2588 SpecVersion Current version of qbXML in use: 10.0
20130913.095701 I 2588 QBSDKMsgSetHandler QUERY: Time Tracking
20130913.095701 I 2588 TimeTrackingStorage::DoQuery Setting
iterator chunk size to 00001000
20130913.100310 E 2588 TimeTrackingStorage::DoQuery Failed to get
an Interface ptr: Source: .\src\TimeActFilter.cpp line #86
HRESULT=0x80004005
20130913.100310 I 2588 QBSDKMsgSetHandler Request 1 failed.
20130913.100310 I 2588 MsgSetHandler Finished.
OpenSync:
20130913.142336 I 2588 QBSDKProcessRequest Application named
'OpenSync' starting requests (process 700).
20130913.142336 I 2588 SpecVersion Current version of qbXML in use: 10.0
20130913.142336 I 2588 QBSDKMsgSetHandler QUERY: Time Tracking
20130913.142336 I 2588 TimeTrackingStorage::DoQuery Setting
iterator chunk size to 2147483647
20130913.142337 E 2588 TimeTrackingStorage::DoQuery Failed to get
an Interface ptr: Source: .\src\TimeActFilter.cpp line #86
HRESULT=0x80004005
20130913.142337 I 2588 QBSDKMsgSetHandler Request failed.
20130913.142337 I 2588 MsgSetHandler Finished.
Any information is appreciated
Sunday, 15 September 2013
Replacing the inventory management system in NopCommerce with our own external system
Replacing the inventory management system in NopCommerce with our own
external system
My company is investigating using NopCommerce to develop a customized
website for selling items online. We already have a Windows based Point Of
Sale system. In an ideal world the NopCommerce system would be able to use
the same database that our POS system uses, then if something updates in
one, it will be updated in the other automatically. It would also mean we
don't need to manage two separate stock databases manually.
I want to know if it's technically possible to replace the inner workings
of the stock management system in NopCommerce and have it use our POS
database for the authoritative stock information? Or will that be a
considerable amount of work?
What would be the best way to approach that if it were possible? Via a
NopCommerce plugin? Via the NopCommerce API? If a change was made in one
system I'm thinking a notification could be sent to update the other stock
system and keep them both in sync. Or would you have to get your hands
dirty and create a new fork of the code?
external system
My company is investigating using NopCommerce to develop a customized
website for selling items online. We already have a Windows based Point Of
Sale system. In an ideal world the NopCommerce system would be able to use
the same database that our POS system uses, then if something updates in
one, it will be updated in the other automatically. It would also mean we
don't need to manage two separate stock databases manually.
I want to know if it's technically possible to replace the inner workings
of the stock management system in NopCommerce and have it use our POS
database for the authoritative stock information? Or will that be a
considerable amount of work?
What would be the best way to approach that if it were possible? Via a
NopCommerce plugin? Via the NopCommerce API? If a change was made in one
system I'm thinking a notification could be sent to update the other stock
system and keep them both in sync. Or would you have to get your hands
dirty and create a new fork of the code?
How to close a child dialog without closing its parent dialog in VB
How to close a child dialog without closing its parent dialog in VB
A OpenFileDialog is shown inside a form which is diaplayed by
ShowDialog(). Everytime the OpenFileDialog is closed, the parent form is
also closed.
Is there any way to avoid this??
Thanks!
A OpenFileDialog is shown inside a form which is diaplayed by
ShowDialog(). Everytime the OpenFileDialog is closed, the parent form is
also closed.
Is there any way to avoid this??
Thanks!
correct usage of carets inside negative lookahead expression in perl
correct usage of carets inside negative lookahead expression in perl
I am trying to match any word that is not completely composed of capitals
or lowercase letters, and I have the following regex written:
if ($line =~ /(?!^[A-Z][A-Z]+(\s*)$)(?!^[a-z][a-z]+(\s*)$)/) {
print $line;
}
The expression below should match words with all capital letters
(?!^[A-Z][A-Z]+(\s*)$)
and this should match words with all lowercase letters
(?!^[a-z][a-z]+(\s*)$)
I combine both and try to match this with the following words, ASDSFSDF,
asdfasdfasdf, and asdasdfFFFdsfs. I notice that it is matching everything.
only when i move the caret outside the brackets as in:
^(?![A-Z][A-Z]+(\s*)$)^(?![a-z][a-z]+(\s*)$)/)
do i see that its only maching the asdasdfFFFdsfs. can someone explain to
me why i need to move the operator outside of the negative lookahead
expression? i am new to regexp and i am confused.
Thanks.
I am trying to match any word that is not completely composed of capitals
or lowercase letters, and I have the following regex written:
if ($line =~ /(?!^[A-Z][A-Z]+(\s*)$)(?!^[a-z][a-z]+(\s*)$)/) {
print $line;
}
The expression below should match words with all capital letters
(?!^[A-Z][A-Z]+(\s*)$)
and this should match words with all lowercase letters
(?!^[a-z][a-z]+(\s*)$)
I combine both and try to match this with the following words, ASDSFSDF,
asdfasdfasdf, and asdasdfFFFdsfs. I notice that it is matching everything.
only when i move the caret outside the brackets as in:
^(?![A-Z][A-Z]+(\s*)$)^(?![a-z][a-z]+(\s*)$)/)
do i see that its only maching the asdasdfFFFdsfs. can someone explain to
me why i need to move the operator outside of the negative lookahead
expression? i am new to regexp and i am confused.
Thanks.
Resizing animation on SizeChanged event doesn't work as it should
Resizing animation on SizeChanged event doesn't work as it should
I want a resizing animation when stackpanel visibility is set to visible
state, but instead of that, I'm getting neverending flickering of border
containing stackpanel.I don't think I'm doing it wrong.
private void MyBorder_SizeChanged_1(object sender, SizeChangedEventArgs e)
{
if (!first)
{
DoubleAnimation anim = new DoubleAnimation();
anim.From = e.PreviousSize.Height;
anim.To = e.NewSize.Height;
anim.Duration = new Duration(TimeSpan.FromSeconds(1));
Storyboard.SetTarget(anim, MyBorder);
Storyboard.SetTargetProperty(anim, new
PropertyPath(Border.HeightProperty));
Storyboard st = new Storyboard();
st.Children.Add(anim);
st.Begin();
}
first = false;
}
private void MyBorder_Tap_1(object sender, GestureEventArgs e)
{
if (MyPanel.Visibility == Visibility.Collapsed)
MyPanel.Visibility = Visibility.Visible;
else
MyPanel.Visibility = Visibility.Collapsed;
}
I want a resizing animation when stackpanel visibility is set to visible
state, but instead of that, I'm getting neverending flickering of border
containing stackpanel.I don't think I'm doing it wrong.
private void MyBorder_SizeChanged_1(object sender, SizeChangedEventArgs e)
{
if (!first)
{
DoubleAnimation anim = new DoubleAnimation();
anim.From = e.PreviousSize.Height;
anim.To = e.NewSize.Height;
anim.Duration = new Duration(TimeSpan.FromSeconds(1));
Storyboard.SetTarget(anim, MyBorder);
Storyboard.SetTargetProperty(anim, new
PropertyPath(Border.HeightProperty));
Storyboard st = new Storyboard();
st.Children.Add(anim);
st.Begin();
}
first = false;
}
private void MyBorder_Tap_1(object sender, GestureEventArgs e)
{
if (MyPanel.Visibility == Visibility.Collapsed)
MyPanel.Visibility = Visibility.Visible;
else
MyPanel.Visibility = Visibility.Collapsed;
}
Migrating a TFS repository to git
Migrating a TFS repository to git
I'm going to happily switch from TFS to git. I can't afford losing the
check-in history or my branches. What is the least painful way to convert
my TFS repository into a git repository by turning each check-in to a git
commit and keeping all the branches?
I'm going to happily switch from TFS to git. I can't afford losing the
check-in history or my branches. What is the least painful way to convert
my TFS repository into a git repository by turning each check-in to a git
commit and keeping all the branches?
C#.NET: How to create/use Configuration File for Infrastructure Layer (Class Library) Project in Domain-Driven Model
C#.NET: How to create/use Configuration File for Infrastructure Layer
(Class Library) Project in Domain-Driven Model
In my Domain Driven Layers, Infrastructure Layer Project is class library
Project which needs to use a configuration file for not only connecting to
database but also to create Repositories and Entities. However, the links
(mentioned at the end of post state that class library project cannot have
a configuration file (I think, class library cannot have a app.config).
My Question is that if not then how to create and use a configuration file
for my Infrastructure Layer (Class Library) Project ? under which Project
and what should be the naming convention ?
DETAIL:
I am following a book on Domain Driven Design in C#.NET. In this model
(Visual Studio Solution), there four layers (each project in Visual Studio
as layer) named below:
1) Presentation Layer Project (WPF, not .NET class library) 2) Application
Layer Project (.NET class Library) 3) Model Layer Project (class Library)
4) Infrastructure Layer (.NET class Library)
Infrastructure Layer Project (as .NET clas Library) needs to use a
configuration file, in order to:
A) Create Repository (using Repository Factory), B) Create Entities (using
EntityFactoryBuilder), C) Connecting to database.
For this i created configuration file under the project
"ProjectName.Infrastructure" as "ProjectName.Infrastructure.config" by
setting its property (using Visual Studio) "Copy to Output Window" as
"CopyAlways".
However, according to some posts (links at the end):
"a class library project (like my "Infrastructure Layer Project") cannot
have a configuration file (application configuration file OR app.config
file) instead a calling application should supply/provide configuration
file and that class library use this provided file".
Links ( That i researched on):
How access a custom config from my class library application?
and
http://msdn.microsoft.com/en-us/library/ms229689.aspx
(Class Library) Project in Domain-Driven Model
In my Domain Driven Layers, Infrastructure Layer Project is class library
Project which needs to use a configuration file for not only connecting to
database but also to create Repositories and Entities. However, the links
(mentioned at the end of post state that class library project cannot have
a configuration file (I think, class library cannot have a app.config).
My Question is that if not then how to create and use a configuration file
for my Infrastructure Layer (Class Library) Project ? under which Project
and what should be the naming convention ?
DETAIL:
I am following a book on Domain Driven Design in C#.NET. In this model
(Visual Studio Solution), there four layers (each project in Visual Studio
as layer) named below:
1) Presentation Layer Project (WPF, not .NET class library) 2) Application
Layer Project (.NET class Library) 3) Model Layer Project (class Library)
4) Infrastructure Layer (.NET class Library)
Infrastructure Layer Project (as .NET clas Library) needs to use a
configuration file, in order to:
A) Create Repository (using Repository Factory), B) Create Entities (using
EntityFactoryBuilder), C) Connecting to database.
For this i created configuration file under the project
"ProjectName.Infrastructure" as "ProjectName.Infrastructure.config" by
setting its property (using Visual Studio) "Copy to Output Window" as
"CopyAlways".
However, according to some posts (links at the end):
"a class library project (like my "Infrastructure Layer Project") cannot
have a configuration file (application configuration file OR app.config
file) instead a calling application should supply/provide configuration
file and that class library use this provided file".
Links ( That i researched on):
How access a custom config from my class library application?
and
http://msdn.microsoft.com/en-us/library/ms229689.aspx
ReferenceError: event is not defined in Firefox
ReferenceError: event is not defined in Firefox
I am using this function:
$("#tooltip").animate({ left: event.clientX, top: event.clientY });
Its working on Chrome and IE but in Firefox I get this error:
ReferenceError: event is not defined $("#tooltip").animate({ left:
event.clientX, top: event.clientY });
How can i solve this?
I am using this function:
$("#tooltip").animate({ left: event.clientX, top: event.clientY });
Its working on Chrome and IE but in Firefox I get this error:
ReferenceError: event is not defined $("#tooltip").animate({ left:
event.clientX, top: event.clientY });
How can i solve this?
Saturday, 14 September 2013
How to read a big binary file and split its content by some marker
How to read a big binary file and split its content by some marker
In Python, reading a big text file line-by-line is simple:
for line in open('somefile', 'r'): ...
But how to read a binary file and 'split' (by generator) its content by
some given marker, not the newline '\n'?
I want something like that:
content = open('somefile', 'r').read()
result = content.split('some_marker')
but, of course, memory-efficient (the file is around 70GB). Of course, we
can't read the file by every byte (it'll be too slow because of the HDD
nature).
The 'chunks' length (the data between those markers) might differ,
theoretically from 1 byte to megabytes.
So, to give an example to sum up, the data looks like that (digits mean
bytes here, the data is in a binary format):
12345223-MARKER-3492-MARKER-34834983428623762374632784-MARKER-888-MARKER-...
Is there any simple way to do that (not implementing reading in chunks,
splitting the chunks, remembering tails etc.)?
In Python, reading a big text file line-by-line is simple:
for line in open('somefile', 'r'): ...
But how to read a binary file and 'split' (by generator) its content by
some given marker, not the newline '\n'?
I want something like that:
content = open('somefile', 'r').read()
result = content.split('some_marker')
but, of course, memory-efficient (the file is around 70GB). Of course, we
can't read the file by every byte (it'll be too slow because of the HDD
nature).
The 'chunks' length (the data between those markers) might differ,
theoretically from 1 byte to megabytes.
So, to give an example to sum up, the data looks like that (digits mean
bytes here, the data is in a binary format):
12345223-MARKER-3492-MARKER-34834983428623762374632784-MARKER-888-MARKER-...
Is there any simple way to do that (not implementing reading in chunks,
splitting the chunks, remembering tails etc.)?
Sublime Snippet Not Working
Sublime Snippet Not Working
I've just started using Sublime 3 as my IDE and it's great!!! I was just
fiddling around and trying to make some snippets but I can't get any of
them to work. Can anyone see what's wrong with this? I read their docs and
thumbed some examples off the web but they don't work either. I've got it
in my /sublime text 3/packages/user folder and it's named using convention
myTest.sublime.snippet.
I dropped it in codepen http://codepen.io/anon/pen/KgIDo if anyone has any
ideas? Thanks
I've just started using Sublime 3 as my IDE and it's great!!! I was just
fiddling around and trying to make some snippets but I can't get any of
them to work. Can anyone see what's wrong with this? I read their docs and
thumbed some examples off the web but they don't work either. I've got it
in my /sublime text 3/packages/user folder and it's named using convention
myTest.sublime.snippet.
I dropped it in codepen http://codepen.io/anon/pen/KgIDo if anyone has any
ideas? Thanks
How to enter a formula into a cell using VBA?
How to enter a formula into a cell using VBA?
I am trying to enter a formula into a cell which contains variable called
var1a? The code that I have is:
Worksheets("EmployeeCosts").Range("B" & var1a).Formula = ""SUM(H5:H""&
var1a)
But it enters into an excel worksheet with a mistake.
I am trying to enter a formula into a cell which contains variable called
var1a? The code that I have is:
Worksheets("EmployeeCosts").Range("B" & var1a).Formula = ""SUM(H5:H""&
var1a)
But it enters into an excel worksheet with a mistake.
Why is there a fixed page width?
Why is there a fixed page width?
Here is the full html of my test page
It's essentially the below. When I browse to it on my android phone (v4.1)
it has a large width and makes it extremely irritating to read because i
have to scroll to the right and left. The font is also tiny. The
resolution of the phone is 720x1280. I'm using the default browser. On
firefox it reads fine (no scrolling).
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Test</title>
</head>
<body>
<p>lots of Lorem ipsum dolor sit amet</p>
</body>
</html>
Here is the full html of my test page
It's essentially the below. When I browse to it on my android phone (v4.1)
it has a large width and makes it extremely irritating to read because i
have to scroll to the right and left. The font is also tiny. The
resolution of the phone is 720x1280. I'm using the default browser. On
firefox it reads fine (no scrolling).
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Test</title>
</head>
<body>
<p>lots of Lorem ipsum dolor sit amet</p>
</body>
</html>
JAVA ANDROID: JSON values from php page not showing
JAVA ANDROID: JSON values from php page not showing
Although this is just a rough sketch..i just want to see if it will
work..Anytime i run the program it doesn't crash and it doesn't show
anything. The error showing on the logcat is JSON result form the php
page..i don't know why the Postexecute() method is not working...
this is the error
09-14 18:21:07.079: E/JSON(21310):
{"tag":"getTopic","success":1,"error":0,"data":[{"title":"Facebook finally
rolls GRAPH Search","tid":"81","time":"2013-06-22
10:05:18"},{"title":"What is Ubuntu for
Android?","tid":"69","time":"2013-06-22 10:18:00"},{"title":"Android and
Windows on same device(samsung)","tid":"98","time":"2013-06-22
10:18:35"},{"title":"\"Tweet\" has been verified as a real word in
English","tid":"67","time":"2013-06-22 10:27:33"},{"title":"Instagram now
has video recording","tid":"97","time":"2013-06-22 10:27:45"},{"title":"An
Open Letter to DBanj","tid":"70","time":"2013-06-22
10:31:41"},{"title":"MTN call rate wahala","tid":"84","time":"2013-06-22
10:32:44"},{"title":"Types of friends essential for
women","tid":"33","time":"2013-06-22 10:45:41"},{"title":"Not to be loved
in return","tid":"106","time":"2013-06-22 18:15:06"},{"title":"I am in
love with you","tid":"107","time":"2013-06-22 18:28:56"},{"title":"I hate
it!!!","tid":"115","time":"2013-06-23 19:06:26"},{"title":"Spoils of
love","tid":"116","time":"2013-06-23 19:14:43"},{"title":"An Apology
Letter from Men To Women","tid":"117","time":"2013-06-26
12:43:02"},{"title":"Ramadan Starts tomorrow (in sha Allah)
!!!","tid":"120","time":"2013-07-09 15:06:09"},{"title":"Preventing
infidelity on your marriage","tid":"29","time":"2013-07-14
12:06:31"},{"title":"How to have a healthy
relationship","tid":"121","time":"2013-08-02 17:17:32"},{"title":"ASUU
strike not ending anytime soon","tid":"124","time":"2013-08-27
12:56:26"},{"title":"Google Announces Android 4.4
KitKat","tid":"126","time":"2013-09-06 20:51:32"},{"title":"Apple Launches
iPhone 5s and iPhone 5c","tid":"127","time":"2013-09-11 15:29:40"}]}
and this is the class
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.nairation.library.JSONParser;
import com.nairation.library.UserFunctions;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class Topic_page extends Activity implements OnItemClickListener{
public static final String TOPIC_DURATION = "relative";
public static final String TOPIC_TITLE = "title";
public static final String TOPIC_PREVIEW = "Testing out";
public static final String TOPIC_ID = null;
public static final Object TOPIC_THUMB_URL = null;
ListView list;
TopicListAdapter adapter;
UserFunctions userf;
JSONParser jpa;
ArrayList<HashMap<String, String>> topicList = new
ArrayList<HashMap<String,String>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.topic_page);
list = (ListView) findViewById(R.id.topic_list);
adapter = new TopicListAdapter(this, topicList);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
try{
new ServiceSync().execute("mash");
}catch(Exception e){
String message = e.getMessage();
}
}
private class ServiceSync extends AsyncTask<String, JSONObject,
JSONObject>{
@Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
String uname = params[0];
userf = new UserFunctions();
JSONObject jp = userf.getTopic(uname);
return jp;
}
@Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
//super.onPostExecute(result);
try {
JSONArray obj = result.getJSONArray("data");
for (int i = 0; i < result.length(); i++) {
JSONObject data = obj.getJSONObject(i);
HashMap<String, String> map = new HashMap<String,
String>();
String title = data.getString(TOPIC_TITLE);
String time = data.getString("time");
String tid = data.getString("tid");
map.put(TOPIC_TITLE, title);
map.put("Date", time);
topicList.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Problem with
loading the feeds", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
// TODO Auto-generated method stub
}
}
So what could be the problem the JSON result is not being processed..
Although this is just a rough sketch..i just want to see if it will
work..Anytime i run the program it doesn't crash and it doesn't show
anything. The error showing on the logcat is JSON result form the php
page..i don't know why the Postexecute() method is not working...
this is the error
09-14 18:21:07.079: E/JSON(21310):
{"tag":"getTopic","success":1,"error":0,"data":[{"title":"Facebook finally
rolls GRAPH Search","tid":"81","time":"2013-06-22
10:05:18"},{"title":"What is Ubuntu for
Android?","tid":"69","time":"2013-06-22 10:18:00"},{"title":"Android and
Windows on same device(samsung)","tid":"98","time":"2013-06-22
10:18:35"},{"title":"\"Tweet\" has been verified as a real word in
English","tid":"67","time":"2013-06-22 10:27:33"},{"title":"Instagram now
has video recording","tid":"97","time":"2013-06-22 10:27:45"},{"title":"An
Open Letter to DBanj","tid":"70","time":"2013-06-22
10:31:41"},{"title":"MTN call rate wahala","tid":"84","time":"2013-06-22
10:32:44"},{"title":"Types of friends essential for
women","tid":"33","time":"2013-06-22 10:45:41"},{"title":"Not to be loved
in return","tid":"106","time":"2013-06-22 18:15:06"},{"title":"I am in
love with you","tid":"107","time":"2013-06-22 18:28:56"},{"title":"I hate
it!!!","tid":"115","time":"2013-06-23 19:06:26"},{"title":"Spoils of
love","tid":"116","time":"2013-06-23 19:14:43"},{"title":"An Apology
Letter from Men To Women","tid":"117","time":"2013-06-26
12:43:02"},{"title":"Ramadan Starts tomorrow (in sha Allah)
!!!","tid":"120","time":"2013-07-09 15:06:09"},{"title":"Preventing
infidelity on your marriage","tid":"29","time":"2013-07-14
12:06:31"},{"title":"How to have a healthy
relationship","tid":"121","time":"2013-08-02 17:17:32"},{"title":"ASUU
strike not ending anytime soon","tid":"124","time":"2013-08-27
12:56:26"},{"title":"Google Announces Android 4.4
KitKat","tid":"126","time":"2013-09-06 20:51:32"},{"title":"Apple Launches
iPhone 5s and iPhone 5c","tid":"127","time":"2013-09-11 15:29:40"}]}
and this is the class
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.nairation.library.JSONParser;
import com.nairation.library.UserFunctions;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class Topic_page extends Activity implements OnItemClickListener{
public static final String TOPIC_DURATION = "relative";
public static final String TOPIC_TITLE = "title";
public static final String TOPIC_PREVIEW = "Testing out";
public static final String TOPIC_ID = null;
public static final Object TOPIC_THUMB_URL = null;
ListView list;
TopicListAdapter adapter;
UserFunctions userf;
JSONParser jpa;
ArrayList<HashMap<String, String>> topicList = new
ArrayList<HashMap<String,String>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.topic_page);
list = (ListView) findViewById(R.id.topic_list);
adapter = new TopicListAdapter(this, topicList);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
try{
new ServiceSync().execute("mash");
}catch(Exception e){
String message = e.getMessage();
}
}
private class ServiceSync extends AsyncTask<String, JSONObject,
JSONObject>{
@Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
String uname = params[0];
userf = new UserFunctions();
JSONObject jp = userf.getTopic(uname);
return jp;
}
@Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
//super.onPostExecute(result);
try {
JSONArray obj = result.getJSONArray("data");
for (int i = 0; i < result.length(); i++) {
JSONObject data = obj.getJSONObject(i);
HashMap<String, String> map = new HashMap<String,
String>();
String title = data.getString(TOPIC_TITLE);
String time = data.getString("time");
String tid = data.getString("tid");
map.put(TOPIC_TITLE, title);
map.put("Date", time);
topicList.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Problem with
loading the feeds", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
// TODO Auto-generated method stub
}
}
So what could be the problem the JSON result is not being processed..
How to get related to db.Model entity from datastore - what API allows it?
How to get related to db.Model entity from datastore - what API allows it?
I want to read related to model entity. What API I should use?
For example:
class DeleteMe(db.Model):
x = db.FloatProperty()
DeleteMe(key_name = '1').put()
How to read raw entity from datastore for key_name = '1'?
I want to read related to model entity. What API I should use?
For example:
class DeleteMe(db.Model):
x = db.FloatProperty()
DeleteMe(key_name = '1').put()
How to read raw entity from datastore for key_name = '1'?
Use do_upload twice
Use do_upload twice
i would like to upload 2 files to different path but at the first path
it's work properly but when it use next path its error with "The filetype
you are attempting to upload is not allowed."
Model
$this->load->model('blogmaintain_helper');
$data['cover_path'] = $this->blogmaintain_helper->upload_cover();
$data['file_path'] = $this->blogmaintain_helper->upload_file();
Controller
function upload_cover(){
$config_cover['upload_path'] =
'ftp://[server_path]/public_html/img/blog/';
$config_cover['allowed_types'] = 'gif|jpg|png|tif';
get_instance()->load->library('upload', $config_cover);
if($this->upload->do_upload('myFile'))
{
echo "Cover upload success";
return true;
}
else
{
echo $this->upload->display_errors();
}
}
function upload_file(){
$config_file['upload_path'] =
'ftp://[server_path]/public_html/document/blog/';
//$config['upload_path'] = 'document/blog/';
$config_file['allowed_types'] = 'doc|docx|pdf|txt|xls|xlsx|ppt|pptx';
get_instance()->load->library('upload', $config_file);
if($this->upload->do_upload('myDoc'))
{
echo "File upload success";
}
else
{
echo $this->upload->display_errors();
}
}
i can upload myFile to img/blog but when it perform 'upload_file' it's
error with "The filetype you are attempting to upload is not allowed."
PS* myDoc is "test.txt" and myFile is "pic.jpg"
i would like to upload 2 files to different path but at the first path
it's work properly but when it use next path its error with "The filetype
you are attempting to upload is not allowed."
Model
$this->load->model('blogmaintain_helper');
$data['cover_path'] = $this->blogmaintain_helper->upload_cover();
$data['file_path'] = $this->blogmaintain_helper->upload_file();
Controller
function upload_cover(){
$config_cover['upload_path'] =
'ftp://[server_path]/public_html/img/blog/';
$config_cover['allowed_types'] = 'gif|jpg|png|tif';
get_instance()->load->library('upload', $config_cover);
if($this->upload->do_upload('myFile'))
{
echo "Cover upload success";
return true;
}
else
{
echo $this->upload->display_errors();
}
}
function upload_file(){
$config_file['upload_path'] =
'ftp://[server_path]/public_html/document/blog/';
//$config['upload_path'] = 'document/blog/';
$config_file['allowed_types'] = 'doc|docx|pdf|txt|xls|xlsx|ppt|pptx';
get_instance()->load->library('upload', $config_file);
if($this->upload->do_upload('myDoc'))
{
echo "File upload success";
}
else
{
echo $this->upload->display_errors();
}
}
i can upload myFile to img/blog but when it perform 'upload_file' it's
error with "The filetype you are attempting to upload is not allowed."
PS* myDoc is "test.txt" and myFile is "pic.jpg"
Issue with math activity in android
Issue with math activity in android
Can any one tell me how to write this type of code in eclipse activity.
basically i want to square root the samv and samvi variables. i am getting
syntax error.
int ki, l,;
int samv = (tdrum / k) / l;
int samvi = (tdrum / ki) / l;
int samv2 = (Math.sqrt(samv);
int samv2i = (Math.sqrt(samvi);
Can any one tell me how to write this type of code in eclipse activity.
basically i want to square root the samv and samvi variables. i am getting
syntax error.
int ki, l,;
int samv = (tdrum / k) / l;
int samvi = (tdrum / ki) / l;
int samv2 = (Math.sqrt(samv);
int samv2i = (Math.sqrt(samvi);
Friday, 13 September 2013
using @model IQuerable, and strong type in View
using @model IQuerable, and strong type in View
How can I using IQueryable for the grid and keep strong type in view?
Here is the view coding:
Index.cshtml
@model IQueryable<MVCApplication.Models.Product>
@(Html.Grid<model>.()
.AutoGenerateLayouts(false)
.Columns ( column =>
{
column.For( e => e.ProductID)
}
)
@Html.DisplayNameFor(model => model.ProductID)
If I used "@model IQueryable", I losed the strong type view.
Thanks Wilson
How can I using IQueryable for the grid and keep strong type in view?
Here is the view coding:
Index.cshtml
@model IQueryable<MVCApplication.Models.Product>
@(Html.Grid<model>.()
.AutoGenerateLayouts(false)
.Columns ( column =>
{
column.For( e => e.ProductID)
}
)
@Html.DisplayNameFor(model => model.ProductID)
If I used "@model IQueryable", I losed the strong type view.
Thanks Wilson
How to add comments to a .docx XML
How to add comments to a .docx XML
At work, we have a word document that we have to edit all the time to pass
on to another team, to tell them how to perform some tasks. Since I don't
like mindlessly filling out data, and I always look for ways to simplify
the tasks I have to do, I decided I would automate this process. After
considering a few methods (such as generating a word document from scratch
or editing an existing document), I decided to edit the document in-place.
I have inserted special tags into the document (specifically, they take
the form [SOME_NAME_HERE]), and I will then parse the document for those
special tags and replace them with the value I actually need. I then
extract the .docx to a folder with all of the XML documents inside of it,
and parse the document.xml file, replacing the values.
During this process, depending on what is actually needed, there are
sections of the document that will have to be removed from it. So my first
thought was to add comments to the document.xml file. For example:
<!-- INITIAL BUILD ONLY -->
<w:p w:rsidR="00202319" w:rsidRPr="00D00FF5"
w:rsidRDefault="00202319" w:rsidP="00AC0192">
<w:r w:rsidR="00E548A2" w:rsidRPr="00D00FF5">
<w:rPr>
<w:rStyle w:val="emcfontstrong"/>
</w:rPr>
<w:t>Some text here</w:t>
</w:r>
</w:p>
<!-- END INITIAL BUILD ONLY -->
Then, when I go to generate the output word document, I would simply
remove all of the sections that were "INITIAL BUILD ONLY" (unless, of
course, it is the initial build).
However, the issue I am running in to is that when you convert the
document back to a Word document, open in Word and save it, it will
"cleanup" the document, and remove all of the comments I've added to it.
So, my question is, is there any way to preserve the comments in the
document, or is there any special tags I could add to the XML that would
not be visible during standard view/edit of the document, but would not be
removed by Word upon a save?
At work, we have a word document that we have to edit all the time to pass
on to another team, to tell them how to perform some tasks. Since I don't
like mindlessly filling out data, and I always look for ways to simplify
the tasks I have to do, I decided I would automate this process. After
considering a few methods (such as generating a word document from scratch
or editing an existing document), I decided to edit the document in-place.
I have inserted special tags into the document (specifically, they take
the form [SOME_NAME_HERE]), and I will then parse the document for those
special tags and replace them with the value I actually need. I then
extract the .docx to a folder with all of the XML documents inside of it,
and parse the document.xml file, replacing the values.
During this process, depending on what is actually needed, there are
sections of the document that will have to be removed from it. So my first
thought was to add comments to the document.xml file. For example:
<!-- INITIAL BUILD ONLY -->
<w:p w:rsidR="00202319" w:rsidRPr="00D00FF5"
w:rsidRDefault="00202319" w:rsidP="00AC0192">
<w:r w:rsidR="00E548A2" w:rsidRPr="00D00FF5">
<w:rPr>
<w:rStyle w:val="emcfontstrong"/>
</w:rPr>
<w:t>Some text here</w:t>
</w:r>
</w:p>
<!-- END INITIAL BUILD ONLY -->
Then, when I go to generate the output word document, I would simply
remove all of the sections that were "INITIAL BUILD ONLY" (unless, of
course, it is the initial build).
However, the issue I am running in to is that when you convert the
document back to a Word document, open in Word and save it, it will
"cleanup" the document, and remove all of the comments I've added to it.
So, my question is, is there any way to preserve the comments in the
document, or is there any special tags I could add to the XML that would
not be visible during standard view/edit of the document, but would not be
removed by Word upon a save?
IPv4 mapped IPv6 addresses
IPv4 mapped IPv6 addresses
I'm trying to make a IP version-agnostic client/server. I've been playing
around with this in C++ and came up with something that works using the
IN6ADDR_SETV4MAPPED macro (as Microsoft so kindly recommends). I followed
the code sample here to accomplish this; my code that converts the address
is no different from the example and everything works. I can connect to
the server from the client by typing in both an IPv4 and IPv6 address
(application does the mapping accordingly).
Now I'm looking for a solution in C# to upgrade a simple chat server I
made and I've been unable to find any resources on how to use mapped
addresses. I haven't found a function that provides the equivalent of
IN6ADDR_SETV4MAPPED or any other facility in .net. My question is: how can
I go about using a IPv4-mapped IPv6 address in C# (client-side)?
What I've tried:
Prepend string "::ffff:" to dotted IPv4 notation, call Socket.Connect
using this address. Resulting address string looks like ::ffff:127.0.0.1.
Prepend string "::ffff:". Convert each octect from dotted format into hex
and separate with colons, call Socket.Connect. Resulting address string
looks like ::ffff:7f:0:0:1.
Neither of these approaches have worked so far.
Code snippet for server:
this.m_endPoint = new IPEndPoint(IPAddress.IPv6Any, 1337);
this.m_server.SetSocketOption(SocketOptionLevel.IPv6,
SocketOptionName.IPv6Only, 0);
this.m_server.Bind(this.m_endPoint);
this.m_server.Listen(10);
Code snippet for client:
public ClientNet(string host, short port)
{
IPAddress ip;
if(IPAddress.TryParse(host, out ip))
{
string[] octs = host.Split(new char[] { '.' });
host = "::ffff:";
for(int i = 0; i < octs.Length; ++i)
{
host += string.Format("{0:x}", int.Parse(octs[i]));
if(i + 1 != octs.Length)
{
host += ":";
}
}
}
else
{
throw new ClientCreateException("[in ClientNet.Constructor] Unable
to create client; use IPv4 address");
}
Socket client = new Socket(AddressFamily.InterNetworkV6,
SocketType.Stream, ProtocolType.Tcp);
client.Connect(host, port);
. . . //More initialization
}
I'm trying to make a IP version-agnostic client/server. I've been playing
around with this in C++ and came up with something that works using the
IN6ADDR_SETV4MAPPED macro (as Microsoft so kindly recommends). I followed
the code sample here to accomplish this; my code that converts the address
is no different from the example and everything works. I can connect to
the server from the client by typing in both an IPv4 and IPv6 address
(application does the mapping accordingly).
Now I'm looking for a solution in C# to upgrade a simple chat server I
made and I've been unable to find any resources on how to use mapped
addresses. I haven't found a function that provides the equivalent of
IN6ADDR_SETV4MAPPED or any other facility in .net. My question is: how can
I go about using a IPv4-mapped IPv6 address in C# (client-side)?
What I've tried:
Prepend string "::ffff:" to dotted IPv4 notation, call Socket.Connect
using this address. Resulting address string looks like ::ffff:127.0.0.1.
Prepend string "::ffff:". Convert each octect from dotted format into hex
and separate with colons, call Socket.Connect. Resulting address string
looks like ::ffff:7f:0:0:1.
Neither of these approaches have worked so far.
Code snippet for server:
this.m_endPoint = new IPEndPoint(IPAddress.IPv6Any, 1337);
this.m_server.SetSocketOption(SocketOptionLevel.IPv6,
SocketOptionName.IPv6Only, 0);
this.m_server.Bind(this.m_endPoint);
this.m_server.Listen(10);
Code snippet for client:
public ClientNet(string host, short port)
{
IPAddress ip;
if(IPAddress.TryParse(host, out ip))
{
string[] octs = host.Split(new char[] { '.' });
host = "::ffff:";
for(int i = 0; i < octs.Length; ++i)
{
host += string.Format("{0:x}", int.Parse(octs[i]));
if(i + 1 != octs.Length)
{
host += ":";
}
}
}
else
{
throw new ClientCreateException("[in ClientNet.Constructor] Unable
to create client; use IPv4 address");
}
Socket client = new Socket(AddressFamily.InterNetworkV6,
SocketType.Stream, ProtocolType.Tcp);
client.Connect(host, port);
. . . //More initialization
}
UIActivityViewController freeze in first time
UIActivityViewController freeze in first time
When I call the first time UIActivityViewController, the interaction is
travada.Já on Monday and other times it will be normal without locking
interaction, does anyone know how to not catch the first time?
When I call the first time UIActivityViewController, the interaction is
travada.Já on Monday and other times it will be normal without locking
interaction, does anyone know how to not catch the first time?
Magento 1.7 Mage::()->getModel() don't work
Magento 1.7 Mage::()->getModel() don't work
I have problem with save records in database using Mage::getModel in
module upgrade.
I'd like add affiliate programs to affiliateplus module table when my
module is installed. My module overwrite affiliateplus module.
In mysql4-upgrade-0.1.3-0.1.4.php I have code
$installer = $this;
$installer->startSetup();
$_programList =[
'affiliate'=>[
'program_id'=>1,
'name' =>'Program Afiliacyjny',
'created_date' =>date('Y-m-d'),
'status' =>1,
'expire_time'=>0,
'num_account'=>2,
'total_sales_amount' =>0.00,
'commission_type'=>'precentage',
'commission'=>1,
'discount_type'=>'precentage',
'discount' =>1,
'autojoin' =>1,
'scope' =>0,
'customer_groups' =>null,
'show_in_welcome' =>0,
'valid_from' =>null,
'valid_to' =>null,
'use_coupon' =>0,
'coupon_pattern'=>null ,
'affiliate_type'=>null ,
'description' =>'Program Afiliacyjny',
'conditions_serialized'
=>'a:6:{s:4:"type";s:32:"salesrule/rule_condition_combine";s:9:"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}',
'actions_serialized'
=>'a:6:{s:4:"type";s:40:"salesrule/rule_condition_product_combine";s:9:"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}',
'is_process' =>0,
'use_tier_config'=>0 ,
'max_level' =>0,
'tier_commission'=>null ,
'sec_commission' =>0,
'sec_commission_type'=>0 ,
'secondary_commission' =>0,
'sec_discount' =>0,
'sec_discount_type'=>null ,
'secondary_discount' =>0,
'customer_group_ids' =>'1',
'use_sec_tier' =>0,
'sec_tier_commission'=>null
],
['more elements...']
];
foreach($_programList as $_v){
$_program = Mage::getModel('affiliateplusprogram/program');
$_program->setData($_v);
$_program->save();
unset($_program);
}
$installer->endSetup();
I tryed also:
foreach inside loop and setData for each value.
setId() before save
When I display object after foreach it's object with only my values
without methods. Magento don't show errors and warnings. My module is
upgrade to good version but in database table is empty.
In all tutorials solve id simple Mage::getModel ->setData()->save()
I have problem with save records in database using Mage::getModel in
module upgrade.
I'd like add affiliate programs to affiliateplus module table when my
module is installed. My module overwrite affiliateplus module.
In mysql4-upgrade-0.1.3-0.1.4.php I have code
$installer = $this;
$installer->startSetup();
$_programList =[
'affiliate'=>[
'program_id'=>1,
'name' =>'Program Afiliacyjny',
'created_date' =>date('Y-m-d'),
'status' =>1,
'expire_time'=>0,
'num_account'=>2,
'total_sales_amount' =>0.00,
'commission_type'=>'precentage',
'commission'=>1,
'discount_type'=>'precentage',
'discount' =>1,
'autojoin' =>1,
'scope' =>0,
'customer_groups' =>null,
'show_in_welcome' =>0,
'valid_from' =>null,
'valid_to' =>null,
'use_coupon' =>0,
'coupon_pattern'=>null ,
'affiliate_type'=>null ,
'description' =>'Program Afiliacyjny',
'conditions_serialized'
=>'a:6:{s:4:"type";s:32:"salesrule/rule_condition_combine";s:9:"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}',
'actions_serialized'
=>'a:6:{s:4:"type";s:40:"salesrule/rule_condition_product_combine";s:9:"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}',
'is_process' =>0,
'use_tier_config'=>0 ,
'max_level' =>0,
'tier_commission'=>null ,
'sec_commission' =>0,
'sec_commission_type'=>0 ,
'secondary_commission' =>0,
'sec_discount' =>0,
'sec_discount_type'=>null ,
'secondary_discount' =>0,
'customer_group_ids' =>'1',
'use_sec_tier' =>0,
'sec_tier_commission'=>null
],
['more elements...']
];
foreach($_programList as $_v){
$_program = Mage::getModel('affiliateplusprogram/program');
$_program->setData($_v);
$_program->save();
unset($_program);
}
$installer->endSetup();
I tryed also:
foreach inside loop and setData for each value.
setId() before save
When I display object after foreach it's object with only my values
without methods. Magento don't show errors and warnings. My module is
upgrade to good version but in database table is empty.
In all tutorials solve id simple Mage::getModel ->setData()->save()
Thursday, 12 September 2013
Parameterize the Decode Funcation
Parameterize the Decode Funcation
In a oracle Function im using an Decode Statement as below For security
reason i dont want the code to have the hardcoded value and i plan to
create a new lookup table.
Select CONCAT( Decode(A.COUNTRY_INITIAL,
'A','America','B','Brazil','F','FINLAND',NULL), Decode(A.ADD_VALUE,
'M','YES', NULL)
from (
Select SUBSTR(COUNTRY_BASE, -1,1) as COUNTRY_INITIAL,
Select SUBSTR(IS_VALUED, -1,1) as ADD_VALUE,
frorm TBL1
)A
Refernece Table
*******************
Clmn1 Clmn2 Clmn3
cntry1 A America
cntry2 B Brazil
cntry3 F Finland
Value1 M YES
Could you please let me know how i can incorporate this in the decode
logic. Also fyi im using this CODE SNIPPET in a Oracle FUNCAtion
In a oracle Function im using an Decode Statement as below For security
reason i dont want the code to have the hardcoded value and i plan to
create a new lookup table.
Select CONCAT( Decode(A.COUNTRY_INITIAL,
'A','America','B','Brazil','F','FINLAND',NULL), Decode(A.ADD_VALUE,
'M','YES', NULL)
from (
Select SUBSTR(COUNTRY_BASE, -1,1) as COUNTRY_INITIAL,
Select SUBSTR(IS_VALUED, -1,1) as ADD_VALUE,
frorm TBL1
)A
Refernece Table
*******************
Clmn1 Clmn2 Clmn3
cntry1 A America
cntry2 B Brazil
cntry3 F Finland
Value1 M YES
Could you please let me know how i can incorporate this in the decode
logic. Also fyi im using this CODE SNIPPET in a Oracle FUNCAtion
How to send data as json object in post method of Rho::AsyncHttp
How to send data as json object in post method of Rho::AsyncHttp
I sending data to a server using the Rho::AsyncHttp.post method, but i'm
unable to send the data as json object. But sending the data as string
reaches the server but the server api requires json data.
Here the code i'm using,
data = { :query1 => "this demo" , :query2 => "another demo" }
result = Rho::AsyncHttp.post(
:url => "https://www.myserverapi.com/myapi",
:body => data
)
The above code fails to connect to server. How ever when i change the
:body => #{data}, its reaches the server but as string. Ant suggestion?
I sending data to a server using the Rho::AsyncHttp.post method, but i'm
unable to send the data as json object. But sending the data as string
reaches the server but the server api requires json data.
Here the code i'm using,
data = { :query1 => "this demo" , :query2 => "another demo" }
result = Rho::AsyncHttp.post(
:url => "https://www.myserverapi.com/myapi",
:body => data
)
The above code fails to connect to server. How ever when i change the
:body => #{data}, its reaches the server but as string. Ant suggestion?
How to set wxpython Grid top headers?
How to set wxpython Grid top headers?
When I create a grid with wxpython, I get top column headers as "A", "B",
"C"...
import wx
import wx.grid as gridlib
########################################################################
class MyForm(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, parent=None, title="A Simple Grid")
panel = wx.Panel(self)
myGrid = gridlib.Grid(panel)
myGrid.CreateGrid(12, 8)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(myGrid, 1, wx.EXPAND)
panel.SetSizer(sizer)
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MyForm().Show()
app.MainLoop()
But I'd like to set custom column headers:
How to do this?
When I create a grid with wxpython, I get top column headers as "A", "B",
"C"...
import wx
import wx.grid as gridlib
########################################################################
class MyForm(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, parent=None, title="A Simple Grid")
panel = wx.Panel(self)
myGrid = gridlib.Grid(panel)
myGrid.CreateGrid(12, 8)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(myGrid, 1, wx.EXPAND)
panel.SetSizer(sizer)
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MyForm().Show()
app.MainLoop()
But I'd like to set custom column headers:
How to do this?
Wrapping all native functions in PHP
Wrapping all native functions in PHP
Since functions get deprecated and sometimes you just find a better way to
do something I was wondering if it's a good or a bad idea to wrapp all
native functions in PHP to a class of my own. For example:
class PHPFUNC {
public static function f_strrev($string) {
return strrev($string);
}
}
And using them like:
PHPFUNC::f_strrev($string);
Instead of:
strrev($string);
This way I could easily change all function calls simultaneously and I
could swap between mb_ versions and normal ones easily too.
What do you think? Pros? Cons? Does this create a lot of overhead?
Since functions get deprecated and sometimes you just find a better way to
do something I was wondering if it's a good or a bad idea to wrapp all
native functions in PHP to a class of my own. For example:
class PHPFUNC {
public static function f_strrev($string) {
return strrev($string);
}
}
And using them like:
PHPFUNC::f_strrev($string);
Instead of:
strrev($string);
This way I could easily change all function calls simultaneously and I
could swap between mb_ versions and normal ones easily too.
What do you think? Pros? Cons? Does this create a lot of overhead?
Sencha onUpdated() function & native apps
Sencha onUpdated() function & native apps
I have read much about this function and I understand how it works in the
web environment. This article gives a good explanation. How does onUpdated
work
What I would like to know is how do I get this to work on Native Apps
I have read much about this function and I understand how it works in the
web environment. This article gives a good explanation. How does onUpdated
work
What I would like to know is how do I get this to work on Native Apps
Regex substitution with Notepad++
Regex substitution with Notepad++
I have a text file with several lines like these ones:
cd_cod_bus
nm_number_ex
cd_goal
And I want to get rid of the - and uppercase the following character using
Notepad++ (I can also use other tool but if it doesn't get the problem
more troublesome).
So I tried to get the characters with the following regex (?<=_)\w and
replace it using \U\1\E\2 for the uppercasing trick but here is where my
problems came. I think the regex is OK but once I click replace all I get
this result:
cd_od_us
nm_umber_x
cd_oal
as you can see it is only deleting the match.
Do you know where the problem is?
Thanks.
I have a text file with several lines like these ones:
cd_cod_bus
nm_number_ex
cd_goal
And I want to get rid of the - and uppercase the following character using
Notepad++ (I can also use other tool but if it doesn't get the problem
more troublesome).
So I tried to get the characters with the following regex (?<=_)\w and
replace it using \U\1\E\2 for the uppercasing trick but here is where my
problems came. I think the regex is OK but once I click replace all I get
this result:
cd_od_us
nm_umber_x
cd_oal
as you can see it is only deleting the match.
Do you know where the problem is?
Thanks.
Wednesday, 11 September 2013
android null pointer exception setting adapter for custom list on fragment
android null pointer exception setting adapter for custom list on fragment
I have a project with fragments working ok, im using actionbarsherlock,
and sliding menu by jeremyfeinstein,
all is working fine, but when I want to customize the left drawer list
cells, i get an exception
NullPointerException
here my code,
for showing the left table working fine on basic mode for list ,
simple_list_item_1
but when I customize it, I get the exception,
here the list [PhoneMenuList.java]:
public class PhoneMenuList extends SherlockListFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
//SET THE LIST ADAPTER!
Hamburger hambu_data[] = new Hamburger[]
{
new Hamburger(R.drawable.icon_hambu_folder, "My Documents"),
new Hamburger(R.drawable.icon_hambu_favs, "Top 10 viewed"),
new Hamburger(R.drawable.icon_hambu_validate, "Validate"),
new Hamburger(R.drawable.icon_hambu_how, "How to use"),
new Hamburger(R.drawable.icon_hambu_how, "About")
};
ListView productList= (ListView)
getActivity().findViewById(R.id.listView1);
//for context!
HamburgerAdapter adapter = new HamburgerAdapter(getActivity(),
R.layout.hamburger_item_row, hambu_data);
/*
View header =
(View)getLayoutInflater(savedInstanceState).inflate(R.layout.hamburger_item_row,
null);
productList.addHeaderView(header);
productList.setAdapter(adapter);
*/
}
}
on list.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#000000"
android:dividerHeight="1dip" />
hamburguer item row
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<ImageView android:id="@+id/imgIcon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
<TextView android:id="@+id/txtTitle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:textStyle="bold"
android:textSize="22dp"
android:textColor="#000000"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
</LinearLayout>
so how to fix the exception when i set my adapter
productList.setAdapter(adapter);
Thanks!
I have a project with fragments working ok, im using actionbarsherlock,
and sliding menu by jeremyfeinstein,
all is working fine, but when I want to customize the left drawer list
cells, i get an exception
NullPointerException
here my code,
for showing the left table working fine on basic mode for list ,
simple_list_item_1
but when I customize it, I get the exception,
here the list [PhoneMenuList.java]:
public class PhoneMenuList extends SherlockListFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
//SET THE LIST ADAPTER!
Hamburger hambu_data[] = new Hamburger[]
{
new Hamburger(R.drawable.icon_hambu_folder, "My Documents"),
new Hamburger(R.drawable.icon_hambu_favs, "Top 10 viewed"),
new Hamburger(R.drawable.icon_hambu_validate, "Validate"),
new Hamburger(R.drawable.icon_hambu_how, "How to use"),
new Hamburger(R.drawable.icon_hambu_how, "About")
};
ListView productList= (ListView)
getActivity().findViewById(R.id.listView1);
//for context!
HamburgerAdapter adapter = new HamburgerAdapter(getActivity(),
R.layout.hamburger_item_row, hambu_data);
/*
View header =
(View)getLayoutInflater(savedInstanceState).inflate(R.layout.hamburger_item_row,
null);
productList.addHeaderView(header);
productList.setAdapter(adapter);
*/
}
}
on list.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#000000"
android:dividerHeight="1dip" />
hamburguer item row
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<ImageView android:id="@+id/imgIcon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
<TextView android:id="@+id/txtTitle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:textStyle="bold"
android:textSize="22dp"
android:textColor="#000000"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
</LinearLayout>
so how to fix the exception when i set my adapter
productList.setAdapter(adapter);
Thanks!
set variables instead of having end-user input them from html form
set variables instead of having end-user input them from html form
I have attempted to set these variables (to, from and mode), instead of
having the user input them. What step am I missing?
var from = (40.750484, -111.811177);
var to = (40.775041, -111.718560);
var mode = driving;
//$('#directions-form').submit(function(e) {
//$('#error').hide();
ds.route({
origin: from,
destination: to,
travelMode: mode
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
fitBounds = true;
dr.setDirections(result);
}
else {
$('#error').text(status).show();
}
recalcHeight();
});
e.preventDefault();
return false;
});
ds.route(from,to,mode);
I have attempted to set these variables (to, from and mode), instead of
having the user input them. What step am I missing?
var from = (40.750484, -111.811177);
var to = (40.775041, -111.718560);
var mode = driving;
//$('#directions-form').submit(function(e) {
//$('#error').hide();
ds.route({
origin: from,
destination: to,
travelMode: mode
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
fitBounds = true;
dr.setDirections(result);
}
else {
$('#error').text(status).show();
}
recalcHeight();
});
e.preventDefault();
return false;
});
ds.route(from,to,mode);
vbs syntax error: 800A03EE ')' expected
vbs syntax error: 800A03EE ')' expected
Private Sub AddCurrentKey(ByVal name As String, ByVal path As String)
Dim key As RegistryKey =
Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run",
True)
key.SetValue(name, path)
End Sub
I try to execute this in a file called 'addcurrentkey.vbs' But it says ')'
is expected in row 1. Character 38.
Private Sub AddCurrentKey(ByVal name As String, ByVal path As String)
Dim key As RegistryKey =
Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run",
True)
key.SetValue(name, path)
End Sub
I try to execute this in a file called 'addcurrentkey.vbs' But it says ')'
is expected in row 1. Character 38.
GWT: Docklayoutpanel in html
GWT: Docklayoutpanel in html
Can someone explain how I can create an html page which is structured like
the Docklayoutpanel from GWT? The page should have a fixed north, west,
east and south area and a dynamic center area.
Can someone explain how I can create an html page which is structured like
the Docklayoutpanel from GWT? The page should have a fixed north, west,
east and south area and a dynamic center area.
How to replace each indice of a substring
How to replace each indice of a substring
String s = "Elephant";
String srep = (s.replaceAll(s.substring(4,6), "_" ));
System.out.println(srep);
So my code outputs Elep_nt But I want it to replace each individual indice
of that substring with an underscore so that it would output Elep__nt is
there anyway to do this in a single line? would I have to use a loop?
String s = "Elephant";
String srep = (s.replaceAll(s.substring(4,6), "_" ));
System.out.println(srep);
So my code outputs Elep_nt But I want it to replace each individual indice
of that substring with an underscore so that it would output Elep__nt is
there anyway to do this in a single line? would I have to use a loop?
Hardware requirements for graphic design
Hardware requirements for graphic design
I'm helping a friend build a computer to be used for graphic design.
Photoshop, Illustrator, that sort of thing. Probably not 3d graphics or
video, but I imagine it'd be nice if it could handle that. I'm not really
a graphics design person but I've built several of my own systems for
gaming. Ideally he'd just buy a Mac for the job, but due to budgets he's
going with a desktop PC.
My understanding (and this could be wrong) is that gaming and graphics
design have a lot of overlap when it comes to hardware. i.e. a good system
for one is most likely a good system for the other. I want to make sure
this isn't a flawed assumption before I start helping him though. I'm
hoping someone else here can tell me what I should look for, not
specifically (like XXX model), but in general (Video cards are just as
important, make sure it supports YYY).
Is there any specific features I want to make sure the video card
supports? Such as DirectX versions or shader models?
In general I choose nVidia for games, and Radion for pure speed (crypto
and the like), not to get into a brand debate, but I find they both have
different strengths. Is one brand or the other better for graphics design?
I've read about people building PC's with Mac compatible hardware. I was
under the impression you couldn't install OSX on just anything (I'm not a
Mac person). How true is this? Anyone have a guide or something? Is this
something I should be concerned with?
I assume RAM and CPU are just as important as in gaming. Are there any
other hardware components I should look at? Disk access speed?
Again, budget is a concern, so all of this won't be perfect, but once I
get an idea of what is vital, what is important, and what is just a nice
thing to have I can prioritize and pick the parts myself. Still, if anyone
has specific suggestions I wouldn't mind hearing them.
Thanks
I'm helping a friend build a computer to be used for graphic design.
Photoshop, Illustrator, that sort of thing. Probably not 3d graphics or
video, but I imagine it'd be nice if it could handle that. I'm not really
a graphics design person but I've built several of my own systems for
gaming. Ideally he'd just buy a Mac for the job, but due to budgets he's
going with a desktop PC.
My understanding (and this could be wrong) is that gaming and graphics
design have a lot of overlap when it comes to hardware. i.e. a good system
for one is most likely a good system for the other. I want to make sure
this isn't a flawed assumption before I start helping him though. I'm
hoping someone else here can tell me what I should look for, not
specifically (like XXX model), but in general (Video cards are just as
important, make sure it supports YYY).
Is there any specific features I want to make sure the video card
supports? Such as DirectX versions or shader models?
In general I choose nVidia for games, and Radion for pure speed (crypto
and the like), not to get into a brand debate, but I find they both have
different strengths. Is one brand or the other better for graphics design?
I've read about people building PC's with Mac compatible hardware. I was
under the impression you couldn't install OSX on just anything (I'm not a
Mac person). How true is this? Anyone have a guide or something? Is this
something I should be concerned with?
I assume RAM and CPU are just as important as in gaming. Are there any
other hardware components I should look at? Disk access speed?
Again, budget is a concern, so all of this won't be perfect, but once I
get an idea of what is vital, what is important, and what is just a nice
thing to have I can prioritize and pick the parts myself. Still, if anyone
has specific suggestions I wouldn't mind hearing them.
Thanks
jsPDF, new document in new browser tab
jsPDF, new document in new browser tab
I use jsPDF to make a pdf document, but it appears in the same window as
page. That is bad, so I want to find how to make it appear in new tab. Can
you help me plz ? Here's the code :
$('.buy-products').on('click',function(){
question = confirm('Would you like to get a printable version ?')
if (question == true){
var list = document.getElementsByClassName('pdf');
var doc = new jsPDF();
doc.text(20, 20, 'What you bought is :');
for(var i = 0; i < list.length; i++)
{
doc.setFontSize(15);
doc.text(20, 30 + i*10,
(list[i].innerHTML.toString()).toLowerCase());
}
doc.output('datauri');
}
I use jsPDF to make a pdf document, but it appears in the same window as
page. That is bad, so I want to find how to make it appear in new tab. Can
you help me plz ? Here's the code :
$('.buy-products').on('click',function(){
question = confirm('Would you like to get a printable version ?')
if (question == true){
var list = document.getElementsByClassName('pdf');
var doc = new jsPDF();
doc.text(20, 20, 'What you bought is :');
for(var i = 0; i < list.length; i++)
{
doc.setFontSize(15);
doc.text(20, 30 + i*10,
(list[i].innerHTML.toString()).toLowerCase());
}
doc.output('datauri');
}
How should I understand mongoDB GridFS?
How should I understand mongoDB GridFS?
I am now using perl script client to store some big data into mongoDB .But
now I met a problem ,some document exceeds the size limit of 16M,so ,I
have to choose GridFS.From the GridFS document ,I read this:
GridFS is a specification for storing and retrieving files that exceed the
BSON-document size limit of 16MB.
Instead of storing a file in a single document, GridFS divides a file into
parts, or chunks, [1] and stores each of those chunks as a separate
document. By default GridFS limits chunk size to 256k.
It really make me confused.What does it mean by "file"?"Instead of storing
a file in a single document",it means , mongoDB stores a file in a single
document without using GridFS,right ?But I think it should say:"Instead of
storing a document in a single file,...".So ,the relationship and
difference between "file" and "document" make me confused.
I am now using perl script client to store some big data into mongoDB .But
now I met a problem ,some document exceeds the size limit of 16M,so ,I
have to choose GridFS.From the GridFS document ,I read this:
GridFS is a specification for storing and retrieving files that exceed the
BSON-document size limit of 16MB.
Instead of storing a file in a single document, GridFS divides a file into
parts, or chunks, [1] and stores each of those chunks as a separate
document. By default GridFS limits chunk size to 256k.
It really make me confused.What does it mean by "file"?"Instead of storing
a file in a single document",it means , mongoDB stores a file in a single
document without using GridFS,right ?But I think it should say:"Instead of
storing a document in a single file,...".So ,the relationship and
difference between "file" and "document" make me confused.
Tuesday, 10 September 2013
python: how to import a module a.b as a_.b?
python: how to import a module a.b as a_.b?
I hava a package a and the tree is:
a/
/__init__.py
/b.py
And how can I import a.b as a_.b ?
I hava a package a and the tree is:
a/
/__init__.py
/b.py
And how can I import a.b as a_.b ?
class assignment error with abstract polymorphism and inheritance
class assignment error with abstract polymorphism and inheritance
public class LawClient extends Client
{
boolean defendant;
String caseTopic;
LawClient (String n, boolean d)
{
name = n;
defendant = d;
}
LawClient (String n, boolean d, String c, String e)
{
name = n;
defendant = d;
caseTopic = c;
email = e;
}
public String determineStatus()
{
if(caseTopic == null)
{
return "none";
}
else
{
String s = "";
s += "defendant: " + defendant +"\n" + "CaseTopic: " + caseTopic;
return s;
}
}
}
i get 2 errors for no sutable constructor for the lawclient constructors
but don't know what i did wrong or how to fix it .if you need the super
class it is already finished so i can post it if needed
public class LawClient extends Client
{
boolean defendant;
String caseTopic;
LawClient (String n, boolean d)
{
name = n;
defendant = d;
}
LawClient (String n, boolean d, String c, String e)
{
name = n;
defendant = d;
caseTopic = c;
email = e;
}
public String determineStatus()
{
if(caseTopic == null)
{
return "none";
}
else
{
String s = "";
s += "defendant: " + defendant +"\n" + "CaseTopic: " + caseTopic;
return s;
}
}
}
i get 2 errors for no sutable constructor for the lawclient constructors
but don't know what i did wrong or how to fix it .if you need the super
class it is already finished so i can post it if needed
Socket error using the validate_email 1.1 package
Socket error using the validate_email 1.1 package
I trying to get validate_email package
(https://pypi.python.org/pypi/validate_email) to verify an email for me on
a Windows 7/Python 2.7 device. The following works:
>>> validate_email('example@example.com')
True
>>> validate_email('example@example.com',check_mx=True)
True
>>> validate_email('example@example.com',verify=True)
True
But when I try a commercial email server example to check if the host has
SMPT Server and/or the email really exists, it fails as follows:
>>> validate_email('example@gmail.com')
True
>>> validate_email('example@gmail.com',check_mx=True)
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\Python27\lib\site-packages\validate_email.py", line 104, in
validate_email
smtp.connect(mx[1])
File "C:\Python27\lib\smtplib.py", line 309, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python27\lib\smtplib.py", line 284, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python27\lib\socket.py", line 571, in create_connection
raise err
error: [Errno 10013] An attempt was made to access a socket in a way
forbidden by its access permissions
>>> validate_email('example@gmail.com',verify=True)
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\Python27\lib\site-packages\validate_email.py", line 104, in
validate_email
smtp.connect(mx[1])
File "C:\Python27\lib\smtplib.py", line 309, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python27\lib\smtplib.py", line 284, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python27\lib\socket.py", line 571, in create_connection
raise err
error: [Errno 10013] An attempt was made to access a socket in a way
forbidden by its access permissions
It appears that I'm trying to access a port that I don't have permission
to, but I don't know how to change to a port that would work and has the
correct permissions.
Any suggestions?
I trying to get validate_email package
(https://pypi.python.org/pypi/validate_email) to verify an email for me on
a Windows 7/Python 2.7 device. The following works:
>>> validate_email('example@example.com')
True
>>> validate_email('example@example.com',check_mx=True)
True
>>> validate_email('example@example.com',verify=True)
True
But when I try a commercial email server example to check if the host has
SMPT Server and/or the email really exists, it fails as follows:
>>> validate_email('example@gmail.com')
True
>>> validate_email('example@gmail.com',check_mx=True)
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\Python27\lib\site-packages\validate_email.py", line 104, in
validate_email
smtp.connect(mx[1])
File "C:\Python27\lib\smtplib.py", line 309, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python27\lib\smtplib.py", line 284, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python27\lib\socket.py", line 571, in create_connection
raise err
error: [Errno 10013] An attempt was made to access a socket in a way
forbidden by its access permissions
>>> validate_email('example@gmail.com',verify=True)
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\Python27\lib\site-packages\validate_email.py", line 104, in
validate_email
smtp.connect(mx[1])
File "C:\Python27\lib\smtplib.py", line 309, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python27\lib\smtplib.py", line 284, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python27\lib\socket.py", line 571, in create_connection
raise err
error: [Errno 10013] An attempt was made to access a socket in a way
forbidden by its access permissions
It appears that I'm trying to access a port that I don't have permission
to, but I don't know how to change to a port that would work and has the
correct permissions.
Any suggestions?
Subscribe to:
Comments (Atom)