Search Results

Search found 4252 results on 171 pages for 'david 85'.

Page 164/171 | < Previous Page | 160 161 162 163 164 165 166 167 168 169 170 171  | Next Page >

  • Haskell math performance

    - by Travis Brown
    I'm in the middle of porting David Blei's original C implementation of Latent Dirichlet Allocation to Haskell, and I'm trying to decide whether to leave some of the low-level stuff in C. The following function is one example—it's an approximation of the second derivative of lgamma: double trigamma(double x) { double p; int i; x=x+6; p=1/(x*x); p=(((((0.075757575757576*p-0.033333333333333)*p+0.0238095238095238) *p-0.033333333333333)*p+0.166666666666667)*p+1)/x+0.5*p; for (i=0; i<6 ;i++) { x=x-1; p=1/(x*x)+p; } return(p); } I've translated this into more or less idiomatic Haskell as follows: trigamma :: Double -> Double trigamma x = snd $ last $ take 7 $ iterate next (x' - 1, p') where x' = x + 6 p = 1 / x' ^ 2 p' = p / 2 + c / x' c = foldr1 (\a b -> (a + b * p)) [1, 1/6, -1/30, 1/42, -1/30, 5/66] next (x, p) = (x - 1, 1 / x ^ 2 + p) The problem is that when I run both through Criterion, my Haskell version is six or seven times slower (I'm compiling with -O2 on GHC 6.12.1). Some similar functions are even worse. I know practically nothing about Haskell performance, and I'm not terribly interested in digging through Core or anything like that, since I can always just call the handful of math-intensive C functions through FFI. But I'm curious about whether there's low-hanging fruit that I'm missing—some kind of extension or library or annotation that I could use to speed up this numeric stuff without making it too ugly.

    Read the article

  • StructureMap problems with bidirectional/circular dependencies

    - by leozilla
    I am currently integrating StructureMap within our business layer but have problems because of bidirectional dependencies. The layer contains multiple manager where each manager can call methods on each other, there are no restrictions or rules for communication. This also includes possible circular dependencies like in the example below. I know the design itself is questionable but currently we just want StructureMap to work and will focus on further refactoring in the future. Every manager implements the IManager interface internal interface IManager { bool IsStarted { get; } void Start(); void Stop(); } And does also have his own specific interface. internal interface IManagerA : IManager { void ALogic(); } internal interface IManagerB : IManager { void BLogic(); } Here are to dummy manager implementations. internal class ManagerA : IManagerA { public IManagerB ManagerB { get; set; } public void ALogic() { } public bool IsStarted { get; private set; } public void Start() { } public void Stop() { } } internal class ManagerB : IManagerB { public IManagerA ManagerA { get; set; } public void BLogic() { } public bool IsStarted { get; private set; } public void Start() { } public void Stop() { } } Here is the StructureMap configuration i use atm. I am still not sure how i should register the managers so currently i use a manual registration. Maybee someone could help me with this too. For<IManagerA>().Singleton().Use<ManagerA>(); For<IManagerB>().Singleton().Use<ManagerB>(); SetAllProperties(convention => { // configure the property injection for all managers convention.Matching(prop => typeof(IManager).IsAssignableFrom(prop.PropertyType)); }); After all i cannot create IManagerA because StructureMap complians about the circular dependency between ManagerA and ManagerB. Is there an easy and clean solution to solve this problem but keep to current design? br David

    Read the article

  • NAnt exec relative path

    - by stacker
    How can I assign to trunk.dir property a relative path to the trunk location? This is my nant.build file: <?xml version="1.0" encoding="utf-8"?> <project name="ProjectName" default="build" xmlns="http://nant.sf.net/release/0.85/nant.xsd"> <!-- Directories --> <property name="trunk.dir" value="C:\Projects\ProjectName" /><!-- I want relative path over here! --> <property name="source.dir" value="${trunk.dir}src\" /> <!-- Working Files --> <property name="msbuild.exe" value="C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\msbuild.exe" /> <property name="solution.sln" value="${source.dir}ProjectName.sln" /> <!-- Called Externally --> <target name="compile"> <!-- Rebuild foces msbuild to clean and build --> <exec program="${msbuild.exe}" commandline="${solution.sln} /t:Rebuild /v:q" /> </target> </project>

    Read the article

  • Can any linux API or tool watch for any change in any folder below e.g. /SharedRoot or do I have to

    - by Simon B.
    I have a folder with ~10 000 subfolders. Can any linux API or tool watch for any change in any folder below e.g. /SharedRoot or do I have to setup inotify for each folder? (i.e. I loose if I want to do this for 10k+ folders). I guess yes, since I've already seen examples of this inefficient method, for instance http://twistedmatrix.com/trac/browser/trunk/twisted/internet/inotify.py?rev=28866#L345 My problem: I need to keep folders time-sorted with most recently active "project" up top. When a file changes, each folder above that file should update its last-modified timestamp to match the file. Delays are ok. Opening a file (typically MS Excel) and closing again, its file date can jump up and then down again. For this reason I need to wait until after a file is closed, then queue the folder of that file for checking, and only a while later do I go and look for the newest file in its folder, since the filedate of the triggering file could already be back-dated to its original timestamp by Excel or similar programs. Also in case several files from same folder are used/created, it makes sense to buffer timestamping of that folders' parents to at least get a bunch of updates collapsed into one delayed update. I'm looking for a linux solution. I have some code that can be run on a windows server, most of the queing functionality is here: http://github.com/sesam/FolderdateFollowsFiles/blob/master/FolderdateFollowsFiles/Follower.vb Available API:s The relative of inotify on windows, ReadDirectoryChangesW, can watch a folder and its whole subtree; see bWatchSubtree on http://msdn.microsoft.com/en-us/library/aa365465(VS.85).aspx Samba? Patching samba source is a possibility, but perhaps there are already hooks available? Other possibilities, like client side (various windows versions) and spying on file activities in order to update folders recursively?

    Read the article

  • VBScript: Disable caching of response from server to HTTP GET URL request

    - by Rob
    I want to turn off the cache used when a URL call to a server is made from VBScript running within an application on a Windows machine. What function/method/object do I use to do this? When the call is made for the first time, my Linux based Apache server returns a response back from the CGI Perl script that it is running. However, subsequent runs of the script seem to be using the same response as for the first time, so the data is being cached somewhere. My server logs confirm that the server is not being called in those subsequent times, only in the first time. This is what I am doing. I am using the following code from within a commercial application (don't wish to mention this application, probably not relevant to my problem): With CreateObject("MSXML2.XMLHTTP") .open "GET", "http://myserver/cgi-bin/nsr/nsr.cgi?aparam=1", False .send nsrresponse =.responseText End With Is there a function/method on the above object to turn off caching, or should I be calling a method/function to turn off the caching on a response object before making the URL? I looked here for a solution: http://msdn.microsoft.com/en-us/library/ms535874(VS.85).aspx - not quite helpful enough. And here: http://www.w3.org/TR/XMLHttpRequest/ - very unfriendly and hard to read. I am also trying to force not using the cache using http header settings and html document header meta data: Snippet of server-side Perl CGI script that returns the response back to the calling client, set expiry to 0. print $httpGetCGIRequest-header( -type = 'text/html', -expires = '+0s', ); Http header settings in response sent back to client: <html><head><meta http-equiv="CACHE-CONTROL" content="NO-CACHE"></head> <body> response message generated from server </body> </html> The above http header and html document head settings haven't worked, hence my question.

    Read the article

  • WPF PasswordBox Input Panel Icon Not Appearing: Better Workaround?

    - by Anna Savarin
    Hello, There is a known issue in WPF where the Input Panel icon does not appear when you set focus on a PasswordBox control. I'm in need of a workaround for this, but the one suggested -- using the ITextInputPanel API -- does not quite cut it for me. Fist of all, the API works with Windows Forms controls and alternatively accepts control handles. Since WPF controls are not handle based, and they are not Forms controls, this is not quite suitable. I tried hosting a Forms control on my WPF page and that worked on the Windows XP Tabled PC (albeit with some COM exceptions) but, since there is no PasswordBox in Forms, I had to stick with a regular textbox, which is not what I need. Alternatively, using the VisualTreeHelper to get a handle on the control did not work, either. The API, according to http://msdn.microsoft.com/en-us/library/ms699559%28VS.85%29.aspx, is only compatible with Vista. I'm dealing with Windows XP tablets. I understand that the IPenInput API can be used as an alternative, but it is now deprecated. Can someone please suggest something? I really need to fix this issue. Thanks in advance!

    Read the article

  • Removing specific XML tags

    - by iTayb
    I'd like to make an application that removes duplicates from my wpl (Windows PlayList) files. The wpl struct is something like this: <?wpl version="1.0"?> <smil> <head> <meta name="Generator" content="Microsoft Windows Media Player -- 11.0.5721.5145"/> <meta name="AverageRating" content="55"/> <meta name="TotalDuration" content="229844"/> <meta name="ItemCount" content="978"/> <author/> <title>english</title> </head> <body> <seq> <media src="D:\Anime con 2006\Shits\30 Seconds to Mars - 30 Seconds to Mars\30 Seconds to Mars - Capricorn.mp3" tid="{BCC6E6B9-D0F3-449C-91A9-C6EEBD92FFAE}" cid="{D38701EF-1764-4331-A332-50B5CA690104}"/> <media src="E:\emule.incoming\Ke$ha - Coming Unglued.mp3" tid="{E2DB18E5-0449-4FE3-BA09-9DDE18B523B1}"/> <media src="E:\emule.incoming\Lady Gaga - Bad Romance.mp3" tid="{274BD12B-5E79-4165-9314-00DB045D4CD8}"/> <media src="E:\emule.incoming\David Guetta -Sexy Bitch Feat. Akon.mp3" tid="{46DA1363-3DFB-4030-A7A9-88E13DF30677}"/> </seq> </body> </smil> This looks like standard XML file. How can I load the file and get the src value of each media tag? How can I remove specific media, in case of duplicates? Thank you very much.

    Read the article

  • How to get XML element/attribute name in SQL Server 2005

    - by OG Dude
    Hi, I have a simple procedure in SQL Server 2005 which takes some XML as input. The element attributes correspond to field names in tables. I'd like to be able to determine <elementName>, <attribNameX> dynamically as to avoid having to hardcode them into the procedure. How can I do this? The XML looks like this: <ROOT> <elementName attribName1 = "xxx" attribName2 = "yyy"/> <elementName attribName1 = "aaa" attribName2 = "bbb"/> ... </ROOT> The stored procedure like this: CREATE PROC dbo.myProc ( @XMLInput varchar(1000) ) AS BEGIN SET NOCOUNT ON DECLARE @XMLDocHandle int EXEC sp_xml_preparedocument @XMLDocHandle OUTPUT, @XMLInput SELECT someTable.someCol FROM dbo.someTable JOIN OPENXML (@XMLDocHandle, '/ROOT/elementName',1) WITH (attrib1Name int, attrib2Name int) AS XMLData ON someTable.attribName1 = XMLData.attribName1 AND someTable.attribName2 = XMLData.attribName2 EXEC sp_xml_removedocument @XMLDocHandle END GO The question has been asked here before but maybe there is a cleaner solution. Additionally, I'd like to pass the tablename as a parameter as well - I read some stuff arguing that this is bad style - so what would be a good solution for having a dynamic tablename? Thanks a lot in advance, /David

    Read the article

  • jQuery "growl-like" effect in VB.net

    - by StealthRT
    Hey all, i have made a simple form that mimiks the jQuery "GROWL" effect seen here http://www.sandbox.timbenniks.com/projects/jquery-notice/ However, i have ran into a problem. If i have more than one call to the form to display a "Growl" then it just refreshes the same form with whatever call i send it. In other words, i can only display one form at a time instead of having one drop down and a new one appear above it. Here is my simple form code for the "GROWL" form: Public Class msgWindow Public howLong As Integer Public theType As String Private loading As Boolean Protected Overrides Sub OnPaint(ByVal pe As System.Windows.Forms.PaintEventArgs) Dim pn As New Pen(Color.DarkGreen) If theType = "OK" Then pn.Color = Color.DarkGreen ElseIf theType = "ERR" Then pn.Color = Color.DarkRed Else pn.Color = Color.DarkOrange End If pn.Width = 2 pe.Graphics.DrawRectangle(pn, 0, 0, Me.Width, Me.Height) pn = Nothing End Sub Public Sub showMessageBox(ByVal typeOfBox As String, ByVal theMessage As String) Me.Opacity = 0 Me.Show() Me.SetDesktopLocation(My.Computer.Screen.WorkingArea.Width - 350, 15) Me.loading = True theType = typeOfBox lblSaying.Text = theMessage If typeOfBox = "OK" Then Me.BackColor = Color.FromArgb(192, 255, 192) ElseIf typeOfBox = "ERR" Then Me.BackColor = Color.FromArgb(255, 192, 192) Else Me.BackColor = Color.FromArgb(255, 255, 192) End If If Len(theMessage) <= 30 Then howLong = 4000 ElseIf Len(theMessage) >= 31 And Len(theMessage) <= 80 Then howLong = 7000 ElseIf Len(theMessage) >= 81 And Len(theMessage) <= 100 Then howLong = 12000 Else howLong = 17000 End If Me.opacityTimer.Start() End Sub Private Sub opacityTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles opacityTimer.Tick If Me.loading Then Me.Opacity += 0.07 If Me.Opacity >= 0.8 Then Me.opacityTimer.Stop() Me.opacityTimer.Dispose() Pause(howLong) Me.loading = False Me.opacityTimer.Start() End If Else Me.Opacity -= 0.08 If Me.Opacity <= 0 Then Me.opacityTimer.Stop() Me.Close() End If End If End Sub Public Sub Pause(ByVal Milliseconds As Integer) Dim dTimer As Date dTimer = Now.AddMilliseconds(Milliseconds) Do While dTimer > Now Application.DoEvents() Loop End Sub End Class I call the form by this simple call: Call msgWindow.showMessageBox("OK", "Finished searching images.") Does anyone know a way where i can have the same setup but would allow me to add any number of forms without refreshing the same form over and over again? Like always, any help would be great! :) David

    Read the article

  • org.apache.http.conn.HttpHostConnectException:Connection to http://172.20.38.143 refused

    - by Passion
    I have developed client server Application .I am accessing mysql with php running on my machine and client running on my cell which is connected to machine.WI-FI is also switched ON. Internet Permission are also added in Manifest file but then also the i encounter error 172.20.38.143 is IP OF MY MACHINE 06-01 13:20:10.391: W/System.err(11157): org.apache.http.conn.HttpHostConnectException: Connection to http://172.20.38.143 refused 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:674) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:511) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:489) 06-01 13:20:10.401: W/System.err(11157): at nineandroid.net.example.library.JSONParser.getJSONFromUrl(JSONParser.java:42) 06-01 13:20:10.401: W/System.err(11157): at nineandroid.net.example.library.UserFunctions.registerUser(UserFunctions.java:59) 06-01 13:20:10.401: W/System.err(11157): at nineandroid.net.example.RegisterActivity$1.onClick(RegisterActivity.java:52) 06-01 13:20:10.411: W/System.err(11157): at android.view.View.performClick(View.java:3567) 06-01 13:20:10.411: W/System.err(11157): at android.view.View$PerformClick.run(View.java:14224) 06-01 13:20:10.411: W/System.err(11157): at android.os.Handler.handleCallback(Handler.java:605) 06-01 13:20:10.411: W/System.err(11157): at android.os.Handler.dispatchMessage(Handler.java:92) 06-01 13:20:10.411: W/System.err(11157): at android.os.Looper.loop(Looper.java:137) 06-01 13:20:10.411: W/System.err(11157): at android.app.ActivityThread.main(ActivityThread.java:4517) 06-01 13:20:10.411: W/System.err(11157): at java.lang.reflect.Method.invokeNative(Native Method) 06-01 13:20:10.411: W/System.err(11157): at java.lang.reflect.Method.invoke(Method.java:511) 06-01 13:20:10.411: W/System.err(11157): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993) 06-01 13:20:10.421: W/System.err(11157): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760) 06-01 13:20:10.421: W/System.err(11157): at dalvik.system.NativeStart.main(Native Method) 06-01 13:20:10.421: W/System.err(11157): Caused by: java.net.ConnectException: failed to connect to /172.20.38.143 (port 80): connect failed: ENETUNREACH (Network is unreachable) 06-01 13:20:10.431: W/System.err(11157): at libcore.io.IoBridge.connect(IoBridge.java:114) 06-01 13:20:10.431: W/System.err(11157): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 06-01 13:20:10.431: W/System.err(11157): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 06-01 13:20:10.431: W/System.err(11157): at java.net.Socket.connect(Socket.java:848) 06-01 13:20:10.431: W/System.err(11157): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119) 06-01 13:20:10.431: W/System.err(11157): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144) 06-01 13:20:10.431: W/System.err(11157): ... 20 more 06-01 13:20:10.431: W/System.err(11157): Caused by: libcore.io.ErrnoException: connect failed: ENETUNREACH (Network is unreachable) 06-01 13:20:10.441: W/System.err(11157): at libcore.io.Posix.connect(Native Method) 06-01 13:20:10.441: W/System.err(11157): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85) 06-01 13:20:10.441: W/System.err(11157): at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 06-01 13:20:10.441: W/System.err(11157): at libcore.io.IoBridge.connect(IoBridge.java:112) 06-01 13:20:10.441: W/System.err(11157): ... 25 more 06-01 13:20:10.441: E/Buffer Error(11157): Error converting result java.lang.NullPointerException 06-01 13:20:10.451: E/JSON Parser(11157): Error parsing data org.json.JSONException: End of input at character 0 of 06-01 13:20:10.451: D/AndroidRuntime(11157): Shutting down VM 06-01 13:20:10.451: W/dalvikvm(11157): threadid=1: thread exiting with uncaught exception (group=0x40c0aa68) 06-01 13:20:10.451: E/AndroidRuntime(11157): FATAL EXCEPTION: main 06-01 13:20:10.451: E/AndroidRuntime(11157): java.lang.NullPointerException 06-01 13:20:10.451: E/AndroidRuntime(11157): at nineandroid.net.example.RegisterActivity$1.onClick(RegisterActivity.java:56) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.view.View.performClick(View.java:3567) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.view.View$PerformClick.run(View.java:14224) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.os.Handler.handleCallback(Handler.java:605) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.os.Handler.dispatchMessage(Handler.java:92) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.os.Looper.loop(Looper.java:137) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.app.ActivityThread.main(ActivityThread.java:4517) 06-01 13:20:10.451: E/AndroidRuntime(11157): at java.lang.reflect.Method.invokeNative(Native Method) 06-01 13:20:10.451: E/AndroidRuntime(11157): at java.lang.reflect.Method.invoke(Method.java:511) 06-01 13:20:10.451: E/AndroidRuntime(11157): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993) 06-01 13:20:10.451: E/AndroidRuntime(11157): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760) 06-01 13:20:10.451: E/AndroidRuntime(11157): at dalvik.system.NativeStart.main(Native Method) UserFunctions.java to call jsonParser public class UserFunctions { private JSONParser jsonParser; private static String loginURL = "http://172.20.38.143/ah_login_api/"; private static String registerURL = "http://172.20.38.143/ah_login_api/"; private static String login_tag = "login"; private static String register_tag = "register"; // constructor public UserFunctions(){ jsonParser = new JSONParser(); } /** * function make Login Request * @param email * @param password * */ public JSONObject loginUser(String email, String password){ // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("tag", login_tag)); params.add(new BasicNameValuePair("email", email)); params.add(new BasicNameValuePair("password", password)); JSONObject json = jsonParser.getJSONFromUrl(loginURL, params); // return json // Log.e("JSON", json.toString()); return json; } /** * function make Login Request * @param name * @param email * @param password * */ public JSONObject registerUser(String name, String email, String password){ // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("tag", register_tag)); params.add(new BasicNameValuePair("name", name)); params.add(new BasicNameValuePair("email", email)); params.add(new BasicNameValuePair("password", password)); // getting JSON Object JSONObject json = jsonParser.getJSONFromUrl(registerURL, params); // return json return json; } /** * Function get Login status * */ public boolean isUserLoggedIn(Context context){ DatabaseHandler db = new DatabaseHandler(context); int count = db.getRowCount(); if(count > 0){ // user logged in return true; } return false; } /** * Function to logout user * Reset Database * */ public boolean logoutUser(Context context){ DatabaseHandler db = new DatabaseHandler(context); db.resetTables(); return true; } } jsonParser.java public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); Log.e("JSON", json); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } RegisterActivity.java public class RegisterActivity extends Activity { Button btnRegister; Button btnLinkToLogin; EditText inputFullName; EditText inputEmail; EditText inputPassword; TextView registerErrorMsg; // JSON Response node names private static String KEY_SUCCESS = "success"; private static String KEY_UID = "uid"; private static String KEY_NAME = "name"; private static String KEY_EMAIL = "email"; private static String KEY_CREATED_AT = "created_at"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register); // Importing all assets like buttons, text fields inputFullName = (EditText) findViewById(R.id.registerName); inputEmail = (EditText) findViewById(R.id.registerEmail); inputPassword = (EditText) findViewById(R.id.registerPassword); btnRegister = (Button) findViewById(R.id.btnRegister); btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen); registerErrorMsg = (TextView) findViewById(R.id.register_error); // Register Button Click event btnRegister.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String name = inputFullName.getText().toString(); String email = inputEmail.getText().toString(); String password = inputPassword.getText().toString(); UserFunctions userFunction = new UserFunctions(); JSONObject json = userFunction.registerUser(name, email, password); // check for login response try { if (json.getString(KEY_SUCCESS) != null) { registerErrorMsg.setText(""); String res = json.getString(KEY_SUCCESS); if(Integer.parseInt(res) == 1){ // user successfully registred // Store user details in SQLite Database DatabaseHandler db = new DatabaseHandler(getApplicationContext()); JSONObject json_user = json.getJSONObject("user"); // Clear all previous data in database userFunction.logoutUser(getApplicationContext()); db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT)); // Launch Dashboard Screen Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class); // Close all views before launching Dashboard dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(dashboard); // Close Registration Screen finish(); }else{ // Error in registration registerErrorMsg.setText("Error occured in registration"); } } } catch (JSONException e) { e.printStackTrace(); } } }); // Link to Login Screen btnLinkToLogin.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(getApplicationContext(), LoginActivity.class); startActivity(i); // Close Registration View finish(); } }); } }

    Read the article

  • juqery image fading with tabs

    - by StealthRT
    Hey all, i am trying my best to figure out how to go about doing this: I have 2 tabs. When the page loads tab1 is selected automatically. This shows the tab as 1.0 transparency while tab2 stays at 0.7. Once the user clicks on tab2, tab1 goes to 0.7 transparency and tab2 goes to 1.0. However, i can not seem to get it to do that! Here is my code: function checkTab(theTab) { $('#tab1').fadeTo(250, 0.70); $('#tab2').fadeTo(250, 0.70); if ($("#tabActive").val() == theTab) { $(theTab).fadeTo(250, 1); } } $(document).ready(function() { $('#tab1').hover(function() {$(this).fadeTo(250, 1)}, function() {checkTab('#tab1')}); $('#tab2').hover(function() {$(this).fadeTo(250, 1)}, function() {checkTab('#tab2')}); $('#tab2').fadeTo(250, 0.70); $('#tabActive').val('tab1'); }); </script> <li class="stats"><img src="images/Stats.png" name="nav1" width="70" height="52" id="tab1" onclick="$('#tabActive').val('tab1');" /></li> <li class="cal"><img src="images/cal.png" name="nav1" width="70" height="52" id="tab2" onclick="$('#tabActive').val('tab2');" /></li> <input name="tabActive" id="tabActive" type="text" /> Any help would be great! :) David

    Read the article

  • jquery image fading with tabs

    - by StealthRT
    Hey all, i am trying my best to figure out how to go about doing this: I have 2 tabs. When the page loads tab1 is selected automatically. This shows the tab as 1.0 transparency while tab2 stays at 0.7. Once the user clicks on tab2, tab1 goes to 0.7 transparency and tab2 goes to 1.0. However, i can not seem to get it to do that! Here is my code: <script type="text/javascript"> function checkTab(theTab) { $('#tab1').fadeTo(250, 0.70); $('#tab2').fadeTo(250, 0.70); if ($("#tabActive").val() == theTab) { $(theTab).fadeTo(250, 1); } } $(document).ready(function() { $('#tab1').hover(function() {$(this).fadeTo(250, 1)}, function() {checkTab('#tab1')}); $('#tab2').hover(function() {$(this).fadeTo(250, 1)}, function() {checkTab('#tab2')}); $('#tab2').fadeTo(250, 0.70); $('#tabActive').val('tab1'); }); </script> <li class="stats"><img src="images/Stats.png" name="nav1" width="70" height="52" id="tab1" onclick="$('#tabActive').val('tab1');" /></li> <li class="cal"><img src="images/cal.png" name="nav1" width="70" height="52" id="tab2" onclick="$('#tabActive').val('tab2');" /></li> <input name="tabActive" id="tabActive" type="text" /> Any help would be great! :) David

    Read the article

  • Visual Studio macro to navigate to T4MVC link

    - by shannon
    I use T4MVC and I'm happy with it and want to keep it - it keeps down run time defects. Unfortunately, it makes it harder to navigate to views and content (a.k.a. Views and Links in T4MVC) though. Even using Resharper, I can't navigate to the referenced item: T4MVC and Resharper Navigation Can I get a hand building a macro to do this? Never having built a VS IDE macro before, I don't have a grasp on how to get at some things, like the internal results of the "Go To Definition" process, if that's even possible. If you aren't familiar with T4MVC, here's generally what the macro might do to help: Given the token: Links.Content.Scripts.jQuery_js in the file MyView.cshtml, '(F12) Go To Definition'. This behaves properly. Having arrived at the the related assignment: public readonly string jQuery_js = "~/Content/Scripts/jQuery.js"; in a file generated by T4MVC (which is very nice, thank you David, but we really don't ever need to see), capture the string assigned and close the file. Navigate in Solution Explorer to the PhysicalPath represented by the captured string. This process would also work for views/layouts/master-pages/partials, etc. If you provide a macro or link to a macro to do this, or have another solution, wonderful. Otherwise, hints on how to do step 3 simply in a VS macro would be especially appreciated and receive upvote from me. I'd post the macro back here as an answer when done. Thanks!

    Read the article

  • How to get smartcard reader name in Windows 7 using C# or C/C++?

    - by AndrejaKo
    Hi! I'm trying to make a C# program which will use a C .dll (unfortunately, the .dll doesn't have good documentation) to access a smart card. One of the functions of the .dll uses name of the reader as argument. My problem is that I don't know how to get the name. After looking for answers I found something similar to what I need in an example here: http://msdn.microsoft.com/en-us/library/aa379803%28VS.85%29.aspx I'm looking for a way to get szReader value as described in the aforementioned example using C#. Can anyone help me or at least point me in the right direction? EDIT: Looks like nobody knows the answer so I'll expand the question: How do I get smartcard reader name using C/C++ and Windows API? I've read through MSDN site for smartcard API, but I couldn't find the function which will list readers. My idea is now to make a C/C++ .dll which will get in-between the smartcard .dll and C# program. It will produce list of readers, let user chose one and call the smartcard .dll using chosen name as argument.

    Read the article

  • Help with Hibernate mapping

    - by GigaPr
    Hi i have the following classes public class RSS { private Integer id; private String title; private String description; private String link; private Date dateCreated; private Collection rssItems; private String url; private String language; private String rating; private Date pubDate; private Date lastBuildDate; private User user; private Date dateModified; public RSS() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public void setDescription(String description){ this.description = description; } public String getDescription(){ return this.description; } public void setLink(String link){ this.link = link; } public String getLink(){ return this.link; } public void setUrl(String url){ this.url = url; } public String getUrl(){ return this.url; } public void setLanguage(String language){ this.language = language; } public String getLanguage(){ return this.language; } public void setRating(String rating){ this.rating = rating; } public String getRating(){ return this.rating; } public Date getPubDate() { return pubDate; } public void setPubDate(Date pubDate) { this.pubDate = pubDate; } public Date getLastBuildDate() { return lastBuildDate; } public void setLastBuildDate(Date lastBuildDate) { this.lastBuildDate = lastBuildDate; } public Date getDateModified() { return dateModified; } public void setDateModified(Date dateModified) { this.dateModified = dateModified; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } public Collection getRssItems() { return rssItems; } public void setRssItems(Collection rssItems) { this.rssItems = rssItems; } } public class RSSItem { private RSS rss; private Integer id; private String title; private String description; private String link; private Date dateCreated; private Date dateModified; private int rss_id; public RSSItem() {} public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } public Date getDateModified() { return dateModified; } public void setDateModified(Date dateModified) { this.dateModified = dateModified; } public RSS getRss() { return rss; } public void setRss(RSS rss) { this.rss = rss; } } that i mapped as <hibernate-mapping> <class name="com.rssFeed.domain.RSS" schema="PUBLIC" table="RSS"> <id name="id" type="int"> <column name="ID"/> <generator class="native"/> </id> <property name="title" type="string"> <column name="TITLE" not-null="true"/> </property> <property name="lastBuildDate" type="java.util.Date"> <column name="LASTBUILDDATE"/> </property> <property name="pubDate" type="java.util.Date"> <column name="PUBDATE" /> </property> <property name="dateCreated" type="java.util.Date"> <column name="DATECREATED" not-null="true"/> </property> <property name="dateModified" type="java.util.Date"> <column name="DATEMODIFIED" not-null="true"/> </property> <property name="description" type="string"> <column name="DESCRIPTION" not-null="true"/> </property> <property name="link" type="string"> <column name="LINK" not-null="true"/> </property> <property name="url" type="string"> <column name="URL" not-null="true"/> </property> <property name="language" type="string"> <column name="LANGUAGE" not-null="true"/> </property> <property name="rating" type="string"> <column name="RATING"/> </property> <set inverse="true" lazy="false" name="rssItems"> <key> <column name="RSS_ID"/> </key> <one-to-many class="com.rssFeed.domain.RSSItem"/> </set> </class> </hibernate-mapping> <hibernate-mapping> <class name="com.rssFeed.domain.RSSItem" schema="PUBLIC" table="RSSItem"> <id name="id" type="int"> <column name="ID"/> <generator class="native"/> </id> <property name="title" type="string"> <column name="TITLE" not-null="true"/> </property> <property name="description" type="string"> <column name="DESCRIPTION" not-null="true"/> </property> <property name="link" type="string"> <column name="LINK" not-null="true"/> </property> <property name="dateCreated" type="java.util.Date"> <column name="DATECREATED"/> </property> <property name="dateModified" type="java.util.Date"> <column name="DATEMODIFIED"/> </property> <many-to-one class="com.rssFeed.domain.RSS" fetch="select" name="rss"> <column name="RSS_ID"/> </many-to-one> </class> </hibernate-mapping> But when i try to fetch an RSS I get the following error Exception occurred in target VM: failed to lazily initialize a collection of role: com.rssFeed.domain.RSS.rssItems, no session or session was closed org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.rssFeed.domain.RSS.rssItems, no session or session was closed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350) at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:97) at org.hibernate.collection.PersistentSet.size(PersistentSet.java:139) at com.rssFeed.dao.hibernate.HibernateRssDao.get(HibernateRssDao.java:47) at com.rssFeed.ServiceImplementation.RssServiceImplementation.get(RssServiceImplementation.java:46) at com.rssFeed.mvc.ViewRssController.handleRequest(ViewRssController.java:20) at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:875) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:476) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:431) at javax.servlet.http.HttpServlet.service(HttpServlet.java:734) at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97) at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:332) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:233) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57) at com.sun.grizzly.ContextTask.run(ContextTask.java:69) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309) at java.lang.Thread.run(Thread.java:619) < what does it mean? Thanks

    Read the article

  • What is the preferred way in C++ for converting a builtin type (int) to bool?

    - by Martin
    When programming with Visual C++, I think every developer is used to see the warning warning C4800: 'BOOL' : forcing value to bool 'true' or 'false' from time to time. The reason obviously is that BOOL is defined as int and directly assigning any of the built-in numerical types to bool is considered a bad idea. So my question is now, given any built-in numerical type (int, short, ...) that is to be interpreted as a boolean value, what is the/your preferred way of actually storing that value into a variable of type bool? Note: While mixing BOOL and bool is probably a bad idea, I think the problem will inevitably pop up whether on Windows or somewhere else, so I think this question is neither Visual-C++ nor Windows specific. Given int nBoolean; I prefer this style: bool b = nBoolean?true:false; The following might be alternatives: bool b = !!nBoolean; bool b = (nBoolean != 0); Is there a generally preferred way? Rationale? I should add: Since I only work with Visual-C++ I cannot really say if this is a VC++ specific question or if the same problem pops up with other compilers. So it would be interesting to specifically hear from g++ or users how they handle the int-bool case. Regarding Standard C++: As David Thornley notes in a comment, the C++ Standard does not require this behavior. In fact it seems to explicitly allow this, so one might consider this a VC++ weirdness. To quote the N3029 draft (which is what I have around atm.): 4.12 Boolean conversions [conv.bool] A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. (...)

    Read the article

  • Return value from Object match

    - by Hito_kun
    I'm, by no means, JS fluent, so forgive me if im asking for some really basic stuff, but I've not being able to find a proper answer to my question. Im writting my first Node.js (plus Extra Framework and Socket.io) app and Im having some fun setting up the server side of a FB-like messenger (surprise!!!). So, let's say I have this data structure to store online users(This is a JSON Array, but I'm not sure it is the best way to do it or should I go with Javascript Objects): [ { "site": 45, "users": [ { "idUser": 5, "idSocket": "qwe87r7w8qwe", "name": "Carlos Ray Norris" }, { "idUser": 6, "idSocket": "v8d9d0fgfs7d", "name": "John Connor" } ] }, { "site": 48, "users": [ { "idUser": 22, "idSocket": "qwe87r7w8qwe", "name": "David Bowie" }, { "idUser": 23, "idSocket": "v8d9d0fgfs7d", "name": "Barack H. Obama" } ] } ] What I want to do is to search in the array for x value given y. In this case, retrieving the idSocket knowing the idUser WITHOUT having to run through the array values. So I have basically 2 questions: first, what would be the proper way to store users online? and secondly, how to find values matching with the values I already know (find the idSocket that has a given idUser). I would like a pure JS approach(or using some of the tools given by Node, Socket.io or Express), but if that's not possible then I can look for some JQuery.

    Read the article

  • fullcalendar events from REST-ful php server.

    - by biagidp
    I've written a very simple RESTful php server (my first experiment with REST, so feel free to make suggestions) to respond to the fullcalendar events callback. It produces exactly the same string output as the json-events.php file in the fullcalendar json example, but for some reason fullcalendar will not accept my server's output. I've tried messing with the headers because they're different from the ones produced by json-events.php, but I'm not really sure what's awry there, if anything. The code for the server is below: <?php class Listener{ function __construct() { $this->getResource(); $this->buildResponse(); } function getResource(){ $parts = explode('/', $_SERVER["REQUEST_URI"]); $script_name = end(explode('/', $_SERVER["SCRIPT_NAME"])); $this->resource = $parts[array_search($script_name, $parts) + 1]; $this->resource_id = $parts[array_search($script_name, $parts) + 2]; } function buildResponse(){ $method = strtolower($_SERVER["REQUEST_METHOD"]); $this->response_string = $method . ucwords($this->resource); } function getResponse(){ return $this->response_string; } } $listener = new Listener(); $thing = $listener->getResponse(); #$thing(); function getEvents(){ $year = date('Y'); $month = date('m'); echo json_encode(array( array( 'id' => 111, 'title' => "Event1", 'start' => "$year-$month-10", 'url' => "http://yahoo.com/" ), array( 'id' => 222, 'title' => "Event2", 'start' => "$year-$month-20", 'end' => "$year-$month-22", 'url' => "http://yahoo.com/" ) )); } ?> Any input, help or suggestions would be greatly appreciated! Thanks, David

    Read the article

  • Internet Explorer not incrementing number for non-sibling <li> elements

    - by biagidp
    I've got some html that looks like this: <ol> <div> <li>one</li> </div> <div> <li>two</li> </div> <div> <li>three</li> </div> </ol> Which looks like this in Chrome/Firefox: 1. one 2. two 3. three But looks like this in IE: 1. one 1. two 1. three If I change the code so that the li element is the parent of the div element instead of the other way around (so that all the li elements are siblings) IE renders it correctly. Anyone know what causes this or if this is the intended working behavior of IE? Furthermore is one way technically more correct than the other? <div><li></li></div> VS. <li><div></div></li> Thanks, David

    Read the article

  • URL protocol handler shell execute problem

    - by Chuck
    Hi, I'm working on a small hobby web site where I'm able to launch a local app with certain arguments based on links. Setting up a protocol wasn't difficult, as described in http://msdn.microsoft.com/en-us/library/aa767914(VS.85).aspx, but I have one dilemma: Let's say the protocol is: foo:127.0.0.1:1111, so a link like href="foo:127.0.0.1:1111" would launch an app like: bar.exe "%1". Since I don't have any control over bar.exe (if I had, then it would be no problem to just parse it, obviously), I need some help parsing %1. bar.exe will launch correctly if it's run as bar.exe 127.0.0.1:1111, but not if it's run as bar.exe foo:127.0.0.1:1111. So I guess my question is... is there ANY way to tell the registry to pass on not %1, but a trimmed %1? (Thinking in terms of regexp where you have match[0] = all of the matched, match[1] = first capture in the matched text). I can solve it by having a .bat instead of .exe, but as I would like to make it as easy as possible for the user to use, I would LOVE it if I could handle it all stricly in registry. Any help is greatly appreciated! Chuck

    Read the article

  • What is the benefit of using ONLY OpenID authentication on a site?

    - by Peter
    From my experience with OpenID, I see a number of significant downsides: Adds a Single Point of Failure to the site It is not a failure that can be fixed by the site even if detected. If the OpenID provider is down for three days, what recourse does the site have to allow its users to login and access the information they own? Takes a user to another sites content and every time they logon to your site Even if the OpenID provider does not have an error, the user is re-directed to their site to login. The login page has content and links. So there is a chance a user will actually be drawn away from the site to go down the Internet rabbit hole. Why would I want to send my users to another company's website? [ Note: my provider no longer does this and seems to have fixed this problem (for now).] Adds a non-trivial amount of time to the signup To sign up with the site a new user is forced to read a new standard, chose a provider, and signup. Standards are something that the technical people should agree to in order to make a user experience frictionless. They are not something that should be thrust on the users. It is a Phisher's Dream OpenID is incredibly insecure and stealing the person's ID as they log in is trivially easy. [ taken from David Arno's Answer below ] For all of the downside, the one upside is to allow users to have fewer logins on the Internet. If a site has opt-in for OpenID then users who want that feature can use it. What I would like to understand is: What benefit does a site get for making OpenID mandatory?

    Read the article

  • PHP Facebook Cronjob with offline access

    - by Mohamed Salem
    1:the code to greet the user, ask for his permission and store his session data so that we can use a cronjob with his session data afterwards. <?php $db_server = "localhost"; $db_username = "username"; $db_password = "password"; $db_name = "databasename"; #go to line 85, the script actually starts there mysql_connect($db_server,$db_username,$db_password); mysql_select_db($db_name); #you have to create a database to store session values. #if you do not know what columns there should be look at line 76 to see column names. #make them all varchars # Now lets load the FB GRAPH API require './facebook.php'; // Create our Application instance. global $facebook; $facebook = new Facebook(array( 'appId' => '121036530138', 'secret' => '9bbec378147064', 'cookie' => false,)); # Lets set up the permissions we need and set the login url in case we need it. $par['req_perms'] = "friends_about_me,friends_education_history,friends_likes, friends_interests,friends_location,friends_religion_politics, friends_work_history,publish_stream,friends_activities, friends_events, friends_hometown,friends_location ,user_interests,user_likes,user_events, user_about_me,user_status,user_work_history,read_requests, read_stream,offline_access,user_religion_politics,email,user_groups"; $loginUrl = $facebook->getLoginUrl($par); function save_session($session){ global $facebook; # OK lets go to the database and see if we have a session stored $sid=mysql_query("Select access_token from facebook_user WHERE uid =".$session['uid']); $session_id=mysql_fetch_row($sid); if (is_array($session_id)) { # We have a stored session, but is it valid? echo " We have a session, but is it valid?"; try { $attachment = array('access_token' => $session_id[0]); $ret_code=$facebook->api('/me', 'GET', $attachment); } catch (Exception $e) { # We don't have a good session so echo " our old session is not valid, let's delete saved invalid session data "; $res = mysql_query("delete from facebook_user WHERE uid =".$session['uid']); #save new good session #to see what is our session data: print_r($session); if (is_array($session)) { $sql="insert into facebook_user (session_key,uid,expires,secret,access_token,sig) VALUES ('".$session['session_key']."','".$session['uid']."','". $session['expires']."','". $session['secret'] ."','" . $session['access_token']."','". $session['sig']."');"; $res = mysql_query($sql); return $session['access_token']; } # this should never ever happen echo " Something is terribly wrong: Our old session was bad, and now we cannot get the new session"; return; } echo " Our old stored session is valid "; return $session_id[0]; } else { echo " no stored session, this means the user never subscribed to our application before. "; # let's store the session $session = $facebook->getSession(); if (is_array($session)) { # Yes we have a session! so lets store it! $sql="insert into facebook_user (session_key,uid,expires,secret,access_token,sig) VALUES ('".$session['session_key']."','".$session['uid']."','". $session['expires']."','". $session['secret'] ."','". $session['access_token']."','". $session['sig']."');"; $res = mysql_query($sql); return $session['access_token']; } } } #this is the first meaningful line of this script. $session = $facebook->getSession(); # Is the user already subscribed to our application? if ( is_null($session) ) { # no he is not #send him to permissions page header( "Location: $loginUrl" ); } else { #yes, he is already subscribed, or subscribed just now #in case he just subscribed now, save his session information $access_token=save_session($session); echo " everything is ok"; # write your code here to do something afterwards } ?> error Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/content/28/9687528/html/ss/src/indexx.php:1) in /home/content/28/9687528/html/ss/src/facebook.php on line 49 Fatal error: Call to undefined method Facebook::getSession() in /home/content/28/9687528/html/ss/src/indexx.php on line 86 2:A cronjob template that reads the stored session of a user from database, uses his session data to work on his behalf, like reading status posts or publishing posts etc. <?php $db_server = "localhost"; $db_username = "username"; $db_password = "pass"; $db_name = "database"; # Lets connect to the Database and set up the table $link = mysql_connect($db_server,$db_username,$db_password); mysql_select_db($db_name); # Now lets load the FB GRAPH API require './facebook.php'; // Create our Application instance. global $facebook; $facebook = new Facebook(array( 'appId' => 'appid', 'secret' => 'secret', 'cookie' => false, )); function get_check_session($uidCheck){ global $facebook; # This function basically checks for a stored session and if we have one it returns it # OK lets go to the database and see if we have a session stored $sid=mysql_query("Select access_token from facebook_user WHERE uid =".$uidCheck); $session_id=mysql_fetch_row($sid); if (is_array($session_id)) { # We have a session # but, is it valid? try { $attachment = array('access_token' => $session_id[0],); $ret_code=$facebook->api('/me', 'GET', $attachment); } catch (Exception $e) { # We don't have a good session so echo " User ".$uidCheck." removed the application, or there is some other access problem. "; # let's delete stored data $res = mysql_query("delete from facebook_user where WHERE uid =".$uidCheck); return; } return $session_id[0]; } else { # "no stored session"; echo " error:newsFeedcrontab.php No stored sessions. This should not have happened "; } } # get all users that have given us offline access $users = getUsers(); foreach($users as $user){ # now for each user, check if they are still subscribed to our application echo " Checking user".$user; $access_token=get_check_session($user); # If we've not got an access_token we actually need to login. # but in the crontab, we just log the error, there is no way we can find the user to give us permission here. if ( is_null($access_token) ) { echo " error: newsFeedcrontab.php There is no access token for the user ".$user." "; } else { #we are going to read the newsfeed of user. There are user's friends' posts in this newsfeed try{ $attachment = array('access_token' => $access_token); $result=$facebook->api('/me/home', 'GET', $attachment); }catch(Exception $e){ echo " error: newsfeedcrontab.php, cannot get feed of ".$user.$e; } #do something with the result here #but what does the result look like? #go to http://developers.facebook.com/docs/reference/api/user/ and click on the "home" link under connections #we can also read the home of user. Home is the wall of the user who has given us offline access. try{ $attachment = array('access_token' => $access_token); $result=$facebook->api('/me/feed', 'GET', $attachment); }catch(Exception $e){ echo " error: newsfeedcrontab.php, cannot get wall of ".$user.$e; } #do something with the result here # #but what does the result look like? #go to http://developers.facebook.com/docs/reference/api/user/ and click on the "feed" link under connections } } function getUsers(){ $sql = "SELECT distinct(uid) from facebook_user Where 1"; $result = mysql_query($sql); while($row = mysql_fetch_array($result)){ $rows [] = $row['uid']; } print_r($rows); return $rows; } mysql_close($link); ?> error Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/content/28/9687528/html/ss/src/cron.php:1) in /home/content/28/9687528/html/ss/src/facebook.php on line 49 Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/content/28/9687528/html/ss/src/cron.php on line 110 Warning: Invalid argument supplied for foreach() in /home/content/28/9687528/html/ss/src/cron.php on line 64

    Read the article

  • WPF: Binding an integer to a TextBlock with TemplateBinding

    - by haagel
    I have a custom control in WPF. In this I have a DependencyProperty of the type integer. In the template for the custom control I have a TextBlock, I and would like to show the value of the integer in the TextBlock. But I can't get it to work. I'm using TemplateBinding. If I use the same code but change the type of the DependencyProperty to string it works fine. But I really want it to be an integer for the rest of my application to work. How can I do this? I've written simplified code that shows the problem. First the custom control: public class MyCustomControl : Control { static MyCustomControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl))); MyIntegerProperty = DependencyProperty.Register("MyInteger", typeof(int), typeof(MyCustomControl), new FrameworkPropertyMetadata(0)); } public int MyInteger { get { return (int)GetValue(MyCustomControl.MyIntegerProperty); } set { SetValue(MyCustomControl.MyIntegerProperty, value); } } public static readonly DependencyProperty MyIntegerProperty; } And this is my default template: <Style TargetType="{x:Type local:MyCustomControl}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:MyCustomControl}"> <Border BorderThickness="1" CornerRadius="4" BorderBrush="Black" Background="Azure"> <StackPanel Orientation="Vertical"> <TextBlock Text="{TemplateBinding MyInteger}" HorizontalAlignment="Center" /> </StackPanel> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> What am I doing wrong? Thanks // David

    Read the article

  • VB.net XML Parser loop

    - by StealthRT
    Hey all i am new to XML parsing on VB.net. This is the code i am using to parse an XML file i have: Dim output As StringBuilder = New StringBuilder() Dim xmlString As String = _ "<ip_list>" & _ "<ip>" & _ "<ip>192.168.1.1</ip>" & _ "<ping>9 ms</ping>" & _ "<hostname>N/A</hostname>" & _ "</ip>" & _ "<ip>" & _ "<ip>192.168.1.6</ip>" & _ "<ping>0 ms</ping>" & _ "<hostname>N/A</hostname>" & _ "</ip>" & _ "</ip_list>" Using reader As XmlReader = XmlReader.Create(New StringReader(xmlString)) Do Until reader.EOF reader.ReadStartElement("ip_list") reader.ReadStartElement("ip") reader.ReadStartElement("ip") reader.MoveToFirstAttribute() Dim theIP As String = reader.Value.ToString reader.ReadToFollowing("ping") Dim thePing As String = reader.ReadElementContentAsString().ToString reader.ReadToFollowing("hostname") Dim theHN As String = reader.ReadElementContentAsString().ToString MsgBox(theIP & " " & thePing & " " & theHN) Loop End Using I put the "do until reader.EOF" myself but it does not seem to work. It keeps giving an error after the first go around. I must be missing something? David

    Read the article

  • can someone help me fix my code?

    - by user267490
    Hi, I have this code I been working on but I'm having a hard time for it to work. I did one but it only works in php 5.3 and I realized my host only supports php 5.0! do I was trying to see if I could get it to work on my sever correctly, I'm just lost and tired lol <?php //Temporarily turn on error reporting @ini_set('display_errors', 1); error_reporting(E_ALL); // Set default timezone (New PHP versions complain without this!) date_default_timezone_set("GMT"); // Common set_time_limit(0); require_once('dbc.php'); require_once('sessions.php'); page_protect(); // Image settings define('IMG_FIELD_NAME', 'cons_image'); // Max upload size in bytes (for form) define ('MAX_SIZE_IN_BYTES', '512000'); // Width and height for the thumbnail define ('THUMB_WIDTH', '150'); define ('THUMB_HEIGHT', '150'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>whatever</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <style type="text\css"> .validationerrorText { color:red; font-size:85%; font-weight:bold; } </style> </head> <body> <h1>Change image</h1> <?php $errors = array(); // Process form if (isset($_POST['submit'])) { // Get filename $filename = stripslashes($_FILES['cons_image']['name']); // Validation of image file upload $allowedFileTypes = array('image/gif', 'image/jpg', 'image/jpeg', 'image/png'); if ($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_NO_FILE) { $errors['img_empty'] = true; } elseif (($_FILES[IMG_FIELD_NAME]['type'] != '') && (!in_array($_FILES[IMG_FIELD_NAME]['type'], $allowedFileTypes))) { $errors['img_type'] = true; } elseif (($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_INI_SIZE) || ($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_FORM_SIZE) || ($_FILES[IMG_FIELD_NAME]['size'] > MAX_SIZE_IN_BYTES)) { $errors['img_size'] = true; } elseif ($_FILES[IMG_FIELD_NAME]['error'] != UPLOAD_ERR_OK) { $errors['img_error'] = true; } elseif (strlen($_FILES[IMG_FIELD_NAME]['name']) > 200) { $errors['img_nametoolong'] = true; } elseif ( (file_exists("\\uploads\\{$username}\\images\\banner\\{$filename}")) || (file_exists("\\uploads\\{$username}\\images\\banner\\thumbs\\{$filename}")) ) { $errors['img_fileexists'] = true; } if (! empty($errors)) { unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file } // Create thumbnail if (empty($errors)) { // Make directory if it doesn't exist if (!is_dir("\\uploads\\{$username}\\images\\banner\\thumbs\\")) { // Take directory and break it down into folders $dir = "uploads\\{$username}\\images\\banner\\thumbs"; $folders = explode("\\", $dir); // Create directory, adding folders as necessary as we go (ignore mkdir() errors, we'll check existance of full dir in a sec) $dirTmp = ''; foreach ($folders as $fldr) { if ($dirTmp != '') { $dirTmp .= "\\"; } $dirTmp .= $fldr; mkdir("\\".$dirTmp); //ignoring errors deliberately! } // Check again whether it exists if (!is_dir("\\uploads\\$username\\images\\banner\\thumbs\\")) { $errors['move_source'] = true; unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file } } if (empty($errors)) { // Move uploaded file to final destination if (! move_uploaded_file($_FILES[IMG_FIELD_NAME]['tmp_name'], "/uploads/$username/images/banner/$filename")) { $errors['move_source'] = true; unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file } else { // Create thumbnail in new dir if (! make_thumb("/uploads/$username/images/banner/$filename", "/uploads/$username/images/banner/thumbs/$filename")) { $errors['thumb'] = true; unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file } } } } // Record in database if (empty($errors)) { // Find existing record and delete existing images $sql = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE (`agent_id`={$user_id}) LIMIT 1"; $result = mysql_query($sql); if (!$result) { unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>"); } $numResults = mysql_num_rows($result); if ($numResults == 1) { $row = mysql_fetch_assoc($result); // Delete old files unlink("/uploads/$username/images/banner/" . $row['bannerORIGINAL']); //delete OLD source file unlink("/uploads/$username/images/banner/thumbs/" . $row['bannerTHUMB']); //delete OLD thumbnail file } // Update/create record with new images if ($numResults == 1) { $sql = "INSERT INTO `agent_settings` (`agent_id`, `bannerORIGINAL`, `bannerTHUMB`) VALUES ({$user_id}, '/uploads/$username/images/banner/$filename', '/uploads/$username/images/banner/thumbs/$filename')"; } else { $sql = "UPDATE `agent_settings` SET `bannerORIGINAL`='/uploads/$username/images/banner/$filename', `bannerTHUMB`='/uploads/$username/images/banner/thumbs/$filename' WHERE (`agent_id`={$user_id})"; } $result = mysql_query($sql); if (!$result) { unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>"); } } // Print success message and how the thumbnail image created if (empty($errors)) { echo "<p>Thumbnail created Successfully!</p>\n"; echo "<img src=\"/uploads/$username/images/banner/thumbs/$filename\" alt=\"New image thumbnail\" />\n"; echo "<br />\n"; } } if (isset($errors['move_source'])) { echo "\t\t<div>Error: Failure occurred moving uploaded source image!</div>\n"; } if (isset($errors['thumb'])) { echo "\t\t<div>Error: Failure occurred creating thumbnail!</div>\n"; } ?> <form action="" enctype="multipart/form-data" method="post"> <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_SIZE_IN_BYTES; ?>" /> <label for="<?php echo IMG_FIELD_NAME; ?>">Image:</label> <input type="file" name="<?php echo IMG_FIELD_NAME; ?>" id="<?php echo IMG_FIELD_NAME; ?>" /> <?php if (isset($errors['img_empty'])) { echo "\t\t<div class=\"validationerrorText\">Required!</div>\n"; } if (isset($errors['img_type'])) { echo "\t\t<div class=\"validationerrorText\">File type not allowed! GIF/JPEG/PNG only!</div>\n"; } if (isset($errors['img_size'])) { echo "\t\t<div class=\"validationerrorText\">File size too large! Maximum size should be " . MAX_SIZE_IN_BYTES . "bytes!</div>\n"; } if (isset($errors['img_error'])) { echo "\t\t<div class=\"validationerrorText\">File upload error occured! Error code: {$_FILES[IMG_FIELD_NAME]['error']}</div>\n"; } if (isset($errors['img_nametoolong'])) { echo "\t\t<div class=\"validationerrorText\">Filename too long! 200 Chars max!</div>\n"; } if (isset($errors['img_fileexists'])) { echo "\t\t<div class=\"validationerrorText\">An image file already exists with that name!</div>\n"; } ?> <br /><input type="submit" name="submit" id="image1" value="Upload image" /> </form> </body> </html> <?php ################################# # # F U N C T I O N S # ################################# /* * Function: make_thumb * * Creates the thumbnail image from the uploaded image * the resize will be done considering the width and * height defined, but without deforming the image * * @param $sourceFile Path anf filename of source image * @param $destFile Path and filename to save thumbnail as * @param $new_w the new width to use * @param $new_h the new height to use */ function make_thumb($sourceFile, $destFile, $new_w=false, $new_h=false) { if ($new_w === false) { $new_w = THUMB_WIDTH; } if ($new_h === false) { $new_h = THUMB_HEIGHT; } // Get image extension $ext = strtolower(getExtension($sourceFile)); // Copy source switch($ext) { case 'jpg': case 'jpeg': $src_img = imagecreatefromjpeg($sourceFile); break; case 'png': $src_img = imagecreatefrompng($sourceFile); break; case 'gif': $src_img = imagecreatefromgif($sourceFile); break; default: return false; } if (!$src_img) { return false; } // Get dimmensions of the source image $old_x = imageSX($src_img); $old_y = imageSY($src_img); // Calculate the new dimmensions for the thumbnail image // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1 = $old_x / $new_w; $ratio2 = $old_y / $new_h; if ($ratio1 > $ratio2) { $thumb_w = $new_w; $thumb_h = $old_y / $ratio1; } else { $thumb_h = $new_h; $thumb_w = $old_x / $ratio2; } // Create a new image with the new dimmensions $dst_img = ImageCreateTrueColor($thumb_w, $thumb_h); // Resize the big image to the new created one imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y); // Output the created image to the file. Now we will have the thumbnail into the file named by $filename switch($ext) { case 'jpg': case 'jpeg': $result = imagepng($dst_img, $destFile); break; case 'png': $result = imagegif($dst_img, $destFile); break; case 'gif': $result = imagejpeg($dst_img, $destFile); break; default: //should never occur! } if (!$result) { return false; } // Destroy source and destination images imagedestroy($dst_img); imagedestroy($src_img); return true; } /* * Function: getExtension * * Returns the file extension from a given filename/path * * @param $str the filename to get the extension from */ function getExtension($str) { return pathinfo($str, PATHINFO_EXTENSION); } ?>

    Read the article

< Previous Page | 160 161 162 163 164 165 166 167 168 169 170 171  | Next Page >