text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Some simple XNA/HLSL questions I've been getting into HLSL programming lately and I'm very curious as to HOW some of the things I'm doing actually work.
For example, I've got this very simple shader here that shades any teal colored pixels to a red-ish color.
sampler2D mySampler;
float4 MyPixelShader(float2 texCoords : TEXCOORD0): COLOR
{
float4 Color;
Color = tex2D(mySampler, texCoords.xy);
if(Color.r == 0 && Color.g == 1.0 && Color.b == 1.0)
{
Color.r = 1.0;
Color.g = 0.5;
Color.b = 0.5;
}
return Color;
}
technique Simple
{
pass pass1
{
PixelShader = compile ps_2_0 MyPixelShader();
}
}
I understand that the tex2D function grabs the pixel's color at the specified location, but what I don't understand is how mySampler even has any data. I'm not setting it or passing in a texture at all, yet it magically contains my texture's data.
Also, what is the difference between things like:
COLOR and COLOR0
or
TEXCOORD and TEXCOORD0
I can take a logical guess and say that COLOR0 is a registry in assembly that holds the currently used pixel color in the GPU. (that may be completely wrong, I'm just stating what I think it is)
And if so, does that mean specifying something like float2 texCoords : TEXCOORD0 will, by default, grab the current position the GPU is processing?
A: mySampler is assgined to a sample register, the first is S0.
SpriteBatch uses the same register to draw textures so you have initilized it before for sure.
this register are in relation with GraphicDevice.Textures and GraphicDevice.SamplerStates arrays.
In fact, in your shader you can use this sentence:
sampler TextureSampler : register(s0);
EDIT:
if you need to use a second texture in your shader you can make this:
HLSL
sampler MaskTexture : register(s1);
C#:
GraphicsDevice.Textures[1] = MyMaskTexture;
GraphicsDevice.SamplerStates[1].AddresU = TextureAddresMode....
Color0 is not a registry and does not hold the current pixel color. It's referred to the vertex structure you are using.
When you define a vertex like a VertexPositionColor, the vertex contains a Position, and a Color, but if you want to define a custom vertex with two colors, you need a way to discriminate between the two colors... the channels.
The number suffix means the channel you are referring in the current vertex.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How can I create a function in another frame? I have a 3rd party generated frameset (from a help system) and I can add code to the subframe that has my content pages. I cannot modify the other frameset content since it is generated by a build process.
I can have some js code myhandler() on each of my HTML content page that gets loaded into the subframe. This myhandler() is triggered to be called when an action occurs in the top frame.
I would like to create the function in the subframe but have it owned by the parent (top) frame, so that it only gets created once meaning I can test if top.myhandler is already set and if so it just reuses it.
When the subframe is loaded with different content HTML then the myhandler() function that was created in the previous content page is no longer accessible when the parent action triggers the call to it.
Is this possible in javascript for a frame to create a function in another frame? Or is there another solution to this?
A: There is 1 condition for cross-frame javascript: All involved pages (in different frames) need to be on the same domain. If pages are on different domains or subdomains - cross-frame javascript access will be restricted for security purposes.
Lets suppose you have a frameset with 2 pages: index.html and index2.html
If these pages are on the same domain - they will share the same javascript namespace, i.e. all javascript libraries linked to index.html will be accessible from index2.html and versa versa.
If pages are located on different subdomains of the same domain - it is possible to step several levels up. For example:
frame1 contains: http://myrepo.site.com/index.html
frame2 contains: http://another.site.com/index2.html
you can set for both (in JavaScript): document.domain = "site.com"
After that - javascript code on both pages will start seing each other, same as these pages are on the same domain.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why don't I see my TODOs for my PHP files in Eclipse? Why don't I see my TODOs for my PHP files in Eclipse?
I ran into this issue in PDT, I just wanted to put the answer up in case someone else did too.
A: I ran into this issue in PDT, I just wanted to put the answer up in case someone else did too.
*
*ANSWER * Although PHP doesn't really need to compile in your IDE, you need to "build" your project for TODO tags to be automatically added as tasks. If you enable Project->"Build Automatically" in Eclipse your TODOs will always become tasks upon saving your file.
A: To get this to work for me (using Eclipse with the Aptana plugin) I had to enable "PHP" as a Project Nature in my project properties, under Project | Properties | Project Natures
I had it set to "Web" and I was only getting TODOs from my Javascript files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Device Identification and setup api Is there a way to obtain properties of devices that correspond or belong to the guid class namely ClassName "Sensor". I want to obtain information to filter out devices(sensors) that are not relevant. I believe you can enumerate devices with SetupDiEnumDeviceInfo but is there way to obtain more information about them?
I'm currently using SetupDiGetDeviceRegistryProperty to obtain registry value associated with the device but is this the correct way or is there an alternative way to accomplish this?
I would like to accomplish this in user-mode if possible.
A: The Windows Driver Kit (WDK) comes with the source/binaries to a utility called devcon which might be useful. There's a "listclass" option that will give you the hardware IDs of every device installed in a given class. For example:
devcon listclass sensor
This might give you what you need, albeit in a roundabout way.
-scott
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get a list of all refs a git push would push? We're trying to implement a git workflow where there exists a pre-receive hook on the remote repo to validate that all pushed refs have commit messages that contain certain required information. In order to provide some convenience to developers, we'd also like a local git command developers can run to see what all refs would be pushed by a push command so they can verify before pushing whether or not their push would pass the hook, and also create a new git command that calls filter-branch or something else to rewrite all the commit messages to fill in any missing information.
So, is it possible to get a list of everything that would be pushed by a push command? git push --dry-run --verbose only gives a very cursory summary:
For example,
> git push --dry-run --verbose origin head:test/me
Pushing to [email protected]:myproject.git
To [email protected]:myproject.git
* [new branch] head -> test/me
A: git log @{u}..
This will list all the commits that are not yet pushed to the remote. If you want the diff of each commit then add a -p after log
git log -p @{u}..
Yes, the two dots at the end are necessary. :)
A: You can use git push --porcelain.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: isFinishing is not always accurate in onPause() I encountered a scenario that isFinishing() returned false, but the activity still exited.
There is Activity Abc in the scenario, which contains a button. When user clicks on the button, Activity Xyz will be started.
Now on Abc activity, I clicked the button on it and the BACK button on the phone almost simultaneously, with the BACK button be a few milliseconds after the touching of the button on Abc. I got the following log message:
09-30 17:32:41.424 I/Abc(20319): [onPause] com.example.Abc@40605928
09-30 17:32:41.424 D/Abc(20319): In onPause, this.isFinishing()=false
09-30 17:32:41.464 I/Xyz(20319): [onCreate] com.example.Xyz@405caf68
09-30 17:32:41.604 I/Xyz(20319): [onStart] com.example.Xyz@405caf68
09-30 17:32:41.644 I/Xyz(20319): [onResume]com.example.Xyz@405caf68
09-30 17:32:41.824 I/Abc(20319): [onStop] com.example.Abc@40605928
09-30 17:32:41.884 D/Abc(20319): [onDestroy] com.example.Abc@40605928
From the log above, we can see, the Abc activity was destroyed even when isFinishing() returned false in onPause().
The code I have in onPause() is:
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "[onPause] " + this);
Log.d(TAG, "In onPause, this.isFinishing()=" + this.isFinishing());
}
Is it a bug in Android?
Thanks.
A: I think it is a bug in Android OS.
When an activity is in onPause(), the OS should ignore the BACK button click on it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to read a text file from the last line to the first I need this to run in reverse so that the lines appear in the reverse order of this. Is there a quick way to flip a TextView or something like that? Thanks for any help.
try {
// Create a URL for the desired page
URL url = new URL("text.txt");
// Read all the text returned by the server
BufferedReader MyBr = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
line = MyBr.readLine();
TextView textview1 = (TextView) findViewById(R.id.textView1);
StringBuilder total = new StringBuilder();
while ((line = MyBr.readLine()) != null) {
total.append(line + "\r\n");}
textview1.setText(total);
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/wonderfull.ttf");
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setTypeface(tf);
MyBr.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
A: Since you are changing the UI in your code, this must be run on the UI thread. Of course you know that doing I/O like this on the UI thread is a no-no and can easily create ANRs. So we'll just assume this is pseudo-code. Your best bet is to reverse things as you read the stream. You could insert at the front of the StringBuilder for example.
A: You could also directly insert into the Editable:
Editable e = textview1.getEditableText();
while ((line = MyBr.readLine()) != null) {
e.insert(0, line + "\r\n");
}
A: You may use this class: java.io.RandomAccessFile, http://download.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html
A: I would read the file into an array or array list and then use a for loop to print it from the last index to the first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get the YouTube preview image to show up in an Android WebView? I realize there are a lot of YouTube in WebView questions but they don't seem to address my problem exactly.
I am loading a website with an embedded YouTube clip in a WebView, the problem is the YouTube preview image does not appear, I just get a black box with YouTube at the bottom.
This same website loads the preview image in the Android browser. The phone does not have Flash.
I understand it cant play the video without flash, I don't want it to play in the WebView, I just need the preview to load like it does in the regular browser.
I cant edit the website itself but it seems to be using this for the YouTube video.
<iframe allowfullscreen="" frameborder="0" height="271" src="http://www.youtube.com/embed/28L-hOJHwUw?rel=0&hd=1" width="475"></iframe></div>
I am enabling both Javascript and Plugins in my WebView.
webView = (WebView) findViewById(R.id.webviewplan);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
Any help would be appreciated.
Thanks.
Edit:
Found out that it is throwing a js error so is anyone out there able to display a YouTube embed preview in a WebView without flash, Or is this simply not possible?
Error:
TypeError: Result of expression 'a' [undefined] is not an object. --
From line 342 of http://s.ytimg.com/yt/jsbin/www-embed_core_module-vflcoqCCO.js
A: The YouTube JS is probably either shutting things down because it does not detect Flash or having a an error. If it is having an error you can find out of these by setting a custom WebChromeClient and override its onConsoleMessage method. Pump this to your LogCat (do a JS alert) and you will know about errors at least.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: vBulletin URL replace code I was previously asking for a smiliar function, but no one of them are like the vBulletin 4 has.
I mean if I paste some URL's in the vBulletins text box it will replace them for example like this:
Input:
http://www.stackoverflow.com/questions/1925455/how-to-mimic-stackoverflow-auto-link-behavior
http://yahoo.com/
Output:
php - How to mimic StackOverflow Auto-Link Behavior - Stack Overflow
Yahoo!
And this is the best of all, because if the URL doesn't exist (or don't have tags) it'll just stay with the URL path!
Input:
http://fake.url
Output:
http://fake.url
Then message BBCODE looks following:
[url=http://www.stackoverflow.com/questions/1925455/how-to-mimic-stackoverflow-auto-link-behavior]php - How to mimic StackOverflow Auto-Link Behavior - Stack Overflow[/url]
[url=http://yahoo.com/]Yahoo![/url]
[url]http://fake.url[/url]
How do they do that?
Is it possible to do with PHP/JS? If so, could you direct me how?
Kind Regards,
Lucas.
A: You have to:
*
*parse the input to extract the URLs(there should be many related topics on SO)
*request the URL's to get the contents of the <title/>
*Build the BBCode regarding to the response
This can be done using PHP, JS-only will not be able, because it may not parse external documents.(But of course you can setup a proxy-script on serverside that requests the document and returns the title to javascript/AJAX)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: When probing for assemblies why does the searched for publicKeyToken differ when running as admin vs as a normal user? I'm following instructions from a 2006 Microsoft .Net course workbook, going through one of the exercises. (Specifically this course is MS2349B and I'm doing Module 4 Exercise 2.). These exercises seem to built for the pre Vista days when everyone has full admin privileges all the time. (I'm using .net 4.0.)
This exercise involves building a strong name assembly, installing it in the GAC, building a local executable against the strong named assembly, verifying that the executable runs.
As per the tutorial, I sign my assembly using a #if block:
#if STRONG
[assembly: System.Reflection.AssemblyVersion("2.0.0.0")]
[assembly: System.Reflection.AssemblyKeyFile("OrgVerKey.snk")]
#endif
I build my executable as a local user:
C:\path\to\lab>csc /define:STRONG /target:library
/out:AReverser_v2.0.0.0\AReverser.dll AReverser_v2.0.0.0\AReverser.cs
C:\path\to\lab>csc /reference:MyStringer\Stringer.dll
/reference:AReverser_v2.0.0.0\AReverser.dll Client.cs
I install it into the GAC via a visual studio command prompt run as administrator:
C:\path\to\lab>gacutil /i AReverser_v2.0.0.0\AReverser.dll
When I run my exe in the administrator prompt I get the output I expect -- the application runs fine and appears to load the dll correctly from the gac. When I run under the non-admin command prompt I get the following error
Unhandled Exception: System.IO.FileLoadException: Could not load file or assembl
y 'AReverser, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b5fcbdcff229fabb'
or one of its dependencies. The located assembly's manifest definition does not
match the assembly reference. (Exception from HRESULT: 0x80131040)
at MainApp.Main()
What's odd to me is that the publicKeyToken is not the same as what's in the GAC:
AReverser, Version=2.0.0.0, Culture=neutral, PublicKeyToken=f0548c0027634b66
BUT if I uninstall AReverser from the GAC and attempt to run my exe as admin prompt I get the following error which indicates its looking for the expected public key token f0548c0027634b66:
C:\path\to\lab>gacutil /u "AReverser,Version=2.0.0.0,Culture=neutral,
PublicKeyToken=f0548c0027634b66"
Microsoft (R) .NET Global Assembly Cache Utility. Version 4.0.30319.1
Copyright (c) Microsoft Corporation. All rights reserved.
Assembly: AReverser, Version=2.0.0.0, Culture=neutral, PublicKeyToken=f0548c0027
634b66
Uninstalled: AReverser, Version=2.0.0.0, Culture=neutral, PublicKeyToken=f0548c0
027634b66
Number of assemblies uninstalled = 1
Number of failures = 0
C:\path\to\lab>Client.exe
Unhandled Exception: System.IO.FileLoadException: Could not load file or assembl
y 'AReverser, Version=2.0.0.0, Culture=neutral, PublicKeyToken=f0548c0027634b66'
or one of its dependencies. The located assembly's manifest definition does not
match the assembly reference. (Exception from HRESULT: 0x80131040)
at MainApp.Main()
Notice under Admin, its actually searching for the correct publicKeyToken.
What gives? Why would the searched for publickKeyTokens differ? What could I have done wrong?
EDIT
The app config we're told to use may be the culprit, I'm wondering if you have to be admin to apply some of these settings. Getting rid of it seems to cause running as admin to fail (although in that case publicKeyToken is listed as NULL). Here's my app config
<configuration>
<runtime>
<assemblyBinding
xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="MyStringer"/>
<publisherPolicy apply="no"/>
<dependentAssembly>
<assemblyIdentity name="AReverser"
publicKeyToken="f0548c0027634b66"
culture=""/>
<publisherPolicy apply="no"/>
<bindingRedirect oldVersion="2.0.0.0"
newVersion="2.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
A: Search your disk for AReverser.dll. It is possible that you have some additional copies somewhere hidden. VS can make shadow copies of compiled dlls.
If that doesn't help activate fusion logging (use fuslogvw.exe or spool fusion logs to disk) and then look in logs where the problematic dll is loaded from.
IMO it is the wrong dll that is loaded.
A: Where is your solution say the assembly is? Visual studio doesn't use the gac to build so if you have an different version of the aigned assembly assembly left behind in your reference directory, the client will be built against that and fail when attempting to load at runtime because the gac is loaded first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Post and receive google map location data to/from external website and android application I'm rather new to android development but I have a little project that I'd like to do and would like to know if it was possible to do.
Basically what I'd like is for an Android app to add location nodes to an external database and also allow the app to read the database and display all of the nodes stored in it. This allows a user of the app app to add nodes to the database and any other user of this app will display the nodes when the app is launched and vice versa.
Is this possible to achieve? And if so what sort of resources would I need to accomplish this?
I'm guessing I might need to use the Google Map API?
A: To show locations on a map use a MapActivity. If you need to get the user's location use the LocamationManager.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using print.css with @media print elsewhere I've got a webpage that uses a site global print.css stylesheet to render the page for print. The page also uses sitewide classes for divs, headers, etc.
I need to increase the width of the body and the size of the font of this page in the print version. I don't have access to edit the global print.css, and would prefer not to make my changes there because the changes will affect other pages that I don't want to change (due to the use of global styles, div classes, etc.).
Fortunately, this page does have its own stylesheet, foo.css that I can edit to make changes that will only affect this page.
Further complicating this is that the page has an inline style on the body class that I need to change for print only.
Normally I would edit foo.css with my style change, using !important to override the inline style as needed, but what I can't figure out is:
*
*Can I use @media print { body {width: 900px; !important;}} in foo.css and have it work even though I already have a print.css?
I've been trying to test this in Firebug (with Web Developer Toolbar), but if I add the @media print call to foo.css, nothing seems to happen.
Thoughts?
A: This should be possible. Things to check:
*
*is foo.css included with all media?
*You shouldn't have a ; before !important.
*Does your @media selector have higher specificity than the inline style?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Terminal emacs colors only work with TERM=xterm-256color I've found that terminal emacs does not render the correct colors unless I explicitly set TERM=xterm-256color. I use gnome-terminal, and from what I understand, TERM should be set to gnome-256color. Similarly, I tend to use tmux a lot, which advises against any TERM setting other than screen-256color. Unfortunately, both of those settings (within their respective context - gnome-terminal or tmux) result in emacs having wrong colors, whereas vim displays colors correctly. However, if I export TERM=xterm-256color, the colors work just fine in emacs.
Can anyone explain what's going on, or offer a solution?
Update
Here's what I'm dealing with:
I can get the colors to look correct in the terminal by adding the following to my init.el:
(defun terminal-init-gnome ()
"Terminal initialization function for gnome-terminal."
;; This is a dirty hack that I accidentally stumbled across:
;; initializing "rxvt" first and _then_ "xterm" seems
;; to make the colors work... although I have no idea why.
(tty-run-terminal-initialization (selected-frame) "rxvt")
(tty-run-terminal-initialization (selected-frame) "xterm"))
This feels really, really wrong though. There has to be a logical explanation for this...
P.S.
I have very little knowledge of terminfo and the precise role that $TERM plays in the process of color terminal behavior. If it's safe to always use xterm-256color (even when $TERM "should" be gnome-256color or screen-256color), I'll go with that.
A: I am not that familiar with how emacs handles different terminals exactly. But looking at lisp/term directory in emacs sources, I found out that the existence of a function terminal-init-xxx allows you to add support for different terminals. For example, I've got:
(defun terminal-init-screen ()
"Terminal initialization function for screen."
;; Use the xterm color initialization code.
(xterm-register-default-colors)
(tty-set-up-initial-frame-faces))
in my .emacs, which adds support for screen-256color. You may try defining a similar function for gnome by renaming the above function to terminal-init-gnome.
NOTE: If you are interested, you can try to track down the calls from tty-run-terminal-initialization code. It first gets the terminal type using tty-type function, then looks at certain locations to load a relevant terminal file, then tries to locate the matching terminal-init-xxx function, and finally calls it. It may help you figure out the correct name for gnome-terminal.
It looks like unless your TERM indicates that your terminal has 256 colors, emacs will only use 8. Changing TERM to gnome-256color allowed the color registration functions to work.
There is a way to cheat, after all. When I run gnome-terminal, my terminal is set to xterm by default. Instead of changing TERM variable, it is possible to redirect xterm to another terminal, say, gnome-256color. Simply create the directory $(HOME)/.terminfo/x, then run ln -s /usr/share/terminfo/g/gnome-256color ~/.terminfo/x/xterm. I think this is better than setting TERM manually in .bashrc, because it only redirects a particular terminal to something else. A console login would still leave TERM as linux, and not xterm-256color.
A: Add this to your ~/.emacs:
(add-to-list 'term-file-aliases
'("st-256color" . "xterm-256color"))
It tells emacs that if it sees TERM=st-256color then it should initialize the terminal as if it had seen TERM=xterm-256color.
Longer answer:
Emacs is showing strange colors because it thinks your terminal can only support 8 colors. In Emacs, run M-x list-colors-display to see the colors it thinks are available. The correct number of colors is detected during terminal-specific initialization. It says, in part:
Each terminal type can have its own Lisp library that Emacs loads when run on that type of terminal.
On my machine, the terminal-specific initialization files are in /usr/local/share/emacs/25.*/lisp/term. It has files for xterm, rxvt, screen, etc. but nothing for st. We need to help Emacs find the right initialization file. The documentation further says:
If there is an entry matching TERM in the term-file-aliases association list, Emacs uses the associated value in place of TERM
So that association list is a recommended way to handle unknown terminals. It works without you having to manually override the TERM environment variable.
A: On ubuntu 10.04 I too had noticed that running emacs -nw inside byobu/tmux/screen was using different colours from emacs -nw in the regular gnome-terminal.
I found that this is because byobu was setting TERM to screen-bce. Then setting TERM to xterm (for me, in the normal gnome-terminal TERM=xterm) gave me the same syntax highlighting when not running through byobu/screen.
So still not sure what the proper solution is.
See also this post:
Emacs Python-mode syntax highlighting
A: Maybe I'm not understanding something, buy why don't you run emacs like this:
TERM=xterm-256color emacs -nw
This way Emacs has its own TERM setting that you know works. You can also make an alias or wrap this in shell-script.
A: Terminals are a special type of device. When a process sends special byte sequences (called control sequences) to the terminal, it performs some action (like cursor positioning, change colors, etc).
You can read the ANSI terminal codes to find more detail about control sequences.
But terminals come from 70s, when hardware was limited in its capabilities, and a terminal cannot provide info about its capabilities (ie. which sequences it supports).
$TERM was used to resolve this issue - it allows programs to know what to send to the terminal to get the job done. termcap and terminfo are databases that store info about terminal capabilities for many $TERM names. If your $TERM is not in the db, you must ask an administrator to add it.
All terminal emulators inherit these limitations from old hardware terminals. So they need a properly set $TERM, and the terminfo/termcap DB MUST have data for this terminal. When a virtual terminal starts it sets the $TERM variable for you (and inside programs like bash). If $TERM is not in the terminfo/termcap you can quickly define an alias from $TERM to xterm-256color (you can find examples in the termcap file on how to do that).
A: This behavior has to do with the logic EMACS uses to determine whether the terminal background is dark or light. Run M-x list-colors-display with TERM set to either xterm-256color or screen-256color and you'll see that the exact same colors are listed. As you pointed out in the comments, the difference in color schemes that you've observed is due to the frame background mode. To see this, with your TERM set to screen-256color, compare the colors in
emacs -Q -nw --eval "(setq frame-background-mode 'light)"
and
emacs -Q -nw --eval "(setq frame-background-mode 'dark)"
The function frame-set-background-mode (in frame.el) checks to see whether the terminal type matches "^\\(xterm\\|\\rxvt\\|dtterm\\|eterm\\)" if it can't deduce the background color otherwise.
Within a running session, you can change the color scheme to 'light by evaluating
(let ((frame-background-mode 'light)) (frame-set-background-mode nil))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
} |
Q: How to keep CPU from 'sleeping' when screen is turned off in Android? I have an application in which I am sending network data over WiFI. Everything is fine until I turn the display off or the device goes to 'sleep'. I'm already locking the WiFi however, it seems to be the case that the CPU speed ramps down when in sleep which causes my streaming to not behave properly (i.e. packets don't flow as fast as I would like as they do when the device is not sleeping).
I know that I possibly can/possibly should address this at the protocol level however, that might possibly not be possible as well...
Is there any way to "prevent the CPU from going to 'sleep' when the screen is off"? If so, how? If not, any advice on how to keep the speed of my WiFi stream consistent whether the device is in sleep mode or not?
A: Grab a PARTIAL_WAKE_LOCK from the PowerManager. You'll also need to add the WAKE_LOCK permission to your manifest.
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Tag");
wl.acquire();
//do what you need to do
wl.release();
A: Okay, so, after much more research and experimenting, it seems that the real issue is the fact that, at least on some phones, their WiFi goes into a 'partial sleep' mode EVEN IF you've taken the WiFi lock. It seems that this is what the 'WIFI_MODE_FULL_HIGH_PERF' flag was invented for when taking the WiFi lock... unfortunately, this flag is only available on some devices/Android versions (I have no clue as to which but, it wasn't available to me). So, therefore, it isn't a fix for all devices.
The only "solution" (which is actually a kludge) seems to be to 'detect when the screen is turned off and then, set an alarm that turns the screen back on immediately thereafter'. The links that helped a little bit with this are:
How to keep a task alive after phone sleeps?
and
http://android.modaco.com/topic/330272-screen-off-wifi-off/
I hope that this helps people who are experiencing WiFi disruption when the phone goes to sleep/screen is turned off (and the phone is unplugged/disconnected [e.g. you won't see this effect when connected to adb; only when the phone is running with nothing connected to it]).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: I do not know why I keep on getting strange feedback when I am trying to format phone numbers from a user in java. Whenever I type in a phone number, this program below that I wrote to format phone numbers from the user gives me back weird numbers that I did not even enter at all. Can someone please explain to me why I am getting such weird errors?
I want it so when someone enters just 12345678978 it will format to 1-234-567-8978
If they enter 2345678978 it will format to 234-567-8978
And if they enter 5678978 it will change to 567-8978.
I always get weird numbers that sometimes aren't even what I entered like
12345678978 I get 144-34--567-
2345678978 I get 153-567-8978
5678978 I get 162-8978
I would really appreciate some help. Thanks.
import java.util.Scanner;
public class Test3 {
public static void main(String[] args) {
Scanner y = new Scanner(System.in);
String phoneNumber;
int phoneNumberLength;
System.out.print
("Please enter your phone number WITHOUT spaces or dashes: ");
phoneNumber = y.nextLine();
phoneNumberLength = phoneNumber.length();
if (phoneNumberLength == 11) {
phoneNumber = phoneNumber.charAt(0) + "-" + phoneNumber.charAt(1)
+ phoneNumber.charAt(2)
+ phoneNumber.charAt(3)
+ "-" + phoneNumber.charAt(4) + phoneNumber.charAt(5)
+ phoneNumber.charAt(6)
+ "-" + phoneNumber.charAt(7) + phoneNumber.charAt(8)
+ phoneNumber.charAt(9)
+ phoneNumber.charAt(10);
}
if (phoneNumberLength == 7) {
phoneNumber = phoneNumber.charAt(0) + phoneNumber.charAt(1)
+ phoneNumber.charAt(2)
+ "-" + phoneNumber.charAt(3) + phoneNumber.charAt(4)
+ phoneNumber.charAt(5) + phoneNumber.charAt(6);
}
else {
phoneNumber = phoneNumber.charAt(0) + phoneNumber.charAt(1)
+ phoneNumber.charAt(2)
+ "-" + phoneNumber.charAt(3) + phoneNumber.charAt(4)
+ phoneNumber.charAt(5)
+ "-" + phoneNumber.charAt(6) + phoneNumber.charAt(7)
+ phoneNumber.charAt(8)
+ phoneNumber.charAt(9);
}
System.out.println("So your phone number is " + phoneNumber + "?");
}
By the way. I know it is not formatted correctly but I am very confused with how stackoverflow allows you to add code.
A: Java is converting the characters from your charAt() calls to numerical values. Use substring methods instead, e.g.
phoneNumber = phoneNumber.substring(0, 3) + "-" + phoneNumber.substring(3);
A: Any string that starts like this:
number = number.charAt(0) + number.charAt(1) + ...
will cause the problem, because you are adding two char types together. This is treated as integer arithmetic, not string concatenation. It would be a lot better to add substrings together, so that the operator is string concatenation, instead of integer addition.
number = number.substring(0, 3) + '-' + number.substring(3, 6) + ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: XmlSimple - using xml_in() to parse data in Ruby on Rails I have a simple XML file like this:
<Course>
<CompanyName value="Ford"/>
<DepartmentName value="assessments"/>
<CourseName value="parts"/>
<Result>
<CoreData>
<Status value="completed"/>
In my controller I have:
def xml_facil
require 'xmlsimple'
config = XmlSimple.xml_in("#{Rails.root}/doc/TestResults/Ford/assessments/mike.xml", { 'KeyAttr' => 'value' })
@results = config['CourseName']
end
In my view I have:
<%= render @results %>
but the error I get is:
undefined method `formats' for nil:NilClass
I guess my method is returning nil here so how do I fix this so my view will render "parts"? Any help is appreciated!
A: Since you've switched to Nokogiri, you can dig out the value attribute that you're interested in with this:
require 'nokogiri'
doc = Nokogiri::XML(open("#{Rails.root}/doc/TestResults/Ford/assessments/mike.xml").read)
value = doc.at('CourseName').attr('value')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't call FB.ui in dev (localhost) environment I used to be able to, but for some reason all my Facebook Javascript API calls using FB.ui() no longer work in my development environment where my url is localhost:8080. In production it works fine though. I have a dev environment Facebook application, but I did just change URLs around in it. I assume that's where the problem is. How do I have a Facebook application that allows FB.ui() calls from dev and production environments? This is the error I get when calling FB.UI() in dev:
An error occurred with AppleTree dev. Please try again later.
API Error Code: 191
API Error Description: The specified URL is not owned by the application
Error Message: redirect_uri is not owned by the application.
A: I always add a entry in my hosts file for something like:
127.0.0.1 dev.mydomain.com
And then set my app domain in the app settings to mydomain.com (to allow subdomains). Then access your site in your browser at http://dev.mydomain.com:8080 and FB.ui should allow the call.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jquery show/hide button and tooltip I am trying to make a show/hide button with jquery and I would also like the tooltip/title to change when the button is hovered over with the mouse but it isn't working at all.
my code can be found here:
http://jsfiddle.net/LYA6q/
A: HTML:
<input id="button" type='button' value='Not Clicked' title = 'Not Clicked'>
Javascript:
$('#button').click(function() {
if ($(this).val() == "Not Clicked")
{
$(this).val("Clicked");
$(this).attr("title", "Clicked");
}
else
{
$(this).val("Not Clicked");
$(this).attr("title", "Not Clicked");
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Best way to print the result of a bool as 'false' or 'true' in c? I have to write a program in which main calls other functions that test a series of number if any are less than a number, if all the series' numbers are between two limits, and if any are negative. My code returns the values of 1 for true and 0 for false, but the assignment asks that they be printed as 'true' or 'false'. I'm not sure how to get the bool answers to print as a string from printf. I used if (atl == false) printf("false"); in my at_least.c and in main.c, but it returns only a long string of true or false (ex: truetruetrue....). I'm not sure if that is the correct coding and I'm putting it in the wrong spot or there was some other code that I need to use.
This is my main.c:
#include "my.h"
int main (void)
{
int x;
int count = 0;
int sum = 0;
double average = 0.0;
int largest = INT_MIN;
int smallest = INT_MAX;
bool atlst = false;
bool bet = true;
bool neg = false;
int end;
while ((end = scanf("%d",&x)) != EOF)
{
sumall(x, &sum); //calling function sumall
count++;
larger_smaller(x, &largest, &smallest); //calling function larger_smaller
if (atlst == false)
at_least(x, &atlst); //calling function at_least if x < 50
if (bet == true)
between(x, &bet); //calling function between if x is between 30 and 40 (inclusive)
if (neg == false)
negative(x, &neg); //calling function negative if x < 0
}
average = (double) sum / count;
print(count, sum, average, largest, smallest, atlst, bet, neg);
return;
}
my results for a set of numbers:
The number of integers is: 15
The sum is : 3844
The average is : 256.27
The largest is : 987
The smallest is : -28
At least one is < 50 : 1 //This needs to be true
All between 30 and 40 : 0 //This needs to be false
At least one is negative : 1 //This needs to be true
This is in C, which I can't seem to find much on.
Thanks in advance for your help!
ADDENDUM:
This is repeated from an answer below.
This worked for the at_least and negative functions, but not for the between function. I have
void between(int x, bool* bet)
{
if (x >= LOWER && x <= UPPER)
*bet = false;
return;
}
as my code. I'm not sure what's wrong.
A: Alternate branchless version:
"false\0true"+6*x
A: So what about this one:
#include <stdio.h>
#define BOOL_FMT(bool_expr) "%s=%s\n", #bool_expr, (bool_expr) ? "true" : "false"
int main(int iArgC, char ** ppszArgV)
{
int x = 0;
printf(BOOL_FMT(x));
int y = 1;
printf(BOOL_FMT(y));
return 0;
}
This prints out the following:
x=false
y=true
Using this with type bool but int should work the same way.
A: You could use C's conditional (or ternary) operator :
(a > b) ? "True" : "False";
or perhaps in your case:
x ? "True" : "False" ;
A: x ? "true" : "false"
The above expression returns a char *, thus you can use like this:
puts(x ? "true" : "false");
or
printf(" ... %s ... ", x ? "true" : "false");
You may want to make a macro for this.
A: I have three arrays for that:
strbool.c:
#include "strbool.h"
const char alx_strbool[2][6] = {"false", "true"};
const char alx_strBool[2][6] = {"False", "True"};
const char alx_strBOOL[2][6] = {"FALSE", "TRUE"};
strbool.h:
#pragma once
/* rename without alx_ prefix */
#if defined(ALX_NO_PREFIX)
#define strbool alx_strbool
#define strBool alx_strBool
#define strBOOL alx_strBOOL
#endif
extern const char alx_strbool[2][6];
extern const char alx_strBool[2][6];
extern const char alx_strBOOL[2][6];
Disclaimer: The prefixes are necessary because names starting with str are reserved (actually, only strbool), but until they are actually used by C or POSIX, I will use the short version.
It's very simple to use them:
#include <stdio.h>
#define ALX_NO_PREFIX
#include "strbool.h"
int main(void)
{
int var = 7;
printf("var is %s\n", strBool[!!var]);
return 0;
}
var is True
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Is there any clever way to determine whether a point is in a rectangle? I want to calculate whether a point, (x,y), is inside a rectangle which is determined by two points, (a,b) and (c,d).
If a<=c and b<=d, then it is simple:
a<=x&&x<=c&&b<=y&&y<=d
However, since it is unknown whether a<=c or b<=d, the code should be
(a<=x&&x<=c||c<=x&&x<=a)&&(b<=y&&y<=d||d<=y&&y<=b)
This code may work, but it is too long. I can write a function and use it, but I wonder if there's shorter way (and should be executed very fast - the code is called a lot) to write it.
One I can imagine is:
((c-x)*(x-a)>=0)&&((d-y)*(y-b)>=0)
Is there more clever way to do this?
(And, is there any good way to iterate from a from c?)
A: Swap the variables as needed so that a = xmin and b = ymin:
if a > c: swap(a,c)
if b > d: swap(b,d)
a <= x <= c and b <= y <= d
Shorter but slightly less efficient:
min(a,c) <= x <= max(a,c) and min(b,d) <= y <= max(b,d)
As always when optimizing you should profile the different options and compare hard numbers. Pipelining, instruction reordering, branch prediction, and other modern day compiler/processor optimization techniques make it non-obvious whether programmer-level micro-optimizations are worthwhile. For instance it used to be significantly more expensive to do a multiply than a branch, but this is no longer always the case.
A: I like the this:
((c-x)*(x-a)>=0)&&((d-y)*(y-b)>=0)
but with more whitespace and more symmetry:
(c-x)*(a-x) <= 0 && (d-y)*(b-y) <= 0
It's mathematically elegant, and probably the fastest too. You will need to measure to really determine which is the fastest. With modern pipelined processors, I would expect that straight-line code with the minimum number of operators will run fastest.
A: While sorting the (a, b) and (c, d) pairs as suggested in the accepted answer is probably the best solution in this case, an even better application of this method would probably be to elevate the a < b and c < d requirement to the level of the program-wide invariant. I.e. require that all rectangles in your program are created and maintained in this "normalized" form from the very beginning. Thus, inside your point-in-rectangle test function you should simply assert that a < b and c < d instead of wasting CPU resources on actually sorting them in every call.
A: Define intermediary variables i = min(a,b), j = min(c,d), k = max(a,b), l = max(c,d)
Then you only need i<=x && x<=k && j<=y && y<=l.
EDIT: Mind you, efficiency-wise it's probably better to use your "too long" code in a function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Copying devices in Linux I am working at an OS independent file manager, in C. I managed to copy files, links and directories, but I am not sure how to copy devices. I would appreciate any help.
A: To create a device file, use the mknod(2) syscall. The struct stat structure will give you the major and minor device numbers for an existing device in st_rdev.
Having said that, there is little value in "copying" a device because a device doesn't contain anything useful. The major and minor numbers are specific to the OS on which they exist.
A: It's not really a useful feature, IMHO. tar(1) needs to be able to do it as part of backing up a system, and setup programs need to be able to create them for you when setting up your system, but few people need to deal directly with device files these days.
Also, modern Linux systems are going to dynamic device files, created on the fly. You plug in a device and the device files appear; you unplug it and they disappear. There is really no use in being able to copy these dynamic files.
A: dd is your friend (man dd)
dd if=/dev/sda1 of=/some_file_or_equally_sized_partition bs=8192
if you want to copy the device-file itself, do this:
cp -p device-filename new-filename
e.g.:
cp -p /dev/sda1 /tmp/sda1
those are both equivalent device files, and can be used to access the device.
If you're want to do this from C, use mknod() .. see "man 2 mknod"
A: This might be useful
cp -dpR devices /destination_directory
cp -dpR console /mnt/dev
A: You don't. Just filter them out of the view such that it can't be done.
Use the stat function to determine the file type.
A: Check if you've the udev package, if you do, chances are that devices are generated on the fly, from the package description:
udev - rule-based device node and kernel event manager
udev is a collection of tools and a daemon to manage events received from the
kernel and deal with them in user-space. Primarily this involves creating and
removing device nodes in /dev when hardware is discovered or removed from the
system.
Events are received via kernel netlink messaged and processed according to
rules in /etc/udev/rules.d and /lib/udev/rules.d, altering the name of the
device node, creating additional symlinks or calling other tools and programs
including those to load kernel modules and initialise the device.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to make cucumber run all feature if no matching tag Im using cucumber with fork. I really like the run_all_when_everything_filtered on Rspec. that runs all the spec if there is no matching tag. Can I do this with cucumber. example in my auto test profile, i specify --tags @wip, but if there is no matching tags it run all of the scenario
A: I'm pretty sure that Cucumber doesn't support this natively. If you're using Guard to run these, you could probably get the behaviour you're after by calling out to a script or custom rake task instead of invoking Cucumber directly.
It should be fairly trivial to write a script or rake task to invoke Cucumber with the -t @wip argument, then check to see if the output contains '0 scenarios', and if so then run Cucumber again without a -t argument, to execute the whole suite.
A: If you know the name of the tag, you can specify the tag with an "~" before the tag. That is --tags ~@wip.
What this means, is the tag you specify to cucumber, can be a boolean expression.
*
*The "~" option before the tag, represents a NOT.
*You can specify an OR, if you write --tags @wip1,@wip2.
*You can specify an AND, by writing the --tags options several times.
I encourage you to run cucumber -h and checkout the option --tags, to see more information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Multi-boxed layout in CSS using DIVs I'm making a website and trying to create a login box. I have a website with two boxes of content, and I want to add a third "login box".
However, I can't seem to do this, because it appears above (when I have the current width of the container) or above (when I increase the width of the container to accommodate for the increase of space because of the box).
Also, margins don't seem to be affecting the newly created box either.
Here is what I want it to look like: http://i.stack.imgur.com/Kmm1g.jpg
And here is the current website: http://www.winterlb.com/
So my question is, what is the easiest way to accomplish this? Thanks.
A: You can put your login box and your nav box in the same div. Float this div and the main content div like so:
HTML:
<div id="navBar">
<div id="loginBox">
...
</div>
<div id="navBox">
...
</div>
</div>
<div id="mainContent">
...
</div>
CSS:
div#navBar {
float: left;
width: 200px;
}
div#mainContent {
float: left;
width: 600px;
}
A: Add the 'third box' inside your 'sidebar' and add another div to wrap your original sidebar content.
Style the approriate login div and navigation div. Float them left if needed.
Here's a sample html of what the structure should look like http://pastebin.com/3hLmGzRZ
A: You will never accomplish this properly without a doctype. You are in quirks mode. Add this to your first line and then see where we are:
<!DOCTYPE html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unit test expected to throw an exception when calling an asynchronous operation on MSTest The source code below is an example code snippet about my problem. I expect an exception to be occurred when an asynchronous operation is called.
Unit Test
[TestMethod()]
[ExpectedException(typeof(Exception))]
public void OperateAsyncTest()
{
//Arrange
var testAsyncClass = new TestAsyncClass();
//Act
testAsyncClass.OperateAsync();
}
Code
public class TestAsyncClass
{
public void OperateAsync()
{
ThreadPool.QueueUserWorkItem( obj =>{
throw new Exception("an exception is occurred.");
});
}
}
However, MsTest cannot catch the exception because probably, the test thread is different from the thread throwing the exception. How is this problem solved? Any idea?
The following code is my workaround, but it is not smart or elegant.
Workaround
[TestClass()]
public class TestAsyncClassTest
{
private static Exception _exception = new Exception();
private static readonly EventWaitHandle ExceptionWaitHandle = new AutoResetEvent(false);
static TestAsyncClassTest()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
_exception = (Exception)e.ExceptionObject;
ExceptionWaitHandle.Set();
}
[TestMethod()]
[ExpectedException(typeof(Exception))]
public void OperateAsyncTest()
{
//Arrange
var testAsyncClass = new TestAsyncClass();
//Act
lock(_exception)
{
testAsyncClass.OperateAsync();
ExceptionWaitHandle.WaitOne();
throw _exception;
}
}
}
A: Perhaps you could implement your asynchronous operation as a Task, return it from OperateAsync and then Task.Wait from the caller?
Task.Wait will "observe" the exception so your unit test can detect it (provided you adorn it with ExpectedException attribute).
The code would look like this:
public class TestAsyncClass {
public Task OperateAsync() {
return Task.Factory.StartNew(
() => {
throw new Exception("an exception is occurred.");
}
);
}
}
[TestClass]
public class TestAsyncClassTest {
[TestMethod]
[ExpectedException(typeof(AggregateException))]
public void OperateAsyncTest() {
var testAsyncClass = new TestAsyncClass();
testAsyncClass.OperateAsync().Wait();
}
}
Note that you'll get an AggregateException from the Task.Wait. Its InnerException will be the exception you threw from OperateAsync.
A: The exception occurs on a different thread and has to be handled accordingly. There are a few options. Please take a look at these two posts:
*
*Async command pattern - exception handling
*Asynchronous Multithreading Exception Handling?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: RegEx to replace trailing underscore with number of a string I have an ID that looks like this: prefix_my-awesome-slug_123
Now I would like to have a regular expression that removes the underscore and number on the end (_%d).
A: for perl like regex implementations this should do it:
s/_\d+$//
A: /_[0-9]+$/ - easy. Just replace the match with an empty string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: How to use execv for commands whose location is not known? Say I want to spawn a process and run execv to execute a command like ls then this is how i do it:
char * const parm[] = { "/usr/bin/ls","-l" , NULL };
if ((pid = vfork()) == -1)
perror("fork error");
else if (pid == 0)
{
execv("/usr/bin/ls", parm);
}
Now the question is that here I have hard coded where the ls command is present (/usr/bin/ls). Now suppose I do not know where a particular command is present and want to execute it then how do I go about it? I know in a regular shell the PATH variable is looked up to achieve the same, but in case of a C program using execv how do I achieve it?
A: Use execvp(3) instead of execv(3). execvp and execlp work exactly like execv and execl respectively, except they search the $PATH environment variable for an executable (see the man page for full details).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: HTML Frames HTML frames are a way of displaying multiple HTML documents in a single browser window. | {
"language": "en",
"url": "https://stackoverflow.com/questions/7617500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Silverligtht WCF enabled service with Prism Im required to write a Silverlight application using WCF.
I'm also required to use Dependency Injection to gain access to this service in another library.
(I add a Silverlight enabled WCF Service)
The problem is in trying to use Dependency Injection (Prism/MEF in this case). When I make a Silverlight Shared library that will have interfaces for this service, I cannot add this library in the ASP.Net project due to the fact that it is Silverlight library. If I make a non-Silverlight library I cannot add that library to other projects to share that common interface.
Basically I need a library I think to share between projects in Silverlight so I can do this service injection.
Any information is appreciated
A: Whether you realise it or not, your question is a duplicate of this one: Shared data object between WCF service and Silverlight app While not asked the same way, the answer is the same.
You need to create a separate project, and share the code files (as links) from one project to the other. Your problem is that the Silverlight project is compiled for a different runtime to the ASP.NET/WCF project. Because they cannot reference a common library, linking the shared files as mentioned is the easiest way to share code between the two projects targetting different runtimes.
A: As slugster said - this done via linking to windows library files from silverlight library.
You do it as described here: http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2010/01/20/linking-files-in-visual-studio.aspx
I just wanted to add.. Since you go there - what you need is another Framework/Technology. Usually those classes you talking about depend on other classes/namespaces that live in windows only or silverlight only world. And then you need to transfer object data via wire.
Microsoft's solution to this - RIA Services. What it does - it takes your Windows classes and generates proxy classes on Silverlight side. Kind of what you need. And it works with WCF services.
There is 3rd party solutions like CSLA and DevForce.
I use DevForce and it does many things automatically, but instead of generating proxy classes - it creates links just like what you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Javascript mp3 audio data Say i have a HTML5 tag. Is there any possible way for Javascript on the page to get the current speaker output, and then graph it to produce a volume bar that got larger when the music got louder and smaller when the music got quieter? I don't care if it works in IE or not. If this is not possible, would it be possible to extract that data out of the mp3 file and hope it lines up? I REALLY don't want to use flash.
Edit: I was inspired by this. Unfortunately it uses hard-coded values which wont work for me.
A: Short answer, yes it's possible. Check out the esteemed Mr. Doob's example. Sadly, looks like the explanatory blog post is down.
Mozilla has a custom extension, but Doob's example is working in WebKit...
A: The JS Audio Data API will let you do this with an html5 audio tag, or audio that is played from javascript. See https://wiki.mozilla.org/Audio_Data_API for details and examples. I don't know offhand what the status of this API is in current browsers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Something with raytracing that has gone wrong I'm trying to do a simple ray tracing assignment, in c# (ported from python).
I've managed to make the sample code show the correct picture, but when I try and adapt it to my assignment something goes wrong.
If I knew what was going wrong I would post some code that I thought might help, but I have no idea where to start.
Basically my assignment outputs something like this:
http://i56.tinypic.com/2vcdobq.png
With specular highlighting on, and
http://i53.tinypic.com/2e1r38o.png
With it off.
It's suppose to look something like:
http://i56.tinypic.com/2m7sxlh.png
My Phong lighting formula looks like:
Colour I = diffuse_colour;
Vector L = light.vector;
Vector N = normal; //FIXME!
Colour Is = diffuse_colour * light.intensity;
Colour Ia = new Colour(1,1,1) * light.ambient;
Colour Kd = specular_colour;
Colour Ka = Kd;
double Ks = sharpness ?? 0.4;
Vector H = Vector.unit(view + L);
//Phong Illumination
//I = KaIa + KdIs max(0,L.N) + KsIs (H.N)^n
I = Ka * Ia
+ Kd * Is * Math.Max(0, L.dot(N))
+ Ks * Is * Math.Pow(H.dot(N),200); //FIXME?
And I copied it from the working sample code, so I know it works.
Any thoughts would be great, because I'm stumped.
A: You have two implementations of the same algorithm. You claim that they produce different results. Finding the mistake seems straightforward: run both algorithms step by step in their respective debuggers, simultaneously. Watch the state of both programs carefully. The moment they produce different program states, there's your bug.
A: It wasnt quite as simple as that, as one implementation was in python, and the other in c#.
Turns out there were 2 things wrong.
First, In my point class one of my overload operators was wrong. (the operator - on 2 points, i had it returning Vector (p1.x - p2.x, p1.y - p2.y, p1.x - p2.x) ... where that last pair should have been p.z instead.
The other mistake i made was when i was saving the bitmap image, i got the columns and rows mixed up, in terms of x and y. (Col = x, Row = y)
Hope this helps anyone else that runs into random problems like me :P
A: While I was writing my ray tracer, I have studied this article to get a good understanding about Phong Illumination.
So have a look at here, I am sure you will get an idea:
www.gamedev.net/page/resources/_/technical/graphics-programming-and-theory/phong-illumination-explained-r667
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Ant mkdir failed i'm new to ant. Please highlight which goes wrong in my build.xml. Any help is appreciated. Thanks.
Problem: The folders i wanted to make kept created on the upper level of current directory.
*
*ant version: 1.8.0
*platform: LinuxMint 10.10
*java version "1.6.0_20"
*OpenJDK Runtime Environment (IcedTea6 1.9.9) (6b20-1.9.9-0ubuntu1~10.10.2)
*OpenJDK Server VM (build 19.0-b09, mixed mode)
build.xml:
<property name="prj.root" value="." />
<property name="build.dir" value="${prj.root}/build"/>
<property name="build.docs" value="${build.dir}/docs"/>
<property name="build.models" value="${build.dir}/models"/>
<property name="build.projects" value="${build.dir}/projects"/>
<property name="dist.dir" value="${prj.root}/dist"/>
<target name="clean">
<delete dir="${build.dir}" />
<delete dir="${dist.dir}" />
</target>
<target name="init" depends="clean" description="initialization target">
<echo message=">> Build JAS ${jas.version} at ${prj.root}"/>
<echo message="build.dir = ${build.dir}" />
<mkdir dir="${build.dir}"/>
<mkdir dir="${build.docs}" />
<mkdir dir="${build.models}" />
<mkdir dir="${build.projects}" />
<mkdir dir="${dist.dir}"/>
</target>
Execution + Output:
yamhon@yamhon-g410 ~/projects/JAS $ ant init
Buildfile: /home/yamhon/projects/JAS/build.xml
clean:
[delete] Deleting directory /home/yamhon/projects/build
[delete] Deleting directory /home/yamhon/projects/dist
init:
[echo] >> Build JAS ${jas.version} at .
[echo] build.dir = ./build
[mkdir] Created dir: /home/yamhon/projects/build
[mkdir] Created dir: /home/yamhon/projects/build/docs
[mkdir] Created dir: /home/yamhon/projects/build/models
[mkdir] Created dir: /home/yamhon/projects/build/projects
[mkdir] Created dir: /home/yamhon/projects/dist
BUILD SUCCESSFUL
Total time: 0 seconds
yamhon@yamhon-g410 ~/projects/JAS $
A: Two things you can try.
1) Resolve your relative '.' path by assigning it to a property with the location attribute.
<property name="my.path" location="."/>
<echo message="my.path = ${my.path}"/>
2) Use the build in basedir property which points to the directory of the build.xml file itself.
<echo message="basedir = ${basedir}"/>
This should get you going :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Animate two views like when you pass a phone call I have made many tries to have the same effect of switch than the one you can see when calling a phone number : the front view disapear with a zoom effect, while the other one appears also with a zoom effect.
I can't achieve doing that effect, it's always a so-so. There seems to have a scale effect, with an action on opacity, but...
Do you know how this can be done to reflect that effect (not a so-so, I have tons of those) ?
A: // Make this interesting.
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2.0];
[UIView setAnimationTransition:UIViewAnimationTransitionNone forView:self.view cache:YES];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(startupAnimationDone:finished:context:)];
self.view.alpha = 0.0;
self.view.frame = CGRectMake(self.view.center.x,self.view.center.y , 0, 0);
[UIView commitAnimations];
}
I hope this is a framework for a better animation. It's not guaranteed to work, but it's the best I could think of for the first part of the transition.
This will change the frame of your view controller's view so that it "sucks" itself into the center of the screen, which is a natural black color. Now that I think about it, a CGAffineTransform would have been much easier...
EDIT (For pedantry's sake): Starting with iOS 4, you can now use the newer, and much more syntactically clean, animation blocks and a nice transform:
[UIView animateWithDuration:0.25 delay:0.0 options:0 animations:^{
//animate the toolbars in from the top and bottom
[myTopView setFrame:CGRectMake(0, self.view.frame.size.height - 44, self.view.frame.size.width, 44)];
[myBottomView setFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
//fade to black...
self.view.alpha = 0.0;
//and suck inwards.
self.view.frame = CGRectMake(self.view.center.x,self.view.center.y , 0, 0);
}
completion:^{
//do something to end nicely, or start another animation block.
}];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: bash file reading, while loop I'm sorry if this has been answered but since I'm not positive what exactly is the problem (among several possibilities) I haven't been successful in my searches.
What I want to do is take label numbers that are each written as a line in a text file, do things with files containting that label, and output the results to a file. What I have is this:
cat good_PFC.txt | while read line;
do
base_file=${line}_blah.nii.gz
new_fa=${line}_fa_uncmasked.nii.gz
new_tr=${line}_tr_uncmasked.nii.gz
if [ -e $base_file ]; then
echo -n "$line " >> FA_unc_stats.txt
fslstats $new_fa -M | tr '\n' ' ' >> FA_unc_stats.txt
fslstats $new_fa -S | tr '\n' ' ' >> FA_unc_stats.txt
else
echo $line "not a file"
fi;
done
In which fslstats is a command that outputs numbers and good_PFC.txt is a test file containing
123
125
132
The output in FA_unc_stats.txt is
123 0.221061 0.097268
What's wrong is, the terminal correctly outputs "125 not a file", but does nothing with 132, which I know happens to point to a real file. So I believe something is wrong with the syntax in my while loop, but I don't know what! I bet it's something stupid but I just can't figure it out. Thanks!
ETA:
Fixed by adding a newline to the end of good_PFC.txt Now the problem is I need a newline written to the output file whenever I get to a new label, but it doesn't do that. I tried adding
echo /n >> FA_unc_stats.txt
first, but it prints "/n" on it's own line... I fail at newline commands!
A: Do you know if the loop is being run on the last line at all? Bash may be skipping the last line due to a lack of a newline terminator. Try adding a newline to the last line in the file and see if that fixes the problem.
A: Just add 'echo $line' and you will see if the read loop is working as you expect.
A: Remove the first pipe with
while read line; do
...
done <good_PFC.txt
A: try putting the fslstsats commands in back ticks:
`fslstats $new_fa -M | tr '\n' ' ' >> FA_unc_stats.txt`
`fslstats $new_fa -S | tr '\n' ' ' >> FA_unc_stats.txt
`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to set the shared preferences value to a layout I have already put everything about shared preferences in place and in one of my activity I am also able to retrieve the shared preferences values like this in logcat.
String i = prefs.getString("bgColor", "#f2345");
System.out.println(i);
But in this activity I am using a layout like this
SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.country_row,c, from, to);
setListAdapter(sca);
where "country_row" is my xml layout file which is like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:id="@+id/year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff000099"
android:background="#ffffff80"
android:padding="10dp"
android:textSize="16sp"
android:text="1964"/>
<TextView android:id="@+id/country"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="#ffffff80"
android:background="#ff000099"
android:padding="10dp"
android:textSize="16sp"
android:text="Sweden"/>
Now using the values that I am already getting from the preferences, I want to change here for example background color or font size being displayed. All I want now is just to imply these shared prefernces values to my layout xml file. How can I do that, I am not being able to do that?
Actually I can get the values from shared preferences like this
boolean i = prefs.getBoolean("fontBold", false);
System.out.println(i);
if (i){
TextView tv = (TextView)findViewById(R.id.year);
tv.setTypeface(null, Typeface.BOLD);//null pointer
}
In the cursor adapter I am already applying a layout country_row.xml. So how can I use the preferences value I am getting to this layout. The boolean value that I am getting from checkbox is correct as I have also printed out to see it. But when I try to do like above it doesn't work and the program crashes saying the null pointer exception.
The thing I am stuck here is....I am getting the correct preferences value but don't know how to use it or apply it to my existing layout...or do i need to make different layout...i am not sure about it.
A: I think what you want to do is to change some layout parameters dynamically in codes.
Generally, you can set attributes to a view(Layout, TextView,EditText,etc.) either by code or by .xml file.
Take a layout as example.
First add an id attribute to the layout.
<LinearLayoout android:id="@+id/layoutID" .../>
Then
LinearLayout layout=(LinearLayout)findViewById(R.id.layoutID) //get the layout object.
layout.setBackgroundColor (color from your preferences);
Above is the basic idea. Please read SDK document to find mor info.
A: As like Huang answer,
1) You should have to create the reference for the layout or view to whom you have to change the properties.
2) After that get the preference's value in to respective variable.
3) Set the value to that layout or view to get effect.
It will surly going to work. For more reference see the below Example for the in which selection of checkbox i do some action like to play Music.
myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
fullResultSound = myPrefs.getBoolean("FullResultIsOn", false);
lessResultSound = myPrefs.getBoolean("LessResultIsOn", false);
System.out.println("============================= The FullResultSound in Result Page is: "+fullResultSound);
System.out.println("============================= The LessResultSound in Result Page is: "+lessResultSound);
if(fullResultSound)
{
playSound(soundFileForFullResult);
}
else
{
playSound();
}
Hope it will works for you. If not then tell me.
A: Actually how I managed to change the layout of the view was by doing this.
ContentResolver contentResolver = getContentResolver();
Cursor c = contentResolver.query(CONTENT_URI, null, null, null, sortOrder);
String[] from = new String[] { "year", "country" };
int[] to = new int[] { R.id.year, R.id.country };
SimpleCursorAdapter sca = new MySimpleCursorAdapter(this, R.layout.country_row,
c, from, to);
setListAdapter(sca);
class MySimpleCursorAdapter extends SimpleCursorAdapter{
public MySimpleCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
// TODO Auto-generated constructor stub
}
@Override // Called when updating the ListView
public View getView(int position, View convertView, ViewGroup parent) {
/* Reuse super handling ==> A TextView from R.layout.list_item */
View v = super.getView(position,convertView,parent);
TextView tYear = (TextView) v.findViewById(R.id.year);
TextView tCountry = (TextView) v.findViewById(R.id.country);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean font_size = prefs.getBoolean("fontSize", false);
boolean italic_font = prefs.getBoolean("fontItalic", false);
String listpref = prefs.getString("bgColor", "#ffffff80");
//System.out.println(listpref);
tYear.setBackgroundColor(Color.parseColor(listpref));
tCountry.setBackgroundColor(Color.parseColor(listpref));
if (font_size){
tYear.setTextSize(25);
tCountry.setTextSize(25);
}
if (italic_font){
tYear.setTypeface(null, Typeface.ITALIC);
tCountry.setTypeface(null, Typeface.ITALIC);
}
//tv.setBackgroundColor(col);
return v;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Authorize login URL in asp.net MVC 3 I am working on an Asp.Net MVC 3 application. I have created admin area for the website and applied [Authorized] attribute to actionmethods after login. When I try to access these urls directly without login like admin/home or admin/productlist, I am redirected to /Home/Login with authentication error. I want to redirect to Admin/Login.
Please suggest.
Thanks
A: If this is a Stock MVC 3 Authorization then myself as well as many others have had problems with the incorrect url address being set for the "LogOn" Action... For some reason authorize is trying to send a user to Account\Login and looking at the account views tells that there is actually no "Login" view it is called "LogOn" so you have to fix this in the Web.config file with the following:
<add key="loginUrl" value="~/Account/LogOn" />
A: The login URL for ASP.NET applications (including MVC3 ones) is controlled in web.config, in the forms authentication section:
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Home/Login" timeout="2880" />
</authentication>
</system.web>
</configuration>
The trick for you is that you want two different login URLs. ASP.NET has a great feature where you can have a web.config file in each directory of your project, and as needed it will use the most specific setting it can find, up to the root web.config. So in the folder where you have your admin views ("Admin" I'm guessing), you should be able to create a second web.config, which will apply only to those pages and lower in the tree:
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Admin/Login" timeout="2880" />
</authentication>
</system.web>
</configuration>
A: You can override your Authorize action filter to handle those issues. For example, you can check not only roles, but some specific permissions, and redirect to different Url's. And also using this approach can take into account your routing configuration.
Take a look at this answer : asp.net mvc Adding to the AUTHORIZE attribute
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Where to find Open Source Implementations of Hashing/Crypting Algorithms(header files) I am trying to find open source implementations of Hashing/Crypting(is it HMAC?) algorithms such as SHA256, SHA512, MD5. This is in C++/C
I know of things like Crypto++ but I find them really difficult to include in my projects because they are in DLL's, ie, I really just dont know how to include & use them in my projects & also I think they make my projects too large unecessarily.
I once found an open source SHA256 header file & .cpp implementation(on google) but I cannot refind it on google.
Anyone know of any or maybe a website with a whole lot of them?
A: Use Google Code Search instead of Google. It'll search open source repositories for whatever you need.
Here is a search for MD5 or SHA implementations in C or C++.
A: I think you still want Crypto++, you seem to have some misconceptions about it.
I know of things like Crypto++ but I find them really difficult to include in my projects because they are in DLL's
You can build Crypto as a static lib. Are you on Windows? The .vcproj file includes a configuration for static building. If you are on Linux, the Makefile also has this.
I really just dont know how to include & use them in my projects
If you build the library statically then usage is very simple. Just add the Crypto++ directory as an include path to your compiler configuration, and add the .lib or .a (depending on your platform) to your linker's configuration.
also I think they make my projects too large unecessarily.
This is another misconception. If you build the Crypto++ static library, then only the portions of the library that you use will be included in your executable. So while the static library can be huge, if you just use the MD5 algorithm, only the MD5 code will be included in your app.
Give Crypto++ another try, it's well worth it!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python Nelder Mead with Kelley restarts I am trying to use the fmin function in scipy.optimize, which implements straightforward Nelder Mead minimization. Is there a version which exists which includes C.T. Kelley's restart?
Thanks,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android: What is the standard to load a file from the filesystem? I am creating an Android app for the Samsung Galaxy Tab 10.1, but the user needs to be able to choose a file (like a text file) from the file system. In Windows, the easiest way to do this would be through an "Open File Dialog Box", but is there a standardized/built-in/simple way to do the same thing on an Android tablet?
Thanks a bunch!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Options for communicating between Chrome Extension and Embedding Page's Javascript I am monitoring browser events such as when a new tab is created. My extension needs to display these browser events in the new tab page.
To make versioning easier I would like the extension to be as dumb as possible. That is, all it needs to do is tell me is that a tab has been created and I need to be able to tell the extension to switch to a tab. Then I do not have to worry about what extension versions people have installed.
The new tab page so far is a redirect to my single-page app hosted on my server.
My options seem to be:
*
*Using custom events to send messages between the content script and embedding page: http://code.google.com/chrome/extensions/content_scripts.html#host-page-communication
This seems like a security risk as the page javascript will also have access to the DOM and hence the messages I am exchanging.
*Loading the HTML from server into an iframe, pulling application JS from server and injecting it into the iframe as a contentscript. This allows the app's JS to have full access to the chrome extension API which is what I need.
Another consideration is that my project is currently using RequireJS. For option 2, it seems I won't be able to use this.
Can anyone recommend the preferred option keeping in mind the security risks of option 1?
Will I be able to use RequireJS with option 2?
Is there another way to acheive this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery Replace content in runtime issue What I am trying to accomplish is, using jQuery, dynamically replace the content (generated from another javascript) of div tag with id="Test".
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script type="text/javascript">
$(function(){
$("#Test").html('<b>test content</b>');
});
</script>
</head>
<body id="testAgain">
begin
<div class="scrollable">
<div class="items" id="Test">
</div>
</div>
end
</body>
</html>
As you can see,
$("#Test").html('<b>test content</b>');
replaces the html code of div tag with id="Test" with html code
<b>test content</b>
this works perfectly fine. I am getting rendered html as
begin
test content
end
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script type="text/javascript">
function TestScript(){
document.write('<b>test content</b>');
};
</script>
<script type="text/javascript">
$(function(){
$("#Test").html(TestScript());
});
</script>
</head>
<body id="testAgain">
begin
<div class="scrollable">
<div class="items" id="Test">
</div>
</div>
end
</body>
</html>
Here,
$("#Test").html(TestScript());
replaces the html code of div tag with id="Test" with generated html from javascript
TestScript()
I am getting rendered html as
test content
It replaces the entire content of the html file. How to resolve this problem?
Kindly help.
Thanks,
John
A: Try this:
<script type="text/javascript">
function TestScript(){
return '<b>test content</b>';
};
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: check current time between time interval android I want to create an app that will allow the user to check whether or not the current time falls between a specified time interval. More specifically, I created a sql table using sqllite program, with the table specifying an end time and a start time for each record. The problem is that the type of data each field can be is limited to text, number, and other type other than a datetime type. So, how would I be able to check if the current time is between the start and end time since the format of time is in h:mm and not just an integer value that I could just do less than or greater than? Do I have to convert the current time to minutes?
A: You should be able to do the comparison even if time is not stored in the datetime type, here is a link that explains the conversion from string to time.
If that doesn't work, convert the time to seconds (int) and calculate the difference.
A: Try this. You can save and retrieve your time as String:
String to long: String.valueOf()
long to String: Long.valueOf()
Then, you use this procedure to check time:
//Time checker
private boolean timeCheck(long startTimeInput, long endTimeInput) {
long currentTime = System.currentTimeMillis();
if ((currentTime > startTimeInput) && (currentTime < endTimeInput)) {
return true;
} else {
return false;
}
}
And in your main program check it like this:
//You kept the times as String
if (timeCheck(Long.valueOf(start), Long.valueOf(end))) {
//it is in the interval
} else {
//not in the interval
}
I hope it helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Allowing WMA (from TTR package) to return original value when fewer than N points When running the following:
wavData = ddply(wavData, c("primary", "interference", "label"), transform,
value = WMA(value,3,wts=1:3))
Some of the resulting groupings made by ddply do not have 3 points in them, thus I get the following error:
Error in WMA(value, 3, wts = 1:3) : Invalid 'n'
Question: How can I allow WMA to return the ORIGINAL values when n<3, and not crash?
A: How about using ifelse?
wavData = ddply(wavData, c("primary", "interference", "label"), transform,
value = ifelse(length(value) < 3, value, WMA(value,3,wts=1:3)))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I add the results of a MySQL query which splits a column into two to a table? I am running the following query on a table, which splits the first name and last name of each person in the Name column of the table into Firstname and Lastname:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(Name, ' ', 1), ' ', -1) as Firstname,
SUBSTRING_INDEX(SUBSTRING_INDEX(Name, ' ', 2), ' ', -1) as Lastname
FROM conference;
This works fine. I would now like to add the results of this to two new columns in the table which I have called Firstname and Lastname.
I tried adding INSERT conference [Firstname, Lastname] to the start of the Query, but that generated an error. Could someone help with the correct way of doing this?
Thanks,
Nick
A: If your intent is to update existing rows with those new fields instead of inserting new records, this should work
UPDATE Conference
SET
Firstname = SUBSTRING_INDEX(SUBSTRING_INDEX(Name, ' ', 1), ' ', -1),
Lastname = SUBSTRING_INDEX(SUBSTRING_INDEX(Name, ' ', 2), ' ', -1)
A: have you tried:
select SUBSTRING_INDEX(SUBSTRING_INDEX(Name, ' ', 1), ' ', -1) as Firstname,
SUBSTRING_INDEX(SUBSTRING_INDEX(Name, ' ', 2), ' ', -1) as Surname
into conference
from conference
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JSON.NET Deserialize string abbreviation into Enum I am just getting into JSON and all that and I ran into a snag. I am trying to parse a string abbreviation. I want to parse the string abbreviation into an Enum. Lets say my strings are:
'Apl', 'Orng', 'Bna'
Which for this example mean apple, orange, banana. Is there a way with JSON.NET to parse the abbreviated strings into an enum?
*Id prefer it if my enum can have the full name (Apple, Orange, Banana)
A: I think you're supposed to do this:
[DataContract]
public enum Fruit
{
[EnumMember(Value = "Apl")]
Apple,
[EnumMember(Value = "Orng")]
Orange,
[EnumMember(Value = "Bna")]
Banana,
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there an alternative to using time to seed a random number generation? I'm trying to run several instances of a piece of code (2000 instances or so) concurrently in a computing cluster. The way it works is that I submit the jobs and the cluster will run them as nodes open up every so often, with several jobs per node. This seems to produce the same values for a good number of the instances in their random number generation, which uses a time-seed.
Is there a simple alternative I can use instead? Reproducibility and security are not important, quick generation of unique seeds is. What would be the simplest approach to this, and if possible a cross platform approach would be good.
A: I assume you have some process launching the other processes. Have it pass in the seed to use. Then you can have that master process just pass in a random number for each process to use as its seed. That way there's really only one arbitrary seed chosen... you can use time for that.
If you don't have a master process launching the others, then if each process at least has a unique index, then what you can do is have one process generate a series of random numbers in memory (if shared memory) or in a file (if shared disk) and then have each process pull the index'th random number out to use as their seed.
Nothing will give you a more even distribution of seeds than a series of random numbers from a single seed.
A: A combination of the PID and the time should be enough to get a unique seed. It's not 100% cross-platform, but getpid(3) on *nix platforms and GetProcessId on Windows will get you 99.9% of the way there. Something like this should work:
srand((time(NULL) & 0xFFFF) | (getpid() << 16));
You could also read data from /dev/urandom on *nix systems, but there's no equivalent to that on Windows.
A: unsigned seed;
read(open("/dev/urandom", O_RDONLY), &seed, sizeof seed);
srand(seed); // IRL, check for errors, close the fd, etc...
I would also recommend a better random number generator.
A: If C++11 can be used then consider std::random_device. I would suggest you to watch link for a comprehensive guide.
Extracting the essential message from the video link : You should never use srand & rand, but instead use std::random_device and std::mt19937 -- for most cases, the following would be what you want:
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> dist(0,99);
for (int i = 0; i < 16; i++) {
std::cout << dist(mt) << " ";
}
std::cout << std::endl;
}
A: The rdtsc instruction is a pretty reliable (and random) seed.
In Windows it's accessible via the __rdtsc() intrinsic.
In GNU C, it's accessible via:
unsigned long long rdtsc(){
unsigned int lo,hi;
__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
return ((unsigned long long)hi << 32) | lo;
}
The instruction measures the total pseudo-cycles since the processor was powered on. Given the high frequency of today's machines, it's extremely unlikely that two processors will return the same value even if they booted at the same time and are clocked at the same speed.
A: Instead of straight time as measured in seconds from the C std lib time() function, could you instead use the processor's counter? Most processors have a free running tick count, for example in x86/x64 there's the Time Stamp Counter:
The Time Stamp Counter is a 64-bit register present on all x86 processors since the Pentium. It counts the number of ticks since reset.
(That page also has many ways to access this counter on different platforms -- gcc/ms visual c/etc)
Keep in mind that the timestamp counter is not without flaws, it may not be synced across processors (you probably don't care for your application). And power saving features may clock up or down the processor (again you probably don't care).
A: Just an idea... generate a GUID (which is 16 bytes) and sum its 4-byte or 8-byte chunks (depending on the expected width of the seed), allowing integer wrap-around. Use the result as a seed.
GUIDs typically encapsulate characteristics of the computer that generated them (such as MAC address), which should make it rather improbable that two different machines will end-up generating the same random sequence.
This is obviously not portable, but finding appropriate APIs/libraries for your system should not be too hard (e.g. UuidCreate on Win32, uuid_generateon Linux).
A: Windows
Provides CryptGenRandom() and RtlGenRandom(). They will give you an array of random bytes, which you can use as seeds.
You can find the docs on the msdn pages.
Linux / Unixes
You can use Openssl's RAND_bytes() to get a random number of bytes on linux. It will use /dev/random by default.
Putting it together:
#ifdef _WIN32
#include <NTSecAPI.h>
#else
#include <openssl/rand.h>
#endif
uint32_t get_seed(void)
{
uint32_t seed = 0;
#ifdef _WIN32
RtlGenRandom(&seed, sizeof(uint32_t) );
#else
RAND_bytes(&seed, sizeof(uint32_t) );
#endif
return seed;
}
Note that openssl provides a Cryptographically secure PRNG by default, so you could use it directly. More info here.
A: Assuming you're on a reasonably POSIX-ish system, you should have clock_gettime. This will give the current time in nanoseconds, which means for all practical purposes it's impossible to ever get the same value twice. (In theory bad implementations could have much lower resolution, e.g. just multiplying milliseconds by 1 million, but even half-decent systems like Linux give real nanosecond results.)
A: If uniqueness is important, you need to arrange for each node to know what IDs have been claimed by others. You could do this with a protocol asking "anyone claimed ID x?" or arranging in advance for each node to have a selection of IDs which have not been allocated to others.
(GUIDs use the machine's MAC, so would fall into the "arrange in advance" category.)
Without some form of agreement, you'll risk two nodes climing the same ID.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
} |
Q: Using Auto Increment with MySQL and need to retrieve that number I have a database in which I need some IDs to be autoincremented, but I also need that ID that gets auto incremented to be the Foreign Key for another table. Is there a way to recover that number within the same transaction to insert values into the second table?
As in:
1) Create a user
2) Retrieve the ID number generated by the auto increment ( for example: AI:5 )
3) Insert values into a table called Doctor, that needs that number retrieved by that user, all within same transaction...
I know that JSP has some function to recover that ID generated but not sure about MySQL.
Another thing is, I can't just send a query to recover the last generated ID because for example if 10 accounts got created at the same time I might not get the supposed number.
A: For a pure MySQL solution:
SELECT LAST_INSERT_ID();
For a Java way:
ResultSet rs = stmt.getGeneratedKeys();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can any user access the %APPDATA% folder Can any user access the %APPDATA% folder? Or can only administrators read & access that directory? Also, do the permissions to access this directory differ over different Windows platforms from 2k to Windows 7?
A: %AppData% is a user-specific path. Yes, any user can access %appdata%, but it will go to a different directory for each user. Only an administrator can read the appdata of another user.
Do the effort of actually going to %appdata% on your machine, and looking at the path it gets converted into. Do you see what I mean?
A: You can see the permissions on %APPDATA% by using the icacls tool at the command prompt. Here's what it looks like on my machine:
C:\Users\davidp>icacls %APPDATA%
C:\Users\davidp\AppData\Roaming NT AUTHORITY\SYSTEM:(I)(OI)(CI)(F)
BUILTIN\Administrators:(I)(OI)(CI)(F)
MACHINE09\davidp:(I)(OI)(CI)(F)
Successfully processed 1 files; Failed processing 0 files
What this means is that only I, administrators, and the system itself can see the folder. If you run this on a folder where other users can see it, you'll see something like this:
C:\Users\davidp>icacls c:\
c:\ BUILTIN\Administrators:(F)
BUILTIN\Administrators:(OI)(CI)(IO)(F)
NT AUTHORITY\SYSTEM:(F)
NT AUTHORITY\SYSTEM:(OI)(CI)(IO)(F)
BUILTIN\Users:(OI)(CI)(RX)
NT AUTHORITY\Authenticated Users:(OI)(CI)(IO)(M)
NT AUTHORITY\Authenticated Users:(AD)
Mandatory Label\High Mandatory Level:(OI)(NP)(IO)(NW)
Successfully processed 1 files; Failed processing 0 files
You can see that the BUILTIN\Users group can see the c:\ folder (as you would expect).
EDIT
I'm not sure how far back the %APPDATA% variable itself goes back in Windows history. I recommend checking directly. On older systems the cacls command was the predecessor to icacls. Regardless, in Windows NT-based OSes there has always been a profile area visible only to the user and administrators.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Java JSlider precision problems I have a list of N JSliders (N does not change procedurally, only as I add more features. Currently N equals 4). The sum of all the sliders values must equal to 100. As one slider moves the rest of the sliders shall adjust. Each slider has values that range from 0 to 100.
Currently I am using this logic when a slider is changed (pseudo-code):
newValue = currentSlider.getValue
otherSliders = allSliders sans currentSlider
othersValue = summation of otherSliders values
properOthersValue = 100 - newValue
ratio = properOthersValue / othersValue
for slider in otherSlider
slider.value = slider.getValue * ratio
The problem with this setup is slider's values are stored as ints. So as I adjust the sliders I get precision problems: sliders will twitch or not move at all depending on the ratio value. Also the total value does not always add up to 100.
Does anyone have a solution to this problem without creating an entirely new JSlider class that supports floats or doubles?
If you want an example of the behavior I want, visit: Humble Indie Bundle and scroll to the bottom of the page.
thank you
p.s. Multiplying the values by the ratio allows for the user to 'lock' values at 0. However, I am not sure what to do when 3 of the 4 sliders are at 0 and the 4th slider is at 100 and I move the 4th slider down. Using the logic above, the 3 sliders with 0 as their value stay put and the 4th slider moves to where the user puts it, which makes the total less than 100, which is improper behavior.
EDIT
Here is the SSCCE:
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.util.LinkedList;
public class SliderDemo
{
static LinkedList<JSlider> sliders = new LinkedList<JSlider>();
static class SliderListener implements ChangeListener
{
boolean updating = false;
public void stateChanged(ChangeEvent e)
{
if (updating) return;
updating = true;
JSlider source = (JSlider)e.getSource();
int newValue = source.getValue();
LinkedList<JSlider> otherSliders = new LinkedList<JSlider>(sliders);
otherSliders.remove(source);
int otherValue = 0;
for (JSlider slider : otherSliders)
{
otherValue += slider.getValue();
}
int properValue = 100 - newValue;
double ratio = properValue / (double)otherValue;
for (JSlider slider : otherSliders)
{
int currentValue = slider.getValue();
int updatedValue = (int) (currentValue * ratio);
slider.setValue(updatedValue);
}
int total = 0;
for (JSlider slider : sliders)
{
total += slider.getValue();
}
System.out.println("Total = " + total);
updating = false;
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame("SliderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = frame.getContentPane();
JPanel sliderPanel = new JPanel(new GridBagLayout());
container.add(sliderPanel);
SliderListener listener = new SliderListener();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
int sliderCount = 4;
int initial = 100 / sliderCount;
for (int i = 0; i < sliderCount; i++)
{
gbc.gridy = i;
JSlider slider = new JSlider(0, 100, initial);
slider.addChangeListener(listener);
slider.setMajorTickSpacing(50);
slider.setPaintTicks(true);
sliders.add(slider);
sliderPanel.add(slider, gbc);
}
frame.pack();
frame.setVisible(true);
}
}
A: Why not making the granularity of the JSlider models finer by say having them go from 0 to 1000000, and having the sum be 1000000? With the proper Dictionary for the LabelTable, the user will probably not know that it doesn't go from 0 to 100.
For example:
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
@SuppressWarnings("serial")
public class LinkedSliders2 extends JPanel {
private static final int SLIDER_COUNT = 5;
public static final int SLIDER_MAX_VALUE = 1000;
private static final int MAJOR_TICK_DIVISIONS = 5;
private static final int MINOR_TICK_DIVISIONS = 20;
private static final int LS_WIDTH = 700;
private static final int LS_HEIGHT = 500;
private JSlider[] sliders = new JSlider[SLIDER_COUNT];
private SliderGroup2 sliderGroup = new SliderGroup2(SLIDER_MAX_VALUE);
public LinkedSliders2() {
Dictionary<Integer, JComponent> myDictionary = new Hashtable<Integer, JComponent>();
for (int i = 0; i <= MAJOR_TICK_DIVISIONS; i++) {
Integer key = i * SLIDER_MAX_VALUE / MAJOR_TICK_DIVISIONS;
JLabel value = new JLabel(String.valueOf(i * 100 / MAJOR_TICK_DIVISIONS));
myDictionary.put(key, value);
}
setLayout(new GridLayout(0, 1));
for (int i = 0; i < sliders.length; i++) {
sliders[i] = new JSlider(0, SLIDER_MAX_VALUE, SLIDER_MAX_VALUE
/ SLIDER_COUNT);
sliders[i].setLabelTable(myDictionary );
sliders[i].setMajorTickSpacing(SLIDER_MAX_VALUE / MAJOR_TICK_DIVISIONS);
sliders[i].setMinorTickSpacing(SLIDER_MAX_VALUE / MINOR_TICK_DIVISIONS);
sliders[i].setPaintLabels(true);
sliders[i].setPaintTicks(true);
sliders[i].setPaintTrack(true);
sliderGroup.addSlider(sliders[i]);
add(sliders[i]);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(LS_WIDTH, LS_HEIGHT);
}
private static void createAndShowGui() {
LinkedSliders2 mainPanel = new LinkedSliders2();
JFrame frame = new JFrame("LinkedSliders");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class SliderGroup2 {
private List<BoundedRangeModel> sliderModelList = new ArrayList<BoundedRangeModel>();
private ChangeListener changeListener = new SliderModelListener();
private int maxValueSum;
public SliderGroup2(int maxValueSum) {
this.maxValueSum = maxValueSum;
}
public void addSlider(JSlider slider) {
BoundedRangeModel model = slider.getModel();
sliderModelList.add(model);
model.addChangeListener(changeListener);
}
private class SliderModelListener implements ChangeListener {
private boolean internalChange = false;
@Override
public void stateChanged(ChangeEvent cEvt) {
if (!internalChange) {
internalChange = true;
BoundedRangeModel sourceModel = (BoundedRangeModel) cEvt.getSource();
int sourceValue = sourceModel.getValue();
int oldSumOfOtherSliders = 0;
for (BoundedRangeModel model : sliderModelList) {
if (model != sourceModel) {
oldSumOfOtherSliders += model.getValue();
}
}
if (oldSumOfOtherSliders == 0) {
for (BoundedRangeModel model : sliderModelList) {
if (model != sourceModel) {
model.setValue(1);
}
}
internalChange = false;
return;
}
int newSumOfOtherSliders = maxValueSum - sourceValue;
for (BoundedRangeModel model : sliderModelList) {
if (model != sourceModel) {
long newValue = ((long) newSumOfOtherSliders * model
.getValue()) / oldSumOfOtherSliders;
model.setValue((int) newValue);
}
}
int total = 0;
for (BoundedRangeModel model : sliderModelList) {
total += model.getValue();
}
//!! System.out.printf("Total = %.0f%n", (double)total * 100 / LinkedSliders2.SLIDER_MAX_VALUE);
internalChange = false;
}
}
}
}
Edited to have SliderGroup2 use a List of BoundedRangeModels rather than JSliders.
A:
sliders will twitch or not move at all depending on the ratio value.
HumbleBundle has the same problem. If you move the slider by the keyboard then the change is only 1, which means it will only ever go to the first slider. So you ratios will eventually get out of sync.
Also the total value does not always add up to 100.
So you need to do a rounding check. If it doesn't add to 100, then you need to decide where the error goes. Maybe the last slider given the above problem?
I am not sure what to do when 3 of the 4 sliders are at 0 and the 4th slider is at 100 and I move the 4th slider down.
The way HumbleBundle handles it is to move all the slicers. However it only allows you to move the slider down increments of 3, so that you can increase each of the 3 sliders by 1.
Even the implementation at HumbleBundle isn't perfect.
A: Borrowing from some of Hovercrafts solution I came up with a different approach. The basis of this approach is that the "other sliders" values are tracked at the time a slider is moved. As long as you continue to slide the same slider the frozen values are used to calculate the new values. Any rounding differences are then applied sequentially to each slider until the difference is used up. Using this approach you can have incremental changes in the slider applied evenly to all of the other sliders.
The values in the model are the actual values of the slider and you can also use the keyboard to adjust the sliders:
import java.awt.*;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SliderGroup implements ChangeListener
{
private List<JSlider> sliders = new ArrayList<JSlider>();
private int groupSum;
private boolean internalChange = false;
private JSlider previousSlider;
private List<SliderInfo> otherSliders = new ArrayList<SliderInfo>();
public SliderGroup(int groupSum)
{
this.groupSum = groupSum;
}
public void addSlider(JSlider slider)
{
sliders.add(slider);
slider.addChangeListener(this);
}
@Override
public void stateChanged(ChangeEvent e)
{
if (internalChange) return;
internalChange = true;
JSlider sourceSlider = (JSlider)e.getSource();
if (previousSlider != sourceSlider)
{
setupForSliding(sourceSlider);
previousSlider = sourceSlider;
}
int newSumOfOtherSliders = groupSum - sourceSlider.getValue();
int oldSumOfOtherSliders = 0;
for (SliderInfo info : otherSliders)
{
JSlider slider = info.getSlider();
if (slider != sourceSlider)
{
oldSumOfOtherSliders += info.getValue();
}
}
int difference = newSumOfOtherSliders - oldSumOfOtherSliders;
if (oldSumOfOtherSliders == 0)
{
resetOtherSliders( difference / otherSliders.size() );
allocateDifference(difference % otherSliders.size(), true);
internalChange = false;
return;
}
double ratio = (double)newSumOfOtherSliders / oldSumOfOtherSliders;
for (SliderInfo info : otherSliders)
{
JSlider slider = info.getSlider();
int oldValue = info.getValue();
int newValue = (int)Math.round(oldValue * ratio);
difference += oldValue - newValue;
slider.getModel().setValue( newValue );
}
if (difference != 0)
{
allocateDifference(difference, false);
}
internalChange = false;
}
private void allocateDifference(int difference, boolean adjustZeroValue)
{
while (difference != 0)
{
for (SliderInfo info : otherSliders)
{
if (info.getValue() != 0 || adjustZeroValue)
{
JSlider slider = info.getSlider();
if (difference > 0)
{
slider.getModel().setValue( slider.getValue() + 1 );
difference--;
}
if (difference < 0)
{
slider.getModel().setValue( slider.getValue() - 1 );
difference++;
}
}
}
}
}
private void resetOtherSliders(int resetValue)
{
for (SliderInfo info : otherSliders)
{
JSlider slider = info.getSlider();
slider.getModel().setValue( resetValue );
}
}
private void setupForSliding(JSlider sourceSlider)
{
otherSliders.clear();
for (JSlider slider: sliders)
{
if (slider != sourceSlider)
{
otherSliders.add( new SliderInfo(slider, slider.getValue() ) );
}
}
}
class SliderInfo
{
private JSlider slider;
private int value;
public SliderInfo(JSlider slider, int value)
{
this.slider = slider;
this.value = value;
}
public JSlider getSlider()
{
return slider;
}
public int getValue()
{
return value;
}
}
private static JPanel createSliderPanel(int groupSum, int sliderCount)
{
int sliderValue = groupSum / sliderCount;
SliderGroup sg = new SliderGroup(groupSum);
JPanel panel = new JPanel( new BorderLayout() );
JPanel sliderPanel = new JPanel( new GridLayout(0, 1) );
panel.add(sliderPanel, BorderLayout.CENTER);
JPanel labelPanel = new JPanel( new GridLayout(0, 1) );
panel.add(labelPanel, BorderLayout.EAST);
for (int i = 0; i < sliderCount; i++)
{
JLabel label = new JLabel();
label.setText( Integer.toString(sliderValue) );
labelPanel.add( label );
JSlider slider = new JSlider(0, groupSum, sliderValue);
slider.setMajorTickSpacing(25);
slider.setMinorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setPaintTrack(true);
slider.addChangeListener( new LabelChangeListener(label) );
sliderPanel.add( slider );
sg.addSlider( slider );
}
return panel;
}
static class LabelChangeListener implements ChangeListener
{
private JLabel label;
public LabelChangeListener(JLabel label)
{
this.label = label;
}
@Override
public void stateChanged(ChangeEvent e)
{
JSlider slider = (JSlider)e.getSource();
label.setText( Integer.toString(slider.getValue()) );
}
}
private static void createAndShowGui()
{
JPanel panel = createSliderPanel(100, 5);
JFrame frame = new JFrame("SliderGroup");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to repeat the alphabet with for loop in caesar cipher in C# I am making a Caesar cipher and I want to make the letters in a loop so for example if the letter 'z' needs to be shifted it should go back to 'a' for both capital and lowercase.
//Array that holds each char in the plaintext inputed is declared and initiated
char[] chars = plainTextInput.ToCharArray();
//For loop that will go through each letter and change the value of each letter by adding the shiftAmount
for (int i = 0; i < plainTextInput.Length; ++i)
{
chars[i] = (char)(((int)chars[i]) + shiftAmount);
if (chars[i] >= 97 && chars[i] <= 122)
{
if (chars[i] > 122)
{
int x = chars[i] - 123;
chars[i] = (char)((int)(97 + x));
}
}
}
//Variable for ciphertext output holds char array chars as a string
cipherTextOutput = new string(chars);
If I input 'xyz' and shift by one I get 'yz{'.
A: Use modulo arithmetic:
new_pos = (current_pos + shift) % 26
current_pos has to be the relative letter position (eg: a=0, b=1... z=25). Something like:
if ('A' <= c && c <= 'Z') // uppercase
{
current_pos = (int) c - (int) 'A';
}
else if ('a' <= c && c <= 'z') // lowercase
{
current_pos = (int) c - (int) 'a';
}
See working demo: http://ideone.com/NPZbT
That being said, I hope this is just code you are playing with, and not something to be used in real code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: python program that scans a page for a specific combination of pixels? I'm trying to write a python program that will take a screen shot and then scan the image for a specific combination of pixels, or pattern. For example: it takes a screen shot of a web page and scans the whole image for a 10X10 pixel pattern. It would also be nice if it could record the x-y position of the image on the screen.
I searched the internet for hours for a solution but found nothing. I only know the basics of python and wouldn't know where to begin with this program.
A: Take a look at some basic pattern recognition and machine vision literature. In order to address your question considerably more detail is needed.
*
*Is the pattern a binary image, a grayscale image, or a color image?
*How often do you need to do this?
*Have you looked at the Python Imaging Library (PIL)?
*How big of an image do you want to search?
A good course of action is to look at PIL, and then look at convolution in Fourier space to localize the target regions (relatively) quickly. Finally, a good Google search is your friend.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating Database using phpMyAdmin in WAMP I've installed WAMP stack and tried creating databases using phpMyAdmin. But in the Databases section it says 'No Privileges' which means that I have no rights to create database. However it seems possible for me to create, drop data bases using command line. Even when I create a database using command line it's not displayed in phpMyAdmin too.
Also I couldn't create database, tables using php also. Please help me out on this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I access specific elements within a div tag using $(this)? I've got some javascript that allows me to load states into a dropdown using json anytime the user changes the country. This works great except that I can't have more than one of combination of country/state dropdowns on a page. So, given HTML like the following:
<div id="div1" data-ajax-address="owner">
<select id="country1" data-ajax-address="country"></select>
<select id="state1" data-ajax-address="state"></select>
</div>
<div id="div2" data-ajax-address="owner">
<p>
<select id="country2" data-ajax-address="country"></select>
</p>
<p>
<select id="state2" data-ajax-address="state"></select>
</p>
</div>
I want to be able to do something like this:
$('div[data-ajax-address="owner"]').each(function() {
$(this).children('select[data-ajax-address="country"]).change(function() {
....
});
});
to access the country/state select elements within the div. I can't use children() because they could be embedded within another element -- like the country2 & state2 being embedded inside of the paragraph tags.
Any ideas on how I can accomplish this?
Thanks.
A: Try something like:
$('div[data-ajax-address="owner"]').each(function() {
$(this).find('select[data-ajax-address="country"]').change(function() {
....
});
});
More info: http://api.jquery.com/find/
A: You can do a direct selection of the descendants if you want to:
$('div[data-ajax-address="owner"] select[data-ajax-address="country"]').change(function() {...});
Shorter and same precision
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Objective C protocols usage I have a homework question which confused me, really badly. Below is a brief explanation of a question.
Imagine you are developing an application that stores contact
information. The address book may contain many entity types e.g. Human
being, a company or anything else that has a contact information.
*
*Now instead of explicitly checking every object type write a
protocol that declares how an object must behave and successfully
appear in your address book.
My understanding and efforts of answering this question is,
*
*Build a protocol which has common methods of each type of contact information under @required tag. And all other methods which are not similar in different contact(Such as fax number has association with company but not person...) under @optional. At runtime you can check whether an object responds to any given method by using selector.
Doubt : However this is again explicitly checking object type indirectly, am I right?
*My second thought is to use something like abstract class in java. Which means inherited class's from abstract class implements their own abstract methods. How ever as a naive iOS developer I don't know how to implement this? and I am not sure whether this is going to solve my problem. I would like get enlighten if someone knows this.
External Reading done so far, Please let me know if the answer I am looking for is in one of these links. I will read it again to understand and solve this :). thanks.
*
*http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProtocols.html#//apple_ref/doc/uid/TP30001163-CH15-TPXREF144
*http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProtocols.html#//apple_ref/doc/uid/TP30001163-CH15-TPXREF146
*http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProtocols.html#//apple_ref/doc/uid/TP30001163-CH15-TPXREF149
A:
However this is again explicitly checking object type indirectly, am I right?
No, checking behavior is different from checking type. You can send -respondsToSelector: to any object, and if the result is YES you can send the message regardless of the object's type. You can also require that an object implement a given protocol, again without caring about its actual type:
id<SomeProtocol> foo; // foo points to any type that implements SomeProtocol
My second thought is to use something like abstract class in java.
That could work, but it's apparently not what your assignment asked for, right? It says "...write a protocol..."
Objective-C doesn't provide a way to explicitly make a class abstract the way Java does. You just create the class, and if you don't want it to be instantiated directly you document that somewhere.
A: A protocol is the same thing as a Java interface. It just defines which methods the class should support. Here's a page that explains it clearly: http://www.otierney.net/objective-c.html#protocols
Essentially if you want to make sure a class will have a phoneNumber method (accessor to the phoneNumber property) you would do something like this:
@protocol ContactProtocol
-(void) phoneNumber;
@end
@interface Person: NSObject <ContactProtocol> {
...
}
@interface Company: NSObject <ContactProtocol> {
...
}
And then at compile time (or live for xcode 4) it will tell you if you forgot to add the phoneNumber method to the Person or Company classes.
A: You have ... options.
Optional methods are convenient for the person writing the class to conform to the protocol, annoying for the person making use of the protocol. So it depends who you are trying to please.
Optional methods are not as bad as checking type. Imagine how the code would look when accessing a contactable entity object. When you use an optional method, you have to have an if case and an else case. It's not as convenient as just going ahead and assuming you can call the method. But it's way more convenient than checking type. That would be one if case for each different type of entity (and an else case, which might be an assertion). Additionally, if you use optional methods, information about the entity is encapsulated in its class. If you check type before calling a method, then the information about what type of contact information an entity provides is outside the class in the calling code. If you upgrade the entity to provide an additional type of contact, that improvement is not available until you update the calling code.
Option B is to make all the methods required, but give them the option of returning a value that indicates that no information is available, such as nil. Of course that still means an if case to check for a nil result, it's just less verbose. An even better solution for this problem is to have the methods return collections of multiple contacts. After all, people can have more than one phone number. Then to indicate that a contact type is not applicable, you would just return an empty collection.
The downside is that whoever writes the class that conforms to the protocol has to add a simple stub method that says return nil or something.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Android: How can I create a layout within a layout ? In my app I want to have a button that if the user clicks it
than a new layout is opened within the current (acually the main) layout.
the new layout should not fill all of the screen and parts of the previous layout
should be grayed out.
Any ideas on how to do this ?
A: You can show a hidden layout within your button's onClick event by calling
view.setVisibility(View.VISIBLE)
You can also fade out view elements or whole views with
view.setAlpha(75);
view.setBackgroundColor(Color.GRAY);
Note that "view" in the first example is your layout element.. LinearLayout, RelativeLayout, etc. and in the 2nd example, "view" is the element(s) you're trying to gray out.
A: Follow the answer of SBerg413. And for more information. you can take the relativelayout for the part that you want to hide and display on the button click.
And as like SBerg413 answer. you can hide the respective layout and show the layout you want to display.
Hope it will help you.
Thanks.
A: you can use a ViewFlipper to achieve what you want, position the viewflipper where the child views should fit (part of the screen you say)..
Inflate the rest of the "child" layouts from other xml, add them to the flipper and switch between them when you want...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make the header part of the site as low as the logo? I just changed some styling and broke my site :) and have not much clue how to set it back.
I put a new image as the logo. Before it was large-font text. And now the div ends at the bottom of other text and not at the bottom of the logo.
See how it is broken here: http://www.problemio.com - see on very top - i need to make the div extend to the bottom of the image on the left.
Here is my css:
.banner
{
width:60em;
margin: 0 auto;
position: relative;
padding: 0.3em 0;
z-index: 1;
}
.banner .site_title
{
background: url("http://www.problemio.com/img/ui/problemio.png") no-repeat scroll 0 0 transparent;
padding:5px 60px;
font-weight: bold;
color: #ffce2e;
text-shadow: 2px 2px 2px rgba(0,0,0,0.8);
font-size:2.5em;
text-align: left
}
and here is the HTML I use:
<div class="banner">
<!-- title and login/sign up go here -->
<a href="http://www.problemio.com">
<div class="site_title">
</div>
</a>
And I am trying to make the image appear in the site title div. I think I should use the img tag, right? How should I augment my styles though?
Thanks,
Alex
A: You're not setting a height on your banner or site_title divs, so they are only going to be as high as the elements inside them, which in the case of the banner div appears to be text links.
In your CSS code, you're setting the background-url inside both the .banner and .site_title classes. This is redundant and can lead to things looking weird if you give only one of the divs a margin. Why not get rid of the site_title div and just make it an image? This should fix your height issues as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: NSTextView incorrectly displaying text from an attributed string based upon HTML I have the following text -
❶can be added as
The above text shows up fine in Text Edit. But when I try displaying the same in NSTextView, I get strange characters -
â¶can be added as
The following is the code that I am using to display the text in NSTextView
NSURL *url = < base URL >;
NSAttributedString *attrString = [[NSAttributedString alloc]
initWithHTML: data baseURL: url documentAttributes: (NSDictionary **) NULL];
[[textView textStorage] setAttributedString: attrString];
[attrString release];
data is set as -
data = NSData.FromString ("<html><head><style>p {font-size:14px;}</style></head><body><p>❶can be added </p></body></html>");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: XSetInputFocus fails In my Xlib application, I need to set up the keyboard to focus on a specific component, and I though of doing it with XSetInputFocus. For some reason I always get a BadMatch error even though my window is visible (and the man pages say that the cause for this error is a window which is not visible/mapped). When I say it's visible, I mean that I can see it on the screen, and I know the list of requests was flushed already.
So, instead of sharing my huge code, I found a smaller demo on the internet and tried to modify it. I took the event handling code in Xlib as presented in the example of an Xlib programming tutorial I found. I tried adding the following line:
XSetInputFocus (display, win, RevertToNone, CurrentTime);
Just before the line
/* perform an events loop */
The error I got was:
X Error of failed request: BadMatch (invalid parameter attributes)
Major opcode of failed request: 42 (X_SetInputFocus)
Serial number of failed request: 12
Current serial number in output stream: 12
This is exactly the same error I got in my own application with exactly the same sequence of events:
*
*Create a window with XCreateSimpleWindow (that shuold be an InputOutput window)
*Use XSelectInput and choose in the mask to also get KeyPressMask)
*Map the window (XMapWindow)
*Request focus using XSetInputFocus using either RevertToNone or RevertToParent (both fail)
I suspect it has to do something with the fact that I need to process the events of the window creation using XNextEvent, untill I finish handling the reparenting of the window, but in that case I don't know untill when should I wait (which events should I receive before atempting this?). I am currently doing this before the first call to XNextEvent in my program.
Any help would be highly appriciated. Thanks in advance!
A: I had a similar issue just yesterday... It's because the X server processes events asynchroniously; thus you need to wait for the window to be mapped before trying to use XSetInputFocus()...
You should call XIfEvent() to determine this.
An example (written in freepascal):
// The filter-function, here you should return true if
// the event parameter matches the one you want
// in this case, I match the type to be MapNotify and the window to be the correct one
Function WaitForNotify(aDPY: PDisplay; anEvent: PXEvent; arg: TXPointer): LongBool; cdecl;
Begin
Result:= (anEvent^._type = MapNotify) and (anEvent^.xmap.window = TWindow(arg));
End;
// XIfEvent cycles through the event cue, and evaluates each event through
// the function you provide it
XIfEvent(dpy, @event, @WaitForNotify, TXPointer(xWindow));
// Then, once this call returns, you're shure you've got focus and you can safely call
// XSetInpuFocus()
XSetInputFocus(dpy, XWindow, RevertToNone, CurrentTime);
Hope this helps!
A: For me a simplified solution also worked:
After a call to XMapWindow() I just called XSync() before performing a XSetInputFocus().
A: I dealt with this problem once and for all with the code found here:
https://www.ultraengine.com/community/blogs/entry/2690-linux-development-progress/
Have never had a problem since. It's a little scary but since the application has
total control (I think and hope) over any time a window is mapped / unmapped it should be fine.
XInputSetFocus is the only command I have encountered that uses this "rest-of-API-is-asynchronous-but-I-want-what-I-want-right-now" design.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What's the simplest way to navigate through a list of images? The purpose of this is to view remote images with a browser. I already have set apache and I can see the folder of pictures with directory listing. The bad thing, is that I have to click each image, each time I want to see one.
What I want is to navigate through the images in the folder using the arrows in my keyboard. I don't want any UI, just the image.
What's the best thing to do this? Is it possible to do using just HTML5?
Thanks.
A: Here is a simple gallery with keyboard navigation. You can (in php) echo out the directory listing of images as a array in js.
Example
Full Screen Example
A: The simplest solution I can think of is Single File PHP Gallery. It's one file. You add it to that directory and it makes it into a gallery. I don't know if it supports the keyboard navigation you're looking for.
The most straightforward approach would really be javascript, as mentioned by rlemon. PHP is overkill for what you've described and by itself cannot add the keyboard shortcuts. You need javascript for that part. The Single File PHP Gallery might work if you're trying to avoid writing any code, though.
A: Or try Files app, see demo.
Files is a single-file PHP app that can be dropped into any directory
on your server, instantly creating a gallery of files and folders. It
supports all file types and allows you to preview images, video, audio
and code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Add a prefix to each item of a PHP array I have a PHP array of numbers, which I would like to prefix with a minus (-). I think through the use of explode and implode it would be possible but my knowledge of php is not possible to actually do it. Any help would be appreciated.
Essentially I would like to go from this:
$array = [1, 2, 3, 4, 5];
to this:
$array = [-1, -2, -3, -4, -5];
Any ideas?
A: In this case, Rohit's answer is probably the best, but the PHP array functions can be very useful in more complex situations.
You can use array_walk() to perform a function on each element of an array altering the existing array. array_map() does almost the same thing, but it returns a new array instead of modifying the existing one, since it looks like you want to keep using the same array, you should use array_walk().
To work directly on the elements of the array with array_walk(), pass the items of the array by reference ( function(&$item) ).
Since php 5.3 you can use anonymous function in array_walk:
// PHP 5.3 and beyond!
array_walk($array, function(&$item) { $item *= -1; }); // or $item = '-'.$item;
Working example
If php 5.3 is a little too fancy pants for you, just use createfunction():
// If you don't have PHP 5.3
array_walk($array,create_function('&$it','$it *= -1;')); //or $it = '-'.$it;
Working example
A: $array = [1, 2, 3, 4, 5];
$array=explode(",", ("-".implode(",-", $array)));
//now the $array is your required array
A: I had the same situation before.
Adding a prefix to each array value
function addPrefixToArray(array $array, string $prefix)
{
return array_map(function ($arrayValues) use ($prefix) {
return $prefix . $arrayValues;
}, $array);
}
Adding a suffix to each array value
function addSuffixToArray(array $array, string $suffix)
{
return array_map(function ($arrayValues) use ($suffix) {
return $arrayValues . $suffix;
}, $array);
}
Now the testing part:
$array = [1, 2, 3, 4, 5];
print_r(addPrefixToArray($array, 'prefix'));
Result
Array ([0] => prefix1 [1] => prefix2 [2] => prefix3 [3] => prefix4 [4] => prefix5)
print_r(addSuffixToArray($array, 'suffix'));
Result
Array ([0] => 1suffix [1] => 2suffix [2] => 3suffix [3] => 4suffix [4] => 5suffix)
A: Something like this would do:
array_map(function($val) { return -$val;} , $array)
A: An elegant way to prefix array values (PHP 5.3+):
$prefixed_array = preg_filter('/^/', 'prefix_', $array);
Additionally, this is more than three times faster than a foreach.
A: Simple:
foreach ($array as &$value) {
$value *= (-1);
}
unset($value);
Unless the array is a string:
foreach ($array as &$value) {
$value = '-' . $value;
}
unset($value);
A: You can replace "nothing" with a string. So to prefix an array of strings (not numbers as originally posted):
$prefixed_array = substr_replace($array, 'your prefix here', 0, 0);
That means, for each element of $array, take the (zero-length) string at offset 0, length 0 and replace it the prefix.
Reference: substr_replace
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "89"
} |
Q: Why can't i use external header? I created a "Cocoa Touch Static Library" and it builds just fine. Peachy so far. Then I created a view based application for iOS. I can import the header from my previously created lib, but I can't run the program. It's always returning:
Undefined symbols for architecture i386:
"_OBJC_CLASS_$_GenericList", referenced from:
objc-class-ref in Hello_World_2ViewController.o"
Why is this happening?
A: It seems like you're not linking against the actual library files, just somehow referenced the header file. Three20 is a popular third-party iOS library, and they have a documentation article on how to add it to your project – look lower on the page for "Manually add Three20 to your project" and adapt the process for your library by skipping any steps that aren't applicable.
Alternately, I'm also guessing that drag-and-dropping the library's .h and .a files into your app's project might Just Work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to restart a task elegantly? So I have something like this:
Task.Factory.FromAsync<TcpClient>(tcpListener.BeginAcceptTcpClient, tcpListener.EndAcceptTcpClient, tcpListener).ContinueWith(ConnectionAccepted);
private void ConnectionAccepted(Task<TcpClient> tcpClientTask)
{
TcpClient tcpClient = tcpClientTask.Result;
// Do something with tcpClient
}
Now I'm wondering, how can I initiate Task.Factory.FromAsync<TcpClient>(...) again at the end of this method? I can't really just copy and paste the line of code because I don't have access to TcpListener and would rather not make it a member variable. Even if I did though, it's such a long line of code it kinda feels like code duplication to me.
Does the Tasks framework provide some sort of mechanism to accomplish this?
Thanks.
A: As svick suggested, the easiest way would be to make tcpListener in to a field. But if for some reason you can't do that, try this pattern:
void AcceptClient()
{
// Create tcpListener here.
AcceptClientImpl(tcpListener);
}
void AcceptClientImpl(TcpListener tcpListener)
{
Task.Factory.FromAsync<TcpClient>(tcpListener.BeginAcceptTcpClient, tcpListener.EndAcceptTcpClient, tcpListener).ContinueWith(antecedent =>
{
ConnectionAccepted(antecedent.Result);
// Restart task by calling AcceptClientImpl "recursively".
// Note, this is called from the thread pool. So no stack overflows.
AcceptClientImpl(tcpListener);
});
}
void ConnectionAccepted(TcpClient tcpClient)
{
// Do stuff here.
}
A: I don't think there is anything in the Framework for restarting Tasks.
But your problem can be trivially solved by putting the tcpListener into a field and putting the line that creates the task into a method, so there won't be any code duplication.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Easy regular expression This pertains to a regex expression.If I have a document with the word Chapter in it how could I select the space right before it?
A: \s+(?=Chapter)
should do it. \s+ matches space, and (?=Chapter) matches the zero-length string that is followed by the word "Chapter".
For .net, space is defined in http://msdn.microsoft.com/en-us/library/ms972966.aspx thus:
\s Matches any white-space character. Equivalent to the Unicode character classes [\f\n\r\t\v\x85\p{Z}]. If ECMAScript-compliant behavior is specified with the ECMAScript option, \s is equivalent to [ \f\n\r\t\v] (note leading space).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: I'm trying to create a database table for each user who registers. What am I doing wrong? I am trying to work on a login and registration page and I am making a new database and i can do it fine like this:
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
// Execute query
mysql_query($sql,$con);
and what I am trying to do is replace the "persons" with a string so that it makes a table but it is dynamic. I need a string because I am making a table for each user that registers and the new table's name is their username and password send through an md5sum encryption. I've tried this with no success it wont make a new table like the other one does :
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE $data
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
// Execute query
mysql_query($sql,$con);
Please help me. I've tried joining strings together with no luck so I need help.
A:
I'm trying to create a database table for each user who registers. What am I doing wrong?
You are creating a database table for each user who registers.
This is not the way you're supposed to use relational databases. You create a row for each new user, not a table. Of course you'll need a few extra columns in your Persons table, like the Password. I'd also recommend against storing the age because that's not constant. Store the Birthday instead.
INSERT INTO Persons (FirstName, LastName, Birthday, Password)
VALUES ('John', 'Smith', '1980-07-21', 'SOME HASH HERE');
I hope you don't take it wrong, but you need to slow down a bit and learn more about SQL before trying to write more code. Trust me, it'll be better in the long run.
A: I'm looking back at some of the questions I've asked in the past in it's crazy to see how much I've learned in the past few years.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python read page from URL? Better documentation? I'm having quite a bit of trouble with Python's documentation. Is there anything like the Mozilla Developer Network for it?
I'm doing a Python puzzle website and I need to be able to read the content of the page. I saw the following posted on a site:
import urllib2
urlStr = 'http://www.python.org/'
try:
fileHandle = urllib2.urlopen(urlStr)
str1 = fileHandle.read()
fileHandle.close()
print ('-'*50)
print ('HTML code of URL =', urlStr)
print ('-'*50)
except IOError:
print ('Cannot open URL %s for reading' % urlStr)
str1 = 'error!'
print (str1)
It keeps saying that there is no urllib2 module.
The Python documentation says
The urllib module has been split into parts and renamed in Python 3.0 to urllib.request, urllib.parse, and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to 3.0. Also note that the urllib.urlopen() function has been removed in Python 3.0 in favor of urllib2.urlopen().
I tried importing urllib.request too, but it ssays urllib 2 is defined... WTF is going on here?
Version 3.2.2
A: Using urllib.request.open(), as recommended in Dive into Python 3...
Python 3.2.1 (default, Jul 24 2011, 22:21:06)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib.request
>>> urlStr = 'http://www.python.org/'
>>> fileHandle = urllib.request.urlopen(urlStr)
>>> print(fileHandle.read()[:100])
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtm'
A: The documentation you were probably referencing was the Python 2 documentation for urllib2. The documentation you should probably be using is the Python 3 documentation for urllib.request.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Firebird CASE statement inside stored procedure I was trying to use the case statement inside a stored procedure but I got "Token unknown" on it. case is not supported in stored procedure? Thanks
A: As Andrei wrote, CASE is only available in SELECT statements. So the trick to use it is to select from some table which has only one row, like RDB$DATABASE:
SELECT
CASE
...
END
FROM RDB$DATABASE INTO :myVAR;
Of course, this is only usefull in case you want to assign value to a variable based on some conditions, if you need a control flow statement then IF / ELSE ladder is the only option.
A: You can use CASE statement only within SELECT operator. Standalone usage is not allowed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: glVertexAttribPointer needed everytime glBindBuffer is called? In OpenGL (OpenGL ES 2.0 in particular), is glVertexAttribPointer required to be called each time a new VBO is bound?
For example:
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer1);
glVertexAttribPointer(ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(vertexStruct), (void*)offsetof(vertexStruct,position));
glEnableVertexAttribArray(ATTRIB_POSITION);
glVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(vertexStruct), (void*)offsetof(vertexStruct,color);
glEnableVertexAttribArray(ATTRIB_COLOR);
glDrawElements(GL_TRIANGLE_STRIP, sizeof(indices)/sizeof(GLubyte), GL_UNSIGNED_BYTE, (void*)0);
// If vertexBuffer2 has the exact same attributes as vertexBuffer1
// is this legal or do the calls to glVertexAttribPointer (and glEnableVertexAttribArray)
// required again?
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer2);
glDrawElements(GL_TRIANGLE_STRIP, sizeof(indices)/sizeof(GLubyte), GL_UNSIGNED_BYTE, (void*)0);
I know that there are VAOs that address not having to call glVertexAttribPointer but I'm wondering if this is ok to do in OpenGL?
A: If you did this:
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer1);
glVertexAttribPointer(ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(vertexStruct), (void*)offsetof(vertexStruct,position));
glEnableVertexAttribArray(ATTRIB_POSITION);
glVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(vertexStruct), (void*)offsetof(vertexStruct,color);
glEnableVertexAttribArray(ATTRIB_COLOR);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDrawElements(GL_TRIANGLE_STRIP, sizeof(indices)/sizeof(GLubyte), GL_UNSIGNED_BYTE, (void*)0);
Your code would work just fine. What all of the gl*Pointer calls do is look at what is stored in GL_ARRAY_BUFFER at the time the function is called, and create an association between that buffer and that attribute. So the only way to change what buffer gets used for an attribute is to call gl*Pointer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: jQuery load: Loading a single file for many purposes? I have few select's which their content is loaded on DOM ready.
It looks something like this:
<select id="select1"> </select>
<select id="select2"> </select>
<select id="select3"> </select>
<select id="select4"> </select>
<select id="select5"> </select>
and the javascript like this:
$(document).ready(function(){
$("#select1").load("select1.html",
function (responseText, textStatus, XMLHttpRequest) {
if (textStatus == "success") {
alert("success");
}
});
$("#select2").load("select2.html",
function (responseText, textStatus, XMLHttpRequest) {
if (textStatus == "success") {
alert("success");
}
});
// and goes on for every select
EDIT:
Now, each select has different values. Select1 for countries, Select2 for colours, Select3 for currency etc. How can I combine all the options into 1 HTML/XML and load for each select its options from that 1 file.
Question 2: Is it better to load each select options its own file or have everything combined?
Note that now the content is loaded on DOM ready; for test purpose. In the feature I will be calling each select content separately. The reason I am loading the options is because each select has about 30 options and I want to reduce the loading time since the entire site its a 1 page dashboard web app with many select options.
A: You can just load fragments from a single page.
Do it like this
$("#select1").load("select.html #select1_content", //continue
In this way, you are loading into #select1 the contents of the #select1_content from your single select.html page.
See Loading Page Fragments here: http://api.jquery.com/load/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Animation and event questions in win32 (C++) I would like to create a small application which has two animated ellipses. One wanders around on its own using a custom function to determine its direction and behavior; the other is controlled by the arrow keys. When the two collide, there is an alert and the ellipses reset to their initial positions.
Using the method described in this video tutorial (found here: http://xoax.net/comp/cpp/win32/Lesson4.php), I have a successfully made a red ellipse so adding a second ellipse should not be too difficult. I would like for the ellipse I have made to move smoothly and continuously about the screen (for now just on its own and just towards the right). However I do not understand how or where I should insert the command to redraw the screen.
From Google searches, I've seen that InvalidateRect(handle of window, rectangular area to be redrawn, Boolean if window should be cleared first) should be used, but I do not understand where it should be called. In the main message loop? In the callback switch statement? I understand that NULL can be used for the whole window, but I don't know what to put for the window handle.
For the collision detection, where should I place the check? In the main loop? Or somewhere in the callback function's switch statement?
My code:
// MyGUI.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "MyGUI.h"
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
float MyX = 10;
float MyY = 10;
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
MSG msg;
HACCEL hAccelTable;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_MYGUI, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MYGUI));
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
MyX+=0.5;
// InvalidateRect(hInst, NULL, true); ???
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
// COMMENTS:
//
// This function and its usage are only necessary if you want this code
// to be compatible with Win32 systems prior to the 'RegisterClassEx'
// function that was added to Windows 95. It is important to call this function
// so that the application will get 'well formed' small icons associated
// with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MYGUI));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_MYGUI);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
HPEN hPenOld;
// Draw a red line
HPEN hEllipsePen;
COLORREF qEllipseColor;
qEllipseColor = RGB(255, 0,0);
hEllipsePen = CreatePen(PS_SOLID, 3, qEllipseColor);
hPenOld = (HPEN)SelectObject(hdc, hEllipsePen);
Arc(hdc, MyX, MyY, MyX+10, MyY+10, 0, 0 ,0, 0);
SelectObject(hdc, hPenOld);
DeleteObject(hEllipsePen);
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
Thanks.
A: The typical structure for games and other kind of graphical apps is this:
main()
{
init();
while (!exit) {
process_input();
update_state();
draw();
}
}
In process_input() you handle the input from the user. Since you get intput on the WndProc function, your handler in WndProc could just record the events in a queue, which is then processed by this function.
The update_state() function will take care of your animation. Any objects that move on their own will be updated here. You will also do collision detection and any other state related functions, like maybe updating the player score or stats.
Finally, the draw() function takes care of the drawing. If you do not need very low latency drawing in your app, then you could just call InvalidateRect() here, and let the system send the WM_PAINT message to your WndProc. If you need low latency, then you can just get a DC for your window and draw directly in this function.
I hope this helps.
A: Basically, both the collision detection and the invalidation should be done in the loop wherein the objects are placed or moved on the screen.
The window handle is the hWnd that you created in InitInstance. Pass it to wherever you need it, or make it a global variable or class member.
A: Your main function as you posted it uses GetMessage(). This function is only partly what you are looking for because it only returns if there is a message in the so called message queue. This means only if the user interacts with your program the GetMessage() functions returns and executes the code within the while() loop. Without any kind of input the program just "waits", and does not move the ellipse on its own. The other alternative is using PeekMessage() which just checks if any messages are available and returns. Using this gives you the opportunity to update the ellipses position very rapidly, but without any control how often the position is being updated/drawn.
In order to control how often user input and draw calls are processed you will need someting like a timer which execute the main loop at certain intervals. Have a look at SetWaitableTimer() and WaitForSingleObject() in the MSDN documentation. The basic structure of the applicatin loop has been described by Miguels post.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: About C# delegate/event processing I have a simple program that doesn't behave the way I expected it to behave. I was under the impression that both Method Signatures would run in the order of the Invocation List of the Delegate during the CallEvent() method and make the Test Property equate to 40. Hence:
Test += (20+15);
Test += (20-15);
Test == 40;
As it would turn out, this assignment is equal to 5, which is the value of the subtraction. If it did the addition first then replaced it with subtraction, doesn't that defeat the purpose of the Test += assignment? Maybe it is bypassing the addition all together (however unlikely). I suspect something more inherent is going on that I just can't see with my current programming knowledge.
Please and Thank You!
LiquidWotter
//MY NAMESPACE
namespace MyNamespace
{
//MAIN
private static void Main(string[] args)
{
//CREATE MY OBJECT
MyClass MyObject = new MyClass();
//ADD CALLS TO EVENT
MyObject.MyEvent += Add;
MyObject.MyEvent += Sub;
//CALL EVENT AND WRITE
MyObject.CallEvent(20, 15);
Console.WriteLine(MyObject.Test.ToString());
//PAUSE
Console.ReadLine();
}
//ADDITION
private static int Add(int x, int y)
{ return x + y; }
//SUBTRACTION
private static int Sub(int x, int y)
{ return x - y; }
//MY CLASS
public class MyClass
{
//MEMBERS
public delegate int MyDelegate(int x, int y);
public event MyDelegate MyEvent;
public int Test { get; set; }
//CONSTRUCTOR
public MyClass()
{
this.Test = 0;
}
//CALL Event
public void CallEvent(int x, int y)
{
Test += MyEvent(x, y);
}
}
}
A: Well you are correct. There can only be one return value[1], while both delegates where called only one, in fact the last, returned its value. Which makes sense, because how should the framework know what to do in cases where you directly place your event in a method as an argument:
this.Foo( MyEvent(x, y) );
call Foo once or multiple times? somehow combine the values? You see it is not clear.
I have to add that the order of delegates is also not defined[2], well currently it is defined(The order of registration) but you should never rely on it.
A: Using the += operator adds a new delegate to the invokation chain. A chain is how it is evaluated. Each delegate will be invoked in order in the chain. But, because the delegates are all invoked (meaning they block and return a value to the caller) only the last result is returned in your assignment.
Assuming this example is a simplification, rather than having delegates with a result you could use a collection of lambda epxressions and Linq extensions to Sum or simply maintain state in your class.
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
//MAIN
private static void Main(string[] args)
{
IEnumerable<Func<int, int, int>> operationsList =
new Func<int,int, int>[] { Add, Sub };
//CALL EVENTs AND WRITE
Console.WriteLine(operationsList.Sum(operation => operation(20, 15)));
//PAUSE
Console.ReadLine();
}
//ADDITION
private static int Add(int x, int y)
{
return x + y;
}
//SUBTRACTION
private static int Sub(int x, int y)
{
return x - y;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: defer font-face fonts loading after document ready Is there any way to prevent fetching custom fonts before document.ready and load fonts after that? This helps making page page load time(the time browser spinner shows)
A: You could try this:
$(document).ready(function() {
var font_settings = " <style type='text/css'> @font-face {font-family: YourFont; src: url('fonts/YourFont.ttf');}</style>";
$("head").append(font_settings);});
Note that if this does get you what you're looking for, you'll probably end up seeing your text flash from the default font face to whatever custom one you've specified.
A: Take a look at newly available font-display property which
allows you to customize how web fonts are displayed when the page is
being rendered
@font-face {
...
font-display: swap
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Make Table Width 100% with Last Column Filling Remainder without squashing other columns content/width Is it possible to make a table (which will have dynamically created text) to have for example:
table width 100% of the screen
5 columns
last column is empty ( )
the first four columns have text and their width is dynamic
the last column is remainder of the width
without squashing the text in the first four columns
I have this so far and it squashes the text which is what I'm trying to avoid:
<table style="width:100%;" border="1">
<tr>
<td>One Two Three</td>
<td>Two Three Four</td>
<td>Three Four Five</td>
<td>Four Five Six</td>
<td style="width:100%;"> </td>
</tr>
</table>
I can't use "white-space: nowrap" as I do want the text to wrap if there's enough text.
Edit: "I'd just like the [first four] columns to be the width they would be if I removed the width attribute from the table tag. But still have the table be 100% of the width of the page."
Any ideas? CSS solutions preferable!
A: You can use flexbox to accomplish this
CSS
table {
width:100%;
border: 1px solid black;
border-collapse: collapse;
}
td + td {
border-left: 1px solid black;
}
tr {
display: flex;
align-items: stretch;
}
td:last-child {
flex: 1;
background: yellow;
display:inline-block;
/* to keep IE happy */
}
FIDDLE (Resize the browser window to see this in action)
table {
width: 100%;
border: 1px solid black;
border-collapse: collapse;
}
td + td {
border-left: 1px solid black;
}
td:last-child {
background: yellow;
}
<table>
<tr>
<td>One Two Three</td>
<td>Two Three Four</td>
<td>Three Four FiveThree Four FiveThree Four FiveThree Four FiveThree Four Five</td>
<td>Four Five Six</td>
<td> f</td>
</tr>
</table>
NB:
IE 10-11 has an issue that Inline elements (and apparently table-cells as well) are not treated as flex-items.
This issue is documented by Phillip Walton here and the workaround (from the above post) is:
This issue can be avoided by adding a non-inline display value to the
items, e.g. block, inline-block, flex, etc.
Btw: the following is what the same fiddle above looks like without using flexbox - Notice that the last td doesn't actually fill up the remaining space, but rather takes up it's own natural space - which is what the OP did NOT want.
A: This is what worked for me (in FireFox, Chrome and old 12.x Opera). My tables which I wanted to have 100% width and the last column to fill the rest has the class tableList and here's CSS:
.tableList { width: 100%; }
.tableList td { width: 1px; } /* min width, actually: this causes the width to fit the content */
.tableList td:last-child { width: 100%; } /* well, it's less than 100% in the end, but this still works for me */
Below, there's a snippet to try:
.tableList { width: 100%; }
.tableList td { width: 1px; } /* min width, actually: this causes the width to fit the content */
.tableList td:last-child { width: 100%; background-color: yellow; } /* well, it's less than 100% in the end, but this still works for me */
<table class="tableList">
<tr><td>game's</td><td>not</td><td>over</td></tr>
<tr><td>one</td><td>two</td><td>three and more</td></tr>
</table>
Like Rahat has noticed, if the content of a column other than the first one is more than one word, it becomes multiline (one line per word):
.tableList { width: 100%; }
.tableList td { width: 1px; } /* min width, actually: this causes the width to fit the content */
.tableList td:last-child { width: 100%; background-color: yellow; } /* well, it's less than 100% in the end, but this still works for me */
<table class="tableList">
<tr><td>game's</td><td>not</td><td>over</td></tr>
<tr><td>one</td><td>two plus plus</td><td>three and more</td></tr>
</table>
but he also has suggested a workaround – adding white-space: nowrap:
.tableList { width: 100%; }
.tableList td { width: 1px; white-space: nowrap; } /* min width, actually: this causes the width to fit the content */
.tableList td:last-child { width: 100%; background-color: yellow; } /* well, it's less than 100% in the end, but this still works for me */
<table class="tableList">
<tr><td>game's</td><td>not</td><td>over</td></tr>
<tr><td>one</td><td>two plus plus</td><td>three and more</td></tr>
</table>
A: Just add
table-layout: fixed;
to your table, and you're done.
Assuming your texts in the other columns do not force a table wider than 100%, your last column will always stretch, so not necessary to apply any widths on the <td>.
A: I solved the same issue by using max-width=99% for the last column and gave fixed sizes to the other columns.
<table style='width: 100%' border='1'>
<tr>
<td style='width:60px'><b>Label 1</b></td>
<td style='width:120px;'><b>Label 2</b></td>
<td style='max-width:99%;'><b>Label 3</b></td>
</tr>
</table>
A: Perhaps instead of setting the last column to 100%, set it to auto?
<table style="width:100%;" border="1">
<tr>
<td>One Two Three</td>
<td>Two Three Four</td>
<td>Three Four Five</td>
<td>Four Five Six</td>
<td style="width:auto;"> </td>
</tr>
</table>
A: It sounds like you want the browser to "intelligently" determine how wide each column should be. You want the columns to wrap, but you don't want their widths to be too small. The problem is that when it's completely up to the browser, the browser can arbitrarily choose how wide each column is. 10 pixels? 100 pixels? Sure, both would be valid if you're not giving the browser any hints.
You can try min-width and max-width as a compromise for your column widths to be dynamic but within a certain range.
If it's possible that a column may be really narrow (e.g. if the data in that column consists of single-digit numbers), then using just max-width might be preferred.
A: Try this method, might work for you.
.myTable {
width: 100%;
}
.myTable td:last-child {
width: auto;
}
<table class="myTable" border="1">
<tr>
<td>One Two Three</td>
<td>Two Three Four</td>
<td>Three Four Five</td>
<td>Four Five Six</td>
<td> </td>
</tr>
</table>
Or through CSS:
table {
width: 100%;
}
table td:nth-child(-n+4) div
{
min-width: 100px;
}
A: Yes, this is not that difficult, though sometimes various browsers will display this a little differently. There are actually several ways to do this, but this is my favorite. The first rows is just a list of the field names and also setting the width of each column...except the last one.
<table style='width: 100%' border='1'>
<tr>
<td style='width:100px;'><b>Label 1</b></td>
<td style='width:120px;'><b>Label 2</b></td>
<td style='width:60px;'><b>Label 3</b></td>
<td style='width:100px;'><b>Label 4</b></td>
<td><b>Label 5</b></td>
</tr>
<!-- insert dynamically generated rows -->
</table>
I have found this works well, particularly if you need only one of the fields to be taking up the remainder. All you do is set the sizes of the fields you need constant, and leaving the one you don't.
Another way to do this is to define css classes with the specific widths, but that's just another way of formatting the same style sheet, really!
A: It depends on the technologies you have available, but perhaps you could try
/* CSS3 method */
table {
width: 100%;
}
table td:nth-child(-n+4) {
min-width: 25%; /* Or set the minimum PX/Percent width */
}
/* CSS2 without nth-child selector */
table {
width: 100%;
}
table td,
table td + td,
table td + td + td,
table td + td + td + td {
min-width: 25% /* Or set the minimum PX/Percent width */
}
This should set the width of the content areas and allow the final column to find its width dynamically.
Another method could be to do something like this, assuming you're able to put content inside of your tables.
/*Markup*/
<table width="100%" border="1">
<tr>
<td>
<div>One</div>
</td>
<td>
<div>Two</div>
</td>
<td>
<div>Three</div>
</td>
<td>
<div>Four</div>
</td>
<td>
<div>Five</div>
</td>
<td>
<div> </div>
</td>
</tr>
</table>
/* CSS3 method */
table {
width: 100%;
}
table td:nth-child(-n+4) div {
min-width: 100px;
}
/* CSS2 without nth-child selector */
table {
width: 100%;
}
table td div,
table td + td div,
table td + td + td div,
table td + td + td + td div {
min-width: 100px;
}
A: try this (Demo)
table {
width:100%;
table-layout: fixed;
}
td:last-child {
background: yellow;
width:200px;
layout:
}
<table border="1">
<tr>
<td>One Two Three</td>
<td>Two Three Four</td>
<td>Three Four FiveThree Four FiveThree Four FiveThree Four FiveThree Four Five</td>
<td>Four Five Six</td>
<td></td>
</tr>
</table>
A: try this, it will occupy 100% width without squashing the last column
<table style="width:100%" border=1>
<tr style="visibility:hidden">
<td width=20%></td>
<td width=20%></td>
<td width=20%></td>
<td width=20%></td>
<td width=20%></td>
</tr>
<tr>
<td>One Two Three</td>
<td>Two Three Four</td>
<td>Three Four Five</td>
<td>Four Five Six</td>
<td></td>
</tr>
</table>
leave the fifth column blank and the width will be divided equally
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: Integrating semi dynamic website with a CMS Is it possible to integrate a semi-dynamic php website(which is technically made up of static pages sharing the same header, footer and sidebar) and a dynamic website(contact forms, polls, login, etc - made with either codeigniter, zend or yii)?
If so, what's the best way to do it? I'm talking about the dynamic website automatically generating the latest news, rss and table of contents from the semi-dynamic php.
I don't mind if I have to add XML generation, additional lines of codes or integrate the semi dynamic website to mysql database in order to integrate with the dynamic website, as long as it stays semi dynamic, in that the content(the articles written) of the semi-dynamic php website is still hardcoded.
A: Use the static website as a template in the frameworked one. This is different for each framework.
A: Search for Yii's "pages" functionality - it's set up for pretty much what you are describing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JS/JQuery: I Can't get the loop right $(document).ready(function() {
$("#main-rss-link").click(function() {
$("#main-rss-link").toggleClass('on'), $("#subscribe-list").slideToggle();
});
var a = $("li.comment").attr("id");
var b = $("li.comment[id='" + a + "']");
var c = $("li.comment > div.comment-body div > p > a").attr("href");
if ($.each('#' + a == c)) {
var d = $("li.comment > div.comment-body div > p > a[href='" + c + "']");
var e = document.createElement("ul");
$(e).addClass("children").appendTo(b);
d.parents("li").appendTo(e);
$("li ul li div.reply").remove();
};
});
I want it to loop through all of my comments, but it only affects the first one it finds.
A: Use $.each to loop through your selected comments.
A:
I added the $.each(), but it still isn't working. I updated the
problem with $.each() inserted to where I believe it was to go.
Do this
$('#' + a).each(function(){ //loop through each a variable
if(a == c){ //then, if a is equal to c, do the following
var d = $("li.comment > div.comment-body div > p > a[href='" + c + "']");
....
///continue with the rest of the code etc.
}
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to avoid ^C getting printed after handling KeyboardInterrupt This morning I decided to handle keyboard interrupt in my server program and exit gracefully. I know how to do it, but my finicky self didn't find it graceful enough that ^C still gets printed. How do I avoid ^C getting printed?
import sys
from time import sleep
try:
sleep(5)
except KeyboardInterrupt, ke:
sys.exit(0)
Press Ctrl+C to get out of above program and see ^C getting printed. Is there some sys.stdout or sys.stdin magic I can use?
A: It's your shell doing that, python has nothing to do with it.
If you put the following line into ~/.inputrc, it will suppress that behavior:
set echo-control-characters off
Of course, I'm assuming you're using bash which may not be the case.
A: try:
while True:
pass
except KeyboardInterrupt:
print "\r "
A: This will do the trick, at least in Linux
#! /usr/bin/env python
import sys
import termios
import copy
from time import sleep
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = copy.deepcopy(old)
new[3] = new[3] & ~termios.ECHO
try:
termios.tcsetattr(fd, termios.TCSADRAIN, new)
sleep(5)
except KeyboardInterrupt, ke:
pass
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
sys.exit(0)
A: I don't know if this is the best way of doing this, but I fix that problem by printing two \b (backspace escape sequence) and then a space or a series of characters. This might work fine
if __name__ == "__main__":
try:
# Your main code goes here
except KeyboardInterrupt:
print("\b\bProgram Ended")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: The operation timed out – ASP I have a vanilla ASP app that runs on IIS 5.1. The below code in an ASP file causes the IIS throw the “Operation timed out” error. However despite of the error the process continues to run on the server at the background and eventually completes as expected.
I increased the ASP Script timeout in IIS via both IIS MMC and the ASP file (Server.ScriptTimeout) from 90 seconds (default) to 600, 1000 and even 10000 seconds (I know the implications of very high script timeouts) but the error occurred consistently regardless of the scrip timeout set.
WebServ is a COM+ app and I observed that the process that runs inside the app takes about 80 - 90 seconds. This app does not manipulate any IIS settings internally.
Although the code in the COM+ app could be optimized, I doubt that the optimizations alone will help because the application deals with large amount of data stored in SQL Server. Hence chances are high that the app will need more than 90 seconds to complete the process as the databases grow.
Therefore can somebody please help me understand
1. Why the error “Operation timed out” occurs regardless of the ASP Script timeout set?
2. What should we do to buy more time for the ASP file to complete the process?
P.S. I did browse a number of other posts here related to this error message but unfortunately did not find anything helpful.
Thanks.
<%
Server.ScriptTimeout = 10000
.... initialize the variables....
Set WebServ = CreateObject("WebServ.RunCommand")
lcResult = WebServ.Call(SessionKey, ConfigID, Program, Function, Mode, Params)
Set WebServ = Nothing
With Response
.ContentType = "text/xml"
.Write(lcResult)
End With
%>
A: Please try to increase time out in Attached application pool of the application.
A: What should the contents of lcResult be?
Place several response.write and response.end in your code to try to find where the timeout is happening.
A: I suggest to add Output Debug Strings to the COM Modules.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa363362%28v=vs.85%29.aspx
you can view them with your debugger or DebugView (http://technet.microsoft.com/en-us/sysinternals/bb896647)
aswell i would wrap output debug string as a COM Module to use it from ASP.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ec2 security group settings, sftp and port 80 settings I have a Linux based ec2 instance on aws with prepackaged Tomcat7 and so far I'm able to:
ssh into the instance from command line,
connect to the instance FileZilla,
sudo start/stop tomcat (tomcat is listening on port 80)
All development administration on the project happens on Ubuntu 10.10
Problems/questions are:
FileZilla: when I try upload a war file to webapps I get:
Error: /opt/tomcat7/webapps/my-fancy-app-0.1.war: open for write: permission denied
Error: File transfer failed
I've not added any users ( or ec2-user to be exact ) to any groups associated with Tomcat.
Port 80: how do enable outside access on port 80?
I have just the default security group, have not added any custom settings. When I select HTTP from the 'Create a new rule' dropdown the default setting is 0.0.0.0/0 - is this the safe or correct setting? When I have Tomcat running with that rule applied and try to visit the url shown next Public DNS I get (503 error I believe): Service Temporarily Unavailable
Last but not least, what is an Elastic IP and what role does it play in the larger picture?
Any help whatsoever will be extremely appreciated. Hopefully I'll get through this and be able to put all this in a 'paint by numbers' kinda tutorial.
A: FTP: are you using the FileZilla server or do you mean that you're using the FileZilla client? In that second case what FTP server are you using. This is a permission problem and the user to authorise might depend on the username that you're using for FTP. For example with proftpd, I'm using a different unix user id (not even created, just using the number) for each FTP username.
Port 80: Yes, 0.0.0.0/0 means to open the port 80 to everyone and this is the correct setting (how safe depends on how you secured your system).
Elastic IP is a way to associate IP addresses to machines, if for any reason your EC2 server doesn't work any more and you prefer to start a new instance, you can within minutes, start the new instance and assign your same IP address to the new instance, all from AWS management console. Even in a different availability zone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make 100.02f - 100 == 0.02f being true in c#? It seems to be rounding problem. I have array of float[] and some operations over this array. I need to write unit tests for this functionality, but comparing expected values to the resulted values happened to be not a simple task taking into account this rounding issues. Is any workaround to test math operations over my array? Thanks
A: Rounding issues are an inherent part of floating-point calculations. Use an array of decimals (decimal[]), perhaps?
100.02m - 100
A: When using floats or doubles in unit tests, your testing framework may allow you to account for an acceptable delta. Using NUnit, for example, you might write
double expected = 1d;
double delta = 0.0001d;
double actual = classUnderTest.Method();
Assert.AreEqual(expected, actual, delta);
Understand that floats and doubles are inherently imprecise for certain things, and that is by design. They represent numbers in base 2. If you need accurate base 10 representation, use the appropriate type for that: decimal.
A: If you'd written 1.1 - 0.1 == 1.0, it would still return false. It's because you're dealing with floating point numbers in a binary number system. You can't represent 0.1 in binary exactly any more than you can represent 1/3 exactly in base 10.
This is true in C#, Java, C++, C, JavaScript, Python, and every other programming language that uses the IEEE floating point standard.
A: You should use an "epsilon" value to check against (where epsilon is chosen by you)
if (yourvalue <= (0.02f + epsilon) && yourvalue >= (0.02f - epsilon))
// do what you want
I don't know if this is already implemented in c#, this is the "technical" approach
Obviusly the epsilon value should be enough small. Also I suggest to write an extension method to feel more comfortable when using it
A: You shouldn't really compare floats for equality – you can't avoid this sort of rounding errors. Depending on your use case, either use decimals if you want rounding to be more intuitive in cases like yours, or compare the difference between the floats to a chosen "acceptable" error value.
A: Since you're writing unit tests, you can easily just compute what the exact output will be. Simply compute the output, then print it using the "roundtrip" format, and then paste that string into your unit test:
float output = Operation(array);
Console.WriteLine(output.ToString("r"));
Then you'll end up with something like Assert.AreEqual(100.02 - 100, 0.019999999999996)
Alternately, you can take the output of your unit test and convert it to a string, and then compare the string. Then you'll end up with something like:
Assert.AreEqual((100.02 - 100).ToString("f"), "0.02");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: segmentation fault when erasing an object from a vector c++ So I am seg faulting when I run this function
class vector <Record<value> >::iterator itr = records.begin();
for (; itr != records.end(); ++itr) {
if (itr->isSelected()) {
itr = records.erase(itr);
recordSize--;
}
}
where my vector is of vector <Record <value> > records; and the function isSelected() is just a boolean that is either true when the object is selected or false when its not.
Can someone help me please, I don't see the problem with doing it this way
A: In the case where you're deleting the last element, itr will first be records.end() because that's what records.erase() will return, and then you're incrementing it with ++itr. Try:
while (itr != records.end()) {
if (itr->isSelected()) {
itr = records.erase(itr);
recordSize--;
} else {
++itr;
}
}
A: You shouldn't be erasing vector elements like that, it is not an efficient method as you may cause the reallocation of the vector several times during the process.
The correct and more efficient way of doing this is to use the std::erase function. See this question for examples.
A: for (; itr != records.end(); ++itr) is guaranteed not to escape the container and invoke UB if itr is not modified in the body of the loop, or if it is decremented.
Here you are advancing the iterator: itr = records.erase(itr);.
When you do so, no only you are skipping an element, also you may skip the one-past-the-end imaginary "element", IOW you may increment past one-past-the-end (UB).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: jquery filter data from json similar to Excel pivot table I have created a complex pivot table in Excel and I want to do the same thing in jquery. I have converted the data to Json. I have been able to find examples of accessing the data and of using the formulas but I can't find examples of using drop-down menus similar to the Escel filtering method.
For instance, I have five different options (City, Bedrooms, Baths, Garage, Foreclosure) and the user is able to make a choice or leave the filter alone. Based on the users choices only specific data will be used for the formulas. If they choose a City and 2 bedrooms all the relevant data will be used in the formulas.
Any suggestions on where I can find examples of doing this type of filtering in jquery with dropdowns?
A: I know, it's late for the OP but I ran into a similar requirement and found a plugin that does exactly what you are asking for, it let's the user "drag and drop" dimensions, "dropdown filtering", several render modes (including charts and heat map).
Also you can check out the code, it is written in coffeescript, you can find it all here: https://github.com/nicolaskruchten/pivottable
A: You could look at existing jQuery plugins that do pivot table stuff. This one looks good:
http://metalogic.dk/jquery.pivot/demo.htm
Although I guess it doesn't use dropdowns in the way you were imagining.
For filtering, you should filter the data yourself before pivoting using the above mentioned plugin. For this you can use jQuery's grep method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: how to change character limit of joomla user profile "About Me" field I am wondering how can I change the character limit of Joomla's user component "About Me" field.
To find this field go to Control Panel, User Manager, select a user, and in the right hand side click over the "User Profile" panel and this text area field is towards the bottom of the form
Thank you
A: OK, so this is about the 'User Profile' plugin, which extends 'com_users'. This plugin ships with core Joomla, but is disabled by default.
You can find the files related to this plugin here: /plugins/user/profile
You probably mean one of two things - either the text box in the form is too small, or the actual character limit is getting in your way. If the text box is too small, you'll find the configuration for this plugins fields here: /plugins/user/profile/profiles/profile.xml. Changing the 'cols' and 'rows' settings in here will have immediate effect.
You'll note from that that there's no explicit character limit set. There is an implicit one however. This plugin stores its data in the core Joomla table jos_user_profiles, which is set up like so:
+---------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| user_id | int(11) | NO | PRI | NULL | |
| profile_key | varchar(100) | NO | PRI | NULL | |
| profile_value | varchar(255) | NO | | NULL | |
| ordering | int(11) | NO | | 0 | |
+---------------+--------------+------+-----+---------+-------+
There's no non-hack way to change this - the varchar(255) limit is set in the schema. But you could extend this by running a query similar to this on the database:
ALTER TABLE jos_user_profiles MODIFY COLUMN profile_value TEXT;
This will change the varchar to a TEXT field, which gives you tons of room:
http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html
...but it'll change that for ALL rows in that table, so it may reduce the DB performance for that plugin. The plugin will continue to work, as the code doesn't enforce length limits anywhere.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Probing Dlls through Reflection in ASP .Net I have been trying to find more information on the technique of dll and exe discovery by way of writing programs using ASP .Net and reflection(?). I haven't been able to find anything.
I know there are dissassemblers but I am not interested in running other tools and disassembling code per say, I am more interested in understanding how to write a program that takes an unknown file or executable and determines the properties and methods within that are public.
I am just starting on my search for this and was wondering of any good resources to jumpstart the learning process.
A:
I am more interested in understanding how to write a program that takes an unknown file or executable and determines the properties and methods within that are public.
Reflection is a good way to do that. Here are a few tips if you don't want a full code explanation.
*
*You could use the Assembly.ReflectionOnlyLoad to load an existing assembly. This will only work for .NET assemblies. The difference between Load and ReflectionOnlyLoad is that Load loads an assembly that allows you to use it, like executing a method on a type in that assembly. ReflectionOnlyLoad is useful when you only want to look at what is in the assembly without executing any code. The other advantage of ReflectionOnlyLoad is that it doesn't care what platform the assembly was compiled for.
*Once you have the assembly, you can use a method like GetExportedTypes to get a list of all of the public types. If you want to get the public and non-public, you can use just GetTypes().
*So now we have our assembly loaded, and a list of all of the types. The Type class has several members for working with that type. GetMethods and GetProperties come to mind.
You can refer to this MSDN article for a more general overview of Reflection.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP script link the *last* files in a folder The way I have organized the reports in a particular folder on my site is fairly straight forward. First they all have the date, in big endian mode. This means the most recent report should be at the bottom.
So, the reports are named like this
20110102China01
20110105China01
Does anybody know a trick to have PHP pick out the very first or last thing in the folder?
A: You can make a call to shell_exec to execute a shell command. If you're doing this in a Linux environment, your command can look like one of the following.
Get the first file alphabetically in the directory:
$result = shell_exec("ls | head -n 1");
Get the last file alphabetically in the directory:
$result = shell_exec("ls | tail -n 1");
A: Try using glob() to grab them all and then getting the last thing in the array returned.
$contents = glob('path/to/directory');
$file = $contents[count($contents) - 1];
echo $file;
To get the first one do this.
$contents = glob('path/to/directory');
$file = $contents[0];
echo $file;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: "Unrecognized configuration section" after adding Signature to Config File using SignedXml.ComputeSignature I have a Windows Forms application built using the .NET 3.5 Framework which self hosts a WCF service. The service & app function properly on their own.
Concerned about having the address & binding info accessible in the app.config file, I decided to add a digital signature using System.Security.Cryptography.Xml.SignedXml.ComputeSignature. I then added the signature to the the app.config and saved it. This creates a Signature element in the app.config as the final child of the configuration node of the app.config file.
I added a function to check the signature before starting the service. The app properly verifies the signature, but then when trying to start the service, it throws the following nested errors:
*
*The type initializer for 'System.ServiceModel.DiagnosticUtility' threw an exception.
2.Configuration system failed to initialize
3.Unrecognized configuration section Signature.
It doesn't seem to matter where I place the Signature element in app.config. The signature always verifies properly, and the service always bombs griping about the unrecognized configuration section. Commenting out the Signature element in the app.config and the signature check in the code, the service will start again with no issues.
Why does the service throw these errors, and what can I do to resolve them?
Here is the app.config with redacted application names & urls:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="MyApp.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="MyAppServicePortBinding" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None" realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://myappurl/MyService" binding="basicHttpBinding" bindingConfiguration="MyAppServicePortBinding" contract="MyAppService" name="MyAppServicePort" />
</client>
<services>
<service name="MyApp.MyService" behaviorConfiguration="MyAppServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://mylocalservice:8080/LocalService" />
</baseAddresses>
</host>
<!-- this endpoint is exposed at the base address provided by host -->
<endpoint address="" binding="wsHttpBinding" contract="MyApp.IServiceInit" bindingNamespace="http://mylocalservice:8080/LocalService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyAppServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<applicationSettings>
<MyApp.My.MySettings>
<setting name="DefaultEntryType" serializeAs="String">
<value>M</value>
</setting>
<setting name="CardTypes" serializeAs="String">
<value>1111</value>
</setting>
<setting name="Freq" serializeAs="String">
<value>120000</value>
</setting>
</MyApp.My.MySettings>
</applicationSettings>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
<Reference URI="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>jJYnz3j6LgxqdcUgvNSGNmJVum4=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>czpn/uA31kMSoGFk2hi3SCYky6YM6/MjBT3lpMn7wluCjeFIFj0vJJZVI9ueQQn/RglFi8RIfAyov3rDwiS+pP/4b1Yh8KqNOftHMH9pC+CFsMHMQnIoPHyXVrFLpuU6rzjACdUky4zuB7I7Q5AHf1CF8F9PSEgIxiQ4gHgPhJCLujl6wvsMg3rXDHazRQ2Curj94iKUIsKo50X1dJxER1oWOB9g6QgzqsXTOmUkgGOygJrnrn1WQJ0UbWAvHHXIPZdD6jOL24vqhOYm55+b6hlkWdIvEvLBPVMtv2V8oQqxBpWRDh8ovMn4LQdgcFOpa/vG3ISXGp2oRzsCEpaxCQ==</SignatureValue>
</Signature>
</configuration>
A: You are missing some essential information to allow signutures to be embedded in the app.config.
From http://www.beefycode.com/post/Managing-AppConfig-Integrity-using-Xml-Digital-Signatures.aspx about adding Signatures to app.config files:
We can't just plop this new element in the app.config and expect the .NET configuration manager to process it without knowing what it is; this will cause failure during application startup. No special tricks here, we simply need to instruct the configuration system to ignore this element by adding the following to the top of the config file.
Start by entering the following in the app.config:
<configSections>
...
<section name="Signature" type="System.Configuration.IgnoreSectionHandler" />
</configSections>
View the above link for full app.config and usage example. It should do the job.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Rails can't match the existed route First I rake routes to check all the routes and make sure it exists in my app.
In my route.rb
resources :user do
resource :account
resource :addresses
end
And now everything is fine so far. I got some path helper method. Such as
user_addresses_path
this helper method works fine in everywhere(I mean it work in every view template)except one place. It can't work under my user's view template. I'll show you blow.
#it works here.
#this file is under app/view/address
<%= user_addresses_path(@user) %>
#it doesn't work here.
#this file is under app/view/user
<%= user_addresses_path(@user) %>
Just for convenient, I don't paste all the codes in here.
But if you understand what I mean, you know, just tell me why is this happening.
Add comment if you want more detail.
A: I believe the issue is the way you've got the address route defined as a nested route for the user. Specifically, in the rails documentation it states:
Passing a record (like an Active Record or Active Resource) instead of a Hash as the options parameter will trigger the named route for that record. The lookup will happen on the name of the class. So passing a Workshop object will attempt to use the workshop_path route. If you have a nested route, such as admin_workshop_path you’ll have to call that explicitly (it’s impossible for url_for to guess that route).
In other words, because the route being referred to is defined as a nested route, rails can't guess the route. Since addresses are nested inside the user, it can guess the user when on a specific address, but not the address when up at the user level.
Also, is it possible that what you have is a 'one-to-many' user-to-address relationship? If that's the case, then your resource might need to be resources (plural) in your routes file.
resources :user do
resource :addresses
end
gives you:
user_addresses POST /user/:user_id/addresses(.:format) {:action=>"create", :controller=>"addresses"}
new_user_addresses GET /user/:user_id/addresses/new(.:format) {:action=>"new", :controller=>"addresses"}
edit_user_addresses GET /user/:user_id/addresses/edit(.:format) {:action=>"edit", :controller=>"addresses"}
GET /user/:user_id/addresses(.:format) {:action=>"show", :controller=>"addresses"}
PUT /user/:user_id/addresses(.:format) {:action=>"update", :controller=>"addresses"}
DELETE /user/:user_id/addresses(.:format) {:action=>"destroy", :controller=>"addresses"}
but,
resources :user do
resources :addresses
end
gives you:
POST /user/:user_id/addresses(.:format) {:action=>"create", :controller=>"addresses"}
new_user_address GET /user/:user_id/addresses/new(.:format) {:action=>"new", :controller=>"addresses"}
edit_user_address GET /user/:user_id/addresses/:id/edit(.:format) {:action=>"edit", :controller=>"addresses"}
user_address GET /user/:user_id/addresses/:id(.:format) {:action=>"show", :controller=>"addresses"}
PUT /user/:user_id/addresses/:id(.:format) {:action=>"update", :controller=>"addresses"}
DELETE /user/:user_id/addresses/:id(.:format) {:action=>"destroy", :controller=>"addresses"}
Notice that the second option (plural) gives you routes to be able to address multiple addresses for each user, whereas the singular route only gives you a single address.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add third level nav in Ruby on Rails? New to ruby on rails, trying to get this url structure:
/about
/about/staff
/about/contact
/about/brazil
/about/brazil/staff
/about/brazil/contact
When I do:
rails generate controller about index
rails generate controller about staff
rails generate controller about contact
I set my routes to:
get "about", :to => "about#index"
get "about/staff", :to => "about#staff"
get "about/contact", :to => "about#contact"
And all is well, but I got stumped when I need to do the same for a third level for the brazil office
Should I just do
rails generate controller about brazil_index
rails generate controller about brazil_staff
rails generate controller about brazil_contact
get "about/brazil", :to => "about#brazil_index"
get "about/brazil/staff", :to => "about#brazil_staff"
get "about/brazil/contact", :to => "about#brazil_contact"
Or is there a cleaner way to accomplish this?
A: I think you want to call this rails generate controller About index staff contact
to generate AboutController with three actions index, staff and contact. Then you want to allow passing in id parameter as the second path element:
Then in config/routes.rb:
get "about/index"
get "about/staff"
get "about/contact"
get "about/:id/index" => 'about#index'
get "about/:id/staff" => 'about#staff'
get "about/:id/contact" => 'about#contact'
When I check routes with rake routes I see now:
$ rake routes
about_index GET /about/index(.:format) {:controller=>"about", :action=>"index"}
about_staff GET /about/staff(.:format) {:controller=>"about", :action=>"staff"}
about_contact GET /about/contact(.:format) {:controller=>"about", :action=>"contact"}
GET /about/:id/index(.:format) {:controller=>"about", :action=>"index"}
GET /about/:id/staff(.:format) {:controller=>"about", :action=>"staff"}
GET /about/:id/contact(.:format) {:controller=>"about", :action=>"contact"}
You can now request http://localhost:3000/about/brazil/staff and the value of params[:id] will be "brazil".
A: One good option for this is to seperate the routes by using a 'namespace' in your /config/routes.rb file like this:
namespace :about do
match '/' => 'about#index'
match '/staff' => 'about#staff'
match '/contact' => 'about#contact'
match '/:country/staff' => 'about#staff'
match '/:country/contact' => 'about#contact'
end
If you then run rake routes, you can see the routing that results:
/about(.:format) {:controller=>"about/about", :action=>"index"}
/about/staff(.:format) {:controller=>"about/about", :action=>"staff"}
/about/contact(.:format) {:controller=>"about/about", :action=>"contact"}
/about/:country/staff(.:format) {:controller=>"about/about", :action=>"staff"}
/about/:country/contact(.:format) {:controller=>"about/about", :action=>"contact"}
So all these route to the same controller (which I believe is what you wanted), and you have only three actions: staff, index and contact. The :country value will be passed in as a parameter if it exists in the url and would be accessed as params[:country].
Is this what you were trying to do?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: weird difference between int pointer and float pointer please see my codes below
#include <stdio.h>
#include <stddef.h>
typedef struct _node
{
int a;
char *s;
}Node, *nodePtr;
int main(int argc, char *argv[])
{
char *str = "string"; /*str points to satic storage area*/
Node nd;
nodePtr pNode = NULL;
size_t offset_of_s = offsetof(Node,s);
nd.a = 1;
nd.s = str;
pNode = &nd;
/*Get addr of s, cast it to a different data types pointer, then de-reference it*/
/*this works, print "string"*/
printf("%s\n", *(int*)((char*)pNode + offset_of_s));
/*this sucks, print (null)*/
printf("%s\n", *(float*)((char*)pNode + offset_of_s));
return 0;
}
i attempt to get the address of the s member of the Node structure, cast it to a data types not less than 4 bytes(4 byte is the width of a pointer on my machine), then de-reference the pointer as a argument to printf.
i do think the outcome of two printfs should be the same, but the second one displays "(null)" .
float and int have the same byte width on my machine, is the internal different representation of the two types that cause this ?
thanks in advance !
A: Your program invokes undefined behavior because the types of the arguments to printf() are not what printf expects. There is no way to predict the outcome by looking at the source code.
C99-TC3, §7.19.6.1/9
If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
However, if you are interested in the reason the behavior you've observed is as it is, it's likely that your compiler is one of those that pass floating-point values to printf() in the floating-point CPU registers. (GNU and CLang do that, for example). The second call to printf placed the dereferenced value in a floating-point register, but printf, seeing the %s conversion specifier, looked at the register where a char* would have been passed, likely a general-purpose register, which happened to be zero in your case.
PS: Here's what GCC 4.6.1 makes out of it on my linux
main:
pushq %rbx
leal .LC0(%rip), %ebx
movl $.LC1, %esi
subq $16, %rsp
movl %ebx, %edx
movl $1, %edi
movq $.LC0, 8(%rsp)
xorl %eax, %eax
call __printf_chk
movd %ebx, %xmm0
movl $.LC1, %esi
movl $1, %edi
movl $1, %eax
unpcklps %xmm0, %xmm0
cvtps2pd %xmm0, %xmm0 # this is where your value went
call __printf_chk # is NOT gonna read from xmm0!
addq $16, %rsp
xorl %eax, %eax
popq %rbx
ret
Same story with clang 2.9
...
movl $.L.str, %ebx
xorb %al, %al
movl $.L.str1, %edi # .L.str1 is your format "%s\n"
movl $.L.str, %esi # .L.str is your static "string"
callq printf
movd %ebx, %xmm0 # your value is in xmm0 again
cvtss2sd %xmm0, %xmm0 # promoted to double, but still in xmm0
movb $1, %al
movl $.L.str1, %edi
callq printf # printf has no idea
A: Your expectations are apparently based on your belief that variadic arguments of variadic functions are passed to those functions in some specific way. This is already very implementation-dependent, so from the point of the formal C language your experiments already make very little sense.
I'd guess that you expect the variadic arguments to be copied to the "variadic argument array" of some sort (stack frame?) as blocks of raw memory, regardless of their type-specific semantics. For this reason you apparently believe that an int argument should be passed in exactly the same way as a float argument since both types happen to have the same size on your platform.
This assumption is totally unfounded and incorrect. What is actually passed to printf in this case is the values of the arguments in question, and since these values have completely different type-specific semantics, they can easily be passed in completely different ways. Needless to say, the behavior of your code is undefined for more reasons than one.
One basic thing that you need to understand in this case is that it is completly impossible to pass a float value as a variadic parameter of a variadic function. All float values are automatically promoted to double values before passing, as required by the language specification. (The same applies to char and short values, which are always promoted to int first.) Considering that in your case the float value was obtained by reinterpreting memory occupied by a pointer object, and then promoted to double, it is not surprising that the results you observe make no sense whatsoever.
Another basic thing that you need to understand that reinterpreting memory occupied by an object of one type and an object of another type is no allowed by C language (in a sense that the resultant behavior is undefined). You are not allowed to reinterpret memory occupied by a pointer object as an int object. And this is exactly what you are attempting to do. Even the first of your printfs, which allegedly "works as expected", does so only by accident.
A: Yes. The internal representation of a float and an integer in binary is vastly different.
A: If you want the address, use the "%p" format specifier with printf(). It's been in C since K&R2 and maybe before.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to query my DB with with javascript? I have a page which allows users to search for their locations using the google maps API, and I want to be able to search for places I have stored in my DB that are close to the searched location.
So how can I query the DB on the fly and have the google map update?
here is my code for geocoding thus far:
function codeAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latLng = results[0].geometry.location;
map.setCenter(results[0].geometry.location);
result=results[0].address_components;
var info=[];
for(var i=0;i<result.length;++i)
{
if(result[i].types[0]=="administrative_area_level_1"){state = i.long_name; }
if(result[i].types[0]=="locality"){city = i.long_name;}
}
......
So how can I take those city and state variables and pass them to my controller to look for records?
EDIT - Im not using jquery on this page at all, the google maps API is plain ol' javascript.
I have zero AJAX knowledge, and very very little javascript knowledge.
So like, if I have the following variables: var state ="MD" and var City = "Bethesda"
and my controller so far is:
def shops
@maps = Map.where("state LIKE ?", "%#{params[:state]}%" and "city LIKE ?", "%#{params[:city]}%")
end
And then I have to get that array back and loop through it all to display it.
And I have no idea how to do this, Ive seen numerous AJAX examples with rails but so far nothing has been particularly helpful..
A: You can use jQuery to make AJAX calls that are portable cross browsers. jQuery is a lightweight JavaScript library. The server will reply with JSON encoded data that in turn will come from the DB. You can use any server side language to do that, such as Ruby, as you suggest from your tags.
Just google for JSON and jQuery.getJson() tutorial and you'll find plenty, such as this one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to protect javascript variables from being manipulated when posting to server? I'm building a simple mvc application in ASP .NET and I would like to keep all the user data of a session on the client side, i.e. that at each time the page is loaded the variables restarts from zero (for example, points in a game). That data would then be sent to the server side (as a post) to be treated and then returned to the client. I'm doing this as to not use a database and gain performance.
However, how can I ensure that this data can't be manipulated before being sent to the server? Excuse me, I'm kind of new to all this.
Thanks
A: Everything coming from the client can be manipulated, including javascript variables, FORM variables etc.
Always treat anything coming from the browser as untrustworthy. Always check if caller has access to the resource which is being requested, for every HTTP request. This is the cardinal rule for all web applications. It is generally done in the filter so, it is not so bad.
A: You could embed an HMAC in the data sent to the client so the server can verify it hasn't changed when the client sends it back later. But you also have to worry about things like replay attacks — even if a malicious client can't change the data, it can send old data that it received several reloads ago.
You say you're trying to gain a performance advantage by not using a database, but have you actually evaluated database performance and found it to be too slow? This sounds like you may be choosing a weird design for your application based on an unfounded assumption.
A: You can't, the best you can do is validate them on the server side and make sure they dont contain any malicious characters, you could also use a hash to verify the variable has not been modified manually, although they will still be able to change it.
A: There isn't a way to protect or preserve values of JavaScript variables when the page is posted back.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: A function is not being called I got a CCNode subclass, and it eventually calls a function located on its parent. First, my class will do this:
-(void)getTargetPosition {
Battle *myParent = (Battle *)self.parent;
position = [myParent getTargetPosition:@"ENEMY"];
}
Where Battle is the parent (a CCLayer).
And here's the code for the function getTargetPosition in the parent:
-(CGPoint)getTargetPosition:(NSString*)target {
NSLog(@"I AM RUNNING");
CGPoint position;
if ([target isEqualToString:@"ENEMY"]) {
position = ccp(400,250);
}else if ([target isEqualToString:@"ALLY"]) {
position = ccp(240,160);
}
return position;
}
But there is this problem: getTargetPosition is, for some reason, never called. I can tell since the NSLog "I AM RUNNING" never displays.
Any ideas why is that method not running?
The functions are all declared on the .h file already. XCode throws me no warnings/errors.
A: Is self.parent (and thus myParent) nil? Then the method would not be called.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Length limit of array of characters My question revolves around the program shown below (environment is Mac Xcode).
#include <iostream>
int main () {
char nameOne [5];
std::cin >> nameOne; // input: BillyBobThorton
std::cout << nameOne; // output: BillyBobThorton
char nameTwo [5] = "BillyBobThorton"; // compile error, initializer string too long
std::cout << nameTwo;
return 0;
}
I have a char array of length 5, so I would expect the maximum amount of characters I could store in this array to be 4 (plus the null terminating char). And this is indeed the case when I attempt to store a string to the nameTwo variable. However, when I use an array of characters as the variable to store user input, the array length is outright ignored and the array seemingly expands to accomodate the extra characters.
Why is this the case, and is there perhaps a more appropriate way to store user input to an array of characters?
A: It doesn't "seemingly expand," rather it unsafely passes the boundaries of your array and can and will cause memory corruption as a result.
There are "safe" functions that will limit the length of the user's input. Have a look at scanf with the length limiter (%xxxs where xxx is the max length), or scanf_s on Windows.
A: Is there perhaps a more appropriate way to store user input to an array of characters?
Yes! The most appropriate way in C++ is to use std::string. This will prevent your user overrunning the end of the buffer you've allocated and corrupting your stack. If you only want to display a certain number of characters, you can limit on output (or during some validation routine) using std::string::substr(). Here's an example.
#include <iostream>
#include <string>
int main ()
{
std::string nameOne;
std::cin >> nameOne; // input: BillyBobThorton
std::cout << nameOne.substr(0, 5); // output: Billy
const std::string nameTwo = "BillyBobThorton";
std::cout << nameTwo.substr(0, 5); // output: Billy
return 0;
}
A: std::cin does not know the size of the buffer when we use operator>>(char*). It only know that it have to fill a char array starting at the given address. And when it fills a char*, it read the input until it encounter the new-line (\n).
If you want to read anything that the user gives as input, you can use a std::string instead of an array of char (std::cin >> string; or std::getline(std::cin, string); to also remove the new-line from the input buffer).
If you want to limit the number of characters to be read, you should use std::cin.get(char*, size) or std::cin.get(streambuf&, size);
It is always preferable to limit the input length to avoid to read a very long string (a few thousand chars or more).
A: The most appropriate way in C++ is to use std::string
Expanding on this, it is almost always bad practice to stream from cin into a fixed size buffer, regardless of the size of the buffer. That is what leads to the infamous buffer overflow. The data coming from standard input could be of any length and you should always check that the buffer you are copying into is big enough to hold whatever you want to put into it.
When you use std::cin and std::string checking that the buffer is large enough as well as reallocating it as needed is all taken care of for you.
That being said, there is, of course, a way to restrict how much cin extracts, see How to set maximum read length for a stream in C++?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ActiveRecord::StatementInvalid: Could not find table I am trying to run users_test.rb file which just has
test "the truth" do
assert true
end
I do have a likes table, still I am getting this error. Why so?
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.
➜ channelappnew rake db:test:clone
➜ channelappnew rake db:test:clone_structure
➜ channelappnew rake db:migrate
➜ channelappnew rake db:test:load
➜ channelappnew rake db:test:prepare
➜ channelappnew rake db:test:purge
➜ channelappnew ruby -Itest test/unit/user_test.rb
Loaded suite test/unit/user_test
Started
E
Error:
test_the_truth(UserTest):
ActiveRecord::StatementInvalid: Could not find table 'likes'
Finished in 0.058371 seconds.
1 tests, 0 assertions, 0 failures, 1 errors, 0 pendings, 0 omissions, 0 notifications
0% passed
17.13 tests/s, 0.00 assertions/s
Thanks!
A: before test do rake db:test:prepare
A: Have you run rake db:migrate?
Check database if the table exists. If you are working with sqlite, then call sqlite3 db/development.sqlite3 and then issue command .schema
You can manually delete database db/test.sqlite3 and then re-create it with rake db:setup.
A: Have you checked your fixtures? It has happened to me that I modified a migration but the fixture staid the same, therefore causing a error.
A: Sometimes it is caused due to multiple versions of active record gems. Please uninstall all gems except one that your application is using. I faced the same problem and did same what i said. It worked.
A: I just had the same problem and found the solution in db/schema.rb:
# Could not dump table "xxx" because of following StandardError
# Unknown type 'bool' for column 'yyy'
maybe this helps!
"bool" worked everywhere except for this schema.rb, but the migrations where executed correctly in development mode.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: std::set constructor second argument error Codeblocks raises an error on this line :
set<string,cmpi> m;
Where the cmpi function is :
int cmpi(string one , string two )
{
one = toLowerCase(one);
two = toLowerCase(two);
if(two == one)
return 0;
else
if (one < two )
return -1;
else
return 1;
}
It says (the ERROR) :
type/value mismatch at argument 2 in template parameter list for 'template<class _Key, class _Compare, class _Alloc> class std::set'
Is there something with the return value of my cmpi function or is it something else ?
A:
type/value mismatch
Indeed.
std::set expects a type, not a function pointer (value):
int cmpi(string one, string two);
typedef int cmpi_t(string one, string two); // the type of cmpi
std::set<string, cmpi_t*> m (&cmpi);
A: The second parameter has to be a type. You can create a type for your function like this:
struct CmpI {
bool operator()(const string &a,const string &b) { return cmpi(a,b)<0; }
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Converting from IEnumerable to List I want to convert from IEnumerable<Contact> to List<Contact>. How can I do this?
A: I use an extension method for this. My extension method first checks to see if the enumeration is null and if so creates an empty list. This allows you to do a foreach on it without explicitly having to check for null.
Here is a very contrived example:
IEnumerable<string> stringEnumerable = null;
StringBuilder csv = new StringBuilder();
stringEnumerable.ToNonNullList().ForEach(str=> csv.Append(str).Append(","));
Here is the extension method:
public static List<T> ToNonNullList<T>(this IEnumerable<T> obj)
{
return obj == null ? new List<T>() : obj.ToList();
}
A: another way
List<int> list=new List<int>();
IEnumerable<int> enumerable =Enumerable.Range(1, 300);
foreach (var item in enumerable )
{
list.Add(item);
}
A: You can do this very simply using LINQ.
Make sure this using is at the top of your C# file:
using System.Linq;
Then use the ToList extension method.
Example:
IEnumerable<int> enumerable = Enumerable.Range(1, 300);
List<int> asList = enumerable.ToList();
A: If you're using an implementation of System.Collections.IEnumerable you can do like following to convert it to a List. The following uses Enumerable.Cast method to convert IEnumerable to a generic List.
// ArrayList implements IEnumerable interface
ArrayList _provinces = new System.Collections.ArrayList();
_provinces.Add("Western");
_provinces.Add("Eastern");
List<string> provinces = _provinces.Cast<string>().ToList();
If you're using Generic version IEnumerable<T>, The conversion is straight forward. Since both are generics, you can do like below,
IEnumerable<int> values = Enumerable.Range(1, 10);
List<int> valueList = values.ToList();
But if the IEnumerable is null, when you try to convert it to a List, you'll get an ArgumentNullException saying Value cannot be null.
IEnumerable<int> values2 = null;
List<int> valueList2 = values2.ToList();
Therefore as mentioned in the other answer, remember to do a null check before converting it to a List.
A: In case you're working with a regular old System.Collections.IEnumerable instead of IEnumerable<T> you can use enumerable.Cast<object>().ToList()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "346"
} |
Q: Android audio reverb Sample App Is there any sample code for Audio reverb using PresetReverb class from
2.3 in Android ?
MediaPlayer mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(this, Uri.parse("/sdcard/music/sample.mp3"));
PresetReverb mReverb = new PresetReverb(0,
mMediaPlayer.getAudioSessionId());
mReverb.setPreset(PresetReverb.PRESET_LARGEROOM);
mReverb.setEnabled(true);
mMediaPlayer.attachAuxEffect(mReverb.getId());
mMediaPlayer.setAuxEffectSendLevel(1.0f);
mMediaPlayer.prepare();
mMediaPlayermp.start();
I executed the source above, but no sound was heard.
When I added this sentence after the souce, I can hear the sound.
Thread.sleep(10000);
mp.stop();
However the sound is normal, not reverbed.
Additionally, this permission is set on Manifest.xml.
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
Is there something else I have to write except for those?
A: PresetReverb mReverb = new PresetReverb(0,mMediaPlayer.getAudioSessionId());//<<<<<<<<<<<<<
mReverb.setPreset(PresetReverb.PRESET_SMALLROOM);
mReverb.setEnabled(true);
mMediaPlayer.setAuxEffectSendLevel(1.0f);
Dont attach it to mediaplayer. it is already attached if u use getAudioSessionId().
(tested on >v4)
To disable, use
effect.setEnabled(false);
A: Instantiate the PresetReverb. You need the audio session id on which PresetReverb to be attached. Then just set pressets for which reverb you are going to use.
PresetReverb reverb = new PresetReverb(0, mediaPlayer.getAudioSessionId());
reverb.setPreset( PresetReverb.PRESET_LARGEHALL);
reverb.setPreset(PresetReverb.PRESET_LARGEROOM);
Also if you need the parameter listener then let your class implements PresetReverb.OnParameterChangeListener
and then override unimplemented method
@Override
public void onParameterChange(PresetReverb effect, int status, int param,
short value) {
// TODO Auto-generated method stub
}
at point where you need to apply the reverb, just use:
reverb.setEnabled(true);
A: Using reverb, create a reverb on the output mix (audio session "0" )
(ref.http://developer.android.com/reference/android/media/audiofx/PresetReverb.html)
Reason
'Audio framework' has two connectMode:(EFFECT_INSERT, EFFECT_AUXILIARY),
'Auxiliary effects' must be created on session 0 (global output mix).
(ref.http://developer.android.com/reference/android/media/audiofx/AudioEffect.html#EFFECT_AUXILIARY)
Imagine the REAL MIXING CONSOLE.
Sample
PresetReverb mReverb = new PresetReverb(0,0);//<<<<<<<<<<<<<
mReverb.setPreset(PresetReverb.PRESET_LARGEROOM);
mReverb.setEnabled(true);
mMediaPlayer.attachAuxEffect(mReverb.getId());
mMediaPlayer.setAuxEffectSendLevel(1.0f);
A: One cent tip here,
Permission MODIFY_AUDIO_SETTINGS is required only if you create a reverb on the output mix (audio session 0)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: showing live content like facebook? I was curious how facebook can show content live. For example, when one user comments, another person from somewhere else in the world can see that comment appear right after the user comments.
I know ajax/jquery can do an .append(data) without refreshing the page, but that won't show on other users. Would it?
A: I'm not sure exactly how Facebook does it, but heres how it probably works.
*
*User comments on item
*Comment is posted to server
*Server processes comment
*Server finds who is subscribed to that item (post, image etc.) and pings them with a notification of a new comment
*The other clients (ones who didn't post the comment) request a page which returns the number of comments
*They compare there comment count with FB's comment count. If they aren't the same, request new comments
See https://www.facebook.com/notes/facebook-engineering/inside-facebook-messages-application-server/10150162742108920
EDIT:
To go in deeply with what function you should use.
Firstly you have a list of comments.
<ul id="comments" style="list-style-type: none;">
</ul>
I set the list-style-type to none so the bullets would not show.
When the page loads, you use a jquery AJAX function, to perform a HTTP GET Request to the page serving comments. You then inject them into the DOM, using
$('#comments').html(loadedAJAXData);
Where loadedAJAXData is the data you got from a GET request.
So the injected data looked like this -
<li>Comment 1
<li>Comment 2
<li>Foo
and now the comments list looks like this -
<ul id="comments" style="list-style-type: none;">
<li>Comment 1
<li>Comment 2
<li>Foo
</ul>
So you have your comments now. Someone makes a new comment? It is sent to your website, which inserts a new comments row into the database.
Say you have another page, which you request the number of comments from. Lets call it comments.php?count.
// set interval
var tid = setInterval(getCommentsCount, 2000);
function getCommentsCount() {
//AJAX will request comment count from comments.php?count .
//Comment count is stored in the variable newCommentCount. Previous or cached comment //count is stored in oldCommentCount.
if(oldCommentCount != newCommentCount){ //If we have a different number of comments
for(int i = oldCommentCount;i<newCommentCount;i++){
//For each new comment
//Make a request to comments.php?get=commentOffset
//Then inject it into the DOM using
$('#comments').append(comment);
oldCommentCount++;
}
}
// no need to recall the function (it's an interval, it'll loop forever)
}
For example, in this script, the browser is requesting comment count every 2 seconds. Our oldCommmentCount was 0. Our newCommentCount is 2. For each new comment, we will make a request to comments.php?get=commentOffset. Where commentOffset is i. Requesting the new comment, we get its data, append it to the comments list, and then increment oldCommentCount.
A: Try something like this:
function checkServer() {
$.ajax('http://example.com/check', {data: ''}, function(data) {
// Process data changes here
}, 'json');
}
$(document).ready(function() {
setInterval("checkServer()", 500)
});
A: It's an ajax called made to the server, the server queries the database and returns any new comment, since the query hits against the database any new comment written in to the table by any user will be returned.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Backlinking through Javascript What possible ways are there for backlinking through javascript based content? I know the crawler doesn't execute the scripts, but is there any other way possible?
Regards,
Mike
A: Google publishes excellent guidelines on making AJAX applications crawlable at:
*
*http://code.google.com/web/ajaxcrawling/
Pretty much everything you need to know there, for Google's crawler anyway.
A: I figured a much easier way to do this. Simply setting up the link in the noscript will redirect back to your site.
I.e.
blahScript;Sponsored by Blah
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Move core plot x axis to last point My core plot graph in my iPhone app is drawing nicely. However, one thing I can't seem to figure out. How can I get the graph to scroll to the end of its x axis after the view loads, rather than starting at the origin? I would like the last data point upon the x axis to be visible when the graph appears. How?
I saw the plotSpace:willDisplaceBy: delegate method, which is "close" to what I need, but I need to be able to tell the graph to displace itself to the end of its x axis when its view loads. I haven't found any relevant example code for core plot to do this.
A: You need to set the xRange of the plot space so that the last point is visible. If you know the ending value and the length of the range you want to be visible, you can do something like this:
CPTXYPlotSpace *plotSpace = graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange rangeWithLocation:CPTDecimalFromDouble(end - length)
length:CPTDecimalFromDouble(length)];
The example assumes that the desired length is positive and your values are doubles. You can of course do the calculations using NSDecimal values if needed.
A: use this method :
-(CPPlotRange *)plotSpace:(CPPlotSpace *)space willChangePlotRangeTo:(CPPlotRange *)newRange forCoordinate:(CPCoordinate)coordinate
{
if (coordinate == CPCoordinateY) {
CPPlotRange *maxRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f) length:CPDecimalFromFloat(6.0f)];
CPPlotRange *changedRange = [[newRange copy] autorelease];
[changedRange shiftEndToFitInRange:maxRange];
[changedRange shiftLocationToFitInRange:maxRange];
newRange = changedRange;
}
return newRange;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to make activity always on top on android? i make a lock screen application that prevent other people to access the device when it's locked. i have an activity called lockscreen activity. here's the code:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class LockScreen extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lockscreen);
}
protected void onPause() {
super.onPause();
// it will display a lock screen again when the home button is pressed
Intent myIntent = new Intent(LockScreen.this, LockScreen.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(myIntent);
}
}
that code is used for relaunch the lockscreen activity when home button pressed, so that device can still locked. if i press the home button and didn't tap any application, it will show that lockscreen activity again within 5 second (based on android issue), but if i tap any application (eg: setting or messages) my lockscreen activity will shown after i close that application (the setting or messages is on the top and cover my lockscreen activity) so the device still can be accessed.
has anyone know how to make an activity stay on top for minimize the access from unauthorized people? thanks..
A: I'm not so sure that is possible to make an app stay on top always like that. And what are you going to do when they push the home button? Or what if they run Cyanogen and hold the back button to "kill" the app? It doesn't sound like an effective way to make a lock screen. Perhaps you can look at some of these other questions that are kinda similar. I just think that there must be a better way to implement a lock screen app.
Source of Android's lock screen
This link tells you how to find the android source code online
Where can I find Android source code online?
And this is the actual link of where the LockScreen.java is located
https://github.com/android/platform_frameworks_policies_base/blob/master/phone/com/android/internal/policy/impl/LockScreen.java
Good luck!
A: I have come across this problem long before, then I finally found out it's impossible to do so unless you modify framework.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Removing headers from jquery text() I need to get the text from a div with an id of mycenter, but I do not want the header text i.e.
<h2>This is my Title</h2>. I only want the text after the header. Additionally, sometimes the div does not contain any header.
I tried:
var pageText = $('#mycenter').text();
This correctly returns the text in the div, but this includes "This is My Title".
Any clue on how I can do this?
Thanks
A: One solution can be
var pageClone = $('#mycenter').clone();
pageClone.find(':header').remove();
var pageText = pageClone.text();
pageClone.remove();
This very well may be inefficient but it will likely serve your needs.
A: Hej Regis
http://jsfiddle.net/buyms/
So what you can do is clone the div and remove the tags in it you dont want
like this
var text = $("div").clone()
.find("h2").remove().end()
.text();
alert(text);
I hope this helps
A: $("#mycenter *").not("h2").text()
OR
$("div :not('h2')").text() // see example below and this will make sense.
Demo: http://jsfiddle.net/Wer58/
A: Use jQuery's contents() function to fetch all child nodes including text nodes. Then filter the set however you like, and finally extract the text from the remaining set.
Given a document fragment like this:
<div id="mycenter">
some text 1
<h2>The header</h2>
some text 2
<div>other stuff</div>
<h1>another header</h1>
</div>
Option #1 : Return only the text that is an immediate child of #mycenter, thus excluding the text of all child elements (not just h* elements):
$('#mycenter').contents().filter(function() {
return this.nodeType == 3;
}).text();
Gives us:
some text 1
some text 2
Option #2 : Return all descendent text, except the contents of header (H1-H6) elements that are immediate children of #mycenter:
$('#mycenter').contents().not('h1,h2,h3,h4,h5,h6').text();
Gives us:
some text 1
some text 2
other stuff
A: I went the regular expression route, but as you're using jQuery anyway I'd go with @Lee's solution.
var pageText = $('#mycenter').html().replace(/\<h2\>.*\<\/h2\>/, '')
.replace( /^\s+|\s+$/g, '' );
Demo: http://jsfiddle.net/jkeyes/RpFjc/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Using CSS3 multiple backgrounds with only one repeating I'm trying to use CSS3 multiple backgrounds: a top section (not repeated), a middle section (a 1px slice to repeat making the container "expandable"), and a bottom section (not repeated). The problem I am having is that the middle section repeats, covering both the top and bottom sections. Same result in IE9, FF6 and Chrome. Here's my code:
#container {
margin: 0 auto;
width:1093px;
background-image: url('WC-Background-Top.jpg'), url('WC-Background-1px.jpg'), url('WC-Background-Bottom.jpg');
background-position: top, middle, bottom;
background-repeat: no-repeat, repeat-y, no-repeat;
}
A: Divide your page up using <div> tags, and apply the pertaining image to each <div>'s background-image property. This way, you can specify differing property values for background-repeat.
A: You could create three separate divs with separate backgrounds specified for each.
#topContainer{background: url('WC-Background-Top.png') no-repeat; }
#midContainer{background: url('WC-Background-1px.png') repeat-y; }
#bottomContainer{background: url('WC-Background-Bottom.png') repeat-y; }
This, I believe, is the most valid way to do what you want.
Add to those the other styles you mentioned. If you want these to fall outside the flow of other elements, consider giving them position:absolute.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.