text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Combining generators I have a function that returns a list via yield. I use this function as follows:
myList = []
for i in range(10):
myList = myList + list(myListGenerator(i))
pickleFile = open("mystuff.dat", "wb")
pickle.dump(myList, pickleFile)
pickleFile.close()
I'm just wondering if this is the most efficient way to pickle the data or if I can combine the generators (myListGenerator(0), myListGenerator(1), etc) into one generator which can then be used by pickle.
Sorry if my question sonds daft but I'm new to both generators and pickle...
Thanks,
Barry
A: You can combine the results of the generators (created using a generator expression) into a single list with itertools.chain.from_iterable:
pickle.dump(list(itertools.chain.from_iterable(
myListGenerator(i) for i in range(10))), pickleFile)
Or rewrite the generator to include the range call internally, and then just do
pickle.dump(list(myListGenerator(10)), pickleFile)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: C++ RNG (Mersenne Twister) needs seed I have written a RNG class which holds different algorithms, however it does not work as expected. Besides the fact that i want use normal (rather than uniform) distribution my code always returns either the same number (max) or just 2 numbers out of the interval [min,max]:
std::function<int(int, int)> mt19937 =
[](int min, int max) -> int {
std::uniform_int_distribution<int> distribution(min, max);
std::mt19937 engine;
engine.seed(time(null));
auto generator = std::bind(distribution, engine);
return generator();
};
Can anyone explain me what is missing to solve this puzzle? Furthermore, how can i implement normal distribution? Last time i tried out std::normal_distribution i was not able to enter bounds!
EDIT: When i speak of a normal distribution i mean that the results of the RNG near the two bounds should not be generated as often as the mean of both. E.g. look at the graphical representation of the standard Gauss distribution. I am referring to it because it visualizes the probabilities of the resulting values which i want to implement/use this way, if you understand.
A: The normal distribution is just this (x is a random uniform number):
But I see something that could be problematic:
std::uniform_int_distribution<int> distribution(min, max);
Isn't this giving your number generator an int type?
To fix the seeding problem, create your engine outside of the lambda and seed it when you create it.
A RNG uses an algorithm that produces numbers that appear random, but have a a very large period of repetition (a highlight of the Mersenne Twister). When you seed, you give the RNG an initial value to start the process with. Each time you ask for another number, it spits out another iteration of the algorithm.
When you seed every iteration:
time(NULL)
this code changes only every second, so when you request a new random number, it will only change every second.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to convert string into int array in C# I am making a credit card validator program in which I am asking for a string which is going to be a 16 digit number (credit card #) and I want to convert that into an int array. How do I do that? I need to then multiply every other digit starting from the first digit by 2.
char[] creditNumbers = creditCardNumber.ToCharArray();
creditNumbers[0] = (char)((int)(creditNumbers[0] * 2));
creditNumbers[2] = (char)((int)(creditNumbers[2] * 2));
creditNumbers[4] = (char)((int)(creditNumbers[4] * 2));
creditNumbers[6] = (char)((int)(creditNumbers[6] * 2));
creditNumbers[8] = (char)((int)(creditNumbers[8] * 2));
This is what I made so far but my casting is not done properly. How do I fix the problem?
A: To just get the int array, I would do this:
creditCardNumber.Select(c => int.Parse(c.ToString())).ToArray()
To check the number using the Luhn algorithm, you could do this:
bool IsValid(string creditCardNumber)
{
var sum = creditCardNumber.Reverse()
.Select(TransformDigit)
.Sum();
return sum % 10 == 0;
}
int TransformDigit(char digitChar, int position)
{
int digit = int.Parse(digitChar.ToString());
if (position % 2 == 1)
digit *= 2;
return digit % 10 + digit / 10;
}
A: var intArray = creditCardNumber.ToCharArray().Select(o => int.Parse(o.ToString())).ToArray();
var result = new List<int>();
for(int i=0; i<intArray.Length; i++){
if((i % 2) == 0)
result.Add(intArray[i] * 2);
else
result.Add(intArray[i]);
}
Console.Write(string.Concat(result.Select(o => o.ToString())));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: jQuery Object Serialize What is the difference between this?
$("form").serialize();
and this?
var theForm = $("form");
$(theForm[0]).serialize();
How do you get the second sample to serialize like the first one?
A: try this:
var theForm = $("form");
theForm.eq(0).serialize();
A: First one selects all forms and serializes all form fields.
Second one selects form fields from FIRST form and serializes them
A: Or you could use in one line:
$("form:first").serialize();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++ Windows Shell Extensions - Win7 32bit - 64bit compatibility issues i have visual studio 2005 and i am writing a shell extension for windows explorer.
It works in Windows Vista 32bit where i compile the project.
It also works on Windows 7 64bit when the project has been compiled on Windows7 64bit.
Now i want to test it also on Windows 7 32bit when the project has been compiled on Windows Vista 32bit but it does not work !
Are there compatibility issues between c++ versions ?
The shell extension dll won't register. (side by side error).
Is it necessary to compile it on Windows 7 32bit to make it work ?
My dll is based on the example of "complete idiot's guide to writing shell extensions" on codeproject.com
Thanks !
A: it should not be compiled in debug mode but only in release mode.
also in a frequent example on the internet there is a bug and the int should get
converted to IntPtr...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Stringstream not working with doubles when _GLIBCXX_DEBUG enabled I'm using _GLIBCXX_DEBUG mode to help find errors in my code but I'm having a problem which I think is an error in the library, but hopefully someone can tell me I'm just doing something wrong. Here is a short example which repro's the problem:
#define _GLIBCXX_DEBUG
#include <iostream>
#include <sstream>
int main (int argc, const char * argv[]) {
std::ostringstream ostr;
ostr << 1.2;
std::cout << "Result: " << ostr.str() << std::endl;
return 0;
}
If I comment out the #define then the output is (as expected):
Result: 1.2
With the _GLIBCXX_DEBUG define in place however the output is simply:
Result:
I've tracked this down to the _M_num_put field of the stream being left as NULL, which causes an exception to be thrown (and caught) in the stream and results in no output for the number. _M_num_put is supposed to be a std::num_put from the locale (I don't claim to understand how that's supposed to work, it's just what I've learned in my searching so far).
I'm running this on a Mac with XCode and have tried it with both "LLVM GCC 4.2" and "Apple LLVM Compiler 3.0" as the compiler with the same results.
I'd appreciate any help in solving this. I want to continue to run with _GLIBCXX_DEBUG mode on my code but this is interfering with that.
A: Someone else has seen this over at cplusplus.com
and here at stackoverflow, too.
Consensus is that it is a known bug in gcc 4.2 for Mac OS, and since that compiler is no longer being updated, it is unlikely to ever be fixed.
Seems to me that you can either (1) use LLVM, or (2) build your own GCC and use it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: What is the best timer technique for exact one second intervals? I am writing a simple timekeeping app for a specialized outdoor sport.
The app performs a series of calculations every second, and displays information of interest to the user. Elapsed time is key to the accuracy of the calculated results. Ideally the calculation and results would be updated exactly every second. I have tried using a timer or a chronometer widget to control the update interval:
Is there a more accurate way to establish the interval?
Is there a technique that will give me a nearly exact one second interval?
The code below is not complete - just an effort to show the type of time and chronometer I am using - they run fine, they are just not precise.
import java.util.Timer ;
import java.util.TimerTask;
...
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
public void run() {
...
TimerMethod();
}
}, 0, 1000);
...
private void TimerMethod()
{
this.runOnUiThread(Timer_Tick);
}
...
private Runnable Timer_Tick = new Runnable() {
public void run() {
blah blah
}
///////////////////////////////
import android.widget.Chronometer;
...
final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
final TextView keyBox = (TextView)findViewById(R.id.keyBox);
...
myChronometer.start();
...
myChronometer.setOnChronometerTickListener(
new Chronometer.OnChronometerTickListener(){
...
public void onChronometerTick(Chronometer myChronometer) {
blah blah
}
A: Did you look at the scheduleAtFixedRate method of java.util.Timer class?
According to javadoc,
"In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate)."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Insert an HTML Object element in Webbrowser's document In a Webbrowser control there is a webpage (the document). I know how to insert any HTML element into the body.
The problem is, how can I insert an <object> along with its <param>? I must keep the existing document, so I wouldn't use Webbrowser1.Document.Write().
Dim player As HtmlElement = Webbrowser1.Document.CreateElement("object")
player.SetAttribute("width", "640")
player.SetAttribute("height", "480")
Dim param As HtmlElement = Webbrowser1.Document.CreateElement("param")
param.SetAttribute("name", "movie")
param.SetAttribute("value", "http://foo.bar.com/player.swf")
player.AppendChild(param) '<== throws an exception
Webbrowser1.Document.Body.AppendChild(player)
Thrown exception: "Value is not among the set of valid lookup values" (I guess, because I'm using french version of VS2010, which gives me "La valeur n'est pas comprise dans la plage attendue.")
WORKAROUND
Finally I could append an <object> element using Navigate() method with Javascript URI. It's a bit ugly, but it works.
A: Well, I realized my answer was exactly what you were doing. Oops.
The MSDN documentation shows a lot of methods for the object Object, but it doesn't specify appendChild. The appendChild method documentation specifies that it is a part of a bunch of objects, but not object. applyElement looks like it might work.
Also, the insertAdjacentHTML method and innerHTML parameter are valid on object Objects, and may be helpful.
Hrm - I'm not familiar with .net, but I have done something similar in Javascript. Chrome seems to produce the correct document setup with the following:
<script>
var newObj=document.createElement( "object" );
newObj.setAttribute( 'width', '640' );
newObj.setAttribute( 'height', '480' );
newObj.setAttribute( 'data', 'http://ozdoctorwebsite.com/test-4938161.gif' );
var newParam=document.createElement( "param" );
newParam.setAttribute( 'name', 'test' );
newObj.appendChild( newParam );
document.body.appendChild( newObj );
</script>
Basically - append your param element to the player and append the player to the document.body.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unit test controller - membership error I want to create a Unit test for the following controller but it got fail in the Membership class:
public class AccountController:BaseController
{
public IFormsAuthenticationService FormsService { get; set; }
public IMembershipService MembershipService { get; set; }
protected override void Initialize(RequestContext requestContext)
{
if(FormsService == null) { FormsService = new FormsAuthenticationService(); }
if(MembershipService == null) { MembershipService = new AccountMembershipService(); }
base.Initialize(requestContext);
}
public ActionResult LogOn()
{
return View("LogOn");
}
[HttpPost]
public ActionResult LogOnFromUser(LappLogonModel model, string returnUrl)
{
if(ModelState.IsValid)
{
string UserName = Membership.GetUserNameByEmail(model.Email);
if(MembershipService.ValidateUser(model.Email, model.Password))
{
FormsService.SignIn(UserName, true);
var service = new AuthenticateServicePack();
service.Authenticate(model.Email, model.Password);
return RedirectToAction("Home");
}
}
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View("LogOn", model);
}
}
Unit test code:
[TestClass]
public class AccountControllerTest
{
[TestMethod]
public void LogOnPostTest()
{
var mockRequest = MockRepository.GenerateMock();
var target = new AccountController_Accessor();
target.Initialize(mockRequest);
var model = new LogonModel() { UserName = "test", Password = "1234" };
string returnUrl = string.Empty;
ActionResult expected = null;
ActionResult actual = target.LogOn(model, returnUrl);
if (actual == null)
Assert.Fail("should have redirected");
}
}
When I googled, I got the following code but I don't know how to pass the membership to the accountcontroller
var httpContext = MockRepository.GenerateMock();
var httpRequest = MockRepository.GenerateMock();
httpContext.Stub(x => x.Request).Return(httpRequest);
httpRequest.Stub(x => x.HttpMethod).Return("POST");
//create a mock MembershipProvider & set expectation
var membershipProvider = MockRepository.GenerateMock();
membershipProvider.Expect(x => x.ValidateUser(username, password)).Return(false);
//create a stub IFormsAuthentication
var formsAuth = MockRepository.GenerateStub();
/*But what to do here???{...............
........................................
........................................}*/
controller.LogOnFromUser(model, returnUrl);
Please help me to get this code working.
A: It appears as though you are using concrete instances of the IMembershipServive and IFormsAuthenticationService because you are using the Accessor to initialize them. When you use concrete classes you are not really testing this class in isolation, which explains the problems you are seeing.
What you really want to do is test the logic of the controller, not the functionalities of the other services.
Fortunately, it's an easy fix because the MembershipService and FormsService are public members of the controller and can be replaced with mock implementations.
// moq syntax:
var membershipMock = new Mock<IMembershipService>();
var formsMock = new Mock<IFormsAuthenticationService>();
target.FormsService = formsMock.Object;
target.MembershipService = membershipService.Object;
Now you can test several scenarios for your controller:
*
*What happens when the MembershipService doesn't find the user?
*The password is invalid?
*The user and password is is valid?
Note that your AuthenticationServicePack is also going to cause problems if it has additional services or dependencies. You might want to consider moving that to a property of the controller or if it needs to be a single instance per authentication, consider using a factory or other service to encapsuate this logic.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Possible for server to run scripts So I realize this question is broad, as I'm looking for a place to start.
Is it possible to have a server that for example runs PHP scripts every day, or every 2 minutes?
Pretty much, I don't want to put these tasks in the users script, because I'm scared they would get run a lot more than is necessary, and I'd prefer to keep it separate.
I'm looking to keep it javascript, PHP or SQL as I don't have the time to learn a new language atm, so if any of you have any good places for me to read up on this, I would greatly appreciate it.
A: There might be some way to run javascript on the server side, but I'd certainly stick to PHP. SQL is not a script, by the way...
You can execute your PHP scripts every x minutes / hours / days using cronjobs. Just google crontab. You need (root) access to the server though.
A: Javascript will not run server side as you are expecting. what I would suggest is you look into writing a cron job to run a bash file. It would take minimal research to complete.
Cron Intro
Bash Intro
A: Yes, it's completely possible. On Linux (Mac too?), you use the cron job scheduler to run your scripts.
For Windows, you can try the Windows Task Scheduler. It provides similar functionality.
You can run just about any script with cron, but not JavaScript (unless you use it for serverside stuff).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the Current State of the Art in AJAX + Rails? I was quite surprised to read about RJS in Rails 3. Is this the way most rails sites work with AJAX?
And if I'm working with Backbone (and this is a good example), won't it have conflicts with ujs?
A: Rjs is easy to use but is not the proper way to deal with Ajax. Rails developers know that; all the more, RJS should be extracted to a gem. Yep, sever side js is not that scalable.
Backbone has been developed with Rails backend, and it's philosophy is a bit inspired from the framework. So you won't have any problems: it has been extensively tested.
Speaking about Backbone and Rails, I suggest you use the backbone-rails gem (my fork handles better the delete method but hasn't been merged yet).
A: Don't know about "most", but for some things, it's way easier than the alternatives (storing stuff in DOM, etc.) Would it conflict with Backbone? Dunno, but if you're using Backbone, what would you be using RJS for (except for non-Backboney parts, if any)? If you're using Backbone wouldn't you just use the Rails JSON bits?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Align an anchor inside a div to right I really don't know how to do this. I tried:
#menu-right div {
position: fixed;
text-align: right;
}
But this didn't work.
Perhaps it is because a is not text. But how do I do this with text?
A: As I understand the problem this solution should work.
div#menu-right {
width: 100%;
position: fixed;
text-align: right;
}
jsfiddle
A: Css text-align property doesn't work on inline element like span, a . To align them you can just wrap them with another element like span. In stylesheet, Then select the wrapping element and simply use display: block; After adding this, the text-align property should work well. Write the code like below.
In html:-
<span id="menu-right>
<a href="#">1</a>
<a href="#">2</a>
<a href="#">3</a>
</span>
<!--in the stylesheet write below code -->
<style>
#menu-right{
display: block; //or use width: 100%;
text-align: right;
}
</style>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to redirect when ActionNotFound in Rails I have a controller SubscriptionsController with only actions new and create. How would I redirect to new if say someone tries to visit GET /subscriptions which would normally trigger the index action?
config/routes.rb
resource :subscriptions, :only => [:new, :create]
A: Using rails3 you can do it from a route, something like:
match "/subscriptions", :to => redirect("/subscriptions/new")
Edit:
From the comments it was made clear you want to capture more than that, using a wild card you can make it more generic. You may need to combine this form with the previous to deal with the non-slash form (or try the below form without a slash, I havent tried that). Also make sure to put these "catch all" routes below your other ones since routes are matched from top to bottom.
match "/subscriptions/*other", :to => redirect("/subscriptions/new")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: File output to Notepad .txt I can't word this well, so I'll just state the facts instead.
Situation:
My C++ program outputs extended ascii characters to a text file.
Problem:
When I open up my text file with Notepad, it displays those characters incorrectly. (I am using Windows XP)
Conclusion:
If I had to guess, I would say that Notepad is saving my file using the wrong encoding. Is there a way to fix it so my program saves the correct output to the text file?
Snippet of code:
char box[] = {
201, 205, 187,
186, 32, 186,
200, 205, 188
};
When I outputFile << box[0], my expected result is "╔". Instead, Notepad displays an "É".
Expected Output:
╔═════╗
║1. ║
║ ║
║ ║
╚═════╝
Notepad Output:
ÉÍÍÍÍÍ»
º1. º
º º
º º
ÈÍÍÍÍͼ
EDIT: Ok. I understand now my mistake. Notepad uses ANSI encoding. Why is it that when I run my program and cout it to the screen, it displays as "╔"? I am using Dev-C++ to write my programs - does that mean I am using an out-of-date encoding? And is there any way in C++ to change the encoding of characters that I use?
A: Your use of the box drawing characters in "extended ASCII" is obsolete. By default, Notepad may be using Latin-1 (ISO-8859-1) encoding, which represents a different set of characters.
A: Here is a 'recursive' solution for you:
*
*select the box above that shows the correct output and copy it to the clipboard
*open notepad
*paste it into notepad (it'll look correct)
*save the notepad file (select Unicode or UTF-8 encoding) and analyze it to find out what you need to write to get that output
I'm sure you can guess from the above that to get these characters you'll have to write a Unicode text file.
A: More sophisticated text editors (like Notepad++) let you choose the encoding. UTF-8 will show you the symbols you expect.
A: If you want to see these line drawing characters in the editor, you will need to select the Windows Terminal font.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What are "separately compiled C++ templates"? Once I saw a statement that "separately compiled C++ templates" is a standard feature that none of available C++ compilers support.
What are those "separately compiled templates" and why are they ignored?
A: C++98 introduced the export keyword which allowed you to have the definition of a function template in another translation unit, with only its declaration needed to compile code that uses it. (See here if you are hazy on what's a definition vs. a declaration. Basically, you could have the function templates implementation in another translation unit.) That's just as it is with other functions.
However, only compilers using EDG's compiler front end ever supported it, and not all of them even did officially. In fact, the only compiler I know that officially supported it was Comeau C++. That's why the keyword, unfortunately, got removed from C++11.
I think it's safe to say that it is expected that a proper module system would cure C++ from many of its shortcomings that surround the whole compilation model, but, again unfortunately, a module system was not considered something that could be tackled in a reasonable amount of time for C++11. We will have to hope for the next version of the standard.
A: Separately compiled templates is where you can bring in template definitions from another translation unit instead of having to define them in every TU (normally in the header).
Basically, they're ignored because they're virtually impossible to implement in terms of complexity and bring a number of unfortunate side effects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Colorbox plugin not resizing after jQuery UI tabs load (First, let me say that I read every similar post with the resize callback. I've also tried the Colorbox API and can't find anything.)
I'm using the Colorbox plugin. Inside of the plugin, there are jQuery UI tabs. The tabs work (i.e., are switching and displaying as expected) inside of the colorbox, except that Colorbox is getting the height of the tabs at the onComplete callback, which is before the tabs are called and are still just a series of stacked divs. I know this because I set an alert with the height of the tabs on the onComplete callback, and it's tall enough that after the tabs load, they have a ton of whitespace below them.
I'm trying to resize the Colorbox, and am using the $.colorbox.resize() method, but it's not working as expected. I would expect that if it resized, it would account for the div that holds the tabs having a smaller height and adjusting accordingly, but nothing changes.
I'm hesitant to paste the HTML because it's around 600 lines.
Here's the JS: (note: I'm using a few plugins, all of which work as expected, so I don't think there's a conflict)
$(document).ready(function(){
var lightboxHeight = $(window).height() + 10; // Get height of window on load for declaring as height property of lightbox
$('.edit-profile-text').colorbox({
onComplete:function(){
$('#cboxLoadedContent').jScrollPane(); // Custom scrollbar plugin
$('html').css('overflow-y', 'hidden'); // Hide scrollbar on load so background doesn't scroll
$('#my-profile-tabs').tabs({ // jQuery UI Tabs
load: function(){
$('.tabs').height('100px'); }
});
$('.editable').editable("http://www.appelsiini.net/projects/jeditable/php/save.php", { // In place Editing
submit: 'Save',
cancel: 'Cancel'
});
$('.editable-textarea').editable("http://www.appelsiini.net/projects/jeditable/php/save.php", { // In place Editing
submit: 'Save',
cancel: 'Cancel',
type: 'textarea'
});
$('.datepicker').datepicker(); // jQuery UI datepicker
$.fn.colorbox.resize(innerHeight);
},
onClosed:function(){
$('html').css('overflow-y', 'scroll'); // Bring scrollbar back on close
},
close: 'X',
height: lightboxHeight,
fixed: true // So that colorbox opens at the point on the document the user has scrolled to
});
});
Note the $.fn.colorbox.resize(innerHeight); method. No luck.
I've also tried really hackish things like changing the height of the div as the last function on the onComplete callback, but nothing changed.
Here's the abbreviated HTML:
<section class="tabs clearfix">
<div id="my-profile-tabs" class="clearfix">
<ul>
<li><a href="#tabs-1">Personal</a></li>
<li><a href="#tabs-2">My Info</a></li>
<li><a href="#tabs-3">Match Me</a></li>
<li><a href="#tabs-4">Settings</a></li>
</ul>
<div id="tabs-1">
...
</div><!-- end #tabs-1 -->
<div id="tabs-2">
...
</div><!-- end #tabs-2 -->
<div id="tabs-3">
...
</div><!-- end #tabs-3 -->
<div id="tabs-4">
...
</div><!-- end #tabs-4 -->
</div><!-- end #my-profile-tabs -->
</section><!-- end .tabs -->
So the goal is that the height of the Colorbox window is appropriate, and that it doesn't add like 1700px whitespace below the tabs (i.e., the height of the tabs div before they become tabs).
I've wasted so much time on this and am pretty frustrated. Any help is greatly appreciated.
A: Try something like this:
$.colorbox.resize({
innerHeight: lightboxHeight
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Style input type = text I have an anchor with background icon which is nice styled. I would like to use it as if user clicks on it choose file window appear.
Simple input type = text doesn't look nice for me. Is it possible to hide it and control appearance of browse windows from my anchor?
Thanks for any help, solution
A: You can't do much with it, but you can get around that limitation quite easily by making the box invisible and triggering it via other elements.
Here are a few implementations (I like the first one):
*
*http://aquantum-demo.appspot.com/file-upload
*http://www.uploadify.com/demos/
*http://creativefan.com/10-ajax-jquery-file-uploaders/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java: Get random line from a big file I've seen how to get a random line from a text file, but the method stated there (the accepted answer) is running horrendously slow. It runs very slowly on my 598KB text file, and still slow on my a version of that text file which has only one out of every 20 lines, at 20KB. I never get past the "a" section (it's a wordlist).
The original file has 64141 lines; the shortened one has 2138 lines. To generate these files, I took the Linux Mint 11 /usr/share/dict/american-english wordlist and used grep to remove anything with uppercase or an apostrophe (grep -v [[:upper:]] | grep -v \').
The code I'm using is
String result = null;
final Random rand = new Random();
int n = 0;
for (final Scanner sc = new Scanner(wordList); sc.hasNext();) {
n++;
if (rand.nextInt(n) == 0) {
final String line = sc.nextLine();
boolean isOK = true;
for (final char c : line.toCharArray()) {
if (!(constraints.isAllowed(c))) {
isOK = false;
break;
}
}
if (isOK) {
result = line;
}
System.out.println(result);
}
}
return result;
which is slightly adapted from Itay's answer.
The object constraints is a KeyboardConstraints, which basically has the one method isAllowed(char):
public boolean isAllowed(final char key) {
if (allAllowed) {
return true;
} else {
return allowedKeys.contains(key);
}
}
where allowedKeys and allAllowed are provided in the constructor. The constraints variable used here has "aeouhtns".toCharArray() as its allowedKeys with allAllowed off.
Essentially, what I want the method to do is to pick a random word that satisfies the constraints (e.g. for these constraints, "outvote" would work, but not "worker", because "w" is not in "aeouhtns".toCharArray()).
How can I do this?
A: You have a bug in your implementation. You should read the line before you choose a random number. Change this:
n++;
if (rand.nextInt(n) == 0) {
final String line = sc.nextLine();
To this (as in the original answer):
n++;
final String line = sc.nextLine();
if (rand.nextInt(n) == 0) {
You should also check the constraints before drawing a random number. If a line fails the constraints it should be ignored, something like this:
n++;
String line;
do {
if (!sc.hasNext()) { return result; }
line = sc.nextLine();
} while (!meetsConstraints(line));
if (rand.nextInt(n) == 0) {
result = line;
}
A: I would read in all the lines, save these somewhere and then select a random line from that. This takes a trivial amount of time because a single file of less than 1 MB is a trivial size these days.
public class Main {
public static void main(String... args) throws IOException {
long start = System.nanoTime();
RandomDict dict = RandomDict.load("/usr/share/dict/american-english");
final int count = 1000000;
for (int i = 0; i < count; i++)
dict.nextWord();
long time = System.nanoTime() - start;
System.out.printf("Took %.3f seconds to load and find %,d random words.", time / 1e9, count);
}
}
class RandomDict {
public static final String[] NO_STRINGS = {};
final Random random = new Random();
final String[] words;
public RandomDict(String[] words) {
this.words = words;
}
public static RandomDict load(String filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
Set<String> words = new LinkedHashSet<String>();
try {
for (String line; (line = br.readLine()) != null; ) {
if (line.indexOf('\'') >= 0) continue;
words.add(line.toLowerCase());
}
} finally {
br.close();
}
return new RandomDict(words.toArray(NO_STRINGS));
}
public String nextWord() {
return words[random.nextInt(words.length)];
}
}
prints
Took 0.091 seconds to load and find 1,000,000 random words.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: rails how to show an array in the view with has_and_belongs_to_many I have Flowers and colors. I have set up a has_and_belongs_to_many relationship.
Through the console I can do:
q=Flower.first
q.colors
=> [#<Color id: 1, name: "Red", hex_code: "#FF0000", created_at: "2011-10-01 19:59:26", updated_at: "2011-10-01 19:59:26">, #<Color id: 3, name: "Blue", hex_code: "#0000FF", created_at: "2011-10-01 19:59:26", updated_at: "2011-10-01 19:59:26">]
and also:
q.color_ids
=> [1, 3]
How can I return the return color names? For example: ["Red", "Blue"].
A: This will give you an array of the color names:
q.colors.map(&:name)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Check Formatting of a String This has probably been answered somewhere before but since there are millions of unrelated posts about string formatting.
Take the following string:
24:Something(true;false;true)[0,1,0]
I want to be able to do two things in this case. I need to check whether or not all the following conditions are true:
*
*There is only one : Achieved using Split() which I needed to use anyway to separate the two parts.
*The integer before the : is a 1-3 digit int Simple int.parse logic
*The () exists, and that the "Something", in this case any string less than 10 characters, is there
*The [] exists and has at least 1 integer in it. Also, make sure the elements in the [] are integers separated by ,
How can I best do this?
EDIT: I have crossed out what I've achieved so far.
A: A regular expression is the quickest way. Depending on the complexity it may also be the most computationally expensive.
This seems to do what you need (I'm not that good so there might be better ways to do this):
^\d{1,3}:\w{1,9}\((true|false)(;true|;false)*\)\[\d(,[\d])*\]$
Explanation
\d{1,3}
1 to 3 digits
:
followed by a colon
\w{1,9}
followed by a 1-9 character alpha-numeric string,
\((true|false)(;true|;false)*\)
followed by parenthesis containing "true" or "false" followed by any number of ";true" or ";false",
\[\d(,[\d])*\]
followed by another set of parenthesis containing a digit, followed by any number of comma+digit.
The ^ and $ at the beginning and end of the string indicate the start and end of the string which is important since we're trying to verify the entire string matches the format.
Code Sample
var input = "24:Something(true;false;true)[0,1,0]";
var regex = new System.Text.RegularExpressions.Regex(@"^\d{1,3}:.{1,9}\(.*\)\[\d(,[\d])*\]$");
bool isFormattedCorrectly = regex.IsMatch(input);
Credit @ Ian Nelson
A: This is one of those cases where your only sensible option is to use a Regular Expression.
My hasty attempt is something like:
var input = "24:Something(true;false;true)[0,1,0]";
var regex = new System.Text.RegularExpressions.Regex(@"^\d{1,3}:.{1,9}\(.*\)\[\d(,[\d])*\]$");
System.Diagnostics.Debug.Assert(regex.IsMatch(input));
This online RegEx tester should help refine the expression.
A: I think, the best way is to use regular expressions like this:
string s = "24:Something(true;false;true)[0,1,0]";
Regex pattern = new Regex(@"^\d{1,3}:[a-zA-z]{1,10}\((true|false)(;true|;false)*\)\[\d(,\d)*\]$");
if (pattern.IsMatch(s))
{
// s is valid
}
If you want anything inside (), you can use following regex:
@"^\d{1,3}:[a-zA-z]{1,10}\([^:\(]*\)\[\d(,\d)*\]$"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: php adding up numbers I think this might be an easy question for the professionals out there, but here goes.
Basically I want to get the total word count of a bunch of paragraphs. Right now I can get the word count of each paragraph, but I can't figure out how to add them all up.
$para // an array of paragraph strings
$totalcount = '';
foreach ($para as $p)
{
$count = str_word_count($p, 0);
echo $count . "<br />";
}
print_r($totalcount);
this prints a list of 41 numbers, representing the word count of each pagraphs
but the $totalcount is an array of all these numbers. How can I get the sum of all 41 paragraphs?
A: $totalcount = 0;
foreach(...) {
$totalcount += $count;
}
echo $totalcount;
A: You need to add to the total count each loop:
$para // an array of paragraph strings
$totalcount = 0;
foreach ($para as $p)
{
$count = str_word_count($p, 0);
echo "Count: ".$count . "<br />";
$totalcount += $count;
}
echo "Total Count: ".$totalcount;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++ class variables as method parameters? When we are defining the method of a class, is it alright if we use the class variables (whether public or private) as the method's-parameters?
In other words which one would be "more correct?"
Having defined ,
class myclass{
public:
int x, y;
double foo(int, int, int);
private:
int z;
}
is this ok
double myclass::foo(int x, int y, int z) {/* Blah Blah */}
or
double myclass::foo(int xx, int yy, int zz){x=xx; y=yy; z=zz /* Blah Blah*/}
A: Either way is fine. If you need to disambiguate, just use the this keyword:
this->x = x;
A: These two:
double myclass::foo(int x, int y, int z) {/* Blah Blah */}
double myclass::foo(int xx, int yy, int zz){x=xx; y=yy; z=zz /* Blah Blah*/}
Do not do the same thing. The first one declares a function who's arguments are called x, y, and z. Because they are named the same as class-scoped variables, they hide the class-scoped variables. To access the hidden members inside "Blah Blah", you would have to use this->x and so forth.
This does not cause the arguments to be forwarded directly into the values of the members of the class.
A: It is "OK" in the same way that you are allowed open new scopes and hide names:
int a;
void foo()
{
int a;
{
int a;
// how do we refer to the other two now?
}
}
If your function definition uses the same symbols for the argument variables as are already used in the class scope, then the functions-scope symbol hides the one in the outer scope. You can sometimes disambiguate (e.g. with ::a in my example, or this->x in yours), but as my example shows, you can always hide a variable so much that it's no longer addressable.
In short, don't make your life hard, and stick to a sensible naming scheme that avoids unnecessary ambiguity. Programming is hard enough without tying your hands to your ankles.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Multiple Fork example in C I am trying to have a program that uses multiple forks.
I used this example to get myself started
Multiple fork() Concurrency
it works perfectly as is. However, when I try to add a print statement in the child like this:
if ((p = fork()) == 0) {
// Child process: do your work here
printf("child %i\n", ii);
exit(0);
}
The process never finishes. How can I do stuff in the child and get the parent to still finish execution of the program?
A: In your example code
if (waitpid(childPids[ii], NULL, WNOHANG) == 0) {
should be
if (waitpid(childPids[ii], NULL, WNOHANG) == childPids[ii]) {
because of
waitpid(): on success, returns the process ID of the child whose state has changed; on error, -1 is returned; if WNOHANG was specified and no child(ren) specified by pid has yet changed state, then 0 is returned.
Reference: http://linux.die.net/man/2/waitpid
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: (id)sender = nil? I have the following code that updates the value of a textfield with the current time. My question is: Why do you send nil as the sender at the bottom part of the code? [self showCurrentTime:nil];
CurrentTimeViewController.m
- (IBAction)showCurrentTime:(id)sender
{
NSDate *now = [NSDate date];
static NSDateFormatter *formatter = nil;
if(!formatter) {
formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterShortStyle];
}
[timeLabel setText:[formatter stringFromDate:now]];
}
...
- (void)viewWillAppear:(BOOL)animated
{
NSLog(@"CurrentTimeViewController will appear");
[super viewWillAppear:animated];
[self showCurrentTime:nil];
}
A: Because normally when action handlers are called, they pass the object that initiated the call to the method, like a UIButton, or UISegmentedControl. But, when you want to call the method from your code, and not as the result of an action, you cannot pass a human as sender, so you pass nil.
Also, the - (IBAction) indicates that this method can be connected to an event via the Interface Builder by dragging a Touch Up Inside (or touch down outside/etc) event from a button (or any other control that has some sort of event) to the File's Owner and selecting thumbTapped:.
For example:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag = 1001;
[button addTarget:self action:@selector(thumbTapped:) forControlEvents:UIControlEventTouchUpInside];
When the touch is released (and the touch is still inside the button), will call thumbTapped:, passing the button object as the sender
- (IBAction)thumbTapped:(id)sender {
if ([sender isKindOfClass:[UIButton class]] && ((UIButton *)sender).tag == 1001) {
iPhoneImagePreviewViewController *previewVC = [[iPhoneImagePreviewViewController alloc] initWithNibName:@"iPhoneImagePreviewViewController" bundle:nil];
[self.navigationController pushViewController:previewVC animated:YES];
[previewVC release];
} else {
[[[[UIAlertView alloc] initWithTitle:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]
message:@"This method was called from somewhere in user code, not as the result of an action!"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil] autorelease] show];
}
}
A: IBAction methods, in their most common form, take a single sender argument. When invoked by the system, they pass the control that triggered the action as the sender parameter. If you're going to call the method directly, you'll need to provide a sender. Since this method isn't being invoked by a control that's just been interacted with by the user, nil is used.
I actually think that calling actions directly isn't a good pattern to follow. Having a method with the tag IBAction implies "This method is invoked in response to user action" and that's an important bit of context to be able to depend on when working within that method. If code is going to call the method directly that idea's been violated.
Usually I think it's better to do something like this:
- (void)updateTime:(NSDate *)date {
static NSDateFormatter *formatter = nil;
if(!formatter) {
formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterShortStyle];
}
[timeLabel setText:[formatter stringFromDate:date]];
}
- (IBAction)showCurrentTime:(id)sender {
[self updateTime:[NSDate date]];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self updateTime:[NSDate date]];
}
A: It's because you need to send something, since the signature of the method you're calling takes an argument.
The :(id)sender is commonly seen in button press actions. When you connect a button in a nib to a method in your view controller, it will check to see if it can take an argument. If it does, the "sender" will point to the instance of the UIButton that was created in the nib.
This is also true for programmatic button creation, and many other cases where you send in selectors.
A: The specifcation for the showCurrentTime function has 1 argument named sender. If you called the function without sending the ID of an object the call would be invalid.
Nil is used instead of NULL in objective-c and it is purely being sent to satisfy the specification of the function you are calling.
As the function does not actually use the argument within the body it does not actually matter what object you send to the function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: securely pass data to AS3 from mySQL I need to pass private data from MySQL to a flash file securely. I have a PHP script that is assigning variables on the server side - how do I pass this to flash without being available publically? I assume XML and an HTTP query string are out of the question because of security. What's the most secure way of doing this?
Thanks!
Basically I have some file paths that I need to load into a music player - however, I don't want these URLs to be publicly known. I was hoping I could pass data directly to flash securely somehow.
Alternatively, should I be storing these documents as local file for flash rather than URLs?
A: If you pass "private" data to the client, he'll be able to read/decrypt it no matter what you do.
A: use htaccess and mod rewrite to dynamically create the filename based on something random that the flash can pass to your server
or
create a PHP session for the user and echo the file contents using PHP, if the session doesn't exist then PHP can just exit
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mysql SELECT not working I have the tables:
users
ID | RANK | NAME | EMAIL | PASS
01 | 1 | Foo | [email protected] | $06$uhAMXXZowVIDQ.ZR1gky.u3f/UBkLW8Kd8cbyDt2eNx1qnZH2AUmW
allow
ID | RANK | STEP
01 | 1 | 1
02 | 1 | 2
03 | 1 | 3
04 | 2 | 1
05 | 4 | *
And, I need to know all allowed steps from user rank.
My code:
SELECT users.*, allow.step AS allow_step
FROM users AS users LEFT JOIN allow ON users.rank = allow.rank
But only one step are selected.
Thanks for help!
A: SELECT u.*, GROUP_CONCAT(a.step) allow_step
FROM users u
LEFT JOIN allow a
ON u.rank = a.rank
GROUP BY a.rank_id
This should select a list of steps separated by commas. Something like 1,2,3.
If you need the concatenated values to be ordered, change the first line of the query to:
SELECT u.*, GROUP_CONCAT(a.step ORDER BY a.step) allow_step
A: The given SQL and data will yield three rows - and would even without the use of a LEFT JOIN (a simple JOIN would suffice).
You don't show or describe how you are running the SQL; do you need to fetch multiple rows in a loop, or use some 'fetch all rows' method?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: hyperlink doesn’t work in Access form I have an Access form in which I am unsuccessful in formatting the record to be in hyperlink format.
The form is in datasheet-view format, which contains records with a link to a website. The form’s datasource is a select-query. The hyperlink is created with the following expression, which concantenates text and data, in order create a web link :
"#http://www.ups.com/WebTracking/processInputRequest?sort_by=status&tracknums_displayed=1&TypeOfInquiryNumber=T&loc=en_us&InquiryNumber1=" & [T].[tracking_number] & "&track.x=0&track.y=0#"
I tried setting the property-sheet format field to “hyperlink” , but it automatically changes to “hy"perli"n\k”, in both the query-design view, and form-design-view.
please advise what I need to do in order to have the form output the records in hyperlink format, so I can just click on the website link and it will open up in a web browser
thanks very much in advance,
Nathaniel, Access 2007
A: You can use the IsHyperlink property for the textbox (format tab) , once again, these are a nuisance to edit. If you create a form based on a table with a hyperlink field, the control created for the hyperlink field will be set up as a link.
More on IsHyperlink: http://msdn.microsoft.com/en-us/library/aa196153(office.11).aspx
Paste something like this into the textbox to see it working:
clickme#http://www.ups.com/WebTracking/processInputRequest?sort_by=status&tracknums_displayed=1&TypeOfInquiryNumber=T&loc=en_us&InquiryNumber1=123456&track.x=0&track.y=0#
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Drupal CCK checkbox edit in views I'm running D6.22 with Views 2.12. I use Views to create a "search / manage content" page for my site editors.
Is there a way, within Views, to show a CCK checkbox, and allow someone to select / unselect the checkbox from the View? I'd like for my client to be able to see a list of all pages, and change the CCK checkbox for these pages without having to go to node/xxx/edit for each page.
A: You can use Views Bulk Operations (VBO) , So select Style: Bulk Operations under "Basic settings" in views admin pane. then set settings of the style(by pressing gear wheel icon):
there is an option named "Modify node fields" at the end of "Selected operations:" now select the defined field(checkbox or somethings else) as Display fields.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rspec testing in ruby mine always returns false I have a class User as follows
class User < ActiveRecord::Base
has_one :session
has_and_belongs_to_many :posts
has_and_belongs_to_many :replies
attr_accessor :clear_text_password;
validates_presence_of :username
validates_uniqueness_of :username
validates :clear_text_password, :presence => true, :length => {:minimum => 6}
validates_confirmation_of :clear_text_password
validates_presence_of :e_mail
validates_uniqueness_of :e_mail
def User.authenticate(name, password)
if user = find_by_username(name)
if user.password == encrypt_password(password)
user
end
end
end
end
Now, my rspec test file is as below
require 'spec_helper'
require 'rspec'
require 'rspec-rails'
require 'user'
describe User do
describe "my first test" do
it "should redirect if user is authenticated" do
user = User.authenticate('abcd','abcdef')
c=false
if user
c=true
end
c.should == true
end
end
end
The database table users has the username and password "abcd" and "abcdef" . but the test always fails. the method call always returns false. Please help!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails 3 nested resources short name? I'm in the process of upgrading a Rails 2.3 app to Rails 3. In the Rails 2.3 router, it was possible to set a :name_prefix of nil on nested resources to get a shorter name. The actual URL would still be fully qualified, but the code could use a shorter name. E.g.,:
map.resources :sites do |site|
site.resources :groups, :as => :groups, :controller => :url_groups, :name_prefix => nil, :member => { :clone => :post } do |group|
group.resources :tests, :as => :tests, :controller => :test_runs, :name_prefix => nil, :collection => { :latest => :get }
end
end
would allow one to use latest_tests_path. I can't figure out how to do the same thing with Rails 3, so I'm stuck with latest_site_group_tests_path. If that's the way it needs to be, I can just go through the code and change every instance of it. But I wanted to make sure I didn't miss anything first. And for better or worse, I do need to maintain the URL structure, so shallow routes don't seem to be the answer.
A: Good news is that Rails 3 still has the ability to setup arbitrary/abbreviated url helpers. Rather than a parameter to the resources method, you can create short-hand url helpers with the match declaration in routes.rb.
Say we have routes setup like this (noting that you need to maintain the 3 levels of nesting):
resources :sites do
resources :groups, :controller => :url_groups do
member do
post :clone
end
resources :test_runs do
collection do
get :latest
end
end
end
end
We get all the standard url helpers (rake routes):
clone_site_group POST /sites/:site_id/groups/:id/clone(.:format) {:action=>"clone", :controller=>"url_groups"}
latest_site_group_test_runs GET /sites/:site_id/groups/:group_id/test_runs/latest(.:format) {:action=>"latest", :controller=>"test_runs"}
site_group_test_runs GET /sites/:site_id/groups/:group_id/test_runs(.:format) {:action=>"index", :controller=>"test_runs"}
(etc)
But to create something shorter than latest_site_group_test_runs_path(site,group), add a match declaration to routes.rb like this:
match 'sites/:site_id/groups/:id/test_runs/latest' => 'test_runs#latest', :as => :latest_tests
Now you can use latest_tests_path(site,group) or latest_tests_url(site,group) to generate the fully nested path.
If your aim is brevity, you could also use implicit polymorphic paths (as long as you have all your models aligned with resource paths).
For example, given @site #1 and @group #1, all of the following will now generate the same path '/sites/1/groups/1/test_runs/latest':
= link_to "latest tests", latest_site_group_test_runs_path(@site,@group) # std helper
= link_to "latest tests", latest_tests_path(@site,@group) # match helper
= link_to "latest tests", [:latest,@site,@group,:test_runs] # implicit polymorphic path
Hope that helps! Seems like you should be able to get the flexibility you need for the app migration.
NB: I glossed over the lurking issue of having a model called "Test" since that's off topic;-) There are a few model names that are a neverending source of pain because of namespace and keyword conflicts. My other favourite is when I really wanted to have a mode called "Case" (since that matched the problem domain best. Bad idea, rapidly reversed!)
A: There's the :shallow option (see the documentation), but I'm not sure it fits your use case:
resources :sites, :shallow => true
resources :groups do
resources :tests
end
end
It has the disadvantage of creating a bunch of additional routes:
group_tests GET /groups/:group_id/tests(.:format) {:action=>"index", :controller=>"tests"}
POST /groups/:group_id/tests(.:format) {:action=>"create", :controller=>"tests"}
new_group_test GET /groups/:group_id/tests/creer(.:format) {:action=>"new", :controller=>"tests"}
edit_test GET /tests/:id/modifier(.:format) {:action=>"edit", :controller=>"tests"}
test GET /tests/:id(.:format) {:action=>"show", :controller=>"tests"}
PUT /tests/:id(.:format) {:action=>"update", :controller=>"tests"}
DELETE /tests/:id(.:format) {:action=>"destroy", :controller=>"tests"}
site_groups GET /sites/:site_id/groups(.:format) {:action=>"index", :controller=>"groups"}
POST /sites/:site_id/groups(.:format) {:action=>"create", :controller=>"groups"}
new_site_group GET /sites/:site_id/groups/creer(.:format) {:action=>"new", :controller=>"groups"}
edit_group GET /groups/:id/modifier(.:format) {:action=>"edit", :controller=>"groups"}
group GET /groups/:id(.:format) {:action=>"show", :controller=>"groups"}
PUT /groups/:id(.:format) {:action=>"update", :controller=>"groups"}
DELETE /groups/:id(.:format) {:action=>"destroy", :controller=>"groups"}
sites GET /sites(.:format) {:action=>"index", :controller=>"sites"}
POST /sites(.:format) {:action=>"create", :controller=>"sites"}
new_site GET /sites/creer(.:format) {:action=>"new", :controller=>"sites"}
edit_site GET /sites/:id/modifier(.:format) {:action=>"edit", :controller=>"sites"}
site GET /sites/:id(.:format) {:action=>"show", :controller=>"sites"}
PUT /sites/:id(.:format) {:action=>"update", :controller=>"sites"}
DELETE /sites/:id(.:format) {:action=>"destroy", :controller=>"sites"}
Besides, the shallow nesting only applies to the following routes: :show, :edit, :update, :destroy.
A: I wanted something like this too, clearly it feels redundant to type the prefixes in named routes all the time for resources that only exist as nested. I was able to get what I wanted using scope, I think this is what you sought too:
resources :sites
scope :path => '/sites/:site_id' do
resources :groups, :controller => :url_groups do
post :clone, :on => :member
end
end
scope :path => '/sites/:site_id/groups/:group_id' do
resources :tests, :controller => :test_runs do
get :latest, :on => :collection
end
end
The rake routes output:
sites GET /sites(.:format) sites#index
POST /sites(.:format) sites#create
new_site GET /sites/new(.:format) sites#new
edit_site GET /sites/:id/edit(.:format) sites#edit
site GET /sites/:id(.:format) sites#show
PUT /sites/:id(.:format) sites#update
DELETE /sites/:id(.:format) sites#destroy
clone_group POST /sites/:site_id/groups/:id/clone(.:format) url_groups#clone
groups GET /sites/:site_id/groups(.:format) url_groups#index
POST /sites/:site_id/groups(.:format) url_groups#create
new_group GET /sites/:site_id/groups/new(.:format) url_groups#new
edit_group GET /sites/:site_id/groups/:id/edit(.:format) url_groups#edit
group GET /sites/:site_id/groups/:id(.:format) url_groups#show
PUT /sites/:site_id/groups/:id(.:format) url_groups#update
DELETE /sites/:site_id/groups/:id(.:format) url_groups#destroy
latest_tests GET /sites/:site_id/groups/:group_id/tests/latest(.:format) test_runs#latest
tests GET /sites/:site_id/groups/:group_id/tests(.:format) test_runs#index
POST /sites/:site_id/groups/:group_id/tests(.:format) test_runs#create
new_test GET /sites/:site_id/groups/:group_id/tests/new(.:format) test_runs#new
edit_test GET /sites/:site_id/groups/:group_id/tests/:id/edit(.:format) test_runs#edit
test GET /sites/:site_id/groups/:group_id/tests/:id(.:format) test_runs#show
PUT /sites/:site_id/groups/:group_id/tests/:id(.:format) test_runs#update
DELETE /sites/:site_id/groups/:group_id/tests/:id(.:format) test_runs#destroy
Update: Duh, I left the static segments of the scope paths out of my example. Fixed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Get postback control in PageRequestManager endRequest event how could I get the ID of the control that caused the postback in the PageRequestManager endRequest event?
I looked at EndRequestEventArgs with Firebug but could not find such property. I am using .NET 4. Thank you.
A: If there is no “postback control ID” property in the “endRequest” eventArgs, it is possible to capture the required data within the “beginRequest” eventArgs and store it via temporary global variable.
Take a look at the “Example” of the “Sys.WebForms.PageRequestManager beginRequest Event” MSDN topic to learn more on how to capture “postback control”.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to call Action Helper as broker method in View Helper? I have Action Helper that is database abstraction layer.
I would like to access it in View Helper to read and present some data from the model.
In Controller I call Action Helper as broker method, but how to achieve the same in View Helper?
Somewhere in controller:
$this->_helper->Service("Custom\\PageService");
Service.php:
...
public function direct($serviceClass)
{
return new $serviceClass($this->em);
}
A: Nicer way will be to create a view helper inside it do
Zend_Controller_Action_HelperBroker::getStaticHelper('service')->direct("Custom\\PageService");
another way would be inside controller init method do
$this->view->helper = $this->_helper;
so in view (phtml) you can do
$this->helper->Service("Custom\\PageService");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: AVAudio detect note/pitch/etc. iPhone xcode objective-c I'm making an app on the iphone and I need a way of detecting the tune of the sounds coming in through the microphone. (I.e. A#, G, C♭, etc.)
I assumed I'd use AVAudio but I really don't know and I can't find anything in the documentation..
Any help?
A: Musical notes are nothing more than specific frequencies of sound. You will need a way to analyze all of the frequencies in your input signal, and then find a way to isolate the individual notes.
Finding frequencies in an audio signal is done using the Fast Fourier Transform (FFT). There is plenty of source code available online to compute the FFT from an audio signal. In particular, oScope offers an open-source solution for the iPhone.
Edit: Pitch detection seems to be the technical name for what you are trying to do. The answers to a similar question here on SO may be of use.
A: There's nothing built-in to the iOS APIs for musical pitch estimation. You will have to code your own DSP function. The FFTs in the Accelerate framework will give you spectral frequency information from a PCM sampled waveform, but frequency is different from psycho-perceptual pitch.
There are a bunch of good and bad ways to estimate frequency and pitch. I have a long partial list of various estimation methods on my DSP resources web page.
You can look at Apple's aurioTouch sample app for an example of getting iOS device audio input and displaying it's frequency spectrum.
A: Like @e.James said, you are looking to find the pitch of a note, its called Pitch Detection. There are a ton of resources at CCRMA, Stanford University for what you are looking for. Just google for Pitch Detection and you will see a brilliant collection of algorithms. As far as wanting to find the FFT of blocks of Audio Samples, you could use the built-in FFT function of the Accelerate Framework (see this and this) or use the MoMu toolkit. Using MoMu has the benefit of it's functions decomposing the audio stream into samples for you and easy application of the FFT using it's own functions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Loading a method using a string variable How can i work with something like:
$parameter = "get_something()";
$value = $this->method->$parameter;
I'm getting the error "undefined property $get_something()" (note the $).
A: Try to use
$name = "get_something";
$value = $this->method->$name();
instead
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Component Based Architecture in game development I have been thinking of trying out component based architecture for game development. I have read some blog posts and articles about it but I have a few things I have not sorted out yet. When I say component based I mean that you can add components to a ComponentManager that updates all components in its list. I want to try this to avoid getting classes that inherits variables and functions that they don´t need. I really like the idea of having an really simple entity class with a lot of components working side by side without getting bloated. Also, it is easy to remove and add functionality at runtime wich makes it really cool.
This is what I am aiming for.
// this is what the setup could be like
entity.componentManager.add(new RigidBody(3.0, 12.0));
entity.componentManager.add(new CrazyMagneticForce(3.0));
entity.componentManager.add(new DrunkAffection(42.0, 3.0));
// the game loop updates the component manager which updates all components
entity.componentManager.update(deltaTime);
Communication: Some of the components need to communicate with other components
I can´t rely on the components to be self-sustaining. Sometime they will need to communicate with the other components. How do I solve this? In Unity 3D, you can access the components using GetComponent().
I was thinking of doing it like this, but what happens if you have two components of the same type? Maybe you get a Vector back.
var someComponent : RigidBody = _componentManager.getComponent(RigidBody);
Priority: Some components need to update before others
Some components need to update before others to get the correct data for the current game loop. I am thinking of adding a PRIORITY to each component, but I am not sure that this is enough. Unity uses LateUpdate and Update but maybe there is a way to get an even better control of the order of execution.
Well, thats it. If you have any thoughts don´t hesitate to leave a comment. Or, if you have any good articles or blogs about this I will gladly take a look at them. Thanks.
Component based game engine design
http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/
EDIT:
My question is really how to solve the issue with priorities and communication between the components.
A: I settled for an RDMBS component entity system http://entity-systems.wikidot.com/rdbms-with-code-in-systems#objc
It is so far working really well. Each component only holds data and has no methods. Then I have subsystems that process the components and do the actual work. Sometimes a subsystem needs to talk to another and for that I use a service locator pattern http://gameprogrammingpatterns.com/service-locator.html
As for priorities. Each system is processed in my main game loop and so it is just a matter of which gets processed first. So for mine I process control, then physics, then camera and finally render.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Check for match in other column I am trying to fabricate an SQL query that will provide these results:
| Category Title | Subcategory Of |
-----------------------------------
| Category 1 | |
| Category 2 | |
| Category 3 | |
| Category 4 | |
| Category 5 | |
| Category 6 | Category 4 |
| Category 7 | Category 5 |
This is what my database looks like:
CREATE TABLE `categories` (
`category_id` int(4) NOT NULL AUTO_INCREMENT,
`subcategory_id` int(4) NOT NULL,
`category_title` longtext COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `categories` (`category_id`, `subcategory_id`, `category_title`) VALUES
(1, 0, 'Category 1'),
(2, 0, 'Category 2'),
(3, 0, 'Category 3'),
(4, 0, 'Category 4'),
(5, 0, 'Category 5'),
(6, 4, 'Category 6'),
(7, 5, 'Category 7');
I thought that you would use JOIN, but I wasn't able to mentally think of what kind of query to run, since as far as I knew JOIN was for joining two tables, not two columns. I'm new to these advanced queries (I'm good with INSERT, UPDATE, DELETE, etc. though). Any help is appreciated.
This is what I was trying, which makes no sense really.
SELECT * FROM categories RIGHT JOIN categories ON subcategory_id = category_id
A: It's called a self-join. You incldue the table name twice in the query, but giving it two different aliases and then it's just like a normal join:
SELECT
C1.category_title AS category_title,
C2.category_title AS subcategory_of
FROM categories C1
LEFT JOIN categories C2
ON C1.subcategory_id = C2.category_id
A:
as far as I knew JOIN was for joining two tables, not two columns
A better way to think about JOIN is that it defines the relationship in your query between columns.
There is no restriction that the columns being joined be in different tables. The only issue is how to refer to them, which you do using aliases, as described by a previous answer. Even when joining different tables the query is, usually, easier to read if you use aliases for the table names.
Aliases are also useful when you need to join two (or more) tables with identical column names.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: notification opening a new window no matter what in Java Android I want to launch a notification. When I click on it, it opens a NEW window of the app.
Here's my code:
public class Noficitation extends Activity {
NotificationManager nm;
static final int uniqueID = 1394885;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent= new Intent (Intent.ACTION_MAIN);
intent.setClass(getApplicationContext(), SchoolBlichActivity.class);
PendingIntent pi=PendingIntent.getActivity(this, 0, intent, 0);
String body = " body";
String title = "title!";
Notification n =new Notification(R.drawable.table, body, System.currentTimeMillis());
n.setLatestEventInfo(this, title, body, pi);
n.defaults = Notification.DEFAULT_ALL;
n.flags = Notification.FLAG_AUTO_CANCEL;
nm.notify(uniqueID,n);
finish();
}
by the way, if i add nm.cancel(uniqueID) before the finish(), it creates the notification and immediately deletes it...
Thanks for the help :D
A: You might want to just add a notification in the notification bar, and when the user clicks it, it will launch the actual Activity. This way the user won't be interrupted in whatever he's doing.
Create the status bar notification like this:
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.notification_icon, "Hello", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, myclass.class);
notification.setLatestEventInfo(getApplicationContext(), "My notification", "Hello world!", notificationIntent, PendingIntent.getActivity(this, 0, notificationIntent, 0));
mNotificationManager.notify(1, notification);
http://developer.android.com/guide/topics/ui/notifiers/notifications.html
A: Are you just trying to open a notification window in a current activity? Because if you are I dont think you need to launch it with an intent. You normally only use intents to launch new services or activities in your app unless youve built a custom view and activity/service which is to take place within the notification box. I see you have it set up in its own class which is fine but I think the way your doing it by default would open an entire new view.
If you need to launch a notification during a process or something like a button click you dont need to have the intent there.....or at least I never did :) What exactly are you trying to achieve with the notification.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I edit song metadata in Node using C++? I am trying to make a program in Node that automatically fills in metadata for a song (album,artist,name,etc.)
Is there a module out there that would let me do this? If not, how would I write one in C++?
A: If you're talking about ID3 tags, you can try Tim Smart's node-id3. If you have npm installed just:
npm install id3
It seems written in JS using async calls.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Delete models and collections Using Backbone.js:
When a user logs out is it normal to delete a bunch of models and collections?
That's what I plan to do in my application to prevent zombie data/bindings but I dont know if it's the best way to handle things.
If this is a good practice should I just call delete this on cleanup?
A: the zombies you need to worry about come from binding to events. i wrote a post about this from the perspective of views: http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/
in your case with models, you should do the unbinding first and then delete the models and collections you don't need. calling delete whatever is the best way to ensure that things are truly gone. be sure to unbind from your model and collection events first, or you'll end up with bindings that point to undefined and cause exceptions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HTML Error Returned on Production ASP.NET MVC 2 Site but Not on localhost I have a RESTful API created with ASP.NET MVC2 that returns all data as XML:
string xml = Serialize(Data, context, AcceptCharsetList, encoding);
context.HttpContext.Response.ContentEncoding = encoding;
context.HttpContext.Response.Charset = encoding.WebName;
context.HttpContext.Response.ContentType = "application/xml";
context.HttpContext.Response.Write(xml);
On my localhost that works fine for both normal responses (model + view) and for errors (error model + error view + http status code).
But on the actual web server only normal requests return xml. For errors it does not work, and the error is served as html with content type = text/html.
My localhost is 64 bit windows 7 with IIS 7.5 and my web server is windows 2008 64 bit with IIS 7.5
What could be wrong?
The expected XML is this:
<?xml version="1.0"?>
<Error xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://api.example.com/">
<Description>(403) Forbidden.</Description>
</Error>
But it is returning this HTML instead on the web server:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>403 - Forbidden: Access is denied.</title>
</head>
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
<div class="content-container"><fieldset>
<h2>403 - Forbidden: Access is denied.</h2>
<h3>You do not have permission to view this directory or page using the
credentials that you supplied.</h3>
</fieldset></div>
</div>
</body>
</html>
A: It looks like IIS is returning it's own error pages. In IIS Manager, navigate to your application, and in the Features view, look at the Error Pages under the IIS section (not the ASP.NET section).
This blog post looks like it is discussing the same problem, and the author uses the HttpResponse.TrySkipIisCustomErrors property to handle it. I'm not sure if this is applicable in your situation - hopefully it is.
A: Probably you have configured Custom Errors pages on production server that are returned when errors ocurs. Try to turn it off in Web.config:
<customErrors mode="Off" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CCSprite not rendering when made in a method from an external class I'm sure this is really obvious to someone, but this simple thing is really frustrating me.
I have a class I made called Class_Sprite, which is a sub-class of CCSprite.
I have a method in this class that is supposed to both create the texture for any given instance of Class_Sprite, and then move it to (200,200).
The program runs in the sim but all I get is a black screen.
I was able to render the sprite directly from the layer class.
Here are the files.
Class_Sprite:
#import "Class_Sprite.h"
@implementation Class_Sprite
-(id)init
{
if ((self = [super init]))
{
}
return self;
}
-(void)make:(id)sender
{
sender = [Class_Sprite spriteWithFile:@"Icon.png"];
[sender setPosition: ccp(200, 200)];
}
@end
Class Sprite header:
#import <Foundation/Foundation.h>
#import "cocos2d.h"
@interface Class_Sprite : CCSprite {
}
-(void)make:(id)sender;
@end
HelloWorldLayer.m (where the method is being called)
@implementation HelloWorldLayer
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
HelloWorldLayer *layer = [HelloWorldLayer node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
// on "init" you need to initialize your instance
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self = [super init])) {
Class_Sprite *pc = [[Class_Sprite alloc] init];
[pc make:self]; //here is where I call the "make" method
[self addChild:pc];
[pc release];
}
return self;
}
// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
// in case you have something to dealloc, do it in this method
// in this particular example nothing needs to be released.
// cocos2d will automatically release all the children (Label)
// don't forget to call "super dealloc"
[super dealloc];
}
@end
And finally the header file for HelloWorldLayer
#import "cocos2d.h"
#import "Class_Sprite.h"
// HelloWorldLayer
@interface HelloWorldLayer : CCLayer
{
}
// returns a CCScene that contains the HelloWorldLayer as the only child
+(CCScene *) scene;
@end
Thanks for your time
A: Try changing to this in Class_Sprite.m:
@implementation Class_Sprite
-(id)init
{
if ((self = [super initWithFile:@"Icon.png"]))
{
}
return self;
}
-(void)make:(CCNode *)sender
{
[self setPosition: ccp(200, 200)];
[sender addChild:self];
}
@end
And use it in HelloWorldLayer as follows:
Class_Sprite *pc = [[Class_Sprite alloc] init];
[pc make:self];
[pc release];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to enable go.vim by default (automatically)? The instructions on the Vim site says to just put the file in the /syntax folder. This works all right and well. But, for me to use the syntax I must set the following
:set syntax=go
Every single time. So, I know I am doing something wrong. I just don't know what.
Here are some things from looking around,
My HTML5 syntax set is from Rodrigo's HTML5 omnicomplete function and syntax vimball file. Though this uses some installation script to get it going.
As far as I can tell this would be my first manual adding of syntax file.
Also, my VIMRUNTIME is not set, well because there is no syntax.vim file, so from reading the documentation I see it checks for files via synload.vim
I even read the "Making Your Own Syntax Files" section, which says that same as above with the syntax=go option. Am I supposed to be detecting the .go filetype as described in new filetype section?
How can I enable syntax highlighting for GO by default?
This is for Mac Snow Leopard.
I don't think it is this complicated but I decided to leave all the different documentation I skimmed. GO and Vim say to just add the file. But it is definitely not detecting it automatically
A: If you are using filetype detection in your ~/.vimrc file with the following line:
filetype plugin indent on
then you can place the file in the following folder:
~/.vim/after/ftplugin/go.vim
or for windows
~/vimfiles/...
For the filetype detection to work, would would want the autocmd in a file in the ftdetect folder:
~/.vim/ftdetect/go.vim
and the contents would be:
autocmd BufNewFile,BufReadPost *.go set filetype=go
A: Use autocmd:
au BufRead,BufNewFile *.go setlocal filetype=go
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: insert multiple rows from array into table with unique ID I have copied and modified a script off the internet. The script originally deleted selected records from a mysql table query. I have modified the script to insert the selected records into another table with the insert into statement.
I would like to know how I can insert all the selected records from the mysql array into the other table with the same id.
The logic is simlar to that of an 'orderdetails' table. I want all products ordered to have the same ordernumber so they share a common value.
How can I modify the below script to insert all values from the array with a unique number?
<?php
mysql_connect("localhost", "user", "pass")or die("cannot connect");
mysql_select_db("db")or die("cannot select DB");
$sql="SELECT * FROM category";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr><td><form name="form1" method="post">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr><td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Insert multiple rows in mysql</strong></td></tr>
<tr><td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Category ID</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Category</strong></td></tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr><td align="center" bgcolor="#FFFFFF"><input type="checkbox" name=check[] value="
<?php echo $rows['cat_id']; ?>"></td>
<td bgcolor="#FFFFFF"><?php echo $rows['cat_id']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['category']; ?></td></tr>
<?php
}
?>
<tr><td colspan="3" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td></tr>
<?php
$check=$_POST['check'];
if($_REQUEST['delete']=='Delete'){
{
$sql="INSERT INTO category1 (cat_id,category)
SELECT cat_ID, category
FROM category
WHERE cat_id='$val'";
foreach($check as $key=>$value)
{
$sql="INSERT INTO category1 (cat_id,category)
SELECT cat_ID, category
FROM category
WHERE cat_id='$value'";
$final = mysql_query($sql);
if($final) {
echo "<meta http-equiv=\"refresh\" content=\"0;URL=php.php\">";
}
}
}
}
// Check if delete button active, start this
// if successful redirect to php.php
mysql_close();
?>
</table></form></td></tr></table>
A: You code has several issues:
A- You have SQL-injection holes: Use mysql_real_escape_string()
B- You have possible XSS vulnerabilities: Use htmlspecialchars to escape all $vars that you echo.
C- Using select * when you're only going to use the fields catID, category is waste full. Always name the fields you select explicitly.
See:
How does the SQL injection from the "Bobby Tables" XKCD comic work?
What are the best practices for avoiding xss attacks in a PHP site
What is the reason not to use select *?
To answer your question
I would use code something like
$check = $_POST['check'];
if (is_array($check)) {
//simple test to see if an array is multi-dimensional.
if (count($array) != count($array, COUNT_RECURSIVE))
{
//die("multidimensional array's are not allowed");
//insert code to reask the array, or work around the issue.
//you really should not use `die` in production code.
} else {
//escape what's inside the array, not the array itself.
$check = array_walk($check, 'mysql_real_escape_string');
$check = "'".implode("','",$check)."'"; //1,2,3 => '1','2','3'
} else { //not an array
$check = "'".mysql_real_escape_string($check)."'";
}
//Inserts all $check's in one go.
$sql = "INSERT INTO category1 (cat_id,category)
SELECT cat_ID, category
FROM category
WHERE cat_id IN ($check) "; //$check is already quoted.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Will the value of a set $_SERVER['HTTP_CLIENT_IP'] be an empty string? I have a simple script which determines the user's IP address:
function GetIp(){
if (!empty($_SERVER['HTTP_CLIENT_IP']))
//check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
//to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
Now on the Net somewhere I saw someone using this script:
if (isset($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != '')
$Ip = $_SERVER['HTTP_CLIENT_IP'];
elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != '')
$Ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] != '')
$Ip = $_SERVER['REMOTE_ADDR'];
I was wondering if my implementation is broken.. Do I need to check if the value of $_SERVER['HTTP_CLIENT_IP'], $_SERVER['HTTP_X_FORWARDED_FOR'], or $_SERVER['REMOTE_ADDR'] is empty? Or is it actually unnecessary to do so?
A: From Kohanas' Request class:
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])
AND isset($_SERVER['REMOTE_ADDR'])
AND in_array($_SERVER['REMOTE_ADDR'], Request::$trusted_proxies))
{
// Use the forwarded IP address, typically set when the
// client is using a proxy server.
// Format: "X-Forwarded-For: client1, proxy1, proxy2"
$client_ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
Request::$client_ip = array_shift($client_ips);
unset($client_ips);
}
elseif (isset($_SERVER['HTTP_CLIENT_IP'])
AND isset($_SERVER['REMOTE_ADDR'])
AND in_array($_SERVER['REMOTE_ADDR'], Request::$trusted_proxies))
{
// Use the forwarded IP address, typically set when the
// client is using a proxy server.
$client_ips = explode(',', $_SERVER['HTTP_CLIENT_IP']);
Request::$client_ip = array_shift($client_ips);
unset($client_ips);
}
elseif (isset($_SERVER['REMOTE_ADDR']))
{
// The remote IP address
Request::$client_ip = $_SERVER['REMOTE_ADDR'];
}
This is pretty much as good as it gets. Please note the Request::$trusted_proxies array and that your $ip var is Request::$client_ip in this case.
A: Do not check any HTTP_* headers for the client IP unless you specifically know your application is configured behind a reverse proxy. Trusting the values of these headers unconditionally will allow users to spoof their IP address.
The only $_SERVER field containing a reliable value is REMOTE_ADDR.
A: If the reason why you want to find out the client's IP address is really important, screw all this stuff.
Any one of these header values can be freely spoofed.
REMOTE_ADDR is the only really reliable information, as it is transmitted to you by your web server that is handling the request. It can be theoretically falsified as well, but that is much, much harder than spoofing a header value, and an entirely different class of attack.
There are exceptions in very, very specific hosting environments behind reverse proxies. In those cases the person administering that proxy will be able to tell what header value you need to test for.
A: The two things are practically identical.. In the script you found, the author is just doing a check if the element in the array is set before checking that it is non-empty.
In regards to using the empty()-function instead of the comparison, check http://php.net/empty. Since you are dealing with a variable that is set by the environment and not a user input it doesn't matter which of the two options you choose. So your script should be perfectly fine
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Android: OpenGL textures too large, can't figure out why Why do my textures seemingly take up so much space?
My app, which uses opengl heavily, produces the following heap stats* during operation:
Used heap dump 1.8 MB
Number of objects 49,447
Number of classes 2,257
Number of class loaders 4
Number of GC roots 8,551
Format hprof
JVM version
Time 1:08:15 AM GMT+02:00
Date Oct 2, 2011
Identifier size 32-bit
But, when I use the task manager on my phone to look at the ram use of my application it says my app uses 44.42MB. Is there any relationship between heap size use and ram use? I think much of that 42MB must be my open GL textures, but I can't figure out why they take up so much space, because on disk all the files together take only take up 24MB (and they are not all loaded at the same time). And I'm even making many of them smaller by resizing the bitmap prior to texture loading. I also dynamically create some textures, but also destroy those textures after use.
I am using OpenGL 1.0 and Android 2.2, typical code that I use to load a texture looks like this:
static int set_gl_texture(Bitmap bitmap){
bitmap = Bitmap.createScaledBitmap(bitmap, 256, 256, true);
// generate one texture pointer
mGL.glGenTextures(1, mTextures, 0);
mGL.glBindTexture(GL10.GL_TEXTURE_2D, mTextures[0]); // A bound texture is
// an active texture
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0,GL10.GL_RGBA, bitmap, 0);
// create nearest filtered texture
mGL.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
GL10.GL_LINEAR); // This is where the scaling algorithms are
mGL.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
GL10.GL_LINEAR); // This is where the scaling algorithms are
mGL.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_CLAMP_TO_EDGE);
mGL.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_CLAMP_TO_EDGE);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
Log.v("GLSurfaceView", "Loading Texture Finished, Error Codes:"+mGL.glGetError());
return mTextures[0];
}
Code which I use to load bitmaps looks like the following:
public int load_texture(int res_id){
if(mBitmapOpts==null){
mBitmapOpts = new BitmapFactory.Options();
mBitmapOpts.inScaled = false;
}
mBtoLoad = BitmapFactory.decodeResource(MyApplicationObject.getContext().getResources(),res_id, mBitmapOpts);
assert mBtoLoad != null;
return GraphicsOperations.set_gl_texture(mBtoLoad);
}
*hprof file analyzed using mat, same data is generated by eclipse ddms
A: PNGs are compressed images. In order for OpenGL to use them, the pngs must be decompressed. This decompression will increase the memory size.
You may want to decrease the size of some of the textures somehow. Maybe instead of using 512x512 images, use 256x256 or 128x128. Some textures that you use may not need to be so large since they are going onto a mobile device with a limited screen size.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C++11 File Streams Has C++11 move semantics made the use of std::ifstream and std::ofstream easier or safer with regards to exceptions? I guess it depends on the standard library aswell. Any differences there between GCC, ICC and VC++ Compiler?
A: No. The exception safety aspects of the std::stream classes has not been impacted. The only difference is that you can now return streams from factory functions and store them in containers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Building dll with g++ for use with MSVC application My end-goal here is to execute g++ from my MSVC application to build dlls at runtime. The dlls which g++ creates will then be loaded by the MSVC app for use.
Just messing around with some test code using the command line I managed to build a dll but it seems to have some problems:
C:\MinGW\bin>g++ -shared -o testdll.dll AIFuncs_RF.cpp AIFuncs_RF.def
Warning: resolving _CreateAIModule by linking to _CreateAIModule@4
Use --enable-stdcall-fixup to disable these warnings
Use --disable-stdcall-fixup to disable these fixups
Warning: resolving _DestroyAIModule by linking to _DestroyAIModule@0
Here is my def file:
LIBRARY "AIFuncs_RF"
EXPORTS
CreateAIModule=CreateAIModule @1
DestroyAIModule=DestroyAIModule @2
And the code for the dll main:
BOOL APIENTRY DllMain(HMODULE hModule, DWORD Reason, LPVOID pReserved)
{ switch ( Reason )
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
extern "C" void __stdcall
CreateAIModule()
{
}
extern "C" void __stdcall
DestroyAIModule()
{
}
Any ideas why the functions aren't linked correctly?
Thanks a lot for any help.
A: The stdcall naming conventions of gcc and Microsoft's C compiler differ. The gcc adds the size of the arguments pushed onto the stack to the function name after an @. MS doesn't. Your def file contains the MS versions, so the gcc uses its auto-fixup to provide the MS style symbols.
This is per se not an error. gcc just warns you it has done such a thing, and you should make this explicit by providing the --enable-stdcall-fixup linker flag (so, -wl,--enable-stdcall-fixup to the compiler call).
The reason for the @ notation is BTW fairly sane: stdcall functions pop their arguments from the stack on return, and the caller pushes them, so they must agree perfectly on the size of these arguments or stack corruption will occur with disastrous results.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Should subtype/supertype used in databses? I have a comments table for blogs, articles, profiles. A comments table could be a supertype and comments_blog, comments_article, comments_profile could be subtypes.
Should supertype/subtype be used in database design since it is object oriented design or should have 3 distinct tables?
A: it depends on the details. There are arguments for each approach. Basically, the more data that is shared between the tables, the more sense it makes to 'normalize' the data and use 'supertype/subtype' as you put it. Note that if you take this approach, your sql can get pretty complicated and you will have to join across the tables.
Another option is to have one table and use a simple column like 'comment_type' to differentiate between if it is a blog, article, or profile. The sql for that approach would be real simple too and its just a where comment_type = 'whatever'. Be sure to index the 'comment_type' column. This approach makes less sense if the columns in your tables are drastically different.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Playing an audio file, from a web page, on a smartphone I'm creating an alternate page of a web site just for smartphones that needs to play an audio file. I can reformat for mp3, ogg, wav, whatever works. I've tried the HTML5 "audio" tag and tested on an iPhone, with no luck. Anyone have any ideas and/or a link to a page that works? -Thanks
A: Each phone is going to be a bit different, in what it supports. Many devices support Flash, but not iOS. It all depends on which platforms you are targeting.
If the audio doesn't have to be playing with the page visible, you can try just linking to a playlist file (such as m3u or pls). Any device I've tested with supports this method, except for Android. For Android, just load Flash.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Goal Seek, in Mathematica For an experiment, we generated in Matlab some images made out of 8 Disks. We constrained, the minimum distance between the disks and between the disks and the frame as well as the location of the Disks Center Of Gravity (COG). Bellow an example of a composition with the COG on the upper lift "third"
FraXYs = {{4.32, 3.23}, {35.68, 26.75}}
stiDisks = {{{8, 11}, 1}, {{10, 17}, 1}, {{16, 24}, 1}, {{25, 22},1},
{{31, 22}, 1}, {{7, 21}, 2}, {{16, 12}, 2}, {{19, 22}, 2}}
Graphics[{White, EdgeForm[Thick],
Rectangle @@ FraXYs,
Red, Disk[{14.77, 18.91}, 1],
Blue, Opacity[.6], EdgeForm[Black],
Blue, Thickness[0.003],
Opacity[1],
Black,
Disk[#[[1]], #[[2]]] & /@ stiDisks}, ImageSize -> {400, 300}]
I would like to generate those stimuli in Mathematica. Below are the element (features and constraints) I am dealing with. The measures are in Cm. The Center Of Gravity (COG) of the shapes is defined as the area weihtgted location of the disks.
The Features :
Stimuli Frame : {{xMin,xMin},{xMax,yMax}}
FraXYs = {{4.32, 3.23}, {35.68, 26.75}}
5 Small Disks : with radius
rSmall=1
3 Large Disks : with radius
rLarge=2
The Constraints :
Minimum distance between the shapes edges :
minDistSha=1
Minimum distance between the shapes edges and the frame border :
minDistFra=1
Distance of shapes COG from the center :
minDistCogCenter=2
Potentially, I will need to constraint the COG of the disks to be on a certain angle from the center (theta coordinate in a polar system?). So I could select the disks coordinates constraining their COGs to be located every 22.5 degree in a polar coordinate
angleBin=22.5
Is there useful Functions in Mathematica to achieve the selection under constraints aside of Selct.
I would be curious to know if a closed formula to generate 1 composition with a particular COG location is possible.
Indicatively, I will need to get a pool of 1000 compositions. Using the "theta constraints"of 36 degrees, I should extract 10*100 composition with their COG located on the 10 different theta bars at a minimum or fixed distance from the center.
Please tell me if clarifications are needed. Thank You for your attention.
A: This might get you started. It is a simple rejection method to generate circles at random, throwing away ensembles that do not meet requirements.
Arguments are the box size, numbers and radii of small and large circles, and a minimum separation. That last is used both for distances to boundary and distances between circles. I double it for the center of gravity to center of frame constraint. Clearly this usage could be generalized by adding more arguments.
For purposes of assessing how likely this is to find viable ensembles, I print the number of times through the loop. Also I use a Catch/Throw mechanism that is not really necessary (artifact of some experimentation that I did not bother to remove).
--- edit ---
The code below has modest changes from what I originally posted. It separates the center of gravity circle as the red one.
To handle the constraint that it lie at some specified angle, one might generate as below, rotate to put into the correct angular position, and recheck distances from circles to frame boundary. Possibly there is something smarter that will be less likely to give a rejection, while still maintaining uniformity. Actually I'm not at all certain that what I coded gives a uniform distribution from the space of allowable configurations. If it does, the influence of rotating will very likely destroy that property.
--- end edit ---
randomConfiguration[{xlo_, ylo_}, {xhi_, yhi_}, nsmall_, nlarge_,
rsmall_, rlarge_, minsep_] := Catch[Module[
{found = False, xsmall, ysmall, xlarge, ylarge, smallsep, largesep,
smallcircs, largecircs, cog, cen, indx = 0},
smallsep = {rsmall + minsep, -rsmall - minsep};
largesep = {rlarge + minsep, -rlarge - minsep};
cen = {xhi - xlo, yhi - ylo};
While[! found,
found = True;
indx++;
xsmall = RandomReal[{xlo, xhi} + smallsep, nsmall];
ysmall = RandomReal[{ylo, yhi} + smallsep, nsmall];
xlarge = RandomReal[{xlo, xhi} + largesep, nlarge];
ylarge = RandomReal[{ylo, yhi} + largesep, nlarge];
smallcircs = Transpose[{xsmall, ysmall}];
Do[If[
Norm[smallcircs[[i]] - smallcircs[[j]]] <= 2*rsmall + minsep,
found = False; Break[]], {i, nsmall - 1}, {j, i + 1, nsmall}];
largecircs = Transpose[{xlarge, ylarge}];
Do[If[
Norm[largecircs[[i]] - largecircs[[j]]] <= 2*rlarge + minsep,
found = False; Break[]], {i, nlarge - 1}, {j, i + 1, nlarge}];
Do[If[
Norm[smallcircs[[i]] - largecircs[[j]]] <=
rsmall + rlarge + minsep, found = False; Break[]], {i,
nsmall}, {j, nlarge}];
cog = (rsmall^2*Total[smallcircs] +
rlarge^2*Total[largecircs])/(nsmall*rsmall^2 +
nlarge*rlarge^2);
If[Norm[cog - cen] <= 2*minsep, found = False;];
];
Print[indx];
Throw[{{cog, rsmall},Map[{#, rsmall} &, smallcircs],
Map[{#, rlarge} &, largecircs]}]
]]
Example:
{smallc, largec} =
randomConfiguration[{4.32, 3.23}, {35.68, 26.75}, 5, 3, 1, 2, 1];
13
FraXYs = {{4.32, 3.23}, {35.68, 26.75}};
{cog, smallc, largec} =
randomConfiguration[{4.32, 3.23}, {35.68, 26.75}, 5, 3, 1, 2, 1];
Graphics[{White, EdgeForm[Thick], Rectangle @@ FraXYs, Red,
Apply[Disk, cog], Blue, Opacity[.6], EdgeForm[Black], Blue,
Thickness[0.003], Opacity[1], Black,
Disk[#[[1]], #[[2]]] & /@ Join[smallc, largec]},
ImageSize -> {400, 300}]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Parallel file matching, Python I am trying to improve on a script which scans files for malicious code. We have a list of regex patterns in a file, one pattern on each line. These regex are for grep as our current implementation is basically a bash script find\grep combo. The bash script takes 358 seconds on my benchmark directory. I was able to write a python script that did this in 72 seconds but want to improve more. First I will post the base-code and then tweaks I have tried:
import os, sys, Queue, threading, re
fileList = []
rootDir = sys.argv[1]
class Recurser(threading.Thread):
def __init__(self, queue, dir):
self.queue = queue
self.dir = dir
threading.Thread.__init__(self)
def run(self):
self.addToQueue(self.dir)
## HELPER FUNCTION FOR INTERNAL USE ONLY
def addToQueue(self, rootDir):
for root, subFolders, files in os.walk(rootDir):
for file in files:
self.queue.put(os.path.join(root,file))
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
self.queue.put(-1)
class Scanner(threading.Thread):
def __init__(self, queue, patterns):
self.queue = queue
self.patterns = patterns
threading.Thread.__init__(self)
def run(self):
nextFile = self.queue.get()
while nextFile is not -1:
#print "Trying " + nextFile
self.scanFile(nextFile)
nextFile = self.queue.get()
#HELPER FUNCTION FOR INTERNAL UES ONLY
def scanFile(self, file):
fp = open(file)
contents = fp.read()
i=0
#for patt in self.patterns:
if self.patterns.search(contents):
print "Match " + str(i) + " found in " + file
############MAIN MAIN MAIN MAIN##################
############MAIN MAIN MAIN MAIN##################
############MAIN MAIN MAIN MAIN##################
############MAIN MAIN MAIN MAIN##################
############MAIN MAIN MAIN MAIN##################
############MAIN MAIN MAIN MAIN##################
############MAIN MAIN MAIN MAIN##################
############MAIN MAIN MAIN MAIN##################
############MAIN MAIN MAIN MAIN##################
fileQueue = Queue.Queue()
#Get the shell scanner patterns
patterns = []
fPatt = open('/root/patterns')
giantRE = '('
for line in fPatt:
#patterns.append(re.compile(line.rstrip(), re.IGNORECASE))
giantRE = giantRE + line.rstrip() + '|'
giantRE = giantRE[:-1] + ')'
giantRE = re.compile(giantRE, re.IGNORECASE)
#start recursing the directories
recurser = Recurser(fileQueue,rootDir)
recurser.start()
print "starting scanner"
#start checking the files
for scanner in xrange(0,8):
scanner = Scanner(fileQueue, giantRE)
scanner.start()
This is obviously debugging\ugly code, do not mind the million queue.put(-1), I will clean this up later. Some indentations are not showing up properly, paticularly in scanFile.
Anyway some things I've noticed. Using 1, 4, and even 8 threads (for scanner in xrange(0,???):) does not make a difference. I still get ~72 seconds regardless. I assume this is due to python's GIL.
As opposed to making a giant regex I tried placing each line (pattern) as a compilex RE in a list and iterating through this list in my scanfile function. This resulted in longer execution time.
In an effort to avoid python's GIL I tried having each thread fork to grep as in:
#HELPER FUNCTION FOR INTERNAL UES ONLY
def scanFile(self, file):
s = subprocess.Popen(("grep", "-El", "--file=/root/patterns", file), stdout = subprocess.PIPE)
output = s.communicate()[0]
if output != '':
print 'Matchfound in ' + file
This resulted in longer execution time.
Any suggestions on improving performance.
:::::::::::::EDIT::::::::
I can not post answers to my own questions yet however here are the answers to several points raised:
@David Nehme - Just to let people know I am aware of the fact that I have a million queue.put(-1)'s
@Blender - To mark the bottom of the queue. My scanner threads keep dequeing until they hit -1 which is at the bottom (while nextFile is not -1:). The processor cores is 8 however due to the GIL using 1 thread, 4 threads, or 8 threads does NOT make a difference. Spawning 8 subprocesses resulted in significantly slower code (142 sec vs 72)
@ed - Yes that and it's just as slow as the find\grep combo, actually slower because it indiscriminately greps file that aren't needed
@Ron - Can't upgrade, this must be universal. Do you think this will speed up > 72 seconds? The bash grepper does 358 seconds. My python giant RE method does 72 seconds w\ 1-8 threads. The popen method w\ 8 thrads (8 subprocesses) ran at 142 seconds. So far the giant RE python only method is a clear winner by far
@intuted
Here's the meat of our current find\grep combo (Not my script). It's pretty simple. There are some additional things in there like ls, but nothing that should result in a 5x slowdown. Even if grep -r is slightly more efficient 5x is a HUGE slowdown.
find "${TARGET}" -type f -size "${SZLIMIT}" -exec grep -Eaq --file="${HOME}/patterns" "{}" \; -and -ls | tee -a "${HOME}/found.txt"
The python code is more efficient, I don't know why, but I experimentally tested it. I prefer to do this in python. I already achieved a speedup of 5x with python, I would like to get it sped up more.
:::::::::::::WINNER WINNER WINNER:::::::::::::::::
Looks like we have a winner.
intued's shell script comes in 2nd place with 34 seconds however @steveha's came in first with 24 seconds. Due to the fact that a lot of our boxes do not have python2.6 I had to cx_freeze it. I can write a shell script wrapper to wget a tar and unpack it. I do like intued's for simplicity however.
Thanks you for all your help guys, I now have an efficient tool for sysadmining
A: I'm a bit confused as to how your Python script ended up being faster than your find/grep combo. If you want to use grep in a way somewhat similar to what's suggested by Ron Smith in his answer, you can do something like
find -type f | xargs -d \\n -P 8 -n 100 grep --file=/root/patterns
to launch grep processes which will process 100 files before exiting, keeping up to 8 such processes active at any one time. Having them process 100 files should make the process startup overhead time of each one negligible.
note: The -d \\n option to xargs is a GNU extension which won't work on all POSIX-ish systems. It specifies that the *d*elimiter between filenames is a newline. Although technically filenames can contain newlines, in practice nobody does this and keeps their jobs. For compatibility with non-GNU xargs you need to add the -print0 option to find and use -0 instead of -d \\n with xargs. This will arrange for the null byte \0 (hex 0x00) to be used as the delimiter both by find and xargs.
You could also take the approach of first counting the number of files to be grepped
NUMFILES="$(find -type f | wc -l)";
and then using that number to get an even split among the 8 processes (assuming bash as shell)
find -type f | xargs -d \\n -P 8 -n $(($NUMFILES / 8 + 1)) grep --file=/root/patterns
I think this might work better because the disk I/O of find won't be interfering with the disk I/O of the various greps. I suppose it depends in part on how large the files are, and whether they are stored contiguously — with small files, the disk will be seeking a lot anyway, so it won't matter as much. Note also that, especially if you have a decent amount of RAM, subsequent runs of such a command will be faster because some of the files will be saved in your memory cache.
Of course, you can parameterize the 8 to make it easier to experiment with different numbers of concurrent processes.
As ed. mentions in the comments, it's quite possible that the performance of this approach will still be less impressive than that of a single-process grep -r. I guess it depends on the relative speed of your disk [array], the number of processors in your system, etc.
A: I think that, rather than using the threading module, you should be using the multiprocessing module for your Python solution. Python threads can run afoul of the GIL; the GIL is not a problem if you simply have multiple Python processes going.
I think that for what you are doing a pool of worker processes is just what you want. By default, the pool will default to one process for each core in your system processor. Just call the .map() method with a list of filenames to check and the function that does the checking.
http://docs.python.org/library/multiprocessing.html
If this is not faster than your threading implementation, then I don't think the GIL is your problem.
EDIT: Okay, I'm adding a working Python program. This uses a pool of worker processes to open each file and search for the pattern in each. When a worker finds a filename that matches, it simply prints it (to standard output) so you can redirect the output of this script into a file and you have your list of files.
EDIT: I think this is a slightly easier to read version, easier to understand.
I timed this, searching through the files in /usr/include on my computer. It completes the search in about half a second. Using find piped through xargs to run as few grep processes as possible, it takes about 0.05 seconds, about a 10x speedup. But I hate the baroque weird language you must use to get find to work properly, and I like the Python version. And perhaps on really big directories the disparity would be smaller, as part of the half-second for Python must have been startup time. And maybe half a second is fast enough for most purposes!
import multiprocessing as mp
import os
import re
import sys
from stat import S_ISREG
# uncomment these if you really want a hard-coded $HOME/patterns file
#home = os.environ.get('HOME')
#patterns_file = os.path.join(home, 'patterns')
target = sys.argv[1]
size_limit = int(sys.argv[2])
assert size_limit >= 0
patterns_file = sys.argv[3]
# build s_pat as string like: (?:foo|bar|baz)
# This will match any of the sub-patterns foo, bar, or baz
# but the '?:' means Python won't bother to build a "match group".
with open(patterns_file) as f:
s_pat = r'(?:{})'.format('|'.join(line.strip() for line in f))
# pre-compile pattern for speed
pat = re.compile(s_pat)
def walk_files(topdir):
"""yield up full pathname for each file in tree under topdir"""
for dirpath, dirnames, filenames in os.walk(topdir):
for fname in filenames:
pathname = os.path.join(dirpath, fname)
yield pathname
def files_to_search(topdir):
"""yield up full pathname for only files we want to search"""
for fname in walk_files(topdir):
try:
# if it is a regular file and big enough, we want to search it
sr = os.stat(fname)
if S_ISREG(sr.st_mode) and sr.st_size >= size_limit:
yield fname
except OSError:
pass
def worker_search_fn(fname):
with open(fname, 'rt') as f:
# read one line at a time from file
for line in f:
if re.search(pat, line):
# found a match! print filename to stdout
print(fname)
# stop reading file; just return
return
mp.Pool().map(worker_search_fn, files_to_search(target))
A: If you are willing to upgrade to version 3.2 or better, you can take advantage of the concurrent.futures.ProcessPoolExecutor. I think it will improve performance over the popen method you attempted because it will pre-create a pool of processes where your popen method creates a new process every time. You could write your own code to do the same thing for an earlier version if you can't move to 3.2 for some reason.
A: Let me also show you how to do this in Ray, which is an open-source framework for writing parallel Python applications. The advantage of this approach is that it is fast, easy to write and extend (say you want to pass a lot of data between the tasks or do some stateful accumulation), and can also be run on a cluster or the cloud without modifications. It's also very efficient at utilizing all cores on a single machine (even for very large machines like 100 cores) and data transfer between tasks.
import os
import ray
import re
ray.init()
patterns_file = os.path.expanduser("~/patterns")
topdir = os.path.expanduser("~/folder")
with open(patterns_file) as f:
s_pat = r'(?:{})'.format('|'.join(line.strip() for line in f))
regex = re.compile(s_pat)
@ray.remote
def match(pattern, fname):
results = []
with open(fname, 'rt') as f:
for line in f:
if re.search(pattern, line):
results.append(fname)
return results
results = []
for dirpath, dirnames, filenames in os.walk(topdir):
for fname in filenames:
pathname = os.path.join(dirpath, fname)
results.append(match.remote(regex, pathname))
print("matched files", ray.get(results))
More information including how to run this on a cluster or the cloud is available in the documentatation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Warning trying to get a string from an array ,iOS My program works OK, but I get this warning when compiling:
format not a string literal and no format arguments
RomanosBasicos is an array of Strings:
RomanosBasicos=[[NSArray alloc] initWithObjects:@"M",@"CM",@"D",@"CD",@"C",@"XC",@"L",@"XL",@"X",@"IX",@"V",@"IV",@"I" , nil];
and I get the warning in this line:
temp = [temp stringByAppendingFormat:[RomanosBasicos objectAtIndex:i]];
Thanks for your help!.
A: instead of
temp = [temp stringByAppendingFormat:[RomanosBasicos objectAtIndex:i]];
use
temp = [temp stringByAppendingString:[RomanosBasicos objectAtIndex:i]];
But if you want to use stringByAooendingFormat: then you have to do this
temp = [temp stringByAppendingFormat:@"%@", [RomanosBasicos objectAtIndex:i]];
I think you get it now what that warning means.
A: You mean [temp stringByAppendingString:[RomanosBasicos objectAtIndex:i]]; instead?
A: stringByAppendingFormat: is expecting an Formatted NSString with arguments. It seems from your program that you actually want stringByAppendingString: like so:
temp = [temp stringByAppendingString:[RomanosBasicos objectAtIndex:i]];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Attempting to install gearmand on AWS Linux EC2, yum can't find necessary packages with default repos I'm attempting to install gearmand on a micro EC2 instance running Amazon Linux 64 bit by following this guide: http://planet.mysql.com/entry/?id=28654
But I'm running into a problem with
sudo yum install -y libevent-devel.i386
I get the following output:
Loaded plugins: fastestmirror, priorities, security, update-motd
Loading mirror speeds from cached hostfile
* amzn-main: packages.eu-west-1.amazonaws.com
* amzn-updates: packages.eu-west-1.amazonaws.com
amzn-main | 2.1 kB 00:00
amzn-updates | 2.1 kB 00:00
Setting up Install Process
No package libevent-devel.i386 available.
Error: Nothing to do
Is there a repository I should add to yum to install these packages? And if so, how do I add a repository to yum?
A: shouldn't it be libevent-devel.x86_64?
and you can install with
sudo yum install -y libevent-devel
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Simple Java Scanner issue I haven't been doing Java long. In this script where it says Thread.sleep(10000); you can still type (I use eclipse) I really don't know why it enables you to type in the output when I have no uno.nextLine(); before or after the 10 second waiting. Please help! Thanks
import java.util.Scanner;
class Tutoiral{
public static void main (String args[])throws InterruptedException {
Scanner uno = new Scanner(System.in);
Scanner uno1 = new Scanner(System.in);
System.out.println("What's your name?");
String name = uno.nextLine();
System.out.println("Hi, " + name + ". Feel free to type whatever you want :) BUT DON'T SPAM!!!!!");
String typed = (": ") + uno1.nextLine();
System.out.println(name + typed + " (5 types remaining)");
uno.nextLine();
System.out.println(name + typed + " (4 types remaining)");
uno.nextLine();
System.out.println(name + typed + " (3 types remaining)");
uno.nextLine();
System.out.println(name + typed + " (2 types remaining)");
uno.nextLine();
System.out.println(name + typed + " (1 type remaining)");
uno.nextLine();
System.out.println(name + typed + " (If you type one more time, then I'll... I'll block you! Ha!)");
uno.nextLine();
System.out.println(name + typed + " (tut tut tut. You have been blocked for a while for spam. Don't type EVER again ok?)");
Thread.sleep(10000);
System.out.println("Ok, you can type again. But I wouldn't If I were you.");
A:
I really don't know why it enables you to type in the output when I have no uno.nextLine();
The call to nextLine will read (and return) characters from standard input. The console will print the characters entered by the user, regardless if you read them or not.
Unfortunately (for you) it's not possible to prevent the user from entering data on standard input.
One workaround would perhaps be to disable "local echo", i.e. avoid printing the characters entered by the user. I'm not sure how to do this. A nasty approach would be to do System.console().readPassword().
Playing around with it, I came up with the following super-nasty hack workaround (Beware that Thread.stop() for instance, is deprecated for good reasons.):
public static void turnOffLocalEcho(long ms) {
Thread t = new Thread() {
public void run() {
while (true) { System.console().readPassword(); }
}
};
t.start();
try {
Thread.sleep(ms);
} catch (InterruptedException ie) {
}
t.stop();
}
Just replace your call to Thread.sleep(10000) with a call to this method:
turnOffLocalEcho(10000);
A: uno will process the input typed whenever (while sleeping, working, or waiting for input) when one of its nextSomething() methods is called. you need not call nextSomething() and parse the input, but the user can enter it either way.
A: Console input (and hence Scanner) does not work the way one might think.
A console program has an input stream called standard input, or stdin. You can think of this as a queue of characters for the program to read.
When you type a character into a console program, it normally has 2 effects:
*
*The terminal immediately prints the character to the screen.
*The character is appended to the program's standard input. (Technically this only happens each time you type a newline (Enter).)
These actions are performed by the OS, so they work regardless of whether your program is currently reading data from stdin. If the program is waiting for data, it will immediately process it (ignoring input stream buffering). But if not (e.g. it is processing something else, or in your case sleeping for 10 seconds), the character just sits in the queue until the program reads it.
Scanner does not actually prompt the user for a line of text. How it works: When a program tries to read from stdin, if there is no data available the program blocks until the OS feeds it enough data. Scanner.nextLine() reads characters from stdin until a newline has been read, at which point it returns the characters entered since the last newline. This means that typically, Scanner.nextLine() will cause the program to wait until the user presses Enter.
However, note that if you input more than one line of text at once, e.g. by pasting several lines into the terminal, or by shell pipes or redirection (such as with java MyProgram < file.txt), the program will keep running until it has eaten all of the input.
While your program is sleeping, the user can still type and append to your program's stdin! (Try adding a few copies of System.out.println(name + typed + uno.nextLine()); at the end of your program, and see what happens when you type while your program is sleeping.)
Therefore, to prevent the user from typing stuff that your main program will read, you need to do 2 things while your main thread sleeps:
*
*Tell the console to stop echoing characters typed to the console.
*Read any characters fed to stdin, and discard them.
You can do both of these by calling System.console().readPassword() in another thread (and discarding its output). That way, after 10 seconds your main thread will wake up and kill the password-reading thread. But by then, anything the user typed while the main thread was sleeping will already have been read (removed from stdin) and discarded by the other thread, so in effect the user has been unable to type on the console. (See aioobe's answer for code of this.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP Convert number to currency I've had a good look around for any help with my problem so hopefully someone can help me here.
Basically i have a number which is saved into a $price, the number is 15900. Which should translate to 159.00.
Does anyone know how to do this?
A: Use number_format for this. It will return a string, thereby keeping the decimal places intact, even if they will be .00.
$price = 15900;
// Defaults to a comma as a thousands separator
// but I've set it to an empty string (last argument)
$formatted = number_format( $price / 100, 2, '.', '' );
echo $formatted;
Or better still, maybe have a look at money_format as well, depending on whether internationalized notations and/or currency symbols are of importance as well.
A: $current = 15900;
$your = round($current / 100, 2);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google analytics track search with Codeigniter I have a Codeigniter app and i want to track the search with Google Analytics.
The thing is: GA asks for a parameter and my URL is something like: http://domain.com/search/searchterm.
No query strings, just clean URL's.
How can i do it ?
Thanks.
A: Short of changing your CodeIgniter app to only use query strings for the search app, the only way for you to utilize Google Analytics Site Search without changing your URL patterns is to create a new duplicate profile in Google Analytics, and create a filter that turns your URL into one with a query string of the search term.
That involves creating an "advanced" Filter, and doing something like this (Note! This is untested. I recommend doing this on a DUPLICATE profile, so you don't disturb your central data irrevocably, and tweaking it to ensure it gives you the results you want).
I just implemented this on a site of mine with a similar URL structure, and it seems to be working.
EDIT: Another alternative, which is slightly more obtrusive, is to send a custom pageview value in your Google Analytics snippet on search results pages, to fake a query string in the case of a search term:
Something like (again, this is hack-y):
var search = location.pathname.match(/^\/search\/[^$]/) ? ("/search/" + ((location.search) ? location.search+"&":"?") + "q=" + location.pathname.split("/")[2].split("?")[0] ): null;
_gaq.push("_trackPageview", search);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: BitmapFactory.decodeFile(); In my application, I have a file:
private File TEMP_PHOTO_FILE = new File(Environment.getExternalStorageDirectory(), "temp_photo.jpg");
This is declared directly in my class, and is visible to all the methods there in.
I want to use this:
Bitmap thePhoto = BitmapFactory.decodeFile(Uri.fromFile(TEMP_PHOTO_FILE).toString());
Uri.fromFile(TEMP_PHOTO_FILE).toString() generates the string: "file:///mnt/sdcard/temp_photo.jpg"
Why does this not work? It seems that since we're dealing with a file, there should be some method of decodeFile() that accepts a URI as input. Not allowing that is very frustrating due to the inconsistency.
A: "file://" doesn't work. Try this:
Bitmap thePhoto = BitmapFactory.decodeFile(TEMP_PHOTO_FILE.getAbsolutePath().toString());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Passing Values Back and Forth from Browser to Controller Using JSON I found a workaround for errors parsing JSON strings sent from (Firefox) browser using JSON.parse() in my controller, but isn't there a better solution?
rails 2.3.12
json (1.6.1)
View --> Controller
views/theme_maps/edit.html.erb:
(javascript)
var labels = ["4", "5"];
document.getElementById("labels").value = JSON.stringify(labels);
(html)
<% form_for(@theme_map}) do |f| %>
<input type="hidden" id='labels' name='labels' />
<%= f.submit 'Update' %>
<% end %>
theme_maps_controller#update:
(ruby)
labels = params[:labels] # get it from the hidden field
the problem, and my hack solution, is here:
# labels.inspect returns: "\"[\\\"4\\\", \\\"5\\\"]\""
# JSON.parse(labels) throws an exception.
labels.gsub!('"[', '[') # remove the quotes
labels.gsub!(']"', ']') # around the brackets.
labels.gsub!('\\', '') # remove the escaped backslash.
# now labels.inspect returns: "[\"4\", \"5\"]"
labels_array = JSON.parse(labels)
# now it's happy.
Controller --> View
Just to round things out, and because it took me ages to figure this out:
theme_maps_controller#edit:
(ruby)
label_list = ["1", "2","3"]
@json_labels = label_list.to_json
views/theme_maps/edit.html.erb:
(javascript)
var exist_labels = <%= @json_labels %>;
A: It looks like the goal is to receive, on the server, something like this:
params[:labels] # ["1", "4", "5"]
Honestly, you should pick one mime-type here and stick with it. If you're willing to post with actual JSON data (say, via an AJAX call), then your submitted data will work with no server-side changes and would look like this:
{labels: ["1", "4", "5"]}
If you're submitting form data, however, your request should look like this:
labels=1&labels=4&labels=5
Again, that would be interpreted correctly with no server-side changes.
TLDR: Don't try to encode and decode JSON strings stuffed into form fields, it doesn't make much sense on the client or the server.
A: The problem is using JSON.stringify(). What is needed is .toSource().
var labels = ["4", "5"];
// document.getElementById("labels").value = JSON.stringify(labels);
document.getElementById("labels").value = labels.toSource();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IRC client - No reply on JOIN I am writing a IRC client in C++ (with the help of the SFML library), but it is behaving strangely. I send the NICK and USER commands and I can connect to the server, but the JOIN command has many strange thing happening that I have to write "Random code that magically works" to solve. I am pretty sure that the commands adhere to the IRC RFC as well.
I know that the sockets are sending what they are supposed to send and I have verified it with Wireshark, so what I post here is what the message of the packet is. In the following examples the socket is already connected to the IRC server (which in this case is irc.freenode.net)
This works:
char mess[] ="NICK lmno \n\rUSER lmno 0 * :lmno\n\rJOIN #mytest\n\r";
Socket.Send(mess, sizeof(mess));
This does not:
char msg[] = "NICK lmno \r\nUSER lmno 0 * :lmno \r\n";
char msga[] = "JOIN #mytest \r\n";
Socket.Send(msg, sizeof(msg));
Socket.Send(msga, sizeof(msga));
But curiously this works:
char msg[] = "NICK lmno \r\nUSER lmno 0 * :lmno \r\n";
char msga[] = "JOIN #mytest \r\n";
Socket.Send(msg, sizeof(msg));
Socket.Send(msga, sizeof(msga));
Socket.Send(msga, sizeof(msga));
I did do some research on this topic and no one seems to have the same problem. Stranger is that when I tried this in telnet, I only have to send JOIN once.
Is anyone able to give me some advice?
Thanks,
SFI
A: It might have to do with the terminating '\0' character at the end of a c-string. Try
Socket.Send(msg, sizeof(msg) - 1);
Socket.Send(msga, sizeof(msga) - 1);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Rails3 / Rails2 - Routing issue Today I tried to follow the basic "Twitter" tutorial on :
--> http://www.noupe.com/ajax/create-a-simple-twitter-app.html
But in the midle of the tutorial I have an issue.
It says that you should edit /config/routes.rb and add this piece of code :
ActionController::Routing::Routes.draw do |map|
map.resources :posts
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
It was written a while ago so there are probably incompatibilities with rails3 especially with the new routing synthax.
So I tried to fix changing it in :
Standart::Application.routes.draw do |map|
resources :posts
match ':controller/:action/:id'
match ':controller/:action/:id.:format'
end
Where "Standart" the name of the application is.
A: You need a root route:
resources :posts
root :to => 'posts#index'
You should try to avoid those catch-all routes that Rails 2 used. If you need other routes, try to see what fits into resourceful routes and use those, and create specific routes with the Rails 3 DSL for anything that doesn't fit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: grails when does ID get assigned? I'm doing myDomainObject.save(flush: true) and then attempting to read the id assigned to myDomainObject in the next statement, and I get a value of "null".
My application needs to use this id as an invoice # (to send out via a service) as soon as I can get the new id.
My question is, what do I need to do to get the assigned ID value as easily/efficiently as possible?
Thanks
A: It should be there as soon as the save completes. In fact in unit and integration tests its a good idea to assert that the id is not null as a simple test that the persistence operation was successful. Are you sure the save is successful?
Check out http://www.grails.org/doc/latest/ref/Domain%20Classes/save.html
for how to determine errors. Specifically the part with
if( !b.save() ) {
b.errors.each {
println it
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP Mail Function with Multiple Table Query I'm working on a script that allows visitors to enter their email address to receive a notification upon a photo upload by other users. For testing purposes, I used this code to query just my "email" table, and it works perfectly when a new photo is uploaded:
$data = mysql_query("SELECT email
FROM email");
if(! $data )
{
die('Could not get data: ' . mysql_error());
}
if($info = mysql_fetch_array($data, MYSQL_ASSOC))
$email=$info['email'];
{
mail($email, 'Test Email', $message);
However, the necessary query will involve 2 tables (to compare info that was tagged during photo upload to info that was provided by the user wishing to receive the email). However, when I use the following query, no email is sent.
$data = mysql_query("SELECT person.event, person.name, email.event, email.name, email.email
FROM person, email
WHERE '$event' = email.event and '$name' = email.name");
if(! $data )
{
die('Could not get data: ' . mysql_error());
}
if($info = mysql_fetch_array($data, MYSQL_ASSOC))
$email=$info['email.email'];
{
mail($email, 'Test Message', $message);
I'm pretty new to php, so I suspect that I'm missing something obvious. I'd appreciate any corrections. Thanks.
A: Assuming that your query is correct, and fetchs the data you need, a problem I found is that you're getting an email.email member from the mysql result array, and you should only get
$email=$info['email'];
there is no table namespace into the mysql results... so if you have to ask for two fields with the same name you have to use an AS clause, and rename one of them.
In addition, you could use the "print_r" php function to output the array fetched and debug your code.
A: Your problem is that you are doing a cross join on two tables.
SELECT person.event, person.name, email.event, email.name, email.email
FROM person, email //Implicit join syntax is evil.
WHERE '$event' = email.event and '$name' = email.name
Never use implicit SQL '89 join syntax, It's an anti-pattern.
Use explicit join syntax instead.
Change the query to:
$event = mysql_real_escape_string($event);
$name = mysql_real_escape_string($name);
$sql = "SELECT p.event, p.name, e.event, e.name, e.email
FROM person p
INNER JOIN email e ON (e.person_id = p.id)
WHERE e.event = '$event' AND e.name = '$name' ";
You might need to tweak the join criterion to match on the relevant fields.
e.g. if you have emailaddress as the PK for person, you'd need:
INNER JOIN email e ON (e.emailaddress = p.emailaddress)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: rails including javascript or files only on certain pages Ok Im new to rails in general and these default loaders and cache loaders an all that stuff they make some sense to me. But my question is. If I want to include a certain JS file or 2 or specific script on a particular page how would I do that.
with rails I have
app/views/layouts/application.html.erb in this file I gather is the base template for my site/service, and in there I would put all the moving parts. However I have an occasional need where I only need a javascript file loaded on a particular page. But it needs to be called after the jquery file so jquery is loaded into memory prior to the file I want loaded. So Im not exactly sure how I would approach that. Cause in the layout I have the javascript loader line whatever it is exactly I dont remember but its :default none the less which means jquery and applications will load out by default from what the API tells me.
Which does bring me to another question the guy who initially set up the rails server we have added a file to the defaults I would like to mimic that but don't know how with that either.
A: content_for might help you, look at the example that includes the piece of code: <%= yield :script %>
Alternatively, think about ways to allow the JS code to detect if it is begin executed on the correct page (maybe a class or id set on the body tag), and only execute if that condition is met. Then you can serve your entire javascript collection compressed and minified to the user's browser on the first page load, increasing site performance.
A: The simplest way would be to just include the script file in the view where you need it. jQuery will have already been loaded in the layout.
Alternatively, you can use content_for, as ctcherry mentions. You can find a more detailed explanation here: Javascript Include Tag Best Practice in a Rails Application
Also, regarding you last question, I'm not sure I understand it correctly, but you can add more options to the javascript_include_tag separated by a comma:
javascript_include_tag :defaults, "my_other_file", "etc"
A:
May be used for this:
<head>
<title>My blog</title>
<%= yield(:head) -%>
</head>
And send it there from a view:
<%- content_for(:head) do -%>
<%= javascript_include_tag :defaults -%>
<%- end -%>
It's good work!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it possible to bypass sorting of localdata when using grouping in jqgrid? I have client-side data (local data) always sorted, and I don't want jqgrid to re-sort the data for grouping (like server-side sorted data behaviour-- groupDataSorted = true).
Is it possible to bypass/disable sorting of data before grouping in jqGrid? In other words, are there any way to use groupDataSorted = true, for editurl= "clientArray"?
datatype: 'local',
data: mydata,
rowNum: 10,
rowList: [10, 20,30,40],
pager: '#pager',
gridview: true,
sortname: 'invdate',
viewrecords: true,
grouping: true,
groupingView: {
groupField: ['name'],
groupSummary: [true],
groupColumnShow: false,
groupText: ['<b>{0}-{1} items</b>'],
},
editurl: 'clientArray'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a way to do an Ajax Post to an ASPX page that doesn't call a static function? The question says it all. I am having no trouble making Ajax calls into my ASPX page - as long as I use static methods. However, I'd like to store a result in the session and so need a "live" function call. Any ideas?
A: Post to a Generic Http handler (.ashx) and have it inherit from IRequireSession interface. Then you can save to session.
A: I have done quite a bit of research on this problem and, while @latr0dectus' answer may work, I am looking to implement quite a few calls back to the application from within the page. Perhaps I needed to do more research but I did not find a way to call multiple methods within the Generic Http handler nor a way to pass in complex arguments. So, this didn't work very well for me.
A much easier solution is just to use a a WebService and to use the [WebMethod(EnableSession = true)] attribute.
A complete example of a Session-aware web service that you can reach from Ajax is:
using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Web.SessionState;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class SCMasterService : System.Web.Services.WebService {
public SCMasterService () {
}
[WebMethod(EnableSession = true)]
public string GetSummaryList(string ID)
{
return Session["SomeVal"];
}
}
To call this from a Javascript/JQuery/Ajax "Post" you will need two key lines:
[System.Web.Script.Services.ScriptService]
Makes this web service available to Ajax and
[WebMethod(EnableSession = true)]
enables session management in the called method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Conversion/Casting between two pointers Lately I've been doing a lot of exercises with file streams. When I use fstream.write(...)
to e.g. write an array of 10 integers (intArr[10]) I write:
fstream.write((char*)intArr,sizeof(int)*10);
Is the (char*)intArr-cast safe? I didn't have any problems with it until now but I learned about static_cast (the c++ way right?) and used static_cast<char*>(intArr) and it failed! Which I cannot understand ... Should I change my methodology?
A: A static cast simply isn't the right thing. You can only perform a static cast when the types in question are naturally convertible. However, unrelated pointer types are not implicitly convertible; i.e. T* is not convertible to or from U* in general. What you are really doing is a reinterpreting cast:
int intArr[10];
myfile.write(reinterpret_cast<const char *>(intArr), sizeof(int) * 10);
In C++, the C-style cast (char *) becomes the most appropriate sort of conversion available, the weakest of which is the reinterpreting cast. The benefit of using the explicit C++-style casts is that you demonstrate that you understand the sort of conversion that you want. (Also, there's no C-equivalent to a const_cast.)
Maybe it's instructive to note the differences:
float q = 1.5;
uint32_t n = static_cast<uint32_t>(q); // == 1, type conversion
uint32_t m1 = reinterpret_cast<uint32_t>(q); // undefined behaviour, but check it out
uint32_t m2 = *reinterpret_cast<const uint32_t *>(&q); // equally bad
Off-topic: The correct way of writing the last line is a bit more involved, but uses copious amounts of casting:
uint32_t m;
char * const pm = reinterpret_cast<char *>(&m);
const char * const pq = reinterpret_cast<const char *>(&q);
std::copy(pq, pq + sizeof(float), pm);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: AFNetworking Post Request I'm a newbie in obj-c and have been using asihttp for some of my projects. When doing a post request in asihttp its done this way.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:height forKey:@"user[height]"];
[request setPostValue:weight forKey:@"user[weight]"];
[request setDelegate:self];
[request startAsynchronous];
How would go about doing this is AFNetworking with a code example ?
I already got the get Json getrequest working in AFNetworking but this post request is giving me some problems. Thanks for help in advance.
A: NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
height, @"user[height]",
weight, @"user[weight]",
nil];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:
[NSURL URLWithString:@"http://localhost:8080/"]];
[client postPath:@"/mypage.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *text = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"Response: %@", text);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@", [error localizedDescription]);
}];
A: For AFNetworking 4
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"user[height]": height,
@"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params headers:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
A: It's first worth adding (as this answer is still popular 6 years after I initially wrote it...) that the first thing you should consider is whether you should even use AFNetworking. NSURLSession was added in iOS 7 and means you don't need to use AFNetworking in many cases - and one less third party library is always a good thing.
For AFNetworking 3.0:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"user[height]": height,
@"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
For AFNetworking 2.0 (and also using the new NSDictionary syntax):
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = @{@"user[height]": height,
@"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
If you are stuck using AFNetworking 1.0, you need to do it this way:
NSURL *url = [NSURL URLWithString:@"https://example.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
height, @"user[height]",
weight, @"user[weight]",
nil];
[httpClient postPath:@"/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"Request Successful, response '%@'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
}];
A: AFHTTPClient * Client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://urlname"]];
NSDictionary * parameters = [[NSMutableDictionary alloc] init];
parameters = [NSDictionary dictionaryWithObjectsAndKeys:
height, @"user[height]",
weight, @"user[weight]",
nil];
[Client setParameterEncoding:AFJSONParameterEncoding];
[Client postPath:@"users/login.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"operation hasAcceptableStatusCode: %d", [operation.response statusCode]);
NSLog(@"response string: %@ ", operation.responseString);
NSDictionary *jsonResponseDict = [operation.responseString JSONValue];
if ([[jsonResponseDict objectForKey:@"responseBody"] isKindOfClass:[NSMutableDictionary class]]) {
NSMutableDictionary *responseBody = [jsonResponseDict objectForKey:@"responseBody"];
//get the response here
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error: %@", operation.responseString);
NSLog(@"%d",operation.response.statusCode);
}];
Hope this works.
A: Here is a simple AFNetworking POST I'm using. To get up and running after
reading the AFNetworking doc, wkiki, ref, etc, I learned a lot by
following http://nsscreencast.com/episodes/6-afnetworking and understanding
the associated code sample on github.
// Add this to the class you're working with - (id)init {}
_netInst = [MyApiClient sharedAFNetworkInstance];
// build the dictionary that AFNetworkng converts to a json object on the next line
// params = {"user":{"email":emailAddress,"password":password}};
NSDictionary *parameters =[NSDictionary dictionaryWithObjectsAndKeys:
userName, @"email", password, @"password", nil];
NSDictionary *params =[NSDictionary dictionaryWithObjectsAndKeys:
parameters, @"user", nil];
[_netInst postPath: @"users/login.json" parameters:params
success:^(AFHTTPRequestOperation *operation, id jsonResponse) {
NSLog (@"SUCCESS");
// jsonResponse = {"user":{"accessId":1234,"securityKey":"abc123"}};
_accessId = [jsonResponse valueForKeyPath:@"user.accessid"];
_securityKey = [jsonResponse valueForKeyPath:@"user.securitykey"];
return SUCCESS;
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"FAILED");
// handle failure
return error;
}
];
A: Here an example with Swift 3.0
let manager = AFHTTPSessionManager(sessionConfiguration: URLSessionConfiguration.default)
manager.requestSerializer = AFJSONRequestSerializer()
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type")
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept")
if authenticated {
if let user = UserDAO.currentUser() {
manager.requestSerializer.setValue("Authorization", forHTTPHeaderField: user.headerForAuthentication())
}
}
manager.post(url, parameters: parameters, progress: nil, success: { (task: URLSessionDataTask, responseObject: Any?) in
if var jsonResponse = responseObject as? [String: AnyObject] {
// here read response
}
}) { (task: URLSessionDataTask?, error: Error) in
print("POST fails with error \(error)")
}
A: [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
[SVProgressHUD show];
NSDictionary *dictParam =@{@"user_id":@"31"};// Add perameter
NSString *URLString =@"your url string";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:@"Authorization"];//strGlobalLoginToken is your login token
// [manager.requestSerializer setValue:setHeaderEnv forHTTPHeaderField:@"Env"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/rss+xml", nil];
[manager POST:URLString parameters:dictParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
NSLog(@"Response DICT:%@",response);
if ([[[[response objectForKey:@"response"] objectAtIndex:0] objectForKey:@"status"] isEqualToString:@"true"])
{
for (NSMutableDictionary *dicAll in [[[response objectForKey:@"response"]objectAtIndex:0]objectForKey:@"plans"])
{
[yourNsmutableArray addObject:[dicAll mutableCopy]];
}
//yourNsmutableArray Nsmutablearray alloction in view didload
NSLog(@"yourNsmutableArray %@",yourNsmutableArray);
}
else
{
NSLog(@"False");
}
[SVProgressHUD dismiss];
} failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error)
{
NSLog(@"RESPONSE STRING:%@",task.response);
NSLog(@"error userInfo:%@",error.userInfo);
NSString *errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
NSLog(@"URLString :--->> %@ Error********* %@",URLString,errResponse);
[SVProgressHUD dismiss];
}];
A: For AFNetworking 3.0 and Swift. Maybe we can use like this:
let configutation = NSURLSessionConfiguration.defaultSessionConfiguration()
manager = AFHTTPSessionManager(sessionConfiguration: configutation)
let urlString = "url"
manager.POST(urlString, parameters: [params here], progress: nil, success: { (dataTask: NSURLSessionDataTask, response: AnyObject?) -> Void in
print(dataTask)
print(response)
}) { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
print(error)
}
Hope this will help other find answer like me!
A: For AFNetworking 3.0 (iOS9 or greter)
NSString *strURL = @"https://exampleWeb.com/webserviceOBJ";
NSDictionary *dictParamiters = @{@"user[height]": height,@"user[weight]": weight};
NSString *aStrParams = [self getFormDataStringWithDictParams:dictParamiters];
NSData *aData = [aStrParams dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *aRequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:strURL]];
[aRequest setHTTPMethod:@"POST"];
[aRequest setHTTPBody:aData];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
[aRequest setHTTPBody:aData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:aRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//
if (error ==nil) {
NSString *aStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"ResponseString:%@",aStr);
NSMutableDictionary *aMutDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(aMutDict);
NSLog(@"responce:%@",aMutDict)
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"error:%@",error.locali)
});
}
}];
[postDataTask resume];
and Add
-(NSString *)getFormDataStringWithDictParams:(NSDictionary *)aDict
{
NSMutableString *aMutStr = [[NSMutableString alloc]initWithString:@""];
for (NSString *aKey in aDict.allKeys) {
[aMutStr appendFormat:@"%@=%@&",aKey,aDict[aKey]];
}
NSString *aStrParam;
if (aMutStr.length>2) {
aStrParam = [aMutStr substringWithRange:NSMakeRange(0, aMutStr.length-1)];
}
else
aStrParam = @"";
return aStrParam;
}
A: NSURL *URL = [NSURL URLWithString:@"url"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"prefix":@"param",@"prefix":@"param",@"prefix":@"param"};
[manager POST:URL.absoluteString parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
self.arrayFromPost = [responseObject objectForKey:@"data"];
// values in foreach loop
NSLog(@"POst send: %@",_arrayFromPost);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
A: NSMutableDictionary *dictParam = [NSMutableDictionary dictionary];
[dictParam setValue:@"VALUE_NAME" forKey:@"KEY_NAME"]; //set parameters like id, name, date, product_name etc
if ([[AppDelegate instance] checkInternetConnection]) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictParam options:NSJSONWritingPrettyPrinted error:&error];
if (jsonData) {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"Api Url"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30.0f];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:jsonData];
[request setValue:ACCESS_TOKEN forHTTPHeaderField:@"TOKEN"];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
op.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json", nil];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
arrayList = [responseObject valueForKey:@"data"];
[_tblView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//show failure alert
}];
[op start];
}
} else {
[UIAlertView infoAlertWithMessage:NO_INTERNET_AVAIL andTitle:APP_NAME];
}
A: // For Image with parameter /// AFMultipartFormData
NSDictionary *dictParam =@{@"user_id":strGlobalUserId,@"name":[dictParameter objectForKey:@"Name"],@"contact":[dictParameter objectForKey:@"Contact Number"]};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:webServiceUrl]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:@"Authorization"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/rss+xml", nil];
[manager POST:@"update_profile" parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
if (Imagedata.length>0) {
[formData appendPartWithFileData:Imagedata name:@"profile_pic" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
}
} progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
NSLog(@"update_profile %@", responseObject);
if ([[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"status"] isEqualToString:@"true"])
{
[self presentViewController:[global SimpleAlertviewcontroller:@"" Body:[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"response_msg"] handler:^(UIAlertAction *action) {
[self.navigationController popViewControllerAnimated:YES];
}] animated:YES completion:nil];
}
else
{
[self presentViewController:[global SimpleAlertviewcontroller:@"" Body:[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"response_msg"] handler:^(UIAlertAction *action) {
}] animated:YES completion:nil];
}
[SVProgressHUD dismiss];
} failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error)
{
[SVProgressHUD dismiss];
}];
A: please try below answer.
+(void)callAFWSPost:(NSDictionary *)dict withURL:(NSString *)strUrl
withBlock:(dictionary)block
{
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
[manager POST:[NSString stringWithFormat:@"%@/%@",WebserviceUrl,strUrl] parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
if (!responseObject)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:ServerResponceError forKey:@"error"];
block(responseObject);
return ;
}
else if ([responseObject isKindOfClass:[NSDictionary class]]) {
block(responseObject);
return ;
}
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:ServerResponceError forKey:@"error"];
block(dict);
}];
}
A: for login screen;
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [NSMutableDictionary
dictionaryWithObjectsAndKeys:_usernametf.text, @"username",_passwordtf.text, @"password", nil];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:@"enter your url" parameters:dict progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"%@", responseObject);
}
failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}
A: Using AFNetworking 3.0, you should write:
NSString *strURL = @"https://exampleWeb.com/webserviceOBJ";
NSURL * urlStr = [NSURL URLWithString:strURL];
NSDictionary *dictParameters = @{@"user[height]": height,@"user[weight]": weight};
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
[manager POST:url.absoluteString parameters:dictParameters success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"PLIST: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "82"
} |
Q: substream from istream Suppose I have an ifstream which represents a large file containing lots of sub-files aggregated together. I want to be able to create a "sub" istream from the larger ifstream (given a size and offest) representing a part of the file so other code can read from that substream as if it was an independent istream.
Any ideas on how I might accomplish this?
EDIT
- I would prefer to avoid boost.
A: This is an example of a streambuf "filter" that reads from a contained streambuf starting at a specified location and reading up to a specified size. You create substreambuf, passing your original streambuf in and substreambuf then translates access so that everything is read from the desired location in the underlying streambuf.
Most of the overhead involved in calling sgetc and snextc from underflow and uflow should optimize away. Many extraction operators work byte by byte, so there should not be additional overhead beyond maintaining the read position within the subsection and checking for the end of the subsection. Of course, reading large chunks of data will be less efficient with this class (although that could be fixed).
This still needs improvements like testing that the requested location is within the underlying streambuf.
class substreambuf : public std::streambuf
{
public:
substreambuf(std::streambuf *sbuf, std::size_t start, std::size_t len) : m_sbuf(sbuf), m_start(start), m_len(len), m_pos(0)
{
std::streampos p = m_sbuf->pubseekpos(start);
assert(p != std::streampos(-1));
setbuf(NULL, 0);
}
protected:
int underflow()
{
if (m_pos + std::streamsize(1) >= m_len)
return traits_type::eof();
return m_sbuf->sgetc();
}
int uflow()
{
if (m_pos + std::streamsize(1) > m_len)
return traits_type::eof();
m_pos += std::streamsize(1);
return m_sbuf->sbumpc();
}
std::streampos seekoff(std::streamoff off, std::ios_base::seekdir way, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out)
{
std::streampos cursor;
if (way == std::ios_base::beg)
cursor = off;
else if (way == std::ios_base::cur)
cursor = m_pos + off;
else if (way == std::ios_base::end)
cursor = m_len - off;
if (cursor < 0 || cursor >= m_len)
return std::streampos(-1);
m_pos = cursor;
if (m_sbuf->pubseekpos(m_start + m_pos, std::ios_base::beg) == std::streampos(-1))
return std::streampos(-1);
return m_pos;
}
std::streampos seekpos(std::streampos sp, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out)
{
if (sp < 0 || sp >= m_len)
return std::streampos(-1);
m_pos = sp;
if (m_sbuf->pubseekpos(m_start + m_pos, std::ios_base::beg) == std::streampos(-1))
return std::streampos(-1);
return m_pos;
}
private:
std::streambuf *m_sbuf;
std::streampos m_start;
std::streamsize m_len;
std::streampos m_pos;
};
It can be used like this
using namespace std;
void somefunc(ifstream &bigifs)
{
substreambuf sbuf(bigifs.rdbuf(),100,100);
//new istream with the substreambuf as its streambuf
istream isub(&sbuf);
//use isub normally
}
This was inspired by Filtering Streambufs
A: I've done something like this using the Boost.Iostreams library. Look under Tutorial|Writing Devices. The idea is to create a "device" class which implements the low-level interface (read/write/seek) and then instantiate an istream/ostream derived class using your device class to do the actual I/O.
A: All iostreams put most of their custom logic in their streambuf specializations. fstream (or basic_fstream) initializes istream with an instance of file_buf. Same for stringstream (stringbuf). If you want to roll your own substream stream, you can do it by implementing your own streambuf in terms of a parent stream.
A: Just a little idea : If you have control over the client side of the code (i.e. the part that uses the input stream), I suggest you modify it to accept two additional parameters, like illustrated below :
// Old code
void ClassUsingInput::SetInput(std::streambuf & inputbuf)
{
// Implementation ...
}
Can become :
// New code
void ClassUsingInput::SetInput(std::streambuf & inputbuf, std::streampos position, std::streamsize size)
{
inputbuf.pubseekpos(position) ;
// internally use size to detect end-of-substream
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Showing branch hierarchy at the command line? I'm curious if there is a way to show branch hierarchy on the command line? For instance if I use git branch, instead of seeing output like this:
* master
joes_work
refactoring
experiment
You see output like this:
* master
joes_work
refactoring
experiment
That way it's easy to see which branch a particular branch.. branched off of. Even if there's no specific command that outputs a tree structure, is there a command that outputs information on which branch came from which branch? I can use a perl script to format the output.
A: That's not how branches work from git's point of view. If I make some commits to branch a, create branch b from it, work there, and then do other work back on a:
A -- B -- D <-- a
\
\
C <-- b
That's indistinguishable if you did it the other way around:
A -- B -- C <-- b
\
\
D <-- a
The only way I can think of to find out from which branch certain branch originated is the reflog, but that's unreliable (entries older than 90 days are usually deleted).
A: I want to complete the answer of @ctcherry.
I like when I can also see the user who did the commit and the date, so this is the following line to use :
git log --all --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
However this is a pretty long line and difficult to memorize so you can use an alias.
You just have to use this in your terminal :
git config --global alias.lg "HERE GOES MY BIG LOG COMMAND LINE"
To summarize copy and paste the line below on your terminal:
git config --global alias.lg "log --all --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
Then you will just have to use git lg to get your log history tree.
Example:
src
A: Try
git show-branch
git show-branch --all
Example output:
bash$ git show-branch --all
! [branchA] commitA only in branchA
* [branchB] commitB
! [branchC] commitC only in branchC
---------------------
+ [branchA] commitA only in branchA
* [branchB] commitB
+ [branchC] commitC only in branchC
*+ [branchC~1] commitB-1 also in branchC
*+ [branchC~2] commitB-2 also in branchC
+++ [branchC~3] common ancestor
+++ [branchC~4] more common ancestors
A: Just type gitk command and press enter.
For me gitk is the easiest solution for this. Though it will not show you command mode, it will automatically populate a nice UI like this :
A: sehe's solution looks great, here is another one that seems to contain similar information, formatted differently, it uses git log, so it contains commit information as well (ignore the branch names, I kind of messed them up!):
git log --all --graph --decorate --oneline --simplify-by-decoration
* ae038ad (HEAD, branch2-1) add content to tmp1
| * f5a0029 (branch2-1-1) Add another
|/
* 3e56666 (branch1) Second wave of commits
| * 6c9af2a (branch1-2) add thing
|/
* bfcf30a (master) commit 1
A: I just made a very simple CLI and put it to brew as I couldn't find anything similar, just a couple of lines in go: https://github.com/mucansever/gittree
A: How about this alias for your .gitconfig:
[alias]
branch-tree = !cd "$(git rev-parse --git-dir)/refs/heads" && tree
You can also give options, depending on what your tree command supports, such as -D for timestamps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "92"
} |
Q: PHP - Mixing object Injection & inheritance This is a follow up question on the following answer : Parent Object in php
class A {
protected function doSomeStuff(){
echo 'a method that all children will need to call';
}
}
class B {
protected $_parent;
public function __construct($parent) {
$this->_parent = $parent;
}
public function doSomeLocalStuff() {
$this->_parent->doSomeStuff(); // Fatal Error
}
}
$a = new A(); // will be used for other children as well.
$b = new B($a);
$b->doSomeLocalStuff();
In the above code, parent object Injection was used, allowing class B to be initialized using a specific instance of class A, but class B wont be able to access class A protected properties or methods (e.g., doSomeStuff()).
But by mixing the above with inheritance, we get the best of both worlds :)
class B extends A {
protected $_parent;
public function __construct($parent) {
$this->_parent = $parent;
}
public function doSomeLocalStuff() {
$this->_parent->doSomeStuff(); // Works :)
}
}
So, is this acceptable ? .. any drawbacks ?
P.S: I'm trying to implement a non-static factory pattern.
Clarification
Consider this, I'm trying to design a class which will be used for calling an external API. We've over 400 different calls, divided into 10 categories (billing, customers, products ... ).
All the 400 calls shares the same parent-url, username/password and some other common properties.
So, instead of putting the 400 method in one big class, I decided to divide them into 10 classes, with a parent class handling common functions (e.g., authentication, url construction, web call ... ), then created a factory pattern, where I can load only needed classes/categories on run-time.
Something like :
$apiCall = new parentPlusFactory();
//contains common methods and a mechanism to load sub-classes
$apiCall->setAPIuserName("user");
$apiCall->setAPIpassword("pass");
$apiCall->useClass('customers')->doSomeCustomerStuff();
$apiCall->useClass('products')->doSomeProductStuff();
That's why I need to share the same parent class instance.
A: There is no friend keyword in PHP, like in C++. You could check this discussion for a way to implement friend classes.
But do you really need that function to be declared protected?
A: In general you should favor composition over inheritance. To me your use case sounds like B should not be extending A at all, but instead you should have two separate classes.
Now, PHP 5.4 will have "horizontal reuse", also known as "traits", where it will be possible to "include" a trait into your class.
trait A
{
public function doSomeStuff()
{
echo 'doing some stuff';
}
}
class B
{
use A;
public function doSomeLocalStuff()
{
$this->doSomeStuff();
}
}
class C
{
use A;
public function doSomeLocalStuff()
{
echo 'Doing something completely different here';
}
}
See also PHP manual: traits and PHP 5.4 beta1 released.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Export SQL data from android to MS SQL server 2008 I'm fairly still new to android and I was wondering, what is the best way to get data from an android device to MS SQL server 2008? I've seen a number of people who have commented on several ways to do this but I'm looking for a means of somehow exporting the data as an XML based file and trying to send it via internet (maybe web service) to be inserted into MS SQL server. Problem is that I'm not sure how to take the XML file from an android device and get it to insert into MS SQL server. I am missing the steps in this process and I haven't seen anything that has clearly stated how to do this. For instance once you have the XML what do you do next, and so on? I just need some light to be shed on this subject anything would be much appreciated, thanks!
A: As much i understood your question that you want to send xml file's(that is in your phone) to mysql server, right?
if data is small and whole data can be send in one request,may be following steps usefull for you-
*
*read data from xml file you can use any technique like xml pull parser or dom.
*make a method for http request.
*make a service that will receive this http request and transfer it to server.
these are the very basic and common steps to perform this task...
hope this will help...
A: How is the data stored on the device? Do you need to send it over the internet or are you exporting it via the usb cable?
If you sending data over the internet to a web server that will then insert this data into your MS SQL database, Android comes with some useful JSON APIs that make serializing the data pretty straight forward.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: post a link from jquery to call a ASHX asp.net I have this function:
function exportdata(ID) {
$.ajax({
type: "POST",
url: "export.ashx?ID=" + ID,
data: "{}",
/*contentType: "application/json; charset=utf-8",*/
dataType: "json"
});
}
It works fine but when I open the Developer Tools of Chrome in the Console tab, I see some errors:
POST http://localhost:1111/export.ashx?ID=1 undefined (undefined)
POST http://localhost:1111/abc.aspx undefined (undefined)
How can I solve this problem?
thanks in dvance.
A: It may be caused by this:
data: "{}",
When you use braces to send data to $.ajax, you do not need quotes around them:
data: {},
The quotes come in when you want to send data in this fashion:
data: "name=John&location=Boston",
Also, data is not required. If you are not sending any data, simply omit it.
Documentation for jquery ajax: http://api.jquery.com/jQuery.ajax/
A: The parameter coming in is ID and you're using tripID in the code. Could that be it?
Try this
function exportdata(tripID) {
$.ajax({
type: "POST",
url: "export.ashx?ID=" + tripID,
data: "{}",
/*contentType: "application/json; charset=utf-8",*/
dataType: "json"
});
}
A: If you aren't posting any data and just want to pass a query-string variable you have to use GET:
$.ajax({
type: "GET",
url: "export.ashx?ID=" + ID
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: VSTO Add in for Office 365 I have a couple of Excel Add ins. If I move to Office 365, will these add ins be available ? Is there any development support(VSTO) for Office 365 ?
A: I to have been curious about the answer to this, so went looking online. From the following site, I'd say the answer is no. It looks like developing for Office 365 is more along the lines of SharePoint development.
http://blogs.msdn.com/b/donovanf/archive/2011/06/29/office-365-developer-guidance-and-resources.aspx
I have seen advertisements online for products such as this... http://www.ocxt.com/products that look like they could provide a possible solution for taking a vsto application to the web.
A: I think things have moved on substantially since this question was asked. Microsoft seem to be fully committed to the Add-in approach with Office 2013 and the equivalent VSTO tooling available in VS2012.
The Office Dev Center home page has Office 2013 and VSTO Add-ins written all over it.
This MSDN Blog Post also clearly shows Add-ins are still part of the strategy.
Until the full capabilities of Desktop MS Office are available in a browser, I can't see this situation changing.
A: If you mean Office 365 installed on client PC then there is no issue with VSTO Add-ins. Our Chem4Word Add-in is using Office 2010 VSTO and happily works with 2010, 2013, 2016, 2019, O365.
If you mean Office 365 on-line then you have to redesign them using the Office 365 Javascript API
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: hide input[type=submit] and show loading image not working using jquery, i am trying to hide the submit button and show an ajax loading gif once it is clicked.
it is working fine, but the form does not get submitted anymore.
heres my jquery code:
$('input[type=submit]').click(function () {
$(this).parent('p').html('<img src="images/ajax-loader.gif" alt="loading" />');
$(this).parent('form').submit();
});
heres my html:
<h1>add</h1>
<form method="post" action="form.php">
<p>
<label for="number">number:</label>
<input type="text" name="number" id="number" size="30" value="" />
</p>
<p style="text-align: center;">
<input type="submit" value="add" />
</p>
</form>
as you can see, i even added $(this).parent('form').submit(); and it still doesn't work.
A: Try this:
$('form').submit(function() {
$('p:last-child', this).html('<img src="images/ajax-loader.gif" alt="loading" />');
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a command to move the whole SVG path to a new position? Is there a command to move the whole SVG path to a new position, instead of adding the offsets to each point of the path?
A: <path transform="translate(x, y)" d="....">
If your path already has transforms and you'd rather not interfere with them:
<g transform="translate(x, y)">
<path transform="..." d="....">
</g>
Stealing from Phrogz's comment and Powerboy's answer.
A: Thanks to sehe's comment. The solution is: wrap the path into
<g transform="translate(offset_x,offset_y)"></g>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Setting modified flag in a class Say I have a class Car that has 2 properties:
NSMutableArray *parts
and
BOOL modified
parts is an array of custom object called Part. I want modified to be set to YES if any property of any Part in the array is modified.
Is this a good candidate for KVO or is there a better way to do this?
A: YES ! That's exactly what KVO is made for, and your use case is a typical usage for this :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What technology can be used for animating a MIPS Pipeline? For my Computer Architecture class, I have to create an Animated MIPS Pipeline Simulation with the colors and everything. Any idea which technology can be used to accomplish this? I can do the coding in several high-level languages but I have no idea how to do the animation (tool, library, templates). The animation must be interactive, the user should be able to enter actual MIPS assembly code, and the simulation demonstrate the path it takes using colors "One color for each type of instruction".
Thanks
Image: http://www.utdallas.edu/~cantrell/ee4304/Pipe-data+control.jpg
A: Try one of these:
Visual MIPS R2000 Processor Simulator - http://jamesgart.com/procsim/
Animated Circuit Simulator - http://www.cs.technion.ac.il/~wagner/index_files/ckt_anim/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to get .class from a generic class? How does one do something like:
Schema<ArrayList<UnitInstanceData>> scheme =
RuntimeSchema.getSchema(ArrayList<UnitInstanceData>.class));
A: The .class is runtime access to the class object. At runtime generics are gone, having been eliminated by "type erasure". In your example, all you can get is ArrayList.class. If you need to know the type of the generic class at runtime you must pass a second parameter, as in
RuntimeSchema.getSchema(ArrayList.class, UnitInstanceData.class));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: BLOB's in SQL that stores a Video file I am hoping someone can explain how to use BLOBs. I see that BLOBs can be used to store video files. My question is why would a person store a video file in a BLOB in a SQL database? What are the advantages and disadvantages compared to storing pointers to the location of the video file?
A: A few different reasons.
If you store a pointer to a file on disk (presumably using the BFILE data type), you have to ensure that your database is updated whenever files are moved, renamed, or deleted on disk. It's relatively common when you store data like this that over time your database gets out of sync with the file system and you end up with broken links and orphaned content.
If you store a pointer to a file on disk, you cannot use transactional semantics when you're dealing with multimedia. Since you can't do something like issue a rollback against a file system, you either have to deal with the fact that you're going to have situations where the data on the file system doesn't match the data in the database (i.e. someone uploaded a video to the file system but the transaction that created the author and title in the database failed or vice versa) or you have to add additional steps to the file upload to simulate transactional semantics (i.e. upload a second <>_done.txt file that just contains the number of bytes in the actual file that was uploaded. That's cumbersome and error-prone and may create usability issues.
For many applications, having the database serve up data is the easiest way to provide it to a user. If you want to avoid giving a user a direct FTP URL to your files because they could use that to bypass some application-level security, the easiest option is to have a database-backed application where to retrieve the data, the database reads it from the file system and then returns it to the middle tier which then sends the data to the client. If you're going to have to read the data into the database every time the data is retrieved, it often makes more sense to just store the data directly in the database and to let the database read it from its data files when the user asks for it.
Finally, databases like Oracle provide additional utilities for working with multimedia data in the database. Oracle interMedia, for example, provides a rich set of objects to interact with video data stored in the database-- you can easily tag where scenes begin or end, tag where various subjects are discussed, when the video was recorded, who recorded it, etc. And you can integrate that search functionality with searches against all your relational data. Of course, you could write an application on top of the database that did all those things as well but then you're either writing a lot of code or using another framework in your app. It's often much easier to leverage the database functionality.
A: Take a read of this : http://www.oracle.com/us/products/database/options/spatial/039950.pdf
(obviously a biased view, but does have a few cons (that have now been fixed by the advent of 11g)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Does MySql Have xml support like SQL Server? Does MySql Have xml support like SQL Server?
I have searched and can't seem to find anything.
In SQL-Server I can use FOR XML to build xml output from my queries.
Is a similar method available in MySQL 5.1?
A: To some extent, but not like MSSQL. See http://dev.mysql.com/doc/refman/5.1/en/xml-functions.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Solve "The command "taskkill /F /IM MyApp.vshost.exe" exited with code 128" error Context
When debugging (with the Debug menu F5) a Visual Studio solution, a process called MyApp.vshost.exe is created. When you stop the debug indecently - I mean using the Stop Debug menu SHIFT+F5 and not waiting for a code line like Application.Exit() occurs - this process is not killed.
Sometimes, when you later start again debugging your application, an error message occurs, saying that the file (obviously, it is the file used by the debug: bin\Debug\MyApp.vshost.exe) is already in use.
That is why I added to the Build events this command line: taskkill /F /IM MyApp.vshost.exe
Problem
When the MyApp.vshost.exeprocess does not exist, Visual Studio is sometimes throwing an error at build time, thus preventing to build the application:
Error c:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets
The command "taskkill /F /IM MyApp.vshost.exe" exited with code 128.
The only existing solution i found is to remove the build event.
Question
Is there a way to resolve the error message without removing the build event?
EDIT
I'm thinking the best solution would be to retrieve the return code (errorlevel) of the command, then return 0 if it is equal to 128. Is it possible to do it in the Build events of the project?
A: As a temporary measure you can disable the Visual Studio host process:
How to: Disable the Hosting Process
To disable the hosting process
Open a project in Visual Studio.
On the Project menu, click Properties.
Click the Debug tab.
Clear the Enable the Visual Studio hosting process check box.
The side effects of doing this may or may not be desirable:
In general, when the hosting process is disabled:
The time needed to begin debugging .NET Framework applications
increases.
Design-time expression evaluation is unavailable.
Partial trust debugging is unavailable.
A: The MyApp.vshost.exe is the Visual Studio hosting process. The purpose of this process is to improve the debugging experience. If you kill this process yourself Visual Studio will recreate it. If you want to get rid of it you can turn off the hosting process in the debugging properties for the project (C# shown here):
You describe the error you experience as "the process is already in use". I don't think I have experienced that myself but on a work PC I'm having great troubles when building after debugging. It seems that MyApp.exe is locked and cannot be overwritten ("file is already in use", not "process") causing the build to fail. By belief is that a virus scanner (Microsoft Forefront) are causing these problems, but being in a corporate environment I can't turn off the scanner to test my hypothesis.
In many cases disabling the hosting process will not have a noticable effect on your debugging experience.
A: taskkill /F /IM MyApp.vshost.exe 2>&1 || exit /B 0
A: running perhaps as administrator with full privileges the IDE ? ( I know this was suggested once upon a time from Microsoft )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Drupal defining node grid data I need to define a 10*10 grid of nodes. Each cell in the grid has to contain exactly one node.
A newly created node gets inserted into the next available cell and a new node can not be step to occupy an occupied cell.
That's the scenario I am trying to accomplish but I need suggestions how I do it.
A: How are your nodes currently being displayed? What version of Drupal are you using?
If you are using Views 7.x-3.x, there's a style plugin called "Grid" bundled with the module. When editing your view, click on Format and select Grid. Click "Apply", and on the following page set the number of columns to 10.
Finally, you probably want to disable the Views pager, but limit the results to 100.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the equivalent of Android's Html.fromHtml() in WP7? Is there a quick and dirty way to render HTML in a textblock in a fashion similar to Android's Html.fromHtml()? I am aware of how to manually parse it with something like the HtmlAgilityPack, but all I really want is for it to render like its source in the textblock.
If not naively then perhaps with a custom control of some sort and, no I don't want to render it as a web page.
A: Ok sorry it took so long. I all but forgot how to use git correctly and hadn't had the time to upload till now. This HtmlTextBlock offers a similar level of functionality as to that of its silverlight counterpart which is pretty close to the android equivalent. Its still a bit buggy at times when dealing with more complex tags like the html dtd tag but does the job....
WP7 Html Text Block. The design is largely based on this guy's Bringing-a-bit-of-html-to-silverlight-htmltextblock-makes-rich-text-display-easy. and rewriting the web browser related classes using html agility. One day I'll post the details but, blah... Not right now. lol
Update
Example of usage:
<local:HtmlTextBlock x:Name="htmlTextBlock" Canvas.Left="2" Canvas.Top="2" TextWrapping="Wrap" UseDomAsParser="true" Text="<p>Your Html here </p>" />
Note: Your html will have to be escaped such that < = < and > = >
For detailed usage see:
https://github.com/musicm122/WP7HtmlTextBlock-/blob/master/HtmlTextBlockTest/HtmlTextBlockTest/MainPage.xaml
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: getting oauth_problem: signature_invalid error in Java running my first OAuth provider/consumer example.
My provider is the below jsp running on Tomcat 7
<%@page import="net.oauth.*, net.oauth.server.*" %>
<%
String consumerSecret="testsecret";
String consumerKey="testkey";
OAuthMessage message=OAuthServlet.getMessage(request,null);
OAuthConsumer consumer=new OAuthConsumer(null, consumerKey, consumerSecret, null);
OAuthAccessor accessor=new OAuthAccessor(consumer);
SimpleOAuthValidator validator=new SimpleOAuthValidator();
validator.validateMessage(message,accessor);
System.out.println("It must have worked");
%>
It's derived from http://communitygrids.blogspot.com/2009/01/simple-oauth-client-and-server-examples.html
Below is my consumer side(a console app) based on the scribe lib
import org.apache.commons.codec.binary.Base64;
import org.scribe.builder.ServiceBuilder;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;
import api.TradeKingAPI;
public class OAuthScribeTest {
public static void main(String[] args) throws Exception {
String url = "http://localhost:9080/OAuthTest/OAuthTest.jsp";
String consumerSecret="testsecret";
String consumerKey="testkey";
OAuthService service = new ServiceBuilder()
.provider(TradeKingAPI.class)
.apiKey(consumerKey)
.apiSecret(consumerSecret)
.build();
Token accessToken = new Token(consumerKey, consumerSecret);
OAuthRequest request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println(response.getBody());
int x = 0;
}
}`
when I run the client, I'm getting this error response from the provider
oauth_signature: onPnFrUtighWHU0UrERD0Wg7mII=
oauth_signature_base_string: GET&http%3A%2F%2Flocalhost%3A9080%2FOAuthTest%2FOAuthTest.jsp&oauth_consumer_key%3Dtestkey%26oauth_nonce%3D2098667235%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1317506767%26oauth_token%3Dtestkey%26oauth_version%3D1.0
oauth_problem: signature_invalid
oauth_signature_method: HMAC-SHA1
net.oauth.signature.OAuthSignatureMethod.validate(OAuthSignatureMethod.java:69)
net.oauth.SimpleOAuthValidator.validateSignature(SimpleOAuthValidator.java:254)
net.oauth.SimpleOAuthValidator.validateMessage(SimpleOAuthValidator.java:148)
org.apache.jsp.OAuthTest_jsp._jspService(OAuthTest_jsp.java:75)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:433)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
any pointer will be greatly appreciated. thx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Pixel collision detection? In my app, I have a bunch of CCSprites and I want to have a collision detection feature that will work only when the non-transparent pixels in the CCSprites collide. I don't want to be restricted to color between the colliding sprites. I think thats what the 'Pixel Perfect Collision Detection' thread does in the Cocos2D forum, but I want to use any color for the real collision. This collision detection would be in my game loop so it can't be too expensive. Anyway, does anyone have any ideas on how I can do this?
I am willing to use Cocos2D, Box2D or Chipmunk or even UIKit if it can do it.
Thanks!
A: When talking about hardware rendered graphics, "I want pixel perfect collisions" and "I don't want them to be too expensive" are pretty mutually exclusive.
Either write a simpler renderer that doesn't allows such complex transformations, anti-aliasing or sub-pixel placement or use the actual GPU to render some sort of collision mask. The problem with doing that on the GPU is that it's fast to send stuff to the GPU and expensive to get it back. There's a reason why this technique is quite uncommon.
Chipmunk Pro's auto-geometry stuff supports turning images of various varieties into collision shapes, but isn't complete yet.
A: It`s imposible to do if you dont want lose performance. Try to do a system colission based in circles, this in best way to do a collision
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why do I keep getting two of same random values in this code?
Possible Duplicate:
Why does it appear that my random number generator isn't random in C#?
I have the following code:
int a;
int aa;
Random aRand = new Random();
Random aaRand = new Random();
a = aRand.Next(20);
aa = aaRand.Next(20);
//if (a == aa)
{
Console.WriteLine(a + " " + aa);
Console.ReadLine();
}
I'm assuming that aRand and aaRand would be two different values, but that's not the case. What am I doing wrong? I'm assuming that aRand and aaRand will not always be the same, but they keep coming out the same all the time.
Thanks
A: This is explicitly covered in the docs for Random():
The default seed value is derived from the system clock and has finite
resolution. As a result, different Random objects that are created in
close succession by a call to the default constructor will have
identical default seed values and, therefore, will produce identical
sets of random numbers.
A: Why are you creating two different Random variables? You could use just one:
int a;
int aa;
Random aRand = new Random();
a = aRand.Next(20);
aa = aRand.Next(20);
//if (a == aa)
{
Console.WriteLine(a + " " + aa);
Console.ReadLine();
}
Edit:
"The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. "
from http://msdn.microsoft.com/en-us/library/system.random.aspx
A: You only need one instance of Random() - just call .Next() twice.
int a;
int aa;
Random aRand = new Random();
a = aRand.Next(20);
aa = aRand.Next(20);
A: You should never have more than One Random variable in your entire application. Get rid of the second
Random aaRand = new Random();
A: It looks like the two instances are using the same seed.
the seed determines all the values that will be generated and in which order. If you create 200 instances of Random with the same seed, they'll all give you the same output.
Create a single Instance when your app starts and reuse it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to take a look at the next character in a stream in C?
Possible Duplicate:
C equivalent to fstream's peek
Say I have a file with characters in it. I want to look at what the next character is without moving the pointer, just to "peak" at it. how would I go about doing that?
FILE *fp;
char c, d;
fp = fopen (file, "r");
c = getc(fp);
d = nextchar?
How do I look at the character that comes next without actually calling getc again and moving the pointer?
A: You can simply use getc() to get the next character, followed by a call to ungetc().
Update: see @Jonathan's comment for a wrapper that allows for peeking past the end of the file (returning EOF in that event).
Update 2: A slightly more compact version:
int fpeek(FILE * const fp)
{
const int c = getc(fp);
return c == EOF ? EOF : ungetc(c, fp);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: std::hash_set vs std::unordered_set, are they the same thing? I know hash_set is non-standard and unordered_set is standard. However, I am wondering, performance wise, what is the difference between the two? Why do they exist separately?
A: Regarding the question "are they the same thing" from the subject line: based on my experience of upgrading code from __gnu_cxx::hash_set to std::unordered_set, they are almost, but not exactly, the same thing.
The difference that I ran into is that iterating through __gnu_cxx::hash_set returned the items in what appeared to be the original order of insertion, whereas std::unordered_set would not. So as the name implies, one cannot rely on an iterator to return the items in any particular order when iterating though the entire std::unordered_set.
A: The complexity requirements for the unordered_-containers set out by the C++ standard essentially don't leave much room for the implementation, which has to be some sort of hash table. The standard was written in full awareness that those data structures had already been deployed by most vendors as an extension.
Compiler vendors would typically call those containers "hash map" or "hash set", which is what you're probably referring to (there is no literal std::hash_set in the standard, but I think there's one in GCC in a separate namespace, and similarly for other compilers).
When the new standard was written, the authors wanted to avoid possible confusion with existing extension libraries, so they went for a name that reflects the typical C++ mindset: say what it is, not how it's implemented. The unordered containers are, well, unordered. That means you get less from them compared to the ordered containers, but this diminished utility affords you more efficient access.
Implementation-wise, hash_set, Boost-unordered, TR1-unordered and C++11-unordered will be very similar, if not identical.
A: Visual Studio 2010 for example has both hash_xxx and unordered_xxx, and if you look through the headers, atleast their implementation is the same for all of those (same base-/"policy"-classes).
For other compilers, I don't know, but due to how hash container usually have to be implemented, I guess there won't be many differences, if any at all.
A: They are pretty much the same things. The standard (C++0x) name is unordered_set. hash_set was an earlier name from boost and others.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Strange exception with python's cgitb and inspect.py I have a function that decodes an exception and pushes the info to a file. Following is what I do basically:
exc_info = sys.exc_info
txt = cgitb.text(exc_info)
Using this, I got the following exception trace:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\job_queue\utils\start_workers.py", line 40, in start_worker
worker_loop(r_jq, worktype, worker_id)
File "C:\Python27\lib\site-packages\job_queue\server\jq_worker.py", line 55, in worker_loop
_job_machine(*job)
File "C:\Python27\lib\site-packages\job_queue\server\jq_worker.py", line 34, in _job_machine
do_verbose_exception()
File "C:\Python27\lib\site-packages\job_queue\server\errors.py", line 23, in do_verbose_exception
txt = cgitb.text(exc_info)
File "C:\Python27\lib\cgitb.py", line 214, in text
formatvalue=lambda value: '=' + pydoc.text.repr(value))
File "C:\Python27\lib\inspect.py", line 885, in formatargvalues
specs.append(strseq(args[i], convert, join))
File "C:\Python27\lib\inspect.py", line 840, in strseq
return convert(object)
File "C:\Python27\lib\inspect.py", line 882, in convert
return formatarg(name) + formatvalue(locals[name])
KeyError: 'connection'
I ran the code multiple times after this exception, but couldn't reproduce it. However, I didn't find any reference in files cgitb.py or inspect.py to a dict with 'connection' key either.
Will anybody know if this is an issue with python's cgitb or inspect files? Any helpful inputs?
A: You passed a wrong type to text function
below is the correct way.
cgitb.text((sys.last_type, sys.last_value, sys.last_traceback))
A: Im not sure specifically why this exception is happening, but have you read the docs for cgitb module? It seems that since python 2.2 it has supported writing exceptions to a file:
http://docs.python.org/library/cgitb.html
Probably something like:
cgitb.enable(0, "/my/log/directory") # or 1 if you want to see it in browser
As far as your actual traceback, are you sure 'connection' isnt a name you are using in your own code? 'inspect' module is most likely trying to examine your own code to build the cgi traceback info and getting a bad key somewhere?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I protect OAuth keys from a user decompiling my project? I am writing my first application to use OAuth. This is for a desktop application, not a website or a mobile device where it would be more difficult to access the binary, so I am concerned on how to protect my application key and secret. I feel it would be trivial to look at the complied file and find the string that stores the key.
Am I over reacting or is this a genuine problem (with a known solution) for desktop apps?
This project is being coded in Java but I am also a C# developer so any solutions for .NET would be appreciated too.
EDIT:
I know there is no perfect solution, I am just looking for mitigating solutions.
EDIT2: I know pretty much only solution is use some form of obfuscation. Are there any free providers for .NET and Java that will do string obfuscation?
A: OAuth is not designed to be used in the situation you described, i.e. its purpose is not to authenticate a client device to a server or other device. It is designed to allow one server to delegate access to its resources to a user who has been authenticated by another server, which the first server trusts. The secrets involved are intended to be kept secure at the two servers.
I think you're trying to solve a different problem. If you're trying to find a way for the server to verify that it is only your client code that is accessing your server, you're up against a very big task.
A: It doesn't matter the platform, what you are asking will always be impossible. Whatever you have done to need this feature is whats wrong with your application. You can never trust a client like this. Perhaps you are looking for (in)Security Through Obscurity.
A: Edit: Let me be clear; this is not a solution for safely storing your keys in a binary, as many others have mentioned, there is no way of doing this.
What I am describing is a method of mitigating some of the danger of doing so.
/Edit
This is only a partial solution, but it can work depending on your setup; it worked well for us in our university internal network.
The idea is that you make a service that is only likely to be accessed by a computer.
For example, an authenticated WCF service, that not only requires you to log in (using the credentials that are stored in your executable) but also requires you to pass a time dependant value (like one of the gadgets you get for your online banking) or a the value of a specific database row, or a number of options.
The idea is simple really, you cannot totally secure the credentials, but you can make them only part of the problem.
We did this for a windows app that uses a student data store, which as you can imagine, had to be pretty secure.
The idea was that we had a connection provider running as a service somewhere and we had a heartbeat system that generated a new key every 30 seconds or so.
The only way you could get the correct connection information was to authenticate with the connection provider and provide the current time-dependant heartbeat. It was complex enough so that a human couldn't sit there and open a connection by hand and provide the correct results, but was performant enough to work in our internal network.
Of course, someone could still disassemble your code, find your credentials, decipher your heartbeat and so on; but if someone is capable and prepared to go to those lengths, then then only way of securing your machine is unplugging it from the network!
Hope this inspires you to some sort of solution!
A: Eazfuscator.NET and other .NET obfuscators do string encryption, which makes slightly less trivial for someone to see your string literals in a de-obfuscation program like Reflector. I say slightly less trivial because the key used to encrypt the strings is still stored in your binary, so an attacker can still decrypt the strings quite easily (just need to find the key, and then determine which crypto algo is being used to encrypt the strings, and they have your string literals decrypted).
A: There is no good or even half good way to protect keys embedded in a binary that untrusted users can access.
There are reasons to at least put a minimum amount of effort to protect yourself.
The minimum amount of effort won't be effective. Even the maximum amount of effort won't be effective against a skilled reverse engineer / hacker with just a few hours of spare time.
If you don't want your OAuth keys to be hacked, don't put them in code that you distribute to untrusted users. Period.
Am I over reacting or is this a genuine problem (with a known solution) for desktop apps?
It is a genuine problem with no known (effective) solution. Not in Java, not in C#, not in Perl, not in C, not in anything. Think of it as if it was a Law of Physics.
Your alternatives are:
*
*Force your users to use a trusted platform that will only execute crypto signed code. (Hint: this is most likely not practical for your application because current generation PC's don't work this way. And even TPS can be hacked given the right equipment.)
*Turn your application into a service and run it on a machine / machines that you control access to. (Hint: it sounds like OAuth 2.0 might remove this requirement.)
*Use some authentication mechanism that doesn't require permanent secret keys to be distributed.
*Get your users to sign a legally binding contract to not reverse engineer your code, and sue them if they violate the contract. Figuring out which of your users has hacked your keys is left to your imagination ... (Hint: this won't stop hacking, but may allow you to recover damages, if the hacker has assets.)
By the way, argument by analogy is a clever rhetorical trick, but it is not logically sound. The observation that physical locks on front doors stop people stealing your stuff (to some degree) says nothing whatsoever about the technical feasibility of safely embedding private information in executables.
And ignoring the fact that argument by analogy is unsound, this particular analogy breaks down for the following reason. Physical locks are not impenetrable. The lock on your front door "works" because someone has to stand in front of your house visible from the road fiddling with your lock for a minute or so ... or banging it with a big hammer. Someone doing that is taking the risk that he / she will be observed, and the police will be called. Bank vaults "work" because the time required to penetrate them is a number of hours, and there are other alarms, security guards, etc. And so on. By contrast, a hacker can spend minutes, hours, even days trying to break your technical protection measures with effectively zero risk of being observed / detected doing it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: 2D coordinates of Histogram3D from a given point of view
I found that plot on the web. I don`t know which kind of Distribution yields this. I would like to draw such plot on paper. But get some help from Mathematica if possible :
With this image as example could I obtain the 2D coordinate of each visible bar edges of the plot?
I don`t know if it is purely edge detection of an image from a plot or if we could get this info from the plot itself.
Ideally I would adjust the image size to match my paper size and obtain the coordinates scaled. It would be incredible.
Thank You for your attention.
A: @500 If you simply want to draw a plot like this by hand, capture it and bring it into a drawing program as a stencil. Then draw over it on a different layer, while gridlines are on; finally, remove the picture and print it. It's an easy job to scale it to whatever size you wish. But it you want to explore how Mathematica works with it, read on.
Looks like you'll want to be using Histogram3D. (See documentation.)
Let's generate normally distributed data points (n= 10k) around means of 40 and 125 with standard deviations of 10 and 50, respectively and a Spearman rho of .45.
data = RandomVariate[BinormalDistribution[{40, 125}, {10, 50}, .45], 10^4]
You may grab data from FullForm if you like. That will give you the z-values.
Let's plot it using Histogram3D. We'll use bins of width 5 and 25 for x, y, respectively.
Histogram3D[data2, {{Table[10 + 5 k, {k, 15}]}, {Table[ 0 + 25 k, {k, 0, 12}]}}]
Edit:
When you mouse over a bar, the z-value will appear in a tooltip. So if you want to gather the data "by hand", you can do it that way. Alternatively, using FullForm you can look for Lists such as the following, which appear to contain the coordinates you are looking for. They appear to be in the List following CuboidBox but they may be the CuboidBox parameters. Someone should be able to clarify this.
List[Tooltip[
StatusArea[
List[RawBoxes[
DynamicBox[
List[FEPrivate`If[CurrentValue["MouseOver"],
EdgeForm[
List[RGBColor[0.6666666666666666`, 0.6666666666666666`,
0.6666666666666666`], AbsoluteThickness[1.5`]]], List[],
List[]],
CuboidBox[List[15.`, 0.`, 0.`], List[20.`, 25.`, 10.`]]]]]],
10.`], Style[10.`, List[GrayLevel[0]]]]]
You could also use LabelingFunction to display the z-values, but this will not look good unless you are looking perpendicular to the x-y plane, in which case it might be better to use DensityPlot.
Histogram3D[data2, {{Table[10 + 5 k, {k, 15}]},
{Table[0 + 25 k, {k, 0, 12}]}},
LabelingFunction -> (Placed[Panel[#1, FrameMargins -> 0], Above] &)]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: mysql (5.1) > select * from database.table where not foo (on all fields) I want to select everything in a table where the cell's value is not foo. I thought it would be something similar to WHERE NOT NULL, like SELECT * FROM database.table WHERE NOT 'foo';, but that just returned the column headers with no data.
edit: i want to do this without specifying a particular column (NOT 'foo' for all fields).
A: There's no way to do this without specifying the fields and conditions, as in
select * from table where
col1 != value and
col2 != value and
...
Depending on what you mean by
the cell's value is not foo
you may need to change and (none of the columns in a row match the condition) to or (at least one column does not match the condition).
A: As @Jim Garrison answers, you must specify the columns to compare your 'foo' value against. Otherwise you're testing a constant value itself, and that can be either false (zero) or true (nonzero).
SELECT * FROM database.table WHERE NOT 'foo' returns no data because 'foo' is a non-false constant value. Therefore NOT 'foo' is false for every row in the table, and so no rows match and the result is an empty set.
Jim gives one syntax for testing each column in turn. Here's another alternative syntax:
SELECT * FROM database.table WHERE 'foo' NOT IN (column1, column2, column3, ...)
However, I agree with the comment from @Mosty Mostacho. In a relational database, it's weird to test for a single value over many columns. Each column should be a different logical type of attribute, so it's uncommon to look for a similar value among many columns (not impossible, but uncommon).
It usually means you're using repeating groups of columns, which violates First Normal Form. Instead, you may need to create a child table, so that all the values you are searching are in a single column, over multiple rows.
A: It seems like MySQL is not sophisticated enough to do this. Instead I'll have to add an if-test in my php loop to check for foo and break if foo is present. I didn't want to do this as I have to get down into several nested loops before testing a cell's value…
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: AS3 - URLload local files with absoute path I am trying to open local hard drive files inside AS3. I'm getting a security error with this code:
var soundFile:URLRequest = new URLRequest("c:\slushy.mp3");
Is it possible to URLload an absolute path on the hard drive?
Edit: so this appears to be a sandboxing issue. Drat. Is it possible to load the local file via PHP and send to flash?
A: PHP is a server language, so the final protocol is http.
The you must to acces by file:/// to the local file, but if you want to share the resources over Internet, you must upload your files to folder in the root of site.
By example: http://www.mysite.com/music
Then you can load the file:
var soundFile:URLRequest = new URLRequest("http://www.mysite.com/music/slushy.mp3");
Requisite: you must to create the directory "music" in server web application directory and upload the file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MVC3 Want Clientside Validation to trigger for two fields when one of the two is modified I am creating an MVC3 website and added a couple of security questions to the "My MVC Application" Registration routine in the form of dropdown boxes. I created a custom validator to check the second dropdown box and if the selected item is the same as the first then it shows an error message.
My problem is that the clientside validation triggers as soon as the second dropdown box loses focus. After the error is displayed, ideally, I should be able to change the selection in the first dropdown box and the validation error message for the second dropdown box should go away. But, of course, changing the first dropdown box does not trigger the clientside validation routine for the second dropdown box and the error does not go away.
I would appreciate it if someone who is well versed with the internalls of unobstrosive Ajax validation routines would guide me to a solution so that when the selection of one dropdown box changes the validation routine of both dropdown boxes is triggered.
Thanks a bunch for any pointers.
A: If you look at this question and my answer, you will see code for client-side validation where changing one field will trigger validation on another field, and will then stop after both fields' validation has run.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sortable linked list of objects For a school lab I have to make a linked list of messages and then sort those messages by priority, with "High" priority being pulled out first, then medium, then low. I've been trying to figure this out for days and I can't wrap my mind around the sorting. I've been trying to get it to sort without adding anything other than a head and a size field in my ListofMessages class but all I seem to do is add garbage code. I wanted to figure this out myself but right now I'm stumped.
Here's what I have so far. Hopefully you can make sense of it:
class ListOfMessages
{
private int m_nSize;
public Message m_cListStart;
//public Message m_cNextItem;
public Message m_cLastItem;
public ListOfMessages()
{
m_nSize = 0;
m_cListStart = null;
//m_cNextItem = null;
}
public int Count
{
get { return m_nSize; }
}
public string Display(Message cMessage)
{
return "Message: " + cMessage.m_strMessage + "\nPriority: " + cMessage.m_strPriority;
}
//list additions
public int Add(Message newMessage)
{
Message nextMessage = new Message();
//inserts objects at the end of the list
if (m_nSize == 0)
{
m_cListStart = newMessage;
//m_cLastItem = newMessage;
}
else
{
Message CurrentMessage = m_cListStart;
if (newMessage.m_strPriority == "High")
{
if (m_cListStart.m_strPriority != "High")
{
//Make the object at the start of the list point to itself
CurrentMessage.m_cNext = m_cListStart;
//Replace the object at the start of the list with the new message
m_cListStart = newMessage;
}
else
{
Message LastMessage = null;
for (int iii = 0; iii < m_nSize; iii++)//(newmessage.m_strpriority == iii.m_strpriority)
//&& (iii.m_cnext == null);)
{
if (m_cListStart.m_strPriority != "High")
{
nextMessage = newMessage;
nextMessage.m_cNext =
CurrentMessage = nextMessage;
//LastMessage.m_cNext = CurrentMessage;
}
LastMessage = CurrentMessage;
if (m_cListStart.m_cNext != null)
m_cListStart = m_cListStart.m_cNext;
}
}
//iii = iii.m_cnext;
}
// for (int iii = m_cListStart; ; iii = iii.m_cNext)//(newMessage.m_strPriority == iii.m_strPriority)
// //&& (iii.m_cNext == null);)
//{
// //Message lastMessage = iii;
// if (iii.m_strPriority != iii.m_strPriority)
// {
// //iii.m_cNext = newMessage;
// newMessage.m_cNext = iii.m_cNext;
// iii.m_cNext = newMessage;
// }
//m_cLastItem.m_cNext = newMessage;
}
//m_cLastItem = newMessage;
return m_nSize++;
}
public Message Pop()
{
//Message Current = m_cListStart;
//if the object at the start of the list has another object after it, make that object the start of the list
//and decrease the size by 1 after popping an object off if there is more than 1 object after the start of the list
if (m_cListStart.m_cNext != null)
{
m_cListStart = m_cListStart.m_cNext;
}
if (m_nSize > 0)
m_nSize--;
else
m_cListStart = null;
return m_cListStart;
//if (m_cListStart.m_cNext != null)
// m_cListStart = m_cListStart.m_cNext;
//if (m_nSize > 1)
// m_nSize--;
//return m_cListStart;
}
My pop function to retrieve the messages might need some refining but most of the work right now lies in the Add function. I'm really just stumbling through the dark there.
Does anyone know of a simple way of doing what I'm asking?
A: Why dont you write a custom linked list as follows:
class Node<T> : IComparable<T>
{
public int Priority {set;get;}
public T Data {set;get;}
public Node<T> Next {set;get;}
public Node<T> Previous {set;get;}
// you need to implement IComparable here for sorting.
}
This is your node definitions. Now We need to implement a LinkedList Class.
Your linked list class can be doubly linked list, since you dont have any specs on it. and it would be easier with doubly linked list.
Here is the definition:
class LinkedList<T> : IEnumerable<T> where T: IComparable
{
public Node<T> Head {set;get;}
public Node<T> Tail {set;get;}
// set of constructors
//.....
public void Insert(Node<T> node)
{
// you can do recursive or iterative impl. very easy.
}
// other public methods such as remove, insertAfter, insert before, insert last etc.
public void Sort()
{
// easiest solution is to use insertion sort based on priority.
}
}
If you can get away by creating extra memory, ie: another linked list. insertion sort would be fine. For this purpose you need to implement insert after functionality as well.
I have a LinkedList implementation, you can check it out. You just need to implement sorting based on priority, you can use bubble sort, insertion sort, or merge sort.
Also, you might want to look at Heap which you can use to implement a priority Queue, it serves the purpose. I have a Heap Data Structure Implementation, you can check it out.
A: The easiest solution would be to have three singly-linked lists, one for each priority.
When you add, you add to the end of the correct list. When you remove, you first try to remove from the highest priority list. If that is empty, try the middle one. If even that is empty, use the lowest list.
If you have constant number of priorities, the time complexities are O(1) in both cases.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Statusnet installation Issue I have been trying to deploy statusnet on Amazon EC2. I have set up the AMI and did other necessary things. Now when it comes to installation I get this error:
"No configuration file found.
I looked for configuration files in the following places:
/etc/statusnet/statusnet.php
/etc/statusnet/laconica.php
/etc/laconica/laconica.php
/etc/statusnet/ec2-174-XXXXXcompute-1.amazonaws.com.php
/etc/laconica/ec2-174-XXXXX.compute-1.amazonaws.com.php
/var/www/html/config.php
You may wish to run the installer to fix this.
Go to the installer."
When I click 'Go to the Installer" it shows the installation form but with this message above it:
"Cannot load required extension: gd
Cannot load required extension: xmlwriter
Cannot load required extension: dom "
Please help me to solve this.
Thanks.
A: I have no experiences in installing StatusNet on Amazon EC2, but I'd like give you some suggestions.
*
*Copy the htaccess.sample file to .htaccess in your StatusNet directory and then change the "RewriteBase" in the new .htaccess file to be the URL path to your StatusNet installation on your server.
*Modify the php.ini items related to gd, xmlwriter and dom.
A: The PHP dependencies (extensions you need) are mentioned in the text file named INSTALL in the root directory of your installation.
Specifically:
*
*Curl. This is for fetching files by HTTP.
*XMLWriter. This is for formatting XML and HTML output.
*MySQL. For accessing the database.
*GD. For scaling down avatar images.
*mbstring. For handling Unicode (UTF-8) encoded strings.
Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to filter a data frame? I am using something like this to filter my data frame:
d1 = data.frame(data[data$ColA == "ColACat1" & data$ColB == "ColBCat2", ])
When I print d1, it works as expected. However, when I type d1$ColB, it still prints everything from the original data frame.
> print(d1)
ColA ColB
-----------------
ColACat1 ColBCat2
ColACat1 ColBCat2
> print(d1$ColA)
Levels: ColACat1 ColACat2
Maybe this is expected but when I pass d1 to ggplot, it messes up my graph and does not use the filter. Is there anyway I can filter the data frame and get only the records that match the filter? I want d1 to not know the existence of data.
A: As you allude to, the default behavior in R is to treat character columns in data frames as a special data type, called a factor. This is a feature, not a bug, but like any useful feature if you're not expecting it and don't know how to properly use it, it can be quite confusing.
factors are meant to represent categorical (rather than numerical, or quantitative) variables, which comes up often in statistics.
The subsetting operations you used do in fact work normally. Namely, they will return the correct subset of your data frame. However, the levels attribute of that variable remains unchanged, and still has all the original levels in it.
This means that any method written in R that is designed to take advantage of factors will treat that column as a categorical variable with a bunch of levels, many of which just aren't present. In statistics, one often wants to track the presence of 'missing' levels of categorical variables.
I actually also prefer to work with stringsAsFactors = FALSE, but many people frown on that since it can reduce code portability. (TRUE is the default, so sharing your code with someone else may be risky unless you preface every single script with a call to options).
A potentially more convenient solution, particularly for data frames, is to combine the subset and droplevels functions:
subsetDrop <- function(...){
droplevels(subset(...))
}
and use this function to extract subsets of your data frames in a way that is assured to remove any unused levels in the result.
A: This was such a pain! ggplot messes up if you don't do this right. Using this option at the beginning of my script solved it:
options(stringsAsFactors = FALSE)
Looks like it is the intended behavior but unfortunately I had turned this feature on for some other purpose and it started causing trouble for all my other scripts.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: AS3 - Cancel PHP request That script below is for uploading an image via PHP. Now I'ld like to give the user the option to cancel the upload.
How to cancel the PHP request once it got send?
package
{
import com.adobe.images.PNGEncoder;
import flash.display.BitmapData;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.SecurityErrorEvent;
import flash.events.IOErrorEvent
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;
public class ServeruploadExample
{
private var loader:URLLoader;
private const API_KEY:String = "<api key>";
private const UPLOAD_URL:String = "http://example.com/upload-image.php";
public function ImgurExample() {
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, onCookieSent);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
// Create a bitmapdata instance of a movieclip on the stage.
var mc:MovieClip;
var b:BitmapData = new BitmapData(mc.width, mc.height, true);
b.draw(mc);
var png:ByteArray = PNGEncoder.encode(b);
var vars:String = "?key=" + API_KEY + "&name=name&title=title";
var request:URLRequest = new URLRequest(UPLOAD_URL + vars);
request.contentType = "application/octet-stream";
request.method = URLRequestMethod.POST;
request.data = png;
loader.load(request);
}
// privates
}
}
A: Just call the .close() method of the URLloader class, which will terminate the load operation.
In your example, set up a cancel button and:
public function cancel_upload_click_handler(e:MouseEvent):void
{
loader.close();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Maven Learning Questions In eclipse I've installed m2e plugin. I am trying to understand how do you know the names of properties for dependencies to add to pom file?
Say for instance how do you know which artifact id to use?
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
why here say aspectjrt in artifact id?
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
and here same as group id ??
is there any pattern?
say my project is missing
org.hibernate.Query;
org.hibernate.Session;
org.hibernate.SessionFactory;
and in maven dependencies folder I have hibernate-core-3.6.0.Final.jar which effectively contains everything except those 3.
Do you write these .pom yourself?
I am betting that for student project I will have to stick with manually adding hundreds of libraries... otherwise I will fail trying to learn it :-)
A: *
*You know what groupId:artifactId:version (we call these coordinates) to use by which artifact you want. Most often, you find out which artifact you want by reading it in the project's documentation, especially for projects with a large number of artifacts, some of which might contain optional addons.
*aspectjrt is short for AspectJ RunTime.
*GroupId and artifactId are defined by the creators of the library in question. There's no universal pattern because there's no one central coordinator. There are some conventions that have evolved, though. Generally, the groupId is at least partly the reversed domain name, like the first part of a Java package name is: org.hibernate, org.apache, org.springframework... The artifactId distinctly identifies the role of that particular artifact in the group it belongs to, like spring-core, spring-tx, spring-jms, etc. You can get an idea of what groupId's and artifactId's look like by searching Maven Central for some of the libraries you know.
*If you're missing org.hibernate.SessionFactory, then you don't have hibernate-core-3.6.0.Final on your classpath. If you have that on your classpath, then you're not missing the SessionFactory class. Those three classes you mentioned are most definitely in that artifact, as you can see from searching for the class in Central. If you still doubt, do a jar -tf hibernate-core-3.6.0.Final.jar and check out the contents yourself. I promise it has those classes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: extjs 3.3: floating panel I am trying to create a floating panel over other pre-created panels, I tried following simple codes, but failed:
var testPanel = new Ext.Panel({
id: 'testP',
width: 50,
height: 100,
floating: true,
title:'Test'
});
testPanel.show();
what else I need to think about?
thanks!
A: Following needs to be taken care of when using the floating config:
1) Fixed width - which you've done
2) The position must be set explicitly after render (e.g., myPanel.setPosition(100,100);).
You can also set the underlying Ext.Layer config option instead of just setting floating : true. You can do that in the following way:
Ext.Panel({
//.. other config..,
floating : {
//Ext.Layer config options. Maybe a property in that will get you the desired effect that you're looking for.
}
});
Try this and update!
Cheers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.