Read File in chunks and then read line by line using LineNumberReader.
Repeat this activity
I have a file containing some 6.5 lakh lines. Now I wish to read every
line of this file using LineNumberReader.
However I am encountering an outofMemoryError on adding these many number
of lines to another 3rd party library..
What I intend to do is, read 200000 lines of a file at a time and add
these lines to 3rd party library.
I am using LineNumberReader but I think the entire file is being read
although I have provided condition that when line count reaches 200000
break the loop and add these to 3rd party library..
A code snippet for the same:
LineNumberReader lnr=new LineNumberReader(new FileReader(file));
String line=null;
int i=0;
while(flags)
{
while( null != (line = lnr.readLine()) ){
i++;
3rdPartyLibrary.add(line.trim());
if(i==200000)
{
System.out.println("Breaking");
lnr.mark(i);
break;
}
if(i==400000)
{
System.out.println("" );
lnr.mark(i);
break;
}
if(i==600000)
{
System.out.println("BREAKING " );
lnr.mark(i);
break;
}
}
if(line==null)
{
System.out.println(" FLAG");
flags=false;
}
lnr.reset();
}
What I am intending to do here is read file from 0-200000 in first
iteration. Then read each individual line and add to 3rd party lib.. Once
this is done, read another 200000 lines from (200001-400000) and then
repeat the same activity.
Need help..Can someone please guide..
Saturday, 31 August 2013
GLSL Shader Ported From HLSL Is Not Working
GLSL Shader Ported From HLSL Is Not Working
I have this HLSL Shader for blur:
struct VS_INPUT
{
float4 Position : POSITION0;
float2 TexCoord : TEXCOORD0;
float4 Color : TEXCOORD1;
};
struct VS_OUTPUT
{
float4 Position : POSITION0;
float4 Color : COLOR0;
float2 TexCoord : TEXCOORD0;
};
float4x4 al_projview_matrix;
VS_OUTPUT vs_main(VS_INPUT Input)
{
VS_OUTPUT Output;
Output.Position = mul(Input.Position, al_projview_matrix);
Output.Color = Input.Color;
Output.TexCoord = Input.TexCoord;
return Output;
}
Frag
texture al_tex;
sampler2D s = sampler_state {
texture = <al_tex>;
};
int tWidth;
int tHeight;
float blurSize = 5.0;
float4 ps_main(VS_OUTPUT Input) : COLOR0
{
float2 pxSz = float2(1.0 / tWidth,1.0 / tHeight);
float4 outC = 0;
float outA = 0;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,-4.0 *
pxSz.y * blurSize)).a * 0.05;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,-3.0 *
pxSz.y * blurSize)).a * 0.09;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,-2.0 *
pxSz.y * blurSize)).a * 0.12;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy +
float2(0,-pxSz.y * blurSize)).a * 0.15;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,0)).a
* 0.16;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,pxSz.y
* blurSize)).a * 0.15;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,2.0 *
pxSz.y * blurSize)).a * 0.12;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,3.0 *
pxSz.y * blurSize)).a * 0.09;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,4.0 *
pxSz.y * blurSize)).a * 0.05;
outC.a = outA;
return outC;
}
There is a similar one for horizontal...
The idea is, I provide tWidth, tHeight for the texture with and height,
and use that to get the 'size' of a pixel relative to UV coords.
I then use this to do normal blur by taking a weighted average of neighbors.
I ported this to GLSL:
attribute vec4 al_pos;
attribute vec4 al_color;
attribute vec2 al_texcoord;
uniform mat4 al_projview_matrix;
varying vec4 varying_color;
varying vec2 varying_texcoord;
void main()
{
varying_color = al_color;
varying_texcoord = al_texcoord;
gl_Position = al_projview_matrix * al_pos;
}
Frag
uniform sampler2D al_tex;
varying float blurSize;
varying float tWidth;
varying float tHeight;
varying vec2 varying_texcoord;
varying vec4 varying_color;
void main()
{
vec4 sum = vec4(0.0);
vec2 pxSz = vec2(1.0 / tWidth,1.0 / tHeight);
// blur in x
// take nine samples, with the distance blurSize between them
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,-4.0 * pxSz.y *
blurSize))* 0.05;
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,-3.0 * pxSz.y *
blurSize))* 0.09;
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,-2.0 * pxSz.y *
blurSize))* 0.12;
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,-pxSz.y *
blurSize))* 0.15;
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,0))* 0.16;
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,pxSz.y *
blurSize))* 0.15;
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,2.0 * pxSz.y *
blurSize))* 0.12;
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,3.0 * pxSz.y *
blurSize))* 0.09;
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,4.0 * pxSz.y *
blurSize))* 0.05;
gl_FragColor = varying_color;
}
This is a little different, but it's the same logic. I convert pixel
coords to UV coords, and multiply by the blur factor, same as the hlsl
factor. Yet, the glsl one gives me an unblurred, slightly more transparent
version of the original.
What could cause this?
Thanks
I have this HLSL Shader for blur:
struct VS_INPUT
{
float4 Position : POSITION0;
float2 TexCoord : TEXCOORD0;
float4 Color : TEXCOORD1;
};
struct VS_OUTPUT
{
float4 Position : POSITION0;
float4 Color : COLOR0;
float2 TexCoord : TEXCOORD0;
};
float4x4 al_projview_matrix;
VS_OUTPUT vs_main(VS_INPUT Input)
{
VS_OUTPUT Output;
Output.Position = mul(Input.Position, al_projview_matrix);
Output.Color = Input.Color;
Output.TexCoord = Input.TexCoord;
return Output;
}
Frag
texture al_tex;
sampler2D s = sampler_state {
texture = <al_tex>;
};
int tWidth;
int tHeight;
float blurSize = 5.0;
float4 ps_main(VS_OUTPUT Input) : COLOR0
{
float2 pxSz = float2(1.0 / tWidth,1.0 / tHeight);
float4 outC = 0;
float outA = 0;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,-4.0 *
pxSz.y * blurSize)).a * 0.05;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,-3.0 *
pxSz.y * blurSize)).a * 0.09;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,-2.0 *
pxSz.y * blurSize)).a * 0.12;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy +
float2(0,-pxSz.y * blurSize)).a * 0.15;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,0)).a
* 0.16;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,pxSz.y
* blurSize)).a * 0.15;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,2.0 *
pxSz.y * blurSize)).a * 0.12;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,3.0 *
pxSz.y * blurSize)).a * 0.09;
outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,4.0 *
pxSz.y * blurSize)).a * 0.05;
outC.a = outA;
return outC;
}
There is a similar one for horizontal...
The idea is, I provide tWidth, tHeight for the texture with and height,
and use that to get the 'size' of a pixel relative to UV coords.
I then use this to do normal blur by taking a weighted average of neighbors.
I ported this to GLSL:
attribute vec4 al_pos;
attribute vec4 al_color;
attribute vec2 al_texcoord;
uniform mat4 al_projview_matrix;
varying vec4 varying_color;
varying vec2 varying_texcoord;
void main()
{
varying_color = al_color;
varying_texcoord = al_texcoord;
gl_Position = al_projview_matrix * al_pos;
}
Frag
uniform sampler2D al_tex;
varying float blurSize;
varying float tWidth;
varying float tHeight;
varying vec2 varying_texcoord;
varying vec4 varying_color;
void main()
{
vec4 sum = vec4(0.0);
vec2 pxSz = vec2(1.0 / tWidth,1.0 / tHeight);
// blur in x
// take nine samples, with the distance blurSize between them
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,-4.0 * pxSz.y *
blurSize))* 0.05;
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,-3.0 * pxSz.y *
blurSize))* 0.09;
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,-2.0 * pxSz.y *
blurSize))* 0.12;
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,-pxSz.y *
blurSize))* 0.15;
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,0))* 0.16;
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,pxSz.y *
blurSize))* 0.15;
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,2.0 * pxSz.y *
blurSize))* 0.12;
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,3.0 * pxSz.y *
blurSize))* 0.09;
sum += texture2D(al_tex, varying_texcoord.xy + vec2(0,4.0 * pxSz.y *
blurSize))* 0.05;
gl_FragColor = varying_color;
}
This is a little different, but it's the same logic. I convert pixel
coords to UV coords, and multiply by the blur factor, same as the hlsl
factor. Yet, the glsl one gives me an unblurred, slightly more transparent
version of the original.
What could cause this?
Thanks
Modify Youtube Video Description with API
Modify Youtube Video Description with API
I'm new to the Youtube API. I'm going through the API documentation and
I'm trying to find if and where it talks about modifying the video
description. I want an api that can change descriptions of specific
videos. Thanks
I'm new to the Youtube API. I'm going through the API documentation and
I'm trying to find if and where it talks about modifying the video
description. I want an api that can change descriptions of specific
videos. Thanks
Issue with @RequestBody annotation with Kendo UI Grid: Invalid Data Type
Issue with @RequestBody annotation with Kendo UI Grid: Invalid Data Type
I 've struggling with a little project in which I use kendo UI Grid ,
Spring 3.2 and jackson com.fasterxml.jackson.core version 2.2.2:(databind,
annotation and the core). and jquery 1.20.2 and spring-data-mongo. below
is a snippet of my mvc application context:
<bean id="messageConverters"
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<!-- Message converters -->
<bean
class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean
class="org.springframework.http.converter.FormHttpMessageConverter"/>
<bean
class="org.springframework.http.converter.ByteArrayHttpMessageConverter"
/>
<bean
class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
<bean
class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"
/>
</list>
</property>
</bean>
I have a PostDTO which represent a post sent throug a Restful API. and
Symptoms a pojo with @Document annotation which is supposed to be
managed(CRUD) by kendo Grid
public class PostDTO {
private String longitude;
private String latitude;
private String postType;
//,,,,
}
@Document
public class Symptom {
@Id
private String ID;
private String code;
private String name;
private String description;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date dateCreated;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date lastModified;
}
below are the Controllers actions to process each of them
@RequestMapping(value = "/api/post",method = RequestMethod.POST)
@ResponseBody
public ApiResponse receivePost(@RequestParam("username") String
username,@RequestParam("password") String password, @RequestBody PostDTO
postDTO , HttpServletRequest request, HttpServletResponse response){
ApiResponse apiResponse = new ApiResponse();
if(username ==null){
response.setStatus(500);
apiResponse.setStatus(500);
apiResponse.setMessage("empty username");
return apiResponse;
}
//other validations and some other long code
return apiResponse;
}
@RequestMapping(value = "/admin/do/symptoms/new",method =
RequestMethod.POST)
public @ResponseBody GridResponse createOne(@RequestBody Symptom symptom){
if(symptom !=null ){
//other processessing
}
//other codes
GridResponse gridResponse = new GridResponse();
return gridResponse;
}
a jquery ajax post to /api/post works well. google chrome extension
postman also works with raw json data in the request header. the PostDTO
object is created without any issue. But it doesn't seem to be the same
story with the Symptom object. I passed the raw Symptom json object using
the same postman with out success: below is what Kendo Ui Grid sends to
back end from what I see on Firebug:
type : application/x-www-form-urlencoded
ID
code something
dateCreated Sat Aug 31 2013 18:18:36 GMT+0000 (GMT)
description something
lastModified Sat Aug 31 2013 18:18:36 GMT+0000 (GMT)
name something
Source:
ID=&code=something&name=something&description=something&dateCreated=Sat+Aug+31+2013+18%3A18%3A36+GMT%2B0000+(GMT)&lastModified=Sat+Aug+31+2013+18%3A18%3A36+GMT%2B0000+(GMT)
Below is the actual kendo grid code :
<script type="text/javascript">
$(document).ready(function() {
var crudServiceBaseUrl = "<spring:url value="/admin/do"/>";
$("#grid").kendoGrid({
dataSource: {
type: "json",
serverPaging: true,
serverSorting: true,
pageSize: 20,
transport: {
read: crudServiceBaseUrl + "/symptoms/list",
create:{
dataType: "json",
url: crudServiceBaseUrl + "/symptoms/new",
type: "POST"
},
update: {
dataType: "json",
url: crudServiceBaseUrl + "/symptoms/update"
},
destroy: {
dataType: "json",
url: crudServiceBaseUrl + "/symptoms/delete"
}
},
schema:{
data: "rows",
total: "total",
model: {
id: "ID",
fields: {
ID: { editable: false, nullable: true },
code:{type: "string"},
name: { validation: { required: true} },
description: { type: "string" },
dateCreated: {type: "date"},
lastModified: {type: "date"}
}
}
}
},
height: 430,
sortable: true,
pageable: true,
columns: [
{field: 'code', title: "Code"},
{field: 'name',title:"Name"},
{field: 'description',title: "Description", width:150},
{field: 'dateCreated',title:"Date Created ",width: 50,
format: "{0:dd/MM/yyyy}"},
{field: 'lastModified',title:"Last Modified",format:
"{0:dd/MM/yyyy}"},
{ command: ["edit", "destroy"], title: " ", width:
"160px" }
],
editable: "popup",
toolbar: ["create"]
});
});
</script>
Am a bit confused why it won't be so. The only difference I see here is
spring-data specific annotations. Is it possible that I left out an
important configuration or Something am doing wrong?
I 've struggling with a little project in which I use kendo UI Grid ,
Spring 3.2 and jackson com.fasterxml.jackson.core version 2.2.2:(databind,
annotation and the core). and jquery 1.20.2 and spring-data-mongo. below
is a snippet of my mvc application context:
<bean id="messageConverters"
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<!-- Message converters -->
<bean
class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean
class="org.springframework.http.converter.FormHttpMessageConverter"/>
<bean
class="org.springframework.http.converter.ByteArrayHttpMessageConverter"
/>
<bean
class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
<bean
class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"
/>
</list>
</property>
</bean>
I have a PostDTO which represent a post sent throug a Restful API. and
Symptoms a pojo with @Document annotation which is supposed to be
managed(CRUD) by kendo Grid
public class PostDTO {
private String longitude;
private String latitude;
private String postType;
//,,,,
}
@Document
public class Symptom {
@Id
private String ID;
private String code;
private String name;
private String description;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date dateCreated;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date lastModified;
}
below are the Controllers actions to process each of them
@RequestMapping(value = "/api/post",method = RequestMethod.POST)
@ResponseBody
public ApiResponse receivePost(@RequestParam("username") String
username,@RequestParam("password") String password, @RequestBody PostDTO
postDTO , HttpServletRequest request, HttpServletResponse response){
ApiResponse apiResponse = new ApiResponse();
if(username ==null){
response.setStatus(500);
apiResponse.setStatus(500);
apiResponse.setMessage("empty username");
return apiResponse;
}
//other validations and some other long code
return apiResponse;
}
@RequestMapping(value = "/admin/do/symptoms/new",method =
RequestMethod.POST)
public @ResponseBody GridResponse createOne(@RequestBody Symptom symptom){
if(symptom !=null ){
//other processessing
}
//other codes
GridResponse gridResponse = new GridResponse();
return gridResponse;
}
a jquery ajax post to /api/post works well. google chrome extension
postman also works with raw json data in the request header. the PostDTO
object is created without any issue. But it doesn't seem to be the same
story with the Symptom object. I passed the raw Symptom json object using
the same postman with out success: below is what Kendo Ui Grid sends to
back end from what I see on Firebug:
type : application/x-www-form-urlencoded
ID
code something
dateCreated Sat Aug 31 2013 18:18:36 GMT+0000 (GMT)
description something
lastModified Sat Aug 31 2013 18:18:36 GMT+0000 (GMT)
name something
Source:
ID=&code=something&name=something&description=something&dateCreated=Sat+Aug+31+2013+18%3A18%3A36+GMT%2B0000+(GMT)&lastModified=Sat+Aug+31+2013+18%3A18%3A36+GMT%2B0000+(GMT)
Below is the actual kendo grid code :
<script type="text/javascript">
$(document).ready(function() {
var crudServiceBaseUrl = "<spring:url value="/admin/do"/>";
$("#grid").kendoGrid({
dataSource: {
type: "json",
serverPaging: true,
serverSorting: true,
pageSize: 20,
transport: {
read: crudServiceBaseUrl + "/symptoms/list",
create:{
dataType: "json",
url: crudServiceBaseUrl + "/symptoms/new",
type: "POST"
},
update: {
dataType: "json",
url: crudServiceBaseUrl + "/symptoms/update"
},
destroy: {
dataType: "json",
url: crudServiceBaseUrl + "/symptoms/delete"
}
},
schema:{
data: "rows",
total: "total",
model: {
id: "ID",
fields: {
ID: { editable: false, nullable: true },
code:{type: "string"},
name: { validation: { required: true} },
description: { type: "string" },
dateCreated: {type: "date"},
lastModified: {type: "date"}
}
}
}
},
height: 430,
sortable: true,
pageable: true,
columns: [
{field: 'code', title: "Code"},
{field: 'name',title:"Name"},
{field: 'description',title: "Description", width:150},
{field: 'dateCreated',title:"Date Created ",width: 50,
format: "{0:dd/MM/yyyy}"},
{field: 'lastModified',title:"Last Modified",format:
"{0:dd/MM/yyyy}"},
{ command: ["edit", "destroy"], title: " ", width:
"160px" }
],
editable: "popup",
toolbar: ["create"]
});
});
</script>
Am a bit confused why it won't be so. The only difference I see here is
spring-data specific annotations. Is it possible that I left out an
important configuration or Something am doing wrong?
Retrieve element from array in Coldfusion
Retrieve element from array in Coldfusion
I get the following struct return from disqus.com API and I just don't
know how to retrieve only the following value in red using Coldfusion.
This is the full array returned.
{
"cursor":{
"prev":null,
"hasNext":false,
"next":"1213061503000000:1:0",
"hasPrev":false,
"total":null,
"id":"1213061503000000:1:0",
"more":false
},
"code":0,
"response":[
{
"category":"1",
"reactions":0,
"identifiers":[],
"forum":"bobross",
"title":"Donkeys live a long time",
"dislikes":0,
"isDeleted":false,
"author":"1",
"userScore":0,
"id":"2",
"isClosed":false,
"posts":0,
"link":null,
"likes":0,
"message":"\"Donkeys live a long time. None of you have ever seen a
dead donkey.\"",
"ipAddress":"127.0.0.1",
"slug":"donkeys_live_a_long_time",
"createdAt":"2008-06-10T02:31:43"
},
{
"category":"1",
"reactions":0,
"identifiers":[
"my-identifier"
],
"forum":"bobross",
"title":"Happy Accidents",
"dislikes":0,
"isDeleted":false,
"author":"1",
"userScore":0,
"id":"1",
"isClosed":false,
"posts":76,
"link":null,
"likes":0,
"message":"\"If you've painted before you know that we don't make
mistakes -- we have happy accidents.\"",
"ipAddress":"127.0.0.1",
"slug":"happy_accidents",
"createdAt":"2008-06-10T01:31:43"
}
]
}
I get the following struct return from disqus.com API and I just don't
know how to retrieve only the following value in red using Coldfusion.
This is the full array returned.
{
"cursor":{
"prev":null,
"hasNext":false,
"next":"1213061503000000:1:0",
"hasPrev":false,
"total":null,
"id":"1213061503000000:1:0",
"more":false
},
"code":0,
"response":[
{
"category":"1",
"reactions":0,
"identifiers":[],
"forum":"bobross",
"title":"Donkeys live a long time",
"dislikes":0,
"isDeleted":false,
"author":"1",
"userScore":0,
"id":"2",
"isClosed":false,
"posts":0,
"link":null,
"likes":0,
"message":"\"Donkeys live a long time. None of you have ever seen a
dead donkey.\"",
"ipAddress":"127.0.0.1",
"slug":"donkeys_live_a_long_time",
"createdAt":"2008-06-10T02:31:43"
},
{
"category":"1",
"reactions":0,
"identifiers":[
"my-identifier"
],
"forum":"bobross",
"title":"Happy Accidents",
"dislikes":0,
"isDeleted":false,
"author":"1",
"userScore":0,
"id":"1",
"isClosed":false,
"posts":76,
"link":null,
"likes":0,
"message":"\"If you've painted before you know that we don't make
mistakes -- we have happy accidents.\"",
"ipAddress":"127.0.0.1",
"slug":"happy_accidents",
"createdAt":"2008-06-10T01:31:43"
}
]
}
sample for camel to send data from grails to services ( service mix)
sample for camel to send data from grails to services ( service mix)
I don't understand what exactly Camel does. If you could give in 101 words
an introduction to Camel:
What exactly is it? How does it interact with an application written in
Java? Is it something that goes together with the server? Is it an
independent program?
Can you give me an sample.
I don't understand what exactly Camel does. If you could give in 101 words
an introduction to Camel:
What exactly is it? How does it interact with an application written in
Java? Is it something that goes together with the server? Is it an
independent program?
Can you give me an sample.
Pass a Nokogiri::XML::Element into Delayed Job
Pass a Nokogiri::XML::Element into Delayed Job
I create a variable, called node:
doc.xpath('//Product').each do |node|
and pass it into a delayed job like this:
delay.create_new_book_record(client_id, user_id, node)
and although the variable 'node' I'm passing in looks something like this
just before I pass it into the delayed method:
//node.inspect #=>
<Product>
<RecordReference>9780857380272</RecordReference>
<NotificationType>02</NotificationType>
#...etc
it is passed in like this to delayed job which looks like an empty hash to
me:
INSERT INTO "delayed_jobs"
....
:create_new_book_record\nargs:\n- 1\n- 2\n-
!ruby/object:Nokogiri::XML::Element {}\n"]
And the error that gets thrown when I try to parse node in the delayed_job
task is
wrong argument type Nokogiri::XML::Element (expected Data)
So: how do I pass a Nokogiri::XML::Element into a delayed job task so that
it can be processed within the task?
I create a variable, called node:
doc.xpath('//Product').each do |node|
and pass it into a delayed job like this:
delay.create_new_book_record(client_id, user_id, node)
and although the variable 'node' I'm passing in looks something like this
just before I pass it into the delayed method:
//node.inspect #=>
<Product>
<RecordReference>9780857380272</RecordReference>
<NotificationType>02</NotificationType>
#...etc
it is passed in like this to delayed job which looks like an empty hash to
me:
INSERT INTO "delayed_jobs"
....
:create_new_book_record\nargs:\n- 1\n- 2\n-
!ruby/object:Nokogiri::XML::Element {}\n"]
And the error that gets thrown when I try to parse node in the delayed_job
task is
wrong argument type Nokogiri::XML::Element (expected Data)
So: how do I pass a Nokogiri::XML::Element into a delayed job task so that
it can be processed within the task?
Friday, 30 August 2013
Play2.11 Play can not find the model class but I can run pure JPA Juit test properly, Please come to help, thanks
Play2.11 Play can not find the model class but I can run pure JPA Juit
test properly, Please come to help, thanks
I am using Play2.11 Java and JPA2.0 Hibernate implementation and mysql
I can run the Junit test case properly to run CURD operation on the models
which put a persistence.xml under test/meat-inf, but when run play to CURD
from the web page, it shows can not find the models.* class. After some
time digging still do not have a clue. please help to check, thanks a lot
conf/meta-inf/persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="DEVUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>dev</non-jta-data-source>
<class>models.Account</class>
<properties>
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="false" />
</properties>
</persistence-unit>
test/meta-inf/persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="DEVUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>models.Account</class>
<properties>
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.connection.driver_class"
value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.username" value="***" />
<property name="hibernate.connection.password" value="***" />
<property name="hibernate.connection.url"
value="jdbc:mysql://****.net:3306/dev?characterEncoding=UTF-8" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="false" />
</properties>
</persistence-unit>
Only one line different the <non-jta-data-source>dev</non-jta-data-source>
conf/application.conf
# This is the main configuration file for the application.
# ~~~~~
# Secret key
# ~~~~~
# The secret key is used to secure cryptographics functions.
# If you deploy your application to several instances be sure to use the
same key!
application.secret="Qk5y/1b1;]>p=yo6?/FnmQR4F@W2lGYWfJI>e4oBs2D0nahNl>Y40y1A:P[uc;RJ"
# The application languages
# ~~~~~
application.langs="en"
# Global object class
# ~~~~~
# Define the Global object class for this application.
# Default to Global in the root package.
#application.global=Global
#ehcacheplugin=disabled
# Router
# ~~~~~
# Define the Router object to use for this application.
# This router will be looked up first when the application is starting up,
# so make sure this is the entry point.
# Furthermore, it's assumed your route file is named properly.
# So for an application router like `conf/my.application.Router`,
# you may need to define a router file `my.application.routes`.
# Default to Routes in the root package (and `conf/routes`)
# application.router=my.application.Routes
# Database configuration
# ~~~~~
# You can declare as many datasources as you want.
# By convention, the default datasource is named `default`
#
db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://****.net/dev?characterEncoding=UTF-8"
db.default.user=***
db.default.password=****
db.default.jndiName=dev
#
# You can expose this datasource via JNDI if needed (Useful for JPA)
# db.default.jndiName=DefaultDS
# Evolutions
# ~~~~~
# You can disable evolutions if needed
evolutionplugin=disabled
# Logger
# ~~~~~
# You can also configure logback (http://logback.qos.ch/), by providing a
logger.xml file in the conf directory .
# Root logger:
logger.root=ERROR
# Logger used by the framework:
logger.play=INFO
# Logger provided to your application:
logger.application=DEBUG
test properly, Please come to help, thanks
I am using Play2.11 Java and JPA2.0 Hibernate implementation and mysql
I can run the Junit test case properly to run CURD operation on the models
which put a persistence.xml under test/meat-inf, but when run play to CURD
from the web page, it shows can not find the models.* class. After some
time digging still do not have a clue. please help to check, thanks a lot
conf/meta-inf/persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="DEVUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>dev</non-jta-data-source>
<class>models.Account</class>
<properties>
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="false" />
</properties>
</persistence-unit>
test/meta-inf/persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="DEVUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>models.Account</class>
<properties>
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.connection.driver_class"
value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.username" value="***" />
<property name="hibernate.connection.password" value="***" />
<property name="hibernate.connection.url"
value="jdbc:mysql://****.net:3306/dev?characterEncoding=UTF-8" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="false" />
</properties>
</persistence-unit>
Only one line different the <non-jta-data-source>dev</non-jta-data-source>
conf/application.conf
# This is the main configuration file for the application.
# ~~~~~
# Secret key
# ~~~~~
# The secret key is used to secure cryptographics functions.
# If you deploy your application to several instances be sure to use the
same key!
application.secret="Qk5y/1b1;]>p=yo6?/FnmQR4F@W2lGYWfJI>e4oBs2D0nahNl>Y40y1A:P[uc;RJ"
# The application languages
# ~~~~~
application.langs="en"
# Global object class
# ~~~~~
# Define the Global object class for this application.
# Default to Global in the root package.
#application.global=Global
#ehcacheplugin=disabled
# Router
# ~~~~~
# Define the Router object to use for this application.
# This router will be looked up first when the application is starting up,
# so make sure this is the entry point.
# Furthermore, it's assumed your route file is named properly.
# So for an application router like `conf/my.application.Router`,
# you may need to define a router file `my.application.routes`.
# Default to Routes in the root package (and `conf/routes`)
# application.router=my.application.Routes
# Database configuration
# ~~~~~
# You can declare as many datasources as you want.
# By convention, the default datasource is named `default`
#
db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://****.net/dev?characterEncoding=UTF-8"
db.default.user=***
db.default.password=****
db.default.jndiName=dev
#
# You can expose this datasource via JNDI if needed (Useful for JPA)
# db.default.jndiName=DefaultDS
# Evolutions
# ~~~~~
# You can disable evolutions if needed
evolutionplugin=disabled
# Logger
# ~~~~~
# You can also configure logback (http://logback.qos.ch/), by providing a
logger.xml file in the conf directory .
# Root logger:
logger.root=ERROR
# Logger used by the framework:
logger.play=INFO
# Logger provided to your application:
logger.application=DEBUG
Wednesday, 28 August 2013
SSL certificate verification fails
SSL certificate verification fails
pIn going through the API tutorials, I'm getting the following error: SSL
certificate problem, verify that the CA cert is OK./p pThe CA certificate
is not in my build of libcurl. Is there anyway I can get it from DocuSign
in PEM format?/p
pIn going through the API tutorials, I'm getting the following error: SSL
certificate problem, verify that the CA cert is OK./p pThe CA certificate
is not in my build of libcurl. Is there anyway I can get it from DocuSign
in PEM format?/p
Passing a URL through jQuery with awkward routing
Passing a URL through jQuery with awkward routing
I am familiar with how to pass data through a url through jQuery, to my
ASP.NET MVC controllers, but I was writing some code today and came upon
an interesting URL that I cannot quite figure out how to format...
The route reads something like this ...
///////////////////////////////////////////
// route: /member/{0}/characters
///////////////////////////////////////////
public ActionResult Characters(int member){
// get the list of the member's characters
}
So the URL would actually have the 'parameter' right in the middle. This
is curious to me, because I'm not sure how this translates to the jQuery
"data" property on $.ajax. I would normally set it like this ....
$.ajax({
url: '/member/characters',
dataType: 'json',
data: { member: 1 }
}).done(function (data) { viewModel.set("Player", data); });
But that can't seem to work in this situation. I suppose I could do some
very hokey string formatting, but I am hoping to do this a bit more
cleanly...
Does anyone have suggestions for handling odd routes like this?
I am familiar with how to pass data through a url through jQuery, to my
ASP.NET MVC controllers, but I was writing some code today and came upon
an interesting URL that I cannot quite figure out how to format...
The route reads something like this ...
///////////////////////////////////////////
// route: /member/{0}/characters
///////////////////////////////////////////
public ActionResult Characters(int member){
// get the list of the member's characters
}
So the URL would actually have the 'parameter' right in the middle. This
is curious to me, because I'm not sure how this translates to the jQuery
"data" property on $.ajax. I would normally set it like this ....
$.ajax({
url: '/member/characters',
dataType: 'json',
data: { member: 1 }
}).done(function (data) { viewModel.set("Player", data); });
But that can't seem to work in this situation. I suppose I could do some
very hokey string formatting, but I am hoping to do this a bit more
cleanly...
Does anyone have suggestions for handling odd routes like this?
(Gmail) Sending emails from spreadsheet. How to add signature with image?
(Gmail) Sending emails from spreadsheet. How to add signature with image?
Due to the large amount of emails i'm sending with GMAIL i decided to
automatize this process using a script and following this
tutorial.Tutorial: Sending emails from a Spreadsheet
The "Message" is being generated by another function i created, called
prepareEmails.
The problems are the following:
1) How can i tell prepareEmails to add my personal signature? I can't
simply copy its text into that function, because my signature contains an
image (for which i have the URL), and i want that image to be into the
signature.
2) How can i make my signature BOLD?
Thanks everybody
Due to the large amount of emails i'm sending with GMAIL i decided to
automatize this process using a script and following this
tutorial.Tutorial: Sending emails from a Spreadsheet
The "Message" is being generated by another function i created, called
prepareEmails.
The problems are the following:
1) How can i tell prepareEmails to add my personal signature? I can't
simply copy its text into that function, because my signature contains an
image (for which i have the URL), and i want that image to be into the
signature.
2) How can i make my signature BOLD?
Thanks everybody
Why does the Android SDK need a JDK?
Why does the Android SDK need a JDK?
I am trying to understand why the Android SDK needs the JDK.
The Android SDK is not supposed to have all the JDK Java classes it needs
(with potential implementation differences) ?
Is that for all the tools included in the JDK ?
Do we use the JDK when we build .dex & .apk files ?
What does it mean to say that Android Java classes must be written with
Java 5 or 6 compiler compliance ?
Thanks
I am trying to understand why the Android SDK needs the JDK.
The Android SDK is not supposed to have all the JDK Java classes it needs
(with potential implementation differences) ?
Is that for all the tools included in the JDK ?
Do we use the JDK when we build .dex & .apk files ?
What does it mean to say that Android Java classes must be written with
Java 5 or 6 compiler compliance ?
Thanks
border-collapse is not working in flying-saucer?
border-collapse is not working in flying-saucer?
In flying-saucer, border-collapse is not working if I use
fs-paginate-table for the same table.
Does anybody know any workaround on this?
In flying-saucer, border-collapse is not working if I use
fs-paginate-table for the same table.
Does anybody know any workaround on this?
"Contains" twice in a collection using lambda expression
"Contains" twice in a collection using lambda expression
Hy, I want to find an item from a collection which contains for e.g. "30
days" . I want to search firstly "30" and then "days". How should I make
this using lambda expression? Can someone give me an example?
Thanks
Hy, I want to find an item from a collection which contains for e.g. "30
days" . I want to search firstly "30" and then "days". How should I make
this using lambda expression? Can someone give me an example?
Thanks
Tuesday, 27 August 2013
cocos2d: why isn't label appearing?
cocos2d: why isn't label appearing?
Hello I am making a side scrolling cocos2d game and I want a label to show
how far the user has flown in the game. For some reason with the code I
wrote the label is not appearing. Here is my GameEngine class that calls
the class method that is supposed to make the label appear:
//Set the meterDistance
meterDistance = [MeterDistance createTheMeterDistance];
[self addChild:meterDistance z:10];
Here is the code in the MeterDistance class:
meters = 1;
meterLabel = [CCLabelBMFont labelWithString:@"0"
fntFile:@"green_arcade-ipad.fnt"];
meterLabel.position = ccp(200, screenHeight - 100);
[self addChild:meterLabel z:10];
meterLabel.anchorPoint = ccp(1.0, 0.5);
[self schedule:@selector(updateLabel:)interval:1.0f/20.0f];
Here is the updateLabel method:
-(void)updateLabel:(ccTime)delta{
meters++;
NSString* scoreString = [NSString stringWithFormat:@"%d", meters];
[meterLabel setString:scoreString];
}
Hello I am making a side scrolling cocos2d game and I want a label to show
how far the user has flown in the game. For some reason with the code I
wrote the label is not appearing. Here is my GameEngine class that calls
the class method that is supposed to make the label appear:
//Set the meterDistance
meterDistance = [MeterDistance createTheMeterDistance];
[self addChild:meterDistance z:10];
Here is the code in the MeterDistance class:
meters = 1;
meterLabel = [CCLabelBMFont labelWithString:@"0"
fntFile:@"green_arcade-ipad.fnt"];
meterLabel.position = ccp(200, screenHeight - 100);
[self addChild:meterLabel z:10];
meterLabel.anchorPoint = ccp(1.0, 0.5);
[self schedule:@selector(updateLabel:)interval:1.0f/20.0f];
Here is the updateLabel method:
-(void)updateLabel:(ccTime)delta{
meters++;
NSString* scoreString = [NSString stringWithFormat:@"%d", meters];
[meterLabel setString:scoreString];
}
How to Redirect this URL to my home page In HTACCESS file
How to Redirect this URL to my home page In HTACCESS file
I am new with PHP , I want to redirect this URL to my home page
www.laroute-angkor.com by Edit HTACCESS file
Here the url that i want to redirect when the visitor click or visit :
www.laroute-angkor.com/component/k2/item/68-tours-by-sub-categories/68-tours-by-sub-categories?cat_id=23&start=5710
http://www.laroute-angkor.com/component/k2/item/62-bakheng-mountain/62-bakheng-mountain?start=1222270
http://www.laroute-angkor.com/component/k2/item/497-tours-by-sub-categories?cat_id=38
http://www.laroute-angkor.com/component/k2/item/496-tours-by-sub-categories?cat_id=38
I am new with PHP , I want to redirect this URL to my home page
www.laroute-angkor.com by Edit HTACCESS file
Here the url that i want to redirect when the visitor click or visit :
www.laroute-angkor.com/component/k2/item/68-tours-by-sub-categories/68-tours-by-sub-categories?cat_id=23&start=5710
http://www.laroute-angkor.com/component/k2/item/62-bakheng-mountain/62-bakheng-mountain?start=1222270
http://www.laroute-angkor.com/component/k2/item/497-tours-by-sub-categories?cat_id=38
http://www.laroute-angkor.com/component/k2/item/496-tours-by-sub-categories?cat_id=38
How to get request information sent to .asmx web service
How to get request information sent to .asmx web service
I have .asmx web service and something doesn't work with one of my methods
and can't figure what.
Is there any way to get request sent to web service from client so I can
log it somewhere to analyze?
Thanks
I have .asmx web service and something doesn't work with one of my methods
and can't figure what.
Is there any way to get request sent to web service from client so I can
log it somewhere to analyze?
Thanks
how to get black&white maps using Google Maps SDK for iOS
how to get black&white maps using Google Maps SDK for iOS
I need a map in black and white which is not possible using native mapkit.
I have looked for this but no luck.
I came across https://tiles.mapbox.com but it is not free.
I need a map in black and white which is not possible using native mapkit.
I have looked for this but no luck.
I came across https://tiles.mapbox.com but it is not free.
Recover Windows 7 Data
Recover Windows 7 Data
I am completely new to Ubuntu. I have a Dell Studio 1555 laptop. I had
Windows 7 Ultimate (64-bit) installed onto it and it was the only OS. In
Windows, my 250-GB hard disk was partitioned only into drive C (where
Windows was installed) and drive D.
Recently, I installed Ubuntu 13.04 via a pen drive; I performed a clean
install. My aim was to be able to use Windows 7 and Ubuntu 13.04 both as
and when required wherein I expected to get a screen that asks me to
choose between the two when I boot the laptop. I had done the same on my
desktop and it worked fine.
However, on my laptop, when I choose Windows 7 at the screen where I am
supposed to choose between Ubuntu 13.04 and Windows 7, it doesn't boot up,
saying "Windows 7 cannot start because of some recent software or hardware
changes". They ask me to use the Windows installation disc and repair my
computer. When I did that (using the installing Windows through USB
method), there was no option to "repair your computer", which I think
indicates that it doesn't detect the already installed Windows.
I don't remember what exactly is it that I did wrong while installing
Ubuntu but I remember NOT selecting "overwrite" or "erase disk", because I
wanted my Windows data to remain intact. Also, I think I must have
installed Ubuntu in the same drive as Windows (drive C) and that my
"home", "root", "bin", "boot" are in the same drive because in Ubuntu the
only device I see under "Devices" is "Computer" with all the
aforementioned folders.
Ubuntu works just fine. However, I can't find my Windows data anywhere!
Almost all the data was in drive D with only programs installed in C. I
don't mind losing the application programs but my drive D contained some
very important data.
I searched the forums for a solution but for fear of making the problem
completely irrepairable, I didn't try most of the stuff. I just need to
access the data so that I can copy it onto my desktop and perform clean
installations of Ubuntu and Windows 7 again.
I don't know if this will help: paste.ubuntu.com/5794687
Thank you!
I am completely new to Ubuntu. I have a Dell Studio 1555 laptop. I had
Windows 7 Ultimate (64-bit) installed onto it and it was the only OS. In
Windows, my 250-GB hard disk was partitioned only into drive C (where
Windows was installed) and drive D.
Recently, I installed Ubuntu 13.04 via a pen drive; I performed a clean
install. My aim was to be able to use Windows 7 and Ubuntu 13.04 both as
and when required wherein I expected to get a screen that asks me to
choose between the two when I boot the laptop. I had done the same on my
desktop and it worked fine.
However, on my laptop, when I choose Windows 7 at the screen where I am
supposed to choose between Ubuntu 13.04 and Windows 7, it doesn't boot up,
saying "Windows 7 cannot start because of some recent software or hardware
changes". They ask me to use the Windows installation disc and repair my
computer. When I did that (using the installing Windows through USB
method), there was no option to "repair your computer", which I think
indicates that it doesn't detect the already installed Windows.
I don't remember what exactly is it that I did wrong while installing
Ubuntu but I remember NOT selecting "overwrite" or "erase disk", because I
wanted my Windows data to remain intact. Also, I think I must have
installed Ubuntu in the same drive as Windows (drive C) and that my
"home", "root", "bin", "boot" are in the same drive because in Ubuntu the
only device I see under "Devices" is "Computer" with all the
aforementioned folders.
Ubuntu works just fine. However, I can't find my Windows data anywhere!
Almost all the data was in drive D with only programs installed in C. I
don't mind losing the application programs but my drive D contained some
very important data.
I searched the forums for a solution but for fear of making the problem
completely irrepairable, I didn't try most of the stuff. I just need to
access the data so that I can copy it onto my desktop and perform clean
installations of Ubuntu and Windows 7 again.
I don't know if this will help: paste.ubuntu.com/5794687
Thank you!
Monday, 26 August 2013
How can template identify what page it's being used on?
How can template identify what page it's being used on?
I have a template that is used for many different sections of my site
(About, News, etc.). The nav bar needs to show a little graphic arrow
below the section you're in. I was passing this via the template:
$page = 'about';
require('header.php');
...but then I realized that won't work since the template file I was
editing is used for a bunch of different sections, not just 'about'.
So I need something on the 'page' interface screen where I can somehow
indicate the page that the user is on. Some ideas for solutions:
Idea #1: does WordPress would set some kind of class on the 'body' tag to
indicate the page you're on (like if it generated a slug based on the page
name and added that as a class to the body tag)? Then just do everything I
need to do in CSS without complicating things.
Idea #2: some kind of built-in field on WordPress's 'page' admin that
would let my header know what page it is on.
Idea #3: I could make copies of my template for each major section. Very
stupid way to go about it.
I would REALLY prefer to not go the whole extra-fields route, manually
adding a metadata field to my pages, pulling it from the db on page load,
etc. That seems like super overkill for just having a way to let my
template code identify what page it is being used on.
Would love any tips.
I have a template that is used for many different sections of my site
(About, News, etc.). The nav bar needs to show a little graphic arrow
below the section you're in. I was passing this via the template:
$page = 'about';
require('header.php');
...but then I realized that won't work since the template file I was
editing is used for a bunch of different sections, not just 'about'.
So I need something on the 'page' interface screen where I can somehow
indicate the page that the user is on. Some ideas for solutions:
Idea #1: does WordPress would set some kind of class on the 'body' tag to
indicate the page you're on (like if it generated a slug based on the page
name and added that as a class to the body tag)? Then just do everything I
need to do in CSS without complicating things.
Idea #2: some kind of built-in field on WordPress's 'page' admin that
would let my header know what page it is on.
Idea #3: I could make copies of my template for each major section. Very
stupid way to go about it.
I would REALLY prefer to not go the whole extra-fields route, manually
adding a metadata field to my pages, pulling it from the db on page load,
etc. That seems like super overkill for just having a way to let my
template code identify what page it is being used on.
Would love any tips.
Is there a noun-form of the word 'intrinsic'?
Is there a noun-form of the word 'intrinsic'?
Is there a noun-form of the word 'intrinsic'? If so, what is it?
Intrinsicity? I suppose I could say 'the intrinsic nature of...', but it
makes grammar awkward when there are multiple subjects to your sentence,
eg: "In regards to your belief in the intrinsic nature of the insult which
lies in calling someone a ____, I'd argue that..."
Is there a noun-form of the word 'intrinsic'? If so, what is it?
Intrinsicity? I suppose I could say 'the intrinsic nature of...', but it
makes grammar awkward when there are multiple subjects to your sentence,
eg: "In regards to your belief in the intrinsic nature of the insult which
lies in calling someone a ____, I'd argue that..."
How to get ID from CSS to Javascript without getElementByID?
How to get ID from CSS to Javascript without getElementByID?
I have a basic question involving CSS and JavaScript.
I have a page with several DIVs, each one with an unique ID taken from a
mysql database. When a user clicks on a certain DIV, I want that one to
disappear from the page. Because everything it's dynamic my solution was
to pass the id as a variable to the function. The problem is I don't know
how use that id. I need something to replace document.getElementById().
JS:
function flashout(the_unique_id){
document.getElementByID(???).style.display = "";
}
HTML/CSS:
<div id="394" onclick="flashout(394)">...</div>
<div id="723" onclick="flashout(723)">...</div>
I have a basic question involving CSS and JavaScript.
I have a page with several DIVs, each one with an unique ID taken from a
mysql database. When a user clicks on a certain DIV, I want that one to
disappear from the page. Because everything it's dynamic my solution was
to pass the id as a variable to the function. The problem is I don't know
how use that id. I need something to replace document.getElementById().
JS:
function flashout(the_unique_id){
document.getElementByID(???).style.display = "";
}
HTML/CSS:
<div id="394" onclick="flashout(394)">...</div>
<div id="723" onclick="flashout(723)">...</div>
Filtering the MAX() function in a JOINED MySQL Query
Filtering the MAX() function in a JOINED MySQL Query
Solved: Here is the solution code.
//Extend Category queries to support "latest_post" for orderby parameter
function filter_term_sort_by_latest_post_clauses( $pieces, $taxonomies,
$args )
{
global $wpdb;
if ( in_array('category', $taxonomies) && $args['orderby'] ==
'latest_post' )
{
$pieces['fields'] .= ", MAX(p.post_date) AS last_date";
$pieces['join'] .= " JOIN $wpdb->term_relationships AS tr JOIN
$wpdb->posts AS p ON p.ID=tr.object_id AND
tr.term_taxonomy_id=tt.term_taxonomy_id";
$pieces['where'] .= " AND p.post_status='publish' GROUP BY
t.term_id";
$pieces['orderby'] = "ORDER BY last_date";
$pieces['order'] = "DESC"; // DESC or ASC
}
return $pieces;
}
add_filter('terms_clauses', 'filter_term_sort_by_latest_post_clauses', 10,
3);
Original question:
I have added the following function & filter hook in a WordPress site that
allows me to list the categories, sorted by the most recent post in each
category. The function works as expected, except that draft posts are
included, and will move that particular category to the top of the list.
//Extend Category queries to support "latest_post" for orderby parameter
function filter_term_sort_by_latest_post_clauses( $pieces, $taxonomies,
$args )
{
global $wpdb;
if ( in_array('category', $taxonomies) && $args['orderby'] ==
'latest_post' )
{
$pieces['fields'] .= ", MAX(p.post_date) AS last_date";
$pieces['join'] .= " JOIN $wpdb->term_relationships AS tr JOIN
$wpdb->posts AS p ON p.ID=tr.object_id AND
tr.term_taxonomy_id=tt.term_taxonomy_id";
$pieces['where'] .= " GROUP BY t.term_id";
$pieces['orderby'] = "ORDER BY last_date";
$pieces['order'] = "DESC"; // DESC or ASC
}
return $pieces;
}
add_filter('terms_clauses', 'filter_term_sort_by_latest_post_clauses', 10,
3);
I would like to be make the select clause "MAX(p.post_date) AS last_date"
only include values from published posts ( WHERE p.post_status=publish" )
How can I accomplish this?
Thanks!
Solved: Here is the solution code.
//Extend Category queries to support "latest_post" for orderby parameter
function filter_term_sort_by_latest_post_clauses( $pieces, $taxonomies,
$args )
{
global $wpdb;
if ( in_array('category', $taxonomies) && $args['orderby'] ==
'latest_post' )
{
$pieces['fields'] .= ", MAX(p.post_date) AS last_date";
$pieces['join'] .= " JOIN $wpdb->term_relationships AS tr JOIN
$wpdb->posts AS p ON p.ID=tr.object_id AND
tr.term_taxonomy_id=tt.term_taxonomy_id";
$pieces['where'] .= " AND p.post_status='publish' GROUP BY
t.term_id";
$pieces['orderby'] = "ORDER BY last_date";
$pieces['order'] = "DESC"; // DESC or ASC
}
return $pieces;
}
add_filter('terms_clauses', 'filter_term_sort_by_latest_post_clauses', 10,
3);
Original question:
I have added the following function & filter hook in a WordPress site that
allows me to list the categories, sorted by the most recent post in each
category. The function works as expected, except that draft posts are
included, and will move that particular category to the top of the list.
//Extend Category queries to support "latest_post" for orderby parameter
function filter_term_sort_by_latest_post_clauses( $pieces, $taxonomies,
$args )
{
global $wpdb;
if ( in_array('category', $taxonomies) && $args['orderby'] ==
'latest_post' )
{
$pieces['fields'] .= ", MAX(p.post_date) AS last_date";
$pieces['join'] .= " JOIN $wpdb->term_relationships AS tr JOIN
$wpdb->posts AS p ON p.ID=tr.object_id AND
tr.term_taxonomy_id=tt.term_taxonomy_id";
$pieces['where'] .= " GROUP BY t.term_id";
$pieces['orderby'] = "ORDER BY last_date";
$pieces['order'] = "DESC"; // DESC or ASC
}
return $pieces;
}
add_filter('terms_clauses', 'filter_term_sort_by_latest_post_clauses', 10,
3);
I would like to be make the select clause "MAX(p.post_date) AS last_date"
only include values from published posts ( WHERE p.post_status=publish" )
How can I accomplish this?
Thanks!
Display posts in a grid by using a for-loop
Display posts in a grid by using a for-loop
I have a PHP script that takes each post of a WordPress and assigns the
post contents to a specific div (.col-1-6). These divs are then arranged
in a grid. I have ten different posts (content divs) and I would like for
them to show up on two rows. The first row should have six posts and the
second row should have four. Right now, each row has five posts. Is there
a way I can edit my PHP script to include the functionality I need?
<?php
$num_cols = 2; // set the number of columns here
//the query section is only neccessary if the code is used in a
page template//
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; //
for pagination
$args = array(
'posts_per_page' => 12, // optional to overwrite the dashboard
setting
'post_type' => 'graduate', // add any other query parameter to
this array
'paged' => $paged
);
query_posts($args);
//end of query section
if (have_posts()) :
for ( $i=1 ; $i <= $num_cols; $i++ ) :
echo '<div id="col-'.$i.'" class="preview">';
$counter = $num_cols + 1 - $i;
while (have_posts()) : the_post();
if( $counter%$num_cols == 0 ) : ?>
<div class="col-1-6">
<?php
if ( has_post_thumbnail() ) { // check if the post
has a Post Thumbnail assigned to it.
the_post_thumbnail();
}
?>
<a href="<?php echo get_permalink(); ?>" title="<?php
the_title(); ?>"><p><?php the_title(); ?></p></a>
</div>
<?php endif;
$counter++;
endwhile;
rewind_posts();
echo '</div>'; //closes the column div
endfor;
else:
echo 'no posts';
endif;
wp_reset_query();
?>
I have a PHP script that takes each post of a WordPress and assigns the
post contents to a specific div (.col-1-6). These divs are then arranged
in a grid. I have ten different posts (content divs) and I would like for
them to show up on two rows. The first row should have six posts and the
second row should have four. Right now, each row has five posts. Is there
a way I can edit my PHP script to include the functionality I need?
<?php
$num_cols = 2; // set the number of columns here
//the query section is only neccessary if the code is used in a
page template//
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; //
for pagination
$args = array(
'posts_per_page' => 12, // optional to overwrite the dashboard
setting
'post_type' => 'graduate', // add any other query parameter to
this array
'paged' => $paged
);
query_posts($args);
//end of query section
if (have_posts()) :
for ( $i=1 ; $i <= $num_cols; $i++ ) :
echo '<div id="col-'.$i.'" class="preview">';
$counter = $num_cols + 1 - $i;
while (have_posts()) : the_post();
if( $counter%$num_cols == 0 ) : ?>
<div class="col-1-6">
<?php
if ( has_post_thumbnail() ) { // check if the post
has a Post Thumbnail assigned to it.
the_post_thumbnail();
}
?>
<a href="<?php echo get_permalink(); ?>" title="<?php
the_title(); ?>"><p><?php the_title(); ?></p></a>
</div>
<?php endif;
$counter++;
endwhile;
rewind_posts();
echo '</div>'; //closes the column div
endfor;
else:
echo 'no posts';
endif;
wp_reset_query();
?>
Why can't I start my activity?
Why can't I start my activity?
For some reason, the my search activity is working but the thumbsup
activity will not start . It recognizes that I am saying "three" and then
my app crashes. What do I need to add here to get this working?
Logcat:
08-26 09:58:14.934: E/Trace(7730): error opening trace file: No such file
or directory (2)
08-26 09:58:14.934: D/ActivityThread(7730): setTargetHeapUtilization:0.25
08-26 09:58:14.934: D/ActivityThread(7730): setTargetHeapIdealFree:8388608
08-26 09:58:14.934: D/ActivityThread(7730):
setTargetHeapConcurrentStart:2097152
08-26 09:58:15.214: D/libEGL(7730): loaded
/system/lib/egl/libEGL_adreno200.so
08-26 09:58:15.244: D/libEGL(7730): loaded
/system/lib/egl/libGLESv1_CM_adreno200.so
08-26 09:58:15.244: D/libEGL(7730): loaded
/system/lib/egl/libGLESv2_adreno200.so
08-26 09:58:15.605: I/Adreno200-EGLSUB(7730): <ConfigWindowMatch:2087>:
Format RGBA_8888.
08-26 09:58:15.695: E/(7730): <s3dReadConfigFile:75>: Can't open file for
reading
08-26 09:58:15.695: E/(7730): <s3dReadConfigFile:75>: Can't open file for
reading
08-26 09:58:15.695: D/OpenGLRenderer(7730): Enabling debug mode 0
08-26 09:58:15.745: I/Choreographer(7730): Skipped 31 frames! The
application may be doing too much work on its main thread.
Java Code:
package com.example.voicerecognitionactivity;
import java.util.ArrayList;
import java.util.List;
import com.example.voicerecognitionactivity.ThumbsUp;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
public class VoiceRecognitionActivity extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
private EditText metTextHint;
private ListView mlvTextMatches;
private Spinner msTextMatches;
private Button mbtSpeak;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
metTextHint = (EditText) findViewById(R.id.etTextHint);
mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches);
msTextMatches = (Spinner) findViewById(R.id.sNoOfMatches);
mbtSpeak = (Button) findViewById(R.id.btSpeak);
}
public void checkVoiceRecognition() {
// Check if voice recognition is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
mbtSpeak.setEnabled(false);
Toast.makeText(this, "Voice recognizer not present",
Toast.LENGTH_SHORT).show();
}
}
public void speak(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// Specify the calling package to identify your application
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
// Display an hint to the user about what he should say.
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, metTextHint.getText()
.toString());
// Given an hint to the recognizer about what the user is going to
say
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
// If number of Matches is not selected then return show toast
message
if (msTextMatches.getSelectedItemPosition() ==
AdapterView.INVALID_POSITION) {
Toast.makeText(this, "Please select No. of Matches from spinner",
Toast.LENGTH_SHORT).show();
return;
}
int noOfMatches = Integer.parseInt(msTextMatches.getSelectedItem()
.toString());
// Specify how many results you want to receive. The results will be
// sorted where the first result is the one with higher confidence.
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, noOfMatches);
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (!textMatchList.isEmpty()) {
if (textMatchList.get(0).contains("three")) {
// create an intent indicating we want
// to start the ThumbsUp activity.
// Important! Make sure your activity is
// in the AndroidManifest.xml file!
Intent i = new Intent(this, ThumbsUp.class);
// start the activity based on the Intent
startActivity(i);
// If first Match contains the 'search' word
// Then start web search.
if (textMatchList.get(0).contains("search")) {
String searchQuery =
textMatchList.get(0).replace("search",
" ");
Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
search.putExtra(SearchManager.QUERY, searchQuery);
startActivity(search);
} else {
// populate the Matches
mlvTextMatches
.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
textMatchList));
}
}
//Result code for various error.
}else if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
showToastMessage("Audio Error");
}else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
showToastMessage("Client Error");
}else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
showToastMessage("Network Error");
}else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
showToastMessage("No Match");
}else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
showToastMessage("Server Error");
}
super.onActivityResult(requestCode, resultCode, data);}
}
void showToastMessage(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
For some reason, the my search activity is working but the thumbsup
activity will not start . It recognizes that I am saying "three" and then
my app crashes. What do I need to add here to get this working?
Logcat:
08-26 09:58:14.934: E/Trace(7730): error opening trace file: No such file
or directory (2)
08-26 09:58:14.934: D/ActivityThread(7730): setTargetHeapUtilization:0.25
08-26 09:58:14.934: D/ActivityThread(7730): setTargetHeapIdealFree:8388608
08-26 09:58:14.934: D/ActivityThread(7730):
setTargetHeapConcurrentStart:2097152
08-26 09:58:15.214: D/libEGL(7730): loaded
/system/lib/egl/libEGL_adreno200.so
08-26 09:58:15.244: D/libEGL(7730): loaded
/system/lib/egl/libGLESv1_CM_adreno200.so
08-26 09:58:15.244: D/libEGL(7730): loaded
/system/lib/egl/libGLESv2_adreno200.so
08-26 09:58:15.605: I/Adreno200-EGLSUB(7730): <ConfigWindowMatch:2087>:
Format RGBA_8888.
08-26 09:58:15.695: E/(7730): <s3dReadConfigFile:75>: Can't open file for
reading
08-26 09:58:15.695: E/(7730): <s3dReadConfigFile:75>: Can't open file for
reading
08-26 09:58:15.695: D/OpenGLRenderer(7730): Enabling debug mode 0
08-26 09:58:15.745: I/Choreographer(7730): Skipped 31 frames! The
application may be doing too much work on its main thread.
Java Code:
package com.example.voicerecognitionactivity;
import java.util.ArrayList;
import java.util.List;
import com.example.voicerecognitionactivity.ThumbsUp;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
public class VoiceRecognitionActivity extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
private EditText metTextHint;
private ListView mlvTextMatches;
private Spinner msTextMatches;
private Button mbtSpeak;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
metTextHint = (EditText) findViewById(R.id.etTextHint);
mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches);
msTextMatches = (Spinner) findViewById(R.id.sNoOfMatches);
mbtSpeak = (Button) findViewById(R.id.btSpeak);
}
public void checkVoiceRecognition() {
// Check if voice recognition is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
mbtSpeak.setEnabled(false);
Toast.makeText(this, "Voice recognizer not present",
Toast.LENGTH_SHORT).show();
}
}
public void speak(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// Specify the calling package to identify your application
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
// Display an hint to the user about what he should say.
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, metTextHint.getText()
.toString());
// Given an hint to the recognizer about what the user is going to
say
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
// If number of Matches is not selected then return show toast
message
if (msTextMatches.getSelectedItemPosition() ==
AdapterView.INVALID_POSITION) {
Toast.makeText(this, "Please select No. of Matches from spinner",
Toast.LENGTH_SHORT).show();
return;
}
int noOfMatches = Integer.parseInt(msTextMatches.getSelectedItem()
.toString());
// Specify how many results you want to receive. The results will be
// sorted where the first result is the one with higher confidence.
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, noOfMatches);
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (!textMatchList.isEmpty()) {
if (textMatchList.get(0).contains("three")) {
// create an intent indicating we want
// to start the ThumbsUp activity.
// Important! Make sure your activity is
// in the AndroidManifest.xml file!
Intent i = new Intent(this, ThumbsUp.class);
// start the activity based on the Intent
startActivity(i);
// If first Match contains the 'search' word
// Then start web search.
if (textMatchList.get(0).contains("search")) {
String searchQuery =
textMatchList.get(0).replace("search",
" ");
Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
search.putExtra(SearchManager.QUERY, searchQuery);
startActivity(search);
} else {
// populate the Matches
mlvTextMatches
.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
textMatchList));
}
}
//Result code for various error.
}else if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
showToastMessage("Audio Error");
}else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
showToastMessage("Client Error");
}else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
showToastMessage("Network Error");
}else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
showToastMessage("No Match");
}else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
showToastMessage("Server Error");
}
super.onActivityResult(requestCode, resultCode, data);}
}
void showToastMessage(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
php - adding messages and setting date
php - adding messages and setting date
I don't know php at all and try to rewrite an example of using php with
android
I want my android app to send some data - name and message and receive
list of this data as JSON
now - what I have from my example :
<?php
// Get Post Data
$data = urldecode($_POST['data']);
$name = urldecode($_POST['name']);
$jsonData = array();
$jsonTempData = array();
$jsonTempData = array();
$jsonTempData['name'] = $name;
$jsonTempData['number'] = $data;
$jsonTempData['date_added'] = // I don't know how to set date
$jsonData[] = $jsonTempData;
$outputArr = array();
$outputArr['Android'] = $jsonData;
// Encode Array To JSON Data
print_r( json_encode($outputArr));
?>
which means I send some data and get it back in one method which is , I
assume, wrong. how can I separate them - sending data to php and receiving
json.i have to repeat, I got zero knowledge in php.
Plus it's only one name-message pair wrapped into array and what I need is
to make array of this messages and return them in JSON.Oh, and I need to
write time of message into array
thank you
I don't know php at all and try to rewrite an example of using php with
android
I want my android app to send some data - name and message and receive
list of this data as JSON
now - what I have from my example :
<?php
// Get Post Data
$data = urldecode($_POST['data']);
$name = urldecode($_POST['name']);
$jsonData = array();
$jsonTempData = array();
$jsonTempData = array();
$jsonTempData['name'] = $name;
$jsonTempData['number'] = $data;
$jsonTempData['date_added'] = // I don't know how to set date
$jsonData[] = $jsonTempData;
$outputArr = array();
$outputArr['Android'] = $jsonData;
// Encode Array To JSON Data
print_r( json_encode($outputArr));
?>
which means I send some data and get it back in one method which is , I
assume, wrong. how can I separate them - sending data to php and receiving
json.i have to repeat, I got zero knowledge in php.
Plus it's only one name-message pair wrapped into array and what I need is
to make array of this messages and return them in JSON.Oh, and I need to
write time of message into array
thank you
does google chrome in cookies database has unique values
does google chrome in cookies database has unique values
now writing some scanner for Google Chrome cookies. Also it has option to
delete cookie, however I didn't find any id field. The most similar is
creation_utc, I don't have much info about it, found out that it is some
kind of time-stamp, I would like to know if this value is unique or not.
I need this because while deleting some cookies I use few fields and it is
not an optimal way. If creation_utc is unique it would take less time for
deleting.
now writing some scanner for Google Chrome cookies. Also it has option to
delete cookie, however I didn't find any id field. The most similar is
creation_utc, I don't have much info about it, found out that it is some
kind of time-stamp, I would like to know if this value is unique or not.
I need this because while deleting some cookies I use few fields and it is
not an optimal way. If creation_utc is unique it would take less time for
deleting.
Sunday, 25 August 2013
Php redirect with variable
Php redirect with variable
I am trying to use
header('Location: http://www.yoursite.com/new_page.php?gameid=$gmid');
To add information from the previous page to a new page with the variable
that will be needed. Its obviously not working and I'm not sure what I am
doing wrong. Thanks for any help.
I am trying to use
header('Location: http://www.yoursite.com/new_page.php?gameid=$gmid');
To add information from the previous page to a new page with the variable
that will be needed. Its obviously not working and I'm not sure what I am
doing wrong. Thanks for any help.
[ Mathematics ] Open Question : 3.04÷4 dividing decimals?
[ Mathematics ] Open Question : 3.04÷4 dividing decimals?
where i can watch Tottenham vs Swansea Live
where i can watch Tottenham vs Swansea Live
Watch Live Streaming Link
Football Live Tv
We also have Streams in Justin, Sopcast, Ustream, Vshare, Livevdo,
Freedocast, Veemi, YYcast – all you need is Adobe Flashplayer. We Always
try our best to get you the best possible HD Streams to watch Live Sports
Online. You will never have to pay for any service just enjoy streaming
live Television, Videos and Sports.
Tottenham vs Swansea Live Stream
Watch Live Streaming Link
Watch Live Streaming Link
Football Live Tv
We also have Streams in Justin, Sopcast, Ustream, Vshare, Livevdo,
Freedocast, Veemi, YYcast – all you need is Adobe Flashplayer. We Always
try our best to get you the best possible HD Streams to watch Live Sports
Online. You will never have to pay for any service just enjoy streaming
live Television, Videos and Sports.
Tottenham vs Swansea Live Stream
Watch Live Streaming Link
displaying table data from a multidimensional array
displaying table data from a multidimensional array
here is my array
Array
(
[0] => Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => no
)
[1] => Array
(
[0] => 2
[1] => 2
[2] => 2
[3] => 2
[4] => yes
)
[2] => Array
(
[0] => 3
[1] => 3
[2] => 3
[3] => 3
[4] => yes
)
[3] => Array
(
[0] => 4
[1] => 4
[2] => 4
[3] => 4
[4] => no
)
[4] => Array
(
[0] => 5
[1] => 5
[2] => 5
[3] => 5
[4] => yes
)
)
this is what i tried, i'm creating a tables tr portion and what it does is
duplicate itself for each record that is being displayed. How else can
this be written so that it displays correctly? I know it must be simple i
just cant wrap my head around it.
<?php
$units = json_decode($tablerow);
foreach($units as $unit) : for($i=0;$i<=count($unit)-1;$i++) : ?>
<tr class="rows">
<td><input type='text' name='bedroom[]' value='<?=$units[$i];?>'
class='input-small'></td>
<td><input type='text' name='bath[]' value='<?=$units[$i];?>'
class='input-small'></td>
<td><input type='text' name='sqrt[]' value='<?=$units[$i];?>'
class='input-small'></td>
<td><input type='text' name='price[]' value='<?=$units[$i];?>'
class='input-small'></td>
<td>
<select name='avail[]' class='input-small'>
<option value='yes' <?=($units[$i] == 'yes') ?
'selected="selected' : '';?>>Yes</option>
<option value='no' <?=($units[$i] == 'no') ? 'selected="selected'
: '';?>>No</option>
</select>
</td>
<td><button type="button" class="btn btn-danger btn-small
removeRow">remove</button></td>
</tr>
<?php endfor; endforeach; ?>
here is my array
Array
(
[0] => Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => no
)
[1] => Array
(
[0] => 2
[1] => 2
[2] => 2
[3] => 2
[4] => yes
)
[2] => Array
(
[0] => 3
[1] => 3
[2] => 3
[3] => 3
[4] => yes
)
[3] => Array
(
[0] => 4
[1] => 4
[2] => 4
[3] => 4
[4] => no
)
[4] => Array
(
[0] => 5
[1] => 5
[2] => 5
[3] => 5
[4] => yes
)
)
this is what i tried, i'm creating a tables tr portion and what it does is
duplicate itself for each record that is being displayed. How else can
this be written so that it displays correctly? I know it must be simple i
just cant wrap my head around it.
<?php
$units = json_decode($tablerow);
foreach($units as $unit) : for($i=0;$i<=count($unit)-1;$i++) : ?>
<tr class="rows">
<td><input type='text' name='bedroom[]' value='<?=$units[$i];?>'
class='input-small'></td>
<td><input type='text' name='bath[]' value='<?=$units[$i];?>'
class='input-small'></td>
<td><input type='text' name='sqrt[]' value='<?=$units[$i];?>'
class='input-small'></td>
<td><input type='text' name='price[]' value='<?=$units[$i];?>'
class='input-small'></td>
<td>
<select name='avail[]' class='input-small'>
<option value='yes' <?=($units[$i] == 'yes') ?
'selected="selected' : '';?>>Yes</option>
<option value='no' <?=($units[$i] == 'no') ? 'selected="selected'
: '';?>>No</option>
</select>
</td>
<td><button type="button" class="btn btn-danger btn-small
removeRow">remove</button></td>
</tr>
<?php endfor; endforeach; ?>
Saturday, 24 August 2013
how do i create individual sessions for clients querying my servlet
how do i create individual sessions for clients querying my servlet
im currently having an intense problem. I cant seem to be able to create
individual sessions for my clients who are using my servlet.
The key point of my servlet is that it provides a diffie hellman key
exchange to individual sessions. That is working as intended , however
when another user concurrently pushes the add token button. The previous
values that were generated will be overwritten , so my server is limited
to serving only one person at a time.
How do i create multiple sessions for my clients using my diffie hellman
servlet? Thanks in advance.
Below is my code snippet.
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if(null == request.getRequestedSessionId())
{
//create new session
System.out.println("No session id found , generating a new session
ID");
session = request.getSession(true);
System.out.println("session id generated is "+session.getId());
@SuppressWarnings("deprecation")
String encodedURL =
response.encodeUrl("/MyServletProject/DHServlet");
System.out.println("res.encodeURL(\"/DHServlet\");="+encodedURL);
response.sendRedirect(encodedURL);
return;
}else
{
System.out.println("session id = "+request.getRequestedSessionId());
System.out.println("no redirect required");
}
processRequest(request,response);
}
My diffie hellman Key Exchange
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// PrintWriter out2=response.getWriter();
DH getDH = new DH();
try {
System.out.println("Session id requested is
"+request.getRequestedSessionId());
long pValue = getDH.getSafePrime();
long gValue = getDH.getGenValue(pValue);
System.out.println("pValue is "+pValue);
System.out.println("gValue us "+gValue);
long serverSK = getDH.generateSKA();
BigInteger safePrimeValue = BigInteger.valueOf(pValue);
BigInteger generatorValue = BigInteger.valueOf(gValue);
System.out.println("the safe Prime is "+safePrimeValue);
System.out.println("the generator value is "+generatorValue);
BigInteger serverPK = getDH.generatePkB(generatorValue,
safePrimeValue, serverSK);
// System.out.println(publicKeyFromClient);
String getTimeOnServer = Time.getTime();
String SPValue = safePrimeValue.toString();
String genValue = generatorValue.toString();
String sPublicKey = serverPK.toString();
// long pkFromClient = Long.parseLong(publicKeyFromClient);
//BigInteger pkC = BigInteger.valueOf(pkFromClient);
System.out.println("the erver public key is "+sPublicKey);
out.print("1"+":"+getTimeOnServer+":"+genValue+":"+SPValue+":"+sPublicKey);
pkClient=sPublicKey.toString();
SpValue = SPValue.toString();
sCValue=Long.toString(serverSK);
} finally {
out.close();
}
}
im currently having an intense problem. I cant seem to be able to create
individual sessions for my clients who are using my servlet.
The key point of my servlet is that it provides a diffie hellman key
exchange to individual sessions. That is working as intended , however
when another user concurrently pushes the add token button. The previous
values that were generated will be overwritten , so my server is limited
to serving only one person at a time.
How do i create multiple sessions for my clients using my diffie hellman
servlet? Thanks in advance.
Below is my code snippet.
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if(null == request.getRequestedSessionId())
{
//create new session
System.out.println("No session id found , generating a new session
ID");
session = request.getSession(true);
System.out.println("session id generated is "+session.getId());
@SuppressWarnings("deprecation")
String encodedURL =
response.encodeUrl("/MyServletProject/DHServlet");
System.out.println("res.encodeURL(\"/DHServlet\");="+encodedURL);
response.sendRedirect(encodedURL);
return;
}else
{
System.out.println("session id = "+request.getRequestedSessionId());
System.out.println("no redirect required");
}
processRequest(request,response);
}
My diffie hellman Key Exchange
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// PrintWriter out2=response.getWriter();
DH getDH = new DH();
try {
System.out.println("Session id requested is
"+request.getRequestedSessionId());
long pValue = getDH.getSafePrime();
long gValue = getDH.getGenValue(pValue);
System.out.println("pValue is "+pValue);
System.out.println("gValue us "+gValue);
long serverSK = getDH.generateSKA();
BigInteger safePrimeValue = BigInteger.valueOf(pValue);
BigInteger generatorValue = BigInteger.valueOf(gValue);
System.out.println("the safe Prime is "+safePrimeValue);
System.out.println("the generator value is "+generatorValue);
BigInteger serverPK = getDH.generatePkB(generatorValue,
safePrimeValue, serverSK);
// System.out.println(publicKeyFromClient);
String getTimeOnServer = Time.getTime();
String SPValue = safePrimeValue.toString();
String genValue = generatorValue.toString();
String sPublicKey = serverPK.toString();
// long pkFromClient = Long.parseLong(publicKeyFromClient);
//BigInteger pkC = BigInteger.valueOf(pkFromClient);
System.out.println("the erver public key is "+sPublicKey);
out.print("1"+":"+getTimeOnServer+":"+genValue+":"+SPValue+":"+sPublicKey);
pkClient=sPublicKey.toString();
SpValue = SPValue.toString();
sCValue=Long.toString(serverSK);
} finally {
out.close();
}
}
somthing wrong with zooker usage
somthing wrong with zooker usage
My Reduce Tasks fail because all the namenode fails trying to connect to
localhost instead of 10.34.187.170 ..
My application even tries to connect manually in the code..
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", "10.34.187.170");
conf.set("hbase.zookeeper.property.clientPort","2181");
conf.set("hbase.master","10.34.187.170");
2013-08-24 20:05:36,213 INFO org.apache.zookeeper.ClientCnxn: Opening
socket connection to server localhost/127.0.0.1:2181. Will not attempt to
authenticate using SASL (Unable to locate a login configuration)
2013-08-24 20:05:36,213 WARN org.apache.zookeeper.ClientCnxn: Session 0x0
for server null, unexpected error, closing socket connection and attempting
reconnect
java.net.ConnectException: Connection refused
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at
sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:567)
at
org.apache.zookeeper.ClientCnxnSocketNIO.doTransport(ClientCnxnSocketNIO.java:350)
at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1068)
Please help. I've been stuck for days..
My Reduce Tasks fail because all the namenode fails trying to connect to
localhost instead of 10.34.187.170 ..
My application even tries to connect manually in the code..
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", "10.34.187.170");
conf.set("hbase.zookeeper.property.clientPort","2181");
conf.set("hbase.master","10.34.187.170");
2013-08-24 20:05:36,213 INFO org.apache.zookeeper.ClientCnxn: Opening
socket connection to server localhost/127.0.0.1:2181. Will not attempt to
authenticate using SASL (Unable to locate a login configuration)
2013-08-24 20:05:36,213 WARN org.apache.zookeeper.ClientCnxn: Session 0x0
for server null, unexpected error, closing socket connection and attempting
reconnect
java.net.ConnectException: Connection refused
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at
sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:567)
at
org.apache.zookeeper.ClientCnxnSocketNIO.doTransport(ClientCnxnSocketNIO.java:350)
at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1068)
Please help. I've been stuck for days..
How can I run cmd-line tests in Xcode5 for an iOS project
How can I run cmd-line tests in Xcode5 for an iOS project
XCode5 includes a new cmd-line test runner, that makes it easier to set up
Continuous Integration builds.
What is the cmd-line test execute tests for a cocoa pods project?
XCode5 includes a new cmd-line test runner, that makes it easier to set up
Continuous Integration builds.
What is the cmd-line test execute tests for a cocoa pods project?
Emacs: Saving and restoring original pane layout (e.g. when working with ediff)
Emacs: Saving and restoring original pane layout (e.g. when working with
ediff)
In a typical Emacs session I often have only one pane open, and I have it
divided into 4 windows forming a 2x2 grid with some specific buffers
(files) in each window.
Every time I use ediff-buffers to compare two buffers, Emacs takes my
existing pane, and re-splits it into two panes vertically (which I can
choose to hortizontal by subsequentially pressing -). However, when I quit
the ediff session, Emacs does not automatically restore the original
layout of windows in my pane.
With this my question is:
Is there any way to automatically restore my original layout?'
Even better, how can I have ediff-buffers open a new separate pane just
for the ediff session and close it automatically when I quit the ediff
session?
ediff)
In a typical Emacs session I often have only one pane open, and I have it
divided into 4 windows forming a 2x2 grid with some specific buffers
(files) in each window.
Every time I use ediff-buffers to compare two buffers, Emacs takes my
existing pane, and re-splits it into two panes vertically (which I can
choose to hortizontal by subsequentially pressing -). However, when I quit
the ediff session, Emacs does not automatically restore the original
layout of windows in my pane.
With this my question is:
Is there any way to automatically restore my original layout?'
Even better, how can I have ediff-buffers open a new separate pane just
for the ediff session and close it automatically when I quit the ediff
session?
Stop deallocation of instance variable I need to stay around (but not worthy of being a property)
Stop deallocation of instance variable I need to stay around (but not
worthy of being a property)
I'm currently making block based wrappers around some methods of the
Dropbox, Google Drive, and Box.com SDKs. I've successfully wrapped upload
functionality into all three, and they all work nicely. The wrappers have
a "common" interface that conform to a universal spec among the three
services, which is why I'm doing this.
Dropbox is the only one that runs on delegate callbacks. I have no issues
with the upload classes. However, I'm trying to implement some download
classes in the same manner. I'm running into an issue so far that my
returned instances are getting immediately deallocated before any of the
delegate methods in the wrapper are called. First, check out the method
structure of the _working_ "Upload" class:
+(id)uploaderWithPaths:(NSMutableDictionary *)paths
progress:(JAUploadProgressBlock)progBlock
completed:(JAUploadCompletedBlock)compBlock
failed:(JAUploadFailedBlock)failBlock;
-(void)upload;
//in .m
return [[[self class] alloc]initWithPaths:paths
progress:progBlock
completed:compBlock
failed:failBlock];
-(void)upload {
//setup Dropbox Rest Client
//configure delegate, etc
[dbRestClient doUpload...];
}
//delegate stuff
..onProgress {
self.progressBlock(progress);
..onComplete {
self.completedBlock(info);
..onFailed {
self.failedBlock(error);
Thus, instantiating and performing an upload goes like this:
JAUploadProgressBlock progress = ^(CGFloat percentage) {
NSLog(@"%.2f",percentage); }
JAUploadCompletedBlock completed = ^(NSMutableDictionary *info) {
NSLog(@"Success: %@",info); }
JAUploadFailedBlock failed = ^(NSError *error) {
NSLog(@"Failed: %@",[error localizedDescription];
JAUploadWrapperDropbox *uploader = [JAUploadWrapperDropbox
uploaderWithPaths:paths
progress:progress
completed:completed
failed:failed];
[uploader upload];
In the upload wrapper class, the instance does not get deallocated
immediately, the delegate messages inside the wrapper get called, my block
callbacks fire, and everything goes as planned.
However, my Download wrapper class, which is modeled exactly like the
upload wrapper, gets deallocated before any of the delegate methods in the
wrapper are called.
This class is not conducive to being a property, because it's not suited
for re-use. It's really meant to be used once or as one offs. Using a
strong property fixes the issue, but like I said, I don't need to use a
property for my upload wrapper class.
What am I doing wrong?
You can check this project out at
https://github.com/justinxxvii/JAOperationWrapper At this time I have not
made a commit with any download wrappers.
worthy of being a property)
I'm currently making block based wrappers around some methods of the
Dropbox, Google Drive, and Box.com SDKs. I've successfully wrapped upload
functionality into all three, and they all work nicely. The wrappers have
a "common" interface that conform to a universal spec among the three
services, which is why I'm doing this.
Dropbox is the only one that runs on delegate callbacks. I have no issues
with the upload classes. However, I'm trying to implement some download
classes in the same manner. I'm running into an issue so far that my
returned instances are getting immediately deallocated before any of the
delegate methods in the wrapper are called. First, check out the method
structure of the _working_ "Upload" class:
+(id)uploaderWithPaths:(NSMutableDictionary *)paths
progress:(JAUploadProgressBlock)progBlock
completed:(JAUploadCompletedBlock)compBlock
failed:(JAUploadFailedBlock)failBlock;
-(void)upload;
//in .m
return [[[self class] alloc]initWithPaths:paths
progress:progBlock
completed:compBlock
failed:failBlock];
-(void)upload {
//setup Dropbox Rest Client
//configure delegate, etc
[dbRestClient doUpload...];
}
//delegate stuff
..onProgress {
self.progressBlock(progress);
..onComplete {
self.completedBlock(info);
..onFailed {
self.failedBlock(error);
Thus, instantiating and performing an upload goes like this:
JAUploadProgressBlock progress = ^(CGFloat percentage) {
NSLog(@"%.2f",percentage); }
JAUploadCompletedBlock completed = ^(NSMutableDictionary *info) {
NSLog(@"Success: %@",info); }
JAUploadFailedBlock failed = ^(NSError *error) {
NSLog(@"Failed: %@",[error localizedDescription];
JAUploadWrapperDropbox *uploader = [JAUploadWrapperDropbox
uploaderWithPaths:paths
progress:progress
completed:completed
failed:failed];
[uploader upload];
In the upload wrapper class, the instance does not get deallocated
immediately, the delegate messages inside the wrapper get called, my block
callbacks fire, and everything goes as planned.
However, my Download wrapper class, which is modeled exactly like the
upload wrapper, gets deallocated before any of the delegate methods in the
wrapper are called.
This class is not conducive to being a property, because it's not suited
for re-use. It's really meant to be used once or as one offs. Using a
strong property fixes the issue, but like I said, I don't need to use a
property for my upload wrapper class.
What am I doing wrong?
You can check this project out at
https://github.com/justinxxvii/JAOperationWrapper At this time I have not
made a commit with any download wrappers.
Java swing components keep size (static)
Java swing components keep size (static)
I've got a problem with the size of some object, for example a JList. If I
add a element, the size of the list will grow. Well that is good, but if I
add alot of elements, the JList will be out of the window of my app and I
can't see the bottom of it(Sorry for bad grammar). How can I can I make
the size static, that it will not go 'under' my window size.
Mathijs
I've got a problem with the size of some object, for example a JList. If I
add a element, the size of the list will grow. Well that is good, but if I
add alot of elements, the JList will be out of the window of my app and I
can't see the bottom of it(Sorry for bad grammar). How can I can I make
the size static, that it will not go 'under' my window size.
Mathijs
Uploading data into Google spreadsheet from android app
Uploading data into Google spreadsheet from android app
I am building an android app in which I was just thinking can I update
required data directly on Google Drive. That is I will be having a Spread
Sheet in my Google Drive so the data which I require I will upload into
that sheet. Is this possible? And If yes which Api for android should I
use and is there any sample for the same.
I am building an android app in which I was just thinking can I update
required data directly on Google Drive. That is I will be having a Spread
Sheet in my Google Drive so the data which I require I will upload into
that sheet. Is this possible? And If yes which Api for android should I
use and is there any sample for the same.
ActionBar Crash Android
ActionBar Crash Android
pI'm having a problem with the action bar, I explain well. So if I'm on a
tab (selected say) if there cliccassi accidentally crashes the app I wish
there does not happen ... But I can not understand. I'll post a bit 'of
the code that I put in the MAIN ACTIVITY FOR THE CONFIGURATION OF TAB./p
precodeprivate class TabListenerlt;T extends Fragmentgt; implements
ActionBar.TabListener { private Fragment mFragment; private final Activity
mActivity; private final String mTag; private final Classlt;Tgt; mClass;
public TabListener(Activity activity, String tag, Classlt;Tgt; clz) {
mActivity = activity; mTag = tag; mClass = clz; } public void
onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { // Check if the
fragment is already initialized if (mFragment == null) { // If not,
instantiate and add it to the activity mFragment =
Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag); } else { // If it exists,
simply attach it in order to show it ft.show(mFragment);
//ft.attach(mFragment); } } public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction ft) { if (mFragment != null) { // Detach the fragment,
because another one is being attached // ft.detach(mFragment);
ft.hide(mFragment); } } public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction ft) { ft.replace(tab.getPosition(),mFragment); // User
selected the already selected tab. Usually do nothing. } } /code/pre
pI'm having a problem with the action bar, I explain well. So if I'm on a
tab (selected say) if there cliccassi accidentally crashes the app I wish
there does not happen ... But I can not understand. I'll post a bit 'of
the code that I put in the MAIN ACTIVITY FOR THE CONFIGURATION OF TAB./p
precodeprivate class TabListenerlt;T extends Fragmentgt; implements
ActionBar.TabListener { private Fragment mFragment; private final Activity
mActivity; private final String mTag; private final Classlt;Tgt; mClass;
public TabListener(Activity activity, String tag, Classlt;Tgt; clz) {
mActivity = activity; mTag = tag; mClass = clz; } public void
onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { // Check if the
fragment is already initialized if (mFragment == null) { // If not,
instantiate and add it to the activity mFragment =
Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag); } else { // If it exists,
simply attach it in order to show it ft.show(mFragment);
//ft.attach(mFragment); } } public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction ft) { if (mFragment != null) { // Detach the fragment,
because another one is being attached // ft.detach(mFragment);
ft.hide(mFragment); } } public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction ft) { ft.replace(tab.getPosition(),mFragment); // User
selected the already selected tab. Usually do nothing. } } /code/pre
Friday, 23 August 2013
Trying to work with @Html.CheckBox for to display text of enum
Trying to work with @Html.CheckBox for to display text of enum
I started doing this to display some checkboxes in my view:
@Html.LabelFor(m => m.MyEnum, T("Pick Your Poison"))
<div>
@for(int i = 0; i < Model.Alcohol.Count; i++)
{
<label>
@T(Model.Alcohol[i].Text)
@Html.CheckBoxFor(m => Model.Alcohol[i].Selected)
@Html.HiddenFor(m => Model.Alcohol[i].Value)
</label>
}
</div>
PLEASE NOTE: The important thing here is the @T method, which is used to
handle translations of the text into other languages.
This works. I've got a simple enum, and some methods in the back end that
turn it into text in the view. So, an enum such as:
public enum MyEnum
{
Beer = 1,
Vodka = 2,
Rum = 3
}
will display list of checkboxes with those 3 choices. In my ViewModel I do
this:
Alcohol= Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Select(x =>
{
return new SelectListItem {
Text = x.ToString().ToUpper(), Value = ((int)x).ToString()
};
}).ToList();
}
However, I want to have more descriptive text to accompany the checkbox. I
would rather the enum have this or some similar type of system (I will
explain the underscore):
public enum MyEnum
{
I_like_Beer = 1,
I_hate_Vodka = 2,
Meh__Rum = 3
}
I was trying to create a method to strip out the underscore "" and replace
it with a space, and in the case of the double underscore "_" replace it
with a comma, so when the checkboxes displayed they would look like:
I like Beer
I hate Vodka
Meh, Rum
But I don't know how to. Also, I am not sure this would be the best thing
to do. I would love to preserve the @T function because then I can easily
translate things in my app. Otherwise, doing anything else will sort of
kill that for me.
Any examples of what I might should be doing? Thanks.
I started doing this to display some checkboxes in my view:
@Html.LabelFor(m => m.MyEnum, T("Pick Your Poison"))
<div>
@for(int i = 0; i < Model.Alcohol.Count; i++)
{
<label>
@T(Model.Alcohol[i].Text)
@Html.CheckBoxFor(m => Model.Alcohol[i].Selected)
@Html.HiddenFor(m => Model.Alcohol[i].Value)
</label>
}
</div>
PLEASE NOTE: The important thing here is the @T method, which is used to
handle translations of the text into other languages.
This works. I've got a simple enum, and some methods in the back end that
turn it into text in the view. So, an enum such as:
public enum MyEnum
{
Beer = 1,
Vodka = 2,
Rum = 3
}
will display list of checkboxes with those 3 choices. In my ViewModel I do
this:
Alcohol= Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Select(x =>
{
return new SelectListItem {
Text = x.ToString().ToUpper(), Value = ((int)x).ToString()
};
}).ToList();
}
However, I want to have more descriptive text to accompany the checkbox. I
would rather the enum have this or some similar type of system (I will
explain the underscore):
public enum MyEnum
{
I_like_Beer = 1,
I_hate_Vodka = 2,
Meh__Rum = 3
}
I was trying to create a method to strip out the underscore "" and replace
it with a space, and in the case of the double underscore "_" replace it
with a comma, so when the checkboxes displayed they would look like:
I like Beer
I hate Vodka
Meh, Rum
But I don't know how to. Also, I am not sure this would be the best thing
to do. I would love to preserve the @T function because then I can easily
translate things in my app. Otherwise, doing anything else will sort of
kill that for me.
Any examples of what I might should be doing? Thanks.
ASP.NET deployment code?
How to use SVM in Weka?
How to use SVM in Weka?
I'm trying to use the svm classifier in weka. When I click on the libsvm
classifier and try to train a model based on some provided training data,
I get the error "libsvm classes not in CLASSPATH."
The weka website has some information on how to fix this but I'm not sure
how to execute them.
http://weka.wikispaces.com/LibSVM
I got the libsvm.jar file from the link provided. I'm not sure which file
to put it in.
Thank You
I'm trying to use the svm classifier in weka. When I click on the libsvm
classifier and try to train a model based on some provided training data,
I get the error "libsvm classes not in CLASSPATH."
The weka website has some information on how to fix this but I'm not sure
how to execute them.
http://weka.wikispaces.com/LibSVM
I got the libsvm.jar file from the link provided. I'm not sure which file
to put it in.
Thank You
Rendering Performance ffmpeg of JAVACV on Android
Rendering Performance ffmpeg of JAVACV on Android
I am doing an application that creates a video using a set of photos saved
in the sd-card. The problem I am trying to fix is that the application
crashes when I create some videos. The crashes depends of the resolution
of the source picture files. For example, I can render a video using 400
images with a resolution of 320x480 but I can only do a 25-frames video
using images with a resolution of 2500x3200.
I am doing the rendering process in background using Asynctask (for
providing a feedback to the user and maintain it informed of the rendering
process). When the rendering process crashes no warnings/errors/etc are
captured in the logcat. Using the DDMS for examining the memory usage I
can not view any memory leak (I also do not recieve any memory warning on
the logcat). For this reasons I supose that it may be a problem related
with the ffmpeg libraries (but I have no idea).
I have testet different codecs defined on avcodec.java, like:
AV_CODEC_ID_MPEG1VIDEO = 1,
AV_CODEC_ID_MPEG2VIDEO = 2,
AV_CODEC_ID_H263 = 5,
AV_CODEC_ID_MJPEG = 8,
etc
Trying with lossless video codecs seems not doing effect, and I also get
some errors when I try with some codecs.
I am running my application on a Sony Ericsson Xperia Arc (1ghz cpu, 320mb
intern memory).
I do not know if my smartphone has enough power to render a long HD video,
but I see that in the market there are some app's like Droid Timelapse
that can do it.
Any suggestion would be appreciated I have no idea how can I fix that.
Thank you.
I am doing an application that creates a video using a set of photos saved
in the sd-card. The problem I am trying to fix is that the application
crashes when I create some videos. The crashes depends of the resolution
of the source picture files. For example, I can render a video using 400
images with a resolution of 320x480 but I can only do a 25-frames video
using images with a resolution of 2500x3200.
I am doing the rendering process in background using Asynctask (for
providing a feedback to the user and maintain it informed of the rendering
process). When the rendering process crashes no warnings/errors/etc are
captured in the logcat. Using the DDMS for examining the memory usage I
can not view any memory leak (I also do not recieve any memory warning on
the logcat). For this reasons I supose that it may be a problem related
with the ffmpeg libraries (but I have no idea).
I have testet different codecs defined on avcodec.java, like:
AV_CODEC_ID_MPEG1VIDEO = 1,
AV_CODEC_ID_MPEG2VIDEO = 2,
AV_CODEC_ID_H263 = 5,
AV_CODEC_ID_MJPEG = 8,
etc
Trying with lossless video codecs seems not doing effect, and I also get
some errors when I try with some codecs.
I am running my application on a Sony Ericsson Xperia Arc (1ghz cpu, 320mb
intern memory).
I do not know if my smartphone has enough power to render a long HD video,
but I see that in the market there are some app's like Droid Timelapse
that can do it.
Any suggestion would be appreciated I have no idea how can I fix that.
Thank you.
ruby - rspec test not passing
ruby - rspec test not passing
I'm working through the learn ruby tutorials and I'm trying pass the last
example where it tests the printable method. I tested the method by
calling the method directly within my ruby program and it spits out
exactly whats needed. What is preventing my code from properly passing?
Any help is greatly appreciated.
Here's the rspec file:
require 'dictionary'
describe Dictionary do
before do
@d = Dictionary.new
end
it 'is empty when created' do
@d.entries.should == {}
end
it 'can add whole entries with keyword and definition' do
@d.add('fish' => 'aquatic animal')
@d.entries.should == {'fish' => 'aquatic animal'}
@d.keywords.should == ['fish']
end
it 'add keywords (without definition)' do
@d.add('fish')
@d.entries.should == {'fish' => nil}
@d.keywords.should == ['fish']
end
it 'can check whether a given keyword exists' do
@d.include?('fish').should be_false
end
it "doesn't cheat when checking whether a given keyword exists" do
@d.include?('fish').should be_false # if the method is empty, this
test passes with nil returned
@d.add('fish')
@d.include?('fish').should be_true # confirms that it actually checks
@d.include?('bird').should be_false # confirms not always returning
true after add
end
it "doesn't include a prefix that wasn't added as a word in and of
itself" do
@d.add('fish')
@d.include?('fi').should be_false
end
it "doesn't find a word in empty dictionary" do
@d.find('fi').should be_empty # {}
end
it 'finds nothing if the prefix matches nothing' do
@d.add('fiend')
@d.add('great')
@d.find('nothing').should be_empty
end
it "finds an entry" do
@d.add('fish' => 'aquatic animal')
@d.find('fish').should == {'fish' => 'aquatic animal'}
end
it 'finds multiple matches from a prefix and returns the entire entry
(keyword + definition)' do
@d.add('fish' => 'aquatic animal')
@d.add('fiend' => 'wicked person')
@d.add('great' => 'remarkable')
@d.find('fi').should == {'fish' => 'aquatic animal', 'fiend' =>
'wicked person'}
end
it 'lists keywords alphabetically' do
@d.add('zebra' => 'African land animal with stripes')
@d.add('fish' => 'aquatic animal')
@d.add('apple' => 'fruit')
@d.keywords.should == %w(apple fish zebra)
end
it 'can produce printable output like so: [keyword] "definition"' do
@d.add('zebra' => 'African land animal with stripes')
@d.add('fish' => 'aquatic animal')
@d.add('apple' => 'fruit')
@d.printable.should == %Q{[apple] "fruit"\n[fish] "aquatic
animal"\n[zebra] "African land animal with stripes"}
end
end
and here's what I've created so far for the printable function:
class Dictionary def initialize(opts = {}) @opts = opts end
def entries
@opts
end
def add(opts)
opts.is_a?(String) ? @opts.merge!(opts => nil) : @opts.merge!(opts)
end
def keywords
@opts.keys.sort
end
def include?(key)
@opts.has_key?(key)
end
def find(key)
@opts.select { |word,defin| word.scan(key).join == key }
end
def printable
opts_sorted = @opts.sort_by { |word,defin| word}
opts_sorted.each do |word,defin|
print "[#{word}] \"#{defin}\"\n"
end
end
end
and here's the error:
1) Dictionary can produce printable output like so: [keyword] "definition"
Failure/Error: @d.printable.should == %Q{[apple] "fruit"\n[fish]
"aquatic animal
"\n[zebra] "African land animal with stripes"}
expected: "[apple] \"fruit\"\n[fish] \"aquatic animal\"\n[zebra]
\"African lan
d animal with stripes\""
got: [["apple", "fruit"], ["fish", "aquatic animal"],
["zebra", "African
land animal with stripes"]] (using ==)
Diff:
@@ -1,4 +1,4 @@
-[apple] "fruit"
-[fish] "aquatic animal"
-[zebra] "African land animal with stripes"
+["apple", "fruit"]
+["fish", "aquatic animal"]
+["zebra", "African land animal with stripes"]
# ./11_dictionary/dictionary_spec.rb:81:in `block (2 levels) in <top
(required)>
'
I'm working through the learn ruby tutorials and I'm trying pass the last
example where it tests the printable method. I tested the method by
calling the method directly within my ruby program and it spits out
exactly whats needed. What is preventing my code from properly passing?
Any help is greatly appreciated.
Here's the rspec file:
require 'dictionary'
describe Dictionary do
before do
@d = Dictionary.new
end
it 'is empty when created' do
@d.entries.should == {}
end
it 'can add whole entries with keyword and definition' do
@d.add('fish' => 'aquatic animal')
@d.entries.should == {'fish' => 'aquatic animal'}
@d.keywords.should == ['fish']
end
it 'add keywords (without definition)' do
@d.add('fish')
@d.entries.should == {'fish' => nil}
@d.keywords.should == ['fish']
end
it 'can check whether a given keyword exists' do
@d.include?('fish').should be_false
end
it "doesn't cheat when checking whether a given keyword exists" do
@d.include?('fish').should be_false # if the method is empty, this
test passes with nil returned
@d.add('fish')
@d.include?('fish').should be_true # confirms that it actually checks
@d.include?('bird').should be_false # confirms not always returning
true after add
end
it "doesn't include a prefix that wasn't added as a word in and of
itself" do
@d.add('fish')
@d.include?('fi').should be_false
end
it "doesn't find a word in empty dictionary" do
@d.find('fi').should be_empty # {}
end
it 'finds nothing if the prefix matches nothing' do
@d.add('fiend')
@d.add('great')
@d.find('nothing').should be_empty
end
it "finds an entry" do
@d.add('fish' => 'aquatic animal')
@d.find('fish').should == {'fish' => 'aquatic animal'}
end
it 'finds multiple matches from a prefix and returns the entire entry
(keyword + definition)' do
@d.add('fish' => 'aquatic animal')
@d.add('fiend' => 'wicked person')
@d.add('great' => 'remarkable')
@d.find('fi').should == {'fish' => 'aquatic animal', 'fiend' =>
'wicked person'}
end
it 'lists keywords alphabetically' do
@d.add('zebra' => 'African land animal with stripes')
@d.add('fish' => 'aquatic animal')
@d.add('apple' => 'fruit')
@d.keywords.should == %w(apple fish zebra)
end
it 'can produce printable output like so: [keyword] "definition"' do
@d.add('zebra' => 'African land animal with stripes')
@d.add('fish' => 'aquatic animal')
@d.add('apple' => 'fruit')
@d.printable.should == %Q{[apple] "fruit"\n[fish] "aquatic
animal"\n[zebra] "African land animal with stripes"}
end
end
and here's what I've created so far for the printable function:
class Dictionary def initialize(opts = {}) @opts = opts end
def entries
@opts
end
def add(opts)
opts.is_a?(String) ? @opts.merge!(opts => nil) : @opts.merge!(opts)
end
def keywords
@opts.keys.sort
end
def include?(key)
@opts.has_key?(key)
end
def find(key)
@opts.select { |word,defin| word.scan(key).join == key }
end
def printable
opts_sorted = @opts.sort_by { |word,defin| word}
opts_sorted.each do |word,defin|
print "[#{word}] \"#{defin}\"\n"
end
end
end
and here's the error:
1) Dictionary can produce printable output like so: [keyword] "definition"
Failure/Error: @d.printable.should == %Q{[apple] "fruit"\n[fish]
"aquatic animal
"\n[zebra] "African land animal with stripes"}
expected: "[apple] \"fruit\"\n[fish] \"aquatic animal\"\n[zebra]
\"African lan
d animal with stripes\""
got: [["apple", "fruit"], ["fish", "aquatic animal"],
["zebra", "African
land animal with stripes"]] (using ==)
Diff:
@@ -1,4 +1,4 @@
-[apple] "fruit"
-[fish] "aquatic animal"
-[zebra] "African land animal with stripes"
+["apple", "fruit"]
+["fish", "aquatic animal"]
+["zebra", "African land animal with stripes"]
# ./11_dictionary/dictionary_spec.rb:81:in `block (2 levels) in <top
(required)>
'
Thursday, 22 August 2013
Extract site that HTML document came from
Extract site that HTML document came from
I have a folder full of HTML documents that are saved copies of webpages,
but i need to know what site they came from, what function can i use to
extract the website name from the documents? I did not find anything in
the BeautifulSoup module. Is there a specific tag that i should be looking
for in the document?
I have a folder full of HTML documents that are saved copies of webpages,
but i need to know what site they came from, what function can i use to
extract the website name from the documents? I did not find anything in
the BeautifulSoup module. Is there a specific tag that i should be looking
for in the document?
HTML Tree Diagram using JSON data
HTML Tree Diagram using JSON data
So I've got some JSON like this (keys/values changed for privacy reasons).
It's basically an Object with a "children" array of Objects, with each
element having its own "children" array of Objects, et cetera.
{
"name": "Main Area",
"children": [
{
"name": "Sub-section A",
"children": [
{
"name": "Procedure 1"
"children": [
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
}
]
},
{
"name": "Procedure 2"
"children": [
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
}
]
},
{
"name": "Procedure 3"
"children": [
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
}
]
},
]
}
]
}
... and it's possible that that gets several times larger/deeper as I go
along. The goal here is to transform this data into a (collapsable) tree
diagram and then showing it on a HTML page using knockout.js (preferably).
All the logic has to be JavaScript code though (grab JSON with jQuery
AJAX, treat it in some way, show it).
Like this only then rotated 90 degrees so it goes down and not to the
side.
http://www.education.vic.gov.au/images/content/studentlearning/mathscontinuum/icecream.gif
Now I know that there are libraries like jsTree out there, but the point
is that I want this to be a learning experience as well so I want to
create my own code here. Also, jsTree prints its structures like a
directory tree. The thing I'm looking for is a more visual top-down tree
diagram that fills the whole width of the page.
Thing is, I'm stuck. I just can't wrap my head around all these nested
arrays/objects. I've probably spent about 3 hours trying things, creating
several different functions to iterate recursively through the entire
array but I can't get it to work right.
The latest idea that crossed my mind was to somehow go through the JSON
structure, starting from the deepest element, moving upwards, somehow
translating the steps into tree diagram levels, until I reach the top, at
which point it's finished.
So, willing to point me in the right direction? You don't have to write
dozens of lines of code for me, just give me an indication, some
pseudocode perhaps, of where I should take this.
Thanks in advance!
So I've got some JSON like this (keys/values changed for privacy reasons).
It's basically an Object with a "children" array of Objects, with each
element having its own "children" array of Objects, et cetera.
{
"name": "Main Area",
"children": [
{
"name": "Sub-section A",
"children": [
{
"name": "Procedure 1"
"children": [
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
}
]
},
{
"name": "Procedure 2"
"children": [
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
}
]
},
{
"name": "Procedure 3"
"children": [
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
}
]
},
]
}
]
}
... and it's possible that that gets several times larger/deeper as I go
along. The goal here is to transform this data into a (collapsable) tree
diagram and then showing it on a HTML page using knockout.js (preferably).
All the logic has to be JavaScript code though (grab JSON with jQuery
AJAX, treat it in some way, show it).
Like this only then rotated 90 degrees so it goes down and not to the
side.
http://www.education.vic.gov.au/images/content/studentlearning/mathscontinuum/icecream.gif
Now I know that there are libraries like jsTree out there, but the point
is that I want this to be a learning experience as well so I want to
create my own code here. Also, jsTree prints its structures like a
directory tree. The thing I'm looking for is a more visual top-down tree
diagram that fills the whole width of the page.
Thing is, I'm stuck. I just can't wrap my head around all these nested
arrays/objects. I've probably spent about 3 hours trying things, creating
several different functions to iterate recursively through the entire
array but I can't get it to work right.
The latest idea that crossed my mind was to somehow go through the JSON
structure, starting from the deepest element, moving upwards, somehow
translating the steps into tree diagram levels, until I reach the top, at
which point it's finished.
So, willing to point me in the right direction? You don't have to write
dozens of lines of code for me, just give me an indication, some
pseudocode perhaps, of where I should take this.
Thanks in advance!
validating uniqueness of has_many association with a string "checksum"
validating uniqueness of has_many association with a string "checksum"
I had an idea to validate the uniqueness of a has_many association: what
if we generate a string based on the ids of the associated records?
For example:
class Exam
has_many :problems
validate :checksum, uniqueness: true #string
before_validate :check
def check
checksum = problems.map {|p| p.id}.join
end
end
(I'm not sure if "checksum" is the right term.)
Does anyone have thoughts on this approach? Is there a better way to
validate uniqueness of has_many?
I had an idea to validate the uniqueness of a has_many association: what
if we generate a string based on the ids of the associated records?
For example:
class Exam
has_many :problems
validate :checksum, uniqueness: true #string
before_validate :check
def check
checksum = problems.map {|p| p.id}.join
end
end
(I'm not sure if "checksum" is the right term.)
Does anyone have thoughts on this approach? Is there a better way to
validate uniqueness of has_many?
QThread finished() emitting fails if called inside window closing
QThread finished() emitting fails if called inside window closing
I have done an application with some threads. Everything seems to work ok
if I call my stopConsumer inside a keypressedEvent. But If I call it
inside a destructor of closeEvent.. it fails.
My QThread class that has a run method like this one:
void Consumer::run()
{
forever {
// do something something
// do something something
// do something something
//-------------------------------- check for abort
abortMutex.lock();
if(abort) {
abortMutex.unlock();
qDebug() << "abort..";
break;
} abortMutex.unlock();
//-------------------------------- check for abort
}
qDebug() << "Consumer > emit finished()";
emit finished();
}
void Consumer::stopConsume() {
abortMutex.lock();
abort = true;
abortMutex.unlock();
}
and a method in the MainWindow:
void initConsumers()
{
consumer1 = new Consumer(....);
connect(consumer1, SIGNAL(finished()),
this, SLOT(deleteConsumer()));
consumer1->start();
}
void stopConsumer() {
if(consumer1!=NULL) {
qDebug() << "stopConsumer";
consumer1->stopConsume();
}
}
If I have a keypressed that calls stopConsumer.. it's ok, deleteConsumer
is reached.
If I call stopConsumer inside the MainWindow destructor or inside a
MainWindow closeEvent.. the slot deleteConsumer is never reached!
Any ideas?
I have done an application with some threads. Everything seems to work ok
if I call my stopConsumer inside a keypressedEvent. But If I call it
inside a destructor of closeEvent.. it fails.
My QThread class that has a run method like this one:
void Consumer::run()
{
forever {
// do something something
// do something something
// do something something
//-------------------------------- check for abort
abortMutex.lock();
if(abort) {
abortMutex.unlock();
qDebug() << "abort..";
break;
} abortMutex.unlock();
//-------------------------------- check for abort
}
qDebug() << "Consumer > emit finished()";
emit finished();
}
void Consumer::stopConsume() {
abortMutex.lock();
abort = true;
abortMutex.unlock();
}
and a method in the MainWindow:
void initConsumers()
{
consumer1 = new Consumer(....);
connect(consumer1, SIGNAL(finished()),
this, SLOT(deleteConsumer()));
consumer1->start();
}
void stopConsumer() {
if(consumer1!=NULL) {
qDebug() << "stopConsumer";
consumer1->stopConsume();
}
}
If I have a keypressed that calls stopConsumer.. it's ok, deleteConsumer
is reached.
If I call stopConsumer inside the MainWindow destructor or inside a
MainWindow closeEvent.. the slot deleteConsumer is never reached!
Any ideas?
The gsutil tool is not working to register a channel in object change notification
The gsutil tool is not working to register a channel in object change
notification
When executin the follow command:
gsutil notifyconfig watchbucket -i myapp-channel -t myapp-token
https://myapp.appspot.com/gcsnotify gs://mybucket
I receive the follow answer, but I used the same command before in another
buckets and it worked:
Watching bucket gs://mybucket/ with application URL
https://myapp.appspot.com/gcsnotify...
Failure: <HttpError 401 when requesting
https://www.googleapis.com/storage/v1beta2/b/mybucket/o/watch?alt=json
returned "Unauthorized WebHook callback channel:
https://myapp.appspot.com/gcsnotify">.
I already tried to set the permissions, made myself owner of the project,
but is not working, any help?
notification
When executin the follow command:
gsutil notifyconfig watchbucket -i myapp-channel -t myapp-token
https://myapp.appspot.com/gcsnotify gs://mybucket
I receive the follow answer, but I used the same command before in another
buckets and it worked:
Watching bucket gs://mybucket/ with application URL
https://myapp.appspot.com/gcsnotify...
Failure: <HttpError 401 when requesting
https://www.googleapis.com/storage/v1beta2/b/mybucket/o/watch?alt=json
returned "Unauthorized WebHook callback channel:
https://myapp.appspot.com/gcsnotify">.
I already tried to set the permissions, made myself owner of the project,
but is not working, any help?
What kind of data to use for training new language for Tesseract OCR
What kind of data to use for training new language for Tesseract OCR
I want to findout what kind of data we will use to train the new language
for Tesseract OCR?
Is it each character? Or we have to make some specific sentences?
Please help to give some source of this information, I can't get clearly
on its wiki page.
I want to findout what kind of data we will use to train the new language
for Tesseract OCR?
Is it each character? Or we have to make some specific sentences?
Please help to give some source of this information, I can't get clearly
on its wiki page.
How to recompile Chrome Embedded for Delphi XE2
How to recompile Chrome Embedded for Delphi XE2
I have downloaded the DCEF3 from here. It works well in Delphi XE2 but
there is a huge problem :
I cannot play MP3 files with HTML5 using Embedded Chrome. I searched a lot
and finally found this topic. As I understood, I must edit the file
cef.gypi and then recompile the C++ version. Now I've downloaded the main
source code placed here. But I do not have any idea how to recompile these
files for using in Delphi XE2. Would anybody tell me how can I recompile
the CEF source code for using it in my client side windows application?
I have downloaded the DCEF3 from here. It works well in Delphi XE2 but
there is a huge problem :
I cannot play MP3 files with HTML5 using Embedded Chrome. I searched a lot
and finally found this topic. As I understood, I must edit the file
cef.gypi and then recompile the C++ version. Now I've downloaded the main
source code placed here. But I do not have any idea how to recompile these
files for using in Delphi XE2. Would anybody tell me how can I recompile
the CEF source code for using it in my client side windows application?
Wednesday, 21 August 2013
Mongo hadoop driver dependency not found
Mongo hadoop driver dependency not found
While running ./sbt I am getting the following dependency error:
http://repo1.maven.org/maven2/org/scala-tools/sbinary/sbinary_2.9.0/0.
4.0/sbinary_2.9.0-0.4.0.pom
==== sonatype-snapshots: tried
https://oss.sonatype.org/content/repositories/snapshots/org/scala-tool
s/sbinary/sbinary_2.9.0/0.4.0/sbinary_2.9.0-0.4.0.pom
::::::::::::::::::::::::::::::::::::::::::::::
:: UNRESOLVED DEPENDENCIES ::
::::::::::::::::::::::::::::::::::::::::::::::
:: org.scala-tools.sbinary#sbinary_2.9.0;0.4.0: not found
::::::::::::::::::::::::::::::::::::::::::::::
While running ./sbt I am getting the following dependency error:
http://repo1.maven.org/maven2/org/scala-tools/sbinary/sbinary_2.9.0/0.
4.0/sbinary_2.9.0-0.4.0.pom
==== sonatype-snapshots: tried
https://oss.sonatype.org/content/repositories/snapshots/org/scala-tool
s/sbinary/sbinary_2.9.0/0.4.0/sbinary_2.9.0-0.4.0.pom
::::::::::::::::::::::::::::::::::::::::::::::
:: UNRESOLVED DEPENDENCIES ::
::::::::::::::::::::::::::::::::::::::::::::::
:: org.scala-tools.sbinary#sbinary_2.9.0;0.4.0: not found
::::::::::::::::::::::::::::::::::::::::::::::
Explanation of the "rel" attribute?
Explanation of the "rel" attribute?
I'm trying to understand exactly what the "rel" attribute does in
reference to anchor tags, and it's not making a whole lot of sense - I
understand that it's got something to do with relationships between things
(documents? elements?) but I don't really get anything past that - would
someone be willing to break it down for me? (Preferably with examples if
possible)
I'm trying to understand exactly what the "rel" attribute does in
reference to anchor tags, and it's not making a whole lot of sense - I
understand that it's got something to do with relationships between things
(documents? elements?) but I don't really get anything past that - would
someone be willing to break it down for me? (Preferably with examples if
possible)
Can a VBA module be made to be separate instances
Can a VBA module be made to be separate instances
I have spent quite a bit of time work ing on a project under the
assumstion that each sheet in an excell book would use an instance of the
module I was writing. I have multiple sheets that are all the same
template but the sheets are specific to the type of data being stored. In
the module I have setters and getters however, I was expecting the getters
on a given sheet to only access the varibles set by the setters on that
same sheet (an instance of the module). As it turns out all of the sheets
are using the same instance of the module and the setters are over-riding
each other, so that only one sheet has acurate results calculated by the
module. I don't want to get into TMI but the setters provide data that is
used to format the raw data provided by the getters. Is there a way to
make each sheet have an instance of the module with out having to code
each and every sheet. What I mean by that is, when the operator has new
set of relults to be stored and processed they just copy the sheet in
excell and put the data on that new sheet. I don't want the operator to
need to modify the code. I have tried to explain this but I am not sure I
did a good job explaining it properly. Is there a way to make separate
instances of the module?
I have spent quite a bit of time work ing on a project under the
assumstion that each sheet in an excell book would use an instance of the
module I was writing. I have multiple sheets that are all the same
template but the sheets are specific to the type of data being stored. In
the module I have setters and getters however, I was expecting the getters
on a given sheet to only access the varibles set by the setters on that
same sheet (an instance of the module). As it turns out all of the sheets
are using the same instance of the module and the setters are over-riding
each other, so that only one sheet has acurate results calculated by the
module. I don't want to get into TMI but the setters provide data that is
used to format the raw data provided by the getters. Is there a way to
make each sheet have an instance of the module with out having to code
each and every sheet. What I mean by that is, when the operator has new
set of relults to be stored and processed they just copy the sheet in
excell and put the data on that new sheet. I don't want the operator to
need to modify the code. I have tried to explain this but I am not sure I
did a good job explaining it properly. Is there a way to make separate
instances of the module?
JMS message not acknowledged error
JMS message not acknowledged error
I am getting this message not acknowledged error:
javax.jms.IllegalStateException: Message not delivered
at
com.tibco.tibjms.TibjmsxSessionImp._confirmNonTransacted(TibjmsxSessionImp.java:3295)
at com.tibco.tibjms.TibjmsxSessionImp._confirm(TibjmsxSessionImp.java:3644)
at
com.tibco.tibjms.TibjmsxSessionImp._confirmNonAuto(TibjmsxSessionImp.java:4980)
at com.tibco.tibjms.TibjmsMessage.acknowledge(TibjmsMessage.java:609)
Here is my code:
public processMessage(Message pMessage){
try{
performOperation();
}
catch(Exception e){
}finally{
if (pMessage != null) {
try {
pMessage.acknowledge();
} catch (Exception e) {
try {
if (pMessage.getJMSRedelivered()) {
log.info("Message has been redelivered");
} else
log.error(("Message has not been delivered"),e);
} catch (JMSException e1) {
log.error(e1);
}
}
}
return null;
}
}
I am getting this message not acknowledged error:
javax.jms.IllegalStateException: Message not delivered
at
com.tibco.tibjms.TibjmsxSessionImp._confirmNonTransacted(TibjmsxSessionImp.java:3295)
at com.tibco.tibjms.TibjmsxSessionImp._confirm(TibjmsxSessionImp.java:3644)
at
com.tibco.tibjms.TibjmsxSessionImp._confirmNonAuto(TibjmsxSessionImp.java:4980)
at com.tibco.tibjms.TibjmsMessage.acknowledge(TibjmsMessage.java:609)
Here is my code:
public processMessage(Message pMessage){
try{
performOperation();
}
catch(Exception e){
}finally{
if (pMessage != null) {
try {
pMessage.acknowledge();
} catch (Exception e) {
try {
if (pMessage.getJMSRedelivered()) {
log.info("Message has been redelivered");
} else
log.error(("Message has not been delivered"),e);
} catch (JMSException e1) {
log.error(e1);
}
}
}
return null;
}
}
LinearLayout's width and height are zero
LinearLayout's width and height are zero
I have the problem, that if I try to get my height and width with
LinearLayout.getWidth() and LinearLayout.getHeight(), the int I get is 0.
This is my onCreat:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View mainView = getLayoutInflater().inflate(R.layout.activity_game,
null);
LinearLayout container = (LinearLayout)
mainView.findViewById(R.id.container);
view = new GameLayout(this, container.getWidth(), container.getHeight());
container.addView(view);
setContentView(mainView);
view.setOnClickListener(this);
}
If you have any idea, what I am doing wrong, pls help.
I need this for getting the size of my Layout, because I want, to position
my Bitmap at the same percental place on every device (for example every
time at the exact center of the screen).
I have the problem, that if I try to get my height and width with
LinearLayout.getWidth() and LinearLayout.getHeight(), the int I get is 0.
This is my onCreat:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View mainView = getLayoutInflater().inflate(R.layout.activity_game,
null);
LinearLayout container = (LinearLayout)
mainView.findViewById(R.id.container);
view = new GameLayout(this, container.getWidth(), container.getHeight());
container.addView(view);
setContentView(mainView);
view.setOnClickListener(this);
}
If you have any idea, what I am doing wrong, pls help.
I need this for getting the size of my Layout, because I want, to position
my Bitmap at the same percental place on every device (for example every
time at the exact center of the screen).
Setting javascript variables from html input field
Setting javascript variables from html input field
This is more of a coding practice question, I want to set variables within
a javascript object / array from a html form.
I am currently doing this using the onkeyup and passing the value to a set
function. e.g: (along the lines of )
onclick="item.setVar('retouch', this.value); return false;"
setVar: function(variable, value){
this[variable] = parseInt(value);
}
is there a better way of doing this or is it down to personal preference.
I have re-written the code so I can specify which values to get and set.
This is more of a coding practice question, I want to set variables within
a javascript object / array from a html form.
I am currently doing this using the onkeyup and passing the value to a set
function. e.g: (along the lines of )
onclick="item.setVar('retouch', this.value); return false;"
setVar: function(variable, value){
this[variable] = parseInt(value);
}
is there a better way of doing this or is it down to personal preference.
I have re-written the code so I can specify which values to get and set.
how to make values appear in forms when form has model with associations with other models in rails
how to make values appear in forms when form has model with associations
with other models in rails
This form makes sure that the data already in the database is displayed in
it if the user has previously entered them and has now come back to update
the already given data or new data.
<%= simple_form_for resource, :as => resource_name, :url =>
registration_path(resource_name), :html => { :method => :put, :multipart
=> true } do |f| %>
<%= devise_error_messages! %>
<div id="tabs-1" class="ui-tabs-panel">
<div><%= f.label :email %><br />
<%= f.email_field :email, :autofocus => true, :readonly => true %></div>
<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
<div>Currently waiting confirmation for: <%= resource.unconfirmed_email
%></div>
<% end %>
<div><%= f.label :password %> <i>(leave blank if you don't want to
change it)</i><br />
<%= f.password_field :password, :autocomplete => "off" %></div>
<div><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %></div>
<div><%= f.label :current_password %> <i>(we need your current
password to confirm your changes)</i><br />
<%= f.password_field :current_password %></div>
</div>
Now this works as required. Now consider the situation where this model User
has_one :profile associations
with the profile model and also has
accepts_nested_attributes_for :profile
in the user.rb file.
Now coming back to the form if inside the above form we have the following
<%= f.fields_for :profile, @user.profile do |prof| %>
<% if @user.profile.first_name ==nil %>
<%= prof.label :first_name%><br/>
<%= prof.text_field :first_name %>
<%else%>
<div class="field">
<%= prof.label :first_name %><br />
<%= prof.text_field :first_name %>
</div>
<%end%>
<div class="field">
<%= prof.label :last_name %><br />
<%= prof.text_field :last_name %>
</div>
<div class="field">
<%= prof.label :address %><br />
<%= prof.text_area :address %>
</div>
Now no data that has been already entered by the user is seen in the form
when he comes back to update the form. Why is this happening?
with other models in rails
This form makes sure that the data already in the database is displayed in
it if the user has previously entered them and has now come back to update
the already given data or new data.
<%= simple_form_for resource, :as => resource_name, :url =>
registration_path(resource_name), :html => { :method => :put, :multipart
=> true } do |f| %>
<%= devise_error_messages! %>
<div id="tabs-1" class="ui-tabs-panel">
<div><%= f.label :email %><br />
<%= f.email_field :email, :autofocus => true, :readonly => true %></div>
<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
<div>Currently waiting confirmation for: <%= resource.unconfirmed_email
%></div>
<% end %>
<div><%= f.label :password %> <i>(leave blank if you don't want to
change it)</i><br />
<%= f.password_field :password, :autocomplete => "off" %></div>
<div><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %></div>
<div><%= f.label :current_password %> <i>(we need your current
password to confirm your changes)</i><br />
<%= f.password_field :current_password %></div>
</div>
Now this works as required. Now consider the situation where this model User
has_one :profile associations
with the profile model and also has
accepts_nested_attributes_for :profile
in the user.rb file.
Now coming back to the form if inside the above form we have the following
<%= f.fields_for :profile, @user.profile do |prof| %>
<% if @user.profile.first_name ==nil %>
<%= prof.label :first_name%><br/>
<%= prof.text_field :first_name %>
<%else%>
<div class="field">
<%= prof.label :first_name %><br />
<%= prof.text_field :first_name %>
</div>
<%end%>
<div class="field">
<%= prof.label :last_name %><br />
<%= prof.text_field :last_name %>
</div>
<div class="field">
<%= prof.label :address %><br />
<%= prof.text_area :address %>
</div>
Now no data that has been already entered by the user is seen in the form
when he comes back to update the form. Why is this happening?
Tuesday, 20 August 2013
Why there is no preprocessing stage in java?
Why there is no preprocessing stage in java?
I understand there are number of problems we have with this stage during
compilation in previous languages
like for example ::
#define PI_PLUS_ONE (3.14 + 1)
x = PI_PLUS_ONE * 5; // a line of code
if i don't use parenthesis i will be getting different result than the
expected output. So what i want to say is if we understand it very well we
can take it advantages one of it is type neutral in defining constants.
What Are the reasons(main) behind the restriction of this stage in java?
Thanks in Advance for help!
I understand there are number of problems we have with this stage during
compilation in previous languages
like for example ::
#define PI_PLUS_ONE (3.14 + 1)
x = PI_PLUS_ONE * 5; // a line of code
if i don't use parenthesis i will be getting different result than the
expected output. So what i want to say is if we understand it very well we
can take it advantages one of it is type neutral in defining constants.
What Are the reasons(main) behind the restriction of this stage in java?
Thanks in Advance for help!
How can I get client ID and redirect URL when a user login to instagram through my site?
How can I get client ID and redirect URL when a user login to instagram
through my site?
I really need them to import their images into my site..
In their documentation they authenticate a use with a response code by the
following url
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
The above url gimme only a code not all the images. And this is not my
target. Actually when a user come to my site and click on the instagram
login button with the user name and password then I need to import all the
images of the logged in user into my site.
Is that possible. I appreciate your inspiration and waiting for a best
solution...
Thanks in advance
through my site?
I really need them to import their images into my site..
In their documentation they authenticate a use with a response code by the
following url
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
The above url gimme only a code not all the images. And this is not my
target. Actually when a user come to my site and click on the instagram
login button with the user name and password then I need to import all the
images of the logged in user into my site.
Is that possible. I appreciate your inspiration and waiting for a best
solution...
Thanks in advance
How to get original string prefix in boost regex_search
How to get original string prefix in boost regex_search
I am using regex_search in boost like this:
std::string symbol = "abcd1234";
boost::regex regExpr("(\\d{4})", boost::regex::icase);
boost::smatch regMatch;
boost::regex_search(symbol, regMatch, regExpr);
What I need to get is: "abcd", i.e. the original string up to the first
matched reg expression. How is this possible? thanks in advance...
I am using regex_search in boost like this:
std::string symbol = "abcd1234";
boost::regex regExpr("(\\d{4})", boost::regex::icase);
boost::smatch regMatch;
boost::regex_search(symbol, regMatch, regExpr);
What I need to get is: "abcd", i.e. the original string up to the first
matched reg expression. How is this possible? thanks in advance...
MV4 Routing Dynamic Routing from MySQL Database
MV4 Routing Dynamic Routing from MySQL Database
I have the following sample data from a MySQL table.
My question is in my MVC 4 project how can I get routing to work so that
if a user goes to the URL www.mydomain.com/products/apples/ I want the
call to actually be the view of www.mydomain.com/products/index/1, how do
I achieve this ?
I have the following sample data from a MySQL table.
My question is in my MVC 4 project how can I get routing to work so that
if a user goes to the URL www.mydomain.com/products/apples/ I want the
call to actually be the view of www.mydomain.com/products/index/1, how do
I achieve this ?
Selenium Webdriver - Not able to enter text in a textbox through sendKeys()
Selenium Webdriver - Not able to enter text in a textbox through sendKeys()
Not able to enter text in a textbox through sendKeys(). It is a email id
textbox. Following is the entire code
<div class="line split_column"> <div class="unit control size1of1">
<div id="contacts_selector_list" class="option_selector" style="display:
block; position: relative; z-index: 3;">
<div class="input full_width_input selector_input_box">
<div class="drop_down_container mtn"
style="display: none;"> </div> </div> </div>
Not able to enter text in a textbox through sendKeys(). It is a email id
textbox. Following is the entire code
<div class="line split_column"> <div class="unit control size1of1">
<div id="contacts_selector_list" class="option_selector" style="display:
block; position: relative; z-index: 3;">
<div class="input full_width_input selector_input_box">
<div class="drop_down_container mtn"
style="display: none;"> </div> </div> </div>
Monday, 19 August 2013
When colimit of subobjects is still a subobject?
When colimit of subobjects is still a subobject?
What are the conditions on a category (or on a certain object) that will
guarantee that the colimit of a family of subobjects of a given object is
a subobject of the same object?
What are the conditions on a category (or on a certain object) that will
guarantee that the colimit of a family of subobjects of a given object is
a subobject of the same object?
Java How to get the global mouse cursor type (busy, pointer, re-size...) cross OS solution?
Java How to get the global mouse cursor type (busy, pointer, re-size...)
cross OS solution?
I am having a trouble to find a correct and optimized way to detect the
global mouse cursor type (and bitmap) is there any solution that would
work across different OS (Windows, Linux, Mac) ?
cross OS solution?
I am having a trouble to find a correct and optimized way to detect the
global mouse cursor type (and bitmap) is there any solution that would
work across different OS (Windows, Linux, Mac) ?
Regex Exact Number of Characters
Regex Exact Number of Characters
How to limit the number of characters (alpha or numeric or anything)
Example I have (x can be any character)
name.xxx-XXX-XXXXXX-name
name.XXXXXXX-name
I want to exclude those of the first format and I thought I should do
something like
name.{7}*-name
I only want those with 7 characters between . and -
How to limit the number of characters (alpha or numeric or anything)
Example I have (x can be any character)
name.xxx-XXX-XXXXXX-name
name.XXXXXXX-name
I want to exclude those of the first format and I thought I should do
something like
name.{7}*-name
I only want those with 7 characters between . and -
Differences between Keyword Arguments in Ruby 2.0 and Interleaved method signatures in Objective-C
Differences between Keyword Arguments in Ruby 2.0 and Interleaved method
signatures in Objective-C
I've been playing with MacRuby, and noticing how it extends Ruby to be
able to handle the Smalltalk-like method (or message) signatures of
Objective-C. At first glance, I thought that it looked a lot like the new
Keyword Arguments of Ruby 2.0, but further inspection shows that they work
in a fundamentally different way.
My first clue was when reading the MacRuby method spec on GitHub.
it "can have multiple arguments with the same name" do
def @o.doSomething(x, withObject:y, withObject:z); x + y + z; end
@o.should have_method(:'doSomething:withObject:withObject:')
@o.should_not have_method(:'doSomething')
end
As far as I know, that behavior is not allowed in Ruby 2.0, because the
withObject: part would be used as the sole identifier for the parameter,
and therefore there could not be two with the same name.
Is this an insurmountable problem? Will MacRuby be forced to remain with
Ruby 1.9 because of this?
signatures in Objective-C
I've been playing with MacRuby, and noticing how it extends Ruby to be
able to handle the Smalltalk-like method (or message) signatures of
Objective-C. At first glance, I thought that it looked a lot like the new
Keyword Arguments of Ruby 2.0, but further inspection shows that they work
in a fundamentally different way.
My first clue was when reading the MacRuby method spec on GitHub.
it "can have multiple arguments with the same name" do
def @o.doSomething(x, withObject:y, withObject:z); x + y + z; end
@o.should have_method(:'doSomething:withObject:withObject:')
@o.should_not have_method(:'doSomething')
end
As far as I know, that behavior is not allowed in Ruby 2.0, because the
withObject: part would be used as the sole identifier for the parameter,
and therefore there could not be two with the same name.
Is this an insurmountable problem? Will MacRuby be forced to remain with
Ruby 1.9 because of this?
Saving string with xml
Saving string with xml
why if I save my variables and load them back then companyName and
playerName is this: System.Xml.XmlElement, instead of what I write? Other
variables works just fine. I am struggling with this for a while, so I
would really appreciate any help, thanks.
public void LoadGamePrefs()
{
string filepath = "c:/Users/gamePrefs.xml";
XmlDocument xmlDoc = new XmlDocument();
if(File.Exists (filepath))
{
xmlDoc.Load(filepath);
XmlNodeList transformList = xmlDoc.GetElementsByTagName("GamePrefs");
foreach (XmlNode transformInfo in transformList)
{
XmlNodeList transformcontent = transformInfo.ChildNodes;
foreach (XmlNode transformItems in transformcontent)
{
if(transformItems.Name == "firstStart")
{
firstStart = bool.Parse(transformItems.InnerText);
}
if(transformItems.Name == "drawFirstGui")
{
drawFirstStartGui = bool.Parse(transformItems.InnerText);
}
if(transformItems.Name == "companyName")
{
companyName = transformItems.InnerText;
}
if(transformItems.Name == "playerName")
{
playerName = transformItems.InnerText;
}
if(transformItems.Name == "money")
{
scriptMainBackground.money =
int.Parse(transformItems.InnerText);
}
if(transformItems.Name == "year")
{
year = int.Parse(transformItems.InnerText);
}
if(transformItems.Name == "month")
{
month = int.Parse(transformItems.InnerText);
}
if(transformItems.Name == "week")
{
week = int.Parse(transformItems.InnerText);
}
if(transformItems.Name == "day")
{
day = int.Parse(transformItems.InnerText);
}
}
}
}
}
public void SaveGamePrefs()
{
// Accesing other script and variable
GameObject mainBackground =
GameObject.FindGameObjectWithTag("MainBackground");
ScriptMainBackground scriptMainBackground =
mainBackground.GetComponent<ScriptMainBackground>();
string filepath = "c:/Users/gamePrefs.xml";
XmlDocument xmlDoc = new XmlDocument();
if(File.Exists (filepath))
{
xmlDoc.Load(filepath);
XmlElement elmRoot = xmlDoc.DocumentElement;
elmRoot.RemoveAll(); // remove all inside the transforms node.
XmlElement elmNew = xmlDoc.CreateElement("GamePrefs");
XmlElement gamePrefs_firstStart = xmlDoc.CreateElement("firstStart");
gamePrefs_firstStart.InnerText = firstStart.ToString();
XmlElement gamePrefs_drawFirstGui =
xmlDoc.CreateElement("drawFirstGui");
gamePrefs_drawFirstGui.InnerText = drawFirstStartGui.ToString();
XmlElement gamePrefs_companyName =
xmlDoc.CreateElement("companyName");
gamePrefs_companyName.InnerText = gamePrefs_companyName.ToString();
XmlElement gamePrefs_playerName = xmlDoc.CreateElement("playerName");
gamePrefs_playerName.InnerText = gamePrefs_playerName.ToString();
XmlElement gamePrefs_Money = xmlDoc.CreateElement("money");
gamePrefs_Money.InnerText = scriptMainBackground.money.ToString();
XmlElement gamePrefs_Year = xmlDoc.CreateElement("year");
gamePrefs_Year.InnerText = week.ToString();
XmlElement gamePrefs_Month = xmlDoc.CreateElement("month");
gamePrefs_Month.InnerText = week.ToString();
XmlElement gamePrefs_Week = xmlDoc.CreateElement("week");
gamePrefs_Week.InnerText = week.ToString();
XmlElement gamePrefs_Day = xmlDoc.CreateElement("day");
gamePrefs_Day.InnerText = day.ToString();
//XmlElement gamePrefs_GenreNumber =
xmlDoc.CreateElement("genreNumber");
//gamePrefs_Day.InnerText = genreNumber.ToString();
elmNew.AppendChild(gamePrefs_firstStart);
elmNew.AppendChild(gamePrefs_drawFirstGui);
elmNew.AppendChild(gamePrefs_companyName);
elmNew.AppendChild(gamePrefs_playerName);
elmNew.AppendChild(gamePrefs_Money);
elmNew.AppendChild(gamePrefs_Week);
elmNew.AppendChild(gamePrefs_Day);
//elmNew.AppendChild(gamePrefs_GenreNumber);
elmRoot.AppendChild(elmNew);
xmlDoc.Save(filepath); // save file.
}
}
why if I save my variables and load them back then companyName and
playerName is this: System.Xml.XmlElement, instead of what I write? Other
variables works just fine. I am struggling with this for a while, so I
would really appreciate any help, thanks.
public void LoadGamePrefs()
{
string filepath = "c:/Users/gamePrefs.xml";
XmlDocument xmlDoc = new XmlDocument();
if(File.Exists (filepath))
{
xmlDoc.Load(filepath);
XmlNodeList transformList = xmlDoc.GetElementsByTagName("GamePrefs");
foreach (XmlNode transformInfo in transformList)
{
XmlNodeList transformcontent = transformInfo.ChildNodes;
foreach (XmlNode transformItems in transformcontent)
{
if(transformItems.Name == "firstStart")
{
firstStart = bool.Parse(transformItems.InnerText);
}
if(transformItems.Name == "drawFirstGui")
{
drawFirstStartGui = bool.Parse(transformItems.InnerText);
}
if(transformItems.Name == "companyName")
{
companyName = transformItems.InnerText;
}
if(transformItems.Name == "playerName")
{
playerName = transformItems.InnerText;
}
if(transformItems.Name == "money")
{
scriptMainBackground.money =
int.Parse(transformItems.InnerText);
}
if(transformItems.Name == "year")
{
year = int.Parse(transformItems.InnerText);
}
if(transformItems.Name == "month")
{
month = int.Parse(transformItems.InnerText);
}
if(transformItems.Name == "week")
{
week = int.Parse(transformItems.InnerText);
}
if(transformItems.Name == "day")
{
day = int.Parse(transformItems.InnerText);
}
}
}
}
}
public void SaveGamePrefs()
{
// Accesing other script and variable
GameObject mainBackground =
GameObject.FindGameObjectWithTag("MainBackground");
ScriptMainBackground scriptMainBackground =
mainBackground.GetComponent<ScriptMainBackground>();
string filepath = "c:/Users/gamePrefs.xml";
XmlDocument xmlDoc = new XmlDocument();
if(File.Exists (filepath))
{
xmlDoc.Load(filepath);
XmlElement elmRoot = xmlDoc.DocumentElement;
elmRoot.RemoveAll(); // remove all inside the transforms node.
XmlElement elmNew = xmlDoc.CreateElement("GamePrefs");
XmlElement gamePrefs_firstStart = xmlDoc.CreateElement("firstStart");
gamePrefs_firstStart.InnerText = firstStart.ToString();
XmlElement gamePrefs_drawFirstGui =
xmlDoc.CreateElement("drawFirstGui");
gamePrefs_drawFirstGui.InnerText = drawFirstStartGui.ToString();
XmlElement gamePrefs_companyName =
xmlDoc.CreateElement("companyName");
gamePrefs_companyName.InnerText = gamePrefs_companyName.ToString();
XmlElement gamePrefs_playerName = xmlDoc.CreateElement("playerName");
gamePrefs_playerName.InnerText = gamePrefs_playerName.ToString();
XmlElement gamePrefs_Money = xmlDoc.CreateElement("money");
gamePrefs_Money.InnerText = scriptMainBackground.money.ToString();
XmlElement gamePrefs_Year = xmlDoc.CreateElement("year");
gamePrefs_Year.InnerText = week.ToString();
XmlElement gamePrefs_Month = xmlDoc.CreateElement("month");
gamePrefs_Month.InnerText = week.ToString();
XmlElement gamePrefs_Week = xmlDoc.CreateElement("week");
gamePrefs_Week.InnerText = week.ToString();
XmlElement gamePrefs_Day = xmlDoc.CreateElement("day");
gamePrefs_Day.InnerText = day.ToString();
//XmlElement gamePrefs_GenreNumber =
xmlDoc.CreateElement("genreNumber");
//gamePrefs_Day.InnerText = genreNumber.ToString();
elmNew.AppendChild(gamePrefs_firstStart);
elmNew.AppendChild(gamePrefs_drawFirstGui);
elmNew.AppendChild(gamePrefs_companyName);
elmNew.AppendChild(gamePrefs_playerName);
elmNew.AppendChild(gamePrefs_Money);
elmNew.AppendChild(gamePrefs_Week);
elmNew.AppendChild(gamePrefs_Day);
//elmNew.AppendChild(gamePrefs_GenreNumber);
elmRoot.AppendChild(elmNew);
xmlDoc.Save(filepath); // save file.
}
}
Subscribe to:
Comments (Atom)