text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Error in the flash builder 4.5 when changing visible value in app-xml file I am using flash builder 4.5 to create an app. when I changer the initial window - visible value in app- xml, I am not able to run the app. I get the following error
"Process terminated unexpectedly.
invalid application descriptor: Illegal value "true
false" for application/initialWindow/visible.
Launch command details: "C:\Program Files\Adobe\Adobe Flash Builder 4.5\sdks\4.5.1\bin\adl.exe" -runtime "C:\Program Files\Adobe\Adobe Flash Builder 4.5\sdks\4.5.1\runtimes\air\win" "C:\Documents and Settings\preevara\Adobe Flash Builder 4.5\Test\bin-debug\Test-app.xml" "C:\Documents and Settings\preevara\Adobe Flash Builder 4.5\Test\bin-debug" "
why is this error thrown
A: Just one year later but I've got the same issue and the solution is : check your xx-app.xml, this message appear when you have more than one tag.
I've found this in my app.xml :
<autoOrients>false</autoOrients>
<fullScreen>false</fullScreen>
<visible>false</visible>
</initialWindow>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Remote acsess to mac pc via iphone using iOS 4.0 Using Ios 4.0
I want to build a project throw which we can remote access other i phone through one.Is it possible in any cases, its totally idea in dreams i don't know whether it is visible or not.
I haven't s
Thanks.
A: There are applications that allow mac/windows desktop sharing from an iphone/ipad (example RemotePC, Splashtop). And there are applications which allow you to access the iPhone screen from a desktop (Veency VNC). Hence accessing iPhone from another also should be possible.
A: You can also check out Game Kit for connecting iOS devices
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Mysql COUNT, GROUP BY and ORDER BY This sounds quite simple but I just can't figure it out.
I have a table orders (id, username, telephone_number).
I want to get number of orders from one user by comparing the last 8 numbers in telephone_number.
I tried using SUBSTR(telephone_number, -8), I've searched and experimented a lot, but still I can't get it to work.
Any suggestions?
A: Untested:
SELECT
COUNT(*) AS cnt,
*
FROM
Orders
GROUP BY
SUBSTR(telephone_number, -8)
ORDER BY
cnt DESC
The idea:
*
*Select COUNT(*) (i.e., number of rows in each GROUPing) and all fields from Orders (*)
*GROUP by the last eight digits of telephone_number1
*Optionally, ORDER by number of rows in GROUPing descending.
1) If you plan to do this type of query often, some kind of index on the last part of the phone number could be desirable. How this could be best implemented depends on the concrete values stored in the field.
A: //Memory intensive.
SELECT COUNT(*) FROM `orders` WHERE REGEXP `telephone_number` = '(.*?)12345678'
OR
//The same, but better and quicker.
SELECT COUNT(*) FROM `orders` WHERE `telephone_number` LIKE '%12345678'
A: You can use the below query to get last 8 characters from a column values.
select right(rtrim(First_Name),8) FROM [ated].[dbo].[Employee]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ajax-style FAQ using a CMS? We plan to create a FAQ website. It will include two types of content:
*
*Lists of questions (FAQs), and
*HTML for each answer.
When user chooses a list and clicks a question, the answer will load in Ajax style.
A very similar approach was described here: Ajax FAQ loading using jquery?
But, before we start developing our own CMS, we would like to make sure that no existing solution is directly applicable. So, my question is: are you aware of any existing CMS for creating Ajax-style FAQs?
We are particularly interested in WordPress plugins (one is listed in my own answer below).
A: Two solutions I found that are likely to be applicable:
*
*WP DS FAQ: FAQ management tool for WordPress. Replaces specific code on a page with a pre-defined list of questions and answers. Requires WordPress version 2.7 or higher, compatible up to 3.2.1. Last ipdated in August 2011.
*Core Design FAQ plugin for Joomla. FAQ is created out of a K2 content module. Requires Joomla version 1.7. Last ipdated in August 2011.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Want to connect PHP5 to MS SQL SERVER 2005 in linux I want to connect mssql server using php code on linux operating system. i want to use mssql_connect() .please help me. my code is
$server='x.x.x.x\SQLEXPRESS';
$link = mssql_connect($server, 'username', 'password');
if (!$link)
{
die("Couldn't connect to SQL Server on $server. Error: " . mssql_get_last_message());
}
else
{
echo "Connected!";
}
it show error "Unable to connect to server: x.x.x.x\SQLEXPRESS"
A: For me, this worked under debian lenny:
apt-get install libsybdb5 freetds-common php5-sybase
/etc/init.d/apache2 restart
I found the solution here: http://docs.moodle.org/20/en/Installing_MSSQL_for_PHP
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Boolean save as tinyint(1) in mysql I made table with some Boolean fields.
CREATE TABLE PM_ADMIN_LIST(
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(250) NOT NULL,
password VARCHAR(250) NOT NULL,
mail VARCHAR(250) NOT NULL,
added_time INT,
super_admin VARCHAR(250) NOT NULL,
last_time INT,
last_ip VARCHAR(250),
see_user_per BOOLEAN DEFAULT FALSE,
change_user_per BOOLEAN DEFAULT FALSE,
see_people_per BOOLEAN DEFAULT FALSE,
change_people_per BOOLEAN DEFAULT FALSE,
add_people_per BOOLEAN DEFAULT FALSE,
remove_people_per BOOLEAN DEFAULT FALSE,
see_album_per BOOLEAN DEFAULT FALSE,
add_album_per BOOLEAN DEFAULT FALSE,
change_album_per BOOLEAN DEFAULT FALSE,
remove_album_per BOOLEAN DEFAULT FALSE,
see_music_per BOOLEAN DEFAULT FALSE,
add_music_per BOOLEAN DEFAULT FALSE,
change_music_per BOOLEAN DEFAULT FALSE,
remove_music_per BOOLEAN DEFAULT FALSE,
admin_per BOOLEAN DEFAULT FALSE,
yahoo_per BOOLEAN DEFAULT FALSE,
status_per BOOLEAN DEFAULT FALSE,
pm_per BOOLEAN DEFAULT FALSE,
ip_blocking_per BOOLEAN DEFAULT FALSE
);
But when I check it in phpmyadmin, BOOLEAN fields are tinyint(1) and they are 0 by default. I can make 1 to be TRUE. But when I use === in my PHP code, they can't be converted. (I should use == in if, for, while and I think it can make some bug in my system.)
So, how should I solve it? How should I get it BOOLEAN by default from mysql?
A: You usually don't get anything but strings in PHP when fetching data from the database. The types are solely used on the database side.
The field is a TINYINT because MySQL doesn't contain a BOOLEAN field at all.
A: There is no 'boolean' type in MySQL. You could just use the == check in PHP.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to Obfuscate my web application project.war using Ant & YGuard? We developed a web application (struts 1.x/Hibernate based) for which I built a
war file using ANT build script. Now, my company wants me to obfuscate the .classes files
before generating a war & distributing it to the client. When I googled, I came
across an example using YGuard library to accomplish this task. The link was pretty useful however, I only had a partial success, as it obfuscated all the java classes, leaving behind the hibernate mapping (*.hbm.xml) files un-obfuscated, which had references to these classes which were already obfuscated.
For example: After obfuscation, references to MenuGlobalBean.class would turn to something like say A.B.H.I.N(where A,B..are package names & N is the class name).
But my MenuGlobal.hbm.xml still refers to this as
<class name="com.mycompany.myproduct.bean.MenuGlobalBean" table="MENU_GLOBAL">
rather than
<class name="A.B.H.I.N" table="MENU_GLOBAL">
Now my question is how do I obfuscate my war file in such a way that
the obfuscated class references reflect in my *.hbm.xml & other config/property files if any.
Below is my complete ANT build script using YGuard library for obfuscation
<!-- Build MyProject.war section -->
<project name="MyProject" default="dist" basedir=".">
<property name="proj-home" value="/home/simba/tomcat-7.0.19/webapps/MyProject" />
<!-- set global properties for this build -->
<property name="src" location="WEB-INF/src"/>
<property name="build" location="build"/>
<property name="lib" location="WEB-INF/lib"/>
<property name="dist" location="dist"/>
<target name="init">
<!-- Create the time stamp -->
<tstamp/>
<!-- Create the build directory structure used by compile -->
<mkdir dir="${build}"/>
</target>
<path id="project-classpath">
<fileset dir="${proj-home}/WEB-INF/lib" includes="*.jar" />
</path>
<target name="copy-non-java-files">
<copy todir="build" includeemptydirs="false">
<fileset dir=".">
<include name="*" />
<include name="css/**/*" />
<include name="help_files/**/*" />
<include name="images/**/*" />
<include name="js/**/*" />
<include name="jsp/**/*" />
<include name="schemas/**/*" />
<include name="Sounds/**/*" />
<include name="VideoImage/**/*" />
<exclude name="WEB-INF/src" />
<exclude name="yguard.jar" />
<exclude name="*.war" />
<exclude name="build.xml" />
</fileset>
<fileset dir=".">
<include name="WEB-INF/classes/**/*" />
<include name="WEB-INF/classes/*.xml" />
<include name="WEB-INF/lib/**/*" />
<include name="WEB-INF/*.xml" />
<include name="WEB-INF/*.properties"/>
<include name="WEB-INF/*.dtd" />
<include name="WEB-INF/*.tld" />
<include name="WEB-INF/*.txt" />
<include name="WEB-INF/*.ico" />
</fileset>
</copy>
</target>
<target name="compile" depends="clean,init,copy-non-java-files" description="compile the source " >
<!-- Compile the java code from ${src} into ${build} -->
<javac srcdir="${src}" destdir="${build}/WEB-INF/classes" classpathref="project-classpath"/>
</target>
<target name="dist" depends="compile"
description="generate the distribution" >
<!-- Create the distribution directory -->
<mkdir dir="${dist}/lib"/>
<!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file -->
<war jarfile="${dist}/lib/MyProject.war" basedir="${build}"/>
</target>
<target name="clean"
description="clean up" >
<!-- Delete the ${build} and ${dist} directory trees -->
<delete dir="${build}"/>
<delete dir="${dist}"/>
</target>
<!-- Using Yguard to obfuscate my .war file -->
<!-- prepare a temporary directory in which the war file is expanded and obfuscated -->
<tempfile property="unwar.dir" destdir="${java.io.tmpdir}" deleteonexit="no"/>
<mkdir dir="${unwar.dir}"/>
<unwar src="${dist}/lib/MyProject.war" dest="${unwar.dir}"/>
<!-- create a jar of webapp classes (required by yguard) for obfuscation -->
<jar destfile="${unwar.dir}/WEB-INF/lib/MyProject.jar" whenempty="fail">
<zipfileset dir="${unwar.dir}/WEB-INF/classes" excludes="*.xml,*.properties"/>
</jar>
<delete dir="${unwar.dir}/WEB-INF/classes/*" excludes="*.xml,*.properties"/>
<!-- create a fileset of internal libraries to be obfuscated -->
<fileset dir="${unwar.dir}/WEB-INF/lib" id="internal.lib.set">
<include name="MyProject.jar"/>
</fileset>
<!-- move the internal libraries to a temporary directory and make a fileset out of them -->
<tempfile property="obfuscation.dir" destDir="${java.io.tmpdir}" deleteonexit="yes"/>
<mkdir dir="${obfuscation.dir}"/>
<move todir="${obfuscation.dir}">
<fileset refid="internal.lib.set"/>
</move>
<!-- create a jar of web.xml (required by yguard) for obfuscation -->
<jar destfile="${obfuscation.dir}/web.xml.jar" whenempty="fail">
<zipfileset dir="${unwar.dir}/WEB-INF" includes="*.xml"/>
</jar>
<!--<delete file="${unwar.dir}/WEB-INF/web.xml"/> -->
<!-- make a fileset of all jars to be obfuscated -->
<fileset dir="${obfuscation.dir}" includes="*.jar" id="in-out.set"/>
<!-- make a fileset of the remaining libraries, these are not obfuscated -->
<path id="external.lib.path">
<fileset dir="${unwar.dir}/WEB-INF/lib" includes="*.jar"/>
</path>
<taskdef name="yguard"
classname="com.yworks.yguard.YGuardTask"
classpath="../ref/yguard.jar"/>
<yguard>
<inoutpairs>
<!-- these filesets are inputs to be obfuscated -->
<fileset refid="in-out.set"/>
</inoutpairs>
<externalclasses refid="external.lib.path"/> <!-- external libs, not obfuscated -->
<rename>
<adjust replaceContent="true">
<include name="web.xml"/> <!-- modified to reference the obfuscated Servlet -->
<include name="struts-config.xml"/>
<include name="*.hbm.xml"/>
</adjust>
<keep>
<!-- classes, packages, methods, and fields which should not obfuscated are specified here -->
</keep>
</rename>
</yguard>
<!-- move our newly obfuscated classes back into the lib area -->
<move todir="${unwar.dir}/WEB-INF/lib">
<fileset dir="${obfuscation.dir}" includes="*_obf.jar"/>
</move>
<!-- unjar the adjusted web.xml -->
<unzip dest="${unwar.dir}/WEB-INF/" src="${unwar.dir}/WEB-INF/lib/web.xml_obf.jar">
<patternset includes="*.xml"/>
</unzip>
<!-- <delete>
<fileset dir="${unwar.dir}/WEB-INF/lib" includes="web.xml*.jar"/>
</delete> -->
<!-- rebuild the war file -->
<war destfile="MyProject_obf.war" basedir="${unwar.dir}"/>
</project>
A: Use the same trick I used to encrypt the references in web.xml -- temporarily put the Hibernate .xml files into a jar. (See the section commented by "create a jar of web.xml (required by yguard) for obfuscation".)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Installing cookbook on RubyMine I am trying to import a folder(open directory) on Ruby Mine but when I do it says "Install missing gems" Everytime I click on it, it installs some and then again gives the same error.
I have Mac OS X 10.7.
Here is the error:
/Users/Vinisa/.rvm/rubies/ree-1.8.7-2011.03/bin/ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/bin/bundle install
Fetching source index for http://rubygems.org/
Using rake (0.9.2)
Using multi_json (1.0.3)
Using activesupport (3.1.0)
Using bcrypt-ruby (3.0.1)
Using builder (3.0.0)
Using i18n (0.6.0)
Using activemodel (3.1.0)
Using erubis (2.7.0)
Using rack (1.3.2)
Using rack-cache (1.0.3)
Using rack-mount (0.8.3)
Using rack-test (0.6.1)
Using hike (1.2.1)
Using tilt (1.3.3)
Using sprockets (2.0.0)
Using actionpack (3.1.0)
Using mime-types (1.16)
Using polyglot (0.3.2)
Using treetop (1.4.10)
Using mail (2.3.0)
Using actionmailer (3.1.0)
Using arel (2.2.1)
Using tzinfo (0.3.29)
Using activerecord (3.1.0)
Using activeresource (3.1.0)
Using ansi (1.3.0)
Using bundler (1.0.18)
Installing nokogiri (1.5.0) with native extensions /Users/Vinisa/.rvm/rubies/ree-1.8.7-2011.03/lib/ruby/site_ruby/1.8/rubygems/installer.rb:551:in `build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)
/Users/Vinisa/.rvm/rubies/ree-1.8.7-2011.03/bin/ruby extconf.rb
checking for libxml/parser.h... yes
checking for libxslt/xslt.h... yes
checking for libexslt/exslt.h... yes
checking for iconv_open() in iconv.h... no
checking for iconv_open() in -liconv... no
-----
libiconv is missing. please visit http://nokogiri.org/tutorials/installing_nokogiri.html for help with installing dependencies.
-----
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.
Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/Users/Vinisa/.rvm/rubies/ree-1.8.7-2011.03/bin/ruby
--with-zlib-dir
--without-zlib-dir
--with-zlib-include
--without-zlib-include=${zlib-dir}/include
--with-zlib-lib
--without-zlib-lib=${zlib-dir}/lib
--with-iconv-dir
--with-iconv-include
--without-iconv-include=${iconv-dir}/include
--with-iconv-lib
--without-iconv-lib=${iconv-dir}/lib
--with-xml2-dir
--without-xml2-dir
--with-xml2-include
--without-xml2-include=${xml2-dir}/include
--with-xml2-lib
--without-xml2-lib=${xml2-dir}/lib
--with-xslt-dir
--without-xslt-dir
--with-xslt-include
--without-xslt-include=${xslt-dir}/include
--with-xslt-lib
--without-xslt-lib=${xslt-dir}/lib
--with-iconvlib
--without-iconvlib
Gem files will remain installed in /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/nokogiri-1.5.0 for inspection.
Results logged to /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/nokogiri-1.5.0/ext/nokogiri/gem_make.out
from /Users/Vinisa/.rvm/rubies/ree-1.8.7-2011.03/lib/ruby/site_ruby/1.8/rubygems/installer.rb:504:in `each'
from /Users/Vinisa/.rvm/rubies/ree-1.8.7-2011.03/lib/ruby/site_ruby/1.8/rubygems/installer.rb:504:in `build_extensions'
from /Users/Vinisa/.rvm/rubies/ree-1.8.7-2011.03/lib/ruby/site_ruby/1.8/rubygems/installer.rb:180:in `install'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/bundler-1.0.18/lib/bundler/source.rb:101:in `install'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/bundler-1.0.18/lib/bundler/rubygems_integration.rb:78:in `preserve_paths'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/bundler-1.0.18/lib/bundler/source.rb:91:in `install'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/bundler-1.0.18/lib/bundler/installer.rb:58:in `run'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/bundler-1.0.18/lib/bundler/rubygems_integration.rb:93:in `with_build_args'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/bundler-1.0.18/lib/bundler/installer.rb:57:in `run'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/bundler-1.0.18/lib/bundler/installer.rb:49:in `run'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/bundler-1.0.18/lib/bundler/installer.rb:8:in `install'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/bundler-1.0.18/lib/bundler/cli.rb:220:in `install'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/bundler-1.0.18/lib/bundler/vendor/thor/task.rb:22:in `send'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/bundler-1.0.18/lib/bundler/vendor/thor/task.rb:22:in `run'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/bundler-1.0.18/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/bundler-1.0.18/lib/bundler/vendor/thor.rb:263:in `dispatch'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/bundler-1.0.18/lib/bundler/vendor/thor/base.rb:386:in `start'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/bundler-1.0.18/bin/bundle:13
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/bin/bundle:19:in `load'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/bin/bundle:19
from -e:1:in `load'
from -e:1
Process finished with exit code 1
Any thoughts on why so?
After installing novigiri, I am getting the following error:
/Users/Vinisa/.rvm/rubies/ree-1.8.7-2011.03/bin/ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /Assorted Mix/OOLS'11/OOLS-Lect/barik-csc517_cookbook3-325ff9f/script/rails server -b 0.0.0.0 -p 3000 -e development
=> Booting WEBrick
=> Rails 3.1.0 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
/Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/activesupport-3.1.0/lib/active_support/dependencies.rb:234:in `load': /Assorted Mix/OOLS'11/OOLS-Lect/barik-csc517_cookbook3-325ff9f/config/initializers/session_store.rb:3: syntax error, unexpected ':', expecting $end (SyntaxError)
...sion_store :cookie_store, key: '_cookbook3_session'
^
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/activesupport-3.1.0/lib/active_support/dependencies.rb:234:in `load'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/activesupport-3.1.0/lib/active_support/dependencies.rb:223:in `load_dependency'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/activesupport-3.1.0/lib/active_support/dependencies.rb:640:in `new_constants_in'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/activesupport-3.1.0/lib/active_support/dependencies.rb:223:in `load_dependency'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/activesupport-3.1.0/lib/active_support/dependencies.rb:234:in `load'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/railties-3.1.0/lib/rails/engine.rb:555
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/railties-3.1.0/lib/rails/engine.rb:554:in `each'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/railties-3.1.0/lib/rails/engine.rb:554
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/railties-3.1.0/lib/rails/initializable.rb:25:in `instance_exec'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/railties-3.1.0/lib/rails/initializable.rb:25:in `run'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/railties-3.1.0/lib/rails/initializable.rb:50:in `run_initializers'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/railties-3.1.0/lib/rails/initializable.rb:49:in `each'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/railties-3.1.0/lib/rails/initializable.rb:49:in `run_initializers'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/railties-3.1.0/lib/rails/application.rb:92:in `initialize!'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/railties-3.1.0/lib/rails/railtie/configurable.rb:30:in `send'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/railties-3.1.0/lib/rails/railtie/configurable.rb:30:in `method_missing'
from /Assorted Mix/OOLS'11/OOLS-Lect/barik-csc517_cookbook3-325ff9f/config/environment.rb:5
from /Assorted Mix/OOLS'11/OOLS-Lect/barik-csc517_cookbook3-325ff9f/config.ru:4:in `require'
from /Assorted Mix/OOLS'11/OOLS-Lect/barik-csc517_cookbook3-325ff9f/config.ru:4
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/rack-1.3.2/lib/rack/builder.rb:51:in `instance_eval'
from /Users/Vinisa/.rvm/gems/ree-1.8.7-2011.03/gems/rack-1.3.2/lib/rack/builder.rb:51:in `initialize'
from /Assorted Mix/OOLS'11/OOLS-Lect/barik-csc517_cookbook3-325ff9f/config.ru:1:in `new'
from /Assorted Mix/OOLS'11/OOLS-Lect/barik-csc517_cookbook3-325ff9f/config.ru:1
Exiting
Process finished with exit code 1
Thanks!
A: Installation of the Nokogiri gem is failing.
Try installing it manually for Mac OS @ Why does installing Nokogiri on Mac OS fail with libiconv is missing?
A: Can you start the project by command line? It could be related with your ruby version.
Check this file and see if yours have the same syntax.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: 401 unauthorized exception while reading data from the document library SharePoint 2010 We developed a WebPart to read the content of the file in the document library in the SiteCollection. I used the following code to read the content.
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultNetworkCredentials;
string documenturl = siteurl+"/" + file.Url.ToString();
content = wc.DownloadData(documenturl);//documenturl is the file path of the document
But, i got the following error 401 unathorized exception
System.Net.WebException: The remote server returned an error:(401) Unauthorized. at System.Net.WebClient.DownloadDataInternal(Uri address,WebRequest& request) at System.Net.WebClient.DownloadData(Uri address)
For your information, i already tried to download document by SPFile openBinary method. But it only works when the document is small. Please refer the below site.
getting ComException while reading the document in SharePoint 2010
Thanks in advance.
A: Probably the local loopback check. (Verify by trying to access your site using the same URL whilst using IE running on your SharePoint server)
Also - any reason why you're using web services to access local content rather than the SharePoint object model (Microsoft.SharePoint.dll)?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make sure that threads spawned by a Windows Service Timer complete executing after stopping the Windows Service? I'm building a Windows Service using System.Timers.Timer. The tasks computed by the Timer's delegate can take from several seconds to several minutes. I would like to make sure that, when the service is stopped, all delegated threads currently running complete before being disposed.
Here is the code, however it does not do what I expect, as currently running threads never complete if the Windows Service is stopped while they are running.
public abstract class AgentServiceBase : ServiceBase
{
private System.ComponentModel.IContainer components = null;
private System.Timers.Timer _Timer;
private string _logPath;
private const int MAXNUMBEROFTHREADS = 10;
protected int interval = 25000;
protected int numberOfAllowedThreads = 2;
public AgentServiceBase()
{
this.InitializeComponent();
this._logPath = (Path.GetDirectoryName(Assembly.GetAssembly(this.GetType()).CodeBase)).Substring(6).Replace("/", @"\");
}
protected override void OnStart(string[] args)
{
if (args.Length > 0)
{
int.TryParse(args[0], out interval);
}
if (args.Length > 1)
{
int.TryParse(args[1], out numberOfAllowedThreads);
if (numberOfAllowedThreads > MAXNUMBEROFTHREADS)
{
numberOfAllowedThreads = MAXNUMBEROFTHREADS;
}
if (numberOfAllowedThreads == 1)
{
numberOfAllowedThreads = 2;
}
}
ThreadPool.SetMaxThreads(numberOfAllowedThreads, numberOfAllowedThreads);
this._Timer = new System.Timers.Timer();
this._Timer.Elapsed += new ElapsedEventHandler(PollWrapper);
this._Timer.Interval = this.interval;
this._Timer.Enabled = true;
}
protected override void OnStop()
{
this._Timer.Enabled = false;
Process currentProcess = Process.GetCurrentProcess();
foreach (Thread t in currentProcess.Threads)
{
t.Join();
}
}
/// <summary>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Agent Service - Johnhenry";
}
private void PollWrapper(object sender, ElapsedEventArgs e)
{
try
{
this.Poll(sender, e);
}
catch (Exception exception)
{
string message = this.GetType().FullName + " - Windows Service Exception\n";
message += exception.GetNestedExceptionInSingleStringOutput();
FileHelper.Log(message, this._logPath, "exception", FileHelper.LogFileNameChangeFrequency.DAYLY);
}
}
protected abstract void Poll(object sender, ElapsedEventArgs e);
}
Many thanks,
Giuseppe
UPDATE:
After few different attempts with counting the current process's own threads I eventually settled with a simpler solution which is using a counter of the threads the timer had initiated and are still running. Based on that I call the Sleep on the main thread and issue a RequestAdditionalTime until all threads have ended.
Following the revised 2 methods:
protected override void OnStop()
{
this._Timer.Enabled = false;
while (numberOfRunningThreads > 0)
{
this.RequestAdditionalTime(1000);
Thread.Sleep(1000);
}
}
private void PollWrapper(object sender, ElapsedEventArgs e)
{
numberOfRunningThreads++;
try
{
this.Poll(sender, e);
}
catch (Exception exception)
{
string message = this.GetType().FullName + " - Windows Service Exception\n";
message += exception.GetNestedExceptionInSingleStringOutput();
FileHelper.Log(message, this._logPath, "exception", FileHelper.LogFileNameChangeFrequency.DAYLY);
}
finally
{
numberOfRunningThreads--;
}
}
A: You can achieve that by calling RequestAdditionalTime as long as your threads haven't finished the work yet in your implementation of OnStop inside the loop (before and/or after the call to Join()).
BUT BEWARE that Windows can get impatient and decide to kill your Windows Service - for example during shutdown...
For more information see the MSDN reference at http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: DataGridCell content template selector Silverlight I have a DataGrid with the dynamic data (collection of custom DataRows), which i get from the server. DataRow has an indexer and a property Data which returns whole data row for the binding (you'll see below)
I create each column of a DataGrid in such a way:
DataGridTextColumn column = new DataGridTextColumn();
Binding binding = new Binding("Data[" + i.ToString() + "]");
binding.Mode = BindingMode.TwoWay;
binding.Converter = _dataContextSelector;
binding.ConverterParameter = dataColumn;
column.Binding = binding;
What I need to do: I need to display the content of the DataGridCells in different ways according to the data, which converter returns.
I wrote the template selector (which inherits ContentControl) and put it in ContentTemplate property of DataGridCell in such a way:
<Style TargetType="sdk:DataGridCell">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<view:DataGridCellTemplateSelector Content="{Binding}" />
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
In this case I have the whole DataRow as the content of my selector (can't undestand why, because the column was bound on the one item of the row) and my converter isn't called. The whole datarow is the default DataContext, so i guess, my code-behind binding is simply ignoring in this case.
So i tried to put my template selector to the ControlTemplate of the DataGridCell:
<Style TargetType="sdk:DataGridCell">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="sdk:DataGridCell">
<view:DataGridCellTemplateSelector Content="{TemplateBinding Content}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
But in this case i have TextBlock with empty text as the content of my selector (SHOCKED). Converter is called after content was changed.
How can I create the template selector, which will select the template according to the data of my binding (after converter is called) ?
A: *
*Consider using implicit data templates instead of a custom template selector.
*Create a custom DataGridBoundColumn and override GenerateElement.
*In GenerateElement, return a ContentControl. You have to bind the Content property of that ContentControl using the Binding property of your custom column.
*
*If using implicit data templates, you're done at this point.
*If using your own DataGridCellTemplateSelector, well, just use it instead of the plain ContentControl mentioned above.
Implicit data templates look like that (note, that they are resources without an x:Key):
<UserControl.Resources>
<DataTemplate DataType="ViewModel:Contact">
<StackPanel>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding City}"/>
</StackPanel>
</DataTemplate>
</UserControl.Resources>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Git Setup - New User on old PC I've taken ownership of a PC that was a former employee. Git was installed and the .config file etc is therefore under the former employees directory under ./Users.
Do I need to do a brand new install of MySysGit or can I run some commands to get git configured to look at my directory under ./Users/MyAccountName?
A: You can just copy the former's employee .gitconfig to your Users' directory, and edit it with a text editor to give it your idenntity (name and email)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: 0 byte file getting created in ftp location Following is my java function to write a csv file in ftp location.The file gets created to ftp location but the file size is 0 bytes and file is empty.Kindly help as I am stuck
public int WriteFileToFtp(String FileName, String FileData) {
//get these details for the version??
//??
FTPClient ftp= new FTPClient();
try {
InputStream is = new ByteArrayInputStream(FileData.getBytes("ISO-8859-1"));
ftp.connect(ftpIP);
boolean isConnection = ftp.login(userName,password);
if(!isConnection){
logger.error("Connection failed");
return -1;
}
ftp.enterLocalActiveMode();
ftp.setFileType(FTP.BINARY_FILE_TYPE);//setting fileType
//?? go to directory using the circle code
if(ftpDirectoryToBeUpdate!=null && ftpDirectoryToBeUpdate.trim().length()>0)
{
logger.error("Changing directory for write="+ftpDirectoryToBeUpdate+" lcd="+ftp.printWorkingDirectory());
ftp.changeWorkingDirectory(ftpDirectoryToBeUpdate);
logger.error("Changed directory for write="+ftpDirectoryToBeUpdate+" lcd="+ftp.printWorkingDirectory());
}else
{
logger.error("Changed directory for write failed lcd="+ftp.printWorkingDirectory());
logger.error("DirectoryToReadFrom="+ftpDirectoryToBeUpdate);
}
ftp.storeFile(FileName,is) ;
logger.error(ftp.getReplyString());
is.close();
if(ftp.isConnected())
ftp.disconnect();
} catch (SocketException e) {
//logger.error(LoggerKeyWord.ERROR_ALERT + " FTP WRITE ERROR");
logger.error(e,e);
e.printStackTrace();
return -1;
} catch (IOException e) {
// logger.error(LoggerKeyWord.ERROR_ALERT + " FTP WRITE ERROR");
logger.error(e,e);
e.printStackTrace();
return -1;
}
try {
if(ftp.isConnected())
ftp.disconnect();
} catch (IOException e) {
logger.error (e,e);
e.printStackTrace();
return -1;
}
return 1;
}
A: have you tried closing input stream before saving the file?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Install and Configure apache Solr - Indexing failed on following nodes, missing required field entity type I am working on Pressflow Drupal 6, Debian, Apache2, PHP 5.3.3 environment. Trying to set up Solr on it. Followed step 9. Install and Configure apache Solr http://groups.drupal.org/pantheon/mercurywiki
*
*Install Tomcat6
*Install Apache Solr
*drush dl apachesolr
*move Drupal specific config and schema files to solr/conf/
Now when I run cron
50% of the site has been indexed. There are 50 items left to index.
After that it fires an Apache Solr error (in 'Reports log entry')
Indexing failed on one of the following nodes: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
"400" Status: Document_tq3l64node1_missing_required_field_entity_type: Document_tq3l64node1_missing_required_field_entity_type
Error 400
HTTP ERROR: 400Document [tq3l64/node/1] missing required field: entity_type
RequestURI=/solr/iexplore/updatePowered by Jetty://
Can you please help, why i am getting this issue and what is fix ?
A: From the error it seems entity_type is a required field defined in the schema for the core.
The data fed to solr does not seem to have entity_type field and hence the documents fail to be indexed.
A: Thanks all, I got it working now. the only issue was schema.xml.
There is another Drupal 7 site running on same server which, so i need to change schema.xml. D7 and D6 schema files are different.
Now its working ..... thanks very much
A: you'd better to configure apachesolr in multisiting way, it's easy. so each site will be using different schemes.
http://drupalconnect.com/blog/steve/configuring-apache-solr-multi-core-drupal-and-tomcat-ubuntu-910
I recommend you to do it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Email Program in Delphi I am building an Email send application in delphi 7. Default email client on my machine is configured with lotus notes.
I have tried shellExecute command on 'send' button click in application. But in this ShellExecute pop up the lotus notes to user with subject, body etc and then user needs to click on Send button in lotus notes.
I want when user click on Send button of my application then automatically email should be sent using lotus notes. Can we do this using ShellExecute? I tried using Indy components also but I didn't get the SMTP details. How can I find out SMTP server details?
thanks for help
A: For sending e-mails using Lotus Notes (even if it looks for me like an overkill a bit) I found this post and tried to translate it to Delphi code but I can't test it anywhere, so I can't tell you if this works or not. I have left the original comments in there.
uses
ComObj, StrUtils;
// Public Sub SendNotesMail(Subject as string, attachment as string,
// recipient as string, bodytext as string,saveit as Boolean)
// This public sub will send a mail and attachment if neccessary to the
// recipient including the body text.
// Requires that notes client is installed on the system.
procedure SendNotesMail(const Subject: string; const Attachment: string;
const Recipient: string; const BodyText: string; const SaveIt: Boolean);
var
Maildb: OleVariant; // The mail database
UserName: string; // The current users notes name
MailDbName: string; // The current users notes mail database name
MailDoc: OleVariant; // The mail document itself
AttachME: OleVariant; // The attachment richtextfile object
Session: OleVariant; // The notes session
EmbedObj: OleVariant; // The embedded object (Attachment)
begin
Session := CreateOleObject('Notes.NotesSession');
// Next line only works with 5.x and above. Replace password with your password
Session.Initialize('password');
// Get the sessions username and then calculate the mail file name
// You may or may not need this as for MailDBname with some systems you
// can pass an empty string or using above password you can use other mailboxes.
UserName := Session.UserName;
MailDbName := LeftStr(UserName, 1) + RightStr(UserName, (Length(UserName) - Pos(UserName, ' '))) + '.nsf';
// Open the mail database in notes
Maildb := Session.GETDATABASE('', MailDbName);
if not Maildb.ISOPEN then
Maildb.OPENMAIL;
// Set up the new mail document
MailDoc := Maildb.CREATEDOCUMENT;
MailDoc.Form := 'Memo';
MailDoc.sendto := Recipient;
MailDoc.Subject := Subject;
MailDoc.Body := BodyText;
MailDoc.SAVEMESSAGEONSEND := SaveIt;
// Set up the embedded object and attachment and attach it
if Attachment <> '' Then
begin
AttachME := MailDoc.CREATERICHTEXTITEM('Attachment');
EmbedObj := AttachME.EMBEDOBJECT(1454, '', Attachment, 'Attachment');
MailDoc.CREATERICHTEXTITEM('Attachment');
end;
// Send the document
MailDoc.PostedDate := Now; // Gets the mail to appear in the sent items folder
MailDoc.SEND(0, Recipient);
end;
A: If you use Indy, the email won't be sent through Lotus Notes, instead it will be sent directly from your application to the specified mail server.
If you have a mail server or have an email account, you can use IdSmtp component from Indy, and configure it with your mail server host name, port name, and authentication method. If you do not know how to obtain such info, you can contact your mail service company, and ask them about their configuration.
Another way to send an email is by creating a SMTP mail server yourself, using IdSmtpServer component. This way your app does not need an external mail server.
Take note that in both cases the email is sent via an email address that you specified, and the default email client installed on the target machine is not used.
A: The Jedi Code Library (JCL) includes a MAPI helper class "TJclEmail" (in unit source\windows\JclMapi) with easy to use commands, sending mails and faxes with and without showing the compose mail window.
Example:
function JclSimpleBringUpSendMailDialog(const Subject, Body: AnsiString;
const Attachment: TFileName = ''; ParentWND: THandle = 0;
const ProfileName: AnsiString = ''; const Password: AnsiString = ''): Boolean;
and
function JclSimpleSendMail(const Recipient, Name, Subject, Body: AnsiString;
const Attachment: TFileName = ''; ShowDialog: Boolean = True; ParentWND: THandle = 0;
const ProfileName: AnsiString = ''; const Password: AnsiString = ''): Boolean;
are convenience methods, using the classes internally.
If Lotus notes is registered as the MAPI mail handler, it should work without SMTP /Indy.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: jQuery ui modal window causes gray line I wanted to change the color of the window surrounding the modal alert-popup in jQuery UI.
So I changed it; .ui-widget-overlay { background: white
But for some weird reason, a gray line with the previously existing color, shows up in the middle of the screen. I haven't been able to select the element with the Chrome debugger, nor have I been able to find it's class in the jQuery-ui css-file. See image.
Anyone know what could be causing this?
A: Fixed this. For some reason, my jquery-ui.css file had two .ui-widget-overlay classes defined. Added the background-color as in Williams example to the other class and it worked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Display Image at project startup - program.cs? I have a small Windows Forms project and now Iam looking to display an image at project startup, I mean Program.cs
Is it possible?
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Image MyPrgImage = Image.FromFile("C:\\Temp\\Images\\For_Network.gif");
??????
Application.Run(new Form1());
}
A: Sure... Add new WindowsForm to your project, call it SplashImageForm. Add PictureBox control to it, and add the image you want in it. Resize the form, set these SplashImageForm properties:
FormBorderStyle - None
ShowInTaskBar - false
StartPosition - CenterScreen
Then you want to show that form before Form1 and close it after the timeout has expired... Like so for example:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SplashImageForm f = new SplashImageForm();
f.Shown += new EventHandler((o,e)=>{
System.Threading.Thread t = new System.Threading.Thread(() =>
{
System.Threading.Thread.Sleep(2000);
f.Invoke(new Action(() => { f.Close(); }));
});
t.IsBackground = true;
t.Start();
});
Application.Run(f);
Application.Run(new Form1());
}
EDIT
Now, there is new thread which blocks on System.Threading.Thread.Sleep(2000) for 2 seconds, and the main thread is allowed to block on Application.Run(f) as it is supposed to, until the SplashImageForm isn't closed. So the image gets loaded by the main thread and the GUI is responsive.
When the timeout ends, Invoke() method is called so the main thread which is the owner of the form closes it. If this wasn't here, Cross threaded exception would be thrown.
Now the image is shown for 2 secs, and after it Form1 is shown.
A: You mean a splash screen, right?
Consider adding a reference to Microsoft.VisualBasic (if not already done) and then set the WindowsFormsApplicationBase.SplashScreen property.
A few more points:
*
*Windows Forms doesn't have support for a simple and straight splash screen.
Even the solution above will take a few seconds until the .net framework is loaded to show the splash screen.
*See this question here for further examples and important remarks.
*See this CodeProject.com sample for a custom solution
A: You would need a simple form, perhaps with a PictureBox, to loadd and display the image. Then remove it once your main form is loaded.
A: Simply add a windows form(let the name of form be imgsplash) & from option set following:-
FormBorderStyle - None
ShowInTaskBar - false
StartPosition - CenterScreen
in this form set background image[image which you want to show at startup of application]
--now in program.cs add folloing steps:-
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
imgsplash f = new imgsplash();
f.Show();
System.Threading.Thread.Sleep(2000);
f.Close();
Application.Run(new Form1());
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Android "Failed to find style 'mapViewStyle' in current Theme" error I'm writing a simple android application that should display google maps. The application displays the "Activity is not responding" error upon startup. In the mapdisplay.xml file where I define the map view activity, I get a "Failed to find style 'mapViewStyle' in current Theme" error message, so I think it's the reason behind the crash.
I have the Internet permission set and the uses-library tag placed correctly in the manifest.
Here is the code listing
public class OnthisdayActivity extends MapActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mapdisplay);
}
@Override
protected boolean isRouteDisplayed()
{
return false;
}
}
And the xml file mapdisplay.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<com.google.android.maps.MapView
android:enabled="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/mapView"
android:clickable="true"
android:apiKey="xxxxxx"
/>
</RelativeLayout>
And the android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="onthisday.main"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"/>
<application android:icon="@drawable/icon" android:label="@string/app_name">
<uses-library android:required="true" android:name="com.google.android.maps"/>
<activity android:name=".OnthisdayActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Problem with FaxComExLib I can successfully fax messages using FAXCOMLib. Now I try to use FAXCOMEXLib, but I have problems with that:/
This is the code (from MSDN VB example):
try
{
FaxServer objFaxServer = new FaxServer();
FaxDocument objFaxDocument = new FaxDocument();
object JobID;
objFaxServer.Connect(Environment.MachineName);
objFaxDocument.Body = "test.bmp";
objFaxDocument.DocumentName = "Test name";
objFaxDocument.Recipients.Add("xxxxxxx", "Name");
objFaxDocument.AttachFaxToReceipt = true;
objFaxDocument.CoverPageType = FAXCOMEXLib.FAX_COVERPAGE_TYPE_ENUM.fcptSERVER;
objFaxDocument.CoverPage = "generic";
objFaxDocument.Note = "Here is the info you requested";
objFaxDocument.ReceiptAddress = "someone@example.com";
objFaxDocument.ReceiptType = FAXCOMEXLib.FAX_RECEIPT_TYPE_ENUM.frtMAIL;
objFaxDocument.ScheduleType = FAXCOMEXLib.FAX_SCHEDULE_TYPE_ENUM.fstNOW;
objFaxDocument.Subject = "Today's fax";
objFaxDocument.Sender.Title = "Mr.";
objFaxDocument.Sender.Name = "Bob";
objFaxDocument.Sender.City = "Cleveland Heights";
objFaxDocument.Sender.State = "Ohio";
objFaxDocument.Sender.Company = "Microsoft";
objFaxDocument.Sender.Country = "USA";
objFaxDocument.Sender.Email = "someone@microsoft.com";
objFaxDocument.Sender.FaxNumber = "12165555554";
objFaxDocument.Sender.HomePhone = "12165555555";
objFaxDocument.Sender.OfficeLocation = "Downtown";
objFaxDocument.Sender.OfficePhone = "12165555553";
objFaxDocument.Sender.StreetAddress = "123 Main Street";
objFaxDocument.Sender.TSID = "Office fax machine";
objFaxDocument.Sender.ZipCode = "44118";
objFaxDocument.Sender.BillingCode = "23A54";
objFaxDocument.Sender.Department = "Accts Payable";
JobID = objFaxDocument.ConnectedSubmit(objFaxServer);
MessageBox.Show(("The Job ID is :" + JobID.ToString()),"Finished");
objFaxServer.Disconnect();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString() + ". " + ex.ToString(), "Exception");
}
The exception is thrown on that line: FaxServer objFaxServer = new FaxServer();
Unable to cast COM object of type 'System.__ComObject' to interface type 'FAXCOMEXLib.FaxServer'.
When I do: FaxServer objFaxServer = new FaxServerClass();
I can't even compile that line.. It shows: Interop type 'FAXCOMEXLib.FaxServerClass' cannot be embedded. Use the applicable interface instead.
So, I was stopped on that line :/
BTW. Basically, I want to implement a class that will send faxes and watch the status of sent messages. I would be very very pleased, if somebody send a whole ready to use class.
Please help me,
A:
When I do: FaxServer objFaxServer = new FaxServerClass(); I can't even
compile that line
Weird thing about COM objects is that interfaces sometimes act as though they have constructors:
FaxServer objFaxServer = new FaxServer();
That is the correct line. I have it on mine and it works. There may be something wrong with the interop.
A: Do the following steps to overcome this issue:
*
*Select FAXCOMEXLib from refrences in Solution Explorer.
*Open Properties
*Set "Enable Interop Type" to False.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Would Lync Server SDK or UCMA enable me to implement additional authentication for conference? I would like to create additional authentication for the conference call.
Scenario would look something like this:
*
*Client calls the conference
*In chat window he is asked for some secret that is authenticating him using 3rd party server
*Client after successful authentication is allowed to join the conference.
Could someone point me in the right direction? Documentation maybe?
A: You could absolutly do this using the UCMA SDK.
If the UCMA application creates the conferences, and is the only conference leader, and the settings of the conference are such that all particiants must join the lobby first and be expressly admitted into the conference, then the bot could be notified of users attempting to join the conference (they would go to the lobby, not the actual conference) and could then start a IM conversation with them to validate them. Once the bot is happy it could then invite them to the conference. Of course, you could also add some participants as attendees - which would mean they could join the conference automatically without being challenged.
Have a look at the conference lobby, meeting setup properties, creating scheduled conferences, and the events which are raised once a conference is created.
The following MSDN sample might be of use:
Schedule and Join a Conference (QuickStart)
Hope that helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Canoo and Groovy - how to use storeRegEx We would like to test the following flow using Canoo. The tests are written in Groovy, and not as Ant tasks.
*
*Send a request to a specific URL (we use "invoke")
*Extract specific information from the response (we use "storeRegEx" with property:"ans")
*Print the extracted value (for debug purposes). println "${ans}" - does not work
*Use the extracted value in the next action (e.g. invoke "new/url/id=#{ans}")
We saw some references to using an AntBuilder, it fails as well.
Is there some example for that flow?
Thanks
A: remember that it depends on the ant property type (dynamic or ant) whether you have to use #{ans} or ${ans}
println will not work in webtests. Use the description property of webtest steps instead:
group(description:"#{ans}") {
...
}
this will show you the value of your property in the test result.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to search for pattern in file and display the line on terminal? i have filw with containtent like following:
pid 4565 Process: /my/name/is/4678 +34787[d]sfh888dwe4rtertfsj@##$
pid 33453 Process: /my/name/is/4678 +34787[d]sfh888dfsj@##werwer$
pid 3453345 Process: /my/name/is/4678 +3478[7]dsfhew46534wy6888dfsj@##$
pid 12335 Process: /my/name/is/4678 +3478se[r]tet57dsfh888dfsj@##$
i need line contaning "+34787[d]sfh888dfsj@##werwer$" this pattern and need to get whole that line on terminal or can ne redirected to another file. Any suggestion?
Thanks in advance.
A: Use grep with fixed strings mode (aka fgrep):
grep -F '+34787[d]sfh888dfsj@##werwer$' /path/to/my/file
Run man grep to learn more.
If you need to redirect it to some output file instead of standards output:
grep -F '+34787[d]sfh888dfsj@##werwer$' /path/to/my/file > /path/to/my/output
Run man sh or man bash and read about Redirections.
A: grep/awk/sed... many tools can do that. grep example:
kent$ echo "pid 4565 Process: /my/name/is/4678 +34787[d]sfh888dwe4rtertfsj@##$
pid 33453 Process: /my/name/is/4678 +34787[d]sfh888dfsj@##werwer$
pid 3453345 Process: /my/name/is/4678 +3478[7]dsfhew46534wy6888dfsj@##$
pid 12335 Process: /my/name/is/4678 +3478se[r]tet57dsfh888dfsj@##$"|grep '\+34787\[d\]sfh888dfsj@##werwer\$'
pid 33453 Process: /my/name/is/4678 +34787[d]sfh888dfsj@##werwer$
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: When to use processes, multithreading or neither While using Chrome I notice a great many processes. As I understand it Chrome's design entails each plugin, tab and extension to be in its own process.
Is this a more effective approach to just using multithreading such as internet explorer does, or having everything in one process such as Firefox?
I feel the different browsers are a good example for my question. When is it appropriately to use a process for everything vs multithreading vs nothing?
A: In Chrome, this multi-processing is done to achieve robustness and security. If one process hangs or crashes, it has absolutely no affect on the other processes (unless it's the process responsible for the UI). This is crucial in an environment where 3rd party extensions might hang, crash or even try to hack your program (different processes don't share the same address space, as opposed to different threads).
Using this approach adds a significant overhead for Inter-Process Communication. When multithreading, passing messages is not a problem, because all threads share the same address space. Passing messages between processes is much harder. Also, the total memory consumption of the program is higher when using processes instead of threads. And then there's the state of the program which is also harder to maintain - if the UI crashes, for instance, all other processes must be shut down. This is not a problem in multithreading, where the main thread exits.
Bottom line - on most cases, using multiple processes is an overkill. However, for better separation of the various tasks, it might be the solution on some cases.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do you print the day name given a day number in SQL Server 2005 using SQL commands? I want to be able to pass in a day number like 1, 2, 3 or 7 and it will return the day name like Sunday, Monday, Tuesday or Saturday. I know there is the option of using a case statement but I would like to do this using SQL commands, would this be at all possible?
DECLARE @m VARCHAR
SET @m=1
SELECT CASE WHEN @m=1 THEN 'Sunday' END
I have already commented on this question when looking for an answer but user @harper suggested that I should submit a new question with a full description.
EDIT:
there is currently answers are given for case statement mostly except one . so again now i am putting my question again here is
" I would like to do this using SQL commands, would this be at all possible?"
A: Try this :
declare @m varchar
set @m=1
SELECT DATENAME(DW,CAST(@m AS INT))
A: SQL Server Denali has the CHOOSE function that will make this more concise. In the meantime just use CASE inside the UDF.
CREATE FUNCTION dbo.WeekDay(@d int)
RETURNS VARCHAR(9)
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS
BEGIN
RETURN
(
SELECT
CASE @d
WHEN 1 THEN 'Sunday'
WHEN 2 THEN 'Monday'
WHEN 3 THEN 'Tuesday'
WHEN 4 THEN 'Wednesday'
WHEN 5 THEN 'Thursday'
WHEN 6 THEN 'Friday'
WHEN 7 THEN 'Saturday'
END
)
END
A: CREATE FUNCTION dbo.udf_DayOfWeek(@dtDate DATETIME)
RETURNS VARCHAR(10)
AS
BEGIN
DECLARE @rtDayofWeek VARCHAR(10)
SELECT @rtDayofWeek = CASE DATEPART(weekday,@dtDate)
WHEN 1 THEN 'Sunday'
WHEN 2 THEN 'Monday'
WHEN 3 THEN 'Tuesday'
WHEN 4 THEN 'Wednesday'
WHEN 5 THEN 'Thursday'
WHEN 6 THEN 'Friday'
WHEN 7 THEN 'Saturday'
END
RETURN (@rtDayofWeek)
END
GO
-- Call this function like this:
SELECT dbo.udf_DayOfWeek(GETDATE()) AS DayOfWeek
orignally from : SQL SERVER – UDF – Get the Day of the Week Function
A: SELECT DATENAME(DW,CAST(a AS INT))
Here we can change the value of a as 0 to 6
Default, 0-Monday to 6- Sunday.
If we use a=7 then it will be calculated as 0, because 7-7=0.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Facebook Open Graph Beta: OAuthException Trying to test the new Open Graph Beta to post a new action.
I'm following the official tutorial
It says to publish an action you would use this POST
For example, sending a POST to:
https://graph.facebook.com/me/YOUR_NAMESPACE:cook
?recipe=OBJECT_URL&access_token=ACCESS_TOKEN
But in the JS call. There is no access token
FB.api('/me/YOUR_NAMESPACE:cook' +
'?recipe=http://example.com/cookie.html','post',
function(response) {
..........
}
I get an error when i try to publish my own action. I have authenticated the publish_actions permission with the app
*
*"OAuthException" - "An unexpected error has occurred. Please retry your request later."
A: It might be possible you are not posting to the correct object.
As in example 'cook' is action and 'recipe' is object..So the 'OBJECT_URL' must be of type 'recipe' as far as tutorial is concerned.
Since timeline is not launched therefore when you create your own object facebook provides you a sample url of that type which can be used to test the posting of your app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Refresh user control in form:1 on form:2 closing event in winforms C# Form:1 contains a user control, on the cell click event of the user control grid I show form:2. When I update values in form:2 and close it, the user control grid in form:1 should get refreshed.
I did the same as in this link though it does not produce any error, the user control grid did not get bind!!!
Please let me know how this can be accomplished.
A: Use the advantage of ShowDialog() method.
If a form is displayed as modal, the code following the ShowDialog method is not executed until the dialog box is closed. However, when a form is shown as modeless, the code following the Show method is executed immediately after the form is displayed.
private void CellClicked()
{
Form2 form2 = new Form2();
form2.ShowDialog();
//Execution stops here until you close the form2.
myForm1Control.Values = form2.GetValues();
}
A: I have implemented this functionality using delegates,
Declare delegate in user control,
public delegate void Delegate1(datatype param1,datatype param2, datatype param3);//should be similar to the method used to bind user control in form1
public Delegate1 RefreshGrid;
In cell click event of user control, after form2.ShowDialog()add
RefreshGrid(param1,param2,param3);
In form1's constructor after intializecomponent() method add
usercontrolID.RefreshGrid = MethodUsedToBindUserControl;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: CSS property Box-Sizing has no effect on the Box Model There was this question posted and it got me thinking.
table cell fixed height and border issue in firefox
So I did as follows.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Template</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<table id="first" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
<td>Cell 4</td>
<td>Cell 5</td>
</tr>
</tbody>
</table>
<table id="second" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
<td>Cell 4</td>
<td>Cell 5</td>
</tr>
</tbody>
</table>
<table id="third" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
<td>Cell 4</td>
<td>Cell 5</td>
</tr>
</tbody>
</table>
</body>
</html>
With the following CSS:
* {
padding: 0;
margin: 0;
font: 15px arial, sans-serif;
line-height: 1;
}
table {
border-collapse: collapse;
border-spacing: 0;
float: left;
margin-left: 5px;
}
table#first tbody tr td {
height: 35px;
border-bottom: 5px solid #000;
box-sizing: border-box;
-moz-box-sizing: border-box;
}
table#second tbody tr td {
height: 35px;
border-bottom: 5px solid #000;
box-sizing: content-box;
-moz-box-sizing: content-box;
}
table#third tbody tr td {
height: 35px;
border-bottom: 5px solid #000;
box-sizing: padding-box;
-moz-box-sizing: padding-box;
}
The problem is that regardless of the box-sizing property with values of border-box(click for pic), content-box(click for pic) and padding-box(click for pic), in Firefox 6.0.2, under Firebug 1.8.2, the layout tab as well as the computed height shows the height of all <td> to be 32px with a 3px border.
Either something is wrong, or I am missing something simple or my concept of the box-model is wrong?
Can also somebody please create the tags for "box-sizing" and "padding-box"
A: This is a known issue with Firefox's implementation of box-sizing. The MDN page for box-sizing says:
Notes
See bug 243412 and its dependents:
*
*-moz-box-sizing doesn't apply to table cells
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Python - self, no self and cls Yet another question on what the 'self' is for, what happens if you don't use 'self' and what's 'cls' for.
I "have done my homework", I just want to make sure I got it all.
self - To access an attribute of an object, you need to prefix the attribute name with the object name (objname.attributename). The same way self is used to access an attribute inside the object (class) itself. So if you didn't prefix a variable with self in a class method, you wouldn't be able to access that variable in other methods of the class, or outside of the class. So you could omit it if you wanted to make the variable local to that method only. The same way if you had a method and you didn't have any variable you wanted to share with other methods, you could omit the self from the method arguments.
cls - Each instance creates it's own "copy" of the attributes, so if you wanted all the instances of a class to share the same variable, you would prefix that variable name with 'cls' in the class declaration.
Is this all right? Thanks.
A: You use self as the first argument in regular methods where the instance is passed automatically through this argument. So whatever the first argument is in a method - it points to the current instance
When a method is decorated with @classmethod it gets the class passed as its first argument so the most common name for it is cls as it points to the class.
You usually do not prefix any variables (hungarian notation is bad).
Here's an example:
class Test(object):
def hello(self):
print 'instance %r says hello' % self
@classmethod
def greet(cls):
print 'class %r greet you' % cls
Output:
>>> Test().hello()
instance <__main__.Test object at 0x1f19650> says hello
>>> Test.greet()
class <class '__main__.Test'> greet you
A:
The same way self is used to access an attribute inside the object (class) itself.
Not inside the object / class, just inside the class' instance methods. self is just a convention, you could call it whatever you wanted, even something different in each method.
So if you didn't prefix a variable with self in a class method, you wouldn't be able to access that variable in other methods of the class, or outside of the class.
self is used in instance methods, cls is often used in class methods. Otherwise, correct.
So you could omit it if you wanted to make the variable local to that method only.
Yes, inside a method a variable name is like inside any other function -- the interpreter looks for the name locally, then in closures, then in the globals / module level, then in the Python built-ins.
The same way if you had a method and you didn't have any variable you wanted to share with other methods, you could omit the self from the method arguments.
No, you can't just omit "self" from the method arguments. You have to tell Python you want a staticmethod, which won't automatically get passed the instance of the class, ether by doing @staticmethod above the def line, or mymethod = staticmethod(mymethod) below the method body.
Each instance creates it's own "copy" of the attributes, so if you wanted all the instances of a class to share the same variable, you would prefix that variable name with 'cls' in the class declaration.
Inside the class definition, but outside any methods, names are bound to the class -- that's how you define methods etc. You don't prefix them with cls or anything else.
cls is generally used in the __new__ special staticmethod, or in classmethods, which you make similarly to staticmethods. These are methods that only need access to the class, but not to things specific to each instance of the class.
Inside a classmethod, yes, you'd use this to refer to attributes you wanted all instances of the class, and the class itself, to share.
Like self, cls is just a convention, and you could call it whatever you wanted.
A brief example:
class Foo(object):
# you couldn't use self. or cls. out here, they wouldn't mean anything
# this is a class attribute
thing = 'athing'
def __init__(self, bar):
# I want other methods called on this instance of Foo
# to have access to bar, so I create an attribute of self
# pointing to it
self.bar = bar
@staticmethod
def default_foo():
# static methods are often used as alternate constructors,
# since they don't need access to any part of the class
# if the method doesn't have anything at all to do with the class
# just use a module level function
return Foo('baz')
@classmethod
def two_things(cls):
# can access class attributes, like thing
# but not instance attributes, like bar
print cls.thing, cls.thing
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "78"
}
|
Q: Thread window is empty I am debugging console application, it has several threads running. Then why Thread Window is empty in VS 2010? I do not see any thread listed here, even main thread is not here. Do I need to enable something?
A: Seen in HansPassant's comment above: This is normal, please try to set a breakpoint or utilize Debug + Break All.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Delphi 7 and WCF. Complex type problem I have a WCF service based on basicHTTPBinding. I am calling this service from Delphi 7 and .NET form. The D7 client is able to successfully call the Operation that has primitive input and output type. However, when an operation with complex type is called, the web service receives the complex type as NULL. .Net client is working fine. Here hare the Request headers retrieved from Fiddler.
Delphi client
<?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<GetDataUsingDataContract xmlns="http://tempuri.org/">
<composite xmlns="http://schemas.datacontract.org/2004/07/DelphiService2">
<BoolValue>true</BoolValue>
<StringValue>Test</StringValue>
</composite>
</GetDataUsingDataContract>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
.Net Client
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetDataUsingDataContract xmlns="http://tempuri.org/">
<composite xmlns:a="http://schemas.datacontract.org/2004/07/DelphiService2" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:BoolValue>true</a:BoolValue>
<a:StringValue>test</a:StringValue>
</composite>
</GetDataUsingDataContract>
</s:Body>
</s:Envelope>
A: Your issue is caused by the Delphi client putting the composite element being defined in the "http://tempuri.org/" XML namespace instead of the "http://schemas.datacontract.org/2004/07/DelphiService2" namespace. The composite, BoolValue & StringValue elements all need to be defined in the "http://schemas.datacontract.org/2004/07/DelphiService2" XML namespace (prefixed with the namespace alias "a:" in this case).
One way to solve this issue if the Delphi client serializer can't be tweaked is to replace the WCF supplied default namespaces of "http://tempuri.org/" and "http://schemas.datacontract.org/2004/07/DelphiService2" with one you define yourself. Tweak the service contract to conform to the changes outlined in this post and also change the DataContracts to match the new XML namespace. This way all the service defined operations and objects will be in the same XML namespace.
[DataContract(Namespace="http://YourNamespace/2011/09/DelphiService2")]
public class composite
{
public bool BoolValue {get; set;}
public string StringValue {get; set;}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MVC in yii: how to build pages with several actions belonging to different models I would like to know how you should write website pages that use for example 3 models and several actions on them.
Because there is usually only a controller involved with a page call and only a special action.
For example:
there should be a page which displays a group of people, and on that page I can edit the peoples names and assign new people to the group and i can add people as new managers of a group.
Does this page need its own controller or how do I program such pages?
A: Using your scenario, here is how I would set things up:
The controller you'd use for all related actions would be 'Group' (in Yii, 'ControllerGroup')
For your main page that displays the group of people, you could make an action in your Group controller called 'manage' (in Yii, the method name would be actionManage). Assuming you aren't going an Ajax route, for each person on the manage page you may have a link to edit that person. The links would point to the 'update' action. For adding, you'd want an action 'add'.
Your models involved would likely be User, Group, and UserGroup and you'd use them as necessary in any controller you have.
A: Actions can belong only to controllers. In each action you can work with any models of your application. In your case you must create a UserController and a list of actions (e.g. actionViewList, actionEdit, actionAssignToGroup).
Check this for more information: Yii Controller
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java code to display an Image in Google App Engine I have an image in the blobstore of my GAE . I need to retrieve it and make some trasformations and finally display it in my jsp page.
Currently I used,
BlobKey blobKey = new BlobKey(req.getParameter("blob-key"));
blobstoreService.serve(blobKey, res);
This shows the picture but I want to retrieve it as an 'Image' type and resize it using the code below
ImagesService imagesService = ImagesServiceFactory.getImagesService();
Image oldImage = ImagesServiceFactory.makeImageFromBlob(blobKey);
Transform resize = ImagesServiceFactory.makeResize(200, 300);
Image newImage = imagesService.applyTransform(resize, oldImage);
byte[] newImageData = newImage.getImageData();
How will I display my 'newImage' in a jsp page? It would be very helpful if I could see an example code. I would also like to know if there is any way i can get the blob-key of the images I presently have in my blobviewer.
A: You should not process the image in the request for your JSP page.
You have to take two steps:
1.
Render a JSP page that contains an image tag like
<img src="mydomain.com/getImage?blob-key=123435"/>
2.
Have a separate servelt mapped to mydomain.com/getImage that outputs the image with the given id.
So all the code you presented above will go in the servlet that delivers the image and not in the JSP delivering code. And then the image can be delivered using the HTTPResponses OutputStream. And don't forget to set the correct content type and length for the response.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Assigning Boolean from Object from Hashtable in Java/Android Just moving to Java, so please forgive this basic question:
After this:
Hashtable<String, Object> ht = (Hashtable<String, Object>) menus.get(position);
String title = (String) ht.get("title");
Boolean isCategory = (Boolean) ht.get("isCatgory");
The value of ht is {isCategory=true, title=Info}, as expected.
The value of title is "Info", as expected.
The value of isCategory is null.
How can I extract the Boolean from the Hashtable?
A: You want to buy a vowel.
ht.get("isCategory"); // notice the "e"
A: Boolean isCategory = (Boolean) ht.get("isCategory");//you left **"e"**
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ASP.NET Change facebook og properties from content page I want to dynamically change in code behind facebook og properties like
< meta property="og:image" content="image_link" />
< meta property="og:title" content="title" />
How to do this?
btw. I'm adding regular meta tags like this:
HtmlMeta tag = new HtmlMeta();
tag.Name = "description";
tag.Content = message;
Page.Header.Controls.Add(tag);
A: Here is how you add the proprietary Facebook "property" attribute to a standard META tag:
HtmlMeta tag = new HtmlMeta();
tag.Attributes.Add("property", "og:title");
tag.Content = "MyTitle"; // don't HtmlEncode() string. HtmlMeta already escapes characters.
Page.Header.Controls.Add(tag);
A: if what you want is to add a property attribute in c# to HtmlControl this should be like so:
tag.Attributes.Add(KEY, VALUE);
where KEY = "property" and VALUE = "og:image"
hope this helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Custom control in StatusStip control Is there a way to add a custom control to a StatusStrip Control?
Say, I need a multicolumn Combobox in the status bar...
A: As the modest Hans Passant mentioned, the solution was using the ToolStripControlHost and the ToolStripDesignerAvailability attribute.
More details could be consulted here
A: Easiest way is to do the drawing yourself using a ToolStripComboBox and then place that control in your StatusStrip. The ToolStripComboBox is different from the normal ComboBox because it derives from the ToolStripControlHost.
Dim comboStatus As New ToolStripComboBox
With DirectCast(comboStatus.Control, ComboBox)
.DrawMode = DrawMode.OwnerDrawFixed
AddHandler .DrawItem, AddressOf comboStatus_DrawItem
End With
StatusStrip1.Items.Add(comboStatus)
And then you use the DrawItem event:
Private Sub comboStatus_DrawItem(ByVal sender As Object, ByVal e As DrawItemEventArgs)
Dim comboStatus As ComboBox = sender
e.DrawBackground()
If e.Index > -1 Then
//Do you drawing.
End If
End Sub
See ComboBox.DrawItem Event for the drawing details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java Play Framework Groovy Scripts within Javascript I want to perform some AJAX style data retrieval using the Java Play Framework and have come across an issue with the 'route' script syntax.
The problem is that in the code below @{Movies.show("'+movie.id+'")} gets compiled to url/etc/+movie.id+ rather than url/etc/1.
<script type="text/javascript">
function showMoreMovies()
{
$.getJSON('@{Movies.jsonAllMovies()}', function(movies) {
var items = [];
$.each(movies, function(i, movie)
{
var div_data = '<div class="movie">'+
'<h2 class="movie-title"><a href="@{Movies.show("'+movie.id+'")}">'+movie.title+'</a></h2>'+
'<div class="release-date">' + movie.releasedString + '</div>'+
'<div class="comments">| comments: ' + movie.commentCount + '</div>'+
'</div>';
$(div_data).appendTo("#movie_results");
});
});
}
</script>
A work around is to hard-code the route url:
<a href="url/etc/'+movie.id+'">
which works, but you lose the benefits of automatic routing.
Has anyone else come across this or found a new solution to this problem?
A: It's quite normal...
Remind that a groovy script is precompiled at server side and not executed at client side.
<a href="@{Movies.show("'+movie.id+'")}"> is compiled and groovy parses @{Movies.show("'+movie.id+'")} and generates "url/etc/+movie.id+" which is the URL of action Movies.show(id="+movie.id+")
You should use this: http://www.playframework.org/documentation/1.2.3/ajax
var showAction = #{jsAction @Movies.show(':id') /}
And then use it like that:
var div_data = '<div class="movie">'+
'<h2 class="movie-title"><a href="'+ showAction({id: movie.id}) +'">'+movie.title+'</a></h2>'+
'<div class="release-date">' + movie.releasedString + '</div>'+
'<div class="comments">| comments: ' + movie.commentCount + '</div>'+
'</div>';
A: Another solution is to use the following:
"/movies/show/etc/"+movie.id;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Qt Jambi eclipse integration error on Windows 64 bits I can't seem to figure out how to properly integrate Qt Jambi to eclipse. Here is what I did:
*
*I installed the version of the toolkit for Windows 64 bits;
*I copied the required integration plugins in {ECLIPSE_PATH}\plugins;
*I launched eclipse and set Qt Jambi's installation directory in the preferences;
*Then, when I tried to apply the new preferences, I got an error that said something about a module that couldn't be launched ({QT_JAMBI_PATH}\bin\qtdesigner.dll);
*After restarting eclipse, I can't find any of Qt Jambi's integration views. I can switch to Qt Designer UI perspective, but then, no new panel is appearing. Finally, .jui files are not recognized and appear as simple text files.
The DLL file qtdesigner.dll does not exist in the bin folder. I tried the same procedure using eclipse 32 bits, and Qt Jambi 32 bits, but it's not working either.
Where do you think the problem comes from?
A: There is currently no known release of QtJambi Eclipse integration plugins that are compatible with a Windows 64bit JVM and therefore also provided as 64bit DLLs (as many parts of it are native code components).
Here is the official page to back up that claim: http://qt.nokia.com/products/eclipse-integration/
Also the QtJambi Eclipse integration source code was never released to the community in order to allow them to either maintain it or build versons for other OS and ABI (like 64bit Windows). Also the version in the page is probably most compatible with older versions of Eclipse such a Eclipse 3.4 and 3.5.
However all is not lost, it is my intention (as one of the QtJambi maintainers) to get something back working again within the next 6 months. But my current attention is on more urgent matters within the project as per our bug reporting system indicates.
...
It is not possible to mix 32bit DLLs in 64bit process address space a simple/naive way. So as a rule all EXE and DLLs have to be the same kind. Since we know that QtJambi Eclipse integration works from windows 32bit here is some information below to help you with that.
...
A Windows 64bit system is capable of running 32bit applications and also capable of having both the 64bit and 32bit JVMs installed separately (just download the appropiate JVM install EXE for each kind 32bit and 64bit and install both individually).
You then of course need to obtain the Win32 version of Eclipse and unzip/install it.
In order to get a 32bit version of Eclipse to run on a 64bit system it is necessary to manually edit the eclipse.ini file here is my example of a working eclipse.ini with the important parts of the additions highlighted (taken from eclipse-jee-indigo-win32 which is Eclipse 3.7 Indigo from
http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/indigo/R/eclipse-jee-indigo-win32.zip ) :
eclipse.ini
-startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.100.v20110502
-product
org.eclipse.epp.package.jee.product
-showsplash
org.eclipse.platform
-vm
C:/Program Files (x86)/Java/jdk1.6.0_26/jre/bin/client/jvm.dll
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms64m
-Xmx1280m
The important changes I ensure I make to the default eclipse.exe are:
-vm
C:/Program Files (x86)/Java/jdk1.6.0_26/jre/bin/client/jvm.dll
Note you need to modify this to the path of the file that exists for your JDK that is installed, in my example I am using the Sun/Oracle JDK. So check the file actually exists in your system, this forces the 32bit JVM to be used with the 32bit version of Eclipse. I don't know why their container exe (eclipse.exe) doesn't already do this at runtime, but still.
--launcher.XXMaxPermSize
256M
Always a good idea as eclipse needs a larger than usual PermGen heap. But all versions of eclipse probably want this configuration and this doesn't affect your problem just some advise here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Read word by word from Msword document asp.net I am working on an application in which I need to read word by word from uploaded document.
For this I have added the following code:
Microsoft.Office.Interop.Word.ApplicationClass Application =
new Microsoft.Office.Interop.Word.ApplicationClass();
object nullobj = System.Reflection.Missing.Value;
object file = "c:\\word.doc";
object value = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Document doc =
Application.Documents.Open(ref file,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
ref value,
ref value,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj);
doc.Activate();
//var ss = doc.Words[0];
var x = doc.Words;
foreach (var v in doc.Words)
{
}
string Doc_Content = doc.Content.Text;
// txtContent.Text = Doc_Content;
doc.Close(ref nullobj, ref nullobj, ref nullobj);
The loop is going on each word in the document but I am not able to get the word inside the loop. If someone has solution then please help me.
A: For this which namespace we have to required added
Microsoft.Office.Interop.Word.ApplicationClass Application =
new Microsoft.Office.Interop.Word.ApplicationClass();
A: You can cast V to range, and grab the text from it.
string ActualText = ((Range)v).Text;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: asp.net MVC3 App_Offline.htm : possible to return application/json header? When you want to put your site offline.
Almost everything in our application (API) is JSON. I think it might be better to return JSON, as the programs build on top of this API expects a JSON response on all of the methods.
Is it possible to return JSON instead with the correct content type in the App_Offline.htm?
A: Have you tried removing the ContentType header and adding it after :
http://i2.iis.net/ConfigReference/system.webServer/httpProtocol/customHeaders
I have never done that with app_offline.htm but might work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: webservice message with images in listview android I have a doubt to be clarified.
I am developing a chat application. I have a smiley button , a Edit Text and a send button.
*
*I send message along with smileys to web service. I need to return the same data i sent from web service into list view where i display the list of messages from web service.
What i achieved is: I am able to send the data with smileys. But when i get back the data from web service i get my data and [obj] icon along with my message. why am i not able to display image that is returned from web service. How can i check if my data is sent along with image to service or not. How can i achieve that.
Thanks
A: if you are going to send the image to the service then try to check the request by printing it in logcat. may be your request is not in proper format. for image we need to send the bytearray stream, are you doing that?
also when you get the data from webservice are you decoding the image data back to bitmap?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: pl/sql conversion from number to string i need to convert number to string in pl/sql without using the inbuilt functions , we should use string/module operations for this. for example if the input is 123 then the output should be one hundred and twenty three can anyone give me suggestions about this pls?
A: You could do this in SQL or PL/SQL using the following:
In SQL:
SELECT to_char(to_date(<number_column>,'j'), 'jsp')
FROM <table>;
In PL/SQL:
DECLARE
v_number NUMBER := 56;
v_text VARCHAR2(128);
BEGIN
v_text := to_char(to_date(v_number,'j'), 'jsp');
END;
More information from AskTom here:
http://asktom.oracle.com/pls/apex/f?p=100:11:0::NO::P11_QUESTION_ID:18305103094123#PAGETOP
I suppose it really depends upon what level of "in-built" functions you are going to artificially prevent yourself using and why?
Hope it helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to create a php extension for an object? I am working on a php extension for c++ classes. How to create a link to a method that accepts as parameter an object of a class?
Can you give me some examples?
THX. APPRECIATE!
I succedded to create a link to a method that accepts as parameter a string or int. But I don't know how to do this for a method.
Here is a short example:
PHP_METHOD(Class1, method_string)
{
Class1 *access;
char *strr=NULL;
int strr_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &strr, &strr_len) == FAILURE) {
RETURN_NULL();
}
access_object *obj = (access_object *)zend_object_store_get_object(
getThis() TSRMLS_CC);
access = obj->access;
if (access != NULL) {
std::string s(strr);
RETURN_BOOL(access->method_string(s));
}
}
A: I believe ZEND_API int zend_parse_method_parameters(int num_args TSRMLS_DC, zval *this_ptr, char *type_spec, ...); AND
ZEND_API int zend_parse_method_parameters_ex(int flags, int num_args TSRMLS_DC, zval *this_ptr, char *type_spec, ...); are the right API for retrieving the input parameters in the method.
I think the same API will help you accept an object as an input parameter.
A: Use the zend API zend_parse_method_parameters():
ZEND_METHOD(ext_access_class, do_something)
{
zval* objid_this = NULL, objid1 = NULL;
// note: ext_access_class_entry and ext_param_class_entry are of type zend_class_entry*
if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &objid_this, ext_access_class_entry, &objid1, ext_param_class_entry) == FAILURE)
RETURN_NULL();
ext_access_class* const access_obj = (ext_access_class*) zend_object_store_get_object(objid_this TSRMLS_CC);
Class1* const access = access_obj->access;
ext_param_class* const param_obj = (ext_param_class*) zend_object_store_get_object(objid1 TSRMLS_CC);
Class2* const myobject = param_obj->myobject;
const bool ret = access->do_something(myobject);
RETURN_BOOL(ret);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MVC.net EF validation when using View Models I'm working on an MVC application and i'm trying to implement some validation. I've strucuture the site to use EF for storage and a set of view models with automapper.
I want to add some validation which i'm sure would work if i added it to the View Models however i'm assuming it would be better to put validation in with the EF model so if in the future i create another interface the same validation would also apply.
First of is this the correct approach and second how do i get MVC to actually test the validation before saving the object. Currently it just skips my EF validation.
The address model is auto generated so i created this partial class to add the validation:
public partial class Address : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!string.IsNullOrWhiteSpace(this.AddressLine1) &&
!string.IsNullOrWhiteSpace(this.AddressLine2) &&
!string.IsNullOrWhiteSpace(this.AddressLine3) &&
!string.IsNullOrWhiteSpace(this.Town) &&
!string.IsNullOrWhiteSpace(this.City) &&
!string.IsNullOrWhiteSpace(this.County) &&
!string.IsNullOrWhiteSpace(this.Postcode))
yield return new ValidationResult("Address cannot be blank.");
}
}
This is my view model class with the display names changed
public class AddressVM
{
public int? ID { get; set; }
[Display(Name = "Address line 1")]
public string AddressLine1 { get; set; }
[Display(Name = "Address line 2")]
public string AddressLine2 { get; set; }
[Display(Name = "Address line 3")]
public string AddressLine3 { get; set; }
[Display(Name = "Town")]
public string Town { get; set; }
[Display(Name = "City")]
public string City { get; set; }
[Display(Name = "County")]
public string County { get; set; }
[Display(Name = "Postcode")]
public string PostCode { get; set; }
}
This is my controller
public ActionResult AddAddress(AddressVM vm)
{
IncidentAddress theAddress = Mapper.Map<AddressVM, Address>(vm);
if (ModelState.IsValid)
{
UOW.Addresses.Add(theAddress);
UOW.Save();
}
return PartialView("AddressVM-edit", vm);
}
A: if (ModelState.IsValid)
This will always be true for your object, as it will look for validity of your model, which is AddressVM (you receive that from view so this is your model) and does not have any validators. ModelState does not know that you have mapped this object to some other which implements validation. You need to run validation on your other object manually and add validation errors to ModelState.
If you want to have this separated, you can implement IValidatableObject on AddressVM, and internally perform validation by creating a instance of Address, mapping it from AddressVM (this) and returning result of it's Validate method. You also can expose the same constructed Address object as a property and use it to perform entity operation.
Example of AddressVM:
public class AddressVM : IValidatableObject
{
public int? ID { get; set; }
[Display(Name = "Address line 1")]
public string AddressLine1 { get; set; }
[Display(Name = "Address line 2")]
public string AddressLine2 { get; set; }
[Display(Name = "Address line 3")]
public string AddressLine3 { get; set; }
[Display(Name = "Town")]
public string Town { get; set; }
[Display(Name = "City")]
public string City { get; set; }
[Display(Name = "County")]
public string County { get; set; }
[Display(Name = "Postcode")]
public string PostCode { get; set; }
//// I added this and interface in class definition:
public IncidentAddress GetIncidentAddress()
{
return Mapper.Map<AddressVM, Address>(this);
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
return this.GetIncidentAddress().Validate(validationContext);
}
}
This way your logic stays in your business object, and your viewmodel uses it without having copy of it or some other dependency.
A: The Address class and AddressVm are not bound to each other in your case - AutoMapper does not do validation stuff, it just copies values. So you do not get ModelState populated and validations performed.
There're two workarounds i'm thinking of
*
*Define the validations on AddressVm. If ModelState.IsValid, then map AddressVm to Address and save.
*You do not need AddressVm at all. Change Action signature to expect Address parameter. That way, ModelState.IsValid will be automatically populated by validation system (Not the best solution).
Ideally, ViewModels should be defined for specific scenarios. In your case, I would define AddAddressModel, use it only for adding addresses and define only the properties needed to create address. Then, define validations on AddAddressModel and use mapper to map ViewModel to Address instance (So, I prefer first solution, plus defining specific model).
If you need reusable validator classes, you could check out FluentValidation. It has good support of asp.net-mvc too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iPhone SDK: Grab HTML and place into Tableview Cell I'm just wondering if it's possible to grab a specific piece of html from a webpage and place the content into a tableview cell?
The reason I ask is because I have a detail page which has a list that I would like to be dynamically updated everytime the webpage is updated.
Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Called id for nil in Rails 3 In development mode:
nil.id
=> "Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id"
In production mode:
nil.id
=> 4
Why?
A: Your development.rb evironment has the following line:
config.whiny_nils = true
Which will log an error when you try to call a method on nil. nil's id is 4 because it is an object which happens to have an id of 4
A: Code of method NilClass#id has good explanation:
# NilClass#id exists in Ruby 1.8 (though it is deprecated). Since +id+ is a fundamental
# method of Active Record models NilClass#id is redefined as well to raise a RuntimeError
# and warn the user. She probably wanted a model database identifier and the 4
# returned by the original method could result in obscure bugs.
#
# The flag <tt>config.whiny_nils</tt> determines whether this feature is enabled.
# By default it is on in development and test modes, and it is off in production
# mode.
https://github.com/rails/rails/blob/0c76eb1106dc82bb0e3cc50498383d6f992da4fb/activesupport/lib/active_support/whiny_nil.rb#L19
A: Look for the line that says the following in your environments configs:
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true # or false in production.rb
This is to prevent you from calling methods on nil while in development mode. I guess they disabled it for performance reasons in production.
And nil is a singleton object in ruby, that's why its id will be 4 no matter what.
A: Whiny nils are only reported during development mode (look into your config files).
"Whiny nils" is the Rails term for putting warnings into the log
whenever a method is invoked on a nil value, with (hopefully) helpful
information about which sort of object you might have been trying to
use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Equivalent of SQL loader in MySQL I have found SQL loader in Oracle is very helpful, fast and efficient. What is the MySQL equivalent of SQL loader?
A: There is MySQL Front 3.2
and
LOAD DATA INFILE
(see docs)
A: LOAD DATA INFILE....
Provides much of the same functionality as you would implement in your control file except for byte ranges and 'WHERE' filters.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Problem with progressEvent Listener for (i=0; i < _xmlContents.img_array.length; i++)
{
_loader = new Loader();
_loader.name = "image"+i;
_loader.load(new URLRequest(_xmlContents.img_array[i]));
_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoadingAction);
//Event.COMPLETE listnere
//error Handler
}
private function onLoadingAction(e:ProgressEvent):void
{
_preLoader = new Preloader();
//addChild(_preLoader);
trace(_loader.name);
}
I want to add preloader for every image in the xml. Now I am getting for last image only.
(consider if xml length is 5, it will trace image4 only)
How can I add that?
A: It is because you have one _loader object. In every loop step you overwrite this loader with new one so previous image stops loading. You should use new loaders for every image:
for (i=0; i < _xmlContents.img_array.length; i++)
{
// create new loader instance, not use a global one
var _loader:Loader = new Loader();
_loader.name = "image"+i;
_loader.load(new URLRequest(_xmlContents.img_array[i]));
_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoadingAction);
//Event.COMPLETE listnere
//error Handler
_preLoader = new Preloader();
//addChild(_preLoader);
}
private function onLoadingAction(e:ProgressEvent):void
{
// trace(e.bytesLoaded, e.bytesTotal);
}
A: I dont think the array is necessary and I think you'll be on a better track adding 4 instances of the preloader by calling it from Event.INIT as opposed to repeatedly adding it by using ProgressEvent.PROGRESS.
A: First of all your event listeners attached to the loader instances before the last one (e.g. loaders 0 to 3) are there. They will still be there for a long long time. Remove them!
ActionScript is a very nice language - use it's power :)
for (i=0; i < img_array.length; i++)
{
_loader = new Loader();
_loader.name = "image"+i;
_loader.load(new URLRequest(img_array[i]));
_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,
function onLoadingAction(e:ProgressEvent):void
{
trace((e.target as LoaderInfo).loader.name);
//Do whatever you want to do here like removing event listener
if ((e.target as LoaderInfo).bytesLoaded == (e.target as LoaderInfo).bytesTotal)
{
(e.target as LoaderInfo).removeEventListener(ProgressEvent.PROGRESS, onLoadingAction);
trace("Event listener for " + (e.target as LoaderInfo).loader.name + " removed ");
}
}, false, i * 1000 /* you can use priority if want to maintain some order in event handling*/);
}
ActionScript provides you with the ability to name inline functions and to have a reference to them. Use this approach when you don't need to keep a reference to some object.
Good luck and have fun!
A: for (i=0; i < _xmlContents.img_array.length; i++)
{
_loader = new Loader();
_loader.name = "image"+i;
_loader.load(new URLRequest(_xmlContents.img_array[i]));
_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,
onLoadingAction);
//Event.COMPLETE listnere
//error Handler
_preLoader = new Preloader();
_bgBox.addChild(_preLoader);
}
This way is solves my problem.. But I don't think so, it's a good way.
A: You your _loader object is defined inside the function and not referenced anywhere else, so it is garbage collected after the function ends. Create an array of loaders and push the loaders to them each time.
private var _loadersArray:Array=[]; //outside the function
for (i=0; i < _xmlContents.img_array.length; i++)
{
// create new loader instance, not use a global one
var _loader:Loader = new Loader();
_loader.name = "image"+i;
_loader.load(new URLRequest(_xmlContents.img_array[i]));
_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoadingAction);
_loadersArray.push(_loader);
//Event.COMPLETE listnere
//error Handler
}
private function onLoadingAction(e:ProgressEvent):void
{
_preLoader = new Preloader();
//addChild(_preLoader);
// get current loader instance
var _loader:Loader = e.target.loader;
trace(_loader.name);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to access component value programmatically Lets assume I want to access the value of a sibling component in an ActionListener.
The following fragment is not working as expected, resulting in a ClassCastException: java.util.HashSet cannot be cast to java.lang.String
public void processAction(final ActionEvent event) {
FacesContext ctx = FacesContext.getCurrentInstance();
UIComponent sibling = event.getComponent().findComponent("inputText");
String value = (String) sibling.getValue();
...
}
If I change the essential part to the following fragment everything works fine:
String value = ctx.getApplication().evaluateExpressionGet(ctx, inputText.getValueExpression("value").getExpressionString(), String.class);
Is there a nicer solution? Why is the value of the inputText of type HashSet?
Thx in advance
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: resteasy, jaxb - How to produce a collection/list of strings? Simple task, I need to produce this XML:
<collection>
<name>bill</name>
<name>monica</name>
<collection>
instead of this (see following example: 19.6. Arrays and Collections of JAXB Objects):
<collection>
<customer><name>bill</name></customer>
<customer><name>monica</name></customer>
<collection>
Simple collection with strings. So the question is how to remove surrounding customer element? How can I do this with RESTeasy and JAXB?
A: On the Customer class map the name property with the @XmlValue annotation:
public class Customer {
private String name;
@XmlValue
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
For More Information
*
*http://blog.bdoughan.com/2011/06/jaxb-and-complex-types-with-simple.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Interactive command for inserting the string returned by a function When evaluating elisp symbolic expressions with (eval-last-sexp), bound to C-x C-e, I can just type C-u before that command to insert the result of the expression into the current buffer.
Is there some equivalent to that when calling functions interactively? For example, if I want to insert the string returned by (emacs-version) into the current-buffer, how would I do that? M-x emacs-version only shows the string in the minibuffer and typing C-u before M-x emacs-version won't work either.
If there is no such equivalent, what would be the easiest way to insert a string returned by a function without first having to type the function down before evaluating it?
UPDATE:
C-u M-x emacs-version does actually work. My mistake. But it does not work for emacs-uptime. How come it doesn't work for that one?
A: (defun my-insert-command-value (command)
"Insert the return value of the command."
(interactive "*C(insert) M-x ")
(print (call-interactively command) (current-buffer)))
A: emacs-uptime was implemented to output the result only to minibuffer
(defun emacs-uptime (&optional format)
(interactive)
(let ((str
(format-seconds (or format "%Y, %D, %H, %M, %z%S")
(float-time
(time-subtract (current-time) before-init-time)))))
(if (called-interactively-p 'interactive)
(message "%s" str)
str)))
emacs-version has the following code which prints output if called with C-u
(if here
(insert version-string)
(if (called-interactively-p 'interactive)
(message "%s" version-string)
version-string))
If you want to print the result of a particular command (e.g. emacs-uptime) you can wrap it to insert result into the current buffer (similar to emacs-version).
However, I don't know a generic solution - how to output the result of any Emacs command.
A: C-u M-x pp-eval-expression RET (emacs-uptime) RET
"Evaluate Emacs-Lisp sexp EXPRESSION, and pretty-print its value.
With a prefix arg, insert the value into the current buffer at point.
With a negative prefix arg, if the value is a string, then insert it
into the buffer without double-quotes (`"')."
See pp+.el.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Two TableLayout having the same columns I have a problem with my column widths in my TableLayouts. This is the situation, I have multiple TableLayouts that need to be aligned all together, the problem is that they are in different XML files (the same one inflated multiple times) and each one has it's one TableLayout.
This is the XML
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow>
<TextView
android:id="@+id/listViewText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" />
<TextView
android:id="@+id/listViewValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" />
</TableRow>
</TableLayout>
This is an image of how I would like to have it.
I hope that someone can help me with this. Important to know is that every row (TableLayout) is in it's own XML and that I'm not able to place the TableLayout outside these XMLs.
A: If your table only has two columns its probably easier to use a linear layout and specify the layout_weight for each member of the LinearLayout. Here is an example:
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="2">
<TextView android:id="@+id/txt1"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:text="Buy"/>
<TextView android:id="@+id/txt2"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:text="Share"/>
</LinearLayout>
You just need to make sure that the sum of the layout_weights of the individual views sums up to the weightSum of the parent ViewGroup.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Neither BindingResult nor plain target object for bean name 'userProfile' available as request attribute I've encountered the folowing exception while I was trying to implement my first spring+hibernate web app:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userProfile' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
at org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
...
UserController.java:
@Controller
public class UserController {
@Autowired
private UserProfileService userProfileService;
public UserController(){
}
@RequestMapping(value="/add", method=RequestMethod.POST)
public String registerUser(@ModelAttribute("userProfile") UserProfile userProfile, BindingResult result, Map model){
userProfileService.addUserProfile(userProfile);
return "redirect:/login";
}
...
}
UserProfile.java
@Entity
@Table(name="USER_PROFILE")
public class UserProfile {
@Id
@GeneratedValue
@Column(name = "ID")
private Long id;
@Column(name = "USERNAME")
private String userName;
@Column(name = "PASSWORD")
private String password;
//sets and gets
}
index.jsp
<form:form method="post" action="add" commandName="userProfile">
<table>
<tr>
<td><form:label path="userName"><spring:message code="label.username" /></form:label></td>
<td><form:input path="userName" /></td>
</tr>
<tr>
<td><form:label path="password"><spring:message code="label.password" /></form:label></td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td><input type="submit" value="<spring:message code="label.adduser" />"></td>
</tr>
</table>
</form:form>
A: I wasn't noticed that I have to implement method for form creation which will provide instance of UserProfile. I've added 2 methods and now everything works fine.
@RequestMapping("/")
public String home() {
return "redirect:/index";
}
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String createRegisterForm(Map<String, Object> model){
model.put("userprofile", new UserProfile());
return "index";
}
A: Add modelAttribute="userProfile" to the <form:form> tag.
<form:form method="post" action="add" commandName="userProfile" modelAttribute="userProfile">
A: Try adding BindingResult as a method parameter next to @ModelAttribute("userProfile") UserProfile userProfile
Spring looks for BindingResult parameter after each @ModelAttribute
A: Adding this to your controller should fix it
model.addAttribute(new UserProfile());
A: @ModelAttribute("userProfile")
public UserProfile getProfile(){
return new UserProfile();
}
<form:form method="post" action="add" modelAttribute="userProfile">
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to code for the "." for the Use of decimal input? I am developing the calculator for android.
I have implemented all the functionality, Now just getting stop at the decimal value.
I dont know how to implement that functionality on the click of custom "." button.
I want decimal value up to two fraction point.
can anybudy help me to develop such code?
I need it. . . I know it seem very easy but right now i got stuck in that matter.
Pleae help me in this
Thanks in advance.
A: As it is, this is a very broad question. I recommend you to check this http://www.codeproject.com/KB/android/androidcalculator.aspx
Generally speaking, you need to:
1) Implement UI
2) Implement click handlers for the buttons
3) Implement evaluation function
If you get stuck at something particular ask it here and post your code.
EDIT:
There you can see how it is implemented, you can use similar logic:
case DECIMAL_SEP: // Handle decimal seperator
if (hasFinalResult || resetInput) { // if previous result is calculated or the input is reset, insert 0 before
userInputText.setText("0.");
hasFinalResult = false;
resetInput = false;
} else if (currentInput.contains(".")) // don't let 2nd '.'
return;
else
userInputText.append("."); // append '.'
break;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Best way to evaluate connection speed I'm developing an app which needs to get music file by streaming for playing live.
In the request song api I can specify the bandwith (eg: 50kbps, 100kbps, 300, 600 or 1 Mbps).
The more the bandwith is big, the more the file will get time to be fetched. As I don't want the users to be restricted about that I have multiple choices to deal with it:
*
*Detect wether the phone is using 3g, wifi or Edge and specify an bandwith for each connection speed.
*Let the user decide the quality of the song he will get: like youtube (but the users won't be people that know much about computing: the more easy is the software, the more it will fit)
*Having a way to evaluate properly the connection speed: Like fetching a file, measure the time that it took and set the bandwith.
I know that connection speed could vary a lot if user loose the wifi, or is using 3g moving in the street. And the thing is that I can't change the bandwidth when the song will be playing.
Maybe you have experience about that you would like to share?
Thank you!
A: why not try to change your view of things.
Try to flow with your users. say your user wishes to download 128 kbit quality song. you start the download , WHILE downloading you make an average download time, take a few seconds for this average to stabilize, and if it's below certain value make a pop up to tell the user that his connection is too slow for the current bandwidth and ask him if to lessen the quality or to keep downloading slowly.
This will:
*
*let the users the option to always assume they can get the best quality media.
*let u do your check in runtime and change the quality accordingly while downloading without the need to pre check.
*keeps your app simple to users.
I know i'm not answering your specific requirement, i'm just offering a different view.
A: Facebook released a library for this:
https://github.com/facebook/network-connection-class
this wasn't existing in 2011..
A: protected String doInBackground(String... urls) {
String response = "";
startTime = System.currentTimeMillis();
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
endTime = System.currentTimeMillis();
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
long dataSize = result.length() / 1024;
takenTime = endTime - startTime;
long s = takenTime / 1000;
double speed = dataSize / s;
Toast.makeText(context, "" + s + "kbps", Toast.LENGTH_SHORT).show();
}
A: Detect network connection type on Android
You can check all available options here: http://developer.android.com/reference/android/telephony/TelephonyManager.html
This can fix the mobile network type but can't help you with the Wifi speed, you should code it by downloading something from a server you know and calculate the time.
I hope it helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
}
|
Q: CAGradientLayer not smooth enough? I'm doing a CAGradientLayer for every background of my UIViews, but I have a small problem. The gradient doesn't seem that smooth enough. The transition between the colors are to present. You can see it in this picture.
This is how I implemented this gradient in the initializer of my UIView.
CAGradientLayer *layer = [CAGradientLayer layer];
layer.colors = [NSArray arrayWithObjects:
(id)[[UIColor darkKinepolisColor] CGColor],
(id)[[UIColor lightKinepolisColor] CGColor],
(id)[[UIColor lightKinepolisColor] CGColor],
(id)[[UIColor darkKinepolisColor] CGColor],
nil];
layer.locations = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0],
[NSNumber numberWithFloat:0.4],
[NSNumber numberWithFloat:0.6],
[NSNumber numberWithFloat:1],
nil];
layer.startPoint = CGPointMake(0, 0);
layer.frame = self.layer.bounds;
layer.endPoint = CGPointMake(1, 1);
layer.contentsGravity = kCAGravityResize;
[self.layer addSublayer:layer];
Could you, fine developers, help me with this problem? Thanks!
A: From what I've seen CAGradientLayer does not support dithering, but CGGradient does. See my answer here. Also see the other answers for example on using CGGradient.
A: Isn't this just a consequence of 8-bit colour values? The steps between the colours are as small as they can possibly be.
i.e. if you want a gradient between rgb(100,100,100) and rgb(109,109,109) it can only be perfectly smooth across a gradient width of 10 pixels. If you tried to draw this gradient across a width of 100 pixels you would get 10 blocks of colour 10px wide and it would look very blocky. What else could happen?
You can make it appear smoother by dithering and adding noise but there is no built in function for this.
So, either, choose colours farther apart, draw the gradient over a shorter distance or make the graphic in Photoshop and apply noise and dithering to make it appear smoother.
A: I'm developing an app that needs a base gradient, and various other gradients are faded into it, depending on various factors (eg: the time of day). I've found that I can continue to use CAGradientLayer for all but the base gradient. For the base gradient, i created it in photoshop and added 0.554% noise. Almost imperceptible, but it prevents the banding effect when I animate the alpha of CAGradientLayers above it.
So I guess the answer would be that you need dithering/noise on at least one of the gradients to avoid the banding effect. It may also be possible to add this programmatically, or by loading a pre-rendered black image with noise over a CAGradientLayer with a low alpha (~0.1f) on the noise layer.
A: Rasterize with your device's screen scale, will be very smooth and crisp!
[layer setShouldRasterize:YES];
[layer setRasterizationScale:[UIScreen mainScreen].scale];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: can not wait for some milliseconds in javascript I want to draw one line then wait for some milliseconds then draw next line again wait for next line and so on, so that its visualize that how line by line it will be drawn(like ECG waveform).
How i can do that in this code?
This is my code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var ms = 0;
var y=5;
var x=5;
var copyendx=0;
var copyendy=0;
var context;
var temp,total=0;
//var data=new Array(-1,3,-3,-7,5,1,-1,-3,2,5,7,7,7,7,1,3,3,4-,8,5,6,6,7,7);
var data=new Array(-1,3,-3,-7,5,1,-1,-3,2,5,7,7,7,7,4,7,9,2,2,8);
//alert(data);
function init() {
var graphCanvas = document.getElementById('graphSpace');
context =graphCanvas.getContext('2d');
drawgraph();
}
function drawgraph() {
drawLine(context,5,50,5,250);
drawLine(context,5,150,7,150);
// setTimeout(drawgraph(),600);
for (var i=0;i<data.length;i++) {
var startx=5+x;
var starty=150-(data[i]*y);
var endx=(5+x)+1;
var endy=150-(data[i]*y);
if (i==0) {
copyendx=endx;
copyendy=endy;
startx=5+x;
starty=150;
}
//draw line and wait for some milliseconds
setInterval(function () {
drawLine(context,startx,starty,copyendx,copyendy); }, 100);
drawLine(context,startx,starty,copyendx,copyendy);
x=x+5;
// pausecomp(100);
copyendx=endx;
copyendy=endy;
}
}
}
//Draw line function
function drawLine(contextO, startx, starty, endx, endy) {
contextO.beginPath();
contextO.moveTo(startx, starty);
contextO.lineTo(endx, endy);
contextO.closePath();
contextO.stroke();
}
</script>
</head>
<body onload="init()">
<canvas id="graphSpace" width="800" height="400" style="background-color: #ffff00;"></canvas>
</body>
</html>
I have tried with setInterval
setInterval(function () {
drawLine(context,startx,starty,copyendx,copyendy);
}, 100);
but i didn't get desired output.
I want wait for some milliseconds before calling method drawLine(contextO, startx, starty, endx, endy) for each line drawing
I got solution for above problem. i have following problem
If i want to draw more points on canvas if that points not fit on my canvas width i am redrawing the canvas but here is problem that my graph is not looking steady (as like ECG wave form applicaion) during first redraw it looks slower, during second redraw it looking faster than first redraw ,during third redraw it looks faster than second redraw and so on.
How to overcome that? I want steady flow till i draw my last graph point.
A: Basically you need to go through your loop and set up all your draw lines. Each should be N milliseconds later then the previous one, hence (i*100).
So after the loop finished one line will be drawn, the next one will be drawn in 1*100ms next one in 2*100ms and so on...
here is your code with few modifications:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var ms = 0;
var y=5;
var x=5;
var copyendx=0;
var copyendy=0;
var context;
var temp,total=0;
//var data=new Array(-1,3,-3,-7,5,1,-1,-3,2,5,7,7,7,7,1,3,3,4-,8,5,6,6,7,7);
var data=new Array(-1,3,-3,-7,5,1,-1,-3,2,5,7,7,7,7,4,7,9,2,2,8);
//alert(data);
function init() {
var graphCanvas = document.getElementById('graphSpace');
context =graphCanvas.getContext('2d');
drawgraph();
}
function drawgraph() {
drawLine(context,5,50,5,250,0);
drawLine(context,5,150,7,150,0);
for (var i=0;i<data.length;i++) {
var startx=5+x;
var starty=150-(data[i]*y);
var endx=(5+x)+1;
var endy=150-(data[i]*y);
if (i==0) {
copyendx=endx;
copyendy=endy;
startx=5+x;
starty=150;
}
//draw line and wait for some milliseconds
drawLine(context,startx,starty,copyendx,copyendy,i*100);
drawLine(context,startx,starty,copyendx,copyendy,i*100);
x=x+5;
copyendx=endx;
copyendy=endy;
}
}
//Draw line function
function drawLine(contextO, startx, starty, endx, endy,delay) {
setTimeout(function(){
contextO.beginPath();
contextO.moveTo(startx, starty);
contextO.lineTo(endx, endy);
contextO.closePath();
contextO.stroke();
},delay);
}
</script>
</head>
<body onload="init()">
<canvas id="graphSpace" width="800" height="400" style="background-color: #ffffff;"></canvas>
</body>
</html>
A: The concept of a loop with sleep(100) is something that is not designed to be done in javascript.
get rid of the loop, do something like this:
var x,y,i=0;
setTimeout(function doDraw() {
var startx=5+x;
var starty=150-(data[i]*y);
var endx=(5+x)+1;
var endy=150-(data[i]*y);
drawline(yourargs);
i++;
if (i < data.length) {
setTimeout(doDraw, 100);
}
}, 100);
A: setInterval is bad. If takes long than the interval to run, you end up with a backup of calls to run. Stick to setTimeout and call it again at the end of the block you're running.
A: This won't do. you need to pass reference to setInterval function.
function drawLine(context,startx,starty,copyendx,copyendy){}
var func = partial(drawline, context,startx,starty,copyendx,copyendy);
setInterval(func, 100);
A: try setTimeout("drawLine(context,startx,starty,copyendx,copyendy)",100);. This will delay it by 100 milliseconds.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Solving the xinetd "Transport endpoint is not connected" I'm trying to get a simple websocket proxy to work with xinetd.
The proxy is here : https://github.com/kumina/wsproxy
(basic proxy for vnc)
Here's my xinetd/wsproxy config:
service wsproxy
{
type = UNLISTED
socket_type = stream
protocol = tcp
user = root
wait = no
port = 8080
server = /usr/sbin/wsproxy
server_args = 5000 9999
disable = no
log_type = SYSLOG daemon info
flags = NOLIBWRAP
}
Also tried various changes like 'wait=yes' and 'wait=no' still the same results
i get a hundred entries like this one in syslog :
ubuntu xinetd[3707]: warning: can't get client address:...
...Transport endpoint is not connected
and finally :
xinetd[8283]: Deactivating service wsproxy due to excessive incoming connections.
xinetd is running and in netstat as well.
Pulling my hairs out, can't find why it doesn't run.
(running ubuntu 11.04 x64)
Any ideas ?
A: Are you sure the vncserver in the backend is up and running?
Even if wsproxy itself is running (check with telnet localhost 8080), if the vncserver isn't running, you might be running into this problem.
Checked with Debian Squeeze (i386) and Scientific Linux (x86_64) that your xinetd-config is correct. Works like charm.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Sencha-touch associate model in the same way JSON is nested my json output is:
{"Result":
{"Data":
[{"gmt_id":"1","gmt":"-12:00","secondsDiff":"-43200","Location":"Baker IslanIsland"},
{"gmt_id":"2","gmt":"-11:00","secondsDiff":"-39600","Location":"American Samoa, Samoa"},
{"gmt_id":"3","gmt":"-10:00","secondsDiff":"-36000","Location":"Hawaii, Papeete"}]}}
--I want my Model to be nested with Result and Data, so that on setting autoLoad:true on the store, should access key:value on the flow. But my console.log gives[]. i am wrong somewhere in my model please help!!!
--this is my model
Ext.regModel('Gmt',
{'Result':
{'Data':
[
{name:'gmt_id',type:'string'},
{name:'Location',type:'string'}
]
}
});
this is my Store to load data:
var jsonStore = new Ext.data.Store({
model: "Gmt",
proxy: {
type: 'ajax',
url: 'gmt.php',
//url: 'data.json',
method: 'GET',
// callback: console.log(response),
reader: {
type: 'json',
//root: 'Data'
root:'Result'
// type:'json'
},
afterRequest: function (request, success) {
if (success) {
console.log("success");
} else {
console.log("failed");
}
}
},
autoLoad: true
});
--access key:value parameters here
jsonStore.on('load', function(){
var lstArr = new Array();
var lstAr = new Array();
jsonStore.each(function(i) {
//var gmtdata = i.data.gmt_id;
// console.log(i);
lstArr.push(i.data.gmt_id);
lstAr.push(i.data.Location);
});
console.log(lstArr);
console.log(lstAr);
});
A: Solved it myself.
--Change the Store root
--Set 'Result.Data' as root
var jsonStore = new Ext.data.Store({
model: "Gmt",
proxy: {
type: 'ajax',
url: 'gmt.php',
//url: 'data.json',
method: 'GET',
// callback: console.log(response),
reader: {
type: 'json',
root:'Result.Data'
},
afterRequest: function (request, success) {
if (success) {
console.log("success");
} else {
console.log("failed");
}
}
},
autoLoad: true
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Application.ProductVersion is not working Application.ProductVersion is not showing the incremental version. can anybody help me how to perform this, using C# ?
A: You can have build and revision incremented for you but not major and minor.
Simply substitute
[assembly: AssemblyVersion("1.0.0.0")]
with
[assembly: AssemblyVersion("1.0.*")]
in the AssemblyInfo.cs
A: Have you tried grabbing the Assembly's version?
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
Perhaps this is what you are looking for.
Also check out this other SO post - I think this is what you are looking for.
Automatically update version number
Below is a second link to a .Net add-in that automatically increments the:
*
*Major
*Minor
*Build
*Revision
http://testdox.wordpress.com/versionupdater/
A: I have found that it works well to simply display the date of the last build using the following wherever a product version is needed:
System.IO.File.GetLastWriteTime(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString("yyyy.MM.dd.HHMM")
Rather than attempting to get the version from something like the following:
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
object[] attributes = assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyFileVersionAttribute), false);
object attribute = null;
if (attributes.Length > 0)
{
attribute = attributes[0] as System.Reflection.AssemblyFileVersionAttribute;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When is tuple length too long? Here is a logical schema for my largest relation:
{(id, uName, supplies, score, playerType, storageSupplies, supplyDrop, barracks, armourDepot, hangar, droneHangar, storage, offensive, defensive, infantry, vehicles, air, fuel, explored, morale, cash, population, tax, food, aSector, cSector, iSector, XP)}
As you can see, each tuple is going to be very long. This is starting to become very cumbersome as attributes are added. The thing is, there is only ever a 1-to-1 relationship so while it would help organisation and avoid obfuscation by breaking this relation up into smaller, meta related relations, wouldn't it add more overhead? Or should I not worry about mysql efficiency when this relation will have tens of thousands of tuples at the most, realistically.
A: 1) Assuming your table is max 10k rows, rarely updated and rarely read (compared to other entities in the database) - you are right efficiency will see no great benefit, however...
2) Every little bit counts; for example with table this small most of it can be kept in memory and you will have very fast SELECTS; if a lot of attributes are mostly NULLS then splitting the table would reduce the SIZE of it and would free RAM for other caches; reduce necessary I/O when updating (generally make the things more scalable). The expense is the slight increase of complexity (for updates, SELECTS can use a VIEW).
3) 'Overhead' for splitting 1-to-1 relations is misconception; it largely depends on the workload - you can construct cases that prefer things broken down into two smaller tables and you can construct cases that benefit from having the data stored in one table.
A:
The internal representation of a table has a maximum row size of
65,535 bytes
Eficiency depends on the MySQL version and the Storage Engine you are using. But you should know that doing this will increase data to be cached that might not be necesary.
For example, a Users table might increase if we add address data of users, and that data maybe is not needed frequently, so, spliting it into 2 tables: Users and Users_address will be more efficient becouse if the table Users is heavily read it could be cached.
There are other considerations like maintenance and index work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to sort Time in JsonParsing? I need to sort the time from the Json feed
{
"events":{
"event":[
{
}
]
}
}
can anyone help me to solve this?
A: I don't know how you want it to be sorted and how your full data looks like but here's the idea:
JSONArray jsonEvents = new JSONObject(json).getJSONArray("event");
JSONObject [] events = new JSONObject[jsonEvents.length()];
// fill an array with your events
for (int i = 0; jsonEvents.length(); i++) {
events[i] = jsonEvents.getJSONObject(i);
}
// sort them
Arrays.sort(events, new Comparator<JSONObject>() {
static final SimpleDateFormat sdfToDate = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
public int compare(JSONObject event1, JSONObject event2) {
return sdfToDate.parse(event1.getString("startTime")).compareTo(
sdfToDate.parse(event2.getString("startTime"))
}
});
A: you can use
Collections.sort(String,new Comparator<String>() {
public int compare(String arg0, String arg1) {
// TODO Auto-generated method stub
return 0;
}
});
All The Best
A: String myjson = "{"events":{"event":[{"title":"Audi urban future","startTime":"2011-09-16 00:30:00","endTime":"2011-09-22 00:35:00","description":"test","image":"http://audi.smart-media.no/wp-content/uploads/2011/09/20110919130749-medium.jpg","latitude":45.73154,"longitude":4.8592365}]}}"
JSONArray array= new JSONArray(myjson);
for(int i = 0; i < array.length; i++) {
JSONObject object = (JSONObject) array.get(i);
object.getString("startTime");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: validating email address which contains non-english (UTF-8) character in Java i am having fallowing email id
闪闪发光@闪闪发光.com
i need to validate this type of email at server side so that user can not enter this type of email..
i have solved similar problem in javascript by using below regex-
/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/gi
But. unable to do same thing in java.Please help me guys.
Thanks in advance!!!
A: The Java regular expression pattern (?i)[-a-z0-9+_][-a-z0-9+_.]*@[-a-z0-9][-a-z0-9.]*\\.[a-z]{2,6} should suffice. Here's what the pattern means:
(?i) # Case insensitive flag
[-a-z0-9+_] # First character
[-a-z0-9+_.]* # Zero or more characters
@ # Literal '@' character
[-a-z0-9] # Match a single character
[-a-z0-9.]* # Match zero or more characters
\. # Literal '.' character
[a-z]{2,6} # Match 2 through 6 alpha characters
The following test code ...
final String ps =
"(?i)[-a-z0-9+_][-a-z0-9+_.]*@[-a-z0-9][-a-z0-9.]*\\.[a-z]{2,6}";
final Pattern p = Pattern.compile(ps);
for (String s : new String[] {"foo@bar.COM", "+foo@bar.COM",
"-foo@bar.COM", "fo_o@bar.COM", "f.oo@bar.COM", "a@b.cdefgh",
"3@4.com", "3@4.5.6-7.8.com", ".foo@bar.com", "a@b.cdefghi",
"闪闪发光@闪闪发光.com"})
{
final Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println("Success: " + s);
} else {
System.out.println("Fail: " + s);
}
}
... will output:
Success: foo@bar.COM
Success: +foo@bar.COM
Success: -foo@bar.COM
Success: fo_o@bar.COM
Success: f.oo@bar.COM
Success: a@b.cdefgh
Success: 3@4.com
Success: 3@4.5.6-7.8.com
Fail: .foo@bar.com
Fail: a@b.cdefghi
Fail: 闪闪发光@闪闪发光.com
By using the Matcher.matches() method, you don't need to include the ^ start-of-line or $ end-of-line boundary matching constructs since Matcher.matches() will match on the whole string.
A: [Update] Sorry for the js code. Try this:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidator{
private Pattern pattern;
private Matcher matcher;
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@
[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public EmailValidator(){
pattern = Pattern.compile(EMAIL_PATTERN);
}
/**
* Validate hex with regular expression
* @param hex hex for validation
* @return true valid hex, false invalid hex
*/
public boolean validate(final String hex){
matcher = pattern.matcher(hex);
return matcher.matches();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: c++ generalized operator templating I'm doing some numerical simulations where it is nice to overload operations on vectors (similar to valarrays). For example, I can write
template <typename T>
vector<T> operator*(const vector<T>& A, const vector<T>& B){
//blah blah
}
But what if I want to generalize this template so as to act on two different types of vectors and (potentially) return a third type? I.e. I want to write
template <typename T, template U, template V>
vector<V> operator*(const vector<T>& A, const vector<U>& B){
//blah blah
}
Now, the above does indeed work if I use the operator in a situation "A*B" where A and B are distinct types and return a another distinct type. However, if A and B are the same type, it does not work. Certainly I could define different templates for each combination (i.e. T only, or T and U only, or T, U, and V) but that seems ugly. Is there a way I can use a single template expression of the T,U, and V variety given above and make it work even if "A", "B", and "A*B" are all the same types (or have only 2 different types?)
A:
Now, the above does indeed work if I use the operator in a situation
"A*B" where A and B are distinct and return a different type.
To be honest, this doesn't make sense. Your template shouldn't work at all because V cannot be deduced and it is the third template parameter. If you had written:
template <typename V, template T, template U>
vector<V> operator*(const vector<T>& A, const vector<U>& B){
//blah blah
}
This would "work" but only if you explicitly specified V, something like
operator*<double>(A, B); //where A is vector<int> and B is vector<float>, for example
Surely you want to return a vector<V> where V is the type of the expression T()*U(). This is possible to do in C++11, but not trivially in C++03( I mean, you could do some type-traiting at best). Here's how it's done in C++11:
template <typename T, template U>
vector<decltype(T()*U())> operator*(const vector<T>& A, const vector<U>& B)
{
//blah blah
}
HTH
A: This can work in C++0x with decltype.
template <typename T, template U>
vector<decltype(declval<T>() + declval<U>())>
operator*(const vector<T>& A, const vector<U>& B){
//blah blah
}
Without using this mechanism- and presuming that T and U do not provide their own mechanism- you can't do something like this. You can only handle the situation where T, U, and the return type are all the same type. You can, however, deal with primitive types- there's a Boost type trait for the result of applying operators like + to various primitive types to find the promoted type.
A: As others have pointed out you can use decltype to achieve this. C++0x also provides the template common_type which deduces a type to which all it template arguments can be coerced without any specific arithmetic operation. So it can also be used if no overloaded operators are available for the argument types.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Faster random generator in Tomcat 7 I have the problem that Tomcat 7 is terribly slow on startup. I found this in the log file:
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [12,367] milliseconds.
Security is important, sure, but not on my development machine. I could perfectly live with a standard fast random number generator. So I don't need this ridiculously slow SecureRandom implementation.
Question is: How can I disable it? Is searched for a solution but only found some deprecated info about a randomClass attribute which can be set to java.util.Random. I also found out that this attribute seems to be named secureRandomClass now in Tomcat 7. I tried to set it to java.util.Random but this fails because Tomcat 7 casts the object to java.util.SecureRandom (And it's also documented that the specified class must extend java.util.SecureRandom, so it's no longer possible to use java.util.Random instead.)
So how can I get rid of this terribly slow random number generator startup so my development tomcat starts/restarts as fast as possible?
A: You might need to install Haveged on your server.
Tomcat is using SecureRandom to generate secure id on startup, and SecureRandom is using /dev/random or /dev/urandom to generate random number.
In some headless linux environment, /dev/random entropy pools might produce low quality of randomness and respond very slow on generating random number.
There is good article on explaining how Haveged can solve this problem.
how-to-setup-additional-entropy-for-cloud-servers-using-haveged
A: You probably need to patch Tomcat.
Though as a hack, you could always try extending java.util.SecureRandom with something that wraps a standard java.util.Random instance....... this would get past the cast problem at least.
One other thought.... could the slowdown be due to an exhausted entropy pool? You might want to try getting more entropy into the pool, this might make it go really fast.
A: just find securerandom.source=... from $JAVA_PATH/jre/lib/security/java.security file and change it as securerandom.source=file:/dev/./urandom
https://stackoverflow.com/a/26432537/450586
A: According to TomCat Wiki you can use non blocking entropy source:
"There is a way to configure JRE to use a non-blocking entropy source by setting the following system property: -Djava.security.egd=file:/dev/./urandom"
A: Old problem, but still around... In my case with an embedded Tomcat.
The -Djava.security.egd=file:/dev/./urandom solution did not work for me. So I googled until understanding the issue, but after a few tests with lsof it was apparent that the workaround doesn't work anymore. A quick look at the code confirmed that the current implementation ignores this system property.
The problem is Tomcat blocking on /dev/random, so I looked for ways to add entropy to the system and found this answer which worked great! In Debian as root:
apt-get install rng-tools
rngd -r /dev/urandom # Run once during system start up
It may not be as super-duper-secure, but in my opinion is more that enough for session id generation.
By the way, I ended up using Jetty. Much quicker if you don't need all the features of Tomcat.
A: If your hardware supports it try using Java RdRand Utility available at:
http://code.google.com/p/lizalab-rdrand-util/
Its based on Intel's RDRAND instruction and is about 10 times faster than SecureRandom and no bandwidth issues for large volume implementation.
Full disclosure, I'm the author of the utility.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Code::Blocks console app won't show output I've got an application in Code::Blocks, and it's the simple Hello, World traditional program.
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
}
The program builds and executes, but the output isn't shown. I checked the project properties in Code::Blocks and it is definitely set to console application. Any suggestions as to the problem?
Edit: The output only fails in the IDE. When run separately the resulting executable functions exactly as expected.
A: It's possible that you don't have xterm installed it.
If you are on Linux (Debian flavor) you can install it with your package manager like so:
sudo apt-get install xterm
A: Maybe you need to set the terminal to launch the console applications. It can be done in the general environment settings.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How can I cut off results in a full-text (boolean mode) search? I'm using a boolean mode full-text search:
SELECT *, match(Tournament.Name) against ('query' in boolean mode) as score FROM `tournaments` AS `Tournament` WHERE 1 =1 ORDER BY `score` desc LIMIT 20
What I wanted to do was to change the where clause to contain something like score > 0.5, but this threw an error about score being an unknown column.
Is there a way around this? Or is my method flawed?
EDIT: For example, say I search for "cheese", I get the following results:
*
*Cheese is great
*I love cheese
*Cheese ftw
*Cake is nice too
*Anyone for a cuppa?
The query has successfully sorted the matches to the top (they have good scores), but the others (with scores of 0) are left in the result set. I want to filter out these low scoring results.
A: Rick James answered this over at the MySQL dev forums.
He wrote:
"score" is derived, so it cannot be in WHERE. Use HAVING instead of
WHERE in this situation
SELECT ... AS score
FROM ...
WHERE ...
HAVING score > 0.5
ORDER BY score DESC
A: I suggest you have a look at the basic mysql functions, to extract substrings from strings and convert them into a number. You can use them in you were clause and compare the result to 0.5
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How and why can a Semaphore give out more permits than it was initialized with? I am reading the book Java Concurrency in Practice. In a section about java.util.concurrent.Semaphore, the below lines are present in the book. It is a comment about its implementation of "virtual permit" objects
The implementation has no actual permit objects, and Semaphore does
not associate dispensed permits with threads, so a permit acquired in
one thread can be released from another thread. You can think of
acquire as consuming a permit and release as creating one; a
Semaphore is not limited to the number of permits it was created with.
Can somebody explain this? I am having trouble understanding this. If we create a pool of fixed size, we create a fixed number of "permits". From the above statement, it looks like the "permits" can keep growing. Why is it designed this way?
A:
Can somebody explain this ? From the above statement, it looks like the "permits" can keep growing.
A semaphore is a counter of permits. acquire is like decrement which waits rather than go below zero. It has no upper limit.
Why is it designed this way ?
Because its simple to do so.
A: I think that it means the times what we may require Semaphore as the times we released "extra" and plus the permits it created with.
Such as:
Semaphore s = new Semaphore(1); // one permit when initialize
s.acquire();
s.release();
s.release(); // "extra" release.
At this moment, this semaphore allows one permit originally and one "extra" permit
A: As mentioned in first post "Semaphore is not limited to the number of permits it was created with"
Every call to .release() API will increase the permit count by one. So Semaphores doesn't have a fixed permit size
A: Instead of "handing out" permit objects, the implementation just has a counter. When a new permit is "created" the counter is increased, when a permit is "returned" the counter is decreased.
This makes for much better performance than creating actual objects all the time.
The tradeoff is that the Semaphore itself cannot detect certain kinds of programming errors (such as unauthorized permit cash-ins, or semaphore leaks). As the coder, you have to make sure to follow the rules on your own.
A: Perhaps the last line " a Semaphore is not limited to the number of permits it was created with" is your source of confusion.
A semaphore when created is initialized with a fixed set of permits. This then becomes the maximum number of permits that the semaphore can simultaneuosly dispense at any time during the life time of that semaphore. You cannot dynamically increase this number except by re-initializing the semaphore .
The meaning if the quoted line ( from JCIP ) is this : First , the semantics of how a semaphore works is not limited to the details of issuing and regaining a permit - this is manifested in the fact that any thread can that has access the semaphore can have a permit released ( even though this thread did not own the permit at the first place)
Second , you can dynamically reduce the maximum permits of a semaphore - by calling reducePermits(int) method.
A: It is surprising to some of us.
You can easily subclass up a bounded semaphore.
/**
* Terrible performance bounded semaphore.
**/
public class BoundedSemaphore extends Semaphore {
private static final long serialVersionUID = -570124236163243243L;
final int bound;
public BoundedSemaphore(int permits) {
super(permits);
bound=permits;
}
@Override
synchronized public void acquire() throws InterruptedException {
super.acquire();
}
@Override
synchronized public boolean tryAcquire() {
return super.tryAcquire();
}
@Override
synchronized public void release() {
if( availablePermits()<bound){
super.release();
}
}
@Override
synchronized public void acquire(int count) throws InterruptedException {
super.acquire(count);
}
@Override
synchronized public boolean tryAcquire(int count) {
return super.tryAcquire(count);
}
@Override
synchronized public void release(int count) {
if( availablePermits()<bound){
super.release(bound-availablePermits());
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Adding a Custom Webpart to a Site Template in Sharepoint 2010 I tried to add a custom created webpart to a customized team site which I then saved as a template. The webpart in question worked fine with the original site. However, when I created a new site based on this template(within the same server that the webpart in question was deployed to) the area which was supposed to contain the webpart was blank. Is there anything I'm missing or is it not possible to deploy a custom webpart into a custom site template?
A: Just guessing here because I haven't tried it but when you add a webpart to the page you are essentially customizing that page for that specific site. The webpart location is stored in the content database just for that individual page.
When you save a site as a template you are just saving the structure so when you provision a new site the customized page isn't there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: android google map route between 2 point I want to draw route between 2 points in Google map with a pin mark at ends points. in this, user can choose any driving route like by car, by cycle, by walk. I have to show routing information like "2 miles ahead , left from next street" and also estimated time.so regarding this , I found a lot of tutorial on the internet. the best I found is:
http://code.google.com/p/j2memaprouteprovider/source/browse/#svn/trunk/J2MEMapRouteAndroidEx
which is very complex and slow.
next I found this one:
http://www.anddev.org/google_driving_directions_-_mapview_overlayed-t826.html
this one is very similar to what I want, except some feature. but it is outdated.
I also found that I have to use KML for this. but i don't want to use it because of complexity so is it necessary to use KML? is there any better way to do this? can i have full source code as I got confused by seeing chunk of code. thanks a lot in advance,.
A: rock,
The simplest solution for this is to open "Google Map Application" that is already installed in android device. Just pass the source and target location's latitude and longitude as a parameter and call the google map application as follows:
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr="+latitude_source+","+longitude_source+"&daddr="+latitude_dest+","+longitude_dest));
startActivity(i);
Using this approach, you can also choose any driving route like by car, by cycle, by walk etc and other functionalities that is provided by application.
A: Google Directions API contains everything you need. I found it easier to learn how the service works before looking at any complete source code.
Basically you will have to execute a UrlConnection and read the input stream. If you paste a basic request into a browser, you can see how your input stream would look like. Ex:
http://maps.googleapis.com/maps/api/directions/xml?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false
The result contains everything you would need but you will have to parse the result for information like step by step directions. Also the node called "overview_polyline" is what you would use to draw a complete route on the MapView. You could use the formula here to decode that polyline into a list of coordinates.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: The cursor:pointer property doesn't apply to file upload buttons in Webkit browsers i have CSS code that does not really work on webkit browsers such as safari and chrome
if you want live example here it is http://jsfiddle.net/mnjKX/1/
i have this CSS code
.file-wrapper {
cursor: pointer;
display: inline-block;
overflow: hidden;
position: relative;
}
.file-wrapper input {
cursor: pointer;
font-size: 100px;
height: 100%;
filter: alpha(opacity=1);
-moz-opacity: 0.01;
opacity: 0.01;
position: absolute;
right: 0;
top: 0;
}
.file-wrapper .button {
background: #79130e;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
color: #fff;
cursor: pointer;
display: inline-block;
font-size: 11px;
font-weight: bold;
margin-right: 5px;
padding: 4px 18px;
text-transform: uppercase;
}
and this HTML code :
<span class="file-wrapper">
<input type="file" name="photo" id="photo" />
<span class="button">Choose a Photo</span>
</span>
this code shows hidden input file tag ,
the problem here is that the cursor:pointer is does not work on webkit browsers ,
how can i solve it or bypass / overtake this ?
A: For starters, it works in Chrome if you remove the height declaration from the input rule.
Live demo: http://jsfiddle.net/mnjKX/16/
But this transparent input field is a hell of a hack... I wouldn't rely on it.
Update:
And here is the proper solution:
::-webkit-file-upload-button { cursor:pointer; }
I thought the file upload button is unreachable, but Chrome's user agent style sheet proved my wrong :)
A: input[type='file']{
opacity: 0;
cursor: pointer;
width: 24px;
height: 24px;
font-size: 0;
position: absolute;
}
<input type="file">
<img width="24" height="24" title="" alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAADs0lEQVR42rWVa2iOYRjH9+zd+dw2oWaGwkjzRY5flDC1nBaxsTnVYkaWc8oHoZalETWHsVGkZo0yIyEmGzkWpZhDbBhmxE7v63fp/0j7YGq89e/+XfdzuJ7/dV/3/Tp+//nndHdD2o4RIQHBnilgIPL3+XytjuO0MkZ4O3zllevve3uUYMaulDxeePL0mruNXeaTmJ/IfMlfJZhekBLv+PuNBEPRq8427wN/jxPmeJxM4seoAH0yF+g9WonmVOTfK+o2weTNyZ6w2KC9fNFuQtz7AuF0+DV8Ft4GZ6OvxPXE7xlLGZ8wF4CLK39MMLNwZDoPJPPAHcJwOAiOhp/Ct+Ba3d9J/I3YEjUzTmNuNuwHd8DtcAg8FK4ica2jeuYyFKM4cyB1aGEz0BoUYw6QLWoEakLLUY25UOl+foSubaB8O1wHmWS+R+YadUojbEmi4WjYo4Rv5SCWMdic2LzYEjfBAXAynImDI78nqOXCWcIk2KsHgmB/+ARs6/BE8UDGuYw5KmkbfA5O1QckwfNJUOqWaCnDdVRuL5WsXO1oobrIXpYgJ9W6N9VKgdZRjmreUwqPReYgg7mjroMlZL5K5v2E8XA/2JKshc9okfui78QNxLaYdxgteQkcCVfCW+HX8LiuDqwFr6Ey1B/1Rm/QMJSP8lCkus4cNNheQbt032G5s4+qR8PRIhwccB1kk/kmmSsIB8GdcDVfkEbyU/B45ntZt3Ctg9icfGQ8zdwW+AY8WG36UA7m8XyZm2CxbrqkElmC2/AE+DKcCMeaC/W8nUUtWthVcJ0WtlXNMhmeS4LjXbvoolmF22ErwSh4BTzTuguFaRPadm9iXG0NAFfA1hQvtEaT4CwSHHLXYBHDLWQJ4lXnp2ifuuUYStRC2zPB6LwdYagQzdImeydNtaOFNTjoOsiSTXuot3q9BW6Bc+E62Hb7EOJQ4irGYsY5zO2E4+FmrYE5GA0vsJPWTbBMtbZWG6AyeJXgkxbTDsKXWoPBKp3tn2DY0c5vhp/BY7TIv9p0idrUNlAfnS3uUW6J3uqsaZM8OnPsQAyRfLr3g1rd2rTYdZAjB0WyGadzphHuBQfqhd+I39jX6p5OObCjIspaWQ7NQQ4OitwEm7hQRMYvfv/gx/vM2UIS7HFLtFG7tUUd1C67Udqdn63HVYpoufmuebtuR/kXlS9cu3w7H3zBTWB/laOxlqDNlABbu37VUWw9bn+lIdrBnxljbMPpno/6w7Hj/B383E4GEjzq9k+/p78fan0xNyGwEGgAAAAASUVORK5CYII=" />
cursor:pointer does not work on input file just because of the default button. No special reason here. You need to remove its appearance via this code, pay attention with font-size:0.
It works perfectly on Chrome, Firefox and IE for me. I hope, this will also help you.
A: An interesting (cross-browser) solution I came up with:
Give the input a CSS property of cursor:pointer, place the input in a div (with overflow:hidden) and give the input a left padding of 100%. The padded area will have the pointer property.
I personally don't trust -webkit and -moz fixes because I feel like they are arbitrary and temporary, and will be replaced soon.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: Why am I getting an AttributeError when trying to print out I am learning about urllib2 by following this tutorial http://docs.python.org/howto/urllib2.html#urlerror Running the code below yields a different outcome from the tutorial
import urllib2
req = urllib2.Request('http://www.pretend-o-server.org')
try:
urllib2.urlopen(req)
except urllib2.URLError, e:
print e.reason
Python interpreter spits this back
Traceback (most recent call last):
File "urlerror.py", line 8, in <module>
print e.reason
AttributeError: 'HTTPError' object has no attribute 'reason'
How come this is happening?
UPDATE
When I try to print out the code attribute it works fine
import urllib2
req = urllib2.Request('http://www.pretend-o-server.org')
try:
urllib2.urlopen(req)
except urllib2.URLError, e:
print e.code
A: Depending on the error type, the object e may or may not carry that attribute.
In the link you provided there is a more complete example:
Number 2
from urllib2 import Request, urlopen, URLError
req = Request(someurl)
try:
response = urlopen(req)
except URLError, e:
if hasattr(e, 'reason'): # <--
print 'We failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'): # <--
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
else:
# everything is fine
A: Because there is no such attribute. Try:
print str(e)
and you will get nice:
HTTP Error 404: Not Found
A: The reason I got the AttributeError was because I was using OpenDNS. Apparently even when you pass in a bogus URL, OpenDNS treats it like it exists. So after switching to Googles DNS server, I am getting the expected result which is:
[Errno -2] Name or service not known
Also I should mention the traceback I got for running this code which is everything excluding try and except
from urllib2 import Request, urlopen, URLError, HTTPError
req = Request('http://www.pretend_server.com')
urlopen(req)
is this
Traceback (most recent call last):
File "urlerror.py", line 5, in <module>
urlopen(req)
File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.6/urllib2.py", line 397, in open
response = meth(req, response)
File "/usr/lib/python2.6/urllib2.py", line 510, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.6/urllib2.py", line 435, in error
return self._call_chain(*args)
File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain
result = func(*args)
File "/usr/lib/python2.6/urllib2.py", line 518, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found
which a kind gentle(wo)man? from IRC #python told me was highly strange and then asked if I was using OpenDNS to which I replied yes. So they suggested I switch it to Google's which I proceeded to do.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Winforms Combobox - do not allow user to edit items This is probably something simple. The winforms combobox items by default can be edited by the user, how to disable this?
A: Set DropDownStyle = DropDownList.
A: Set the ComboBox style to ComboBoxStyle.DropDownList
A: Set the ComboBox.DropDownStyle to DropDownList.
ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
Specifies that the list is displayed by clicking the down arrow and
that the text portion is not editable. This means that the user cannot
enter a new value. Only values already in the list can be selected.
A: Try setting the DropDownStyle property to DropDownList. Style of Simple makes it like a listbox, Combobox is what you are seeing allowing editing, and DropDownList only allows user to select.
A: two Method that help you Stop User to not Edit DropDownList:
A. using Programming code:
DropDownListName.DropDownStyle = ComboBoxStyle.DropDownList;\
B. using Design properties of Visual Studio
Set DropDownStyle = DropDownList.
I hope this well help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: Calculating Reciprocals: n**(-1) or (1/n)? In random.py's source code, there is the following constant definition:
BPF = 53 # Number of bits in a float
RECIP_BPF = 2**-BPF
I'm no math major, but isn't it more readable to invert BPF by placing a 1 over it?
Or is there something about multiplication that is more convenient than division in programming?
Nevermind.
In an effort to clean up my question I found this:
"On many machines, particularly those without hardware support for division, division is a slower operation than multiplication, so this approach can yield a considerable speedup. The first step is relatively slow but only needs to be done once."
http://en.wikipedia.org/wiki/Multiplicative_inverse
A: RECIP_BPF, despite its name, is not 1/BPF. It is 1/(2^BPF). I can't speak for everyone, but I find it easier to read as 2**-BPF than I would as 1.0/2**BPF.
Note that the speed of multiplication and division is not really relevant here; in particular, since these are constants, a compiler or interpreter only needs to evaluate them once (and a compiler can even do it at compile time). Moreover, since these are exact powers of two, there are direct ways to produce the result without doing either multiplication or division, using the fact that floating-point uses a binary encoding.
A: "2**-BPF" means 2 raised to the -BPF power.
A: Redability is subjective. That said, I personally find 2**-BPF easier to read than 1.0/2**BPF (with or without parentheses around 2**BFP).
As to performance differences, I doubt they are relevant since the expression is only evaluated once, when the module is imported.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Calling function to execute javascript code I would like to place a javascript (adsense) code inside the post (not above or after the post). It will be a HTML page.
Is there any way i can put my adsense code in external Js file and i will use one function to display it.
adsense code looks something like
<script type="text/javascript"><!--
google_ad_client = "pub-xxxxxxxxxxxxxxxx";
google_ad_host = "pub-xxxxxxxxxxxxxxxx";
google_ad_slot = "xxxxxxxxxx";
google_ad_width = 336;
google_ad_height = 280;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
So if i call a function CallMe() which will start showing ad wherever i have used the function. In future if i would like to replace ad code with another code then i dont want to go to each post and replace it. I will just replace the adcode from js file.
I am a newbie and have just started learning JavaScript so i am really not aware if it can be done or not.
Any suggestion ?
A: Create file called AdSense.js with the following code:
google_ad_client = "pub-xxxxxxxxxxxxxxxx";
google_ad_host = "pub-xxxxxxxxxxxxxxxx";
google_ad_slot = "xxxxxxxxxx";
google_ad_width = 336;
google_ad_height = 280;
function ApplyAdSense() {
var oScript = document.createElement("script");
oScript.type = "text/javascript";
oScript.src = "http://pagead2.googlesyndication.com/pagead/show_ads.js";
document.getElementsByTagName("head")[0].appendChild(oScript);
}
Now whenever you want adsense in your code, first include the file:
<script type="text/javascript" src="AdSense.js"></script>
Then call the function:
<script type="text/javascript">
ApplyAdSense();
</script>
This way, until you call the function nothing happens.. and you can also comment the code inside the function to disable adsense throughout all your site.
A: Wherever you want the ad to show up, place this code (assuming you have a function called CallMe).
<some html>
<script type="text/javascript">CallMe();</script>
</some html>
A: If your concern is about the page loading time, Adsense released the asynchronous version of their Adsense code. Please see https://support.google.com/adsense/answer/3221666?hl=en
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Website Downloader using Python I am trying to create a website downloader using python. I have the code for:
*
*Finding all URLs from a page
*Downloading a given URL
What I have to do is to recursively download a page, and if there's any other link in that page, I need to download them also. I tried combining the above two functions, but recursion thing doesn't work.
The codes are given below:
1)
*from sgmllib import SGMLParser
class URLLister(SGMLParser):
def reset(self):
SGMLParser.reset(self)
self.urls = []
def start_a(self, attrs):
href = [v for k, v in attrs if k=='href']
if href:
self.urls.extend(href)
if __name__ == "__main__":
import urllib
wanted_url=raw_input("Enter the URL: ")
usock = urllib.urlopen(wanted_url)
parser = URLLister()
parser.feed(usock.read())
parser.close()
usock.close()
for url in parser.urls: download(url)*
2) where download(url) function is defined as follows:
*def download(url):
import urllib
webFile = urllib.urlopen(url)
localFile = open(url.split('/')[-1], 'w')
localFile.write(webFile.read())
webFile.close()
localFile.close()
a=raw_input("Enter the URL")
download(a)
print "Done"*
Kindly help me on how to combine these two codes to "recursively" download the new links on a webpage that's being downloaded.
A: You may want to look into the Scrapy library.
It would make a task like this pretty trivial, and allow you to download multiple pages concurrently.
A: done_url = []
def download(url):
if url in done_url:return
...download url code...
done_url.append(url)
urls = sone_function_to_fetch_urls_from_this_page()
for url in urls:download(url)
This is a very sad/bad code. For example you will need to check if the url is within the domain you want to crawl or not. However, you asked for recursive.
Be mindful of the recursion depth.
There are just so many things wrong with my solution. :P
You must try some crawling library like Scrapy or something.
A: Generally, the idea is this:
def get_links_recursive(document, current_depth, max_depth):
links = document.get_links()
for link in links:
downloaded = link.download()
if current_depth < max_depth:
get_links_recursive(downloaded, depth-1, max_depth)
Call get_links_recursive(document, 0, 3) to get things started.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: masked own parameter in Symfony routing If i will make own link in symfony:
http://www.mypage.com/phone/show/id/1
for:
http://www.mypage.com/linksone
in routing:
linksone:
url: /linksone
param: { module: phone, action: show, id: 1 }
what if i use own parameter in URL?
how example:
http://www.mypage.com/phone/show?number=3
i dont have change this link for
http://www.mypage.com/phone/show/number/3
i must use:
http://www.mypage.com/phone/show?number=3 - with /number/3 doesnt work.
is possible make routing with own parameter?
linksone:
url: /linksone
param: { module: phone, action: show, number: 3 }
doesnt work
A: This page in the "Practical Symfony" tutorial explains the routing in Symfony: http://www.symfony-project.org/jobeet/1_4/Doctrine/en/05
You can introduce parameters in your URL like this:
linksone:
url: /phone/show/:number
param: { module: phone, action: show }
If you want to make the :number parameter optional, you can add the default value to the param option:
linksone:
url: /phone/show/:number
param: { module: phone, action: show, number: 1 }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: .net 2.0 winform control in asp.net I want to use .net winform control in asp.net.I wrote the control and displays in asp.net.Is it necessary I have to create a package and deploy in client machine? or since .net framework available in client machine without package it will work.
A: While this is possible, by hosting a UserControl as Active-X - I generally don't recommend it for a variety of reasons:
*
*It's basically an Active-X control. There have been a lot of security concerns around this technology.
*It will only work in Internet Explorer. Internet Explorer has been hemorrhaging market share over the past few years.
*Generally it's possible to achieve what you want using JavaScript + HTML. What specific example can you think of where current web standards cannot solve it?
You can learn more about using a WinForm UserControl as an Active-X object here.
In reality, you are better off using browser-based technologies, such as HTML, JavaScript, SVG, etc. If that isn't good enough - then alternative technologies like Silverlight are a much better choice. It's cross-platform, more modern, and designed to run in the browser.
A: You can not do what you are wanting to do. WinForms controls have no way to render as HTML.
A: This blog explains how to do it, especially how to package the dll and deploy it (using gacutil).
And, obviously, you will have to have the .net framework on the client computer.
However, in the 2010's I'd would highly suggest you to use more manageable tools, like SilverLigth, Flash, or event Html + Javascript (jQuery is your friend)
A: You can't use a WinForms control in ASP.Net.
ASP.Net controls render to html on a webpage. WinForms controls run in a message loop on the client machine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Neural Network based ranking of documents I'm planning of implementing a document ranker which uses neural networks. How can one rate a document by taking in to consideration the ratings of similar articles?. Any good python libraries for doing this?. Can anyone recommend a good book for AI, with python code.
EDIT
I'm planning to make a recommendation engine which would make recommendations from similar users as well as using the data clustered using tags. User would be given chance to vote for articles. There will be about hundred thousand articles. Documents would be clustered based on their tags. Given a keyword articles would be fetched based on their tags and passed through a neural network for ranking.
A: Packages
If you're not committed to neural networks, I've had good luck with SVM, and k-means clustering might also be helpful. Both of these are provided by Milk. It also does Stepwise Discriminant Analysis for feature selection, which will definitely be useful to you if you're trying to find similar documents by topic.
God help you if you choose this route, but the ROOT framework has a powerful machine learning package called TMVA that provides a large number of classification methods, including SVM, NN, and Boosted Decision Trees (also possibly a good option). I haven't used it, but pyROOT provides python bindings to ROOT functionality. To be fair, when I first used ROOT I had no C++ knowledge and was in over my head conceptually too, so this might actually be amazing for you. ROOT has a HUGE number of data processing tools.
(NB: I've also written a fairly accurate document language identifier using chi-squared feature selection and cosine matching. Obviously your problem is harder, but consider that you might not need very hefty tools for it.)
Storage vs Processing
You mention in your question that:
...articles would be fetched based on their tags and passed through a neural network for ranking.
Just as another NB, one thing you should know about machine learning is that processes like training and evaluating tend to take a while. You should probably consider ranking all documents for each tag only once (assuming you know all the tags) and storing the results. For machine learning generally, it's much better to use more storage than more processing.
Now to your specific case. You don't say how many tags you have, so let's assume you have 1000, for roundness. If you store the results of your ranking for each doc on each tag, that gives you 100 million floats to store. That's a lot of data, and calculating them all will take a while, but retrieving them is very fast. If instead you recalculate the ranking for each document on demand, you have to do 1000 passes of it, one for each tag. Depending on the kind of operations you're doing and the size of your docs, that could take a few seconds to a few minutes. If the process is simple enough that you can wait for your code to do several of these evaluations on demand without getting bored, then go for it, but you should time this process before making any design decisions / writing code you won't want to use.
Good luck!
A: If I understand correctly, your task is something related to Collaborative filtering. There are many possible approaches to this problem; I suggest you follow the wikipedia page to have an overview of the main approaches you can choose.
For your project work I can suggest looking at Python based intro to Neural Networks with a simple BackProp NN implementation and a classification example. This is not "the" solution, but perhaps you can build your system out of that example without the need for a bigger framework.
A: You might want to check out PyBrain.
A: The problem you are trying to solve is called "collaborative filtering".
Neural Networks
One state-of-the-art neural network method is Deep Belief Networks and Restricted Boltzman Machines. For a fast python implementation for a GPU (CUDA) see here. Another option is PyBrain.
Academic papers on your specific problem:
*
*This is probably the state-of-the-art of neural networks and collaborative filtering (of movies):
Salakhutdinov, R., Mnih, A. Hinton, G, Restricted Boltzman
Machines for Collaborative Filtering, To appear in
Proceedings of the 24th International Conference on
Machine Learning 2007.
PDF
*A Hopfield network implemented in Python:
Huang, Z. and Chen, H. and Zeng, D. Applying associative retrieval techniques to alleviate the sparsity problem in collaborative filtering.
ACM Transactions on Information Systems (TOIS), 22, 1,116--142, 2004, ACM. PDF
*A thesis on collaborative filtering with Restricted Boltzman Machines (they say Python is not practical for the job):
G. Louppe. Collaborative filtering: Scalable
approaches using restricted Boltzmann machines.
Master's thesis, Universite de Liege, 2010.
PDF
Neural networks are not currently the state-of-the-art in collaborative filtering. And they are not the simplest, wide-spread solutions. Regarding your comment about the reason for using NNs being having too little data, neural networks don't have an inherent advantage/disadvantage in that case. Therefore, you might want to consider simpler Machine Learning approaches.
Other Machine Learning Techniques
The best methods today mix k-Nearest Neighbors and Matrix Factorization.
If you are locked on Python, take a look at pysuggest (a Python wrapper for the SUGGEST recommendation engine) and PyRSVD (primarily aimed at applications in collaborative filtering, in particular the Netflix competition).
If you are open to try other open source technologies look at: Open Source collaborative filtering frameworks and http://www.infoanarchy.org/en/Collaborative_Filtering.
A: The FANN library also looks promising.
A: I am not really sure if a neural networks are the best way to solve this. I think Euclidean Distance Score or Pearson Correlation Score combined with item or user based filtering would be a good start.
An excellent book on the topic is: Programming Collective Intelligence from Toby Segaran
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: MonoTouch 4.2 does not support System.ServiceModel.EndpointAddress() when running on the device (works on the simulator) I am using MonoTouch 4.2.1 with MonoDevelop 2.8 Beta 2 and XCode 4. We are trying to call a .Net web service method through classes generated by the slsvcutil proxy generator.
When testing the app on the iPhone simulator, the code is working and we succeed to connect to the server and send web services requests.
However, when testing the app on a device (iPhone 4 with iOS 4.3.5), the app fails to connect to the server when calling System.ServiceModel.EndpointAddress() constructor.
Note that it was working fine with MonoTouch 4.0.7.
we get the error:
Attempting to JIT compile method 'System.Linq.Enumerable:FirstOrDefault<System.ServiceModel.Description.OperationDescription> (System.Collections.Generic.IEnumerable`1<System.ServiceModel.Description.OperationDescription>,System.Func`2<System.ServiceModel.Description.OperationDescription, bool>)' while running with --aot-only.
It is the following line that seems to crash:
new System.ServiceModel.EndpointAddress(
string.Format(System.Globalization.CultureInfo.InvariantCulture, "http://{0}:{1}/Dartfish/RemoteControlServices/",
address, port)));
Error stack:
[ERROR] FATAL UNHANDLED EXCEPTION: System.ExecutionEngineException: Attempting to JIT compile method
'System.Linq.Enumerable:FirstOrDefault<System.ServiceModel.Description.OperationDescription> (System.Collections.Generic.IEnumerable`1<System.ServiceModel.Description.OperationDescription>,System.Func`2 System.ServiceModel.Description.OperationDescription, bool)' while running with --aot-only.
at System.ServiceModel.Description.ContractDescriptionGenerator.GetOrCreateOperation (System.ServiceModel.Description.ContractDescription cd, System.Reflection.MethodInfo mi, System.Reflection.MethodInfo serviceMethod, System.ServiceModel.OperationContractAttribute oca, System.Type asyncReturnType, Boolean isCallback, System.Type givenServiceType)
at System.ServiceModel.Description.ContractDescriptionGenerator.FillOperationsForInterface (System.ServiceModel.Description.ContractDescription cd, System.Type exactContractType, System.Type givenServiceType, Boolean isCallback)
at System.ServiceModel.Description.ContractDescriptionGenerator.GetContractInternal (System.Type givenContractType, System.Type givenServiceType, System.Type serviceTypeForCallback)
at System.ServiceModel.Description.ContractDescriptionGenerator.GetContract (System.Type givenContractType, System.Type givenServiceType, System.Type serviceTypeForCallback)
at System.ServiceModel.Description.ContractDescriptionGenerator.GetContract (System.Type givenContractType, System.Type givenServiceType)
at System.ServiceModel.Description.ContractDescriptionGenerator.GetContract (System.Type contractType)
at System.ServiceModel.Description.ContractDescription.GetContract (System.Type contractType)
at System.ServiceModel.ChannelFactory`1[ICommandMgr].CreateDescription ()
m.ServiceModel.ChannelFactory`1[ICommandMgr]..ctor (System.Type type)
at System.ServiceModel.ChannelFactory`1[ICommandMgr]..ctor (System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress)
at System.ServiceModel.ClientBase`1[ICommandMgr].Initialize (System.ServiceModel.InstanceContext instance, System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress)
at System.ServiceModel.ClientBase`1[ICommandMgr]..ctor (System.ServiceModel.InstanceContext instance, System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress)
at System.ServiceModel.ClientBase`1[ICommandMgr]..ctor (System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress)
at CommandMgrClient..ctor (System.ServiceModel.Channels.
at Dartfish.ViewModel.RemoteControlViewModel.ProxyTransportViewModel.DoCommandMgrOpenAsync (System.String address, Int32 port)
It's don't seems to be a compiler issue since compiler option is "Link SDK assemblies only" as it should be. Someone know how to fix this crash or if is a new MonoTouch limitation/a bug in the last MonoTouch version?
A:
Someone know how to fix this crash or if is a new MonoTouch
limitation/a bug in the last MonoTouch version?
Have you tried the current version and/or contacted the support personal for MonoTouch? Your only question seems like it would better directed at the support staff at MonoTouch and not here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to use if else conditon on button press based on image of button? I am trying to use some logics on the base of button click.i use button as checkmark and when i click on this check mark the image of button changed into checked.png or unchecked.png.On that basis i use this code...
if([UIImage imageNamed:@"checkbox_ticked.png"])
{
isActiveStr=[arrayPickerData objectAtIndex:17];
NSLog(@" is active value is %@ ",isActiveStr);
isActiveStr=nil;
}
else
{
NSLog(@"no vlaue send");
isActiveStr=[[NSMutableString alloc]initWithString:@"1"];
NSLog(@" is active value %@",isActiveStr);
}
Now i dont know how to use the else condtion...i run this code but it always run only if codition.It never goes in else conditon.I want that i codtion is true it goes in if part and when condition is false it goes in else part.And how i use image property of button to check the condition.
A: You have to have a flag variable that holds the status of the button(checked/unchecked).
BOOL checked;
And, you have to update it when ever you click on the the button.
- (void)onButtonTapped:(UIButton *)button {
checked = !checked;
...
}
And change your if statement like this,
if (checked) {
// The button is checked
} else {
// The button is not checked
}
A: Try this if statement:
if ([[myButton imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:@"checkbox_ticked.png"]]) {
...
But as for me this is bad approach, better to have some bool flag that indicate that button is checked.
A: the if condition will always evaluate true. You should instead check for [myButton state] to see if it's enabled or not. You may have to add an IBOutlet or IBAction according to your needs.
A: USE this in your IBAction method
if(!btnCheckbox.selected)
{
[btnCheckbox setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"check-out_h" ofType:@"png"]] forState:UIControlStateNormal];
btnCheckbox.selected=YES;
}
else {
[btnCheckbox setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"check-out" ofType:@"png"]] forState:UIControlStateNormal];
btnCheckbox.selected=NO;
}
A: -(void)checkBoxIsHideNationWideClicked
{
NSLog(@"nation wide button clicked");
mybtn.selected=!mybtn.selected;
defaultsCheckBox=[NSUserDefaults standardUserDefaults];
if (mybtn.selected)
{
[defaultsCheckBox setValue:@"One" forKey:@"CheckBox"];
NSLog(@" is active value is %@ is fetched succesfuly",hideNationWideStr);
[CommonVar setHideNationwideData:hideNationWideStr];
NSLog(@" is active value send to cmmon class %@ sent succesfuly",hideNationWideStr);
}
else
{
[defaultsCheckBox setValue:@"Two" forKey:@"CheckBox"];
NSLog(@"no vlaue send");
hideNationWideStr=[[NSMutableString alloc]initWithString:@"1"];
[CommonVar setHideNationwideData:hideNationWideStr];
NSLog(@" is active value send to cmmon class %@ sent succesfuly",hideNationWideStr);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: handling an executable file in Visual Studio C# My env is Visual Studio 2008 C# and .Net. I like to call an executable from the code and pass parameters to it and then get the output. How do I do this?
Thanks
Bruce
A: Use Process.Start to start a process. How you give it data and get the output will depend on the executable, but you can pass command line arguments, and if it writes its output to a file, that will be simple. You can capture its standard output, standard error and standard input streams too - ideally use ProcessStartInfo to configure everything you need before starting the process.
Reading/writng data from the process via the standard output/error/input can be slightly tricky (as you may need to use multiple threads) so if you can specify command line arguments to specify input and output files, that would be ideal.
A: processInfo.FileName =FileName.exe;
processInfo.WorkingDirectory = fileDirectory;
processInfo.RedirectStandardInput =false;
processInfo.CreateNoWindow =true;
processInfo.UseShellExecute =false;
Process startRestore = Process.Start(processInfo);
startRestore.WaitForExit();
Replace your file with "FileName.exe" and File path with fileDirectory.
I hope it will be helpful to you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set height for the listview that created dynamically through java code? I 'm trying to set the height of the listview which has been created through java code dynamically. I'm using 3 listviews(one below another) in a scrollview(to avoid hiding of lists). If i use scroll view, i cannot see all the list items of the listviews.Is there any idea to set height for those 3 list views through java coding in android? Any help is really appreciated and thanks in advance...
A: Don't put ListViews in ScrollViews! In Detail Information from the developers of Listview is available in the talk World of ListViews
It is possible to make the three ListViews share the space on the Screen by using the layoutWeight parameter.
Make a layout like this (you can also use code for that):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="@+id/listView1" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_weight="1"></ListView>
<ListView android:id="@+id/listView2" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_weight="1"></ListView>
<ListView android:id="@+id/listView3" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_weight="1"></ListView>
</LinearLayout>
Here each ListView takes a third of the available space (all weights set to 1).
To set the layoutWeight in code use this line as example:
listview1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: First Row As Column Header in OPENROWSET select * from OpenRowset('MSDASQL',
'Driver={Microsoft Text Driver (*.txt; *.csv)};
DefaultDir=C:\;
Extended properties=''ColNameHeader=True;
Format=Delimited(\tab);''',
'select * from MyFile.txt')
The issue is, the first row from the file becomes the header of the table.
What should I add/modify so that the first row from the file will not be the header?
ColNameHeader=False --> will not solve the problem.
Thanks.
A: SELECT * FROM
OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0',
'Data Source=C:\;
Extended Properties="Text;HDR=No;FMT=Delimited"')...[FILE#txt] This one solves the problem :D
A: You'll need to use a schema.ini file, which should reside in the same directory as the file you're reading: http://msdn.microsoft.com/en-us/library/windows/desktop/ms709353(v=vs.85).aspx
That will allow you to specify your column names.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How-to create SQL-script? I use MSSQL Management Studio 2005 Express Edition, and I have more than 100 stored procedures. How create sql-script which contain only stored procedures? Thanks.
A: Right click on the database -> Tasks -> Generate Scripts -> Go through the steps -> There are check boxes to select Tables, SPs, UDFs and Users. Select only SPs and create the script.
Here is the starting point.
A: If you do exec SP_HelpText StoredProcedureNameGoesHere, you will get the full script of that procedure.
Do this to get 5 procedures (you get the picture)
exec SP_HelpText StoredProcedure01
exec SP_HelpText StoredProcedure02
exec SP_HelpText StoredProcedure03
exec SP_HelpText StoredProcedure04
exec SP_HelpText StoredProcedure05
Here's a script to generate the script for all procedures in your db.
SELECT 'Exec sp_Helptext ' + SPECIFIC_NAME
FROM INFORMATION_SCHEMA.Routines
A: Open Databases >> DBName >> Programability >> Stored Procedures in Object Explorer Details and then select all procedures except "System Stored Procedures" folder and right click on it and select "Script Stored Procedures as >> Create To >>" option.
A: Right click on ur database name -> Select Task -> Generate Script -> Next -> Next -> Select things to be scripted ->next - > Select All -> Finish
i have posted an image for help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ChartDirector sometimes draws crosses, refreshing sometimes shows data I'm using asp.net and ChartDirector Version 5.
I got a page, generating 3 Charts which is working locally perfect.
After uploading it to my webserver it draws f.e. chart 1 and 3, an leaves chart2 as a blue cross. When i refresh it draws something else, f.e. chart 2 and 3, but leaves chart 1 as a cross. Refreshing is randomly changing which ones are shown, but at least one chart, sometimes all.
All charts are using a session ID, to prevent wrong data to be shown
viewer1.ImageSessionId = "xyz" + DateTime.Now.Ticks.ToString();
What are the reasons for that strange behaviour? What can I do?
I'd be glad for every advice :D
Thx, Harry
A: see here
its not as difficult as it seems, you'll have to generate tempfiles, using an provided function as mentioned in the link. No big deal, but hard to find.
Greetings,
Harry
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to parse atom feed using jquery I want to know how to parse atom feed using jquery.
i had feed url like below
http://www.google.co.in/trends/hottrends/atom/hourly
Below is jsfiddle but it's not working
http://jsfiddle.net/sukumar/sWPkT/
A: To make cross-browser request, see the link I pointed out in my comment.
You can use this code:
<script src="jquery.js"></script>
<script src="jquery.jgfeed.js"></script>
<script>
$.jGFeed('http://twitter.com/statuses/user_timeline/26767000.rss',
function(feeds){
// Check for errors
if(!feeds){
// there was an error
return false;
}
// do whatever you want with feeds here
for(var i=0; i<feeds.entries.length; i++){
var entry = feeds.entries[i];
// Entry title
entry.title;
}
}, 10);
</script>
Don't forget to include Google Feeds API plugin (jquery.jgfeed.js)
Source
A: If you look in your browser's JavaScript console, you'd probably see something among the lines of:
XMLHttpRequest cannot load http://www.google.co.in/trends/hottrends/atom/hourly. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
Basically, for security reasons, you can't make an AJAX request from one domain to another. All browsers enforce this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java SSLException: hostname in certificate didn't match for www.googleapis.com Environment: Mac OS X Lion & Linux Debian squeeze/sid, JDK 1.7.0 & JDK 1.6.0_27
Error:
javax.net.ssl.SSLException: hostname in certificate didn't match: <www.googleapis.com/74.125.47.95> != <*.googleapis.com> OR <googleapis.com> OR <*.googleapis.com> .
I'm getting this error in all the above OS/JDK combinations.
Background: I am using google-api-services-customsearch and google-api-service-shopping jars to do webservice calls to Google. My calls were working correctly until a day ago. Since yesterday, the code has started to throw...
javax.net.ssl.SSLException: hostname in certificate didn't match: <www.googleapis.com/74.125.47.95> != <*.googleapis.com> OR <googleapis.com> OR <*.googleapis.com>
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:228)
at org.apache.http.conn.ssl.BrowserCompatHostnameVerifier.verify(BrowserCompatHostnameVerifier.java:54)
.....
at com.google.api.services.shopping.Shopping$Products$List.execute(Shopping.java:156)
I tried importing the cert into the cacerts keystore using the instructions here, but that does not seem to solve the problem.
A: AsyncHttpClient client = new AsyncHttpClient(true,80,443);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to map a String[] in hibernate How would you map the following class in hibernate:
private class Book {
private int id;
private String title;
private String[] chapterTitles;
//Constructor, Getters and Setters
}
I have mapped Collections and primitive arrays in Hibernate, but how do I do it with a String[]? My hibernate tools stops with a 'NullPointerException' thereby I am unable to generate the mappings. And I have googled but couldn't find any.
A: I have no clue how to do it with Annotations and personally, I don't think it's good idea and you should use List<String> however you can do it using xml mapping.
You should use <array>
<array name="chapterTytles" table="Titles">
<key column="title_ID" />
<index column="tytle_index" />
<element column="tytle_name" type="string" />
</array>
A: You can do it by creating a custom value type, although I would personally prefer to change your design and use a List instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to use Ext.state.LocalStorageProvider? How to setup Ext.state.LocalStorageProvider so it saves states for all items?
A: LocalStorageProvide is a HTML5 Local Storage wrapper for Ext JS. You can make use of the local storage provided the browser you use support it.
The storage is based on key/value pairs. You can store up to 5MB (I think thats the specification and some browsers don't provide that much space. I am not sure of the size limit) and use simple APIs of the LocalStorageProvider to store and retrieve data. Storing the state is NOT automated! You should know when to store, and when to retrieve!
You can make use of the set & get method to store and retrieve values. Here is an example:
var store = Ext.state.LocalStorageProvider.create();
store.set('record',rec); //This could be a object like (Ext.data.Model)
You can retrieve the data (may be in initComponent of a form etc) using:
var rec = store.get('record');
form.loadRecord(rec); // Load the form with the saved data...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Xcode 4 file complete path If I have any file open in Xcode and I would like to know the complete path to the file, how do I do that in Xcode 4? In Xcode 3 I could hover over the file name and get a tooltip with the complete path. I could also right-click a file name at the very top and get a pop-up window with the complete path. This is all gone in Xcode 4.
The annoyance is that when using the Xcode 4 search, it doesn't even show the complete path of the file in the results?!
The only solution I have currently found is to open the save as dialog and get the path from there! That definitely can't be the solution. What am I missing?
A: For files that are not part of the project you can use the File menu's Show in Finder option.
Update: Xcode 4.2 restored the ability to right-click or command-click on the file's name in the title bar to get a drop-down with the full path.
A: Show the file inspector utility (normally at the right hand side of the main window on my setup , to do that click the rightmost button of the "View" buttons menu). Click on your file in the navigator and the inspector will refresh with the information. Full path is disclosed and there is a button to open a new Finder window with the enclosing folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: SWT label size is not correctly updated I'm new in Java/SWT. I'm experiencing some troubles using a SWT label.
When I update the text on the label, its size is not correctly updated (the label is cut, respecting the original size). However, if I perform a very small resize in my dialog, the size is updated correctly.
Basically, I create the label with a default text and then, when I load data I update the label with the real text, that is bigger than the original one.
I tried calling label.update() and label.redraw() without luck.
A: I know this is old, but in order to not lose any LayoutData settings that may be set on the controls. You should call getParent().requestLayout(). The documentation specifically discourages the user of getParent().layout() which loses all the cached Data settings on the controls.
A: Try to call parent.layout(), where parent is the Composite which contains your label. Also see Understanding Layouts in SWT.
A:
Use of this method is discouraged since it is the least-efficient way to trigger a layout. The use of layout(true) discards all cached layout information, even from controls which have not changed. It is much more efficient to invoke Control.requestLayout() on every control which has changed in the layout than it is to invoke this method on the layout itself.
Based on the documentation of getParent().layout(), you should call requestLayout() on the control itself not its parent as @kingargyle said.
What I always did was label.requestLayout() and it worked flawlessly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: What is an "Async Pinned Handle"? I'm trying to investigate a really nasty software crash which is possibly related to a managed heap corruption (since it happens during a garbage collection). Using WinDbg with the (SOS) !gchandles command I get something like
0:000> !gchandles
GC Handle Statistics:
Strong Handles: 259
Pinned Handles: 137
Async Pinned Handles: 1
Ref Count Handles: 79
Weak Long Handles: 197
Weak Short Handles: 650
Other Handles: 0
Statistics:
And I'm just curious, what is the difference between a "normal" pinned handle and an "async pinned" one? And can I find which one of my handles is the "async" one?
I couldn't find any information on the net about it and since it seems that the application always crashes when this counter is exactly one it might be relevant to the crash. But then again it might just be some internal stuff used during the garbage collection..
A: Async pinned handles are strongly correlated with overlapped I/O in Windows. Which supports asynchronous reading and writing with ReadFile and WriteFile, using the OVERLAPPED argument. The device driver stores the passed buffer pointer and directly reads/writes from/to the buffer, entirely asynchronously from the program's operation. The managed wrapper methods are BeginRead and BeginWrite.
If the buffer is allocated in the GC heap then it needs to be pinned until the driver finishes using the buffer. Having the GC move the buffer while the driver is working on the I/O transfers is disastrous, writes would produce junk and reads would corrupt the GC heap, pinning is required to prevent the buffer from being moved while the driver is using it.
Pinned objects are pretty unpleasant, they give the garbage collector a hard time to work around the rock in the road when it compacts the heap. A necessary evil here, the only possible way to get ahead is to leave the buffer pinned for as short amount of time as possible.
Async pinned handles are marked specially to allow the CLR to automatically unpin the buffer on I/O completion. As quickly as possible, when the I/O completion port signals completion and thus not having to wait for the client code to execute the callback and unpin the buffer. Which could take a while when there are lots of threadpool threads in flight. It is a micro-optimization that tends to turn into a macro one when you have, say, a web server that handles tens of thousands of client requests.
It is only ever used for objects of type System.Threading.OverlappedData, an internal class in mscorlib.dll that the CLR has special knowledge of and is the managed facsimile for the native OVERLAPPED structure that the Windows api functions use.
Long story short, all you really know is that there's an overlapped I/O pending if you see the handle count at 1 when it crashes. Having any native code that does overlapped I/O with gc allocated buffers that are not pinned is otherwise indeed a good way to destroy the heap. You have rather a lot of pinned handles btw.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
}
|
Q: get current location from GPS in Blackberry application How to get current location from GPS in Blackberry application. I tried to get location from Locationmanager method in simulator its work fine but in my device (Storm 2 using wifi) I am not able to get current lat long.
my code
private class LocationListenerImpl implements LocationListener {
public void locationUpdated(LocationProvider provider, Location location) {
if (location.isValid()) {
heading = location.getCourse();
longitude = location.getQualifiedCoordinates().getLongitude();
latitude = location.getQualifiedCoordinates().getLatitude();
altitude = location.getQualifiedCoordinates().getAltitude();
speed = location.getSpeed();
// This is to get the Number of Satellites
String NMEA_MIME = "application/X-jsr179-location-nmea";
satCountStr = location.getExtraInfo("satellites");
if (satCountStr == null) {
satCountStr = location.getExtraInfo(NMEA_MIME);
}
// this is to get the accuracy of the GPS Cords
QualifiedCoordinates qc = location.getQualifiedCoordinates();
accuracy = qc.getHorizontalAccuracy();
}
}
public void providerStateChanged(LocationProvider provider, int newState) {
// no-op
}
}
A: I found this on the first place I looked for storm issues : If you run the above code on your BlackBerry device (for instance a Storm), you will get a "GPS not allowed" LocationProvider exception. You need to get your code signed if you want to use the BlackBerry Storm with GPS in your app. To do this, you need to buy a $20 certificate from RIM.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is error in code of view did load so it crashed progrme? I am using this code for view did load..
- (void)viewDidLoad {
myPicker.hidden=TRUE;
NSArray * shopping=[NSArray arrayWithObjects:@"Lie in bed",
@"Shower",
@"Brush Teeth",
@"Eat",
@"Make Lunch",
@"Dressed",
@"Make up",
@"Hair",
@"Prepare Childern",
@"Other",nil];
for(int i=0;i<61;i++)
{
if (array_time ==nil) {
array_time=[[NSMutableArray alloc] init];
}
NSString *str=[NSString stringWithFormat:@"%i Min",i];
[array_time addObject:[NSString stringWithFormat:@"%@",str]];
[str release];
}
for (int i=0; i<61; i++) {
NSLog(@"%@",[array_time objectAtIndex:i]);
}
if(array_from==nil)
{
array_from=[[NSMutableArray alloc] init];
}
[array_from addObject:shopping];
[super viewDidLoad];
}
after that i have coded for table view. I have checked by applying break point all over but i was terminate after view did load. On console it is not giving any error.
So what is mistake in this code or any where?
Thanks in advance..
A: you don't really need to release this string:
str
NSString *str=[NSString stringWithFormat:@"%i Min",i];
[array_time addObject:[NSString stringWithFormat:@"%@",str]];
[str release];
you didn't allocate it
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to Handle ftp request using servlet? Is it possible to write a servlet which handles FTP request instead of usual HTTP request?, If yes, how can we do this?
A: Although it says that you can extend GenericServlet to use other protocols than HTTP - you can't. There's no implementation that handles the networking, especially since FTP is a statefull protocol.
I would suggest implementing something like the Apache Mina Ftp Server (http://mina.apache.org/ftpserver-project/) to handle that for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to set Content Length REST Request - for Android I'm trying to connect to a webservice using Java and REST. This is what I've tried, and I get a 411 error.
public static String getSiteToken(String host,String token) throws IOException, JSONException
{
host = host.replace("https://", "http://");
URL url = new URL(host + "/tokens");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", token);
conn.setRequestProperty("Content-Length", "57");
//conn.setFixedLengthStreamingMode(57);
conn.setRequestProperty("Connection","keep-alive");
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader rd = new BufferedReader(isr);
JSONObject json = new JSONObject(rd.readLine());
rd.close();
conn.disconnect();
return json.getString("token");
}
I also tried " setFixedLengthStreamingMode " method, but the application wasn't responding after that line of code. Everything works fine when connecting with REST Client for firefox. I can't figure it out. Thanks!
A: You aren't writing anything to the body of the request. In that case the content length should be 0 and not 57
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Open a new window using MapAreaAttributes in microsoft chart control i am using MS asp.net 3.5 chart control (Pyramid) and on the click of the series/datapoint i need to open a URL in a new window, something like javascript window.open.
Now i have tried a hell lot but that doesn't work. I am not able to give javascript to the datapoint.
Secondly i got to know that MapAreaAttributes could be given to Series as mentioned below if a new window needs to be open
series.MapAreaAttributes= "target='_blank'";
But even this doesn't works????
Guide me! Thanks
A: I had your same problem just now.
Here is the solutions and it works:
Notice in your code that you're using the single quotation ('). It seems that this is not allowed by the chart control or something. Let me give you an example that might help you understand:
Let's assume you have a JavaScript function that opens a window showing some data when the user clicks on a column (point) in your data (series). You can do it like this:
Chart1.Series["MySeries"].Points[0].Url = "javascript:void(0)"; //this is just to tell the browser not follow a URL, since you will control this with your javascript
Chart1.Series["MySeries"].Points[0].MapAreaAttributes = "onclick=\"OpenWindow();\""; //this is to set the onclick attribute to fire your javascript function when the user clicks your column.
In the above example in the second line of code, notice that I have used double quotation instead of single ones. If you wrote it like this :
"onclick=\'OpenWindow();\'";
it will never work! You have to use double quotations...
Also, since I am a C# developer, you have to use the \" code to write double quotations otherwise, you will get compiler error.
I hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make custom Scroll Bar image and A-Z effect in contacts? I am creating a contacts like application with a listview. I would like to use the scrolling effect in android contacts which displays A-Z in the middle of the screen while we scroll on the contacts list.Also i want to implement custom scroll bar image?
Can anybody help me?
A: check this API Demo >> Lists >> Array(Overlay )demo code..
it will help you..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there any alternate way for CheckBox onClick Event in JavaScript? I have written one JavaScript function which would rise the event when the User clicks the CheckBox.
But I have already written some other function which too has to rise when the user clicks the CheckBox. I included that function on onClick event like below:
<asp:CheckBox ID="chkSelect" runat="server" Checked='<%#Bind("Select") %>' onClick="CheckedTotal();" />
But now I want to include another function called "EnableLink" into that onClick event of the CheckBox. How to include this function to the CheckBox? I have tried to combine both the function as a single one. But it has become a complex one for me. So Is there any alternate way for this?
A: Lots of ways to do this..quickest one
<asp:CheckBox ID="chkSelect" runat="server" Checked='<%#Bind("Select") %>' onClick="CheckedTotal(); EnableLink(); MoreClick();" />
A: This will Help you,
<asp:CheckBox ID="chkSelect" runat="server" Checked='<%#Bind("Select") %>' onClick="CheckedTotal();EnableLink();" />
A: 1) .. onClick="CheckedTotal();myFn();" ..
2) .. onClick="someFn();" ..
<script>
function someFn(){
CheckedTotal();
myFn();
}
</script>
3) in onload of the window/page
document.getElementById('myCheckboxID').addEventListener('click', myFn,false);
UPDATE: myFn() = EnableLink();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Access nested web user control elements I have a nested web user control. Main web user control I have used on a page but now I want to access the control inside the inner web user control and its events.
Can any body help me in this issue.
A: In the parent user control, expose a reference to your child control, or it's properties through a property. For example
public partial class ParentControl : UserControl
{
...
// Expose the whole child control
public ChildControl MyChild
{
get { return this.theIdOfTheChildControl; }
}
...
// or expose specific properties
public string MyChildText
{
get { return this.theIdOfTheChildControl.Text; }
set { this.theIdOfTheChildControl.Text = value; }
}
}
A: try this method
private List<Control> GetAllNestedUserControl(Control ph)
{
List<Control> Get = new List<Control>();
foreach (var control in ph.Controls)
{
if (control is UserControl)
{
UserControl uc = control as UserControl;
if (uc.HasControls())
{
Get = GetAllNestedUserControl(uc);
}
}
else
{
Control c = (Control)control;
if (!(control is LiteralControl))
{
Get.Add(c);
}
}
}
return Get;
}
this method will return the list of all controls then do the following to get the control u want
List<Control> Get = GetAllNestedUserControl(ph);
Label l = (Label)Get.Find(o => o.ID == "lblusername");
l.Text = "changed from master";
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.