Strange Stack Overflow Error in Sudoko Backtracker
(Disclaimer: There are maybe 20 different versions of this question on SO,
but a reading through most of them still hasn't solved my issue)
Hello all, (relatively) beginner programmer here. So I've been trying to
build a Sudoku backtracker that will fill in an incomplete puzzle. It
seems to works perfectly well even when 1-3 rows are completely empty
(i.e. filled in with 0's), but when more boxes start emptying
(specifically around the 7-8 column in the fourth row, where I stopped
writing in numbers) I get a Stack Overflow Error. Here's the code:
import java.util.ArrayList;
import java.util.HashSet;
public class Sudoku
{
public static int[][] puzzle = new int[9][9];
public static int filledIn = 0;
public static ArrayList<Integer> blankBoxes = new ArrayList<Integer>();
public static int currentIndex = 0;
public static int runs = 0;
/**
* Main method.
*/
public static void main(String args[])
{
//Manual input of the numbers
int[] completedNumbers = {0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,3,4,
8,9,1,2,3,4,5,6,7,
3,4,5,6,7,8,9,1,2,
6,7,8,9,1,2,3,4,5,
9,1,2,3,4,5,6,7,8};
//Adds the numbers manually to the puzzle array
ArrayList<Integer> completeArray = new ArrayList<>();
for(Integer number : completedNumbers) {
completeArray.add(number);
}
int counter = 0;
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
puzzle[i][j] = completeArray.get(counter);
counter++;
}
}
//Adds all the blank boxes to an ArrayList.
//The index is stored as 10*i + j, which can be retrieved
// via modulo and integer division.
boolean containsEmpty = false;
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
if(puzzle[i][j] == 0) {
blankBoxes.add(10*i + j);
containsEmpty = true;
}
}
}
filler(blankBoxes.get(currentIndex));
}
/**
* A general method for testing whether an array contains a
* duplicate, via a (relatively inefficient) sort.
* @param testArray The int[] that is being tested for duplicates
* @return True if there are NO duplicate, false if there
* are ANY duplicates.
*/
public static boolean checkDupl(int[] testArray) {
for(int i = 0; i < 8; i++) {
int num = testArray[i];
for(int j = i + 1; j < 9; j++) {
if(num == testArray[j] && num != 0) {
return false;
}
}
}
return true;
}
/**
* If the puzzle is not full, the filler will be run. The filler is my
attempt at a backtracker.
* It stores every (i,j) for which puzzle[i][j] == 0. It then adds 1
to it's value. If the value
* is already somewhere else, it adds another 1. If it is 9, and
that's already there, it loops to
* 0, and the index beforehand is rechecked.
*/
public static void filler(int indexOfBlank) {
//If the current index is equal to the size of blankBoxes, meaning
that we
//went through every index of blankBoxes, meaning the puzzle is
full and correct.
runs++;
if(currentIndex == blankBoxes.size()) {
System.out.println("The puzzle is full!" + "\n");
for(int i = 0; i < 9; i++) {
System.out.println();
for(int j = 0; j < 9; j++) {
System.out.print(puzzle[i][j]);
}
}
System.out.println("\n" + "The filler method was run " + runs
+ " times");
return;
}
//Assuming the puzzle isn't full, find the row/column of the
blankBoxes index.
int row = blankBoxes.get(currentIndex) / 10;
int column = blankBoxes.get(currentIndex) % 10;
//Adds one to the value of that box.
puzzle[row][column] = (puzzle[row][column] + 1);
//Just used as a breakpoint for a debugger.
if(row == 4 && column == 4){
int x = 0;
}
//If the value is 10, meaning it went through all the possible
values:
if(puzzle[row][column] == 10) {
//Do filler() on the previous box
puzzle[row][column] = 0;
currentIndex--;
filler(currentIndex);
}
//If the number is 1-9, but there are duplicates:
else if(!(checkSingleRow(row) && checkSingleColumn(column) &&
checkSingleBox(row, column))) {
//Do filler() on the same box.
filler(currentIndex);
}
//If the number is 1-9, and there is no duplicate:
else {
currentIndex++;
filler(currentIndex);
}
}
/**
* Used to check if a single row has any duplicates or not. This is
called by the
* filler method.
* @param row
* @return
*/
public static boolean checkSingleRow(int row) {
return checkDupl(puzzle[row]);
}
/**
* Used to check if a single column has any duplicates or not.
* filler method, as well as the checkColumns of the checker.
* @param column
* @return
*/
public static boolean checkSingleColumn(int column) {
int[] singleColumn = new int[9];
for(int i = 0; i < 9; i++) {
singleColumn[i] = puzzle[i][column];
}
return checkDupl(singleColumn);
}
public static boolean checkSingleBox(int row, int column) {
//Makes row and column be the first row and the first column of
the box in which
//this specific cell appears. So, for example, the box at
puzzle[3][7] will iterate
//through a box from rows 3-6 and columns 6-9 (exclusive).
row = (row / 3) * 3;
column = (column / 3) * 3;
//Iterates through the box
int[] newBox = new int[9];
int counter = 0;
for(int i = row; i < row + 3; i++) {
for(int j = row; j < row + 3; j++) {
newBox[counter] = puzzle[i][j];
counter++;
}
}
return checkDupl(newBox);
}
}
Why am I calling it a weird error? A few reasons:
The box that the error occurs on changes randomly (give or take a box).
The actual line of code that the error occurs on changes randomly (it
seems to always happen in the filler method, but that's probably just
because that's the biggest one.
Different compilers have different errors in different boxes (probably
related to 1)
What I assume is that I just wrote inefficient code, so though it's not an
actual infinite recursion, it's bad enough to call a Stack Overflow Error.
But if anyone that sees a glaring issue, I'd love to hear it. Thanks!
Saturday, 31 August 2013
Printed page information within PDF file
Printed page information within PDF file
I just opened my PDF file using the default PDF reader on Ubuntu, and when
I tried to print it, the "Pages" box was already filled with "108-115". I
was surprised, because that's the page number that I printed from this
file last time, which was many days ago!
I wonder where the "last printed page information" is stored. Is it in the
PDF file itself, or is it somewhere else in the computer?
I just opened my PDF file using the default PDF reader on Ubuntu, and when
I tried to print it, the "Pages" box was already filled with "108-115". I
was surprised, because that's the page number that I printed from this
file last time, which was many days ago!
I wonder where the "last printed page information" is stored. Is it in the
PDF file itself, or is it somewhere else in the computer?
How do you add mysql-connector-java-5.1.26 to Eclipse Android Developer Tools
How do you add mysql-connector-java-5.1.26 to Eclipse Android Developer Tools
I want the following line of code to work in Eclipse Java but apparently I
need to import/add mysql-connector-java-5.1.26 to my eclipse android
project so I can send a mySQL query via an android device.
Class.forName("com.mysql.jdbc.Driver");
How can I add the mySQL library to a current project? I've seen other
tutorials about doing this here at stack overflow but they've been kind of
unspecific and just say "just ADD it to your current project" but that's
where I'm stumped.
Most tutorials online just tell you how to start a new project from
scratch, but I'm working with an android application.
Do I go to File>Import? and then select the .zip with the mySQL files? Or
do I select the folder or something? I'm doing this on a Mac.
Thanks.
I want the following line of code to work in Eclipse Java but apparently I
need to import/add mysql-connector-java-5.1.26 to my eclipse android
project so I can send a mySQL query via an android device.
Class.forName("com.mysql.jdbc.Driver");
How can I add the mySQL library to a current project? I've seen other
tutorials about doing this here at stack overflow but they've been kind of
unspecific and just say "just ADD it to your current project" but that's
where I'm stumped.
Most tutorials online just tell you how to start a new project from
scratch, but I'm working with an android application.
Do I go to File>Import? and then select the .zip with the mySQL files? Or
do I select the folder or something? I'm doing this on a Mac.
Thanks.
Support in data cubes
Support in data cubes
I am asked to find the number of cells in a data cube, with support
greater than 0, assuming that I have only one row in my fact table.
According to this link (under the heading Iceberg-cubes)
http://www2.cs.uregina.ca/~hamilton/courses/831/notes/dcubes/dcubes.html
Now, according to the definition of minimum support is the minimum number
of tuples in which a combination of attribute values must appear to be
considered frequent. In this case the support should be 1, since only 1
rows exist. But how can I find the number of cells with support >0 in the
corresponding data cube. Any pointers in this regard is also appreciated.
Thanks in advance.
I am asked to find the number of cells in a data cube, with support
greater than 0, assuming that I have only one row in my fact table.
According to this link (under the heading Iceberg-cubes)
http://www2.cs.uregina.ca/~hamilton/courses/831/notes/dcubes/dcubes.html
Now, according to the definition of minimum support is the minimum number
of tuples in which a combination of attribute values must appear to be
considered frequent. In this case the support should be 1, since only 1
rows exist. But how can I find the number of cells with support >0 in the
corresponding data cube. Any pointers in this regard is also appreciated.
Thanks in advance.
How to add two UITableViews to ViewController in storyboard?
How to add two UITableViews to ViewController in storyboard?
In my app, I want to handle 2 tables in one ViewController.
First I drag a UITableViewController into NavigationController, so there
is already a UITableView.
Then I drag another UITableView to the scene, but the second UITableView
can't be placed at the same level as first UITableView, it can only be a
subview of first UITableView or replace the first UITableView. Here is the
structs, please help.
In my app, I want to handle 2 tables in one ViewController.
First I drag a UITableViewController into NavigationController, so there
is already a UITableView.
Then I drag another UITableView to the scene, but the second UITableView
can't be placed at the same level as first UITableView, it can only be a
subview of first UITableView or replace the first UITableView. Here is the
structs, please help.
How can I prevent a page from loading if there is no javascript, but using php instead of ?
How can I prevent a page from loading if there is no javascript, but using
php instead of ?
I have a page with php and other stuff in the code. What I need to do is a
way to check with php if there is javascript enabled in the browser. This
way, the whole page source will be prevented to be loaded, instead of
using that only prevents the page from loading, but allows the source
code.
php instead of ?
I have a page with php and other stuff in the code. What I need to do is a
way to check with php if there is javascript enabled in the browser. This
way, the whole page source will be prevented to be loaded, instead of
using that only prevents the page from loading, but allows the source
code.
content is undefined,error is Error:ENOENT,open 'C:\Windows\system32\hello.txt'
content is undefined,error is Error:ENOENT,open
'C:\Windows\system32\hello.txt'
i just started learning node. and here is my problem,i got sample.js file
var fs=require("fs");
console.log("starting");
fs.readFile("hello.txt" , function(error,data){
console.log("content is asdas " + data);
});
console.log("executed");
and hello.txt with content ,they both are on my desktop
hello
when i run as administrator in powershell or cmd this code
C:\Windows\system32\ node C:\Users\X\Desktop\sample.js
i get
starting
executing
content is asdas undefined
when i log error
var fs=require("fs");
console.log("starting");
fs.readFile("hello.txt" , function(error,data){
console.log("content is asdas " + error);
});
console.log("executed");
i get
starting
executing
content is asdas Error:ENOENT,open 'C:\Windows\system32\hello.txt'
So i guess that error is that node is looking in system32,not in desktop...?
Thanks!
'C:\Windows\system32\hello.txt'
i just started learning node. and here is my problem,i got sample.js file
var fs=require("fs");
console.log("starting");
fs.readFile("hello.txt" , function(error,data){
console.log("content is asdas " + data);
});
console.log("executed");
and hello.txt with content ,they both are on my desktop
hello
when i run as administrator in powershell or cmd this code
C:\Windows\system32\ node C:\Users\X\Desktop\sample.js
i get
starting
executing
content is asdas undefined
when i log error
var fs=require("fs");
console.log("starting");
fs.readFile("hello.txt" , function(error,data){
console.log("content is asdas " + error);
});
console.log("executed");
i get
starting
executing
content is asdas Error:ENOENT,open 'C:\Windows\system32\hello.txt'
So i guess that error is that node is looking in system32,not in desktop...?
Thanks!
Mark current location on google map
Mark current location on google map
How to mark my current location on google map. I am using google place
API. I have to show all near places from my current position. All places
are showing on google map, but how to show my current position.? The code
is given below...` public class PoliceStationMapActivity extends
FragmentActivity implements LocationListener { private ArrayList
mArrayListPoliceStations; private GoogleMap mMap;
private LocationManager locManager;
private double latitude;
private double longitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_police_station);
locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
0, 0, this);
else
Log.i("Test", "network provider unavailable");
Location lastKnownLocation =
locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
latitude = lastKnownLocation.getLatitude();
longitude = lastKnownLocation.getLongitude();
if (lastKnownLocation != null) {
Log.i("Test", lastKnownLocation.getLatitude() + ", " +
lastKnownLocation.getLongitude());
locManager.removeUpdates(this);
}
mMap = ((SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (mMap != null) {
new GetAllPoliceStationsTask().execute("" + latitude, "" +
longitude);
}
}
private class GetAllPoliceStationsTask extends AsyncTask<String, Void,
ArrayList<Place>> {
@Override
protected ArrayList<Place> doInBackground(String... param) {
ArrayList<Place> policeStationsList =
RequestHandler.getInstance(PoliceStationMapActivity.this).getAllPlaces(param[0],
param[1]);
return policeStationsList;
}
@Override
protected void onPostExecute(java.util.ArrayList<Place> result) {
if (result != null) {
mArrayListPoliceStations = result;
placeAllPoliceStationMarkersOnMap(mArrayListPoliceStations);
}
}
}
private void placeAllPoliceStationMarkersOnMap(ArrayList<Place>
policeStationList) {
for (Place place : policeStationList) {
addPlaceMarkerOnMap(place);
}
};
private void addPlaceMarkerOnMap(Place place) {
LatLng latLng = new LatLng(place.getLatitude(), place.getLongitude());
Marker poiMarker = mMap.addMarker(new
MarkerOptions().position(latLng).title(place.getName()).snippet(place.getVicinity()));
Marker currentMarker = mMap.addMarker(new MarkerOptions().position());
}
@Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}`
How to mark my current location on google map. I am using google place
API. I have to show all near places from my current position. All places
are showing on google map, but how to show my current position.? The code
is given below...` public class PoliceStationMapActivity extends
FragmentActivity implements LocationListener { private ArrayList
mArrayListPoliceStations; private GoogleMap mMap;
private LocationManager locManager;
private double latitude;
private double longitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_police_station);
locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
0, 0, this);
else
Log.i("Test", "network provider unavailable");
Location lastKnownLocation =
locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
latitude = lastKnownLocation.getLatitude();
longitude = lastKnownLocation.getLongitude();
if (lastKnownLocation != null) {
Log.i("Test", lastKnownLocation.getLatitude() + ", " +
lastKnownLocation.getLongitude());
locManager.removeUpdates(this);
}
mMap = ((SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (mMap != null) {
new GetAllPoliceStationsTask().execute("" + latitude, "" +
longitude);
}
}
private class GetAllPoliceStationsTask extends AsyncTask<String, Void,
ArrayList<Place>> {
@Override
protected ArrayList<Place> doInBackground(String... param) {
ArrayList<Place> policeStationsList =
RequestHandler.getInstance(PoliceStationMapActivity.this).getAllPlaces(param[0],
param[1]);
return policeStationsList;
}
@Override
protected void onPostExecute(java.util.ArrayList<Place> result) {
if (result != null) {
mArrayListPoliceStations = result;
placeAllPoliceStationMarkersOnMap(mArrayListPoliceStations);
}
}
}
private void placeAllPoliceStationMarkersOnMap(ArrayList<Place>
policeStationList) {
for (Place place : policeStationList) {
addPlaceMarkerOnMap(place);
}
};
private void addPlaceMarkerOnMap(Place place) {
LatLng latLng = new LatLng(place.getLatitude(), place.getLongitude());
Marker poiMarker = mMap.addMarker(new
MarkerOptions().position(latLng).title(place.getName()).snippet(place.getVicinity()));
Marker currentMarker = mMap.addMarker(new MarkerOptions().position());
}
@Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}`
Friday, 30 August 2013
Primitive variables perform calculations faster than their associated wrapper class
Primitive variables perform calculations faster than their associated
wrapper class
This is an exact statement from a book on Java. Can someone confirm
whether this is indeed right ?
And why does the operation cost done on wrapper classes will be higher
than their primitive counterpart ?
wrapper class
This is an exact statement from a book on Java. Can someone confirm
whether this is indeed right ?
And why does the operation cost done on wrapper classes will be higher
than their primitive counterpart ?
Thursday, 29 August 2013
Production and Development in WAMP
Production and Development in WAMP
I'm trying to output errors in WAMP, I know there's production and
development mode's.
But how do you switch between the modes? How can i define that i'm now in
development and now in production. Or am I getting this totally wrong?
Thanks
I'm trying to output errors in WAMP, I know there's production and
development mode's.
But how do you switch between the modes? How can i define that i'm now in
development and now in production. Or am I getting this totally wrong?
Thanks
Wednesday, 28 August 2013
C++ returning HashMap object to Java
C++ returning HashMap object to Java
I have a JNI function that JAVA calls that needs to build and return a
HashMap. The key for the map is 'String' and the respective value is
'boolean' or 'Boolean' (either one is fine, as long as it works). With the
current code that I have (below), the string is successfully added to the
map that is returned and can be accessed in Java. However, when trying to
access the value in JAVA, it comes up null.
jclass mapclass = env->FindClass("java/util/HashMap");
jmethodID initmeth = env->GetMethodID(mapclass, "<init>", "()V");
jmethodID putmeth = env->GetMethodID(mapclass, "put",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
jobject roster_return = env->NewObject(mapclass, initmeth);
int roster_map_size;
std::map<std::string, RosterItem>* roster_map = GetRosterMap();
std::map<std::string, RosterItem>::iterator iter;
if (!roster_map || roster_map->size() < 1)
return roster_return;
iter = roster_map->begin();
while (iter != roster_map->end())
{
env->CallObjectMethod(roster_return, putmeth,
env->NewStringUTF(iter->second.name.c_str()),
(jboolean)iter->second.isfriend);
iter++;
}
I've tried generating a Boolean object, but I cannot seem to figure out
how to create a new one. I've tried the following code, but it errors on
the "GetMethodID" for the boolean "init".
jclass mapclass = env->FindClass("java/util/HashMap");
jclass boolclass = env->FindClass("java/lang/Boolean");
jmethodID initmeth = env->GetMethodID(mapclass, "<init>", "()V");
//-----------------It errors on the next line-----------------------
jmethodID initbool = env->GetMethodID(boolclass, "<init>", "()V");
jmethodID putmeth = env->GetMethodID(mapclass, "put",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
jobject roster_return = env->NewObject(mapclass, initmeth);
int roster_map_size;
std::map<std::string, RosterItem>* roster_map = GetRosterMap();;
std::map<std::string, RosterItem>::iterator iter;
if (!roster_map || roster_map->size() < 1)
return roster_return;
iter = roster_map->begin();
while (iter != roster_map->end())
{
LOGE("adding contact: %s", iter->second.jid.Str().c_str());
//---Not sure what to pass in the next function here for the fourth
argument---
env->CallObjectMethod(roster_return, putmeth,
env->NewStringUTF(iter->second.name.c_str()),
(jboolean)iter->second.isfriend);
iter++;
}
I have a JNI function that JAVA calls that needs to build and return a
HashMap. The key for the map is 'String' and the respective value is
'boolean' or 'Boolean' (either one is fine, as long as it works). With the
current code that I have (below), the string is successfully added to the
map that is returned and can be accessed in Java. However, when trying to
access the value in JAVA, it comes up null.
jclass mapclass = env->FindClass("java/util/HashMap");
jmethodID initmeth = env->GetMethodID(mapclass, "<init>", "()V");
jmethodID putmeth = env->GetMethodID(mapclass, "put",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
jobject roster_return = env->NewObject(mapclass, initmeth);
int roster_map_size;
std::map<std::string, RosterItem>* roster_map = GetRosterMap();
std::map<std::string, RosterItem>::iterator iter;
if (!roster_map || roster_map->size() < 1)
return roster_return;
iter = roster_map->begin();
while (iter != roster_map->end())
{
env->CallObjectMethod(roster_return, putmeth,
env->NewStringUTF(iter->second.name.c_str()),
(jboolean)iter->second.isfriend);
iter++;
}
I've tried generating a Boolean object, but I cannot seem to figure out
how to create a new one. I've tried the following code, but it errors on
the "GetMethodID" for the boolean "init".
jclass mapclass = env->FindClass("java/util/HashMap");
jclass boolclass = env->FindClass("java/lang/Boolean");
jmethodID initmeth = env->GetMethodID(mapclass, "<init>", "()V");
//-----------------It errors on the next line-----------------------
jmethodID initbool = env->GetMethodID(boolclass, "<init>", "()V");
jmethodID putmeth = env->GetMethodID(mapclass, "put",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
jobject roster_return = env->NewObject(mapclass, initmeth);
int roster_map_size;
std::map<std::string, RosterItem>* roster_map = GetRosterMap();;
std::map<std::string, RosterItem>::iterator iter;
if (!roster_map || roster_map->size() < 1)
return roster_return;
iter = roster_map->begin();
while (iter != roster_map->end())
{
LOGE("adding contact: %s", iter->second.jid.Str().c_str());
//---Not sure what to pass in the next function here for the fourth
argument---
env->CallObjectMethod(roster_return, putmeth,
env->NewStringUTF(iter->second.name.c_str()),
(jboolean)iter->second.isfriend);
iter++;
}
Return an unset value in value converter
Return an unset value in value converter
Using a value converter in WPF, you can return something like
DependecyProperty.UnsetValue or Binding.DoNothing as special values to say
leave the binding alone. Is there a similar mechanism in MVVMCross?
To be more specific about what I'm trying to do, is I have a view model
property that is a three-state enum that I need to bind to 3 binary
controls. So I thought I could bind each of the controls to a MyEnum ->
bool converter that will have a conversion parameter set to the value of
the converter and in the Convert method it will return true if the MyEnum
state is equal to the parameter and false otherwise. So far so good. But I
want this binding to be two-way, so I need to convert back. My convert
back works something like this:
protected override MyEnum ConvertBack(bool value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
if (parameter is MyEnum)
{
if (value)
{
return (MyEnum)parameter; // this is fine
}
else
{
return ???
}
}
return base.ConvertBack(value, targetType, parameter, culture);
}
Basically, what I want to be able to do is say, if the state of my control
is true update the bound property on my view model to be the same as the
parameter, if not, leave the view model property alone.
Maybe this is the problem with using the strongly typed value converters?
Using a value converter in WPF, you can return something like
DependecyProperty.UnsetValue or Binding.DoNothing as special values to say
leave the binding alone. Is there a similar mechanism in MVVMCross?
To be more specific about what I'm trying to do, is I have a view model
property that is a three-state enum that I need to bind to 3 binary
controls. So I thought I could bind each of the controls to a MyEnum ->
bool converter that will have a conversion parameter set to the value of
the converter and in the Convert method it will return true if the MyEnum
state is equal to the parameter and false otherwise. So far so good. But I
want this binding to be two-way, so I need to convert back. My convert
back works something like this:
protected override MyEnum ConvertBack(bool value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
if (parameter is MyEnum)
{
if (value)
{
return (MyEnum)parameter; // this is fine
}
else
{
return ???
}
}
return base.ConvertBack(value, targetType, parameter, culture);
}
Basically, what I want to be able to do is say, if the state of my control
is true update the bound property on my view model to be the same as the
parameter, if not, leave the view model property alone.
Maybe this is the problem with using the strongly typed value converters?
Displaying an element similar to p inside a span?
Displaying an element similar to p inside a span?
I have a span with an inculded p, like this:
<span>
<p>this is the p</p>
</span>
This is not allowed according to the HTML5 specs. Now, my HTML is more
complex than the above and I need something similar to a p which I can use
instead. Which tag could I use or which element can I change using css so
it behaves like a p?
I have a span with an inculded p, like this:
<span>
<p>this is the p</p>
</span>
This is not allowed according to the HTML5 specs. Now, my HTML is more
complex than the above and I need something similar to a p which I can use
instead. Which tag could I use or which element can I change using css so
it behaves like a p?
Separators in django.simplejson "missing"
Separators in django.simplejson "missing"
In django I have created a view that returns a json object.
def get_json_for_all_drives(request):
drive_ids = []
for entry in Drive.objects.all():
drive_ids.append(entry.id)
no_of_drives = len(drive_ids)
all_values = []
for drive_id in drive_ids:
drive_values = []
for entry in Drivespace.objects.filter(driveid=drive_id):
drive_values.append([delorean.Delorean(entry.datetime,
timezone="UTC").epoch()*1000,entry.freespace/1024.0/1024.0/1024.0])
all_values.append(drive_values)
data = simplejson.dumps(all_values, separators=(',',','))
return HttpResponse(all_values,content_type = 'application/json;
charset=utf8')
However, there is a thing that bothers me. The result looks like the
following:
[[1,1],[2,2],[3,3]][[a,a],[b,b],[c,]]
As you can see there is no comma between the two lists. Without the comma
I am not able to parse is it in javascript. If I work with a fixed set of
arguments to dump into jason it works, e.g.:
data = simplejson.dumps([myList[0], myList[1]])
Does anyone have an idea on how to solve this?
In django I have created a view that returns a json object.
def get_json_for_all_drives(request):
drive_ids = []
for entry in Drive.objects.all():
drive_ids.append(entry.id)
no_of_drives = len(drive_ids)
all_values = []
for drive_id in drive_ids:
drive_values = []
for entry in Drivespace.objects.filter(driveid=drive_id):
drive_values.append([delorean.Delorean(entry.datetime,
timezone="UTC").epoch()*1000,entry.freespace/1024.0/1024.0/1024.0])
all_values.append(drive_values)
data = simplejson.dumps(all_values, separators=(',',','))
return HttpResponse(all_values,content_type = 'application/json;
charset=utf8')
However, there is a thing that bothers me. The result looks like the
following:
[[1,1],[2,2],[3,3]][[a,a],[b,b],[c,]]
As you can see there is no comma between the two lists. Without the comma
I am not able to parse is it in javascript. If I work with a fixed set of
arguments to dump into jason it works, e.g.:
data = simplejson.dumps([myList[0], myList[1]])
Does anyone have an idea on how to solve this?
SSL_connect Error with "rake one_sky:upload"
SSL_connect Error with "rake one_sky:upload"
I plan to use oneSky's i18n-one_sky-ruby gem for translation.
When I did "rake one_sky:upload", I got this error:
SSL_connect returned=1 errno=0 state=SSLv2/v3 read server hello A: (null)
I tried reinstalling openssl
moved
config.ssl_options = {hsts: {expires: 3600}}
to production.rb, but nothing changed.
How can I fix this error?
I plan to use oneSky's i18n-one_sky-ruby gem for translation.
When I did "rake one_sky:upload", I got this error:
SSL_connect returned=1 errno=0 state=SSLv2/v3 read server hello A: (null)
I tried reinstalling openssl
moved
config.ssl_options = {hsts: {expires: 3600}}
to production.rb, but nothing changed.
How can I fix this error?
Passing string from edit text to another activity
Passing string from edit text to another activity
I have looked through the example here on stack overflow. However, I can't
get a solution that works correctly. My application still crashes. How do
I pass the string from an edit text in one activity to another?
This is my code from the first activity: Button btnGo = (Button)
findViewById(R.id.btnGo);
btnGo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText etLocation = (EditText) findViewById(R.id.et_location);
Intent intent = new Intent();
intent.putExtra("location", etLocation.getText().toString());
startActivity(intent);
Code from Second Activity:
textView1 = (TextView) findViewById(R.id.textView1);
Intent intent = getIntent();
String str = intent.getStringExtra("location");
textView1.setText(str);
I have looked through the example here on stack overflow. However, I can't
get a solution that works correctly. My application still crashes. How do
I pass the string from an edit text in one activity to another?
This is my code from the first activity: Button btnGo = (Button)
findViewById(R.id.btnGo);
btnGo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText etLocation = (EditText) findViewById(R.id.et_location);
Intent intent = new Intent();
intent.putExtra("location", etLocation.getText().toString());
startActivity(intent);
Code from Second Activity:
textView1 = (TextView) findViewById(R.id.textView1);
Intent intent = getIntent();
String str = intent.getStringExtra("location");
textView1.setText(str);
Tuesday, 27 August 2013
Redirect to login page onajax request
Redirect to login page onajax request
I am using jsp and jquery...and struts.I have a problem understanding the
redirect to login page for ajax request.I tried to see request on browser
on XHR tab and it gives me 302 status code in header.I am not able to
comprehend how do i redirect. My approach 1)The application has a function
which checks if the user is signed in or not and has function to redirect
to login url. 2)Else do some other processing.
How do I come back to same page after login.Is there any way?.....Also for
redirecting on server side i am using Response.redirect().When i debug the
code and response comes on client side the error function in ajax funcn is
executed not success function..Can someone explain how to catch response
from server?...
function buttonpress(param1,param2) {
$.ajax({
type:"GET",
data: {
X:param1,
Y:param2,
},
url:"/application",
success:function() {
alert("success message");
},
error:function() {
alert("error message");
}
});
}
I am using jsp and jquery...and struts.I have a problem understanding the
redirect to login page for ajax request.I tried to see request on browser
on XHR tab and it gives me 302 status code in header.I am not able to
comprehend how do i redirect. My approach 1)The application has a function
which checks if the user is signed in or not and has function to redirect
to login url. 2)Else do some other processing.
How do I come back to same page after login.Is there any way?.....Also for
redirecting on server side i am using Response.redirect().When i debug the
code and response comes on client side the error function in ajax funcn is
executed not success function..Can someone explain how to catch response
from server?...
function buttonpress(param1,param2) {
$.ajax({
type:"GET",
data: {
X:param1,
Y:param2,
},
url:"/application",
success:function() {
alert("success message");
},
error:function() {
alert("error message");
}
});
}
sort 2-D list python
sort 2-D list python
I'm relatively new to programming, and I want to sort a 2-D array (lists
as they're called in Python) by the value of all the items in each
sub-array. For example:
pop = [[1,5,3],[1,1,1],[7,5,8],[2,5,4]]
The sum of the first element of pop would be 9, because 1 + 5 + 3 = 9. The
sum of the second would be 3, because 1 + 1 + 1 = 3, and so on.
I want to rearrange this so the new order would be:
newPop = [pop[1], pop[0], pop[3], pop[2]]
How would I do this?
Note: I don't want to sort the elements each sub-array, but sort according
to the sum of all the numbers in each sub-array.
I'm relatively new to programming, and I want to sort a 2-D array (lists
as they're called in Python) by the value of all the items in each
sub-array. For example:
pop = [[1,5,3],[1,1,1],[7,5,8],[2,5,4]]
The sum of the first element of pop would be 9, because 1 + 5 + 3 = 9. The
sum of the second would be 3, because 1 + 1 + 1 = 3, and so on.
I want to rearrange this so the new order would be:
newPop = [pop[1], pop[0], pop[3], pop[2]]
How would I do this?
Note: I don't want to sort the elements each sub-array, but sort according
to the sum of all the numbers in each sub-array.
Hibernate lazy-load transient fields
Hibernate lazy-load transient fields
I expect that this is an unusual use-case.
Say I have a entity class Foo:
@Entity
public class Foo {
@Id
private Long id;
private String bar;
@Transient
private long bazz;
...
}
I also have an Interceptor defined such that Foo.bazz is initialized when
instances of Foo are read from the database:
public class MyInterceptor extends EmptyInterceptor {
...
@Override
public boolean onLoad(
Object entity,
Serializable id,
Object[] state,
String[] propertyNames,
Type[] types) {
if(entity instanceof Foo) {
Foo foo = (Foo)entity;
long bazzValue = ... // some very heavyweight code
foo.setBazz(bazzValue);
}
return false;
}
So far, so good. But not all code paths will need the value of every Foo
instance's bazz field. This means that the heavyweight code to find a
value for each and every instance of Foo is sometimes needlessly invoked.
How do I go about avoiding invoking the code to find a value for bazz
unless Foo.getBazz() is actually invoked?
I expect that this is an unusual use-case.
Say I have a entity class Foo:
@Entity
public class Foo {
@Id
private Long id;
private String bar;
@Transient
private long bazz;
...
}
I also have an Interceptor defined such that Foo.bazz is initialized when
instances of Foo are read from the database:
public class MyInterceptor extends EmptyInterceptor {
...
@Override
public boolean onLoad(
Object entity,
Serializable id,
Object[] state,
String[] propertyNames,
Type[] types) {
if(entity instanceof Foo) {
Foo foo = (Foo)entity;
long bazzValue = ... // some very heavyweight code
foo.setBazz(bazzValue);
}
return false;
}
So far, so good. But not all code paths will need the value of every Foo
instance's bazz field. This means that the heavyweight code to find a
value for each and every instance of Foo is sometimes needlessly invoked.
How do I go about avoiding invoking the code to find a value for bazz
unless Foo.getBazz() is actually invoked?
Javascript Clear all script. High I/O (in/out) usage
Javascript Clear all script. High I/O (in/out) usage
Using this script
function clearChildren(element) {
for (var i = 0; i < element.childNodes.length; i++) {
//for (var i = 0; i < 30; i++) {
var e = element.childNodes[i];
if (e.tagName) switch (e.tagName.toLowerCase()) {
case 'input':
switch (e.type) {
case "radio":
case "checkbox": e.checked = false; break;
case "button":
case "submit":
case "image": break;
default: e.value = ''; break;
}
break;
case 'textarea': e.value = ''; break;
case 'select': e.selectedIndex = -1; break;
default: clearChildren(e);
}
}
}
On CPanel see high I/O usage. element.childNodes.length is 30 and for each
row there are ~20 columns.
Is it possible to improve the script to reduce I/O usage? Or it is because
of so many columns/rows?
Removed case "radio": and other unnecessary, but I/O usage is the same.
Please advice what to do
Using this script
function clearChildren(element) {
for (var i = 0; i < element.childNodes.length; i++) {
//for (var i = 0; i < 30; i++) {
var e = element.childNodes[i];
if (e.tagName) switch (e.tagName.toLowerCase()) {
case 'input':
switch (e.type) {
case "radio":
case "checkbox": e.checked = false; break;
case "button":
case "submit":
case "image": break;
default: e.value = ''; break;
}
break;
case 'textarea': e.value = ''; break;
case 'select': e.selectedIndex = -1; break;
default: clearChildren(e);
}
}
}
On CPanel see high I/O usage. element.childNodes.length is 30 and for each
row there are ~20 columns.
Is it possible to improve the script to reduce I/O usage? Or it is because
of so many columns/rows?
Removed case "radio": and other unnecessary, but I/O usage is the same.
Please advice what to do
SharePoint CrossListQueryInfo run elevated
SharePoint CrossListQueryInfo run elevated
I have a CrossListQueryInfo/Cache method that works as expected.
Unfortunately security trimming filters out all list items the user has no
access to (of course). But I want to find these list items too. That's why
I went for SPSecurity.RunWithElevatedPrivileges but that didn't work out
as expected.
Any hints?
private class ContentManager
{
private const string FIELD_CONTENTTYPE = "ContentType";
private const string FIELD_PUBLISH_START = "PublishingStartDate";
private const string FIELD_PUBLISH_END = "PublishingExpirationDate";
private const string FIELD_TITLE = "Title";
public string FindPage(string contentTypeName)
{
Guid[] viewFieldsIds = { SPBuiltInFieldId.Title,
SPBuiltInFieldId.FileRef };
string query =
CamlexNET.Camlex.Query()
.Where(
spListItem =>
(string)spListItem[FIELD_CONTENTTYPE] == contentTypeName
&& ((DateTime)spListItem[FIELD_PUBLISH_START] <=
DateTime.Now || spListItem[FIELD_PUBLISH_START] ==
null)
&& ((DateTime)spListItem[FIELD_PUBLISH_END] >
DateTime.Now || spListItem[FIELD_PUBLISH_END] ==
null))
.OrderBy(x => x[FIELD_TITLE])
.ToString();
string viewFields =
CamlexNET.Camlex.Query().ViewFields(viewFieldsIds);
//DataTable results =
crossListCache.GetSiteData(SPContext.Current.Site);
DataTable results = null;
SPSecurity.RunWithElevatedPrivileges(
() =>
{
CrossListQueryInfo crossListQueryInfo = new
CrossListQueryInfo();
crossListQueryInfo.Query = query;
crossListQueryInfo.UseCache = true;
crossListQueryInfo.ShowUntargetedItems = true;
crossListQueryInfo.ViewFields = viewFields;
crossListQueryInfo.Webs = "<Webs Scope=\"Recursive\" />";
crossListQueryInfo.Lists = "<Lists
ServerTemplate=\"850\" />";
crossListQueryInfo.WebUrl = "/";
CrossListQueryCache crossListCache = new
CrossListQueryCache(crossListQueryInfo);
using (SPSite site = new
SPSite(SPContext.Current.Site.ID))
{
results = crossListCache.GetSiteData(site);
}
});
return results.Rows.Count.ToString();
}
}
I have a CrossListQueryInfo/Cache method that works as expected.
Unfortunately security trimming filters out all list items the user has no
access to (of course). But I want to find these list items too. That's why
I went for SPSecurity.RunWithElevatedPrivileges but that didn't work out
as expected.
Any hints?
private class ContentManager
{
private const string FIELD_CONTENTTYPE = "ContentType";
private const string FIELD_PUBLISH_START = "PublishingStartDate";
private const string FIELD_PUBLISH_END = "PublishingExpirationDate";
private const string FIELD_TITLE = "Title";
public string FindPage(string contentTypeName)
{
Guid[] viewFieldsIds = { SPBuiltInFieldId.Title,
SPBuiltInFieldId.FileRef };
string query =
CamlexNET.Camlex.Query()
.Where(
spListItem =>
(string)spListItem[FIELD_CONTENTTYPE] == contentTypeName
&& ((DateTime)spListItem[FIELD_PUBLISH_START] <=
DateTime.Now || spListItem[FIELD_PUBLISH_START] ==
null)
&& ((DateTime)spListItem[FIELD_PUBLISH_END] >
DateTime.Now || spListItem[FIELD_PUBLISH_END] ==
null))
.OrderBy(x => x[FIELD_TITLE])
.ToString();
string viewFields =
CamlexNET.Camlex.Query().ViewFields(viewFieldsIds);
//DataTable results =
crossListCache.GetSiteData(SPContext.Current.Site);
DataTable results = null;
SPSecurity.RunWithElevatedPrivileges(
() =>
{
CrossListQueryInfo crossListQueryInfo = new
CrossListQueryInfo();
crossListQueryInfo.Query = query;
crossListQueryInfo.UseCache = true;
crossListQueryInfo.ShowUntargetedItems = true;
crossListQueryInfo.ViewFields = viewFields;
crossListQueryInfo.Webs = "<Webs Scope=\"Recursive\" />";
crossListQueryInfo.Lists = "<Lists
ServerTemplate=\"850\" />";
crossListQueryInfo.WebUrl = "/";
CrossListQueryCache crossListCache = new
CrossListQueryCache(crossListQueryInfo);
using (SPSite site = new
SPSite(SPContext.Current.Site.ID))
{
results = crossListCache.GetSiteData(site);
}
});
return results.Rows.Count.ToString();
}
}
Simulate No Service on iOS device
Simulate No Service on iOS device
I am currently testing an iOS app on an iPad 4 with 3G running iOS 6. Part
of the testing I need to do requires that I use the app when the iPad has
different reachabilities (No Service, 3G, WiFi, Edge, Airplane).
Is there a way I can simulate the iPad to think it has no service other
than me going underground and jumping on the tube. I have tried taking out
the SIM card but it does not say No Service, it just says No SIM.
Thanks
I am currently testing an iOS app on an iPad 4 with 3G running iOS 6. Part
of the testing I need to do requires that I use the app when the iPad has
different reachabilities (No Service, 3G, WiFi, Edge, Airplane).
Is there a way I can simulate the iPad to think it has no service other
than me going underground and jumping on the tube. I have tried taking out
the SIM card but it does not say No Service, it just says No SIM.
Thanks
using jquery validate accept methods with ie - any pollyfills
using jquery validate accept methods with ie - any pollyfills
so the jQuery validate has an extra plugin called accept
http://jqueryvalidation.org/accept-method
what this allows you to do is validate file types on an upload form for
example
so you could have a bit of code that looks like
$("#addNewDocumentForm").validate({
rules: {
inputDocument: { required: true, accept: "png|jpe?g|gif|pdf" }
},
messages: {
inputDocument: "File must be PDF, DOCX, JPG, GIF or PNG"
},
submitHandler: function(e) {
...
the problem is using this in ie 8 or 9 because while it will do the
required part it will not do the accept bit as it uses the file API part
of HTML5
I was wondering if anyone has come across any similar issues? any if they
found any polyfills for it etc?
can anyone help / suggest anything
thanks
so the jQuery validate has an extra plugin called accept
http://jqueryvalidation.org/accept-method
what this allows you to do is validate file types on an upload form for
example
so you could have a bit of code that looks like
$("#addNewDocumentForm").validate({
rules: {
inputDocument: { required: true, accept: "png|jpe?g|gif|pdf" }
},
messages: {
inputDocument: "File must be PDF, DOCX, JPG, GIF or PNG"
},
submitHandler: function(e) {
...
the problem is using this in ie 8 or 9 because while it will do the
required part it will not do the accept bit as it uses the file API part
of HTML5
I was wondering if anyone has come across any similar issues? any if they
found any polyfills for it etc?
can anyone help / suggest anything
thanks
Monday, 26 August 2013
Matrix Multiplication using IAS Instruciton Set
Matrix Multiplication using IAS Instruciton Set
I have to write a program using IAS Instruction set for multiplying two
2*2 martix and store the result in another matrix C. I saw a program
posted by another guy for matrix addition
**********************
* Initialize a variable 'count' to 999
Label: TOP
00000001 LOAD M(A[count]) Transfer M(A[count]) to the
accumulator
00000101 ADD M(B[count]) Add M(B[count]) to AC and store
result in AC
00100001 STOR M(C[count]) Transfer contents of accumulator
to memory location C[count]
00001010 LOAD M(address of count) Transfer the contents of M(address
of count) to the AC
00000110 SUB M(the number 1) Subtract one from AC and store in AC
00100001 STOR M(D) Transfer contents of AC to
location M(D)
00001111 JUMP+ M(X,0:19) If number in accumulator is
non-negative take next
instruction from left half of M(X)
**************************
How do we initialize a variable 'count' to 999??
I am quite new to IAS Instruction set programming. Can anyone please help
me??
I have to write a program using IAS Instruction set for multiplying two
2*2 martix and store the result in another matrix C. I saw a program
posted by another guy for matrix addition
**********************
* Initialize a variable 'count' to 999
Label: TOP
00000001 LOAD M(A[count]) Transfer M(A[count]) to the
accumulator
00000101 ADD M(B[count]) Add M(B[count]) to AC and store
result in AC
00100001 STOR M(C[count]) Transfer contents of accumulator
to memory location C[count]
00001010 LOAD M(address of count) Transfer the contents of M(address
of count) to the AC
00000110 SUB M(the number 1) Subtract one from AC and store in AC
00100001 STOR M(D) Transfer contents of AC to
location M(D)
00001111 JUMP+ M(X,0:19) If number in accumulator is
non-negative take next
instruction from left half of M(X)
**************************
How do we initialize a variable 'count' to 999??
I am quite new to IAS Instruction set programming. Can anyone please help
me??
how to redirect visetors using internet explorer to a specific .html page
how to redirect visetors using internet explorer to a specific .html page
I am busy working on a project wish responsive css and a lot of jquery
targeting css 3 elements it will be ridiculous to make a style sheet for
IE how can i make a redirect for users using IE to a page telling them
there browser sucks?
I am busy working on a project wish responsive css and a lot of jquery
targeting css 3 elements it will be ridiculous to make a style sheet for
IE how can i make a redirect for users using IE to a page telling them
there browser sucks?
Get Windows User ID in ASP.NET
Get Windows User ID in ASP.NET
pI have a ASP.NET application where an employee logs into Windows and then
they have to select their name from a long list of names and log in into
the application./p pWhat I want to do is as soon as the employee opens the
application it selects their name from the drop down box. /p pI believe if
I can get the Windows User Id on page load I can then make my code select
the user depending on the Windows user that is logged in./p pQuestion is.
How do you get Windows User Id that is currently logged in in C# Asp.net?
Any ideas./p
pI have a ASP.NET application where an employee logs into Windows and then
they have to select their name from a long list of names and log in into
the application./p pWhat I want to do is as soon as the employee opens the
application it selects their name from the drop down box. /p pI believe if
I can get the Windows User Id on page load I can then make my code select
the user depending on the Windows user that is logged in./p pQuestion is.
How do you get Windows User Id that is currently logged in in C# Asp.net?
Any ideas./p
How to correctly express a successful job (where others failed) in a cover letter
How to correctly express a successful job (where others failed) in a cover
letter
I was working on a project where the two other person before me failed to
get the job done as expected. Basically that was the reason they hired me,
and fortunately I did it better than expected.
How can I express it in a proper English in a cover letter when I'm
applying for a new job?
Just in the case that it might help, the first person lost the job
(employer didn't renew the contract) however he's still promoting himself
using the project name and saying he were working on the project. The
second person got fired, however he is also doing the same like the other
one.
I think, I have to mention it somehow that it was my effort to make the
project successful, because that could potentially land me the job, but I
really don't know how should I express that that doesn't sound negative,
etc.
P.S. I know that I have to discuss it while they are interviewing me,
however I prefer to increase the chance by putting that in the cover
letter first.
letter
I was working on a project where the two other person before me failed to
get the job done as expected. Basically that was the reason they hired me,
and fortunately I did it better than expected.
How can I express it in a proper English in a cover letter when I'm
applying for a new job?
Just in the case that it might help, the first person lost the job
(employer didn't renew the contract) however he's still promoting himself
using the project name and saying he were working on the project. The
second person got fired, however he is also doing the same like the other
one.
I think, I have to mention it somehow that it was my effort to make the
project successful, because that could potentially land me the job, but I
really don't know how should I express that that doesn't sound negative,
etc.
P.S. I know that I have to discuss it while they are interviewing me,
however I prefer to increase the chance by putting that in the cover
letter first.
Could not load file or assembly
Could not load file or assembly
In my power shell script I am loading a custom assembly and then
instantiating a class of that assembly by New-Object.
Assembly.LoadFile() executes successfully but New-Object statement gives
the bellow exception.
New-Object : Exception calling ".ctor" with "1" argument(s): "Could not
load file or assembly 'MyAssembly, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null' or one of i
ts dependencies. The system cannot find the file specified."
Script:
[System.Reflection.Assembly]::LoadFile("MyAssembly.dll")
$a=New-Object MyAssembly.MyClass -ArgumentList "arg1"
This custom assembly references only the following assemblies
System
System.Core
System.Runtime.Serialization
System.Xml.Linq
System.Data
System.Xml
I tried explicitly loading the System.Runtime.Serialization dll like
below. But same exception
[System.Reflection.Assembly]::Load("System.Runtime.Serialization,
Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
Any idea?
In my power shell script I am loading a custom assembly and then
instantiating a class of that assembly by New-Object.
Assembly.LoadFile() executes successfully but New-Object statement gives
the bellow exception.
New-Object : Exception calling ".ctor" with "1" argument(s): "Could not
load file or assembly 'MyAssembly, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null' or one of i
ts dependencies. The system cannot find the file specified."
Script:
[System.Reflection.Assembly]::LoadFile("MyAssembly.dll")
$a=New-Object MyAssembly.MyClass -ArgumentList "arg1"
This custom assembly references only the following assemblies
System
System.Core
System.Runtime.Serialization
System.Xml.Linq
System.Data
System.Xml
I tried explicitly loading the System.Runtime.Serialization dll like
below. But same exception
[System.Reflection.Assembly]::Load("System.Runtime.Serialization,
Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
Any idea?
Why my sound is mute?
Why my sound is mute?
I have problem with my mac mini, sound icon is mute and i am unable to
click to unmute it.
I have problem with my mac mini, sound icon is mute and i am unable to
click to unmute it.
Get Date from Datetime String
Get Date from Datetime String
This is my String Tue, 20 Aug 2013 10:45:05 and i want to this string in
Date Format Like this :
2013-08-20.
Guys Please help.
Thanks
This is my String Tue, 20 Aug 2013 10:45:05 and i want to this string in
Date Format Like this :
2013-08-20.
Guys Please help.
Thanks
Sunday, 25 August 2013
SSIS disable passing sp parameter
SSIS disable passing sp parameter
I have SSIS package where I have for each loop which runs stored
procedures. The loop containter pases parameters to the stored procedures.
In some cases I need to pass all parametrs to stored procedure and in
other cases I need to pass only one parameter. Is there any way where I
can set if parameter should be passed or not? Maybe will be it possible
using Expression in Loop container?
I have SSIS package where I have for each loop which runs stored
procedures. The loop containter pases parameters to the stored procedures.
In some cases I need to pass all parametrs to stored procedure and in
other cases I need to pass only one parameter. Is there any way where I
can set if parameter should be passed or not? Maybe will be it possible
using Expression in Loop container?
Pass html object through string into function
Pass html object through string into function
What I have is kinda unusual I guess. I have this function deleteItem
which is triggered onclick and has the following parameters
function dItem(type,id,element,confirmed){
if(confirmed){
handle delete function
}else{
var c = ',';
popup('Are you sure you want to delete this item?',
{"Yes":"dItem("+type+c+id+c+element+c+true+")","Cancel":"popupClose()"}
)
}
}
.. onclick='dItem("comment",15,this,false)' ..
In popup()'s second parameter are passed the buttons that are to be
displayed in the popup and the functions they call respectively. The
problem is that element is a HTMLDIV element and I cannot figure out a
neat way to pass that through a string. The only solution I could come to
think of is to have a global variable holding the element in question and
not passing it at all, although I don't really want to do that since it's
more of a hack rather than a solution. Does anybody have any idea how I
can pass that element through a string? Thanks in advance!
What I have is kinda unusual I guess. I have this function deleteItem
which is triggered onclick and has the following parameters
function dItem(type,id,element,confirmed){
if(confirmed){
handle delete function
}else{
var c = ',';
popup('Are you sure you want to delete this item?',
{"Yes":"dItem("+type+c+id+c+element+c+true+")","Cancel":"popupClose()"}
)
}
}
.. onclick='dItem("comment",15,this,false)' ..
In popup()'s second parameter are passed the buttons that are to be
displayed in the popup and the functions they call respectively. The
problem is that element is a HTMLDIV element and I cannot figure out a
neat way to pass that through a string. The only solution I could come to
think of is to have a global variable holding the element in question and
not passing it at all, although I don't really want to do that since it's
more of a hack rather than a solution. Does anybody have any idea how I
can pass that element through a string? Thanks in advance!
No protocol binding matches the given address' error
No protocol binding matches the given address' error
I am using Visual Studio 2008. I created a WCF application and when I ran
the service for the first time from VS IDE (not hosted on IIS), the
service opened in the web browser with the address localhost:1927/. Every
time I run this service from VS IDE, it runs in the same port, i.e 1927
I wanted to change the port number (for some reason), so I gave specific
address localhost:1928 in the web.config file. When I run the web service
in IDE after this change, I keep getting the following error.
No protocol binding matches the given address 'localhost:1928/'. Protocol
bindings are configured at the Site level in IIS or WAS configuration.
Following is the <service> section from the web.config file.
<service name="EMS.ServiceImplementation.EmployeeService"
behaviorConfiguration="EM.EmployeeServiceBehavior" >
<endpoint name="httpEndPoint"
address="http://localhost:1928/"
binding="basicHttpBinding" bindingConfiguration=""
contract="EMS.ServiceContracts.IEmployeeService" />
<endpoint name="MEXEndPoint"
address="mex"
binding="mexHttpBinding" bindingConfiguration=""
contract="IMetadataExchange" />
</service>
My specific questions are:
How does VS IDE run the service always on the same port which it picked in
the first run? Where is this information stored? (I looked through all
files in the solution but I couldn't find port 1927 mentioned anywhere).
How can I make the service run on a different port?
(Please note that, I have seen similar threads in Stackoverflow, but they
relate to service hosted in IIS)`
I am using Visual Studio 2008. I created a WCF application and when I ran
the service for the first time from VS IDE (not hosted on IIS), the
service opened in the web browser with the address localhost:1927/. Every
time I run this service from VS IDE, it runs in the same port, i.e 1927
I wanted to change the port number (for some reason), so I gave specific
address localhost:1928 in the web.config file. When I run the web service
in IDE after this change, I keep getting the following error.
No protocol binding matches the given address 'localhost:1928/'. Protocol
bindings are configured at the Site level in IIS or WAS configuration.
Following is the <service> section from the web.config file.
<service name="EMS.ServiceImplementation.EmployeeService"
behaviorConfiguration="EM.EmployeeServiceBehavior" >
<endpoint name="httpEndPoint"
address="http://localhost:1928/"
binding="basicHttpBinding" bindingConfiguration=""
contract="EMS.ServiceContracts.IEmployeeService" />
<endpoint name="MEXEndPoint"
address="mex"
binding="mexHttpBinding" bindingConfiguration=""
contract="IMetadataExchange" />
</service>
My specific questions are:
How does VS IDE run the service always on the same port which it picked in
the first run? Where is this information stored? (I looked through all
files in the solution but I couldn't find port 1927 mentioned anywhere).
How can I make the service run on a different port?
(Please note that, I have seen similar threads in Stackoverflow, but they
relate to service hosted in IIS)`
Saturday, 24 August 2013
stackoverflow.com/questions/13063268 like routing in asp.net mvc
stackoverflow.com/questions/13063268 like routing in asp.net mvc
I am stil new to ASP.NET MVC routing, I want to achieve stack-overflow
like routing.
For example
http://stackoverflow.com/questions/13063268/are-there-any-responsive-templates-for-asp-net-mvc-3-4/
and
http://stackoverflow.com/questions/13063268/
both redirect to a same action and view. I want to be able to do something
like that I am trying this
routes.MapRoute(
name: "Notes",
url: "Notes/{id}/{ignore}",
defaults: new { controller = "Notes", action = "View", id =
UrlParameter.Optional, ignore = "" }
);
But this does not work. Please help.
I am stil new to ASP.NET MVC routing, I want to achieve stack-overflow
like routing.
For example
http://stackoverflow.com/questions/13063268/are-there-any-responsive-templates-for-asp-net-mvc-3-4/
and
http://stackoverflow.com/questions/13063268/
both redirect to a same action and view. I want to be able to do something
like that I am trying this
routes.MapRoute(
name: "Notes",
url: "Notes/{id}/{ignore}",
defaults: new { controller = "Notes", action = "View", id =
UrlParameter.Optional, ignore = "" }
);
But this does not work. Please help.
Massive RegEx Checking With JavaScript
Massive RegEx Checking With JavaScript
I am tasked with creating a user script for a Wikia wiki that will get the
pages name, and compare it with about 3,000 RegEx strings to find a match,
then adding categories based on what string it matched. I have no idea
where to start, any help?
I am tasked with creating a user script for a Wikia wiki that will get the
pages name, and compare it with about 3,000 RegEx strings to find a match,
then adding categories based on what string it matched. I have no idea
where to start, any help?
Android: Spinner inside Dialog with "text message" when selected
Android: Spinner inside Dialog with "text message" when selected
I'm trying to change my spinner into: Button > Dialog > Spinner.
Works perfectly, but I can't see message when I select:
"You have selected English en-us", "You have selected Português pt-br"
Before:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
if (pos == 0) {
Toast.makeText(parent.getContext(),
"You have selected English en-us",
Toast.LENGTH_SHORT)
.show();
setLocale("en");
} else if (pos == 1) {
Toast.makeText(parent.getContext(),
"You have selected Português pt-br",
Toast.LENGTH_SHORT)
.show();
setLocale("br");
}
}
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
}
public void setLocale(String lang)
{
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
}
My new code:
Button bt_lang = (Button) findViewById(R.bt.language);
bt_lang.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
AlertDialog.Builder builder = new
AlertDialog.Builder(MainActivity.this);
builder.setTitle("Select Language");
builder.setAdapter(adapter, new
DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
AdapterView<?> parent = null;
switch(which)
{
case 0:
setLocale("en");
Toast.makeText(parent.getContext(),
"You have selected English en-us",
Toast.LENGTH_SHORT)
.show();
case 1:
setLocale("br");
Toast.makeText(parent.getContext(),
"Você selecionou Português pt-br",
Toast.LENGTH_SHORT)
.show();
break;
}
dialog.dismiss();
}
});
builder.create();
builder.show();
}
});
}
public void setLocale(String lang)
{
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
}
I'm trying to change my spinner into: Button > Dialog > Spinner.
Works perfectly, but I can't see message when I select:
"You have selected English en-us", "You have selected Português pt-br"
Before:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
if (pos == 0) {
Toast.makeText(parent.getContext(),
"You have selected English en-us",
Toast.LENGTH_SHORT)
.show();
setLocale("en");
} else if (pos == 1) {
Toast.makeText(parent.getContext(),
"You have selected Português pt-br",
Toast.LENGTH_SHORT)
.show();
setLocale("br");
}
}
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
}
public void setLocale(String lang)
{
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
}
My new code:
Button bt_lang = (Button) findViewById(R.bt.language);
bt_lang.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
AlertDialog.Builder builder = new
AlertDialog.Builder(MainActivity.this);
builder.setTitle("Select Language");
builder.setAdapter(adapter, new
DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
AdapterView<?> parent = null;
switch(which)
{
case 0:
setLocale("en");
Toast.makeText(parent.getContext(),
"You have selected English en-us",
Toast.LENGTH_SHORT)
.show();
case 1:
setLocale("br");
Toast.makeText(parent.getContext(),
"Você selecionou Português pt-br",
Toast.LENGTH_SHORT)
.show();
break;
}
dialog.dismiss();
}
});
builder.create();
builder.show();
}
});
}
public void setLocale(String lang)
{
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
}
Create a drop down select box with dynamic options - ios xcode
Create a drop down select box with dynamic options - ios xcode
I am trying to recreate a popular effect that all iPhone users have seen
before on their settings page. Something like when selecting a wireless
network. There is normally a title that says "Available Networks" with a
blue arrow icon to the right. onClick there is an accordion style slide
down effect to reveal the available networks.
I am trying to recreate this to use as a drop down input for my app's
settings page since iPhone does not have anything like that in their
storyboard builder interface. The other issue is the options will be
dynamic (coming from a database).
Has anyone seen a tutorial on this or maybe an open source app I can use
as reference.
I am using iOS 6.1 using Storyboards.
I am trying to recreate a popular effect that all iPhone users have seen
before on their settings page. Something like when selecting a wireless
network. There is normally a title that says "Available Networks" with a
blue arrow icon to the right. onClick there is an accordion style slide
down effect to reveal the available networks.
I am trying to recreate this to use as a drop down input for my app's
settings page since iPhone does not have anything like that in their
storyboard builder interface. The other issue is the options will be
dynamic (coming from a database).
Has anyone seen a tutorial on this or maybe an open source app I can use
as reference.
I am using iOS 6.1 using Storyboards.
Issues with deploying with Capistrano
Issues with deploying with Capistrano
I'm having trouble deploying my Rails app with Capistrano. I keep getting
the connection failed for ec2_domain error.
* 2013-08-24 19:50:51 executing `deploy:setup'
* executing "mkdir -p /home/ubuntu/www/crowdcode
/home/ubuntu/www/crowdcode/releases /home/ubuntu/www/crowdcode/shared
/home/ubuntu/www/crowdcode/shared/system
/home/ubuntu/www/crowdcode/shared/log
/home/ubuntu/www/crowdcode/shared/pids"
servers: [ec2_domain]
connection failed for: ec2_domain (SocketError: getaddrinfo: Name or
service not known)
Here's what's inside of my deploy.rb file.
require "bundler/capistrano"
#set :application, "set your application name here"
set :repository, "https://github.com/path/to/code.git"
set :scm, :git
set :branch, "master"
set :user, "ubuntu"
set :use_sudo, false
set :deploy_to, "/home/ubuntu/www/crowdcode"
# set :scm, :git # You can set :scm explicitly or Capistrano will make an
intelligent guess based on known version control directory names
# Or: `accurev`, `bzr`, `cvs`, `darcs`, `git`, `mercurial`, `perforce`,
`subversion` or `none`
role :web, ec2_domain # Your HTTP server, Apache/etc
role :app, ec2_domain # This may be the same as
your `Web` server
role :db, ec2_domain, :primary => true # This is where Rails migrations
will run
#role :db, "your slave db-server here"
# if you want to clean up old releases on each deploy uncomment this:
# after "deploy:restart", "deploy:cleanup"
# if you're still using the script/reaper helper you will need
# these http://github.com/rails/irs_process_scripts
# If you are using Passenger mod_rails uncomment this:
namespace :deploy do
task :start do ; end
task :stop do ; end
task :restart, :roles => :app, :except => { :no_release => true } do
run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}"
end
end
ssh_options[:keys] = ["/home/ubuntu/.ssh/first_pair.pem"]
ssh_options[:forward_agent] = true
I'm not sure what's causing this error. I've looked at a few tutorials but
can't seem to fix the error. Anyone have an idea as to what the issue
could be?
I'm having trouble deploying my Rails app with Capistrano. I keep getting
the connection failed for ec2_domain error.
* 2013-08-24 19:50:51 executing `deploy:setup'
* executing "mkdir -p /home/ubuntu/www/crowdcode
/home/ubuntu/www/crowdcode/releases /home/ubuntu/www/crowdcode/shared
/home/ubuntu/www/crowdcode/shared/system
/home/ubuntu/www/crowdcode/shared/log
/home/ubuntu/www/crowdcode/shared/pids"
servers: [ec2_domain]
connection failed for: ec2_domain (SocketError: getaddrinfo: Name or
service not known)
Here's what's inside of my deploy.rb file.
require "bundler/capistrano"
#set :application, "set your application name here"
set :repository, "https://github.com/path/to/code.git"
set :scm, :git
set :branch, "master"
set :user, "ubuntu"
set :use_sudo, false
set :deploy_to, "/home/ubuntu/www/crowdcode"
# set :scm, :git # You can set :scm explicitly or Capistrano will make an
intelligent guess based on known version control directory names
# Or: `accurev`, `bzr`, `cvs`, `darcs`, `git`, `mercurial`, `perforce`,
`subversion` or `none`
role :web, ec2_domain # Your HTTP server, Apache/etc
role :app, ec2_domain # This may be the same as
your `Web` server
role :db, ec2_domain, :primary => true # This is where Rails migrations
will run
#role :db, "your slave db-server here"
# if you want to clean up old releases on each deploy uncomment this:
# after "deploy:restart", "deploy:cleanup"
# if you're still using the script/reaper helper you will need
# these http://github.com/rails/irs_process_scripts
# If you are using Passenger mod_rails uncomment this:
namespace :deploy do
task :start do ; end
task :stop do ; end
task :restart, :roles => :app, :except => { :no_release => true } do
run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}"
end
end
ssh_options[:keys] = ["/home/ubuntu/.ssh/first_pair.pem"]
ssh_options[:forward_agent] = true
I'm not sure what's causing this error. I've looked at a few tutorials but
can't seem to fix the error. Anyone have an idea as to what the issue
could be?
How pretend website builtwith Ruby
How pretend website builtwith Ruby
There is a website http://builtwith.com/ which reveals what a website is
built upon. It opens the door for hackers. I have a website built with
laravel. How can I pretend to this website that it is built with ruby?
There is a website http://builtwith.com/ which reveals what a website is
built upon. It opens the door for hackers. I have a website built with
laravel. How can I pretend to this website that it is built with ruby?
how to check if email address is already exist on server?
how to check if email address is already exist on server?
Can you help me to check email if it already exist on server.
I'm using XCode 4.6.3 and I have seen a lot of topics where explained how
to check it through contacts and file manager but didn't found how to
check on server.
Thanks a lot.
Can you help me to check email if it already exist on server.
I'm using XCode 4.6.3 and I have seen a lot of topics where explained how
to check it through contacts and file manager but didn't found how to
check on server.
Thanks a lot.
On Centos Linux Gnome, when you delete "/usr/share/icons/" folder, the default icon becomes blank white for everything, how to modify it?
On Centos Linux Gnome, when you delete "/usr/share/icons/" folder, the
default icon becomes blank white for everything, how to modify it?
I deleted the folder
/usr/share/icons/
now all icons on my centos linux desktop are
blank white. i need to change them so they are
dark gray
is this possible ?
where is this icon located
some said it is not an icon, if so, how can i modify it to
dark gray anyway ?
default icon becomes blank white for everything, how to modify it?
I deleted the folder
/usr/share/icons/
now all icons on my centos linux desktop are
blank white. i need to change them so they are
dark gray
is this possible ?
where is this icon located
some said it is not an icon, if so, how can i modify it to
dark gray anyway ?
golang type conversion not working as (I) expected
golang type conversion not working as (I) expected
I'm using go-flags to parse command line options.
Per the go-flags docs: "... [if] either -h or --help was specified in the
command line arguments, a help message will be automatically printed.
Furthermore, the special error type ErrHelp is returned."
The method I'm calling is:
func (p *Parser) Parse() ([]string, error) {
I'm invoking this with a simple:
args, err := parser.Parse()
A snippet from the file that defines ErrHelp looks like this:
type ErrorType uint
const (
// Unknown or generic error
ErrUnknown ErrorType = iota
// Expected an argument but got none
ErrExpectedArgument
// ...
// The error contains the builtin help message
ErrHelp
// ...
)
// Error represents a parser error. The error returned from Parse is of this
// type. The error contains both a Type and Message.
type Error struct {
// The type of error
Type ErrorType
// The error message
Message string
}
// Get the errors error message.
func (e *Error) Error() string {
return e.Message
}
func newError(tp ErrorType, message string) *Error {
return &Error{
Type: tp,
Message: message,
}
}
So they have this custom "Error" type. And in the Parse() method above,
internally, the error is getting created with a block of code like this:
help.ShowHelp = func() error {
var b bytes.Buffer
p.WriteHelp(&b)
return newError(ErrHelp, b.String())
}
As you can see newError() returns "*Error" as it's type. But the anonymous
function just above returns type "error" - so those types must be
compatible.(?)
But now back to the original problem - I'm just trying to see if my "err"
is an "Error" and has member "Type" equal to ErrHelp. So I try this:
if err != nil && flags.Error(err).Type == flags.ErrHelp {
Or even just this:
fmt.Printf("test:", flags.Error(err))
And either way the compiler gives me:
main.go:37: cannot convert err (type error) to type flags.Error
But does not state why that conversion can't be done. Any ideas?
(I don't get how (*Error) successfully converts to "error" in the
anonymous function above, and I even more don't get why if that works then
I can't convert it back the other way... I must be missing something
really dumb here, but I'm not seeing what it is.)
I'm using go-flags to parse command line options.
Per the go-flags docs: "... [if] either -h or --help was specified in the
command line arguments, a help message will be automatically printed.
Furthermore, the special error type ErrHelp is returned."
The method I'm calling is:
func (p *Parser) Parse() ([]string, error) {
I'm invoking this with a simple:
args, err := parser.Parse()
A snippet from the file that defines ErrHelp looks like this:
type ErrorType uint
const (
// Unknown or generic error
ErrUnknown ErrorType = iota
// Expected an argument but got none
ErrExpectedArgument
// ...
// The error contains the builtin help message
ErrHelp
// ...
)
// Error represents a parser error. The error returned from Parse is of this
// type. The error contains both a Type and Message.
type Error struct {
// The type of error
Type ErrorType
// The error message
Message string
}
// Get the errors error message.
func (e *Error) Error() string {
return e.Message
}
func newError(tp ErrorType, message string) *Error {
return &Error{
Type: tp,
Message: message,
}
}
So they have this custom "Error" type. And in the Parse() method above,
internally, the error is getting created with a block of code like this:
help.ShowHelp = func() error {
var b bytes.Buffer
p.WriteHelp(&b)
return newError(ErrHelp, b.String())
}
As you can see newError() returns "*Error" as it's type. But the anonymous
function just above returns type "error" - so those types must be
compatible.(?)
But now back to the original problem - I'm just trying to see if my "err"
is an "Error" and has member "Type" equal to ErrHelp. So I try this:
if err != nil && flags.Error(err).Type == flags.ErrHelp {
Or even just this:
fmt.Printf("test:", flags.Error(err))
And either way the compiler gives me:
main.go:37: cannot convert err (type error) to type flags.Error
But does not state why that conversion can't be done. Any ideas?
(I don't get how (*Error) successfully converts to "error" in the
anonymous function above, and I even more don't get why if that works then
I can't convert it back the other way... I must be missing something
really dumb here, but I'm not seeing what it is.)
Friday, 23 August 2013
How to save a files contents in Javascript/jQuery
How to save a files contents in Javascript/jQuery
Basically, I want to upload ONLY a CSV file via Javascript or jQuery.
I want to try and do this without any PHP involved.
I need to use a HTML upload form, and then save only it's contents to a
multidimensional array or a string.
I do not need to save the uploaded file to the server, I just need to save
it's contents to a string as stated.
I have looked far and wide online, yet everything involves PHP.
Is this possible with just Javascript or jQuery?
Thanks in advance
Basically, I want to upload ONLY a CSV file via Javascript or jQuery.
I want to try and do this without any PHP involved.
I need to use a HTML upload form, and then save only it's contents to a
multidimensional array or a string.
I do not need to save the uploaded file to the server, I just need to save
it's contents to a string as stated.
I have looked far and wide online, yet everything involves PHP.
Is this possible with just Javascript or jQuery?
Thanks in advance
How to get a fully transparent TabBar in UITabBarController
How to get a fully transparent TabBar in UITabBarController
I have spent the last few hours trying to get the TabBar in a
UITabBarController fully transparent (clear background). I use a custom
subclass of the UITabBarController and I managed to change the tintColor,
the alpha, but the background color definitely remains the one defined in
IB. Thanks for your help, I'm getting crazy...
I have spent the last few hours trying to get the TabBar in a
UITabBarController fully transparent (clear background). I use a custom
subclass of the UITabBarController and I managed to change the tintColor,
the alpha, but the background color definitely remains the one defined in
IB. Thanks for your help, I'm getting crazy...
Need Help for Cold Fusion SessionToken and AIM for Authorize.net
Need Help for Cold Fusion SessionToken and AIM for Authorize.net
I am trying to solve a problem that occurs with Authorize.net. The
SessionToken is generated while in test mode through a test account. Now,
a new SessionToken is generated each time the form is previewed through
the test account or the actual account.
A hidden input field is shown each time when the form is accessed in
preview mode. I have generated a hidden input field on my form by using a
toBase64() string combined from the x_login and the x_tran_key. The output
is this: in the forms hidden input field for SessionToken as you can see
above.
When generating my own SessionToken for processing, the error shown after
trying to process the https://test.authorize.net/gateway/transact.dll
shows this: (46) Your session has expired or does not exist. You must log
in again to continue working.
The only way for the form to actually work is after grabbing the
SessionToken code from the form in preview mode. For example: Go to
Account --> Settings --> Payment Form --> Preview --> and viewing and
copying the code from view frame source. It looks like this:
Finally, if I use the value:
jMsCez2DId$VvgF4s4Hbjbe$Uv6WnJh8cEKBD5HqTUEqlHoRBebKZ07bp4RZdpwOPnGabB3pbcWFppJCph7dg6HjQeroJvlay6mQm5ocjkZPq44uT4nqeg2zWhX13b7Blp$qN7ZDzQ5HF1abfukJTQAA
as the SessionToken as
and process the form it works. But it only works one time for the current
session if signed into the Test Account.
All help is appreciated of course. This is the last part to the code I
need and just can not figure out how to make it work. I need to fetch the
response for the SessionToken to populate the SessionToken hidden field
input on the form.
I am not using the CFHTTP method because the form is on the website and
when the payment form loads the SessionToken is needed. Meaning that the
submit/sending... button on the form is submitted it then processes the
payment and displays the receipt.
I am trying to solve a problem that occurs with Authorize.net. The
SessionToken is generated while in test mode through a test account. Now,
a new SessionToken is generated each time the form is previewed through
the test account or the actual account.
A hidden input field is shown each time when the form is accessed in
preview mode. I have generated a hidden input field on my form by using a
toBase64() string combined from the x_login and the x_tran_key. The output
is this: in the forms hidden input field for SessionToken as you can see
above.
When generating my own SessionToken for processing, the error shown after
trying to process the https://test.authorize.net/gateway/transact.dll
shows this: (46) Your session has expired or does not exist. You must log
in again to continue working.
The only way for the form to actually work is after grabbing the
SessionToken code from the form in preview mode. For example: Go to
Account --> Settings --> Payment Form --> Preview --> and viewing and
copying the code from view frame source. It looks like this:
Finally, if I use the value:
jMsCez2DId$VvgF4s4Hbjbe$Uv6WnJh8cEKBD5HqTUEqlHoRBebKZ07bp4RZdpwOPnGabB3pbcWFppJCph7dg6HjQeroJvlay6mQm5ocjkZPq44uT4nqeg2zWhX13b7Blp$qN7ZDzQ5HF1abfukJTQAA
as the SessionToken as
and process the form it works. But it only works one time for the current
session if signed into the Test Account.
All help is appreciated of course. This is the last part to the code I
need and just can not figure out how to make it work. I need to fetch the
response for the SessionToken to populate the SessionToken hidden field
input on the form.
I am not using the CFHTTP method because the form is on the website and
when the payment form loads the SessionToken is needed. Meaning that the
submit/sending... button on the form is submitted it then processes the
payment and displays the receipt.
Looking for an algorithm to cluster 3d points, around 2d points
Looking for an algorithm to cluster 3d points, around 2d points
I'm trying to cluster photos (GPS + timestamp) around known GPS locations.
3d points = 2d + time stamp.
For example: I walk along the road and take photos of lampposts, some are
interesting and so I take 10 photos and others are not so I don't take
any.
I'd like to cluster my photos around the lampposts, allowing me to see
which lamppost was being photographed.
I've been looking at something like k-means clustering and wanted
something intelligent than just snapping the photos to nearest lamppost.
(I'm going to write the code in javascript for a client side app handing
about (2000,500) points at a time )
I'm trying to cluster photos (GPS + timestamp) around known GPS locations.
3d points = 2d + time stamp.
For example: I walk along the road and take photos of lampposts, some are
interesting and so I take 10 photos and others are not so I don't take
any.
I'd like to cluster my photos around the lampposts, allowing me to see
which lamppost was being photographed.
I've been looking at something like k-means clustering and wanted
something intelligent than just snapping the photos to nearest lamppost.
(I'm going to write the code in javascript for a client side app handing
about (2000,500) points at a time )
Android - Set Text on 'Loading" ProgressBar from strings.xml
Android - Set Text on 'Loading" ProgressBar from strings.xml
I am working on a Live Project. and we are designing it for 2 languages.
So, I have to take each text from strings.xml When I click on any link and
when a view is loading it is showing ProgressDialog showing Loading... The
code for that is,
ProgressDialog dialog =
ProgressDialog.show(HomeScreen_menu.this,"","Loading...", true, false);
but, I want it from from strings.xml
How can I do that?? I tried,
ProgressDialog dialog =
ProgressDialog.show(HomeScreen_menu.this,"",R.string.loading_data, true,
false);
but, It is showing error at R.string.loading_data because it is int value.
Please Help..!
Thank You..:-)
I am working on a Live Project. and we are designing it for 2 languages.
So, I have to take each text from strings.xml When I click on any link and
when a view is loading it is showing ProgressDialog showing Loading... The
code for that is,
ProgressDialog dialog =
ProgressDialog.show(HomeScreen_menu.this,"","Loading...", true, false);
but, I want it from from strings.xml
How can I do that?? I tried,
ProgressDialog dialog =
ProgressDialog.show(HomeScreen_menu.this,"",R.string.loading_data, true,
false);
but, It is showing error at R.string.loading_data because it is int value.
Please Help..!
Thank You..:-)
Django Ajax-Jquery does not fetch the data
Django Ajax-Jquery does not fetch the data
I am not able to get the input text field data with id city_name from the
form via jQuery-Ajax method.
The error that I keeps getting is "NetworkError: 403 FORBIDDEN -
http://127.0.0.1:8000/dashboard".
I know how to get the data using hidden field type, but that option cannot
be used here and moreover, getting data from hidden field is now an
outdated method. So, how can I get data using Django-AjaxJquery method.
HTML
<form type = "POST">
{% csrf_token %}
<input type="text" placeholder = "Enter City Name" id =
"city_name">
<input type="button" value = "On" id="on">
<input type="button" value = "Off" id="off">
<input type="submit" value="Submit">
</form>
JS File
$(function(){
$("#on").click(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "dashboard",
data : {
'city_name' : $("#city_name").val(),
},
});
});
});
View.py
@login_required
def dashboard(request):
ctx = {}
if request.is_ajax():
city_name = request.POST['city_name']
print city_name
return render_to_response('dashboard/dashboard.html',ctx,
context_instance = RequestContext(request))
urls.py
urlpatterns = patterns('',
url(r'^dashboard$','apps.dashboard.views.dashboard', name =
'llumpps_dashboard'),
)
I am not able to get the input text field data with id city_name from the
form via jQuery-Ajax method.
The error that I keeps getting is "NetworkError: 403 FORBIDDEN -
http://127.0.0.1:8000/dashboard".
I know how to get the data using hidden field type, but that option cannot
be used here and moreover, getting data from hidden field is now an
outdated method. So, how can I get data using Django-AjaxJquery method.
HTML
<form type = "POST">
{% csrf_token %}
<input type="text" placeholder = "Enter City Name" id =
"city_name">
<input type="button" value = "On" id="on">
<input type="button" value = "Off" id="off">
<input type="submit" value="Submit">
</form>
JS File
$(function(){
$("#on").click(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "dashboard",
data : {
'city_name' : $("#city_name").val(),
},
});
});
});
View.py
@login_required
def dashboard(request):
ctx = {}
if request.is_ajax():
city_name = request.POST['city_name']
print city_name
return render_to_response('dashboard/dashboard.html',ctx,
context_instance = RequestContext(request))
urls.py
urlpatterns = patterns('',
url(r'^dashboard$','apps.dashboard.views.dashboard', name =
'llumpps_dashboard'),
)
Thursday, 22 August 2013
how to serialize a blob javascript
how to serialize a blob javascript
I need to serialize some blobs to send to php. I also want to be able to
unserialize it when the php script sends it back. JSON does not stringify
the contents of the blob, just metadata like the name, size, etc. How can
I do this?
I need to serialize some blobs to send to php. I also want to be able to
unserialize it when the php script sends it back. JSON does not stringify
the contents of the blob, just metadata like the name, size, etc. How can
I do this?
ec2 logs say ImportError: No module named requests, yet it's installed
ec2 logs say ImportError: No module named requests, yet it's installed
In my ec2 instance, I run pip freeze | grep requests, which prints
requests==0.13.5. Yet when I run my server with python application.py, the
server hangs, and when I snapshot the logs, I see this error: ImportError:
No module named requests
In my ec2 instance, when I run python and call import requests, it imports
it just fine. What's preventing my flask application from seeing the
requests module?
In my ec2 instance, I run pip freeze | grep requests, which prints
requests==0.13.5. Yet when I run my server with python application.py, the
server hangs, and when I snapshot the logs, I see this error: ImportError:
No module named requests
In my ec2 instance, when I run python and call import requests, it imports
it just fine. What's preventing my flask application from seeing the
requests module?
Would lots of idle clients cause a "service too busy" exception?
Would lots of idle clients cause a "service too busy" exception?
I have a WCF service that has an instance mode of Single and a concurrency
mode of Multiple. I have the following code:
public static ICmsDataServiceWcf data
{
get
{
if (HttpContext.Current != null && HttpContext.Current.Session
!= null && HttpContext.Current.Session["DataService"] == null)
{
HttpContext.Current.Session.Add("DataService",
GetDataService());
}
if (HttpContext.Current != null && HttpContext.Current.Session
!= null && HttpContext.Current.Session["DataService"] != null)
{
return
(ICmsDataServiceWcf)HttpContext.Current.Session["DataService"];
}
return GetDataService();
}
}
The idea is that every client gets their own WCF client which only blocks
for their requests and I don't have to suffer the overhead of
creating/destroying clients multiple times.
Recently I have been getting some "service too busy" exceptions. Most of
these clients are sat idle most of the time. Does an idle client still
consume resources on the server? Is its instance persisted somehow server
side?
Can anyone see a reason why this could cause issues? (Except for the
memory wastage of letting lots of clients sit around until sessions get
abandoned - I'm looking at using a pool of clients and periodically
culling inactive/errored ones.)
Thanks,
Joe
I have a WCF service that has an instance mode of Single and a concurrency
mode of Multiple. I have the following code:
public static ICmsDataServiceWcf data
{
get
{
if (HttpContext.Current != null && HttpContext.Current.Session
!= null && HttpContext.Current.Session["DataService"] == null)
{
HttpContext.Current.Session.Add("DataService",
GetDataService());
}
if (HttpContext.Current != null && HttpContext.Current.Session
!= null && HttpContext.Current.Session["DataService"] != null)
{
return
(ICmsDataServiceWcf)HttpContext.Current.Session["DataService"];
}
return GetDataService();
}
}
The idea is that every client gets their own WCF client which only blocks
for their requests and I don't have to suffer the overhead of
creating/destroying clients multiple times.
Recently I have been getting some "service too busy" exceptions. Most of
these clients are sat idle most of the time. Does an idle client still
consume resources on the server? Is its instance persisted somehow server
side?
Can anyone see a reason why this could cause issues? (Except for the
memory wastage of letting lots of clients sit around until sessions get
abandoned - I'm looking at using a pool of clients and periodically
culling inactive/errored ones.)
Thanks,
Joe
Qt: Connect casted sender to a receiver
Qt: Connect casted sender to a receiver
In my program, I have a QTableView which is set to display
QStandardItemModel. I want to connect Model's
itemChanged(QStandardItem*)
Signal to my SLOT. I did
connect(dynamic_cast<QStandardItemModel*>(ui->tableView->model()),
SIGNAL(itemChanged(QStandardItem*)), this,
SLOT(saveItem(QStandardItem*)));
But this always fails to connect (returns false). I am guessing it is
because of dynamic_cast but I am not sure.
What am I doing wrong??
In my program, I have a QTableView which is set to display
QStandardItemModel. I want to connect Model's
itemChanged(QStandardItem*)
Signal to my SLOT. I did
connect(dynamic_cast<QStandardItemModel*>(ui->tableView->model()),
SIGNAL(itemChanged(QStandardItem*)), this,
SLOT(saveItem(QStandardItem*)));
But this always fails to connect (returns false). I am guessing it is
because of dynamic_cast but I am not sure.
What am I doing wrong??
Apache: fall through to controller if matching file not found
Apache: fall through to controller if matching file not found
We have a Perl based web site that runs under Apache with mod_perl. At its
core are a large number of individual Perl scripts - one per page. For
example:
www.example.com/index.pl
www.example.com/account.pl
www.example.com/login.pl
We are slowly refactoring it and moving towards a controlled based model
where we have a single point of entry - a dispatcher. The current approach
is to replace the code in each page script with a call to the controller
as it is refactored. This leaves us with lots of stub scripts that all do
the same thing. Is there a way to tell Apache to look for a matching file
first, and if that fails, call the controller code and pass it the request
URI?
We have a Perl based web site that runs under Apache with mod_perl. At its
core are a large number of individual Perl scripts - one per page. For
example:
www.example.com/index.pl
www.example.com/account.pl
www.example.com/login.pl
We are slowly refactoring it and moving towards a controlled based model
where we have a single point of entry - a dispatcher. The current approach
is to replace the code in each page script with a call to the controller
as it is refactored. This leaves us with lots of stub scripts that all do
the same thing. Is there a way to tell Apache to look for a matching file
first, and if that fails, call the controller code and pass it the request
URI?
Wednesday, 21 August 2013
Cassandra GUI tool -- Helenos does not return value when I query
Cassandra GUI tool -- Helenos does not return value when I query
I have installed the Helenos successfully according to
https://github.com/tomekkup/helenos.
But when I use cql to query, I got nothing. Anyone can help me ? thanks!
I have installed the Helenos successfully according to
https://github.com/tomekkup/helenos.
But when I use cql to query, I got nothing. Anyone can help me ? thanks!
create javascript object (with key pairs) from json (not in correct key pair)
create javascript object (with key pairs) from json (not in correct key pair)
I don't know how to extract key/values from a json array to hook them into
different parts of a javascript array.
E.g. I have 2 json arrays which looks like this:
series 1:
{"label1":"91970","label2":"1231", ... "labeln": "somenumbers".}
series 2:
{"label1":"4556","label2":"3434", ....}
I would like to transform both of them to 1 javascript object (for nvd3
plotting) like this:
long_short_data = [
{
key: 'Series1',
color: '#d62728',
values: [
{
"cell" : "label1" ,
"value" : 91970
} ,
{
"cell" : "label2" ,
"value" : 1231
} ,
.....
]
},
{
key: 'Series2',
color: '#1f77b4',
values: [
{
"cell" : "label1" ,
"value" : 4556
} ,
{
"cell" : "label2" ,
"value" : 3434
} ,
...
}
]
}
];
Appreciate your help.
I don't know how to extract key/values from a json array to hook them into
different parts of a javascript array.
E.g. I have 2 json arrays which looks like this:
series 1:
{"label1":"91970","label2":"1231", ... "labeln": "somenumbers".}
series 2:
{"label1":"4556","label2":"3434", ....}
I would like to transform both of them to 1 javascript object (for nvd3
plotting) like this:
long_short_data = [
{
key: 'Series1',
color: '#d62728',
values: [
{
"cell" : "label1" ,
"value" : 91970
} ,
{
"cell" : "label2" ,
"value" : 1231
} ,
.....
]
},
{
key: 'Series2',
color: '#1f77b4',
values: [
{
"cell" : "label1" ,
"value" : 4556
} ,
{
"cell" : "label2" ,
"value" : 3434
} ,
...
}
]
}
];
Appreciate your help.
socket error using boto with Jython
socket error using boto with Jython
I'm in the process of porting a project originally done in CPython over to
Jython in order to leverage some java libraries. Things seem to be working
fine except that for some reason I'm getting errors when trying to connect
to s3 with boto:
>>> from boto.s3.connection import S3Connection
>>> s3 = S3Connection(aws_access_id, aws_secret_key)
>>> s3.get_all_buckets()
File "<stdin>", line 1, in <module>
File "/usr/share/jython/Lib/site-packages/boto/s3/connection.py", line
384, in
body = response.read()
File "/usr/share/jython/Lib/site-packages/boto/connection.py", line 411,
in rea
self._cached_response = httplib.HTTPResponse.read(self)
File "/usr/share/jython/Lib/httplib.py", line 546, in read
s = self.fp.read()
File "/usr/share/jython/Lib/httplib.py", line 1296, in read
return s + self._file.read()
File "/usr/share/jython/Lib/socket.py", line 1672, in read
data = self._sock.recv(recv_size)
File "/usr/share/jython/Lib/socket.py", line 180, in set_last_error
return method(obj, *args, **kwargs)
File "/usr/share/jython/Lib/socket.py", line 171, in map_exception
raise _map_exception(jlx)
socket.error: [Errno 104] Software caused connection abort
Running the exact same connection code in CPython works perfectly. I've
tried forcing boto to log debug messages, but they are the exact same
between Jython and CPython until the Jython one fails. Has anyone run into
this before or have any suggestions for debugging this further?
I'm in the process of porting a project originally done in CPython over to
Jython in order to leverage some java libraries. Things seem to be working
fine except that for some reason I'm getting errors when trying to connect
to s3 with boto:
>>> from boto.s3.connection import S3Connection
>>> s3 = S3Connection(aws_access_id, aws_secret_key)
>>> s3.get_all_buckets()
File "<stdin>", line 1, in <module>
File "/usr/share/jython/Lib/site-packages/boto/s3/connection.py", line
384, in
body = response.read()
File "/usr/share/jython/Lib/site-packages/boto/connection.py", line 411,
in rea
self._cached_response = httplib.HTTPResponse.read(self)
File "/usr/share/jython/Lib/httplib.py", line 546, in read
s = self.fp.read()
File "/usr/share/jython/Lib/httplib.py", line 1296, in read
return s + self._file.read()
File "/usr/share/jython/Lib/socket.py", line 1672, in read
data = self._sock.recv(recv_size)
File "/usr/share/jython/Lib/socket.py", line 180, in set_last_error
return method(obj, *args, **kwargs)
File "/usr/share/jython/Lib/socket.py", line 171, in map_exception
raise _map_exception(jlx)
socket.error: [Errno 104] Software caused connection abort
Running the exact same connection code in CPython works perfectly. I've
tried forcing boto to log debug messages, but they are the exact same
between Jython and CPython until the Jython one fails. Has anyone run into
this before or have any suggestions for debugging this further?
Send checkboxes values from a view to a controller in two steps?
Send checkboxes values from a view to a controller in two steps?
Let's say I've a two vanilla* html checkboxes in a Razor cshtml view.
<input type="checkbox" name="tags[]" id="categorieOne" value="1">
<input type="checkbox" name="tags[]" id="categorieTwo" value="2">
The first step would be to send this tags[] array to a controller.
The second step would be to get values 1 & 2 in seperated variables
(example: in order to show "You've selected the following categories 1 ...
2" )
*By vanilla I mean they are not written with razor.
Let's say I've a two vanilla* html checkboxes in a Razor cshtml view.
<input type="checkbox" name="tags[]" id="categorieOne" value="1">
<input type="checkbox" name="tags[]" id="categorieTwo" value="2">
The first step would be to send this tags[] array to a controller.
The second step would be to get values 1 & 2 in seperated variables
(example: in order to show "You've selected the following categories 1 ...
2" )
*By vanilla I mean they are not written with razor.
Android: Is it possible to have two surfaceview on top of each other?
Android: Is it possible to have two surfaceview on top of each other?
My idea is to have two surfaceViews. One surfaceView which will hold an
image (say ImageSurgaceView) and second surface that lie on top of the
first one which holds the annotations (say AnnotationSurfaceView) like
circle, rectangle etc. Now I have to map these surface views such that the
height, width are same and moreover, both the surface view should move on
drag i.e share the touch events. To be precise, when I move the image up
the annotations should also move up.
Now, I am not sure if this is possible in android. Can any one tell or
share some info on this. I don't have any implementation idea to this and
hence I don't have any specific code. Moreover, I couldn't find anything
similar.
Thanks for helping.
My idea is to have two surfaceViews. One surfaceView which will hold an
image (say ImageSurgaceView) and second surface that lie on top of the
first one which holds the annotations (say AnnotationSurfaceView) like
circle, rectangle etc. Now I have to map these surface views such that the
height, width are same and moreover, both the surface view should move on
drag i.e share the touch events. To be precise, when I move the image up
the annotations should also move up.
Now, I am not sure if this is possible in android. Can any one tell or
share some info on this. I don't have any implementation idea to this and
hence I don't have any specific code. Moreover, I couldn't find anything
similar.
Thanks for helping.
Click Event Never Called (but copy/paste works) in Content Script
Click Event Never Called (but copy/paste works) in Content Script
I'm writing a very simple chrome extension, and I can't seem to get a
click event to work.
This is the part of the script I'm having trouble with. I tried the native
addEventListener, and the jQuery version.
var $btn = $('<button>');
$btn.text(fix.name);
$btn.appendTo($buttonContainer);
$btn.on("click", function() {
alert("abc");
}
Preemptive Q&A:
Is this code ever reached?
This code is being reached, tested by alerts and the fact that I can see
the button. Is there some difference between normal JavaScript and chrome
extensions that would cause this?
Are there any errors in your console?
I don't have any errors in my console. jQuery is included in my content
scripts, and is apparently existent, based on the buttons showing up.
What does this have to do with chrome extensions?
I believe it's a difference between a usual script, and a content script
because I can copy and paste my entire content script into the developer
console, and it works as expected.
Where's the rest of the code?
The entire code may be found on PasteBin, and the CoffeeScript source.
I'll update the question later if I didn't include a relevant portion of
the code.
What Chrome version?
29.0.1547.49 beta.
What about...?
Please ask :-)
I'm writing a very simple chrome extension, and I can't seem to get a
click event to work.
This is the part of the script I'm having trouble with. I tried the native
addEventListener, and the jQuery version.
var $btn = $('<button>');
$btn.text(fix.name);
$btn.appendTo($buttonContainer);
$btn.on("click", function() {
alert("abc");
}
Preemptive Q&A:
Is this code ever reached?
This code is being reached, tested by alerts and the fact that I can see
the button. Is there some difference between normal JavaScript and chrome
extensions that would cause this?
Are there any errors in your console?
I don't have any errors in my console. jQuery is included in my content
scripts, and is apparently existent, based on the buttons showing up.
What does this have to do with chrome extensions?
I believe it's a difference between a usual script, and a content script
because I can copy and paste my entire content script into the developer
console, and it works as expected.
Where's the rest of the code?
The entire code may be found on PasteBin, and the CoffeeScript source.
I'll update the question later if I didn't include a relevant portion of
the code.
What Chrome version?
29.0.1547.49 beta.
What about...?
Please ask :-)
Tuesday, 20 August 2013
what is the right way to get request's ip
what is the right way to get request's ip
I find some different ways to get ip in servlet. but i don't know which
one is rigth and why.
1:request.getHeader( "X-Real-IP" )
2:String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
3:String ip=request.getHeader("x-forwarded-for"); if(ip==null){
ip=request.getRemoteAddr(); } String ips[]=ip.split(","); ip=ips[0];
4:request.getRemoteAddr() request.getHeader("X-Forwarded-For")
request.getHeader("Client-IP")
I find some different ways to get ip in servlet. but i don't know which
one is rigth and why.
1:request.getHeader( "X-Real-IP" )
2:String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
3:String ip=request.getHeader("x-forwarded-for"); if(ip==null){
ip=request.getRemoteAddr(); } String ips[]=ip.split(","); ip=ips[0];
4:request.getRemoteAddr() request.getHeader("X-Forwarded-For")
request.getHeader("Client-IP")
Message: Missing argument 2 for ::__construct(),
Message: Missing argument 2 for ::__construct(),
I have a codeigniter constructor that begins like:
public function __construct($login, $pass)
I'm trying to pass parameters to it in my controller like so:
$params = array(1=>'xxx',2 =>'yyy');
$this->load->library('my_library',$params);
but I'm getting:
Message: Missing argument 2 for my_library::__construct(),
How can I fix this?
I have a codeigniter constructor that begins like:
public function __construct($login, $pass)
I'm trying to pass parameters to it in my controller like so:
$params = array(1=>'xxx',2 =>'yyy');
$this->load->library('my_library',$params);
but I'm getting:
Message: Missing argument 2 for my_library::__construct(),
How can I fix this?
Wrapping Standard HTTP Exceptions in Custom Response Using ResponseEntityExceptionHandler
Wrapping Standard HTTP Exceptions in Custom Response Using
ResponseEntityExceptionHandler
Background
I am creating a restful web service using Spring MVC 3.2.1.RELEASE. I
would like to be able to wrap the standard HTTP errors (400, 404, 500,
etc.) handled by the default exception handler resolvers with my own
response bodies and have those responses processed by MessageConverters
like any other response.
Example:
I would like my api to return the following for a 404 instead of the
standard message:
{
"status" : 404,
"message" : "The requested resource could not be found."
}
I have extended ResponseEntityExceptionHandler and overridden the
exception handling methods that I am interested in, but I cannot get
Spring to call my exception handler.
Question
How can I get Spring to call my subclass of ResponseEntityExceptionHandler?
What I Have Tried
I have implemented a custom exception handler that extends
ResponseEntityExceptionHandler and annotated it with @ControllerAdvice
@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object>
handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException
ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
ErrorMessage errorMessage = new ErrorMessage("The requested
resource could not be found.");
return new ResponseEntity<Object>(errorMessage,
HttpStatus.NOT_FOUND);
}
}
Based on the following quote in the javadocs for
ResponseEntityExceptionHandler
Note that in order for an {@code @ControllerAdvice} sub-class to be
detected, {@link ExceptionHandlerExceptionResolver} must be configured.
I added the following method to my Spring config:
@Configuration
@ComponentScan(basePackages = {"foo.app", "foo.app.common"})
@ImportResource({"classpath*:/foo-core-config.xml",
"classpath*:/applicationContext.xml"})
@PropertySource("classpath:env-config.properties")
public class FooAppConfiguration extends WebMvcConfigurationSupport
implements EnvironmentAware {
@Override
protected void
configureHandlerExceptionResolvers(List<HandlerExceptionResolver>
exceptionResolvers) {
ExceptionHandlerExceptionResolver resolver = new
ExceptionHandlerExceptionResolver();
resolver.setMessageConverters(getMessageConverters());
resolver.setOrder(Integer.MIN_VALUE);
resolver.setMappedHandlerClasses(new
Class[]{MyExceptionHandler.class});
exceptionResolvers.add(resolver);
}
}
ResponseEntityExceptionHandler
Background
I am creating a restful web service using Spring MVC 3.2.1.RELEASE. I
would like to be able to wrap the standard HTTP errors (400, 404, 500,
etc.) handled by the default exception handler resolvers with my own
response bodies and have those responses processed by MessageConverters
like any other response.
Example:
I would like my api to return the following for a 404 instead of the
standard message:
{
"status" : 404,
"message" : "The requested resource could not be found."
}
I have extended ResponseEntityExceptionHandler and overridden the
exception handling methods that I am interested in, but I cannot get
Spring to call my exception handler.
Question
How can I get Spring to call my subclass of ResponseEntityExceptionHandler?
What I Have Tried
I have implemented a custom exception handler that extends
ResponseEntityExceptionHandler and annotated it with @ControllerAdvice
@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object>
handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException
ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
ErrorMessage errorMessage = new ErrorMessage("The requested
resource could not be found.");
return new ResponseEntity<Object>(errorMessage,
HttpStatus.NOT_FOUND);
}
}
Based on the following quote in the javadocs for
ResponseEntityExceptionHandler
Note that in order for an {@code @ControllerAdvice} sub-class to be
detected, {@link ExceptionHandlerExceptionResolver} must be configured.
I added the following method to my Spring config:
@Configuration
@ComponentScan(basePackages = {"foo.app", "foo.app.common"})
@ImportResource({"classpath*:/foo-core-config.xml",
"classpath*:/applicationContext.xml"})
@PropertySource("classpath:env-config.properties")
public class FooAppConfiguration extends WebMvcConfigurationSupport
implements EnvironmentAware {
@Override
protected void
configureHandlerExceptionResolvers(List<HandlerExceptionResolver>
exceptionResolvers) {
ExceptionHandlerExceptionResolver resolver = new
ExceptionHandlerExceptionResolver();
resolver.setMessageConverters(getMessageConverters());
resolver.setOrder(Integer.MIN_VALUE);
resolver.setMappedHandlerClasses(new
Class[]{MyExceptionHandler.class});
exceptionResolvers.add(resolver);
}
}
BC not handling scale = 0 correctly
BC not handling scale = 0 correctly
I defined the cbrt function to return a cube root. I need to get an
integer back (even if it is close to the cube root, it will be acceptable
in my case). However, when I put the scale as 0 to get an integer, I get
numbers which are grossly incorrect. What is going on and how do I get an
integer cube root out?
bc -l
define cbrt(x) { return e(l(x)/3) }
scale=1;cbrt(1000000)
99.4
scale=0;cbrt(1000000)
54
I defined the cbrt function to return a cube root. I need to get an
integer back (even if it is close to the cube root, it will be acceptable
in my case). However, when I put the scale as 0 to get an integer, I get
numbers which are grossly incorrect. What is going on and how do I get an
integer cube root out?
bc -l
define cbrt(x) { return e(l(x)/3) }
scale=1;cbrt(1000000)
99.4
scale=0;cbrt(1000000)
54
extract html templates in js tree with brunch compiler
extract html templates in js tree with brunch compiler
I have an AngularJS project that I moved to brunch recently where all the
templates are stored in side the javascript tree.
example:
js/
-- main/
----main.js
----main.html
--sub/
----sub,js
----sub.html
I haven't been able to figure out how to configure Brunch.io to extract
the html files from the js tree and publish them under public/
As a workaround I copied the js tree in assets and removed all the js files.
I'd like to keep the templates with the js files if possible.
I have an AngularJS project that I moved to brunch recently where all the
templates are stored in side the javascript tree.
example:
js/
-- main/
----main.js
----main.html
--sub/
----sub,js
----sub.html
I haven't been able to figure out how to configure Brunch.io to extract
the html files from the js tree and publish them under public/
As a workaround I copied the js tree in assets and removed all the js files.
I'd like to keep the templates with the js files if possible.
Jquery: return: false on submit not working - form still submits
Jquery: return: false on submit not working - form still submits
Is there a reason that the form is still submitting? The validation checks
work but if it everything is input correctly, the form submits and the
ajax request does not fire.
$("#formRegister").submit(function () {
var username = $("#registerUsername").val();
var password = $("#registerPassword").val();
var passwordConfirm = $("#registerPasswordConfirm").val();
var avatar = $("#registerAvatar").val();
if (username == 'Username') {
$("#registerError").html('You must enter a username');
} else if (password == 'Password') {
$("#registerError").html('You must enter a password');
} else if (password != passwordConfirm) {
$("#registerError").html('Your passwords did not match');
} else if (avatar == 'Avatar URL') {
$("#registerError").html('You must enter the URL for your combine
avatar');
} else {
$.ajax({
type: "POST",
url: "processUsers.php",
data: {
mode: mode,
username: username,
password: password,
avatar: avatar
},
dataType: "JSON",
success: function(data) {
alert('success!');
}
});
}
return false;
});
Is there a reason that the form is still submitting? The validation checks
work but if it everything is input correctly, the form submits and the
ajax request does not fire.
$("#formRegister").submit(function () {
var username = $("#registerUsername").val();
var password = $("#registerPassword").val();
var passwordConfirm = $("#registerPasswordConfirm").val();
var avatar = $("#registerAvatar").val();
if (username == 'Username') {
$("#registerError").html('You must enter a username');
} else if (password == 'Password') {
$("#registerError").html('You must enter a password');
} else if (password != passwordConfirm) {
$("#registerError").html('Your passwords did not match');
} else if (avatar == 'Avatar URL') {
$("#registerError").html('You must enter the URL for your combine
avatar');
} else {
$.ajax({
type: "POST",
url: "processUsers.php",
data: {
mode: mode,
username: username,
password: password,
avatar: avatar
},
dataType: "JSON",
success: function(data) {
alert('success!');
}
});
}
return false;
});
PHPFox, I'am working on phpfox theme
PHPFox, I'am working on phpfox theme
I am working on PHPFox theme, I need to change theme, as this theme
"http://nerby.com/project/facebook/", but I have many problems: 1- after
you login, and go to profile page, the posts sorted as Metro UI design. I
need plugin, that can help me to do this.
2- other problem, in signup page, I can't retrieve error messages, if user
enter an empty field or has problem with password, etc ...
Site: http://entrypost.com/.
Thanks
I am working on PHPFox theme, I need to change theme, as this theme
"http://nerby.com/project/facebook/", but I have many problems: 1- after
you login, and go to profile page, the posts sorted as Metro UI design. I
need plugin, that can help me to do this.
2- other problem, in signup page, I can't retrieve error messages, if user
enter an empty field or has problem with password, etc ...
Site: http://entrypost.com/.
Thanks
Monday, 19 August 2013
Change Vertex massive in Renderer class from MainActivity onTouchEvent
Change Vertex massive in Renderer class from MainActivity onTouchEvent
i am newbie in android developement and thi is my question, how i can
change Vertex massive inside class "MainRenderer" inside class "Ship" from
MainActivity onTouchEvent?
Here is my code: MainActivity.java:
package com.example.galaga2d;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.app.Activity;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
public class MainActivity extends Activity {
//private boolean isTouch = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Óáèðàåì òàéòë ïðèëîæåíèÿ, òîáèøü äåëàåì åãî FullScreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Ñîçäà¸ì íîâûé Surface è óñòàíàâëèâàåì MainRenderer
GLSurfaceView view = new GLSurfaceView(this);
view.setRenderer(new MainRenderer());
view.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
setContentView(view);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int X = (int) event.getX();
int Y = (int) event.getY();
int upX = (int) event.getX();
int upY = (int) event.getY();
int downX = (int) event.getX();
int downY = (int) event.getY();
int eventaction = event.getAction();
switch (eventaction) {
case MotionEvent.ACTION_DOWN:
Toast.makeText(this, "ÂÍÈÇ "+"X: "+X+" Y: "+Y,
Toast.LENGTH_SHORT).show();
break;
case MotionEvent.ACTION_MOVE:
Toast.makeText(this, "ÄÂÈÆÅÍÈÅ "+"X: "+X+" Y: "+Y,
Toast.LENGTH_SHORT).show();
break;
case MotionEvent.ACTION_UP:
Toast.makeText(this, "ÂÂÅÐÕ "+"X: "+X+" Y: "+Y,
Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
and MainRenderer.java:
package com.example.galaga2d;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.ByteOrder;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView.Renderer;
public class MainRenderer implements Renderer {
public int playerSize = 0;
private Ship playerShip = new Ship();
private Astedoid enemyAstedoid = new Astedoid();
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
gl.glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
}
@Override
public void onDrawFrame(GL10 gl) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
playerShip.draw(gl);
enemyAstedoid.draw(gl);
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(0, width, height, 0, 1, -1);
gl.glMatrixMode(GL10.GL_MODELVIEW);
}
//
--------------------------------------------------------------------------------
class Ship {
public int health = 100;
public int life = 3;
public FloatBuffer ShipVertexBuffer;
public float ShipVerticles[] = {
5, 5, // ëåâî íèç
5, 10, // ëåâî ââåðõ
10, 5, // ïðàâî íèç
10, 10 // ïðàâî ââåðõ
};
public Ship() {
ByteBuffer bb = ByteBuffer.allocateDirect(36);
bb.order(ByteOrder.nativeOrder());
ShipVertexBuffer = bb.asFloatBuffer();
ShipVertexBuffer.put(ShipVerticles);
ShipVertexBuffer.position(0);
}
public void draw(GL10 gl) {
gl.glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, ShipVertexBuffer);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
}
}
class Astedoid {
public int health = 100;
public int life = 3;
public FloatBuffer AsteroidColorBuffer;
public FloatBuffer AsteroidVertexBuffer;
public float AsteroidVerticles[] = {
25, 25, // ëåâî íèç
25, 30, // ëåâî ââåðõ
30, 25, // ïðàâî íèç
30, 30 // ïðàâî ââåðõ
};
public Astedoid() {
ByteBuffer bb = ByteBuffer.allocateDirect(36);
bb.order(ByteOrder.nativeOrder());
AsteroidVertexBuffer = bb.asFloatBuffer();
AsteroidVertexBuffer.put(AsteroidVerticles);
AsteroidVertexBuffer.position(0);
}
public void draw(GL10 gl) {
gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, AsteroidVertexBuffer);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
}
}
//
--------------------------------------------------------------------------------
}
I want do this, create some variable like "objectSize" and give it some
value 5 in main activity onTouchEvent on "case MotionEvent.ACTION_DOWN",
for example:
case MotionEvent.ACTION_DOWN:
objectSize = 5;
break;
than i want to use this variable to change size of drawing object in
MainRenderer in class Ship, for example:
public float ShipVerticles[] = {
5*objectSize , 5*objectSize,
5*objectSize, 10*objectSize,
10*objectSize, 5*objectSize,
10*objectSize, 10*objectSize
};
How i can do this? Thx!
i am newbie in android developement and thi is my question, how i can
change Vertex massive inside class "MainRenderer" inside class "Ship" from
MainActivity onTouchEvent?
Here is my code: MainActivity.java:
package com.example.galaga2d;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.app.Activity;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
public class MainActivity extends Activity {
//private boolean isTouch = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Óáèðàåì òàéòë ïðèëîæåíèÿ, òîáèøü äåëàåì åãî FullScreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Ñîçäà¸ì íîâûé Surface è óñòàíàâëèâàåì MainRenderer
GLSurfaceView view = new GLSurfaceView(this);
view.setRenderer(new MainRenderer());
view.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
setContentView(view);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int X = (int) event.getX();
int Y = (int) event.getY();
int upX = (int) event.getX();
int upY = (int) event.getY();
int downX = (int) event.getX();
int downY = (int) event.getY();
int eventaction = event.getAction();
switch (eventaction) {
case MotionEvent.ACTION_DOWN:
Toast.makeText(this, "ÂÍÈÇ "+"X: "+X+" Y: "+Y,
Toast.LENGTH_SHORT).show();
break;
case MotionEvent.ACTION_MOVE:
Toast.makeText(this, "ÄÂÈÆÅÍÈÅ "+"X: "+X+" Y: "+Y,
Toast.LENGTH_SHORT).show();
break;
case MotionEvent.ACTION_UP:
Toast.makeText(this, "ÂÂÅÐÕ "+"X: "+X+" Y: "+Y,
Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
and MainRenderer.java:
package com.example.galaga2d;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.ByteOrder;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView.Renderer;
public class MainRenderer implements Renderer {
public int playerSize = 0;
private Ship playerShip = new Ship();
private Astedoid enemyAstedoid = new Astedoid();
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
gl.glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
}
@Override
public void onDrawFrame(GL10 gl) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
playerShip.draw(gl);
enemyAstedoid.draw(gl);
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(0, width, height, 0, 1, -1);
gl.glMatrixMode(GL10.GL_MODELVIEW);
}
//
--------------------------------------------------------------------------------
class Ship {
public int health = 100;
public int life = 3;
public FloatBuffer ShipVertexBuffer;
public float ShipVerticles[] = {
5, 5, // ëåâî íèç
5, 10, // ëåâî ââåðõ
10, 5, // ïðàâî íèç
10, 10 // ïðàâî ââåðõ
};
public Ship() {
ByteBuffer bb = ByteBuffer.allocateDirect(36);
bb.order(ByteOrder.nativeOrder());
ShipVertexBuffer = bb.asFloatBuffer();
ShipVertexBuffer.put(ShipVerticles);
ShipVertexBuffer.position(0);
}
public void draw(GL10 gl) {
gl.glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, ShipVertexBuffer);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
}
}
class Astedoid {
public int health = 100;
public int life = 3;
public FloatBuffer AsteroidColorBuffer;
public FloatBuffer AsteroidVertexBuffer;
public float AsteroidVerticles[] = {
25, 25, // ëåâî íèç
25, 30, // ëåâî ââåðõ
30, 25, // ïðàâî íèç
30, 30 // ïðàâî ââåðõ
};
public Astedoid() {
ByteBuffer bb = ByteBuffer.allocateDirect(36);
bb.order(ByteOrder.nativeOrder());
AsteroidVertexBuffer = bb.asFloatBuffer();
AsteroidVertexBuffer.put(AsteroidVerticles);
AsteroidVertexBuffer.position(0);
}
public void draw(GL10 gl) {
gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, AsteroidVertexBuffer);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
}
}
//
--------------------------------------------------------------------------------
}
I want do this, create some variable like "objectSize" and give it some
value 5 in main activity onTouchEvent on "case MotionEvent.ACTION_DOWN",
for example:
case MotionEvent.ACTION_DOWN:
objectSize = 5;
break;
than i want to use this variable to change size of drawing object in
MainRenderer in class Ship, for example:
public float ShipVerticles[] = {
5*objectSize , 5*objectSize,
5*objectSize, 10*objectSize,
10*objectSize, 5*objectSize,
10*objectSize, 10*objectSize
};
How i can do this? Thx!
Is it safe to rely on session variables to store information to be shared between multiple asynchronous flows?
Is it safe to rely on session variables to store information to be shared
between multiple asynchronous flows?
I have a couple of flows that rely on session variables that are generated
in one flow and then passed to the other. Is it safe to rely on session
variables used by two asynchronous flows? I guess I don't fully understand
the scope of 'sessionVars' in a mule application or in a given mule
message.
between multiple asynchronous flows?
I have a couple of flows that rely on session variables that are generated
in one flow and then passed to the other. Is it safe to rely on session
variables used by two asynchronous flows? I guess I don't fully understand
the scope of 'sessionVars' in a mule application or in a given mule
message.
LINQ2SQL query with IEnumerable as parameter
LINQ2SQL query with IEnumerable as parameter
I would be grateful if someone could help me. I have 2 tables:
Accounts
PK int AccountID
nvarchar(50) Name
and
Captions
PK int CaptionID
FK int AccountID
nvarchar(50) Key
nvarchar(50) Value
Within my code I have DTO:
public class CaptionDto
{
public string Key {get;set;}
public string Value {get;set;}
}
I have to implement method
public IEnumerable<Account> GetAccountsByCaptions(IEnumerable<CaptionDto>
captions);
Basically, I have to check all accounts who have captions (key and value)
matched with all input captions. I am using .NET, C# and this query should
be written using LINQ2SQL. Note that dbContext.Account has property
Captions (FK constraint)
public IEnumerable<Account> GetAccountsByCaptions(IEnumerable<CaptionDto>
captions)
{
using(var dbContext = new AccountDataContext)
{
....
}
}
Thanks in advance.
I would be grateful if someone could help me. I have 2 tables:
Accounts
PK int AccountID
nvarchar(50) Name
and
Captions
PK int CaptionID
FK int AccountID
nvarchar(50) Key
nvarchar(50) Value
Within my code I have DTO:
public class CaptionDto
{
public string Key {get;set;}
public string Value {get;set;}
}
I have to implement method
public IEnumerable<Account> GetAccountsByCaptions(IEnumerable<CaptionDto>
captions);
Basically, I have to check all accounts who have captions (key and value)
matched with all input captions. I am using .NET, C# and this query should
be written using LINQ2SQL. Note that dbContext.Account has property
Captions (FK constraint)
public IEnumerable<Account> GetAccountsByCaptions(IEnumerable<CaptionDto>
captions)
{
using(var dbContext = new AccountDataContext)
{
....
}
}
Thanks in advance.
Pause/Stop or remove HTML5 video on window resize
Pause/Stop or remove HTML5 video on window resize
I currently have a responsive HTML banner that has video (utilizing the
video tag) inside of it. My unit is responsive as the entire thing will
scale and so will the video. I have a breakpoint setup that turns on new
divs when the window is closed below 820px. This is accomplished via
@media (max-width:820px) {
//css is here
}
I'd like to include either javascript of jquery that also removes or
pauses the video when this size is reached just so the video doesn't
continue to play out of sight. My simple:
.ad_div2
{
display:none;
}
where the video element lives simply hides that div but you can still hear
the video playing in the background.
I've tried a couple of things but not sure that I'm setting it up right.
<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>
(with my appropriate id names) and that within my @media tag isn't doing
it - maybe i've placed this in the wrong area or it's not quite what I
need.
Any help would, as always, be greatly appreciated. Thanks!
I currently have a responsive HTML banner that has video (utilizing the
video tag) inside of it. My unit is responsive as the entire thing will
scale and so will the video. I have a breakpoint setup that turns on new
divs when the window is closed below 820px. This is accomplished via
@media (max-width:820px) {
//css is here
}
I'd like to include either javascript of jquery that also removes or
pauses the video when this size is reached just so the video doesn't
continue to play out of sight. My simple:
.ad_div2
{
display:none;
}
where the video element lives simply hides that div but you can still hear
the video playing in the background.
I've tried a couple of things but not sure that I'm setting it up right.
<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>
(with my appropriate id names) and that within my @media tag isn't doing
it - maybe i've placed this in the wrong area or it's not quite what I
need.
Any help would, as always, be greatly appreciated. Thanks!
php js mysql dropdown selection fills textboxes with db value
php js mysql dropdown selection fills textboxes with db value
Dear stackoverflow users, I am banging my head for a piece of code that
cant be to difficult but somehow my brains are not working today so please
help.
I am creating a form where i want to select an id from an dropdown(this is
working) and after selection i want to see all the records related to the
id in textfields. i want to create the fields manually so i dont want an
autocreate script. this is the code i have so far.
<!--Onderstaande gegevens worden NIET geprint!-->
<div id="non-printable">
<!---->
<?
// Load Joomla! configuration file
require_once('configuration.php');
// Create a JConfig object
$config = new JConfig();
// Get the required codes from the configuration file
$server = $config->host;
$username = $config->user;
$password = $config->password;
$database = $config->db;
// Tools dropdown
$con = mysql_connect($server,$username,$password);
mysql_select_db($database);
$sql = "SELECT cb_dealerid FROM cypg8_comprofiler";
$result = mysql_query($sql);
// Dealergegevens fields
?>
<!--Begin TOOLS-->
<div class="tools">
<div class="dealerselectie">
<?
echo "<select name='cb_dealerid'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['cb_dealerid'] . "'>" . $row['cb_dealerid']
. "</option>";
}
echo "</select>";
?>
</div><!--/.Dealerselectie-->
</div><!--/.Tools-->
<!--Einde TOOLS-->
<!--Begin DEALERGEGEVENS-->
<div class="dealergegevens">
<input type="text" name="cb_dealerid" value='" . $row['cb_dealerid']
. "'><br>
<input type="text" name="cb_dealerbedrijfsnaam" value='" .
$row['cb_dealerbedrijfsnaam'] . "'>
</div><!--/.dealergegevens-->
<!--Einde DEALERGEGEVENS-->
</div><!--/#non-printable-->
<!--Bovenstaande gegevens worden NIET geprint!-->
I know i am doing something wrong but i cant figure out what it is. I need
to create this without using a multipage form it all needs to stay on one
page. Any advice would greatly be appreciated.
Thanks in advance.
EDIT 1:
I keep on trying to get it to work obviously and this is one of the
attempts which is also not working.
<?echo "<input type=\"text\" value='" . $row['cb_dealerid'] . "'>";?>
<?echo "<input type=\"text\" value='" . $row['cb_dealerbedrijfsnaam'] .
"'>";?>
EDIT 2: <== MORE INFORMATION ABOUT WHAT I WANT TO ACHIEVE
I have in my database table the following details
cb_dealerid = 100, 101, 102, 103 cb_dealerbedrijfsnaam = willem, henk,
piet, klaas
When i select in the dropdown id 101 i want to see in the textbox the name
henk.
Dear stackoverflow users, I am banging my head for a piece of code that
cant be to difficult but somehow my brains are not working today so please
help.
I am creating a form where i want to select an id from an dropdown(this is
working) and after selection i want to see all the records related to the
id in textfields. i want to create the fields manually so i dont want an
autocreate script. this is the code i have so far.
<!--Onderstaande gegevens worden NIET geprint!-->
<div id="non-printable">
<!---->
<?
// Load Joomla! configuration file
require_once('configuration.php');
// Create a JConfig object
$config = new JConfig();
// Get the required codes from the configuration file
$server = $config->host;
$username = $config->user;
$password = $config->password;
$database = $config->db;
// Tools dropdown
$con = mysql_connect($server,$username,$password);
mysql_select_db($database);
$sql = "SELECT cb_dealerid FROM cypg8_comprofiler";
$result = mysql_query($sql);
// Dealergegevens fields
?>
<!--Begin TOOLS-->
<div class="tools">
<div class="dealerselectie">
<?
echo "<select name='cb_dealerid'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['cb_dealerid'] . "'>" . $row['cb_dealerid']
. "</option>";
}
echo "</select>";
?>
</div><!--/.Dealerselectie-->
</div><!--/.Tools-->
<!--Einde TOOLS-->
<!--Begin DEALERGEGEVENS-->
<div class="dealergegevens">
<input type="text" name="cb_dealerid" value='" . $row['cb_dealerid']
. "'><br>
<input type="text" name="cb_dealerbedrijfsnaam" value='" .
$row['cb_dealerbedrijfsnaam'] . "'>
</div><!--/.dealergegevens-->
<!--Einde DEALERGEGEVENS-->
</div><!--/#non-printable-->
<!--Bovenstaande gegevens worden NIET geprint!-->
I know i am doing something wrong but i cant figure out what it is. I need
to create this without using a multipage form it all needs to stay on one
page. Any advice would greatly be appreciated.
Thanks in advance.
EDIT 1:
I keep on trying to get it to work obviously and this is one of the
attempts which is also not working.
<?echo "<input type=\"text\" value='" . $row['cb_dealerid'] . "'>";?>
<?echo "<input type=\"text\" value='" . $row['cb_dealerbedrijfsnaam'] .
"'>";?>
EDIT 2: <== MORE INFORMATION ABOUT WHAT I WANT TO ACHIEVE
I have in my database table the following details
cb_dealerid = 100, 101, 102, 103 cb_dealerbedrijfsnaam = willem, henk,
piet, klaas
When i select in the dropdown id 101 i want to see in the textbox the name
henk.
iCloud using document based
iCloud using document based
I have a master detail view controller which shows the files and when i
select a cell it opens up a textview and a save button which saves the
content on the iCloud.But it doesnt seem to work.Here is the code
MasterViewController.h
#import <UIKit/UIKit.h>
#import "Note.h"
#define kFILENAME @"mydocument.dox"
@interface MasterViewController : UITableViewController
@property(strong)Note *doc;
@property(strong)NSMetadataQuery *query;
-(void)loadDocument;
@end
MasterViewController.m
#import "MasterViewController.h"
#import "DetailViewController.h"
@interface MasterViewController () {
NSMutableArray *_objects;
}
@end
@implementation MasterViewController
@synthesize doc=_doc;
@synthesize query=_query;
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadDocument];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self
action:@selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
}
-(void)loadDocument
{
NSMetadataQuery *query=[[NSMetadataQuery alloc]init];
_query=query;
[query setSearchScopes:[NSArray
arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
NSPredicate *pred=[NSPredicate predicateWithFormat:@"%K ==
%@",NSMetadataItemFSNameKey
,kFILENAME];
[query setPredicate:pred];
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(queryDidFinishGathering:)
name:NSMetadataQueryDidFinishGatheringNotification object:query];
[query startQuery];
}
-(void)queryDidFinishGathering:(NSNotification*)notification
{
NSMetadataQuery *query=[notification object];\
[query disableUpdates];
[query stopQuery];
[[NSNotificationCenter defaultCenter]removeObserver:self
name:NSMetadataQueryDidFinishGatheringNotification object:query];
_query=nil;
[self loadData:query];
}
-(void)loadData:(NSMetadataQuery*)query
{
if ([query resultCount]==1) {
NSMetadataItem *item=[query resultAtIndex:0];
NSURL *url=[item valueForAttribute:NSMetadataItemURLKey];
Note *doc=[[Note alloc]initWithFileURL:url];
self.doc=doc;
[self.doc openWithCompletionHandler:^(BOOL success){
if(success)
{
NSLog(@"iCloud Document Opened");
}
else
{
NSLog(@"Failed Opening the document");
NSURL *ubiq=[[NSFileManager
defaultManager]URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage=[[ubiq
URLByAppendingPathComponent:@"Documents"]URLByAppendingPathComponent:kFILENAME];
Note *doc=[[Note alloc]initWithFileURL:ubiquitousPackage];
self.doc=doc;
[doc saveToURL:[doc fileURL]
forSaveOperation:UIDocumentSaveForCreating
completionHandler:^(BOOL success){
if (success) {
[doc openWithCompletionHandler:^(BOOL success) {
NSLog(@"new document opened from iCloud");
}];
}
}];
}
}];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)insertNewObject:(id)sender
{
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationAutomatic];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return _objects.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
NSDate *object = _objects[indexPath.row];
cell.textLabel.text = [object description];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView
canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into
the array, and add a new row to the table view.
}
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath
*)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView
canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSDate *object = _objects[indexPath.row];
[[segue destinationViewController] setDetailItem:object];
}
}
Note.h
#import <UIKit/UIKit.h>
@interface Note : UIDocument
@property (strong) NSString * noteContent;
@end
Note.m
#import "Note.h"
@implementation Note
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName
error:(NSError **)outError
{
if ([contents length] > 0) {
self.noteContent = [[NSString alloc]
initWithBytes:[contents bytes]
length:[contents length]
encoding:NSUTF8StringEncoding];
} else {
// When the note is first created, assign some default content
self.noteContent = @"Empty";
}
return YES;
}
// Called whenever the application (auto)saves the content of a note
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
if ([self.noteContent length] == 0) {
self.noteContent = @"Empty";
}
return [NSData dataWithBytes:[self.noteContent UTF8String]
length:[self.noteContent length]];
}
@end
DetailViewController.h
#import <UIKit/UIKit.h>
@interface DetailViewController : UIViewController
@property (strong, nonatomic) id detailItem;
@property(strong)Note *doc;
- (IBAction)saveClicked:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *detailDescriptionLabel;
@end
DetailViewController.m
#import "Note.h"
#import "DetailViewController.h"
#define kFILENAME @"mydocument.dox"
@interface DetailViewController ()
- (void)configureView;
@end
@implementation DetailViewController
#pragma mark - Managing the detail item
- (void)setDetailItem:(id)newDetailItem
{
if (_detailItem != newDetailItem) {
_detailItem = newDetailItem;
// Update the view.
[self configureView];
}
}
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem) {
self.detailDescriptionLabel.text = [self.detailItem description];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self configureView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)saveClicked:(id)sender {
NSURL *ubiq=[[NSFileManager
defaultManager]URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage=[[ubiq
URLByAppendingPathComponent:@"Documents"]URLByAppendingPathComponent:kFILENAME];
Note *doc=[[Note alloc]initWithFileURL:ubiquitousPackage];
self.doc=doc;
[doc saveToURL:[doc fileURL]
forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL
success){
if (success) {
[doc openWithCompletionHandler:^(BOOL success) {
NSLog(@"new document opened from iCloud");
}];
}
else
{
NSLog(@"I dont know");
}
}];
}
@end
I have a master detail view controller which shows the files and when i
select a cell it opens up a textview and a save button which saves the
content on the iCloud.But it doesnt seem to work.Here is the code
MasterViewController.h
#import <UIKit/UIKit.h>
#import "Note.h"
#define kFILENAME @"mydocument.dox"
@interface MasterViewController : UITableViewController
@property(strong)Note *doc;
@property(strong)NSMetadataQuery *query;
-(void)loadDocument;
@end
MasterViewController.m
#import "MasterViewController.h"
#import "DetailViewController.h"
@interface MasterViewController () {
NSMutableArray *_objects;
}
@end
@implementation MasterViewController
@synthesize doc=_doc;
@synthesize query=_query;
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadDocument];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self
action:@selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
}
-(void)loadDocument
{
NSMetadataQuery *query=[[NSMetadataQuery alloc]init];
_query=query;
[query setSearchScopes:[NSArray
arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
NSPredicate *pred=[NSPredicate predicateWithFormat:@"%K ==
%@",NSMetadataItemFSNameKey
,kFILENAME];
[query setPredicate:pred];
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(queryDidFinishGathering:)
name:NSMetadataQueryDidFinishGatheringNotification object:query];
[query startQuery];
}
-(void)queryDidFinishGathering:(NSNotification*)notification
{
NSMetadataQuery *query=[notification object];\
[query disableUpdates];
[query stopQuery];
[[NSNotificationCenter defaultCenter]removeObserver:self
name:NSMetadataQueryDidFinishGatheringNotification object:query];
_query=nil;
[self loadData:query];
}
-(void)loadData:(NSMetadataQuery*)query
{
if ([query resultCount]==1) {
NSMetadataItem *item=[query resultAtIndex:0];
NSURL *url=[item valueForAttribute:NSMetadataItemURLKey];
Note *doc=[[Note alloc]initWithFileURL:url];
self.doc=doc;
[self.doc openWithCompletionHandler:^(BOOL success){
if(success)
{
NSLog(@"iCloud Document Opened");
}
else
{
NSLog(@"Failed Opening the document");
NSURL *ubiq=[[NSFileManager
defaultManager]URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage=[[ubiq
URLByAppendingPathComponent:@"Documents"]URLByAppendingPathComponent:kFILENAME];
Note *doc=[[Note alloc]initWithFileURL:ubiquitousPackage];
self.doc=doc;
[doc saveToURL:[doc fileURL]
forSaveOperation:UIDocumentSaveForCreating
completionHandler:^(BOOL success){
if (success) {
[doc openWithCompletionHandler:^(BOOL success) {
NSLog(@"new document opened from iCloud");
}];
}
}];
}
}];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)insertNewObject:(id)sender
{
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationAutomatic];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return _objects.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
NSDate *object = _objects[indexPath.row];
cell.textLabel.text = [object description];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView
canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into
the array, and add a new row to the table view.
}
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath
*)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView
canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSDate *object = _objects[indexPath.row];
[[segue destinationViewController] setDetailItem:object];
}
}
Note.h
#import <UIKit/UIKit.h>
@interface Note : UIDocument
@property (strong) NSString * noteContent;
@end
Note.m
#import "Note.h"
@implementation Note
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName
error:(NSError **)outError
{
if ([contents length] > 0) {
self.noteContent = [[NSString alloc]
initWithBytes:[contents bytes]
length:[contents length]
encoding:NSUTF8StringEncoding];
} else {
// When the note is first created, assign some default content
self.noteContent = @"Empty";
}
return YES;
}
// Called whenever the application (auto)saves the content of a note
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
if ([self.noteContent length] == 0) {
self.noteContent = @"Empty";
}
return [NSData dataWithBytes:[self.noteContent UTF8String]
length:[self.noteContent length]];
}
@end
DetailViewController.h
#import <UIKit/UIKit.h>
@interface DetailViewController : UIViewController
@property (strong, nonatomic) id detailItem;
@property(strong)Note *doc;
- (IBAction)saveClicked:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *detailDescriptionLabel;
@end
DetailViewController.m
#import "Note.h"
#import "DetailViewController.h"
#define kFILENAME @"mydocument.dox"
@interface DetailViewController ()
- (void)configureView;
@end
@implementation DetailViewController
#pragma mark - Managing the detail item
- (void)setDetailItem:(id)newDetailItem
{
if (_detailItem != newDetailItem) {
_detailItem = newDetailItem;
// Update the view.
[self configureView];
}
}
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem) {
self.detailDescriptionLabel.text = [self.detailItem description];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self configureView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)saveClicked:(id)sender {
NSURL *ubiq=[[NSFileManager
defaultManager]URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage=[[ubiq
URLByAppendingPathComponent:@"Documents"]URLByAppendingPathComponent:kFILENAME];
Note *doc=[[Note alloc]initWithFileURL:ubiquitousPackage];
self.doc=doc;
[doc saveToURL:[doc fileURL]
forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL
success){
if (success) {
[doc openWithCompletionHandler:^(BOOL success) {
NSLog(@"new document opened from iCloud");
}];
}
else
{
NSLog(@"I dont know");
}
}];
}
@end
Subscribe to:
Comments (Atom)