PhpMyAdmin not access able after setting tomcat on port 80
I just set tomcat on port 80 by adding this on /etc/httpd/conf/httpd.conf
<VirtualHost *:80>
ServerAdmin tomcat@something.com
ServerName something.com
ServerAlias www.something.com
ProxyRequests Off
ProxyPreserveHost On
<Proxy *>
Order allow,deny
Allow from all
</Proxy>
ProxyPass / http://something.com:8080/
ProxyPassReverse / http://something.com:8080/
ErrorLog logs/something.com-error_log
CustomLog logs/something.com-access_log common
</VirtualHost>
But now i am trying to access something.com/phpMyadmin
It is redirecting to something.com:8080/something.com
which is a wrong path
Please help
Saturday, 31 August 2013
Pandas aggregate count distinct
Pandas aggregate count distinct
Let's say I have a log of user activity and I want to generate a report of
total duration and the number of unique users per day.
import numpy as np
import pandas as pd
df = pd.DataFrame({'date':
['2013-04-01','2013-04-01','2013-04-01','2013-04-02', '2013-04-02'],
'user_id': ['0001', '0001', '0002', '0002', '0002'],
'duration': [30, 15, 20, 15, 30]})
Aggregating duration is pretty straightforward:
group = df.groupby('date')
agg = group.aggregate({'duration': np.sum})
agg
duration
date
2013-04-01 65
2013-04-02 45
What I'd like to do is sum the duration and count distincts at the same
time, but I can't seem to find an equivalent for count_distinct:
agg = group.aggregate({ 'duration': np.sum, 'user_id': count_distinct})
This works, but surely there's a better way, no?
group = df.groupby('date')
agg = group.aggregate({'duration': np.sum})
agg['uv'] = df.groupby('date').user_id.nunique()
agg
duration uv
date
2013-04-01 65 2
2013-04-02 45 1
I'm thinking I just need to provide a function that returns the count of
distinct items of a Series object to the aggregate function, but I don't
have a lot of exposure to the various libraries at my disposal. Also, it
seems that the groupby object already knows this information, so wouldn't
I just be duplicating effort?
Let's say I have a log of user activity and I want to generate a report of
total duration and the number of unique users per day.
import numpy as np
import pandas as pd
df = pd.DataFrame({'date':
['2013-04-01','2013-04-01','2013-04-01','2013-04-02', '2013-04-02'],
'user_id': ['0001', '0001', '0002', '0002', '0002'],
'duration': [30, 15, 20, 15, 30]})
Aggregating duration is pretty straightforward:
group = df.groupby('date')
agg = group.aggregate({'duration': np.sum})
agg
duration
date
2013-04-01 65
2013-04-02 45
What I'd like to do is sum the duration and count distincts at the same
time, but I can't seem to find an equivalent for count_distinct:
agg = group.aggregate({ 'duration': np.sum, 'user_id': count_distinct})
This works, but surely there's a better way, no?
group = df.groupby('date')
agg = group.aggregate({'duration': np.sum})
agg['uv'] = df.groupby('date').user_id.nunique()
agg
duration uv
date
2013-04-01 65 2
2013-04-02 45 1
I'm thinking I just need to provide a function that returns the count of
distinct items of a Series object to the aggregate function, but I don't
have a lot of exposure to the various libraries at my disposal. Also, it
seems that the groupby object already knows this information, so wouldn't
I just be duplicating effort?
saving and deleting fileI/O
saving and deleting fileI/O
Two part question.
First, how can i change this(i've tried using 'for' but i cant figure it
out) so that it saves like; 'key value' instead of '{key: value}'.
with open("phonebook.txt", "w") as x:
json.dump(a, x)
Second, how do you delete from a file by using the users input. I cannot
see a way of changing this to delete from file instead of the dict 'a';
name = input("enter name of contact you want to delete: ")
if name in a:
del a[name]
Two part question.
First, how can i change this(i've tried using 'for' but i cant figure it
out) so that it saves like; 'key value' instead of '{key: value}'.
with open("phonebook.txt", "w") as x:
json.dump(a, x)
Second, how do you delete from a file by using the users input. I cannot
see a way of changing this to delete from file instead of the dict 'a';
name = input("enter name of contact you want to delete: ")
if name in a:
del a[name]
Iterate to next element in Ruby
Iterate to next element in Ruby
Summary: Is there a way to get the next element in a loop without starting
from the beginning of the loop? I know that next allows for iterating to
the next element, but it starts at the beginning of the loop. I want to
get the next element and continue to the next statement in the loop.
Details:
I am parsing a text file that is structured as follows:
element 1
part 1
part 2
element 2
part 1
part 2
(note there are 11 parts per element this is just an example).
I read all of the text into an array and then I want to process each line
using something like:
text.each do |L|
#if L is new element create object to store data
#parse next line store as part 1
#parse next line store as part 2
end
I know how to do this with a while loop and a C-like coding style where I
explicitly index into the array and increment the index variable by the
amount I want each time. But I'm wondering if there is a Ruby way to do
this. Something analogous to next but that would continue from the same
point in the loop, just with the next element, rather than starting from
the beginning of the loop.
Summary: Is there a way to get the next element in a loop without starting
from the beginning of the loop? I know that next allows for iterating to
the next element, but it starts at the beginning of the loop. I want to
get the next element and continue to the next statement in the loop.
Details:
I am parsing a text file that is structured as follows:
element 1
part 1
part 2
element 2
part 1
part 2
(note there are 11 parts per element this is just an example).
I read all of the text into an array and then I want to process each line
using something like:
text.each do |L|
#if L is new element create object to store data
#parse next line store as part 1
#parse next line store as part 2
end
I know how to do this with a while loop and a C-like coding style where I
explicitly index into the array and increment the index variable by the
amount I want each time. But I'm wondering if there is a Ruby way to do
this. Something analogous to next but that would continue from the same
point in the loop, just with the next element, rather than starting from
the beginning of the loop.
Objective-C ARC pointer ownership vs C++
Objective-C ARC pointer ownership vs C++
Lets say I have a high level class that instantiates an object and then
passes it down to a lower level class:
- (void) doSomeStuff {
MyBusinessObject* obj = [[MyBusinessObject alloc] init];
[obj setFoo:@"bar"];
[dataManager takeObj:obj withKey:@"abc" andKey:@"def"];
}
and then in the implementation of takeObj I want to keep two different
dictionaries...
- (void) takeObj:(MyBusinessObject*)obj withKey:(NSString*)key1
andKey:(NSString*)key2 {
[primaryDict setObject:obj forKey:key1];
[secondaryDict setObject:obj forKey:key2];
}
Now, what I want is for the ownership of obj to be passed down to my data
manager and have primaryDict hold strong references and secondaryDict hold
weak references. This is how I would do it in C++:
map<string, unique_ptr<MyBusinessObject>> primaryDict;
map<string, MyBusinessObject*> secondaryDict;
The takeObj function would accept a unique_ptr<MyBusinessObject> that
would be passed down with std::move. That would then be moved again into
primaryDict and a weak reference would be added with a raw pointer in
secondaryDict.
My question is--what is the correct way to tell the Objective-C ARC system
to manage my references in that way?
Lets say I have a high level class that instantiates an object and then
passes it down to a lower level class:
- (void) doSomeStuff {
MyBusinessObject* obj = [[MyBusinessObject alloc] init];
[obj setFoo:@"bar"];
[dataManager takeObj:obj withKey:@"abc" andKey:@"def"];
}
and then in the implementation of takeObj I want to keep two different
dictionaries...
- (void) takeObj:(MyBusinessObject*)obj withKey:(NSString*)key1
andKey:(NSString*)key2 {
[primaryDict setObject:obj forKey:key1];
[secondaryDict setObject:obj forKey:key2];
}
Now, what I want is for the ownership of obj to be passed down to my data
manager and have primaryDict hold strong references and secondaryDict hold
weak references. This is how I would do it in C++:
map<string, unique_ptr<MyBusinessObject>> primaryDict;
map<string, MyBusinessObject*> secondaryDict;
The takeObj function would accept a unique_ptr<MyBusinessObject> that
would be passed down with std::move. That would then be moved again into
primaryDict and a weak reference would be added with a raw pointer in
secondaryDict.
My question is--what is the correct way to tell the Objective-C ARC system
to manage my references in that way?
Trying to run Android game using libgdx on Genymotion
Trying to run Android game using libgdx on Genymotion
Anybody experienced with libgdx and genymotion?
I'm trying to get a libgdx game running on genymotion android emulator -
http://www.genymotion.com/
Everytime I try to run on genymotion I get the following exception:
java.lang.ExceptionInInitializerError
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load
shared library 'gdx' for target: Linux, 32-bit
at
com.badlogic.gdx.utils.SharedLibraryLoader.load(SharedLibraryLoader.java:113)
at com.badlogic.gdx.utils.GdxNativesLoader.load(GdxNativesLoader.java:34)
at
com.badlogic.gdx.backends.android.AndroidApplication.<clinit>(AndroidApplication.java:61)
... 15 more
Caused by: java.lang.UnsatisfiedLinkError: Couldn't load gdx: findLibrary
returned null
at java.lang.Runtime.loadLibrary(Runtime.java:365)
at java.lang.System.loadLibrary(System.java:535)
at
com.badlogic.gdx.utils.SharedLibraryLoader.load(SharedLibraryLoader.java:109)
... 17 more
Any Ideas?
Anybody experienced with libgdx and genymotion?
I'm trying to get a libgdx game running on genymotion android emulator -
http://www.genymotion.com/
Everytime I try to run on genymotion I get the following exception:
java.lang.ExceptionInInitializerError
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load
shared library 'gdx' for target: Linux, 32-bit
at
com.badlogic.gdx.utils.SharedLibraryLoader.load(SharedLibraryLoader.java:113)
at com.badlogic.gdx.utils.GdxNativesLoader.load(GdxNativesLoader.java:34)
at
com.badlogic.gdx.backends.android.AndroidApplication.<clinit>(AndroidApplication.java:61)
... 15 more
Caused by: java.lang.UnsatisfiedLinkError: Couldn't load gdx: findLibrary
returned null
at java.lang.Runtime.loadLibrary(Runtime.java:365)
at java.lang.System.loadLibrary(System.java:535)
at
com.badlogic.gdx.utils.SharedLibraryLoader.load(SharedLibraryLoader.java:109)
... 17 more
Any Ideas?
neo4j subqueries in Cypher
neo4j subqueries in Cypher
I cypher queries are beginners. I want to query is as follows
data insert
CREATE ( USER{ talk_id : 1 , phone_num : "1" } ); //[1]
CREATE ( USER{ talk_id : 2 , phone_num : "2" } ); //[2]
CREATE ( USER{ talk_id : 3 , phone_num : "3" } ); //[3]
CREATE ( USER{ talk_id : 4 , phone_num : "4" } ); //[4]
CREATE ( USER{ talk_id : 5 , phone_num : "5" } ); //[5]
CREATE ( USER{ talk_id : 6 , phone_num : "6" } ); //[6]
CREATE ( USER{ talk_id : 7 , phone_num : "7" } ); //[7]
START s=node(1) , d=node(2) CREATE s-[r:FRIEND]->d RETURN r;
START s=node(1) , d=node(3) CREATE s-[r:FRIEND]->d RETURN r;
START s=node(1) , d=node(4) CREATE s-[r:FRIEND]->d RETURN r;
START s=node(2) , d=node(7) CREATE s-[r:FRIEND]->d RETURN r;
quering
step 1 :
START s=node(1) match s-[r]->f return f;
result:
+----------------------------------+
| f |
+----------------------------------+
| Node[2]{talk_id:2,phone_num:"2"} |
| Node[3]{talk_id:3,phone_num:"3"} |
| Node[4]{talk_id:4,phone_num:"4"} |
+----------------------------------+
step 2
start s = node( 2, 3 , 4 ) , s1 = node( 2 , 3 , 4 ) match p=n-[r]->n1
return n , n1;
result:
+---------------------------------------------------------------------+
| n | n1 |
+---------------------------------------------------------------------+
| Node[2]{talk_id:2,phone_num:"2"} | Node[3]{talk_id:3,phone_num:"3"} |
+---------------------------------------------------------------------+
1 row
Query to the above two, I want to query one. What should I do, but? RDMS
just like the subquery
TANK YOU ^^;
I cypher queries are beginners. I want to query is as follows
data insert
CREATE ( USER{ talk_id : 1 , phone_num : "1" } ); //[1]
CREATE ( USER{ talk_id : 2 , phone_num : "2" } ); //[2]
CREATE ( USER{ talk_id : 3 , phone_num : "3" } ); //[3]
CREATE ( USER{ talk_id : 4 , phone_num : "4" } ); //[4]
CREATE ( USER{ talk_id : 5 , phone_num : "5" } ); //[5]
CREATE ( USER{ talk_id : 6 , phone_num : "6" } ); //[6]
CREATE ( USER{ talk_id : 7 , phone_num : "7" } ); //[7]
START s=node(1) , d=node(2) CREATE s-[r:FRIEND]->d RETURN r;
START s=node(1) , d=node(3) CREATE s-[r:FRIEND]->d RETURN r;
START s=node(1) , d=node(4) CREATE s-[r:FRIEND]->d RETURN r;
START s=node(2) , d=node(7) CREATE s-[r:FRIEND]->d RETURN r;
quering
step 1 :
START s=node(1) match s-[r]->f return f;
result:
+----------------------------------+
| f |
+----------------------------------+
| Node[2]{talk_id:2,phone_num:"2"} |
| Node[3]{talk_id:3,phone_num:"3"} |
| Node[4]{talk_id:4,phone_num:"4"} |
+----------------------------------+
step 2
start s = node( 2, 3 , 4 ) , s1 = node( 2 , 3 , 4 ) match p=n-[r]->n1
return n , n1;
result:
+---------------------------------------------------------------------+
| n | n1 |
+---------------------------------------------------------------------+
| Node[2]{talk_id:2,phone_num:"2"} | Node[3]{talk_id:3,phone_num:"3"} |
+---------------------------------------------------------------------+
1 row
Query to the above two, I want to query one. What should I do, but? RDMS
just like the subquery
TANK YOU ^^;
Efficient method for converting a floating point number to string without any library function
Efficient method for converting a floating point number to string without
any library function
I am working on a code to convert a floating point number to it's
equivalent string. For example if the number is : 2.3456 then the string
should also be 2.3456 (without trailing zeros).
I searched on stackoverflow on these 2 links:
C++ convert floating point number to string
Convert Double/Float to string
but both these are slightly off topic as they tend to ask for
representation in 1eX format or xE+0 format.
This is my attempt:
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
vector<char> V;
string S;
int i=0;
float f=3.14156;
float x=f*1e6;
long long int y=(long long int)(x);
while(y)
{
V.push_back(y%10+'0');
y/=10;
}
reverse(V.begin(),V.end());
for(i=0;i<V.size()-6;i++)
{
S.push_back(V[i]);
}
S.push_back('.');
for(;i<V.size();i++)
S.push_back(V[i]);
i=S.size();
while(i--)
{
if(S[i]=='0')
S.erase(S.begin()+i);
else break;
}
cout<<S<<"\n";
//system("pause");
return 0;
}
Link to ideone: http://ideone.com/Z8wBD7
I want to know how can I efficiently exploit the IEEE 754 floating point
representation standard (using typecesting a char pointer or any other
method) and acheive such a conversion , without using any predefined
library function / scanning from a file.
any library function
I am working on a code to convert a floating point number to it's
equivalent string. For example if the number is : 2.3456 then the string
should also be 2.3456 (without trailing zeros).
I searched on stackoverflow on these 2 links:
C++ convert floating point number to string
Convert Double/Float to string
but both these are slightly off topic as they tend to ask for
representation in 1eX format or xE+0 format.
This is my attempt:
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
vector<char> V;
string S;
int i=0;
float f=3.14156;
float x=f*1e6;
long long int y=(long long int)(x);
while(y)
{
V.push_back(y%10+'0');
y/=10;
}
reverse(V.begin(),V.end());
for(i=0;i<V.size()-6;i++)
{
S.push_back(V[i]);
}
S.push_back('.');
for(;i<V.size();i++)
S.push_back(V[i]);
i=S.size();
while(i--)
{
if(S[i]=='0')
S.erase(S.begin()+i);
else break;
}
cout<<S<<"\n";
//system("pause");
return 0;
}
Link to ideone: http://ideone.com/Z8wBD7
I want to know how can I efficiently exploit the IEEE 754 floating point
representation standard (using typecesting a char pointer or any other
method) and acheive such a conversion , without using any predefined
library function / scanning from a file.
Friday, 30 August 2013
How can I use the CSS before selector for links except those containing an
How can I use the CSS before selector for links except those containing an
a:before {
content: "› ";
}
a img:before {
content: ""
}
I know the above syntax is incorrect technically and semantically, but I
want to exclude the content from the a tag any time an img is included
within. Is this possible, or should I do it with a class instead, i.e.
a:before {
content: "> ";
}
a.no-before:before {
content: "";
}
I'd prefer to do it without having to define classes for it, but I can see
that might be required.
a:before {
content: "› ";
}
a img:before {
content: ""
}
I know the above syntax is incorrect technically and semantically, but I
want to exclude the content from the a tag any time an img is included
within. Is this possible, or should I do it with a class instead, i.e.
a:before {
content: "> ";
}
a.no-before:before {
content: "";
}
I'd prefer to do it without having to define classes for it, but I can see
that might be required.
Thursday, 29 August 2013
Passing user parameters to SSIS package
Passing user parameters to SSIS package
Here's my problem. I have a SSIS package that takes 1 parameter on input
called SegmentID. But I cant pass it from the c# code. I'm searching for2
days so far, and here's a solution I came up with, which should work, but
doesn't - SSIS package fails at the stage of getting parameter. What a
hell am I doing wrong?
using (SqlConnection con = GetConnection())
{
var integrationServices = new IntegrationServices(con);
if (integrationServices.Catalogs.Contains("SSISDB"))
{
var catalog = integrationServices.Catalogs["SSISDB"];
if (catalog.Folders.Contains("PSO"))
{
var folder = catalog.Folders["PSO"];
if (folder.Projects.Contains("PSO_SSIS"))
{
var project = folder.Projects["PSO_SSIS"];
project.Parameters["SegmentID"].Set(ParameterInfo.ParameterValueType.Literal,
segmentID);
if (project.Packages.Contains("Main.dtsx"))
{
var package = project.Packages["Main.dtsx"];
long executionIdentifier =
package.Execute(false, null);
return catalog.Executions[executionIdentifier];
}
}
}
}
}
Here's my problem. I have a SSIS package that takes 1 parameter on input
called SegmentID. But I cant pass it from the c# code. I'm searching for2
days so far, and here's a solution I came up with, which should work, but
doesn't - SSIS package fails at the stage of getting parameter. What a
hell am I doing wrong?
using (SqlConnection con = GetConnection())
{
var integrationServices = new IntegrationServices(con);
if (integrationServices.Catalogs.Contains("SSISDB"))
{
var catalog = integrationServices.Catalogs["SSISDB"];
if (catalog.Folders.Contains("PSO"))
{
var folder = catalog.Folders["PSO"];
if (folder.Projects.Contains("PSO_SSIS"))
{
var project = folder.Projects["PSO_SSIS"];
project.Parameters["SegmentID"].Set(ParameterInfo.ParameterValueType.Literal,
segmentID);
if (project.Packages.Contains("Main.dtsx"))
{
var package = project.Packages["Main.dtsx"];
long executionIdentifier =
package.Execute(false, null);
return catalog.Executions[executionIdentifier];
}
}
}
}
}
JSON formatter in Pascal / Delphi
JSON formatter in Pascal / Delphi
I am looking for a function that will take a string of Json as input and
format it with line breaks and indentations (tabs).
Example: I have input a line:
{"menu": {"header": "JSON", "items": [{"id": "Delphi"},{"id": Pascal",
"label": "Nice tree format}, null]}}
And want to get this:
{
"menu":{
"header":"JSON",
"items":[
{
"id":"Delphi"
},
{
"id":"Pascal",
"label":"Nice tree format"
},
null
]
}
}
I found a lot of examples for PHP and C#, but not for Delphi. Could
someone help with such a function?
I am looking for a function that will take a string of Json as input and
format it with line breaks and indentations (tabs).
Example: I have input a line:
{"menu": {"header": "JSON", "items": [{"id": "Delphi"},{"id": Pascal",
"label": "Nice tree format}, null]}}
And want to get this:
{
"menu":{
"header":"JSON",
"items":[
{
"id":"Delphi"
},
{
"id":"Pascal",
"label":"Nice tree format"
},
null
]
}
}
I found a lot of examples for PHP and C#, but not for Delphi. Could
someone help with such a function?
RestKit: How to preprocess JSON value before mapping
RestKit: How to preprocess JSON value before mapping
Currently I am using the following JSON format which is a snippet from
SharePoint REST service:
{results:[
{uri:"https://site.com/_api/Web/Lists(guid'43963c38-4d1c-4734-8b2d-22dc0b92908c')"},
{uri:"https://site.com/_api/Web/Lists(guid'5363c738-7d9d-9774-6b2d-52dc0b93903d')"}]
}
And I have the following object mapping:
RKEntityMapping *listMapping = [RKEntityMapping
mappingForEntityForName:@"SPList"
inManagedObjectStore:managedObjectStore];
[listMapping addAttributeMappingsFromDictionary:@{
@"uri": @"guid"}];
listMapping.identificationAttributes = @[@"guid"];
However, before saving to guid, I would like to add logic to retrieve only
the guid part from uri before saving, so only
"43963c38-4d1c-4734-8b2d-22dc0b92908c" is stored in guid field. I don't
know where to add that logic, could anyone help me?
Currently I am using the following JSON format which is a snippet from
SharePoint REST service:
{results:[
{uri:"https://site.com/_api/Web/Lists(guid'43963c38-4d1c-4734-8b2d-22dc0b92908c')"},
{uri:"https://site.com/_api/Web/Lists(guid'5363c738-7d9d-9774-6b2d-52dc0b93903d')"}]
}
And I have the following object mapping:
RKEntityMapping *listMapping = [RKEntityMapping
mappingForEntityForName:@"SPList"
inManagedObjectStore:managedObjectStore];
[listMapping addAttributeMappingsFromDictionary:@{
@"uri": @"guid"}];
listMapping.identificationAttributes = @[@"guid"];
However, before saving to guid, I would like to add logic to retrieve only
the guid part from uri before saving, so only
"43963c38-4d1c-4734-8b2d-22dc0b92908c" is stored in guid field. I don't
know where to add that logic, could anyone help me?
Wednesday, 28 August 2013
Unity - loading configuration, resolving types in different namespace
Unity - loading configuration, resolving types in different namespace
Situation: 2 projects 1 project is of type WCF Service Library (ProjA) 1
project is a console application with Unity references (ProjB)
Inside ProjB I want to do UnityContainer.LoadConfiguration and resolve
types which are in ProjA.
I have tried this in ProjB.AppConfig file
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="IClass" type="OtherNameSpace.IClass, OtherNameSpace"/>
<alias alias="Class" type="OtherNameSpace.Class, OtherNameSpace"/>
<container>
<register type="IClass" mapTo="Class"/>
</container>
</unity>
For reference the ProjB namespace is ClientHost and ProjB namespace is
OtherNameSpace.
The exception I get is: The type name or alias OtherNameSoace.IClass,
OtherNameSpace could not be resolved. Please check your configuration file
and verify this type name.
Situation: 2 projects 1 project is of type WCF Service Library (ProjA) 1
project is a console application with Unity references (ProjB)
Inside ProjB I want to do UnityContainer.LoadConfiguration and resolve
types which are in ProjA.
I have tried this in ProjB.AppConfig file
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="IClass" type="OtherNameSpace.IClass, OtherNameSpace"/>
<alias alias="Class" type="OtherNameSpace.Class, OtherNameSpace"/>
<container>
<register type="IClass" mapTo="Class"/>
</container>
</unity>
For reference the ProjB namespace is ClientHost and ProjB namespace is
OtherNameSpace.
The exception I get is: The type name or alias OtherNameSoace.IClass,
OtherNameSpace could not be resolved. Please check your configuration file
and verify this type name.
How to apply a patch to soap rtl in Delphi?
How to apply a patch to soap rtl in Delphi?
I have corrected an error in a soap unit (Soap.OPToSOAPDomConv.pas), but I
don't know how to rebuild soaprtl170.bpl. (Delphi XE3). I need to do this
as I have a component to install in the ide that requires that bpl, and
when dropping it in a form and activating it makes webservice calls in
design mode. In design mode it seems to use the soaprtl instead my
modified Soap.OPToSOAPDomConv.dcu. In runtime it works as I'm not using
runtime packages and my dcu is taking precedence. Any help on how to
recompile the bpl would be appreciated. Regards Gonzalo
I have corrected an error in a soap unit (Soap.OPToSOAPDomConv.pas), but I
don't know how to rebuild soaprtl170.bpl. (Delphi XE3). I need to do this
as I have a component to install in the ide that requires that bpl, and
when dropping it in a form and activating it makes webservice calls in
design mode. In design mode it seems to use the soaprtl instead my
modified Soap.OPToSOAPDomConv.dcu. In runtime it works as I'm not using
runtime packages and my dcu is taking precedence. Any help on how to
recompile the bpl would be appreciated. Regards Gonzalo
MVC : Dynamic action links in a view: where to put the business logic (zend2)
MVC : Dynamic action links in a view: where to put the business logic (zend2)
So, I am fairly new to Zend 2 and MVC as a whole, and I find myself in a
situation where I want to follow best practices to make my code reusable
and easy to understand.
The particular scenario I want to deal with is the following. Let's say I
am writing an editorial application, where users can send articles, but
they need to be approved before they are published. When you access an
article /article/view/101 , you get a page with the article info on one
side (Status, Author, Date, Title, Body) and on the sidebar you get a set
of actions. The set of actions (links) changes based on the type of user
viewing the article (guest, user, reviewer or admin) and also based on the
status of the article (draft,finished,published)
So the question is: Where do on the MVC model do I put the business logic
to decide which actions (links) to put on the sidebar?
The controller does not seem appropriate because I would be adding
Business Logic there, and also adding HTML (bad + bad)
The view does not work either because I would be adding business logic.
A service doesn't seem to work either because it seems I would be either
adding HTML, or calling partials from there, and that should not be done
either...
The only thing I could think of is doing the Business Logic in a service
or helper (since more than one model is needed, article and user) and
return an 'array' of actions (no HTML). Then the view processes those to
actually get the HTML, but I'm not sure if that is the way to do it, and
wanted some experienced input.
Thanks.
So, I am fairly new to Zend 2 and MVC as a whole, and I find myself in a
situation where I want to follow best practices to make my code reusable
and easy to understand.
The particular scenario I want to deal with is the following. Let's say I
am writing an editorial application, where users can send articles, but
they need to be approved before they are published. When you access an
article /article/view/101 , you get a page with the article info on one
side (Status, Author, Date, Title, Body) and on the sidebar you get a set
of actions. The set of actions (links) changes based on the type of user
viewing the article (guest, user, reviewer or admin) and also based on the
status of the article (draft,finished,published)
So the question is: Where do on the MVC model do I put the business logic
to decide which actions (links) to put on the sidebar?
The controller does not seem appropriate because I would be adding
Business Logic there, and also adding HTML (bad + bad)
The view does not work either because I would be adding business logic.
A service doesn't seem to work either because it seems I would be either
adding HTML, or calling partials from there, and that should not be done
either...
The only thing I could think of is doing the Business Logic in a service
or helper (since more than one model is needed, article and user) and
return an 'array' of actions (no HTML). Then the view processes those to
actually get the HTML, but I'm not sure if that is the way to do it, and
wanted some experienced input.
Thanks.
GCM not working for Android 4.0.3 but works for 4.1.2
GCM not working for Android 4.0.3 but works for 4.1.2
I am sending notifications to Android using Rapns Ruby gem.
Server side:
n = Rapns::Gcm::Notification.new
n.app = Rapns::Gcm::App.find_by_name("myapp")
n.registration_ids = ["some_id"]
n.data = { message: 'test' }
n.save!
Client side:
public void registerInBackground() {
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getBaseContext());
}
gcm.unregister();
regId = gcm.register(SENDER_ID);
storeRegistrationId(regId);
}
It gets delivered on devices with Android version 4.1.2, but doesn't get
delivered on 4.0.3. All devices get registered and give us registration
id.
GCM always responds with delivered status. I've also tried setting
delay_while_idle: false, collapse_key: 'test' in my request. Didn't work
either. What am I doing wrong?
I am sending notifications to Android using Rapns Ruby gem.
Server side:
n = Rapns::Gcm::Notification.new
n.app = Rapns::Gcm::App.find_by_name("myapp")
n.registration_ids = ["some_id"]
n.data = { message: 'test' }
n.save!
Client side:
public void registerInBackground() {
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getBaseContext());
}
gcm.unregister();
regId = gcm.register(SENDER_ID);
storeRegistrationId(regId);
}
It gets delivered on devices with Android version 4.1.2, but doesn't get
delivered on 4.0.3. All devices get registered and give us registration
id.
GCM always responds with delivered status. I've also tried setting
delay_while_idle: false, collapse_key: 'test' in my request. Didn't work
either. What am I doing wrong?
IntelliJ: Maven project using JibX to run in IntelliJ
IntelliJ: Maven project using JibX to run in IntelliJ
I have a multi-module Maven project. One of the projects uses a plugin for
a post compile operation, JibX.
When I run the project (WAR) in Tomcat inside IntelliJ, IntelliJ seems to
override the updated binaries because the Make is invoked.
I tried to add the jibx:bind after the Make in the Run configuration, but
this goal needs to be executed together with the goal compile, otherwise
it does nothing. So in essence the jibx:bind would need to be launched at
the time the Make is done.
How can I achieve that?
I have a multi-module Maven project. One of the projects uses a plugin for
a post compile operation, JibX.
When I run the project (WAR) in Tomcat inside IntelliJ, IntelliJ seems to
override the updated binaries because the Make is invoked.
I tried to add the jibx:bind after the Make in the Run configuration, but
this goal needs to be executed together with the goal compile, otherwise
it does nothing. So in essence the jibx:bind would need to be launched at
the time the Make is done.
How can I achieve that?
Tuesday, 27 August 2013
Error while fragment trsaction
Error while fragment trsaction
I have a notification which will call a SherlockFragmentActivity by click
on notification
public class MainActivity extends SherlockFragmentActivity{
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.e(TAG, "========onNewIntent");
Fragment fragment = null;
if(intent == null)
return;
String intentAction = intent.getAction();
Log.e(TAG, "========onNewIntent"+intentAction);
if (!intentAction.equalsIgnoreCase(SipManager.ACTION_SIP_HOME)) {
FragmentTransaction ft =
getSupportFragmentManager().beginTransaction();
if(intentAction.equalsIgnoreCase(SipManager.ACTION_SIP_MESSAGES)){
fragment = new ConversationsListFragment();
}
fragment.setArguments(null);
ft.replace(R.id.main_frag_content, fragment);
getSupportFragmentManager().popBackStack();
ft.commit();
}
if(intentAction.equalsIgnoreCase(SipManager.ACTION_SIP_HOME)){
Log.e(TAG, "========ACTION_SIP_HOME"+intentAction);
return;
}
}
}
manifest file is :
<intent-filter android:priority="10" >
<action android:name="com.name.phone.action.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter android:priority="10" >
<action android:name="com.name.phone.action.DIALER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter android:priority="10" >
<action android:name="android.intent.action.DIAL" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="sip" />
<data android:scheme="csip" />
</intent-filter>
<intent-filter android:priority="10" >
<action android:name="com.name.phone.action.CALLLOG" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter android:priority="10" >
<action android:name="com.name.phone.action.MESSAGES" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter android:priority="10" >
<action android:name="com.name.phone.action.CHAT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
I am getting error like
08-28 11:08:29.531: E/AndroidRuntime(18195): FATAL EXCEPTION: main 08-28
11:08:29.531: E/AndroidRuntime(18195): java.lang.IllegalStateException:
Can not perform this action after onSaveInstanceState 08-28 11:08:29.531:
E/AndroidRuntime(18195): at
android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1299)
08-28 11:08:29.531: E/AndroidRuntime(18195): at
android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1310)
08-28 11:08:29.531: E/AndroidRuntime(18195): at
android.support.v4.app.FragmentManagerImpl.popBackStack(FragmentManager.java:436)
08-28 11:08:29.531: E/AndroidRuntime(18195): at
net.telivo.fiestacancun.ui.tablet.MainActivity.onNewIntent(MainActivity.java:671)
08-28 11:08:29.531: E/AndroidRuntime(18195): at
android.app.Instrumentation.callActivityOnNewIntent(Instrumentation.java:1168)
08-28 11:08:29.531: E/AndroidRuntime(18195): at
android.app.ActivityThread.deliverNewIntents(ActivityThread.java:2190)
08-28 11:08:29.531: E/AndroidRuntime(18195): at
android.app.ActivityThread.performNewIntents(ActivityThread.java:2203)
08-28 11:08:29.531: E/AndroidRuntime(18195): at
android.app.ActivityThread.handleNewIntent(ActivityThread.java:2212) 08-28
11:08:29.531: E/AndroidRuntime(18195): at
android.app.ActivityThread.access$1400(ActivityThread.java:140) 08-28
11:08:29.531: E/AndroidRuntime(18195): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1299) 08-28
11:08:29.531: E/AndroidRuntime(18195): at
android.os.Handler.dispatchMessage(Handler.java:99) 08-28 11:08:29.531:
E/AndroidRuntime(18195): at android.os.Looper.loop(Looper.java:137) 08-28
11:08:29.531: E/AndroidRuntime(18195): at
android.app.ActivityThread.main(ActivityThread.java:4895) 08-28
11:08:29.531: E/AndroidRuntime(18195): at
java.lang.reflect.Method.invokeNative(Native Method) 08-28 11:08:29.531:
E/AndroidRuntime(18195): at
java.lang.reflect.Method.invoke(Method.java:511) 08-28 11:08:29.531:
E/AndroidRuntime(18195): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
08-28 11:08:29.531: E/AndroidRuntime(18195): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761) 08-28
11:08:29.531: E/AndroidRuntime(18195): at
dalvik.system.NativeStart.main(Native Method)
I have a notification which will call a SherlockFragmentActivity by click
on notification
public class MainActivity extends SherlockFragmentActivity{
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.e(TAG, "========onNewIntent");
Fragment fragment = null;
if(intent == null)
return;
String intentAction = intent.getAction();
Log.e(TAG, "========onNewIntent"+intentAction);
if (!intentAction.equalsIgnoreCase(SipManager.ACTION_SIP_HOME)) {
FragmentTransaction ft =
getSupportFragmentManager().beginTransaction();
if(intentAction.equalsIgnoreCase(SipManager.ACTION_SIP_MESSAGES)){
fragment = new ConversationsListFragment();
}
fragment.setArguments(null);
ft.replace(R.id.main_frag_content, fragment);
getSupportFragmentManager().popBackStack();
ft.commit();
}
if(intentAction.equalsIgnoreCase(SipManager.ACTION_SIP_HOME)){
Log.e(TAG, "========ACTION_SIP_HOME"+intentAction);
return;
}
}
}
manifest file is :
<intent-filter android:priority="10" >
<action android:name="com.name.phone.action.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter android:priority="10" >
<action android:name="com.name.phone.action.DIALER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter android:priority="10" >
<action android:name="android.intent.action.DIAL" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="sip" />
<data android:scheme="csip" />
</intent-filter>
<intent-filter android:priority="10" >
<action android:name="com.name.phone.action.CALLLOG" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter android:priority="10" >
<action android:name="com.name.phone.action.MESSAGES" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter android:priority="10" >
<action android:name="com.name.phone.action.CHAT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
I am getting error like
08-28 11:08:29.531: E/AndroidRuntime(18195): FATAL EXCEPTION: main 08-28
11:08:29.531: E/AndroidRuntime(18195): java.lang.IllegalStateException:
Can not perform this action after onSaveInstanceState 08-28 11:08:29.531:
E/AndroidRuntime(18195): at
android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1299)
08-28 11:08:29.531: E/AndroidRuntime(18195): at
android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1310)
08-28 11:08:29.531: E/AndroidRuntime(18195): at
android.support.v4.app.FragmentManagerImpl.popBackStack(FragmentManager.java:436)
08-28 11:08:29.531: E/AndroidRuntime(18195): at
net.telivo.fiestacancun.ui.tablet.MainActivity.onNewIntent(MainActivity.java:671)
08-28 11:08:29.531: E/AndroidRuntime(18195): at
android.app.Instrumentation.callActivityOnNewIntent(Instrumentation.java:1168)
08-28 11:08:29.531: E/AndroidRuntime(18195): at
android.app.ActivityThread.deliverNewIntents(ActivityThread.java:2190)
08-28 11:08:29.531: E/AndroidRuntime(18195): at
android.app.ActivityThread.performNewIntents(ActivityThread.java:2203)
08-28 11:08:29.531: E/AndroidRuntime(18195): at
android.app.ActivityThread.handleNewIntent(ActivityThread.java:2212) 08-28
11:08:29.531: E/AndroidRuntime(18195): at
android.app.ActivityThread.access$1400(ActivityThread.java:140) 08-28
11:08:29.531: E/AndroidRuntime(18195): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1299) 08-28
11:08:29.531: E/AndroidRuntime(18195): at
android.os.Handler.dispatchMessage(Handler.java:99) 08-28 11:08:29.531:
E/AndroidRuntime(18195): at android.os.Looper.loop(Looper.java:137) 08-28
11:08:29.531: E/AndroidRuntime(18195): at
android.app.ActivityThread.main(ActivityThread.java:4895) 08-28
11:08:29.531: E/AndroidRuntime(18195): at
java.lang.reflect.Method.invokeNative(Native Method) 08-28 11:08:29.531:
E/AndroidRuntime(18195): at
java.lang.reflect.Method.invoke(Method.java:511) 08-28 11:08:29.531:
E/AndroidRuntime(18195): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
08-28 11:08:29.531: E/AndroidRuntime(18195): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761) 08-28
11:08:29.531: E/AndroidRuntime(18195): at
dalvik.system.NativeStart.main(Native Method)
What is the Purpose of Console.WriteLine() in Winforms
What is the Purpose of Console.WriteLine() in Winforms
I once saw the source code of a winform application and the code had a
Console.WriteLine();. I asked the reason for that and i was told that it
was for debugging purposes.
Pls what is the essence of Console.WriteLine(); in a winform and what
action does it perform because when i tried using it, it never wrote
anything.
I once saw the source code of a winform application and the code had a
Console.WriteLine();. I asked the reason for that and i was told that it
was for debugging purposes.
Pls what is the essence of Console.WriteLine(); in a winform and what
action does it perform because when i tried using it, it never wrote
anything.
Factory reset for Canon MF4690 ImageClass?
Factory reset for Canon MF4690 ImageClass?
I have a Canon MF4690 ImageClass. It has a lot of issues working with SMB.
I've already tried to use the web interface for it which crashes after a
few page views. I have called Canon support several times and they refuse
to give me the factory reset so I can restore it to factory settings,
because I don't have the paid receipt for this printer. I've never had a
product that I couldn't restore to factory settings, and need to give this
a try before recycling and banning Canon products entirely. Sorry for the
frustration, but this is not some huge enterprise product, it's a
multifunction thing that was sold at Staples.
I have some similar instructions for factory reset of Canon printers, but
none of them have the exact same interface I have seen so far. So I would
need specific to the MF4690 model. If you have something close to it that
might work, I am willing to give it a try. Trying to be "green" to
continue to get use out of this product.
I have located the Service Manual for the MF4690 online, but I don't see
mention of how to do a factory reset. It talks about Service Mode but I
can't figure it out:
http://cms.cmexonline.com.mx/media/canon/manuales/fichero/116_imageCLASS_MF4690_ServiceManual_EN_A4.pdf
I have a Canon MF4690 ImageClass. It has a lot of issues working with SMB.
I've already tried to use the web interface for it which crashes after a
few page views. I have called Canon support several times and they refuse
to give me the factory reset so I can restore it to factory settings,
because I don't have the paid receipt for this printer. I've never had a
product that I couldn't restore to factory settings, and need to give this
a try before recycling and banning Canon products entirely. Sorry for the
frustration, but this is not some huge enterprise product, it's a
multifunction thing that was sold at Staples.
I have some similar instructions for factory reset of Canon printers, but
none of them have the exact same interface I have seen so far. So I would
need specific to the MF4690 model. If you have something close to it that
might work, I am willing to give it a try. Trying to be "green" to
continue to get use out of this product.
I have located the Service Manual for the MF4690 online, but I don't see
mention of how to do a factory reset. It talks about Service Mode but I
can't figure it out:
http://cms.cmexonline.com.mx/media/canon/manuales/fichero/116_imageCLASS_MF4690_ServiceManual_EN_A4.pdf
VS2012 All packages(Nuget) are already installed and there is nothing to restore
VS2012 All packages(Nuget) are already installed and there is nothing to
restore
I was debugging a project when my computer crashed with a blue screen.
After the crash I had to recover my files from a backup. My computer was
restored to its original settings. Then I started to get the following
errors when compiling
NuGet package restore started.
All packages are already installed and there is nothing to restore.
NuGet package restore finished.
HRESULT: 0x80070057 (E_INVALIDARG)
So I googled for the error and according to instructions deleted files
from Temp and ASPWEBADMIN folders. This solved the HRESULT error and my
project is running normally except that when I compile and debug any
project I still get the NUGET package restore. I googled for solution and
landed on this Link. But I am not sure how to use this link. I want to
know 1) Is this Build Output a problem? (If it aint broke dont fix it) 2)
If it is a problem do u know any solution.
restore
I was debugging a project when my computer crashed with a blue screen.
After the crash I had to recover my files from a backup. My computer was
restored to its original settings. Then I started to get the following
errors when compiling
NuGet package restore started.
All packages are already installed and there is nothing to restore.
NuGet package restore finished.
HRESULT: 0x80070057 (E_INVALIDARG)
So I googled for the error and according to instructions deleted files
from Temp and ASPWEBADMIN folders. This solved the HRESULT error and my
project is running normally except that when I compile and debug any
project I still get the NUGET package restore. I googled for solution and
landed on this Link. But I am not sure how to use this link. I want to
know 1) Is this Build Output a problem? (If it aint broke dont fix it) 2)
If it is a problem do u know any solution.
After disconnecting from my Office VPN, internet is not working
After disconnecting from my Office VPN, internet is not working
Aug 26, 2013.. I did my ubuntu12.04 upgrate using update manager...
After that, I'm unable to connect to internet. But, with VPN I'm able to
connect..
What might causing the issue?
Aug 26, 2013.. I did my ubuntu12.04 upgrate using update manager...
After that, I'm unable to connect to internet. But, with VPN I'm able to
connect..
What might causing the issue?
Monday, 26 August 2013
Android drawText including text wrapping
Android drawText including text wrapping
I am currently creating an image editor and am attempting to draw text on
top of on image using canvas.drawText(). So far I have been successful in
doing this but when the user enters text that is too long, the text just
continues on one line out of the page and doesn't wrap itself to the width
of the screen. How would I go about doing this? I have tried using a
static layout but cannot seem to get it to work, has anyone got a tutorial
to do this?
My function for drawing on a canvas using static layout:
public Bitmap createImage(float scr_x,float scr_y,String user_text){
Canvas canvas = new Canvas(image);
scr_x = 100;
scr_y = 100;
final TextPaint tp = new TextPaint(Color.WHITE);
canvas.save();
StaticLayout sl = new StaticLayout("" + user_text, tp,
originalBitmap.getWidth(), Layout.Alignment.ALIGN_NORMAL,
1.0f, 0.0f, false);
sl.draw(canvas);
return image;
}
I am currently creating an image editor and am attempting to draw text on
top of on image using canvas.drawText(). So far I have been successful in
doing this but when the user enters text that is too long, the text just
continues on one line out of the page and doesn't wrap itself to the width
of the screen. How would I go about doing this? I have tried using a
static layout but cannot seem to get it to work, has anyone got a tutorial
to do this?
My function for drawing on a canvas using static layout:
public Bitmap createImage(float scr_x,float scr_y,String user_text){
Canvas canvas = new Canvas(image);
scr_x = 100;
scr_y = 100;
final TextPaint tp = new TextPaint(Color.WHITE);
canvas.save();
StaticLayout sl = new StaticLayout("" + user_text, tp,
originalBitmap.getWidth(), Layout.Alignment.ALIGN_NORMAL,
1.0f, 0.0f, false);
sl.draw(canvas);
return image;
}
How to edit string letters in a for loop
How to edit string letters in a for loop
I'm new with python and I really cannot find a way to do this.
I want to change the letters of a string based on some criteria. Here is
the code:
for c in text:
ordChar=ord(c)
if ordChar>=65 and ordChar<=90:
ordChar=ordChar+13
if ordChar>90:
ordChar=ordChar-90+64
c=chr(ordChar)
else:
if ordChar>=97 and ordChar<=122:
ordChar=ordChar+13
if ordChar>122:
ordChar=ordChar-122+96
c=chr(ordChar)
return text
The returned text value is the same as the parameter value. I thought
variables were pointers, so editing c, it should edit text. What am I
doing wrong?
I'm new with python and I really cannot find a way to do this.
I want to change the letters of a string based on some criteria. Here is
the code:
for c in text:
ordChar=ord(c)
if ordChar>=65 and ordChar<=90:
ordChar=ordChar+13
if ordChar>90:
ordChar=ordChar-90+64
c=chr(ordChar)
else:
if ordChar>=97 and ordChar<=122:
ordChar=ordChar+13
if ordChar>122:
ordChar=ordChar-122+96
c=chr(ordChar)
return text
The returned text value is the same as the parameter value. I thought
variables were pointers, so editing c, it should edit text. What am I
doing wrong?
change thumbnail size in GalleryView
change thumbnail size in GalleryView
I am using NextGen Gallery with template GalleryView.
I have to change a little bit GalleryView template. I made all changes I
need, instead I do not know how to change galleryview template thumbnails
and big image size.
I am familiar with php and css, but not able to find where to edit code. I
believe it is not customized now without editing php code, am I right?
I am using NextGen Gallery with template GalleryView.
I have to change a little bit GalleryView template. I made all changes I
need, instead I do not know how to change galleryview template thumbnails
and big image size.
I am familiar with php and css, but not able to find where to edit code. I
believe it is not customized now without editing php code, am I right?
Get the count of Checked check box using Jquery
Get the count of Checked check box using Jquery
I want to get the count of checked check Boxes form below code sample,
Thnks, Digambar K.
I want to get the count of checked check Boxes form below code sample,
Thnks, Digambar K.
css as assets font embedding won't work on firefox
css as assets font embedding won't work on firefox
I am building a website that serve the assets (image, css, javascript)
from a subdomain inside the same server, everything works fine except
Firefox doesn't seem to render the fonts i am embedding
my css (on assets.mydomain.dev)
@font-face {
font-family: 'FontAwesome';
src:
url('http://assets.mydomain.dev/fonts/awesome/fontawesome-webfont.eot?v=3.1.0');
src:
url('http://assets.mydomain.dev/fonts/awesome/fontawesome-webfont.eot?#iefix&v=3.1.0')
format('embedded-opentype'),
url('http://assets.mydomain.dev/fonts/awesome/fontawesome-webfont.woff?v=3.1.0')
format('woff'),
url('http://assets.mydomain.dev/fonts/awesome/fontawesome-webfont.ttf?v=3.1.0')
format('truetype'),
url('http://assets.mydomain.dev/fonts/awesome/fontawesome-webfont.svg#fontawesomeregular?v=3.1.0')
format('svg');
font-weight: normal;
font-style: normal;
}
htaccess (on assets.mydomain.dev)
AddType fonts/ttf .ttf
AddType fonts/eot .eot
AddType fonts/otf .otf
AddType fonts/woff .woff
<FilesMatch "\.(ttf|otf|eot|woff)$">
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
</FilesMatch>
folder structure (on assets.mydomain.dev)
/
/fonts
/awesome
/fontawesome-webfont.eot
/fontawesome-webfont.woff
/fontawesome-webfont.ttf
/fontawesome-webfont.svg
i have been looking into some "how to" here in stackoverflow, such as these
css-font-face-absolute-url-from-external-domain-fonts-not-loading-in-firefox
css-font-face-not-working-with-firefox-but-working-with-chrome-and-ie
but none seems to work, please help me
I am building a website that serve the assets (image, css, javascript)
from a subdomain inside the same server, everything works fine except
Firefox doesn't seem to render the fonts i am embedding
my css (on assets.mydomain.dev)
@font-face {
font-family: 'FontAwesome';
src:
url('http://assets.mydomain.dev/fonts/awesome/fontawesome-webfont.eot?v=3.1.0');
src:
url('http://assets.mydomain.dev/fonts/awesome/fontawesome-webfont.eot?#iefix&v=3.1.0')
format('embedded-opentype'),
url('http://assets.mydomain.dev/fonts/awesome/fontawesome-webfont.woff?v=3.1.0')
format('woff'),
url('http://assets.mydomain.dev/fonts/awesome/fontawesome-webfont.ttf?v=3.1.0')
format('truetype'),
url('http://assets.mydomain.dev/fonts/awesome/fontawesome-webfont.svg#fontawesomeregular?v=3.1.0')
format('svg');
font-weight: normal;
font-style: normal;
}
htaccess (on assets.mydomain.dev)
AddType fonts/ttf .ttf
AddType fonts/eot .eot
AddType fonts/otf .otf
AddType fonts/woff .woff
<FilesMatch "\.(ttf|otf|eot|woff)$">
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
</FilesMatch>
folder structure (on assets.mydomain.dev)
/
/fonts
/awesome
/fontawesome-webfont.eot
/fontawesome-webfont.woff
/fontawesome-webfont.ttf
/fontawesome-webfont.svg
i have been looking into some "how to" here in stackoverflow, such as these
css-font-face-absolute-url-from-external-domain-fonts-not-loading-in-firefox
css-font-face-not-working-with-firefox-but-working-with-chrome-and-ie
but none seems to work, please help me
Sunday, 25 August 2013
Delete 100 lines from vi editor using single comaand
Delete 100 lines from vi editor using single comaand
I am using ubuntu and trying to delete all 100 lines from vi editor but I
got interview question of doing this in one comaand
I am using ubuntu and trying to delete all 100 lines from vi editor but I
got interview question of doing this in one comaand
How to output elements in a JSON array with AngularJS
How to output elements in a JSON array with AngularJS
JSON array defined in scope:
$scope.faq = [
{"Question 1": "Answer1"},
{"Question 2": "Answer2"}
];
HTML:
<div ng-repeat="f in faq">
{{f}}
</div>
Output:
{"Question 1": "Answer1"}
{"Question 2": "Answer2"}
What I want output to look like:
Question 1 - Answer1
Question 2 - Answer2
How it seems like it should work:
<div ng-repeat="f in faq">
{{f.key}}-{{f.value}}
</div>
... but it doesn't.
JSON array defined in scope:
$scope.faq = [
{"Question 1": "Answer1"},
{"Question 2": "Answer2"}
];
HTML:
<div ng-repeat="f in faq">
{{f}}
</div>
Output:
{"Question 1": "Answer1"}
{"Question 2": "Answer2"}
What I want output to look like:
Question 1 - Answer1
Question 2 - Answer2
How it seems like it should work:
<div ng-repeat="f in faq">
{{f.key}}-{{f.value}}
</div>
... but it doesn't.
How to make RelativeLayout not take up the whole screen?
How to make RelativeLayout not take up the whole screen?
Currently, I have a relative layout defined programatically
RelativeLayout layout = new RelativeLayout(this);
then I add textviews and buttons like this
layout.addView(myText, params);
layout.addView(myBtn, param);
However, this makes the entire screen fill up with my relativelayout, how
do I (programatically) set only certain number of pixels(dp) take up the
screen? My goal is to have like the bottom half of the screen
relativelayout
Anyhelp?
Currently, I have a relative layout defined programatically
RelativeLayout layout = new RelativeLayout(this);
then I add textviews and buttons like this
layout.addView(myText, params);
layout.addView(myBtn, param);
However, this makes the entire screen fill up with my relativelayout, how
do I (programatically) set only certain number of pixels(dp) take up the
screen? My goal is to have like the bottom half of the screen
relativelayout
Anyhelp?
Who is the main leader of SPQR?
Who is the main leader of SPQR?
In Rome Total War what major military leader is the faction dominance for
SPQR? If you assassinate all SPQR members can they crumble?
In Rome Total War what major military leader is the faction dominance for
SPQR? If you assassinate all SPQR members can they crumble?
Payments Callback URL not being call after new local currency changes
Payments Callback URL not being call after new local currency changes
After switching to the new Facebook local currency API the process is
working, but my server is not involve in the process so i really don't
know if the user bought coins cause the payment callback URL is not being
called now (using static payment).
I tried to use real time update to get Facebook data but can make it work,
what is the best practice to involve the server in the process so it will
be aware of the purchase?
I prefer for security reasons to get the update from Facebook and not from
my client.
After switching to the new Facebook local currency API the process is
working, but my server is not involve in the process so i really don't
know if the user bought coins cause the payment callback URL is not being
called now (using static payment).
I tried to use real time update to get Facebook data but can make it work,
what is the best practice to involve the server in the process so it will
be aware of the purchase?
I prefer for security reasons to get the update from Facebook and not from
my client.
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, string given in /home/######/public_html/whatever/this/my_stats.php on line...
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, string
given in /home/######/public_html/whatever/this/my_stats.php on line...
This is line 40 $row83 = mysql_fetch_assoc($important);
This is line 38 to 41
//Check to see if the warlist message exists
$important = ("SELECT * FROM invites WHERE user_id='".$id."' AND
sent_id='".$userp['id']."'");
$row83 = mysql_fetch_assoc($important);
$result = mysql_query($important);
given in /home/######/public_html/whatever/this/my_stats.php on line...
This is line 40 $row83 = mysql_fetch_assoc($important);
This is line 38 to 41
//Check to see if the warlist message exists
$important = ("SELECT * FROM invites WHERE user_id='".$id."' AND
sent_id='".$userp['id']."'");
$row83 = mysql_fetch_assoc($important);
$result = mysql_query($important);
Saturday, 24 August 2013
GLSL: define a constant for both vertex and fragment shader
GLSL: define a constant for both vertex and fragment shader
I have a constant for defining an array in the vertex shader. I want to
use this constant also in the fragment shader to define another array of
the same size. Naive attempts fail (simply use the constant of the vertex
shader in the fragment shader or using a #define from the vertex shader).
Is this somehow possible?
The only idea I can come up with is using something like an include
statement, which seems to be added (source), but I didn't yet find the
time to implement this.
Thank you in advance!
I have a constant for defining an array in the vertex shader. I want to
use this constant also in the fragment shader to define another array of
the same size. Naive attempts fail (simply use the constant of the vertex
shader in the fragment shader or using a #define from the vertex shader).
Is this somehow possible?
The only idea I can come up with is using something like an include
statement, which seems to be added (source), but I didn't yet find the
time to implement this.
Thank you in advance!
ObjectOutputStream readInt() doesn't work
ObjectOutputStream readInt() doesn't work
I'm doing a calculador in Java with sockets. The server receives the
operation code (Add: 1, Product: 3) and the numbers which send the client.
I have to use ObjectOutputStream and ObjectInputStream for writing and
reading the data, but I have a problem.
The client writes the operation code but the Server doesn't receive, but
if I try to send some data from the server to client, it works.
PD. I'm using threads. And the program doesn't send an exception. The
client write the data but the server is waiting for receving it forever.
This is my code:
Servidor.java
package com.distribuidos.calculadora.servidor;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* @author Israel
*/
public class Servidor extends Thread{
private ServerSocket serverSocket = null;
private static final int PUERTO = 6666;
public Servidor()
{
try {
serverSocket = new ServerSocket(PUERTO);
System.out.println("Funcionando");
} catch (IOException ioe) {
ioe.printStackTrace();
}
start();
}
@Override
public void run()
{
try {
while(true){
System.out.println("Listo para recibir conexiones");
Socket socketCliente = serverSocket.accept();
System.out.println("Cliente conectado de " +
socketCliente.getInetAddress());
Operaciones operacion = new Operaciones(socketCliente);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public static void main(String[] args) {
new Servidor();
}
}
Operaciones.java
package com.distribuidos.calculadora.servidor;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
/**
*
* @author Israel
*/
public class Operaciones extends Thread {
private ObjectOutputStream oos = null;
private ObjectInputStream ois = null;
private Socket socketCliente;
private int operacion;
private final static int SUMA = 6;
private final static int RESTA = 1;
private final static int MULTIPLICACION = 2;
private final static int DIVISION = 3;
private final static int FACTORIAL = 4;
private final static int FIBONACCI = 5;
public Operaciones(Socket socketCliente) {
this.socketCliente = socketCliente;
try {
oos = new ObjectOutputStream(socketCliente.getOutputStream());
oos.flush();
ois = new ObjectInputStream(socketCliente.getInputStream());
} catch (IOException ioe) {
ioe.printStackTrace();
try {
socketCliente.close();
} catch (Exception ee) {
ee.printStackTrace();
}
return;
}
start();
}
@Override
public void run(){
try {
oos.writeObject(new String("conectado"));
System.out.println("Escribi al cliente");
System.out.println("Corriendo hilo");
System.out.println(socketCliente.isConnected());
operacion = ois.readInt();
System.out.println("Lei operacion " + operacion);
switch(operacion)
{
case SUMA:
oos.writeFloat(Suma(ois.readFloat(), ois.readFloat()));
break;
case RESTA:
oos.writeFloat(Resta(ois.readFloat(), ois.readFloat()));
break;
case MULTIPLICACION:
oos.writeFloat(Multiplicacion(ois.readFloat(),
ois.readFloat()));
break;
case DIVISION:
oos.writeFloat(Division(ois.readFloat(),
ois.readFloat()));
break;
case FACTORIAL:
oos.writeInt(Factorial(ois.readInt()));
break;
case FIBONACCI:
oos.writeInt(Fibonacci(ois.readInt()));
break;
default:
oos.writeInt(0);
break;
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
socketCliente.close();
ois.close();
oos.close();
} catch (IOException e) {
}
}
}
private float Suma(float numero1, float numero2)
{
return numero1 + numero2;
}
private float Multiplicacion(float numero1, float numero2)
{
return numero1 * numero2;
}
private float Resta(float numero1, float numero2)
{
return numero1 - numero2;
}
private float Division(float numero1, float numero2)
{
return numero1 / numero2;
}
private int Factorial(int numero)
{
int resultado = 1;
for (int i = numero; i > 0 ; i--)
resultado *= numero;
return resultado;
}
private int Fibonacci(int numero)
{
if(numero<2)
return numero;
else
return Fibonacci(numero-1) + Fibonacci(numero-2);
}
}
Cliente.java
package com.distribuidos.calculadora.cliente;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
/**
*
* @author Israel
*/
public class Cliente {
private Socket socket = null;
private ObjectOutputStream oos = null;
private ObjectInputStream ois = null;
private static final int PUERTO = 6666;
public Cliente()
{
try {
socket = new Socket("localhost", PUERTO);
oos = new ObjectOutputStream(socket.getOutputStream());
oos.flush();
ois = new ObjectInputStream(socket.getInputStream());
} catch (UnknownHostException uhe) {
System.err.println(uhe.getMessage());
throw new RuntimeException();
}
catch (IOException ioe)
{
System.err.println(ioe.getMessage());
throw new RuntimeException();
}
}
public float leerFloat()
{
try {
return ois.readFloat();
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
throw new RuntimeException();
}
}
public int leerInt()
{
try {
return ois.readInt();
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
throw new RuntimeException();
}
}
public void escribirFloat(float numero)
{
try {
oos.writeFloat(numero);
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
throw new RuntimeException();
}
}
public void escribirEntero(int numero)
{
try {
oos.writeInt(numero);
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
public void escribirOperacion(int operacion)
{
try {
oos.writeInt(operacion);
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
throw new RuntimeException();
}
}
public void close()
{
try {
socket.close();
ois.close();
oos.close();
} catch (Exception e) {
}
}
public Socket getSocket()
{
return this.socket;
}
public String leerString()
{
String cad="";
try {
cad = (String)ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return cad;
}
}
GUI.java
private void btnIgualActionPerformed(java.awt.event.ActionEvent evt) {
try {
initCliente();
System.out.println(cliente.leerString());
cliente.escribirEntero(operacion);
System.out.println(cliente.getSocket().isConnected());
numeroDos = Integer.parseInt(txtCantidad.getText());
System.out.println("Primer operando " + numeroUno);
System.out.println("Segundo operando " + numeroDos);
System.out.println(cliente.getSocket().isConnected());
System.out.println(cliente.getSocket().isConnected());
System.out.println("Escribi la operacion " + operacion);
switch(operacion)
{
case SUMA:
case RESTA:
case MULTIPLICACION:
case DIVISION:
cliente.escribirFloat(numeroUno);
System.out.println("Escribi el primer numero");
cliente.escribirFloat(numeroDos);
System.out.println("Escribi el segundo numero");
txtCantidad.setText(Float.toString(cliente.leerFloat()));
System.out.println("Recibi el resultado");
break;
case FACTORIAL:
case FIBONACCI:
cliente.escribirEntero((int)numeroUno);
txtCantidad.setText(Integer.toString(cliente.leerInt()));
default:
cliente.escribirFloat(0);
cliente.escribirFloat(0);
txtCantidad.setText("0");
}
cliente.close();
} catch (Exception e)
{
}
}
Thanks for your help.
I'm doing a calculador in Java with sockets. The server receives the
operation code (Add: 1, Product: 3) and the numbers which send the client.
I have to use ObjectOutputStream and ObjectInputStream for writing and
reading the data, but I have a problem.
The client writes the operation code but the Server doesn't receive, but
if I try to send some data from the server to client, it works.
PD. I'm using threads. And the program doesn't send an exception. The
client write the data but the server is waiting for receving it forever.
This is my code:
Servidor.java
package com.distribuidos.calculadora.servidor;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* @author Israel
*/
public class Servidor extends Thread{
private ServerSocket serverSocket = null;
private static final int PUERTO = 6666;
public Servidor()
{
try {
serverSocket = new ServerSocket(PUERTO);
System.out.println("Funcionando");
} catch (IOException ioe) {
ioe.printStackTrace();
}
start();
}
@Override
public void run()
{
try {
while(true){
System.out.println("Listo para recibir conexiones");
Socket socketCliente = serverSocket.accept();
System.out.println("Cliente conectado de " +
socketCliente.getInetAddress());
Operaciones operacion = new Operaciones(socketCliente);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public static void main(String[] args) {
new Servidor();
}
}
Operaciones.java
package com.distribuidos.calculadora.servidor;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
/**
*
* @author Israel
*/
public class Operaciones extends Thread {
private ObjectOutputStream oos = null;
private ObjectInputStream ois = null;
private Socket socketCliente;
private int operacion;
private final static int SUMA = 6;
private final static int RESTA = 1;
private final static int MULTIPLICACION = 2;
private final static int DIVISION = 3;
private final static int FACTORIAL = 4;
private final static int FIBONACCI = 5;
public Operaciones(Socket socketCliente) {
this.socketCliente = socketCliente;
try {
oos = new ObjectOutputStream(socketCliente.getOutputStream());
oos.flush();
ois = new ObjectInputStream(socketCliente.getInputStream());
} catch (IOException ioe) {
ioe.printStackTrace();
try {
socketCliente.close();
} catch (Exception ee) {
ee.printStackTrace();
}
return;
}
start();
}
@Override
public void run(){
try {
oos.writeObject(new String("conectado"));
System.out.println("Escribi al cliente");
System.out.println("Corriendo hilo");
System.out.println(socketCliente.isConnected());
operacion = ois.readInt();
System.out.println("Lei operacion " + operacion);
switch(operacion)
{
case SUMA:
oos.writeFloat(Suma(ois.readFloat(), ois.readFloat()));
break;
case RESTA:
oos.writeFloat(Resta(ois.readFloat(), ois.readFloat()));
break;
case MULTIPLICACION:
oos.writeFloat(Multiplicacion(ois.readFloat(),
ois.readFloat()));
break;
case DIVISION:
oos.writeFloat(Division(ois.readFloat(),
ois.readFloat()));
break;
case FACTORIAL:
oos.writeInt(Factorial(ois.readInt()));
break;
case FIBONACCI:
oos.writeInt(Fibonacci(ois.readInt()));
break;
default:
oos.writeInt(0);
break;
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
socketCliente.close();
ois.close();
oos.close();
} catch (IOException e) {
}
}
}
private float Suma(float numero1, float numero2)
{
return numero1 + numero2;
}
private float Multiplicacion(float numero1, float numero2)
{
return numero1 * numero2;
}
private float Resta(float numero1, float numero2)
{
return numero1 - numero2;
}
private float Division(float numero1, float numero2)
{
return numero1 / numero2;
}
private int Factorial(int numero)
{
int resultado = 1;
for (int i = numero; i > 0 ; i--)
resultado *= numero;
return resultado;
}
private int Fibonacci(int numero)
{
if(numero<2)
return numero;
else
return Fibonacci(numero-1) + Fibonacci(numero-2);
}
}
Cliente.java
package com.distribuidos.calculadora.cliente;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
/**
*
* @author Israel
*/
public class Cliente {
private Socket socket = null;
private ObjectOutputStream oos = null;
private ObjectInputStream ois = null;
private static final int PUERTO = 6666;
public Cliente()
{
try {
socket = new Socket("localhost", PUERTO);
oos = new ObjectOutputStream(socket.getOutputStream());
oos.flush();
ois = new ObjectInputStream(socket.getInputStream());
} catch (UnknownHostException uhe) {
System.err.println(uhe.getMessage());
throw new RuntimeException();
}
catch (IOException ioe)
{
System.err.println(ioe.getMessage());
throw new RuntimeException();
}
}
public float leerFloat()
{
try {
return ois.readFloat();
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
throw new RuntimeException();
}
}
public int leerInt()
{
try {
return ois.readInt();
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
throw new RuntimeException();
}
}
public void escribirFloat(float numero)
{
try {
oos.writeFloat(numero);
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
throw new RuntimeException();
}
}
public void escribirEntero(int numero)
{
try {
oos.writeInt(numero);
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
public void escribirOperacion(int operacion)
{
try {
oos.writeInt(operacion);
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
throw new RuntimeException();
}
}
public void close()
{
try {
socket.close();
ois.close();
oos.close();
} catch (Exception e) {
}
}
public Socket getSocket()
{
return this.socket;
}
public String leerString()
{
String cad="";
try {
cad = (String)ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return cad;
}
}
GUI.java
private void btnIgualActionPerformed(java.awt.event.ActionEvent evt) {
try {
initCliente();
System.out.println(cliente.leerString());
cliente.escribirEntero(operacion);
System.out.println(cliente.getSocket().isConnected());
numeroDos = Integer.parseInt(txtCantidad.getText());
System.out.println("Primer operando " + numeroUno);
System.out.println("Segundo operando " + numeroDos);
System.out.println(cliente.getSocket().isConnected());
System.out.println(cliente.getSocket().isConnected());
System.out.println("Escribi la operacion " + operacion);
switch(operacion)
{
case SUMA:
case RESTA:
case MULTIPLICACION:
case DIVISION:
cliente.escribirFloat(numeroUno);
System.out.println("Escribi el primer numero");
cliente.escribirFloat(numeroDos);
System.out.println("Escribi el segundo numero");
txtCantidad.setText(Float.toString(cliente.leerFloat()));
System.out.println("Recibi el resultado");
break;
case FACTORIAL:
case FIBONACCI:
cliente.escribirEntero((int)numeroUno);
txtCantidad.setText(Integer.toString(cliente.leerInt()));
default:
cliente.escribirFloat(0);
cliente.escribirFloat(0);
txtCantidad.setText("0");
}
cliente.close();
} catch (Exception e)
{
}
}
Thanks for your help.
Python - vectorizing a sliding window
Python - vectorizing a sliding window
I'm trying to vectorize a sliding window operation. For the 1-d case a
helpful example could go along the lines of:
x= vstack((np.array([range(10)]),np.array([range(10)])))
x[1,:]=np.where((x[0,:]<5)&(x[0,:]>0),x[1,x[0,:]+1],x[1,:])
The n+1 value for each current value for indices <5. But I get this error:
x[1,:]=np.where((x[0,:]<2)&(x[0,:]>0),x[1,x[0,:]+1],x[1,:])
IndexError: index (10) out of range (0<=index<9) in dimension 1
Curiously I wouldn't get this error for the n-1 value which would mean
indices smaller than 0. It doesn't seem to mind:
x[1,:]=np.where((x[0,:]<5)&(x[0,:]>0),x[1,x[0,:]-1],x[1,:])
print(x)
[[0 1 2 3 4 5 6 7 8 9]
[0 0 1 2 3 5 6 7 8 9]]
Is there anyway around this? is my approach totally wrong? any comments
would be appreciated.
I'm trying to vectorize a sliding window operation. For the 1-d case a
helpful example could go along the lines of:
x= vstack((np.array([range(10)]),np.array([range(10)])))
x[1,:]=np.where((x[0,:]<5)&(x[0,:]>0),x[1,x[0,:]+1],x[1,:])
The n+1 value for each current value for indices <5. But I get this error:
x[1,:]=np.where((x[0,:]<2)&(x[0,:]>0),x[1,x[0,:]+1],x[1,:])
IndexError: index (10) out of range (0<=index<9) in dimension 1
Curiously I wouldn't get this error for the n-1 value which would mean
indices smaller than 0. It doesn't seem to mind:
x[1,:]=np.where((x[0,:]<5)&(x[0,:]>0),x[1,x[0,:]-1],x[1,:])
print(x)
[[0 1 2 3 4 5 6 7 8 9]
[0 0 1 2 3 5 6 7 8 9]]
Is there anyway around this? is my approach totally wrong? any comments
would be appreciated.
Visual C# Can't create directory, security error
Visual C# Can't create directory, security error
I see myself forced to ask once again, I'm avoiding external help as much
as possible, want to do as much on my own, but my knowledge is still very
limited. My problem is as follows. I have this code:
public string path = Application.StartupPath + @"\maquinas\";
Directory.CreateDirectory(path + Form1.cmaq + @"\" + textinCliente);
Form1.cmaq just has a name such as a,b,c, whatever!
However, I get the following exception once I the
Directory.CreateDirectory code runs. http://i.imgur.com/II1Tqqd.png It
seems to be related with folder permissions.
How can I fix that programatically? So that no action has to be taken by
the user to set the folder permissions.
Thank you in advance!
P.S. since that is in portuguese, in the first line, after
System.NotSupportedException it reads "The format of the specified path is
not supported" That could also be the issue but I can't see what's wrong
with the format of the path really -.-
Also "em" means at / in
I see myself forced to ask once again, I'm avoiding external help as much
as possible, want to do as much on my own, but my knowledge is still very
limited. My problem is as follows. I have this code:
public string path = Application.StartupPath + @"\maquinas\";
Directory.CreateDirectory(path + Form1.cmaq + @"\" + textinCliente);
Form1.cmaq just has a name such as a,b,c, whatever!
However, I get the following exception once I the
Directory.CreateDirectory code runs. http://i.imgur.com/II1Tqqd.png It
seems to be related with folder permissions.
How can I fix that programatically? So that no action has to be taken by
the user to set the folder permissions.
Thank you in advance!
P.S. since that is in portuguese, in the first line, after
System.NotSupportedException it reads "The format of the specified path is
not supported" That could also be the issue but I can't see what's wrong
with the format of the path really -.-
Also "em" means at / in
Easy way to view multiple Y variables against same X
Easy way to view multiple Y variables against same X
I want to visualize many time series at once. I am new at R, and have
spent about 6 hours searching the web and reading about how to tackle this
relatively simple problem. My dataset has five time points arranged as
rows, and 100 columns. I can easily plot any column against the time
points [qplot(time, var2, geom="line"). But I want to learn how to do this
for a flexible number of columns, and how to print 6 to 12 of the
individual graphs on one page.
Here I learned about the multiplot function, got that to work in terms of
layout.
What I am stuck on is how for get the list of variables into a FOR
statement so I can have one statement to plot all the variables against
the same five time points.
this is what I am playing with. It makes 9 plots, 3 columns wide, but I do
not know how to get all my variables into the array for yvars?
for (i in 1:9) {
+ p1 = qplot(symbol,yvar, geom ="smooth", main = i))
+ plots[[i]] <- p1 # add each plot into plot list
+ }
multiplot(plotlist = plots, cols = 3)
Stupidly on my part right now it makes 9 identical plots. So how do I
create the list so the above will cycle through all my columns and make
those plots?
Thank you,
I want to visualize many time series at once. I am new at R, and have
spent about 6 hours searching the web and reading about how to tackle this
relatively simple problem. My dataset has five time points arranged as
rows, and 100 columns. I can easily plot any column against the time
points [qplot(time, var2, geom="line"). But I want to learn how to do this
for a flexible number of columns, and how to print 6 to 12 of the
individual graphs on one page.
Here I learned about the multiplot function, got that to work in terms of
layout.
What I am stuck on is how for get the list of variables into a FOR
statement so I can have one statement to plot all the variables against
the same five time points.
this is what I am playing with. It makes 9 plots, 3 columns wide, but I do
not know how to get all my variables into the array for yvars?
for (i in 1:9) {
+ p1 = qplot(symbol,yvar, geom ="smooth", main = i))
+ plots[[i]] <- p1 # add each plot into plot list
+ }
multiplot(plotlist = plots, cols = 3)
Stupidly on my part right now it makes 9 identical plots. So how do I
create the list so the above will cycle through all my columns and make
those plots?
Thank you,
in Jquery why it won't alert each one in while loop?
in Jquery why it won't alert each one in while loop?
<body>
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<script>
$(document).ready(function(){
var boxNumber=1;
while(boxNumber<=3){
$('#div'+boxNumber).click(function(){
alert(boxNumber);
});
boxNumber++;
}
});
</script>
</body>
I expected the code to alert its box number when i click on it, but it
alerted number 4 instead. how do i fix it? Thanks
<body>
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<script>
$(document).ready(function(){
var boxNumber=1;
while(boxNumber<=3){
$('#div'+boxNumber).click(function(){
alert(boxNumber);
});
boxNumber++;
}
});
</script>
</body>
I expected the code to alert its box number when i click on it, but it
alerted number 4 instead. how do i fix it? Thanks
telephonymanager works in emulator but not in phone
telephonymanager works in emulator but not in phone
I would like to get the phone number with android.
I did:
TelephonyManager tMgr
=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
String phoneNumber = tMgr.getLine1Number();
phoneNumberT = (TextView)findViewById(R.id.phone);
phoneNumberT.setText("Number: " + phoneNumber);
and in Android Manifest:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
with the emulator i see this:
Number: 15555215554
But I installed the app in my android phone I only see
Number:
Why is not shown in the number?
I would like to get the phone number with android.
I did:
TelephonyManager tMgr
=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
String phoneNumber = tMgr.getLine1Number();
phoneNumberT = (TextView)findViewById(R.id.phone);
phoneNumberT.setText("Number: " + phoneNumber);
and in Android Manifest:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
with the emulator i see this:
Number: 15555215554
But I installed the app in my android phone I only see
Number:
Why is not shown in the number?
c# Scripting has wrong data when accessing from another AppDomain
c# Scripting has wrong data when accessing from another AppDomain
I am trying to add C# scripting to my application and decided to use
AppDomain(s) so that I can successfully load and unload scripts without
causing memory issues. My current code has a ScriptManager that loads
scripts within a folder using a watcher to check for changes:
private static void LoadScript(string scriptPath)
{
string scriptName = Path.GetFileNameWithoutExtension(scriptPath);
AppDomain domain = AppDomain.CreateDomain(scriptName);
domains.Add(domain);
ScriptCompiler scriptCompiler =
(ScriptCompiler)domain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location,
"Milkshake.Tools.ScriptCompiler");
scriptCompiler.Compile(scriptPath);
}
It creates a new appdomain instance of my scriptcompiler and then attempts
to compile the script code and finally instantiates the script:
public void Compile(string filepath)
{
string code = File.ReadAllText(filepath);
CSharpCodeProvider codeProvider = new CSharpCodeProvider(new
Dictionary<String, String> { { "CompilerVersion", "v3.5" } });
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
parameters.GenerateExecutable = false;
//Add references used in scripts
parameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
//Current application ('using milkshake;')
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Core.dll");
parameters.ReferencedAssemblies.Add("System.Data.dll");
parameters.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
parameters.ReferencedAssemblies.Add("System.Xml.dll");
parameters.ReferencedAssemblies.Add("System.Xml.Linq.dll");
CompilerResults results =
codeProvider.CompileAssemblyFromSource(parameters, code);
if (results.Errors.HasErrors)
{
string error = "Error in script: " +
Path.GetFileNameWithoutExtension(filepath);
foreach (CompilerError e in results.Errors)
{
error += "\n" + e;
}
Log.Print(LogType.Error, error);
}
else
{
//Successful Compile
Log.Print(LogType.Debug, "Script Loaded: " +
Path.GetFileNameWithoutExtension(filepath));
assembly = results.CompiledAssembly;
type = assembly.GetTypes()[0];
//Instansiate script class.
Activator.CreateInstance(type);
}
}
Now the code actually works fine, it loads the script and unloads it
correctly, however when I try call a method in my main application from
the script, it has the wrong data. For example, this script will print out
"Test", and then print out how many players are on the server and finally
send the message "Test" to all of the players.
class TestScript
{
public TestScript()
{
Log.Print(LogType.Debug, "Test!");
//TODO Figure out why the FK this doesnt work :(
Log.Print(LogType.Debug, WorldServer.Sessions.Count);
WorldServer.Sessions.ForEach(s => s.sendMessage("Test!!"));
}
}
Now the interesting thing here is that my WorldServer.Sessions.Count
(WorldServer is static) always comes out as 0 when I call it from the
script (when I call it from my main application it comes out as 1).
Everytime I try and call a method or get data from my main application, it
has problems. I am guessing this is to do with cross-appdomain stuff, so I
really don't know what the best approach is.
I am trying to add C# scripting to my application and decided to use
AppDomain(s) so that I can successfully load and unload scripts without
causing memory issues. My current code has a ScriptManager that loads
scripts within a folder using a watcher to check for changes:
private static void LoadScript(string scriptPath)
{
string scriptName = Path.GetFileNameWithoutExtension(scriptPath);
AppDomain domain = AppDomain.CreateDomain(scriptName);
domains.Add(domain);
ScriptCompiler scriptCompiler =
(ScriptCompiler)domain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location,
"Milkshake.Tools.ScriptCompiler");
scriptCompiler.Compile(scriptPath);
}
It creates a new appdomain instance of my scriptcompiler and then attempts
to compile the script code and finally instantiates the script:
public void Compile(string filepath)
{
string code = File.ReadAllText(filepath);
CSharpCodeProvider codeProvider = new CSharpCodeProvider(new
Dictionary<String, String> { { "CompilerVersion", "v3.5" } });
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
parameters.GenerateExecutable = false;
//Add references used in scripts
parameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
//Current application ('using milkshake;')
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Core.dll");
parameters.ReferencedAssemblies.Add("System.Data.dll");
parameters.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
parameters.ReferencedAssemblies.Add("System.Xml.dll");
parameters.ReferencedAssemblies.Add("System.Xml.Linq.dll");
CompilerResults results =
codeProvider.CompileAssemblyFromSource(parameters, code);
if (results.Errors.HasErrors)
{
string error = "Error in script: " +
Path.GetFileNameWithoutExtension(filepath);
foreach (CompilerError e in results.Errors)
{
error += "\n" + e;
}
Log.Print(LogType.Error, error);
}
else
{
//Successful Compile
Log.Print(LogType.Debug, "Script Loaded: " +
Path.GetFileNameWithoutExtension(filepath));
assembly = results.CompiledAssembly;
type = assembly.GetTypes()[0];
//Instansiate script class.
Activator.CreateInstance(type);
}
}
Now the code actually works fine, it loads the script and unloads it
correctly, however when I try call a method in my main application from
the script, it has the wrong data. For example, this script will print out
"Test", and then print out how many players are on the server and finally
send the message "Test" to all of the players.
class TestScript
{
public TestScript()
{
Log.Print(LogType.Debug, "Test!");
//TODO Figure out why the FK this doesnt work :(
Log.Print(LogType.Debug, WorldServer.Sessions.Count);
WorldServer.Sessions.ForEach(s => s.sendMessage("Test!!"));
}
}
Now the interesting thing here is that my WorldServer.Sessions.Count
(WorldServer is static) always comes out as 0 when I call it from the
script (when I call it from my main application it comes out as 1).
Everytime I try and call a method or get data from my main application, it
has problems. I am guessing this is to do with cross-appdomain stuff, so I
really don't know what the best approach is.
Server-side Mail Rules on OS X Server (Mountain Lion)
Server-side Mail Rules on OS X Server (Mountain Lion)
I would like to set up server-side mail filter rules for Dovecot on my OS
X Server (Mountain Lion). I would like for sieve scripts to be in the user
directories i.e. ~/.dovecot.sieve. I can't seem to find any documentation
on this. From what I can determine from the information in dovecotd -a the
sieve seems to be already set up, but if I add a script to
~/.dovecot.sieve it doesn't initiate the filtering.
managesieve_client_workarounds = managesieve_implementation_string =
Dovecot Pigeonhole managesieve_logout_format = bytes=%i/%o
managesieve_max_compile_errors = 5 managesieve_max_line_length = 65536
managesieve_notify_capability = mailto managesieve_sieve_capability =
fileinto reject envelope encoded-character vacation subaddress
comparator-i;ascii-numeric relational regex imap4flags copy include
variables body enotify environment mailbox date ihave
Thanks for any tips
I would like to set up server-side mail filter rules for Dovecot on my OS
X Server (Mountain Lion). I would like for sieve scripts to be in the user
directories i.e. ~/.dovecot.sieve. I can't seem to find any documentation
on this. From what I can determine from the information in dovecotd -a the
sieve seems to be already set up, but if I add a script to
~/.dovecot.sieve it doesn't initiate the filtering.
managesieve_client_workarounds = managesieve_implementation_string =
Dovecot Pigeonhole managesieve_logout_format = bytes=%i/%o
managesieve_max_compile_errors = 5 managesieve_max_line_length = 65536
managesieve_notify_capability = mailto managesieve_sieve_capability =
fileinto reject envelope encoded-character vacation subaddress
comparator-i;ascii-numeric relational regex imap4flags copy include
variables body enotify environment mailbox date ihave
Thanks for any tips
Friday, 23 August 2013
Define a class MyClass or a function MyFunction(T x) where T can only by a type that implements IMyInterface
Define a class MyClass or a function MyFunction(T x) where T can only by a
type that implements IMyInterface
I want to define a class MyClass<T> and a very particular function
MyFunc<T>, but I want to force T to inherit from (in any way) an interface
or a class. Let's call this IMyInterface.
The only way my knowledge of C# allows me to do this is to define a
generic class, check if it inherits (see In C#, how do I check if a type
is a subtype OR the type of an object? for example), and throw an
exception otherwise.
Is there a way to force this at compile-time, rather than runtime?
type that implements IMyInterface
I want to define a class MyClass<T> and a very particular function
MyFunc<T>, but I want to force T to inherit from (in any way) an interface
or a class. Let's call this IMyInterface.
The only way my knowledge of C# allows me to do this is to define a
generic class, check if it inherits (see In C#, how do I check if a type
is a subtype OR the type of an object? for example), and throw an
exception otherwise.
Is there a way to force this at compile-time, rather than runtime?
typecasting void *object pointers
typecasting void *object pointers
With regards to this piece of code:
#include <iostream>
class CClass1
{
public:
void print() {
std::cout << "This should print first" << std::endl;
}
};
class CClass2
{
public:
void print() {
std::cout << "This should print second" << std::endl;
}
};
So someone asked an interesting question about having a "free pointer" (so
to speak) which can point to multiple instances of different objects
without having to create a new type of that object. The person had the
idea that this pointer can be of type void * and since it is void, it can
be made to point to any instance of an object and access the object's
public properties.
The following solution was submitted:
int main() {
void *pClass(NULL);
((CClass1 *)(pClass))->print();
((CClass2 *)(pClass))->print();
std::cin.ignore();
return 0;
}
My question is why does the above work, but this doesn't:
int main() {
(CClass1 *FG)->print();
(CClass2 *FG)->print();
std::cin.ignore();
return 0;
}
With regards to this piece of code:
#include <iostream>
class CClass1
{
public:
void print() {
std::cout << "This should print first" << std::endl;
}
};
class CClass2
{
public:
void print() {
std::cout << "This should print second" << std::endl;
}
};
So someone asked an interesting question about having a "free pointer" (so
to speak) which can point to multiple instances of different objects
without having to create a new type of that object. The person had the
idea that this pointer can be of type void * and since it is void, it can
be made to point to any instance of an object and access the object's
public properties.
The following solution was submitted:
int main() {
void *pClass(NULL);
((CClass1 *)(pClass))->print();
((CClass2 *)(pClass))->print();
std::cin.ignore();
return 0;
}
My question is why does the above work, but this doesn't:
int main() {
(CClass1 *FG)->print();
(CClass2 *FG)->print();
std::cin.ignore();
return 0;
}
Is device memory allocated using CudaMalloc inaccessible on the device with free?
Is device memory allocated using CudaMalloc inaccessible on the device
with free?
I cannot deallocate memory on the host that I've allocated on the device
or deallocate memory on the device that I allocated on the host. I'm using
CUDA 5.5 with VS2012 and Nsight. Is it because the heap that's on the host
is not transferred to the heap that's on the device or the other way
around, so dynamic allocations are unknown between host and device?
If this is in the documentation, it is not easy to find. It's also
important to note, an error wasn't thrown until I ran the program with
CUDA debugging and with Memory Checker enabled. The problem did not cause
a crash outside of CUDA debugging, but would've cause problems later if I
hadn't checked for memory issues retroactively. If there's a handy way to
copy the heap/stack from host to device, that'd be fantastic... hopes and
dreams.
Here's an example for my question:
__global__ void kernel(char *ptr)
{
free(ptr);
}
void main(void)
{
char *ptr;
cudaMalloc((void **)&ptr, sizeof(char *), cudaMemcpyHostToDevice);
kernel<<<1, 1>>>(ptr);
}
with free?
I cannot deallocate memory on the host that I've allocated on the device
or deallocate memory on the device that I allocated on the host. I'm using
CUDA 5.5 with VS2012 and Nsight. Is it because the heap that's on the host
is not transferred to the heap that's on the device or the other way
around, so dynamic allocations are unknown between host and device?
If this is in the documentation, it is not easy to find. It's also
important to note, an error wasn't thrown until I ran the program with
CUDA debugging and with Memory Checker enabled. The problem did not cause
a crash outside of CUDA debugging, but would've cause problems later if I
hadn't checked for memory issues retroactively. If there's a handy way to
copy the heap/stack from host to device, that'd be fantastic... hopes and
dreams.
Here's an example for my question:
__global__ void kernel(char *ptr)
{
free(ptr);
}
void main(void)
{
char *ptr;
cudaMalloc((void **)&ptr, sizeof(char *), cudaMemcpyHostToDevice);
kernel<<<1, 1>>>(ptr);
}
Play all youtube video from database randomly and repeatedly into iframe
Play all youtube video from database randomly and repeatedly into iframe
It play only single video randomly from mysql database into iframe tag in
php page. how to play all video???
It play only single video randomly from mysql database into iframe tag in
php page. how to play all video???
Does the Play! Framework have an equivalent of phpinfo?
Does the Play! Framework have an equivalent of phpinfo?
Actually, that was my entire question, "Does the Play! Framework have an
equivalent of phpinfo?" I would like to get some info on my dev stack out
on a web page.
Actually, that was my entire question, "Does the Play! Framework have an
equivalent of phpinfo?" I would like to get some info on my dev stack out
on a web page.
Error while Retriving files from google drive using drive API. Calling this from your main thread can lead to deadlock
Error while Retriving files from google drive using drive API. "Calling
this from your main thread can lead to deadlock
Hi this is what i am trying to do to get the text files.I tried same with
New thread
also when i create new thread its not coming inside the getfiles(Drive
services) method only. Please give me solution i am not getting this.
Error is runnung with main may lead to deadlock
public class MainActivity extends Activity {
static final int REQUEST_ACCOUNT_PICKER = 1;
private static Uri fileUri;
private static Drive service;
private GoogleAccountCredential credential;
Button b;
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.b1);
credential = GoogleAccountCredential.usingOAuth2(this,
DriveScopes.DRIVE);
startActivityForResult(credential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
Toast.makeText(getApplicationContext(), "case1",
Toast.LENGTH_LONG).show();
}
protected void onActivityResult(final int requestCode, final int
resultCode, final Intent data)
{
if(requestCode==REQUEST_ACCOUNT_PICKER)
{
if (resultCode == RESULT_OK && data != null && data.getExtras()
!= null)
{
Toast.makeText(getApplicationContext(), "case2",
Toast.LENGTH_LONG).show();
String accountName =
data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null)
{
credential.setSelectedAccountName(accountName);
service = getDriveService(credential);
Toast.makeText(getApplicationContext(), "Got the E mail
id", Toast.LENGTH_LONG).show();
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "case4",
Toast.LENGTH_LONG).show();
getfiles(service);
}
});
}
}
}
}
public void getfiles(final Drive service)
{
Toast.makeText(getApplicationContext(), "case5",
Toast.LENGTH_LONG).show();
String TEXT_PLAIN = "TEXT/PLAIN";
try
{
Files.List request = service.files().list().setQ("mimeType = '" +
TEXT_PLAIN +"'");
Toast.makeText(getApplicationContext(), "case",
Toast.LENGTH_LONG).show();
Map<String, File> textFiles = new HashMap<String, File>();
do {
Toast.makeText(getApplicationContext(), "case6",
Toast.LENGTH_LONG).show();
FileList files = request.execute(); //this is error line
Toast.makeText(getApplicationContext(), "case7",
Toast.LENGTH_LONG).show();
for (File file : files.getItems())
{
textFiles.put(file.getId(), file);
}
request.setPageToken(files.getNextPageToken());
} while (request.getPageToken() != null &&
request.getPageToken().length() > 0);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),e.toString(),
Toast.LENGTH_LONG).show();
}
}
private Drive getDriveService(GoogleAccountCredential credential) {
return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new
GsonFactory(), credential)
.build();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
this from your main thread can lead to deadlock
Hi this is what i am trying to do to get the text files.I tried same with
New thread
also when i create new thread its not coming inside the getfiles(Drive
services) method only. Please give me solution i am not getting this.
Error is runnung with main may lead to deadlock
public class MainActivity extends Activity {
static final int REQUEST_ACCOUNT_PICKER = 1;
private static Uri fileUri;
private static Drive service;
private GoogleAccountCredential credential;
Button b;
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.b1);
credential = GoogleAccountCredential.usingOAuth2(this,
DriveScopes.DRIVE);
startActivityForResult(credential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
Toast.makeText(getApplicationContext(), "case1",
Toast.LENGTH_LONG).show();
}
protected void onActivityResult(final int requestCode, final int
resultCode, final Intent data)
{
if(requestCode==REQUEST_ACCOUNT_PICKER)
{
if (resultCode == RESULT_OK && data != null && data.getExtras()
!= null)
{
Toast.makeText(getApplicationContext(), "case2",
Toast.LENGTH_LONG).show();
String accountName =
data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null)
{
credential.setSelectedAccountName(accountName);
service = getDriveService(credential);
Toast.makeText(getApplicationContext(), "Got the E mail
id", Toast.LENGTH_LONG).show();
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "case4",
Toast.LENGTH_LONG).show();
getfiles(service);
}
});
}
}
}
}
public void getfiles(final Drive service)
{
Toast.makeText(getApplicationContext(), "case5",
Toast.LENGTH_LONG).show();
String TEXT_PLAIN = "TEXT/PLAIN";
try
{
Files.List request = service.files().list().setQ("mimeType = '" +
TEXT_PLAIN +"'");
Toast.makeText(getApplicationContext(), "case",
Toast.LENGTH_LONG).show();
Map<String, File> textFiles = new HashMap<String, File>();
do {
Toast.makeText(getApplicationContext(), "case6",
Toast.LENGTH_LONG).show();
FileList files = request.execute(); //this is error line
Toast.makeText(getApplicationContext(), "case7",
Toast.LENGTH_LONG).show();
for (File file : files.getItems())
{
textFiles.put(file.getId(), file);
}
request.setPageToken(files.getNextPageToken());
} while (request.getPageToken() != null &&
request.getPageToken().length() > 0);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),e.toString(),
Toast.LENGTH_LONG).show();
}
}
private Drive getDriveService(GoogleAccountCredential credential) {
return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new
GsonFactory(), credential)
.build();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Thursday, 22 August 2013
Bitwise & operator returns 255
Bitwise & operator returns 255
I am using bitwise & operator but instead of 1 and 0 result I am getting
255 and 0.What could be the reason? The code is
cv::Mat TL_k_idx =
((orientation_map.col(0)<=(quad_coords[0]+quad_coords[2])/2) &
(orientation_map.col(1)<=(quad_coords[1]+quad_coords[3])/2));
cout<<TL_k_idx;
The output of TL_k_idx is:
255 255 255 255 0 0............
The orientation_map is of Mat data type,the quad_coords is an array.What
am I doing wrong?
I am using bitwise & operator but instead of 1 and 0 result I am getting
255 and 0.What could be the reason? The code is
cv::Mat TL_k_idx =
((orientation_map.col(0)<=(quad_coords[0]+quad_coords[2])/2) &
(orientation_map.col(1)<=(quad_coords[1]+quad_coords[3])/2));
cout<<TL_k_idx;
The output of TL_k_idx is:
255 255 255 255 0 0............
The orientation_map is of Mat data type,the quad_coords is an array.What
am I doing wrong?
How do you take outside sensitive information in Perl
How do you take outside sensitive information in Perl
Sometimes I do hard coding to stuff that is important like IPs and passwords:
eval {
$ldap = LDAPModule->new(
host => '1.1.1.1',
domain => 'my.domain.local',
)->authenticate( $args->{id}, $args->{pw} );
};
...
What ways we have to hide such information or manage better (modules?,
take outside? .... )
Sometimes I do hard coding to stuff that is important like IPs and passwords:
eval {
$ldap = LDAPModule->new(
host => '1.1.1.1',
domain => 'my.domain.local',
)->authenticate( $args->{id}, $args->{pw} );
};
...
What ways we have to hide such information or manage better (modules?,
take outside? .... )
jquery validator plugin time and date
jquery validator plugin time and date
i am using the jquery validator plugin, which has no way to validate the
date and time. By using the jquery input features, i know that the time
will be in the correct format.
<input type="time" id="time />
<input type="time" id="time2 />
<input type="date" id="date" />
However, can someone please teach me how to create a method that ensures
that "time2" is no later than 11:59 PM or 23:59 and another method that
requires "time2" to be greater than "time"
I have tried but I do not understand the syntax required for the addMethod
function
i am using the jquery validator plugin, which has no way to validate the
date and time. By using the jquery input features, i know that the time
will be in the correct format.
<input type="time" id="time />
<input type="time" id="time2 />
<input type="date" id="date" />
However, can someone please teach me how to create a method that ensures
that "time2" is no later than 11:59 PM or 23:59 and another method that
requires "time2" to be greater than "time"
I have tried but I do not understand the syntax required for the addMethod
function
Is it possible to assign a ReadOnly variable in a child class?
Is it possible to assign a ReadOnly variable in a child class?
Suppose I have this parent class:
Public MustInherit Class Parent
' ReadOnly instance variables:
Protected ReadOnly str1 As String
Protected ReadOnly str2 As String
Protected ReadOnly str3 As String
' constructor:
Public Sub New()
End Sub
End Class
I want to assign these variables in a child class' constructor, and I want
them to be ReadOnly so they cannot be changed once assigned, like this:
Public Class Child
Inherits Parent
' constructor:
Public Sub New()
MyBase.New()
' can't assign the ReadOnly variables here!
' compile error: 'ReadOnly' variable cannot be the target of an
assignment
Me.str1 = "asdf"
Me.str2 = "qwerty"
Me.str3 = "foobar"
End Sub
End Class
How can I do this? If it's not possible, why not?
Suppose I have this parent class:
Public MustInherit Class Parent
' ReadOnly instance variables:
Protected ReadOnly str1 As String
Protected ReadOnly str2 As String
Protected ReadOnly str3 As String
' constructor:
Public Sub New()
End Sub
End Class
I want to assign these variables in a child class' constructor, and I want
them to be ReadOnly so they cannot be changed once assigned, like this:
Public Class Child
Inherits Parent
' constructor:
Public Sub New()
MyBase.New()
' can't assign the ReadOnly variables here!
' compile error: 'ReadOnly' variable cannot be the target of an
assignment
Me.str1 = "asdf"
Me.str2 = "qwerty"
Me.str3 = "foobar"
End Sub
End Class
How can I do this? If it's not possible, why not?
Reconnecting After Twitter Streaming Disconnect Status Code 7
Reconnecting After Twitter Streaming Disconnect Status Code 7
I have been working on streaming twitter data to my application and nearly
managed to get things working by using some of the code from the following
StackOverflow question: Getting 401 from Twitter Stream API using C#.
However, if I close the connection whilst the streaming is taking place
within my application and try to restart it, I get the following API
response:
{"disconnect":{"code":7,"stream_name":"sbhomra-statuses171190","reason":"admin
logout"}}
I understand from the Twitter documentation that:
The same credentials were used to connect a new stream and the oldest was
disconnected.
But how do I go about reconnecting to my stream after this error has
occurred?
I have been working on streaming twitter data to my application and nearly
managed to get things working by using some of the code from the following
StackOverflow question: Getting 401 from Twitter Stream API using C#.
However, if I close the connection whilst the streaming is taking place
within my application and try to restart it, I get the following API
response:
{"disconnect":{"code":7,"stream_name":"sbhomra-statuses171190","reason":"admin
logout"}}
I understand from the Twitter documentation that:
The same credentials were used to connect a new stream and the oldest was
disconnected.
But how do I go about reconnecting to my stream after this error has
occurred?
Html getting distorted in mobile browser when rotating the device (changing orientation from landscape to portrait and vice versa)
Html getting distorted in mobile browser when rotating the device
(changing orientation from landscape to portrait and vice versa)
I have website www.xyz.com, when I load this url in mobile in portrait
mode it looks nice, it even looks good when I load in landscape mode, but
suppose when I load the page in landscape mode and rotate the mobile to
portrait mode then design gets zoomed out and suppose I loaded the page in
portrait mode and rotated to landscape mode then design gets zoomed in.
Can you please suggest?
(changing orientation from landscape to portrait and vice versa)
I have website www.xyz.com, when I load this url in mobile in portrait
mode it looks nice, it even looks good when I load in landscape mode, but
suppose when I load the page in landscape mode and rotate the mobile to
portrait mode then design gets zoomed out and suppose I loaded the page in
portrait mode and rotated to landscape mode then design gets zoomed in.
Can you please suggest?
Wednesday, 21 August 2013
Image PNG on Internet Explorer 10?
Image PNG on Internet Explorer 10?
because a png image that I put in the header of my website on all browsers
display correctly on Internet Explorer and 10 displays a square around it?
I'm going crazy trying to figure out why. Can anyone help me? The image
has no background, is transparent. I attach a screenshot for you to
understand the problem better.
http://i43.tinypic.com/2wovu5f.png
The blue part is the logo (which I covered)
because a png image that I put in the header of my website on all browsers
display correctly on Internet Explorer and 10 displays a square around it?
I'm going crazy trying to figure out why. Can anyone help me? The image
has no background, is transparent. I attach a screenshot for you to
understand the problem better.
http://i43.tinypic.com/2wovu5f.png
The blue part is the logo (which I covered)
access folder other than inside static
access folder other than inside static
How can I access a folder, which is in the same level that of 'static'.
e.g. I want to put a 'download' folder. Although static/download can be
accessed and working.
Since files gets changed inside download folder, want to change the folder
level. Is there a way out???
How can I access a folder, which is in the same level that of 'static'.
e.g. I want to put a 'download' folder. Although static/download can be
accessed and working.
Since files gets changed inside download folder, want to change the folder
level. Is there a way out???
Get Developer Options -> Pointer location logs in android
Get "Developer Options -> Pointer location" logs in android
For the research I am doing, I am required to collect data from user
interaction with android devices ICS or better for touch inputs. I was
thinking the best way to do so would be to use the Pointer Location
available under Developer Options settings. I traced the source code that
recreated that into a program was able to see the logs from that program
through logcat, but I am not able to see it when I am running from the
settings. Could anyone please point me into a right direction on how can I
go about getting those log files? Here's the source that seems to be
responsible for logging which does fine in my application but not through
the settings menu:
private void More ...logPointerCoords(MotionEvent.PointerCoords coords,
int id) {
Log.i(TAG, mText.clear()
.append("Pointer ").append(id + 1)
.append(": (").append(coords.x, 3).append(",
").append(coords.y, 3)
.append(") Pressure=").append(coords.pressure, 3)
.append(" Size=").append(coords.size, 3)
.append(" TouchMajor=").append(coords.touchMajor, 3)
.append(" TouchMinor=").append(coords.touchMinor, 3)
.append(" ToolMajor=").append(coords.toolMajor, 3)
.append(" ToolMinor=").append(coords.toolMinor, 3)
.append(" Orientation=").append((float)(coords.orientation *
180 / Math.PI), 1)
.append("deg").toString());
}
What I did with source:
I recreated a program/app from two class: public class PointerLocationView
extends View called from public class PointerLocation extends Activity and
managed to replicate the same functionality in an activity.
Thank your for the help.
For the research I am doing, I am required to collect data from user
interaction with android devices ICS or better for touch inputs. I was
thinking the best way to do so would be to use the Pointer Location
available under Developer Options settings. I traced the source code that
recreated that into a program was able to see the logs from that program
through logcat, but I am not able to see it when I am running from the
settings. Could anyone please point me into a right direction on how can I
go about getting those log files? Here's the source that seems to be
responsible for logging which does fine in my application but not through
the settings menu:
private void More ...logPointerCoords(MotionEvent.PointerCoords coords,
int id) {
Log.i(TAG, mText.clear()
.append("Pointer ").append(id + 1)
.append(": (").append(coords.x, 3).append(",
").append(coords.y, 3)
.append(") Pressure=").append(coords.pressure, 3)
.append(" Size=").append(coords.size, 3)
.append(" TouchMajor=").append(coords.touchMajor, 3)
.append(" TouchMinor=").append(coords.touchMinor, 3)
.append(" ToolMajor=").append(coords.toolMajor, 3)
.append(" ToolMinor=").append(coords.toolMinor, 3)
.append(" Orientation=").append((float)(coords.orientation *
180 / Math.PI), 1)
.append("deg").toString());
}
What I did with source:
I recreated a program/app from two class: public class PointerLocationView
extends View called from public class PointerLocation extends Activity and
managed to replicate the same functionality in an activity.
Thank your for the help.
What's wrong with my code? Camera app not saving pictures
What's wrong with my code? Camera app not saving pictures
I'm programming a camera app and it lets me see the camera and snap the
photo and everything but for some reason it doesn't save. Also I'd like
the picture to stay for a few seconds after taken before going back to
camera mode. Can someone please tell me what's wrong with my code?
Thanks so much!!
AndroidManifest:
<uses-feature android:name="android.hardware.camera"
android:required="true"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="WRITE_INTERNAL_STORAGE"/>
MainActivity.java:
@Override
public void onPictureTaken(byte[] data, Camera camera) {
//Here, we chose internal storage
try {
FileOutputStream out = openFileOutput("picture.jpg",
Activity.MODE_PRIVATE);
out.write(data);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
camera.startPreview();
}
I'm programming a camera app and it lets me see the camera and snap the
photo and everything but for some reason it doesn't save. Also I'd like
the picture to stay for a few seconds after taken before going back to
camera mode. Can someone please tell me what's wrong with my code?
Thanks so much!!
AndroidManifest:
<uses-feature android:name="android.hardware.camera"
android:required="true"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="WRITE_INTERNAL_STORAGE"/>
MainActivity.java:
@Override
public void onPictureTaken(byte[] data, Camera camera) {
//Here, we chose internal storage
try {
FileOutputStream out = openFileOutput("picture.jpg",
Activity.MODE_PRIVATE);
out.write(data);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
camera.startPreview();
}
get attribute with getattr from a object in python
get attribute with getattr from a object in python
I have an object p (liblas.point.Point) with several attributes
pattr = {
"r": 'return_number',
"n": 'number_of_returns',
"s": 'get_point_source_id()',
"e": 'flightline_edge',
"c": 'classification',
"a": 'scan_angle',
}
mylist = ["r", "n", "e", "c", "a"]
for letter in mylist:
print getattr(p, pattr[letter])
1
3
0
1
-23
I have a problem with get_point_source_id() where
p.get_point_source_id()
20
but when i use getattr i got this message
getattr(p, pattr["s"])
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py",
line 2721, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "<ipython-input-81-bbad74aa3829>", line 1, in <module>
getattr(p, pattr["s"])
AttributeError: 'Point' object has no attribute 'get_point_source_id()'
I have an object p (liblas.point.Point) with several attributes
pattr = {
"r": 'return_number',
"n": 'number_of_returns',
"s": 'get_point_source_id()',
"e": 'flightline_edge',
"c": 'classification',
"a": 'scan_angle',
}
mylist = ["r", "n", "e", "c", "a"]
for letter in mylist:
print getattr(p, pattr[letter])
1
3
0
1
-23
I have a problem with get_point_source_id() where
p.get_point_source_id()
20
but when i use getattr i got this message
getattr(p, pattr["s"])
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py",
line 2721, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "<ipython-input-81-bbad74aa3829>", line 1, in <module>
getattr(p, pattr["s"])
AttributeError: 'Point' object has no attribute 'get_point_source_id()'
Not enter while lop after mysql_fetch_assoc
Not enter while lop after mysql_fetch_assoc
please take a look at this code :
$sql = "SELECT * FROM shop";
$result = mysql_query($sql);
echo $result;
echo "before lop";
while ($xxx = mysql_fetch_assoc($result)) {
echo "inside lop";
echo $xxx['column_name'];
}
echo "after lop";
When I run such code i receive :
Resource id #244
before lop
after lop
It did not enter while lop, and I really don't know why :( I used before
such code and there were no problems. Can someone help me?
please take a look at this code :
$sql = "SELECT * FROM shop";
$result = mysql_query($sql);
echo $result;
echo "before lop";
while ($xxx = mysql_fetch_assoc($result)) {
echo "inside lop";
echo $xxx['column_name'];
}
echo "after lop";
When I run such code i receive :
Resource id #244
before lop
after lop
It did not enter while lop, and I really don't know why :( I used before
such code and there were no problems. Can someone help me?
How to write htaccess rewrite rules
How to write htaccess rewrite rules
I am using the following htaccess code for rewrite my url
site.com/page.php?id=1 to site.com/page/1.
RewriteEngine On
RewriteRule ^page/(.*) page.php?id=$1 [L]
If i add 8 rewrite rules to the main htaccess file , it may increase
increase execution time.So i am planing to create directories like page
and place a new htaccess files to it.
RewriteEngine On
RewriteRule (.*) index.php?id=$1 [L]
But this code doesn't works.
I am using the following htaccess code for rewrite my url
site.com/page.php?id=1 to site.com/page/1.
RewriteEngine On
RewriteRule ^page/(.*) page.php?id=$1 [L]
If i add 8 rewrite rules to the main htaccess file , it may increase
increase execution time.So i am planing to create directories like page
and place a new htaccess files to it.
RewriteEngine On
RewriteRule (.*) index.php?id=$1 [L]
But this code doesn't works.
Tuesday, 20 August 2013
Make sure weather row in a table is deleted
Make sure weather row in a table is deleted
function child_delete($c_no, $shift, $p_date, $dname) {
$p_status = 0;
$query = "DELETE from $this->tb1_name2 WHERE c_no=? AND
time_slot=? AND p_date=? AND d_name=? AND p_status=?";
$statement = $this->connection->mysqli_conn->prepare($query)
or die(mysqli_error($this->connection->mysqli_conn));
$statement->bind_param("dsssd", $c_no, $shift, $p_date, $dname,
$p_status) or die(mysqli_error($this->connection->mysqli_conn));
$result = $statement->execute() or
die(mysqli_error($this->connection->mysqli_conn));
print_r(mysqli_affected_rows($statement));
i used above code to delete row in a table and make sure weather the row
is deleted.but it gives following error.
<b>Warning</b>: mysqli_affected_rows() expects parameter 1 to be
mysqli, object given in
<b>/opt/lampp/htdocs/NEW/patient_channel/controller/Patient_controller.php</b>
on line <b>318</b><br />
function child_delete($c_no, $shift, $p_date, $dname) {
$p_status = 0;
$query = "DELETE from $this->tb1_name2 WHERE c_no=? AND
time_slot=? AND p_date=? AND d_name=? AND p_status=?";
$statement = $this->connection->mysqli_conn->prepare($query)
or die(mysqli_error($this->connection->mysqli_conn));
$statement->bind_param("dsssd", $c_no, $shift, $p_date, $dname,
$p_status) or die(mysqli_error($this->connection->mysqli_conn));
$result = $statement->execute() or
die(mysqli_error($this->connection->mysqli_conn));
print_r(mysqli_affected_rows($statement));
i used above code to delete row in a table and make sure weather the row
is deleted.but it gives following error.
<b>Warning</b>: mysqli_affected_rows() expects parameter 1 to be
mysqli, object given in
<b>/opt/lampp/htdocs/NEW/patient_channel/controller/Patient_controller.php</b>
on line <b>318</b><br />
How to use GLKTextureLoader to load a cubemap from a web url
How to use GLKTextureLoader to load a cubemap from a web url
Unsure how to use an image loaded from the web as an asset in a GLKit
skybox (like the old apple/google maps streetview) There are 2 methods for
loading cubemaps with GLKTextureLoader: cubeMapWithContentsOfFile and
cubeMapWithContentsOfUrl
If I grab the image locally it works fine:
NSString *path = [[NSBundle mainBundle] pathForResource:@"pano"
ofType:@"jpg"];
GLKTextureInfo *skyboxCubemap = [GLKTextureLoader
cubeMapWithContentsOfFile:imgPath options:options error:&error];
So is there a way to get a path from an image loaded from the web and use
it here?
Unsure how to use an image loaded from the web as an asset in a GLKit
skybox (like the old apple/google maps streetview) There are 2 methods for
loading cubemaps with GLKTextureLoader: cubeMapWithContentsOfFile and
cubeMapWithContentsOfUrl
If I grab the image locally it works fine:
NSString *path = [[NSBundle mainBundle] pathForResource:@"pano"
ofType:@"jpg"];
GLKTextureInfo *skyboxCubemap = [GLKTextureLoader
cubeMapWithContentsOfFile:imgPath options:options error:&error];
So is there a way to get a path from an image loaded from the web and use
it here?
HttpPost gives Illegalstateexception
HttpPost gives Illegalstateexception
I am trying to connect to a localhost (WAMP) webservice I created using an
httpPost request. It keeps failing and giving an IllegalStateExecption.
Can anyone provide some insight to the problem? Thank you!
String songtext,artisttext;
HttpResponse response ;
EditText song;
EditText artist;
EditText party;
HttpPost post;
HttpClient client;
ArrayList<NameValuePair> nameValuePairs;
String URL = "http://10.0.2.2/GoDJ/index.php?r=request/create";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
song = (EditText)findViewById(R.id.songTitle);
artist = (EditText)findViewById(R.id.songArtist);
party = (EditText)findViewById(R.id.partyid);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void uploadToDB(View view)
{
//send user message
Context context = getApplicationContext();
CharSequence text = "Letting the DJ Know!!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
//add values
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("party",
party.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("title",
song.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("artist",
artist.getText().toString()));
try
{
//instantiate request
client = new DefaultHttpClient();
post = new HttpPost(URL);
text = "Set Up Client and Post";
toast = Toast.makeText(context, text, duration);
toast.show();
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
text = "Entity Set";
toast = Toast.makeText(context, text, duration);
toast.show();
response = client.execute(post);
text = "Post Executed SUCCESS";
toast = Toast.makeText(context, text, duration);
toast.show();
}
catch(Exception e)
{
text = "FAILURE";
toast = Toast.makeText(context, text, duration);
toast.show();
e.printStackTrace();
}
}
}
I am trying to connect to a localhost (WAMP) webservice I created using an
httpPost request. It keeps failing and giving an IllegalStateExecption.
Can anyone provide some insight to the problem? Thank you!
String songtext,artisttext;
HttpResponse response ;
EditText song;
EditText artist;
EditText party;
HttpPost post;
HttpClient client;
ArrayList<NameValuePair> nameValuePairs;
String URL = "http://10.0.2.2/GoDJ/index.php?r=request/create";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
song = (EditText)findViewById(R.id.songTitle);
artist = (EditText)findViewById(R.id.songArtist);
party = (EditText)findViewById(R.id.partyid);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void uploadToDB(View view)
{
//send user message
Context context = getApplicationContext();
CharSequence text = "Letting the DJ Know!!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
//add values
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("party",
party.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("title",
song.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("artist",
artist.getText().toString()));
try
{
//instantiate request
client = new DefaultHttpClient();
post = new HttpPost(URL);
text = "Set Up Client and Post";
toast = Toast.makeText(context, text, duration);
toast.show();
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
text = "Entity Set";
toast = Toast.makeText(context, text, duration);
toast.show();
response = client.execute(post);
text = "Post Executed SUCCESS";
toast = Toast.makeText(context, text, duration);
toast.show();
}
catch(Exception e)
{
text = "FAILURE";
toast = Toast.makeText(context, text, duration);
toast.show();
e.printStackTrace();
}
}
}
Show wait cursor when all work is synchronous
Show wait cursor when all work is synchronous
In my Winforms application when you start an operation it may or may not
be done asynchronously. In the case that the work is all done
synchronously, I cannot get the wait cursor to show up using the same
approach I use when the work is done asynchronously.
Here's an example showing the issue:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var t = ButtonClick(button1, DoWorkAsync1);
}
private void button2_Click(object sender, EventArgs e)
{
var t = ButtonClick(button2, DoWorkAsync2);
}
private async Task ButtonClick(Button btn, Func<Task> doWorkAsync)
{
// Disable the UI and show the wait cursor
btn.Text = "Working...";
btn.Enabled = false;
UseWaitCursor = true;
// Application.DoEvents(); // Inserting this causes the problem to
go away.
await doWorkAsync();
// Simulate an update of the UI taking a long time
Thread.Sleep(2000);
// Renable the UI and stop showing the wait cursor
UseWaitCursor = false;
btn.Enabled = true;
}
private Task DoWorkAsync1()
{
// Work takes some time
return Task.Delay(2000);
}
private Task DoWorkAsync2()
{
// Work doesn't take any time, results are immediately available
return Task.FromResult<int>(0);
}
}
In this example:
Clicking button1 does show the Wait cursor (because the work is done
asynchronously).
Clicking button2 does not show the Wait cursor (because the work is all
done synchronously).
Clicking either button1 and button2 does result in the UI being disabled
as expected.
What is desired is that clicking either button1 or button2 should cause
the Wait cursor to be displayed for the entire interval between clicking
the button and the UI update work being completed.
Question:
Is there a way to solve this without inserting an Application.DoEvent (nor
anything equivalent that would cause message pumping to occur), or is it
only possible by pumping messages.
As an aside: why does the disabling of the control work correctly (unlike
the cursor).
In my Winforms application when you start an operation it may or may not
be done asynchronously. In the case that the work is all done
synchronously, I cannot get the wait cursor to show up using the same
approach I use when the work is done asynchronously.
Here's an example showing the issue:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var t = ButtonClick(button1, DoWorkAsync1);
}
private void button2_Click(object sender, EventArgs e)
{
var t = ButtonClick(button2, DoWorkAsync2);
}
private async Task ButtonClick(Button btn, Func<Task> doWorkAsync)
{
// Disable the UI and show the wait cursor
btn.Text = "Working...";
btn.Enabled = false;
UseWaitCursor = true;
// Application.DoEvents(); // Inserting this causes the problem to
go away.
await doWorkAsync();
// Simulate an update of the UI taking a long time
Thread.Sleep(2000);
// Renable the UI and stop showing the wait cursor
UseWaitCursor = false;
btn.Enabled = true;
}
private Task DoWorkAsync1()
{
// Work takes some time
return Task.Delay(2000);
}
private Task DoWorkAsync2()
{
// Work doesn't take any time, results are immediately available
return Task.FromResult<int>(0);
}
}
In this example:
Clicking button1 does show the Wait cursor (because the work is done
asynchronously).
Clicking button2 does not show the Wait cursor (because the work is all
done synchronously).
Clicking either button1 and button2 does result in the UI being disabled
as expected.
What is desired is that clicking either button1 or button2 should cause
the Wait cursor to be displayed for the entire interval between clicking
the button and the UI update work being completed.
Question:
Is there a way to solve this without inserting an Application.DoEvent (nor
anything equivalent that would cause message pumping to occur), or is it
only possible by pumping messages.
As an aside: why does the disabling of the control work correctly (unlike
the cursor).
$().attr not working on second pagebeforechange event
$().attr not working on second pagebeforechange event
I am using this code to show a week overview of lectures. It is a listview
wich is populated based on the week_id passed to the page using a q
variable in the url e.g. /week.html?q=32
The footer of the page has two buttons to navigate to the previous/next
week, which is the same page. The /week.html?q= is updated using
$("#week_prev").attr("href", '/week.html?q='+ weeknumber_prev);
$("#week_next").attr("href", '/week.html?q='+ weeknumber_next);
$("#text_week").text(week_id);
This code works flawless when I use the pageshow event listener.
Now I prefer to use the pagebeforeshow event listener, because the page is
then updated before the transition start. For some reason when using
pagebeforeshow event the footer href and text are not updated, but the
listview is. Variables are present and valid as I checked using alert()
Any help is very much appreciated.
Javascript
// Get dynamic data for specified week
//
// this is working:
// $(document).on('pageshow','#onderwijs_week', function(e, data){
//
// this isn't
$(document).on('pagebeforeshow', "#onderwijs_week", function (event,
data) {
var parameters = $(this).data("url").split("?")[1];
var week_id = parameters.replace("q=","");
//var week_id = getUrlVars()['q'];
$.getJSON("/json.php",{
section: "onderwijs",
query: week_id
},
function(json){
var mydate = new Date();
weeknumber_next = parseInt(week_id) + 1;
weeknumber_prev = parseInt(week_id) - 1;
week_id = "Week " + week_id;
if (json.onderwijs) {
$("#week_list").empty();
$.each(json.onderwijs,function(i,item){
date2check = new Date(item.date);
if (areSameDate(mydate, date2check)){
$("#week_list").append('<li
data-role="list-divider" role="heading"
data-theme="e">'+item.datum+
'</li><li data-theme="e">'+
'<h5
class="no-ellipsis"><strong>'+item.title
+'</strong></h5>'+
'<p>'+item.speaker+'</p>'+
'<p
class="ui-li-aside"><strong>'+item.time+'</strong></p></li>');
week_id = "Deze Week";
} else {
$("#week_list").append('<li
data-role="list-divider"
role="heading">'+item.datum+
'</li><li>'+
'<h5
class="no-ellipses"><strong>'+item.title
+'</strong></h5>'+
'<p>'+item.speaker+'</p>'+
'<p
class="ui-li-aside"><strong>'+item.time+'</strong></p></li>');
}
});
//
// This is the part failing using
pagebeforechange and is working using pageshow
$("#week_prev").attr("href", '/week.html?q='+
weeknumber_prev);
$("#week_next").attr("href", '/week.html?q='+
weeknumber_next);
$("#text_week").text(week_id);
} else {
$("#week_list").empty();
$("#week_list").append('<li
data-role="list-divider"
role="heading">'+week_id+' 2013'+
'</li><li>'+
'<h5><strong>Nog geen
programma
bekend</strong></h5>'+
'<p>Dit wordt meestal ca 2
weken voor het begin van
de maand
gepubliceerd</p></li>');
$("#week_prev").attr("data-rel", "back");
$("#week_next").remove();
$("#text_week").text(week_id);
}
$("#week_list").listview('refresh');
});
});
HTML
<html>
<head>
</head>
<body>
<!-- Begin Page -->
<div data-role="page" id="onderwijs_week" data-theme="c">
<div data-role="header" data-id="navbar" data-position="fixed"
data-theme="f">
<a href="#main_panel" data-icon="bars" data-iconpos="notext"
class="ui-btn-left" data-transition="slide">Panel</a>
<h1>Onderwijs</h1>
<a href="/colofon.html" data-icon="info" data-iconpos="notext"
class="ui-btn-right" data-transition="fade">Colofon</a>
</div>
<div data-role="content">
<ul data-role="listview" id="week_list" data-dividertheme="c"></ul>
</div>
<div data-role="footer" data-position="fixed" data-id="footer"
data-theme="c" id="week_footer">
<a id="week_prev" href="" data-role="button" data-icon="arrow-l"
class="ui-btn-left" data-iconpos="notext" data-transition="slide"
data-direction="reverse">Vorige</a><h1 id="text_week"></h1><a
id="week_next" href="" data-role="button" data-icon="arrow-r"
class="ui-btn-right" data-iconpos="notext"
data-transition="slide">Volgende</a>
</div>
<div data-role="panel" id="main_panel" data-position="left"
data-display="reveal">
<ul data-role="listview" data-divider-theme="a">
<li data-role="list-divider" role="heading">Hoofdmenu</li>
<li><a href="/home.html" data-transition="slide">Home</a></li>
<li><a href="/content/mp/" data-transition="slide">Medische
protocollen</a></li>
<li><a href="#main_panel">Onderwijs</a></li>
<li><a href="/onderzoek.html">Onderzoek</a></li>
</ul>
</div>
</div>
</body>
</html>
I am using this code to show a week overview of lectures. It is a listview
wich is populated based on the week_id passed to the page using a q
variable in the url e.g. /week.html?q=32
The footer of the page has two buttons to navigate to the previous/next
week, which is the same page. The /week.html?q= is updated using
$("#week_prev").attr("href", '/week.html?q='+ weeknumber_prev);
$("#week_next").attr("href", '/week.html?q='+ weeknumber_next);
$("#text_week").text(week_id);
This code works flawless when I use the pageshow event listener.
Now I prefer to use the pagebeforeshow event listener, because the page is
then updated before the transition start. For some reason when using
pagebeforeshow event the footer href and text are not updated, but the
listview is. Variables are present and valid as I checked using alert()
Any help is very much appreciated.
Javascript
// Get dynamic data for specified week
//
// this is working:
// $(document).on('pageshow','#onderwijs_week', function(e, data){
//
// this isn't
$(document).on('pagebeforeshow', "#onderwijs_week", function (event,
data) {
var parameters = $(this).data("url").split("?")[1];
var week_id = parameters.replace("q=","");
//var week_id = getUrlVars()['q'];
$.getJSON("/json.php",{
section: "onderwijs",
query: week_id
},
function(json){
var mydate = new Date();
weeknumber_next = parseInt(week_id) + 1;
weeknumber_prev = parseInt(week_id) - 1;
week_id = "Week " + week_id;
if (json.onderwijs) {
$("#week_list").empty();
$.each(json.onderwijs,function(i,item){
date2check = new Date(item.date);
if (areSameDate(mydate, date2check)){
$("#week_list").append('<li
data-role="list-divider" role="heading"
data-theme="e">'+item.datum+
'</li><li data-theme="e">'+
'<h5
class="no-ellipsis"><strong>'+item.title
+'</strong></h5>'+
'<p>'+item.speaker+'</p>'+
'<p
class="ui-li-aside"><strong>'+item.time+'</strong></p></li>');
week_id = "Deze Week";
} else {
$("#week_list").append('<li
data-role="list-divider"
role="heading">'+item.datum+
'</li><li>'+
'<h5
class="no-ellipses"><strong>'+item.title
+'</strong></h5>'+
'<p>'+item.speaker+'</p>'+
'<p
class="ui-li-aside"><strong>'+item.time+'</strong></p></li>');
}
});
//
// This is the part failing using
pagebeforechange and is working using pageshow
$("#week_prev").attr("href", '/week.html?q='+
weeknumber_prev);
$("#week_next").attr("href", '/week.html?q='+
weeknumber_next);
$("#text_week").text(week_id);
} else {
$("#week_list").empty();
$("#week_list").append('<li
data-role="list-divider"
role="heading">'+week_id+' 2013'+
'</li><li>'+
'<h5><strong>Nog geen
programma
bekend</strong></h5>'+
'<p>Dit wordt meestal ca 2
weken voor het begin van
de maand
gepubliceerd</p></li>');
$("#week_prev").attr("data-rel", "back");
$("#week_next").remove();
$("#text_week").text(week_id);
}
$("#week_list").listview('refresh');
});
});
HTML
<html>
<head>
</head>
<body>
<!-- Begin Page -->
<div data-role="page" id="onderwijs_week" data-theme="c">
<div data-role="header" data-id="navbar" data-position="fixed"
data-theme="f">
<a href="#main_panel" data-icon="bars" data-iconpos="notext"
class="ui-btn-left" data-transition="slide">Panel</a>
<h1>Onderwijs</h1>
<a href="/colofon.html" data-icon="info" data-iconpos="notext"
class="ui-btn-right" data-transition="fade">Colofon</a>
</div>
<div data-role="content">
<ul data-role="listview" id="week_list" data-dividertheme="c"></ul>
</div>
<div data-role="footer" data-position="fixed" data-id="footer"
data-theme="c" id="week_footer">
<a id="week_prev" href="" data-role="button" data-icon="arrow-l"
class="ui-btn-left" data-iconpos="notext" data-transition="slide"
data-direction="reverse">Vorige</a><h1 id="text_week"></h1><a
id="week_next" href="" data-role="button" data-icon="arrow-r"
class="ui-btn-right" data-iconpos="notext"
data-transition="slide">Volgende</a>
</div>
<div data-role="panel" id="main_panel" data-position="left"
data-display="reveal">
<ul data-role="listview" data-divider-theme="a">
<li data-role="list-divider" role="heading">Hoofdmenu</li>
<li><a href="/home.html" data-transition="slide">Home</a></li>
<li><a href="/content/mp/" data-transition="slide">Medische
protocollen</a></li>
<li><a href="#main_panel">Onderwijs</a></li>
<li><a href="/onderzoek.html">Onderzoek</a></li>
</ul>
</div>
</div>
</body>
</html>
Excel Sorting "mixed data"
Excel Sorting "mixed data"
I have 3 columns of data that need sorting into a specific order. The
column to sort on are alpha numberics but contain letters and numbers. The
best I can do using the standard Excel sort function on the ribbon bar is:
Ideally the output should be:
AS you can see the Excel sort fucntion isnt doing the job I want it to!
Any ideas?
I have 3 columns of data that need sorting into a specific order. The
column to sort on are alpha numberics but contain letters and numbers. The
best I can do using the standard Excel sort function on the ribbon bar is:
Ideally the output should be:
AS you can see the Excel sort fucntion isnt doing the job I want it to!
Any ideas?
How to run source on terminal start up?
How to run source on terminal start up?
I have alias ready on .bash_aliases
Problem I'm having right now is that I need to run source ~/. first before
I can execute the alias command.
My question would be how do I run the source ~/. when user opens terminal.
I have alias ready on .bash_aliases
Problem I'm having right now is that I need to run source ~/. first before
I can execute the alias command.
My question would be how do I run the source ~/. when user opens terminal.
Monday, 19 August 2013
All functions in class
All functions in class
I am thinking about create one or many classes that house a collection of
functions. I know I can add easy scripts to include all function files
individually but I think it would be better to just create class's that
match the group of functions and then house them there. Then I could use
spl_autoload_register to load that group when needed (lazy load). This
should limit the amount of overall functions I include maybe?
Example Code:
class uberFunc {
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) &&
recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
}
Then call something like `uberfunc::recursive_array_search($needle,$haystack)
I am thinking about create one or many classes that house a collection of
functions. I know I can add easy scripts to include all function files
individually but I think it would be better to just create class's that
match the group of functions and then house them there. Then I could use
spl_autoload_register to load that group when needed (lazy load). This
should limit the amount of overall functions I include maybe?
Example Code:
class uberFunc {
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) &&
recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
}
Then call something like `uberfunc::recursive_array_search($needle,$haystack)
base_url doesn't work in external js and css file
base_url doesn't work in external js and css file
I was trying to call "base_url()" inside of an external .js file. my
'test.js' file path is "js/test.js". my test.js code was:
function download(s){
var w=window.open('<?php base_url();
?>home/download?f='+s+'.ogg','Download','height=100,width=100');
}
and I linked that file(my js file is working fine when trying simple
javascript codes) :
<script src="<?php echo base_url(); ?>js/test.js"
type="text/javascript"></script>
but that always said that the access was denied and asked for server
permission. I tried 'site_url()' too, even I tried just an echo"hello" in
'download' function but those didn't work. but when I add that code inside
of header.php view file like:
<script type="text/javascript">
function download(s){
var w=window.open('<?php base_url();
?>home/download?f='+s+'.ogg','Download','height=100,width=100');
}
</script>
then that worked. and in case of external css when I write
background:url('<?php base_url(); ?>images/side.png');
that doesn't work. but if I write
background:url('../images/side.png');
then that works.
so how can I call "base_url()" inside of external .js file and .css file ?
-thanks.
I was trying to call "base_url()" inside of an external .js file. my
'test.js' file path is "js/test.js". my test.js code was:
function download(s){
var w=window.open('<?php base_url();
?>home/download?f='+s+'.ogg','Download','height=100,width=100');
}
and I linked that file(my js file is working fine when trying simple
javascript codes) :
<script src="<?php echo base_url(); ?>js/test.js"
type="text/javascript"></script>
but that always said that the access was denied and asked for server
permission. I tried 'site_url()' too, even I tried just an echo"hello" in
'download' function but those didn't work. but when I add that code inside
of header.php view file like:
<script type="text/javascript">
function download(s){
var w=window.open('<?php base_url();
?>home/download?f='+s+'.ogg','Download','height=100,width=100');
}
</script>
then that worked. and in case of external css when I write
background:url('<?php base_url(); ?>images/side.png');
that doesn't work. but if I write
background:url('../images/side.png');
then that works.
so how can I call "base_url()" inside of external .js file and .css file ?
-thanks.
Recoding over multiple data frames in R
Recoding over multiple data frames in R
I'm a bit stuck on what I suspect is an easy enough problem. I have
multiple different data sets that I have loaded into R, all of which have
different numbers of observations, but all of which have two variables
named "A1," "A2," and "A3". I want to create a new variable in each of the
three data frames that contains the value held in "A1" if A3 contains a
value greater than zero, and the value held in "A2" if A3 contains a value
less than zero. Seems simple enough, right?
My attempt at this code uses this faux-data:
set.seed(1)
A1=seq(1,100,length=100)
A2=seq(-100,-1,length=100)
A3=runif(100,-1,1)
df1=cbind(A1,A2,A3)
A3=runif(100,-1,1)
df2=cbind(A1,A2,A3)
I'm about a thousand percent sure that R has some functionality for
creating the same named variable in multiple data frames, but I have tried
doing this with lapply:
mylist=list(df1,df2)
lapply(mylist,function(x){
x$newVar=x$A1
x$newVar[x$A3>0]=x$A2
})
With for loops:
for(df in mylist){
df$newVar=df$A1
df$newVar[df$A3>0]=df$A2
}
But I always get some variation of the error:
Error in x$A1 : $ operator is invalid for atomic vectors
Any help would be appreciated.
Thank you.
I'm a bit stuck on what I suspect is an easy enough problem. I have
multiple different data sets that I have loaded into R, all of which have
different numbers of observations, but all of which have two variables
named "A1," "A2," and "A3". I want to create a new variable in each of the
three data frames that contains the value held in "A1" if A3 contains a
value greater than zero, and the value held in "A2" if A3 contains a value
less than zero. Seems simple enough, right?
My attempt at this code uses this faux-data:
set.seed(1)
A1=seq(1,100,length=100)
A2=seq(-100,-1,length=100)
A3=runif(100,-1,1)
df1=cbind(A1,A2,A3)
A3=runif(100,-1,1)
df2=cbind(A1,A2,A3)
I'm about a thousand percent sure that R has some functionality for
creating the same named variable in multiple data frames, but I have tried
doing this with lapply:
mylist=list(df1,df2)
lapply(mylist,function(x){
x$newVar=x$A1
x$newVar[x$A3>0]=x$A2
})
With for loops:
for(df in mylist){
df$newVar=df$A1
df$newVar[df$A3>0]=df$A2
}
But I always get some variation of the error:
Error in x$A1 : $ operator is invalid for atomic vectors
Any help would be appreciated.
Thank you.
Can´t use cue file in K3b
Can´t use cue file in K3b
can someone help me with problem to add cue file in K3b(Kubuntu 13.04). I
want to split flac tracks with cue file(the flac is one file),but when i
drag or dubble click the cue file in new audio project then i got the
message:problem to add files,sorry in the end.cuetools didn´t help.Thx if
any can help!
can someone help me with problem to add cue file in K3b(Kubuntu 13.04). I
want to split flac tracks with cue file(the flac is one file),but when i
drag or dubble click the cue file in new audio project then i got the
message:problem to add files,sorry in the end.cuetools didn´t help.Thx if
any can help!
upload video clips display video thumb images not working? php
upload video clips display video thumb images not working? php
I have created an upload_video.php page and having issues with it. Hoping
that some PHP genius irate: can help me out a little for which I would be
ever so grateful.
Change my video page does not display video thumb images. Linked to
include/generatevideothumb.php
In my upload_video.php page I have defined thumb variables as follows
// Thumb size
$th_max_height1 = 150;
$th_max_width1 = 250;
$th_max_width = 55;
$th_max_height = 55;
$thumb_dir="upload/video/thumbs/";
$thumb_dir1="upload/video/thumbs1/";
// Thumb
$thumb_video_name=$video_name;
generatevideothumb($dir,$th_max_width,
$th_max_height,$thumb_dir,$thumb_video_name);
generatevideothumb($dir,$th_max_width1,
$th_max_height1,$thumb_dir1,$thumb_video_name);
The issue is with creating video thumb images. Error is: Warning:
imagecreate() [function.imagecreate]: Invalid image dimensions in
html\include\generatevideothumb.php on line 25
Complete code from generatevideothumb.php below
<?php
function generatevideothumb($im_file,$th_max_width,
$th_max_height,$thumb_dir,$thumb_video_name)
{
@chmod($im_file,0777);
$image_attribs = getimagesize($im_file);
if($image_attribs[0]>$th_max_width)
{
$ratio = $th_max_width/$image_attribs[0];
$th_width = $image_attribs[0] * $ratio;
$th_height = $image_attribs[1] * $ratio;
}
elseif($image_attribs[1]>$th_max_height)
{
$ratio = $th_max_height/$image_attribs[1];
$th_width = $image_attribs[0] * $ratio;
$th_height = $image_attribs[1] * $ratio;
}
else
{
$th_width = $image_attribs[0];
$th_height = $image_attribs[1];
}
**//This code below is where I get that error saying invalid image dimensions
$im_new = imagecreate($th_width,$th_height); //returns an image identifier
representing a black image of size x_size by y_size.
$th_file_name = $thumb_dir.$thumb_video_name;
@chmod($th_file_name,0777);**
if($image_attribs[2]==2)
{
$im_old = imageCreateFromJpeg($im_file);
imagecopyresized($im_new,$im_old,0,0,0,0,$th_width,$th_height,
$image_attribs[0], $image_attribs[1]);
imagejpeg($im_new,$th_file_name,100);
}
elseif($image_attribs[2]==1)
{
$im_old = imagecreatefromgif($im_file);
imageCopyResampled($im_new,$im_old,0,0,0,0,$th_width,$th_height,
$image_attribs[0], $image_attribs[1]);
imagegif($im_new,$th_file_name,100);
}
}
?>
I have created an upload_video.php page and having issues with it. Hoping
that some PHP genius irate: can help me out a little for which I would be
ever so grateful.
Change my video page does not display video thumb images. Linked to
include/generatevideothumb.php
In my upload_video.php page I have defined thumb variables as follows
// Thumb size
$th_max_height1 = 150;
$th_max_width1 = 250;
$th_max_width = 55;
$th_max_height = 55;
$thumb_dir="upload/video/thumbs/";
$thumb_dir1="upload/video/thumbs1/";
// Thumb
$thumb_video_name=$video_name;
generatevideothumb($dir,$th_max_width,
$th_max_height,$thumb_dir,$thumb_video_name);
generatevideothumb($dir,$th_max_width1,
$th_max_height1,$thumb_dir1,$thumb_video_name);
The issue is with creating video thumb images. Error is: Warning:
imagecreate() [function.imagecreate]: Invalid image dimensions in
html\include\generatevideothumb.php on line 25
Complete code from generatevideothumb.php below
<?php
function generatevideothumb($im_file,$th_max_width,
$th_max_height,$thumb_dir,$thumb_video_name)
{
@chmod($im_file,0777);
$image_attribs = getimagesize($im_file);
if($image_attribs[0]>$th_max_width)
{
$ratio = $th_max_width/$image_attribs[0];
$th_width = $image_attribs[0] * $ratio;
$th_height = $image_attribs[1] * $ratio;
}
elseif($image_attribs[1]>$th_max_height)
{
$ratio = $th_max_height/$image_attribs[1];
$th_width = $image_attribs[0] * $ratio;
$th_height = $image_attribs[1] * $ratio;
}
else
{
$th_width = $image_attribs[0];
$th_height = $image_attribs[1];
}
**//This code below is where I get that error saying invalid image dimensions
$im_new = imagecreate($th_width,$th_height); //returns an image identifier
representing a black image of size x_size by y_size.
$th_file_name = $thumb_dir.$thumb_video_name;
@chmod($th_file_name,0777);**
if($image_attribs[2]==2)
{
$im_old = imageCreateFromJpeg($im_file);
imagecopyresized($im_new,$im_old,0,0,0,0,$th_width,$th_height,
$image_attribs[0], $image_attribs[1]);
imagejpeg($im_new,$th_file_name,100);
}
elseif($image_attribs[2]==1)
{
$im_old = imagecreatefromgif($im_file);
imageCopyResampled($im_new,$im_old,0,0,0,0,$th_width,$th_height,
$image_attribs[0], $image_attribs[1]);
imagegif($im_new,$th_file_name,100);
}
}
?>
Subscribe to:
Comments (Atom)