text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Workflow for restarting a HTTP server from Clojure REPL A Clojure-based project of mine uses the netty (required by aleph) web server. I start the server, along with other components, in a web.clj file like this:
(ns myproject.web)
(def server (atom nil))
(defn initialize []
(if @server
(println "Warning: already initialized")
(let [port 8001]
(println (format "Starting http://localhost:%s/" port))
(swap! server (fn [_] (start-http-server
(wrap-ring-handler app-routes)
{:port port}))))))
(defn shutdown []
(when @server
(do
(println "Shutting down web server")
(@server)
(swap! server (fn [_] nil)))))
(defn reinitialize []
"Run this on the REPL to reload web.clj and restart the web server"
(myproject.web/shutdown)
(use :reload-all 'myproject.web)
(myproject.web/initialize))
The server instance is stored in a Clojure atom, so that it can be stopped later.
I use Emacs and Swank to directly launch the server on the REPL like this (after compiling web.clj with C-c C-k):
user> (myproject.web/initialize)
Whenever web.clj or other dependent modules are edited, I must
*
*remember NOT to recompile web.clj using C-c C-k because the atom holding the running instance would vanish (due to the atom from a newly compiled module) from the REPL.
*Run (myproject.web/reinitialize) which stops the server and then reloads the module before starting it again.
There are two problems with this:
*
*Often I forget point #1 and press C-c C-k anyway. This causes the loss of server atom in REPL, leading to having to kill swank (or restart emacs) so that I can start the server at the same port number.
*:reload-all doesn't report compile errors as friendly as C-c C-k (ugly traceback vs concise clickable errors).
How can I best address these two problems in this edit-compile-restart workflow?
A: You can replace
(def server (atom nil))
with
(defonce server (atom nil))
that way when you evaluate the buffer it will not redefine server.
A: for your first problem you can store the atom in a different namespace and on load only overwrite it if it is not yet defined. putting it in it's own namepspace will prevent it from being erased by the reload-all
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Are there mesh building helper classes in WPF or .NET 4.0? The mechanisms for building a mesh in WPF are quite low-level. For example you have to supply the vertexes and the indexes. Are there helpers in the WPF or anywhere in the .NET 4.0 framework I can use? Or do I have to resort to third party libraries?
A: Here's an older chunk of XNA 3.1 code I wrote to build a Sphere. I apply a transformation matrix in my rendering loop that allows me to stretch and orient it. Computing the vertices is fairly straightforward... computing the indices are what I find more difficult. This should hopefully give you an idea, though. The other primitives (e.g. cone, cylinder, cube...) are much simpler to compute.
The m_iSegments paremeter just allows me to define how many slices I want to divide the sphere into... the more segments, the more vertices, the smoother the sphere.
The m_Appearance parameter is my wrapper for the shader.
/// <summary>
/// This method constructs ellipsoid vertices, indices, and normals.
/// Equations are performed using the parameterized equations:
///
/// x = a cos(B)cos(L)
/// y = b cos(B)sin(L)
/// z = c sin(B)
///
/// Where:
///
/// B = latitude and,
/// L = longitude
///
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Ellipsoid">Wikipedia - Ellipsoid</seealso>
public override void BuildVertices()
{
#region Declarations
int iIndex = 0; // Stores the index of the vertex array.
int iBeta = 0; // Stores the beta increment.
int iLambda = 0; // Stores the lambda increment.
float Beta = 0.0f; // Beta0 - Stores the latitude.
float Lambda = 0.0f; // Lambda0 - Stores the longitude.
float BetaStep = MathHelper.Pi / m_iSegments; // Latitude Segements, in degrees.
float LambdaStep = MathHelper.TwoPi / m_iSegments; // Longitude Segments, in degrees.
Vector3 vectPos = Vector3.Zero; // Vertex Position Vector
Vector3 vectNor = Vector3.Zero; // Vertex Normal Vector
Vector2 vectTex = Vector2.Zero; // Vertex Texture Coordinate
#endregion
#region Build the vertices.
int[] iIndices = new int[6 * m_iSegments * m_iSegments];
Vector3[] vVertices = new Vector3[(m_iSegments + 1) * (m_iSegments + 1)];
Vector2[] vTexCrds = new Vector2[vVertices.Length];
iIndex = 0;
for (iBeta = 0; iBeta <= m_iSegments; iBeta++)
{
// Compute the latitude.
Beta = MathHelper.Clamp((-MathHelper.PiOver2) + (iBeta * BetaStep), -MathHelper.PiOver2, MathHelper.PiOver2);
for (iLambda = 0; iLambda <= m_iSegments; iLambda++)
{
// Compute the current longitude.
Lambda = MathHelper.Clamp((-MathHelper.Pi) + (iLambda * LambdaStep), -MathHelper.Pi, MathHelper.Pi);
// Compute the current vertex.
vVertices[iIndex] = new Vector3((float)(Math.Cos(Beta) * Math.Sin(Lambda)),
(float)(Math.Sin(Beta)),
(float)(Math.Cos(Beta) * Math.Cos(Lambda)));
// Compute the triangle indices.
if (iBeta < m_iSegments &&
iLambda < m_iSegments)
{
iIndices[iIndex + (iIndex * 5) - (iBeta * 6) + 0] = iIndex;
iIndices[iIndex + (iIndex * 5) - (iBeta * 6) + 1] = iIndex + m_iSegments + 1;
iIndices[iIndex + (iIndex * 5) - (iBeta * 6) + 2] = iIndex + m_iSegments + 2;
iIndices[iIndex + (iIndex * 5) - (iBeta * 6) + 3] = iIndex;
iIndices[iIndex + (iIndex * 5) - (iBeta * 6) + 4] = iIndex + m_iSegments + 2;
iIndices[iIndex + (iIndex * 5) - (iBeta * 6) + 5] = iIndex + 1;
}
// Compute the texture coordinates.
vTexCrds[iIndex] = new Vector2((float)iLambda / (float)m_iSegments, 1.0f - (float)iBeta / (float)m_iSegments);
iIndex++;
}
}
# endregion
#region Build the normals.
Vector3[] vNormals = new Vector3[vVertices.Length];
for (iIndex = 0; iIndex < vVertices.Length; iIndex++)
{
vNormals[iIndex] = vVertices[iIndex] - this.AbsolutePosition;
vNormals[iIndex].Normalize();
}
#endregion
#region Build the buffers.
VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[vVertices.Length];
for (iIndex = 0; iIndex < vVertices.Length; iIndex++)
vertices[iIndex] = new VertexPositionNormalTexture(vVertices[iIndex], vNormals[iIndex], vTexCrds[iIndex]);
m_pAppearance.SetBuffers(vertices, iIndices);
#endregion
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PDO Misunderstanding I am writing my PHP blog engine. I am using PDO for it. And now, when I am writing class Member - I have an error.
Fatal error: Call to a member function fetch() on a non-object in
/home/tucnak/Server/scripts/php/classes/Member.php on line 42
And source code of my Class:
public function authMember($user, $password)
{
$password = hashIt($password);
$count = 100500;
$count = $this->db->query("SELECT count(*) FROM users-general WHERE nick = $user AND password = $password;")->fetch();
echo($count);
// if ($count == 1){ return 1; } else { throw new Exception("",491); }
}
I have an error using this function.
A: Your query probably fails because you don't have quotes wrapped around your query.
When that happens, query() will return false instead of an object, breaking the chain.
Don't do it this way; run the query first, save its result, then check whether it's false.
By the way, you should really use prepared statements - your current statement is vulnerable to SQL injection.
A: "SELECT count(*) FROM `users-general` WHERE nick = '$user' AND password = '$password'"
note the single quotes of 2 different types
Thought, your misunderstanding has nothing to do with PDO. it's basic SQL syntax you have to learn
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Having issues with execvp() So here is the bit of my code that's giving me problems:
void childProcessHandler(string command){
int argCounter = 0;
for(int i=0; i!=command.size(); i++)
argCounter+=( command.at(i) == ' ');
char * temp, *token;
char *childArgs[argCounter];
argCounter = 1;
temp = new char [command.size()+1];
strcpy (temp, command.c_str());
token = strtok (temp," ");
childArgs[0] = token;
while (token!=NULL)
{
token = strtok(NULL," ");
childArgs[argCounter] = token;
argCounter++;
}
//delete[] temp; //Should remove token as well?
execvp(childArgs[0], childArgs);
cout<<"PROBLEM!"<<endl;
exit(-1);
}
In the main() method my code gets to a point where it forks() (the parent process then waits for the child to exit.) then the child process (process ID == 0 yes?) calls the method childProcessHandler with the user input (command to run + args) as it's argument. Then I tokenize the user input and call execvp on it.
Everything compiles and executes. The line after execvp is never reached because execvp only returns when there is an error yes?
The project is to simulate a unix terminal however when I give it the command "date" nothing gets printed like it should... The child exits and the parent process resumes just fine however nothing is sent back up to the terminal window...
What am I doing wrong?
(Also we were "recommended" to use strtok to tokenize it but if anyone has anything simpler i'm open to opinions.)
THANKS!
EDIT
The above code works, for example, if I type in "date " instead of "date". I think there might be something fishy with the "tokenizer" not putting a null character at the end of the childArgs[] array. I'll play around with that and thanks for the quick responses!
(Ninja edit, also commented out delete[] temp for the time being)
A: You're mixing std::string and char/char*. Fine, but you have to be careful, they have different behaviours.
In particular this line:
temp = new char [command.size()+1];
Is creating an actual array to hold a string in.
token = strtok (temp," ");
This is making token (which is just a pointer) point to a place inside temp. strtok() modifies the input string to make a temporary string within a string (sounds crazy, I know).
You need to copy the string strtok() gives you into a permanent home. Either use std::string to save you time and code, or do it the char* way and allocate the new string yourself. E.g. instead of:
childArgs[0] = token;
you need:
childArgs[0] = new char[strlen(token)+1];
strcpy(childArgs[0], token);
The same applies to tokens stored in the array during the loop over the command arguments.
A: Your childargs vector of pointers point into the bytes allocated in the block of memory "temp". When you free temp, you are removing the memory pointed to by the childargs pointers, possibly corrupting some of the values within your vector.
Remove the call to delete[] to stop freeing the memory pointed to by the childargs pointers. You will not be leaking memory. Once you call exec_() your entire process image is replaced anyway. The only thing that survives a call to exec_() (for the most part) are your file descriptors.
As a test, try something a bit more simple: After your call to fork() in the child, just call exec with the path to "date". Make that work before fiddling with the parameter list vector.
As another test, remove your call to exec, and print out your entire vector of pointers to make sure that your tokenizing is working the way you think it should. Remember that your final entry must be NULL so that you know where the end of the vector is.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JMenuItems don't show in JDialog This is probably a dumb question, but I just can't see it! I have Swing app that uses a popup menu. It works fine, but I want to make the menu persistent (i.e. until I close it). I have basically changed the JPopupMenu to JDialog, and I am getting the JDialog panel, but the menu items are invisible! It's probably something very obvious, so I'll probably be embarrassed! Here is part of the code:
JDialog buildNewItemMenu(DrawFBP base) {
JDialog jd = new JDialog();
jd.setSize(200, 300);
JMenuItem menuItem = null;
JLabel label2 = new JLabel();
label2.setForeground(Color.BLUE);
JMenu menu = new JMenu();
jd.add(menu);
jd.setVisible(true);
menu.setVisible(true);
menu.add(label2);
menu.addSeparator();
menuItem = new JMenuItem("Component");
menuItem.addActionListener(base);
menu.add(menuItem);
....
menu.addSeparator();
menuItem = new JMenuItem("Enclosure");
menuItem.addActionListener(base);
menu.add(menuItem);
return jd;
A: I think I will close this - as I said in the comment, changing the JMenu to a JPanel and adding
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
fixed the problem, but I plan to tackle the problem a different way. Thanks anyway!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: a file is copied to a specific folder and renamed to x.txt how do i open x.txt and paste "X:" EDIT: regulus6633 has made a script that's a lot better than my outline below, it works perfectly IF you're template file isn't completely empty (I think this caused an error originally). Thanks!
This script is supposed to (1) copy a x.txt to a specific folder rename it to new_name, (2) open it, (3) paste "new_name" in all caps, and (4) insert ":" followed by return & return. The first part is working, but I'm having trouble figuring out (2), (3) and (4). The code I've written so far is pasted below.
tell application "Finder"
display dialog "new_name_dialogue" default answer " "
set new_name to (text returned of result)
set Selected_Finder_Item to (folder of the front window) as text
duplicate file "Q:x:7:n7:GTD scripting:template folder:x.txt" to "Q:X:7:SI:SIAG1"
set Path_Of_X to "Q:X:7:SI:SIAG1:" & "x.txt" as string
set name of file Path_Of_X to (new_name as text) & ".txt"
#[something that let's me open the file is needed here]
#[something that pastes "new_name" & ":" in ALL CAPS]
#[something that inserts two lineshifts]
end tell
A: In general since you're dealing with a txt file, you do not need to "open" the file in an application and paste in text. We can read and write to text files directly from applescript. As such we read in the text from the template file, add whatever text we want to that, and then write the new text to a new file. If you then want to open and view the new file you can do that after. I did that in the "TextEdit" section of the code.
You can see at the end of the script I have subroutines to write a text file and also to change the file name to CAPS. So try the following...
-- initial variables
set templateFile to "Q:x:7:n7:GTD scripting:template folder:x.txt"
set copyFolder to "Q:X:7:SI:SIAG1:" -- notice this path ends in ":" because it's a folder
-- get the new name
display dialog "new_name_dialogue" default answer ""
set newName to (text returned of result)
set newPath to copyFolder & newName
-- get the text of the template file
set templateText to read file templateFile
-- add the file name in CAPS, a colon, and 2 returns at the beginning of templateText
set capsName to upperCase(newName)
set newText to capsName & ":" & return & return & templateText
-- write the newText to newPath
writeTo(newPath, newText, text, false)
-- open the new file in textedit
tell application "TextEdit" to open file newPath
(*============== SUBROUTINES ==============*)
on writeTo(targetFile, theData, dataType, apendData)
-- targetFile is the path to the file you want to write
-- theData is the data you want in the file.
-- dataType is the data type of theData and it can be text, list, record etc.
-- apendData is true to append theData to the end of the current contents of the file or false to overwrite it
try
set targetFile to targetFile as text
if targetFile does not contain ":" then set targetFile to POSIX file targetFile as text
set openFile to open for access file targetFile with write permission
if apendData is false then set eof of openFile to 0
write theData to openFile starting at eof as dataType
close access openFile
return true
on error
try
close access file targetFile
end try
return false
end try
end writeTo
on upperCase(theText)
set chrIDs to id of theText
set a to {}
repeat with i from 1 to (count of chrIDs)
set chrID to item i of chrIDs
if chrID ≥ 97 and chrID ≤ 122 then set chrID to (chrID - 32)
set end of a to chrID
end repeat
return string id a
end upperCase
A:
something that lets me open the file is needed here
tell application "TextEdit" to open Path_Of_X
something that pastes new_name in ALL CAPS
There is a really good third party scripting addition (Satimage OSAX) that you can use for things just like this (this will only work if you've downloaded the scripting addition)...
set UPPER_CASE to uppercase new_name & ":"
something that inserts two lineshifts
return & return
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error for the header file of goblin library in c++ I am trying to use Goblin library which is used for special network algorithms. This library provides some header files and objects in C/C++. So, you can easily add a header file to your program and use some special classes and functions.
Unfortunately, when I add the header file, I get error. In the following you can see the simple code and error.
Source:
#include<goblin.h>
int main()
{
return 0;
}
Error:
$ g++ -o test.o test.cpp
/tmp/ccB0Rb25.o: In function `goblinRootObject::~goblinRootObject()':
test.cpp:(.text._ZN16goblinRootObjectD1Ev[goblinRootObject::~goblinRootObject()]+0x10): undefined reference to `goblinNObjects'
test.cpp:(.text._ZN16goblinRootObjectD1Ev[goblinRootObject::~goblinRootObject()]+0x18): undefined reference to `goblinNObjects'
test.cpp:(.text._ZN16goblinRootObjectD1Ev[goblinRootObject::~goblinRootObject()]+0x2c): undefined reference to `goblinRootObject::operator delete(void*)'
/tmp/ccB0Rb25.o: In function `goblinRootObject::~goblinRootObject()':
test.cpp:(.text._ZN16goblinRootObjectD0Ev[goblinRootObject::~goblinRootObject()]+0x10): undefined reference to `goblinNObjects'
test.cpp:(.text._ZN16goblinRootObjectD0Ev[goblinRootObject::~goblinRootObject()]+0x18): undefined reference to `goblinNObjects'
test.cpp:(.text._ZN16goblinRootObjectD0Ev[goblinRootObject::~goblinRootObject()]+0x2c): undefined reference to `goblinRootObject::operator delete(void*)'
collect2: ld returned 1 exit status
A: try:
g++ -lgoblin -L/pathToLibgoblin/ -o test.o test.cpp
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is this the correct way to set an id for an element that doesn't have an id yet in jQuery? $("a[href*='http://www.google.com']").attr('id','newId');
Can only reference it by href.
A: Yes, that's the correct way to add an id attribute to an element that doesn't already have one.
However you should ensure that there's only one matching element, as it's incorrect to have two elements with the same ID on a page, e.g.:
$("a[href*='http://www.google.com']").first().attr('id', 'newId');
This would, of course, still leave you with the problem of what to do with the remaining matching elements, if any. A possible solution would be:
$("a[href*='http://www.google.com']").attr('id', function(index, attr) {
return 'newId_' + index;
});
which will assign the elements the IDs newId_0, newId_1, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CCSprite runAction and Remove I have a ccLayer where I'm trying to make it rain.
On init i schedule the following:
[self schedule:@selector(throwRain) interval:0.1f];
And here is the rest of the code:
-(void) throwRain {
CCSprite *gota;
for (int i = 1; i <= 6; i++){
gota = [CCSprite spriteWithFile:@"4_gota.png"];
gota.position = ccp(arc4random() % 768, 1060);
gota.scale = (arc4random () % 25 + 50.0f) / 100.0f;
gota.rotation = 35 ;
[self addChild:gota z:arc4random() % 5 + 7];
[gota runAction:[CCSequence actions:[CCEaseRateAction actionWithAction:[CCMoveTo actionWithDuration:3.0f + (arc4random() % 200) / 100.0f position:ccp(gota.position.x, 0)] rate:3] , [CCCallFunc actionWithTarget:self selector:@selector(spriteDone:)], nil]];
}
}
-(void) spriteDone:(id)sender {
[self removeChild:sender cleanup:YES];
}
However, the drops gets to the bottom and just stays there, and never gets removed. Any idea?
Thanks.
A: Try changing from CCCallFunc to CCCallFuncN. The 'N' stands for Node, and will pass the Node that is performing the action to the selector.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there anyway to limit bundle version while updating? When I use update command in OSGi, the framework (Equinox) uses the file in update location in order to update the bundle. No matter if the bundle in the location has a higher version or not. for example the framework updated version 1.2.0 with 1.0.0.
is there anyway to limit the version of the file that is going to be used as the updated file? I mean something like what we can do in import bundles.
A: No, the framework won't do this kind of checking for you. If you don't want to update the bundle from that location, just don't call update.
Note that it is possible to update a bundle from a different location than it was originally installed from, using the version of the update method that takes an InputStream, e.g.:
File newLocation = new File("...");
bundle.update(new FileInputStream(newLocation));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Update with column name by parameter How can I pass a columns name by parameter,
follow an example
DataTable dt = new DataTable();
// Here I fill my datatable
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
string columnsname = dt.Rows[i][dt.columns[j].toString()].toString();
SqlCommand comando = new SqlCommand();
comando.commandText = "UPDATE Sales.Store SET @columnname = @demographics where id = @id";
comando.Parameters.Add(new SqlParameter("@columnname", columname));
comando.Parameters.Add(new SqlParameter("@dados2", dados2));
comando.ExecuteNonQuery();
comando.Clear();
comando.Dispose()
}
}
This doesn't work, but I have 88 columns, and I need update all data in every 88 columns in each row.
A: You cannot parameterize column names.
To do what you want you will need to resort to dynamic SQL.
A: Well, if you have 30,000 rows with 88 columns, and you need to update all 88 columns, you probably want to rethink your database schema.
Itay.
A: I have figured out a way to include a work around for parametrized column names. I had the same problem but came up with a different way and since I would be the only one using the column names then I believe this is still a safe bet.
String sqlcomm = "SELECT * FROM Asset WHERE " + assetColName + " = ";
command.CommandText = sqlcomm + "$assetColValue";
//command.CommandText = @"SELECT * FROM Asset WHERE $assetColName = '$assetColValue'";
//command.Parameters.AddWithValue("$assetColName", assetColName);
command.Parameters.AddWithValue("$assetColValue", assetColValue);
As you can see from the code above. I tried almost what you did which I then had to comment out. I then concatenated strings together and was able to use my parametrized column name and value which then the value is securely added. The column name however is not secured but this is a method that only I will be using so its still somewhat safe. You can add regular expressions if you want to be more secure but you get the idea of the fix.
A: Just concatenate the sql string:
"UPDATE Contracts set " + columnName + " = @columnValue where ID = @ID"
Where column name is a string that represents a column in the table
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is FluorineFX mature enough to use for a large web application? I am in the planning stages of developing a large web application written in Flex and was wondering if anyone has actually used FluorineFX in a large production environment?
The documentation and online community makes it seem like it could be abandoned in the years to come and I have yet to read about it being used in production.
I have been assessing Weborb as well, but the costs are extremely high and I'm not entirely satisfied with the general workflow/setup of it. Are there any other solutions out there that I should consider?
A: I've used FlourineFx with great success in a large product with a Flex 3 client, and it actually works better than the ColdFusion (Adobe LiveCycle) product it replaced. It does require some configuration to work correctly, but it seems to work quite well once your config files are set up -- then again, its the same config files that Adobe LiveCycle need.
A: Not sure about FlourineFX. It looks like it is either just getting started or ending.
Working with DotNet and Flex, I would recommend writing the Flex Client and using ASP.NET web services to communicate. Microsoft ASP.NET MVC is a wonderful framework that is free and well supported. See: http://www.asp.net/mvc
The advantage of using a web service is that the client can change so that if you decide against Flex in the future or decide to use a Mobile Client then the service will remain the same. Plus, ASP.NET MVC has been proven on some very large sites like SO here.
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Split a block of time if appointments occur within There are two types of time_block - free, appointment - each time_block has a start_time and end_time.
Say I have five appointment time_blocks and two free time_blocks.
I need to create actual free time_blocks that fill with free time between the appointments, like so:
$appointments = array(
array(
'start_time' => 730,
'end_time' => 830),
array(
'start_time' => 830,
'end_time' => 930),
array(
'start_time' => 945,
'end_time' => 1000),
array(
'start_time' => 1045,
'end_time' => 1100),
array(
'start_time' => 1130,
'end_time' => 1145)
);
$free_time_blocks = array(
array(
'start_time' => 900,
'end_time' => 1000),
array(
'start_time' => 1030,
'end_time' => 1200)
);
// Result should be
$actual_free_time = array(
array(
'start_time' => 930,
'end_time' => 945
),
array(
'start_time' => 1030,
'end_time' => 1045
),
array(
'start_time' => 1100,
'end_time' => 1130
),
array(
'start_time' => 1145,
'end_time' => 1200
),
)
A: *
*sort all the appointments by start time
*free slot start with previous appointment slot end time
*free slot ends with start of next appointment slot
I would suggest you to used timestamps.
A: Solution by OP.
Problem solved by trial and error. This is ugly, but it works with every situation I've put it through.
<?php
function getAppointmentsInRange($start_time, $end_time){
$appointments = array(
array(
'start_time' => 730,
'end_time' => 830),
array(
'start_time' => 830,
'end_time' => 930),
array(
'start_time' => 945,
'end_time' => 1000),
array(
'start_time' => 1000,
'end_time' => 1035),
array(
'start_time' => 1035,
'end_time' => 1100),
array(
'start_time' => 1105,
'end_time' => 1125),
array(
'start_time' => 1130,
'end_time' => 1230)
);
foreach($appointments as $appointment){
if($appointment['start_time'] < $end_time && $appointment['end_time'] > $start_time){
$return[] = $appointment;
}
}
return $return;
}
function setFreeTime($start_time, $end_time){
echo "Free Time. Start: $start_time, End: $end_time <br/>";
}
$free_time_blocks = array(
array(
'start_time' => 900,
'end_time' => 1000),
array(
'start_time' => 1030,
'end_time' => 1200)
);
foreach($free_time_blocks as $free_time_block){
// Get appointments with any part falling inside the range (eg. starting before but ending after the start)
$appointments = getAppointmentsInRange($free_time_block['start_time'], $free_time_block['end_time']);
$start_time = $free_time_block['start_time'];
$end_time = $free_time_block['start_time'];
$finished = false;
$i = 0;
foreach($appointments as $appointment){
echo "trying...<br/>";
$next = $i + 1;
$prev = $i - 1;
if($appointment['start_time'] <= $free_time_block['start_time']){
echo "case 1 <br/>";
// If appointment starts before ftb then start ftb at end of appointment, and end at start of next appointment or end of ftb
if($appointment['end_time'] < $free_time_block['end_time']){
$start_time = $appointment['end_time'];
}else{
$start_time = $end_time;
break;
}
if(isset($appointments[$next])){
$end_time = $appointments[$next]['start_time'];
}else{
$end_time = $free_time_block['end_time'];
}
}
elseif($appointment['start_time'] > $free_time_block['start_time']){
echo 'case 2 <br/>';
// If appointment starts during ftb then start ftb at last end time
// Start time = previous end time
if($appointment['end_time'] < $free_time_block['end_time']){
if(isset($appointments[$next])){
$end_time = $appointment['start_time'];
}else{
$end_time = $free_time_block['end_time'];
}
}elseif($start_time < $appointment['start_time']){
if(isset($appointments[$prev])){
$start_time = $appointments[$prev]['end_time'];
}
$end_time = $appointment['start_time'];
}else{
break;
}
}
elseif($appointment['start_time'] == $end_time){
echo "case 3 <br/>";
if($appointment['end_time'] < $free_time_block['end_time']){
$start_time = $appointment['start_time'];
}else{
break;
}
if(isset($appointments[$next])){
$end_time = $appointments[$next]['start_time'];
}else{
$end_time = $free_time_block['end_time'];
}
}
if($start_time != $end_time){
setFreeTime($start_time, $end_time);
$start_time = $end_time;
}
$i++;
}
echo "<hr/>";
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Clearing the State of Fields in InstallOptions pages I'm working on an NSIS installer. One of the requirements is to allow the user to input some information multiple times for multiple different entries (essentially, it allows them to enter server information for as many servers as they'd like). I'm currently recycling the pages by going to this page after my advanced options page:
Function RedirectPage
${If} $addtCheck <> 0 ; Was the checkbox checked?
StrCpy $startedXml 1 ; make this "true"
SendMessage $HWNDPARENT 0x408 -1 "" ; If so, go back
${Else}
Abort
${EndIf}
FunctionEnd
addtCheck checks to see if the checkbox is ticked that recycles the page. If so this function causes the previous page to be displayed again. The problem is that the fields contain the information that the user just entered. Now, what I want to do is to clear the State of all of the fields of the previous page before they go back to it. I have tried doing something like this,
!insertmacro MUI_INSTALLOPTIONS_WRITE "ioAdv.ini" "Field 2" "State" ""
but it doesn't seem to allow me to clear the state. I know of the SendMessage and GetDlgItem commands, but am unaware of any methods that allow me to use them to clear the text boxes, check boxes, and list boxes of contained in the InstallOptions INI file.
Anyone who can point me in the right direction, thanks. If you want to see any more of the script, let me know.
A: So you should have the controls in the ini like this:
[Field 1]
Type=Label
Left=15
Top=7
Right=112
Bottom=16
Text=Text 1
then you can get a handle on the field like this:
ReadIniStr $0 $PLUGINSDIR\page_ini.ini "Field 1" "HWND"
So then you can use the SendMessage command with $0 like this:
SendMessage $0 ${WM_SETTEXT} 0 "STR:$InitialString"
This example should work on Text Boxes, for the other controls see the following:
In the NSIS Installation Path under "Include" there is the File Winmessages.nsh with the Message Keys to use.
In my tests i found the key for setting checkboxes:
SendMessage $0 ${BM_SETCHECK} 0 "0"
For ListBoxes i found: (untested)
LB_RESETCONTENT
LB_SELECTSTRING
Hope that helps.
PS: If you have any questions or critisism, please let me know.
PPS:
Alternatively, you could use the nsDialogs Macros with the HWND handle, i.e. for the Checkbox:
${NSD_Uncheck} $0
More Information to this Macros are here:
nsDialogs Readme - Macros
A: You can use SendMessage to reset each control but then you have to handle different types of controls, it is much better to just reset the .ini:
page custom custdircreate_1
page directory dirpagecreate
Function custdircreate_1
SetOverwrite on
!insertmacro INSTALLOPTIONS_EXTRACT "ioAdv.ini"
SetOverwrite lastused
!insertmacro INSTALLOPTIONS_DISPLAY "ioAdv.ini"
FunctionEnd
Function dirpagecreate
SendMessage $HWNDPARENT 0x408 -1 ""
FunctionEnd
..or reset the state and keep everything else:
Function custdircreate_2
; INSTALLOPTIONS_EXTRACT was called in .onInit
!insertmacro INSTALLOPTIONS_READ $1 "ioAdv.ini" "Settings" "NumFields"
StrCpy $0 1
loop:
!insertmacro INSTALLOPTIONS_WRITE "ioAdv.ini" "Field $0" "State" ""
IntOp $0 $0 + 1
IntCmpU $0 $1 loop loop
!insertmacro INSTALLOPTIONS_DISPLAY "ioAdv.ini"
FunctionEnd
(This will reset link and button controls so filter those out of the loop if required)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Banish unmatched top-level trees when performing tag search in Emacs Org Mode For the past year and a half, I've maintained a monolithic buffer in Org Mode for my engineering notes with my current employer. Despite containing mostly pointers to other documents, this file has become quite large by human standards (48,290 lines of text), while remaining trivially searchable and editable through programmatic means (read: grep and Org Mode tag search).
One thing bothers me, though. When I perform a tag search using Org Mode 6.33x, Org's sparse tree view retains the folded representation of unmatched trees within the buffer (that is, content preceded by a single asterisk, *). This is generally useful for smaller buffers or those better organized into a single tree with multiple branches. However, this doesn't work especially well for documentation where each new tree is generated chronologically, one for each day, as I've been doing.
.
Before I continue, I'll note that my workaround is inherent in what I've just asked, as are the obvious alterations in my documentation habits with this buffer. However, the following questions remain:
1) Why does Org Mode organize trees in this manner when performing sparse tag searching? The technical details are self-evident, the UX decisions less so.
2) If I wished to correct this issue with a script written in Emacs Lisp, what hooks and commands should I explore in more detail to restructure the document view? Writing overrides for the standard commands (for example, org-match-sparse-tree) is already self-evident.
.
Thank you in advance.
A: As you already noticed the problem only affects the top level headings. The good thing is that in org-mode you can demote easily all headings with simple keystrokes. This way you can avoid the problem. Also cleaning up afterwards are just some simple keystrokes.
Step-by-step instructions:
*
*Mark the full buffer
*Call M-right (for outline-demote)
*Input * root\n at the beginning of the file
*Now, build up your subtree and do what you want with it.
*When done you can remove * root\n at the beginning of the file and promote the headings again with M-left
I have got the impression that you can even leave the overall-heading where it is for your application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: TortoiseSVN backup and restore I need to backup repository in TortoiseSVN and move it to a new PC. What are the steps to do create the back up?
I can't find backup option in the menu, the only thing I found was the command-line way:
svnadmin dump C:\SVN\MyProject > C:\tmp\MyProject.bak
I am assuming that C:\SVN\MyProject is the repository directory? If so, I don't know where mine is located and don't know how to find out (no indication is given in the menu at all).
If someone knows how to backup and restore a repository using clear steps that would be great!
EDITED:
My SVN is served with file system
file:///D:/svn/myproject
svnadmin command doesn't work
The easiest and simplest way is appreciated.
A: If you access you repository through svn:// protocol then it means it's served by the svnserve service.
Try to look up that service in the services manager and see the command line used to start it. That command line contains the path to the repository directory on disk. That's the directory you want to back up.
Command line options for svnserve are documented here. You're interested in the root option.
If your repository is served by Apache (http:// protocol) then you can find out the repository path in the Apache configuration files, as described here. Look for SVNPath.
Usually you can just copy the given repository directory to a new PC and point svnserve or Apache to that new directory.
This may not work due to differences in svn versions. Thus you may want to go with dump / load approach documented here.
It's pretty straightforward:
svnadmin dump C:\SVN\MyProject > dumpfile
# copy the dumpfile to a new PC
svnadmin load C:\SVN\MyNewProject < dumpfile
A: All you should need to do is copy the filesytem files of where the actual repository is located. Depending on what is serving your subversion repository (Apache or IIS web servers) there should be a configuration file (apache) or setting (iis) that has the path to the repository in it.
for example I have a repository url like:
https://server/svn01p/svn/Repositories/MyStuff/MyProject/branches/December2011
Whatever web server is processing that url will need to know where the actual repository is located so you should be able to work your way back from there.
A: You don't backup tortoise. You backup the actual repository files, and then you point tortoise to the new location using the "relocate" command in the menu.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is there a way to #define a C macro that is only defined while in an Eclipse editor window? I'm using Eclipse Galileo with CDT for C development targeting embedded devices.
Like so many other compilers targeted at µcontrollers, the IAR compiler uses some non-standard variable types that Eclipse/CDT doesn't recognize and flags them as problems. Since these variable types are the foundations of other variable types I use the problem cascades to the point that just about every line using variables declared with the non-standard types are flagged as having syntax problems, even when the syntax is correct. It's not a critical problem, but it is definitely a nuisance.
*
*Is there a setting within Eclipse/CDT where I can add non-standard syntax, or...
*Is there some predefined macro within Eclipse/CDT that I can access with something like #ifdef SECRET_ECLIPSE_MACRO ... for conditionally setting or clearing a macro with the string of the offending variable type definition?
A: Well, you can go the other way around. Define a NOT_ECLIPSE macro when you compile your code, and check for its non-existence in your code. If it's not defined, you're in Eclipse.
A:
Is there some predefined macro within Eclipse/CDT that I can access
Yes, there are many.
See this page.
http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.cdt.doc.user/reference/cdt_u_prop_build_variables.htm
Don't forget to check the 'SHow system variables' option.
A: __CDT_PARSER__
is defined during CDT editor preprocessing stage (works at least with Indigo SR2)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How would I make a program to monitor another system's vitals with a remote connection? I'm looking to write a custom program in VB.NET / C++ / C# that would allow me to monitor a system's vitals over a Remote Desktop Connection.
I'm only looking for tips on how to implement a connection like this in code (eg. is it just a simple object or call to a WScript function? or is it much more sophisticated?). As to the specifics of operation after making the connection, I have that figured out based on another program which shares some similar features.
I would definitely look on Google and self-teach this, but I don't even know where to begin / what to search for. Some advice into this would be amazing, thanks!
EDIT: This doesn't have to go through an RDP connection, I'm definitely looking for better ways. Reason I mention RDP is because I currently do this manually over an RDP connection, but I don't wanna have to constantly open the window.
A: I don't think the RDP protocol is the right solution for this. Other mechanisms were invented for this, such as WMI.
WMI is a scriptable interface that allows you to query the local or remote computer's information. You can use your tool of choice - C#, VBScript, or my personal preference - Powershell. Here is an example of how to get all of the processes on a remote machine.
EDIT:
This doesn't have to go through an RDP connection, I'm definitely looking for better ways. Reason I mention RDP is because I currently do this manually over an RDP connection, but I don't wanna have to constantly open the window.
Then ignore everything below the line. Really.
The RDP protocol is very specialized for sharing specific resources. Namely the screen, disks, clipboard, printer, ports, and sound. That's it for what's out-of-the-box. The best thing you could possibly do is occasionally monitor the contents of a file with the RDP protocol - and it is cumbersome and slow.
I'd encourage you to look at alternative solutions like WMI instead.
That said, it is possible to do this with RDP's support for Virtual Channels. You could create a scriptable virtual channel to accomplish this (which is no easy feat). You would have to write a client and server. Your server side functionality would report the information you are interested in monitoring, and the client side would receive it. Again, I would stress that this is not the correct solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Vtiger: I can't add a To Do event If I got to calendar, click on To Do, then try to add an event, the form pops up, I fill it out, press save, but no Event gets added.
In the SQL error log's I see an error like this:
2011-09-29 14:57:07 EDT ERROR: null value in column "visibility" violates not-null constraint
2011-09-29 14:57:07 EDT STATEMENT: insert into
vtiger_activity(activityid,subject,date_start,time_start,time_end,due_date,status,eventstatus,priority,sendnotification,activitytype,visibility,duration_hours,duration_minutes,location,recurringtype,notime)
values('235','Testing','2011-09-29','19:50',NULL,'2011-09-29','Not Started',NULL,'High','0','Task',NULL,NULL,NULL,NULL,NULL,'0')
So, for some reason, it is trying to add a To-Do while inserting null values. My biggest problem is that I cannot locate the origin of the query. So, basically, the most important thing I am asking is what file takes the data that was input into the todosave form and turns it into a query.
I don't know if many people on here use Vtiger, but I couldn't figure this out so I went ahead and posted anyway. The official documentation is not very helpful in my opinion.
Thanks for everything, have a good day.
A: This might be an isolated case, but was any of the modules modified recently? In this case, I would assume that it would be the Calendar module. I've tested this on the demo website and on my vTiger installation and it works fine..
Perhaps you can download a fresh copy of vTiger and replace the modules/Calendar all its content.
By the way, another place to ask if you have any questions, is the vTiger forums.
http://forums.vtiger.com/index.php
Usually you can ask it in the Help - 5.2.1 section. Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C++ std::string and string I don't suppose anyone tell me whats the difference between using the std::string and just the string data type in C++??
In what situation should the std::string should be used over the standard string??
Thanks.
A: They're both the same type. std::string specifies the namespace, while string only makes sense if a using namespace std; or using std::string statement is used. So it doesn't make any difference what you use (as long as you're consistent).
If you're talking about the string literals (such as "hello"), then they're of type const char [], that implicitly decays in a const char *. std::string has a non-explicit constructor that takes a const char *, this allowing implicit conversion from const char * to std::string. The opposite operation can be done with the std::string::c_str() method.
If you're looking for a reason to use std::string instead of const char *, then I guess my answer would be "as much as you can".
A: These are likely the same thing within your program. The "standard" string resides within the "std" namespace. If you are "using std::string;" or "using namespace std;" within the module, then they are equivalent. If you aren't specifying a "using" statement, then you are required to provide the namespace of the object. It's preferable to not provide "using" statements within the header file and therefore you will typically see namespace resolution/specifiers on objects. (i.e. std::vector, mynamespace::myclass, etc.). The use of "using" is more common in implementation files where they won't affect other files as they would if specified in a header file.
It's possible to use a string object from another provider. In this case the provider would/should have their string object implementation in their own namespace and you would need to declare which string object you were using.
So:
File: stdString.cpp
-------------
#include <string>
#include "providerx/string.h"
using namespace std;
void foo()
{
string x; // Using string object provided by the C++ standard library
std::string y; // Again, using C++ standard lib string
providerx::string // Using string object defined within the providerx namespace
}
File: providerString.cpp
-------------------
#include "providerx/string.h"
using providerX::string;
void foo()
{
string x; // Using providerx string object
}
A: Most likely, you have using namespace std somewhere in your code. This is allowing you to access members of the std namespace without resolving the scope. Therefore...
std::string == string
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Regex? Search Engine? I've read through some documentation on the re module that comes with built-in python, but I just can't seem to get a grasp on it. In fact, I'm not exactly sure that is what I'm looking for, so let me explain:
I have a huge dictionary. What I want is to be able to type in a search criteria, let's say for example hello, and then have it search through the dictionary and give me a list like this:
hello, hell, hello world, hello123. Basically anything resembling the search criteria. Would I use regex for this or something else?
A: Since you are using Python, you should look at Xapian, it had great Python bindings.
What you are asking for is way more sophisticated that what regular expressions are for.
You need full text search, with stemming and other tricks to do the fuzzy matching.
A: You might want to look at something that can compute a Levenshtein (edit) distance. There's an excellent article here on how to build something like you are talking about from scratch (in Python! well and it has been ported to lots of other languages).
You might not want to go the "from-scratch" route, but the article will give you lots of interesting background that should help you decide which tool has the right level of sophistication for you. Xapian, as suggested above, Lucene, and other full-text search engines will provide this kind of capability, and it can be very sophisticated, but then again you might not need all that.
A: There is a new regexp module in PyPI repository (which will possibly replace the current Python re module sometimes).
It allows fuzzy matching.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sphinx indexer delta --rotate I have followed the sphinx manual here: http://sphinxsearch.com/docs/current.html#delta-updates on how to perform delta updates to your index.
my searchd is running of the correct config file.
the indexer was previously ran to create the main index.
when I run this command:
indexer -c /home/brandon/workspace/gallery/server/lib/sphinx/sphinx.conf --rotate delta
I get this result:
using config file '/home/brandon/workspace/gallery/server/lib/sphinx/sphinx.conf'...
read 0.1 of 0.1 MB, 100.0% done
merged 10.8 Kwords
merged in 0.010 sec
total 389 reads, 0.000 sec, 2.0 kb/call avg, 0.0 msec/call avg
total 7 writes, 0.000 sec, 78.6 kb/call avg, 0.0 msec/call avg
rotating indices: succesfully sent SIGHUP to searchd (pid=28039).
Everything looks as though it worked, and the main index should have been updated. I then go to my search bar, but it has not been updated as I can't search for the new item.
Any suggestions?
A: Make sure you search using both (main and delta) indexes in your app.
Delta index is just another index, so basically when you reindex delta index, it adds nothing to the main index. So your app should search in both indexes (main, delta).
A: My suggestion is simple.
Write a simple program to index it frequently and after that restart sphinx service ( searchd ).
The results would come out.
Make sure you include both main and index in the api code. ( $index = "main,delta"; )
you may follow my instruction in the previous answer here: Does Sphinx auto update is index when you add data to your SQL?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Structural type in method type parameterization in Scala? Consider the following Scala code (e.g., in REPL)
object A{def foo:Unit = {}}
object B{def foo:Unit = {}}
def bar[T <: Any {def foo: Unit}](param: T*):Unit = param.foreach(x => x.foo)
bar(A, A) // works fine
bar(B, B) // works fine
bar(A, B) // gives error
The first two work fine. The third ones gives an error:
error: inferred type arguments [ScalaObject] do not conform to method bar's type parameter bounds [T <: Any{def foo: Unit}]
Are there any ways to do what I want?
A: This is usually called structural typing, not duck typing. I edited your title. :)
I think that your problem is caused by defining the type parameter T and then using it in an invariant way. T can only refer to one concrete type, but you have parameters of different types A and B.
This works:
def bar(param: {def foo: Unit}*) = param.foreach(x => x.foo)
Edit: Using a type alias also works:
type T = {def foo: Unit}
def bar(param: T*) = param.foreach(x => x.foo)
This works because the compiler will simply substitute the structural type in place of its alias, T. After the substitution, this example is exactly the same as the one above.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Windows EXE can run as service or application. How can I determine if it is running as a service or not? I am looking for a Win32 API call to return the runtime context of my process. I want to be able to programmatically test if I am running as a service or am I running as standard application process.
Several ideas come to mind.... Since I always have service DAD.exe who runs SON.exe sometimes as his child and in service context --- and sometimes SON.exe is started not by DAD, and by a user.
SON.EXE would do API whoami() to learn which context he is running in.
Now DAD could create an environment var -- and then SON could test for this var -- and if found he knows he is a son of DAD and thus runnning as a service..... But this is weak...
Another idea would be to look at my SID or token and see if I could make this determination.... Again this looks at best more complex vs. a single API check...
A: The simple low-tech solution to this is to register your service to run with command line arguments that identify it as a service.
A: Another option is to use the Tool Help library. Using it, you take a snapshot of all the currently running processes and then you can walk through all the processes using the Process32First and Process32Next function. These return a structure (PROCESSENTRY32) that looks like:
typedef struct tagPROCESSENTRY32 {
DWORD dwSize;
DWORD cntUsage;
DWORD th32ProcessID;
ULONG_PTR th32DefaultHeapID;
DWORD th32ModuleID;
DWORD cntThreads;
DWORD th32ParentProcessID;
LONG pcPriClassBase;
DWORD dwFlags;
TCHAR szExeFile[MAX_PATH];
} PROCESSENTRY32, *PPROCESSENTRY32;
as you walk through all the processes, as soon as you find the one whose th32ProcessID matches the one for SON.exe (see GetCurrentProcessId or GetProcessId ). If the th32ParentProcessID of that structure matches that of DAD.exe, then you know you were launched from DAD.exe.
Edit:
Answering your comment, I guess you could go one step further and then see who the parent of DAD.exe is, if it's services.exe, then you're a service.
A: Reading the documentation, I think you could determine whether you're in an interactive session or service via:
*
*GetProcessWindowStation
*GetUserObjectInformation(UOI_FLAGS)
and then WSF_VISIBLE should tell you.
If you wanted to differentiate between a logged-in user session and one that's inactive (Fast User Switching), I guess you could use GetThreadDesktop and GetUserObjectInformation(UOI_IO).
The best and simplest way to tell from inside the service is to set a flag when ServiceMain is called. But you're testing a child process, so see above.
A: I found the following:
bool WinUtil::IsServiceUser(HANDLE hToken, bool *is_service) {
if (is_service == NULL) {
return false;
}
TOKEN_STATISTICS ts;
DWORD dwSize = 0;
// Use token logon LUID instead of user SID, for brevity and safety
if (!::GetTokenInformation(hToken, TokenStatistics,
(LPVOID)&ts, sizeof(ts), &dwSize)) {
return false;
}
// Compare LUID
const LUID SystemLuid = SYSTEM_LUID;
const LUID LocalServiceLuid = LOCALSERVICE_LUID;
const LUID NetworkServiceLuid = NETWORKSERVICE_LUID;
if (EqualLuid(SystemLuid, ts.AuthenticationId) ||
EqualLuid(LocalServiceLuid, ts.AuthenticationId) ||
EqualLuid(NetworkServiceLuid, ts.AuthenticationId)) {
*is_service = true;
return true;
}
// Not a service account
*is_service = false;
return true;
}
bool WinUtil::IsServiceProcess(bool *is_service) {
if (is_service == NULL) {
return false;
}
if (Util::IsVistaOrLater()) {
// Session 0 is dedicated to services
DWORD dwSessionId = 0;
if (!::ProcessIdToSessionId(::GetCurrentProcessId(), &dwSessionId) ||
(dwSessionId == 0)) {
*is_service = true;
return true;
}
}
// Get process token
HANDLE hProcessToken = NULL;
if (!::OpenProcessToken(::GetCurrentProcess(),
TOKEN_QUERY | TOKEN_QUERY_SOURCE,
&hProcessToken)) {
return false;
}
ScopedHandle process_token(hProcessToken);
// Process token is one for a service account.
if (!IsServiceUser(process_token.get(), is_service)) {
return false;
}
return true;
}
A: I think your looking for Topshelf http://topshelf-project.com/, it does the heavy lifting and makes it easier run as console or install as a service. Topshelf hosting application debugging in VS2010
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How do I reorder a vector during a Thrust transformation? How could i transform this simple code to thrust code?
for (i=0;i<cA-rA;i++)
sn[i]=c[n_index[i]]-sn[i];
More Info:
cA and rA are const integers so we can concider as an 'n'= cA-rA
sn : array of float(n)
n_index : array of int(n)
c : array of float(cA)
My problem is with the n_index[i] that points to the element of the C array.
thank you!
A: You can implement this by fusing thrust::transform with a "gather" operation using a permutation_iterator:
#include <thrust/device_vector.h>
#include <thrust/iterator/permutation_iterator.h>
#include <thrust/transform.h>
#include <thrust/sequence.h>
#include <thrust/functional.h>
int main()
{
size_t n = 100;
// declare storage
thrust::device_vector<int> sn(n);
thrust::device_vector<int> n_index(n);
thrust::device_vector<int> c(n);
// initialize vectors with some sequential values for demonstrative purposes
thrust::sequence(sn.begin(), sn.end());
thrust::sequence(n_index.begin(), n_index.end());
thrust::sequence(c.begin(), c.end());
// sn[i] = c[n_index[i]] - sn[i]
thrust::transform(thrust::make_permutation_iterator(c.begin(), n_index.begin()),
thrust::make_permutation_iterator(c.end(), n_index.end()),
sn.begin(),
sn.begin(),
thrust::minus<int>());
return 0;
}
A: I tried the first one and wasn't getting the correct results. the second permutation_iterator needs to be at the end of BOTH vectors.
Try the following correction:
// sn[i] = c[n_index[i]] - sn[i]
thrust::transform(thrust::make_permutation_iterator(c.begin(), n_index.begin()),
thrust::make_permutation_iterator(c.end(), n_index.end()),
sn.begin(),
sn.begin(),
thrust::minus<int>());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Notepad++ incrementally replace Lets say I want to have a 10 rows of data but I want a value to increment for each row or piece of data. How do I increment that value?
For example....If I have these rows, is there a regex way of replacing the id values to increment?
<row id="1" />
<row id="1" />
<row id="1" />
<row id="1" />
<row id="1" />
--- Here is what I would like it to look like... (if the first row's id goes up one thats ok)
<row id="1" />
<row id="2" />
<row id="3" />
<row id="4" />
<row id="5" />
A: Since there are limited real answers I'll share this workaround. For really simple cases like your example you do it backwards...
From this
1
2
3
4
5
Replace \r\n with " />\r\n<row id=" and you'll get 90% of the way there
1" />
<row id="2" />
<row id="3" />
<row id="4" />
<row id="5
Or is a similar fashion you can hack about data with excel/spreadsheet. Just split your original data into columns and manipulate values as you require.
| <row id=" | 1 | " /> |
| <row id=" | 1 | " /> |
| <row id=" | 1 | " /> |
| <row id=" | 1 | " /> |
| <row id=" | 1 | " /> |
Obvious stuff but it may help someone doing the odd one-off hack job to save a few key strokes.
A: http://docs.notepad-plus-plus.org/index.php/Inserting_Variable_Text
Notepad++ comes equipped with a Edit -> Column "Alt+C" Editor which can work on a rectangular selection in two different ways: Coledit.png
inserting some fixed text on every line including and following the current line, at the column of the insertion point (aka caret). Initially selected text is left untouched.
As the picture illustrates, a linear series of numbers can be inserted in the same manner. The starting value and increment are to be provided. Left padding with zeroes is an option, and the number may be entered in base 2, 8, 10 or 16 - this is how the computed values will be displayed too, padding being based on the largest.
A: Solutions suggested above will work only if data is aligned..
See solution in the link using PythonScript Notepad++ plugin, It Works great!
stackoverflow Find/Replace but Increment Value
A: You can do it using Powershell through regex and foreach loop, if you store your values in file input.txt:
$initialNum=1; $increment=1; $tmp = Get-Content input.txt | foreach { $n = [regex]::match($_,'id="(\d+)"').groups[1
].value; if ($n) {$_ -replace "$n", ([int32]$initialNum+$increment); $increment=$increment+1;} else {$_}; }
After that you can store $tmp in file using $tmp > result.txt. This doesn't need data to be in columns.
A: I was looking for the same feature today but couldn't do this in Notepad++. However, we have TextPad to our rescue. It worked for me.
In TextPad's replace dialog, turn on regex; then you could try replacing
<row id="1"/>
by
<row id="\i"/>
Have a look at this link for further amazing replace features of TextPad -
http://sublimetext.userecho.com/topic/106519-generate-a-sequence-of-numbers-increment-replace/
A: Not sure about regex, but there is a way for you to do this in Notepad++, although it isn't very flexible.
In the example that you gave, hold Alt and select the column of numbers that you wish to change. Then go to Edit->Column Editor and select the Number to Insert radio button in the window that appears. Then specify your initial number and increment, and hit OK. It should write out the incremented numbers.
Note: this also works with the Multi-editing feature (selecting several locations while maintaining Ctrl key pressed).
This is, however, not anywhere near the flexibility that most people would find useful. Notepad++ is great, but if you want a truly powerful editor that can do things like this with ease, I'd say use Vim.
A: i had the same problem with more than 250 lines and here is how i did it:
for example :
<row id="1" />
<row id="1" />
<row id="1" />
<row id="1" />
<row id="1" />
you put the cursor just after the "1" and you click on alt + shift and start descending with down arrow until your reach the bottom line now you see a group of selections click on erase to erase the number 1 on each line simultaneously and go to Edit -> Column Editor and select Number to Insert then put 1 in initial number field and 1 in incremented by field and check zero numbers and click ok
Congratulations you did it :)
A: (Posting in case someone might have a use of it).
I was looking for a solution for a problem a bit more sophisticated than OP - replacing EVERY occurrence of something with the number by same thing with incremented number
E.g. Replacing something like this:
<row id="1" />
<row id="2" />
<row id="1" />
<row id="3" />
<row id="1" />
By this:
<row id="2" />
<row id="3" />
<row id="2" />
<row id="4" />
<row id="2" />
Couldnt find the solution online so I wrote my own script in groovy (a bit ugly but does the job):
/**
* <p> Finds words that matches template and increases them by 1.
* '_' in word template represents number.
*
* <p> E.g. if template equals 'Row="_"', then:
* ALL Row=0 will be replaced by Row="1"
* All Row=1 will be replaced by Row="2"
* <p> Warning - your find template might not work properly if _ is the last character of it
* etc.
* <p> Requirments:
* - Original text does not contain tepmlate string
* - Only numbers in non-disrupted sequence are incremented and replaced
* (i.e. from example below, if Row=4 exists in original text, but Row=3 not, than Row=4 will NOT be
* replaced by Row=5)
*/
def replace_inc(String text, int startingIndex, String findTemplate) {
assert findTemplate.contains('_') : 'search template needs to contain "_" placeholder'
assert !(findTemplate.replaceFirst('_','').contains('_')) : 'only one "_" placeholder is allowed'
assert !text.contains('_____') : 'input text should not contain "______" (5 underscores)'
while (true) {
findString = findTemplate.replace("_",(startingIndex).toString())
if (!text.contains(findString)) break;
replaceString = findTemplate.replace("_", "_____"+(++startingIndex).toString())
text = text.replaceAll(findString, replaceString)
}
return text.replaceAll("_____","") // get rid of '_____' character
}
// input
findTemplate = 'Row="_"'
path = /C:\TEMP\working_copy.txt/
startingIndex = 0
// do stuff
f = new File(path)
outText = replace_inc(f.text,startingIndex,findTemplate)
println "Results \n: " + outText
f.withWriter { out -> out.println outText }
println "Results written to $f"
A: You can use this very similar script in Python. It is a very good code. Just change $item_id = abc; with your <row id="abc" /> (in your case)
import os
import re
def read_text_from_file(file_path):
"""
Aceasta functie returneaza continutul unui fisier.
file_path: calea catre fisierul din care vrei sa citesti
"""
with open(file_path, encoding='utf8') as f:
text = f.read()
return text
def write_to_file(text, file_path):
"""
Aceasta functie scrie un text intr-un fisier.
text: textul pe care vrei sa il scrii
file_path: calea catre fisierul in care vrei sa scrii
"""
with open(file_path, 'wb') as f:
f.write(text.encode('utf8', 'ignore'))
def incrementare_fisiere_html(cale_folder_html):
"""
Functia itereaza printr-un folder care contine fisiere html si adauga index-ul corespunzator in fiecare fisier
"""
count = 0
current_id = 1
for f in os.listdir(cale_folder_html):
if f.endswith('.html'):
cale_fisier_html = cale_folder_html + "\\" + f
html_text = read_text_from_file(cale_fisier_html)
item_id_pattern = re.compile('\$item_id = (.*?);')
item_id = re.findall(item_id_pattern, html_text)
if len(item_id) > 0:
print("{} a fost modificat. ".format(f))
item_id = item_id[0]
html_text = html_text.replace(item_id, str(current_id))
current_id += 1
count += 1
write_to_file(html_text, cale_fisier_html)
else:
# print("{} nu are $item_id.".format(f))
continue
else:
continue
print("Numarul de fisiere modificate: ", count)
if __name__ == '__main__':
# sa pui calea catre folderul cu fisiere
incrementare_fisiere_html('e:\\Folder1')
The explanation and SOURCE code CLICK HERE:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "100"
}
|
Q: How do I set XAML Elements from C# code? So i have wpf application and my xaml looks like this:
<Window x:Class="MyTest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:MyTest.Layouts"
xmlns:pl="clr-namespace:Planerator"
Title="CardView" Topmost="False" AllowsTransparency="True" WindowStyle="None" WindowState="Maximized" ShowInTaskbar="False">
<Grid>
<pl:Planerator x:FieldModifier="public" x:Name="FrontProjection" Margin="240" >
<my:FrontLayout />
</pl:Planerator>
<pl:Planerator x:FieldModifier="public" x:Name="BackProjection" Margin="240" >
<my:BackLayout />
</pl:Planerator>
</Grid>
<Window.Background>
<SolidColorBrush />
</Window.Background>
</Window>
Is there a way to set the <my:FrontLayout /> and <my:FrontLayout /> for the Planerators inside my C# code?
EDIT:
Planerator: http://blogs.msdn.com/b/greg_schechter/archive/2007/10/26/enter-the-planerator-dead-simple-3d-in-wpf-with-a-stupid-name.aspx
And the FrontLayot and BackLayout -s are just simple xaml layouts.
EDIT2: The reason why i need to set them from code is that i want o use conditional compilasion. because for example for DEBUG it should be <my:DebugFrontLayer /> .
A: Give them names, e.g.
<my:FrontLayout Name="FrontLayout1" />
and then they should be accessible from C# as variables of that name.
A: Looking at the Planerator class you'll see it has the ContentPropertyAttribute set:
[ContentProperty("Child")]
public class Planerator : FrameworkElement
{
}
This means that
<pl:Planerator x:FieldModifier="public" x:Name="FrontProjection" Margin="240" >
<my:FrontLayout />
</pl:Planerator>
Actually does this:
<pl:Planerator x:FieldModifier="public" x:Name="FrontProjection" Margin="240" >
<pl:Planerator.Child>
<my:FrontLayout />
</pl:Planerator.Child>
</pl:Planerator>
Which also means that from code-behind, for example in the constructor of MyTest, or anywhere else really, you could do the following to achieve the same:
public MyTest()
{
InitializeComponent();
FrontProjection.Child = new FrontLayout();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GetFileSizeEx fails for file mapping Im having trouble creating a named shared memory and inspecting its size. The function GetFileSizeEx fails when I call it in a function like this. Any ideas on how to debug this?
void test_getsize(const char* lpName, int size){
HANDLE handle = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
size, // maximum object size (low-order DWORD)
lpName); // name of mapping object
if (handle== NULL || handle== INVALID_HANDLE_VALUE){
last_error = get_error_from_errorno();
*error_return =1;
}
LARGE_INTEGER new_size;
err = GetFileSizeEx(handle, &new_size);
if (err==0){ printf("err ");} else {printf("pass ");}
printf("size=%lu\n", (unsigned long)new_size.QuadPart);
}
A: The handle you pass to GetFileSizeEx must be a handle to a file. You are passing it a handle to a file mapping, which is a completely different thing, so it won't work.
Since apparently you want the size of the file mapping (called a section object), and I don't think the Win32 API provides this feature, you would need to use the native Windows API called NtQuerySection. Here's an idea of how it might work (I haven't tried it):
typedef enum _SECTION_INFORMATION_CLASS
{
SectionBasicInformation,
SectionImageInformation
} SECTION_INFORMATION_CLASS;
typedef struct _SECTION_BASIC_INFORMATION {
PVOID Base;
ULONG Attributes;
LARGE_INTEGER Size;
} SECTION_BASIC_INFORMATION;
typedef DWORD (WINAPI* NTQUERYSECTION)
(HANDLE, SECTION_INFORMATION_CLASS, PVOID, ULONG, PULONG);
NTQUERYSECTION NtQuerySection =
(NTQUERYSECTION)GetProcAddress(LoadLibrary("ntdll.dll"), "NtQuerySection");
SECTION_BASIC_INFORMATION SectionInfo = { 0 };
NTSTATUS = NtQuerySection(handle, SectionBasicInformation, &SectionInfo,
sizeof(SectionInfo), 0);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CSS JS(maybe) Div scroll bars show and hide I have an autocomplete search that I want to be 40% of the screen then scroll the rest.
I have that part working fine, my problem is the scroll bar always shows, regardless if there is overflow. I want the vertical scroll to be hidden if there are only, say, 2 results returned. Then if there are 50 it shows.
Here is what I have:
HTML:
<div id="AccountSearchResultsContainer">
<div id="AccountSearchResults">
</div>
</div>
CSS:
#AccountSearchResults {
border: 2px solid #666;
margin: 0px auto;
width: 100%;
display: none;
}
#AccountSearchResultsContainer {
border-bottom: 2px solid #666;
margin: 0px auto;
width: 54%;
height: 40%;
overflow: scroll;
overflow-x: hidden;
display: none;
padding-right: 4px;
}
Will I have to write a script to determine the screen height AccountSearchResultContainer, and the height of AccountSearchResult...if ASR > ASRC then show scroll bar or is there a way to achieve this with CSS?
A: I think this can be done when you change
overflow: scroll;
overflow-x: hidden;
to
overflow: auto;
overflow-x: hidden;
or simply
overflow-y: auto;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Galaxy Tab 10.1 usable screen resolution (- the menu bar) I know that the screen resolution is 1280×800px but Honeycomb's bottum menu bar makes this a tad smaller, but how much smaller?
Has google published the height of the menubar? (the one that can't be taken away as it has the home/back etc buttons)
I want to know this because when I draw a fullscreen background for the Tab I want to know the exact size as to get a pixel perfect result.
A: The height of the menu bar on Honeycomb is 48 pixels, for devices with 1280x800 pixels at least.
A: Yes its 48 on Samsung Galaxy P7500 10.1
A: Use http://supportdetails.com/ to find out the size. Remember. You can rotate a tablet!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How come the only value ever entered in the SQL Server field is 0? I have two tables csvtemp and leads in both tables i have a is_download field and i am moving data from one table to another
First i insert into the csvtemp table with this
CREATE TABLE CSVTemp
(id INT,
firstname VARCHAR(255),
lastname VARCHAR(255),
department VARCHAR(255),
architecture VARCHAR(255),
phone VARCHAR(255),
email VARCHAR(255),
download VARCHAR(255),
comments VARCHAR(MAX),
company VARCHAR(255),
location VARCHAR(255),
is_download VARCHAR(255)
)
GO
BULK
INSERT CSVTemp
FROM 'c:\leads\leads.csv'
WITH
(
DATAFILETYPE = 'char',
BATCHSIZE = 50,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO
--Check the content of the table.
SELECT *
FROM CSVTemp
GO
i then checked the csvtemp table and here is my data so far
id,firstname,lastname,department,architecture,phone,email,download,comments,company,location,is_download
258,sdf,ssss,NULL,NULL,951-5566,kate@gmail.com,"Aldelo for Restaurants","I am just looking right now. When I get ready to purchasing I will contact you.","my Diner","Aldelo for Restaurants demo download",1
274,Scott,Henry,sales,NULL,485-755-7439,aerf99@comcast.net,NULL,"Need a POS cash registering system that can help us.","The Attak","Contact Us: Contact Form",0
275,Test,Tstt,NULL,NULL,8566778888,test@test.com,"Aldelo for Restaurants",testing,Staction,"Aldelo for Restaurants demo download",1
so far so good the 1 and 0 is being entered in the is_download field as expected but when i do this next stell to move it from csvtemp to the leads table its 0
INSERT INTO [SalesLogix].[sysdba].[LEAD] (
LEADID,
ASSIGNDATE,
COMPANY_UC,
EMAIL,
ISDOWNLOAD,
WORKPHONE)
SELECT
'Q' + cast(floor(999997 * RAND(convert(varbinary, newid()))) as varchar(20)) + cast(floor(999 * RAND(convert(varbinary, newid()))) as varchar(20))
,CURRENT_TIMESTAMP
,replace(UPPER(company), '"', '')
,replace(email, '"', '')
,is_download
,replace(phone, '"', '')
FROM [SalesLogix].[sysdba].[CSVTemp]
everything else inserts fine but the is_download is always 0
BTW the ISDOWNLOAD in the leads table is varchar (80)
UPDATE...
here are some records in the leads table...i could not get the three froom earlier because they were deleted but here is what all look like the ISDOWNLOAD is 0
LEADID CREATEUSER CREATEDATE MODIFYUSER MODIFYDATE ACCOUNTMANAGERID ASSIGNDATE BUSINESSDESCRIPTION COMPANY COMPANY_UC CREDITRATING DATAQUALITY DESCRIPTION DIVISION DONOTSOLICIT EMAIL EMPLOYEES FAX FIRSTNAME HOMEPHONE IMPORTID IMPORTSOURCE INDUSTRY INTERESTS ISPRIMARY LASTCALLDATE LASTNAME LASTNAME_UC LEADSOURCEID MIDDLENAME MOBILE NEXTCALLDATE NOTES PREFERRED_CONTACT PREFIX PRIORITY QUALIFICATION_CATEGORYID REVENUE SECCODEID SICCODE STATUS SUFFIX TICKER TITLE TOLLFREE TYPE ISDOWNLOAD USERFIELD2 USERFIELD3 USERFIELD4 USERFIELD5 USERFIELD6 USERFIELD7 USERFIELD8 USERFIELD9 USERFIELD10 WEBADDRESS WORKPHONE LEAD_ADDRESSID DONOTEMAIL DONOTFAX DONOTMAIL DONOTPHONE
Q102842996 U6UJ9A00000S 36:10.1 U6UJ9A00000G 31:27.0 U6UJ9A00000G 36:10.1 NULL Lunch Money LUNCH MONEY NULL NULL NULL NULL 0 shane.hubbell@gmail.com NULL NULL Shane NULL NULL NULL sales Contact Us: Contact Form T NULL Hubbell HUBBELL L6UJ9A000004 NULL NULL NULL Interested in your software more than your hardware. Please email first and well setup some time to chat. NULL NULL NULL NULL NULL SYST00000001 NULL New NULL NULL NULL NULL NULL 0 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 5185705656 QQ102842996 NULL NULL NULL NULL
Q103999935 U6UJ9A00000S 06:10.2 U6UJ9A00000E 53:43.0 U6UJ9A00000E 06:10.2 NULL Alajamy ALAJAMY NULL NULL NULL NULL 0 sfgsd@hotmail.fr NULL NULL Nizar NULL NULL NULL NULL Aldelo for Restaurants demo download T NULL Ben Ali BEN ALI L6UJ9A000002 NULL NULL NULL NULL NULL NULL NULL NULL NULL SYST00000001 NULL Follow-up NULL NULL NULL NULL NULL 0 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL QQ103999935 NULL NULL NULL NULL
Q109565345 U6UJ9A00000S 36:10.1 U6UJ9A00000G 00:20.0 NULL 36:10.1 NULL NULL NULL NULL NULL NULL NULL 0 NULL NULL NULL NULL NULL NULL NULL NULL NULL T NULL NULL NULL L6UJ9A000004 NULL NULL NULL NULL NULL NULL NULL NULL NULL SYST00000001 NULL Purge NULL NULL NULL NULL NULL 0 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL QQ109565345 NULL NULL NULL NULL
Q11143312 U6UJ9A00000S 06:10.1 U6UJ9A00000G 10:27.0 U6UJ9A00000G 06:10.1 NULL Noobs NOOBS NULL NULL NULL NULL 0 fdfgsd@gmail.com NULL NULL Eduardo NULL NULL NULL NULL Aldelo for Restaurants demo download T NULL Torres TORRES L6UJ9A000004 NULL NULL NULL NULL NULL NULL NULL NULL NULL SYST00000001 NULL New NULL NULL NULL NULL NULL 0 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL QQ11143312 NULL NULL NULL NULL
ANOTHER EDIT after running SELECT '$$' + is_download + '$$' FROM CSVTemp
$$1 $$
$$0 $$
$$1 $$
A: Using only the code you posted and an insert statement to replace the BULK INSERT (which does not seem to be the problem), I am able to create rows in CSVTemp that translate correctly to the LEAD table.
Something else must be going on. Check to make sure the LEAD table doesn't have any triggers on it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Double loop with random sampling I wanted to generate score i (0:36) with frequency j. I wanted j loop to be random numbers. What I did was:
j<-1:70
for(i in 0:36) {
for (j in 1:sample(j)) {
print(i,j)
}
}
But I got error. Should have I put sample(j,1, replacement=TRUE) instead of just sample(j)?
thank you
A: If I understand correctly, you want each element in i replicated from one to 70 times (randomly choosing the number of times to replicate the value).
i <- 0:36
j <- 1:70
#number of times to replicate each i
times <- sample(j, length(i), replace=FALSE)
result <- rep(i, times)
Whether to use replace=FALSE or not depends on how you'd like the sampling done (e.g. replace=FALSE assures that each j is chosen at most one time.
A: If you want a random number, you should use runif. It has min/max to control the range. You can also use sample, but then it's better to use sample.int(max, 1)
j<-70
for(i in 0:36) {
for (k in 1:runif(1,1,j)) {
cat(i,k, "\n")
}
}
Then the inner loop shouldn't overwrite j (which should be a constant) - so I renamed the loop variable to k.
...and print doesn't print multiple args like that - but cat does!
A: Try
for(i in 0:36) {
for(k in 1:sample(70, 1)) {
print(c(i,k))
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Fire comboBox SelectedIndexChanged only from user click I wrote a method to handle a comboBox's SelectedIndexChanged event.
In the constructor I populated the comboBox, and this activated my event-handling method. Which I don't want since nobody clicked on the comboBox.
Is there an easy way to get the comboBox not to fire the event unless the user clicked it?
If that is not possible, is there a way to disconnect the event to the method temporarily? Could I just set "my_combo.SelectedIndexChanged = null" and then create a new System.EventHandler?
Or I guess I could create some kind of boolean member variable that I can switch on or off and put a branch check in my method. That seems like a kludge, though.
A: You can use both methods You proposed:
*
*use boolean variable
*detach event method, populate combobox, attach event method like this
my_combo.SelectedIndexChanged -= my_Combo_SelectedIndexChanged;
populateCombo();
my_combo.SelectedIndexChanged += my_Combo_SelectedIndexChanged;
my_Combo_SelectedIndexChanged is the name of method you attached to the event.
A: I would use control.ContainsFocus instead of creating other bool. The caveat here is that you have to make sure the user has focus on that control. Either by key or mouse.
if(combo.ContainsFocus){ MyEventLogic();}
A: I have done it a lot number of times.
Solution1: Delete EventHandler from designer. Populate the combobox and then set EventHandler.
Combo1.SelectedIndexChanged += new EventHandler Combo1_SelectedIndexChanged;
But it will work only if you are populating the combobox once.If you are doing it for many number of times, then you may be in a mess.
Solution2: Its my preference and I use it regularily.
Change your selection change event as:
private void cb1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cb = (ComboBox)sender;
if(!cb.Focused)
{
return;
}
// Here is your Code for selection change
}
So now the event will be fired only if its in focus. Hope you were looking for the same.
Hope it Helps
A: Not sure if this is any use now but I found this answer, which seems cleaner to me.
From the MSDN Library - ComboBox.SelectionChangeCommitted Event
"SelectionChangeCommitted is raised only when the user changes the combo box selection. Do not use SelectedIndexChanged or SelectedValueChanged to capture user changes, because those events are also raised when the selection changes programmatically."
A: *
*Solution: If you're populating combobox with static values only ones, just populate them and after subscribe to event from code. Do not use WinForms Designer to subscribe to it.
*If it's not possible during loading can:
a) define a boolean variable bool loading, set it to true before you begin to populate combo with data, and in event handler check
if(loading)
return;
b) Unsubsribe from event:
If subscription was:
comboBox.SelectedIndexChanged += delegate(...);
Unsubscription before you begin load data is:
comboBox.SelectedIndexChanged -= delegate(...);
As loading of data finished, subscribe again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: View Hierarchy, UITabBarController, adding more views in certain tabs So I'm not sure what is the best way to do something, or the preferred way. Here's essentially what we are trying to do:
-UITabBarController as the root
-first tab is a FruitViewController
-FruitViewController can push an AppleViewController (not sure if push is the correct word, but basically go to the next viewController)
-AppleViewController has a back button in the UIToolBar to return to FruitViewController
-second tab is VegetableViewController
-VegetableFruitViewController can push CeleryViewController
At the end of both ViewControllers, you can push another ViewController called CalorieViewController. My question is that what's the best way to present view controllers per tab? Since I want both tabs to use CalorieViewController, in order to reuse it, I'm assuming I need to keep it non-coupled with the other ViewControllers.
The way my coworker implemented is, on each tab, all ViewControllers for that tab are created and added as a subview. Based on the button pressed, it hides and shows the other view. This seems like not a good idea. It seems like presentModalViewController, and dismissModalViewController (for the back button) might work, but I'm not sure if that's the preferred method.
A: I would suggest you make the root view controller for each tab a UINavigationController, with the view controller's that are currently set for the tabs as the root view controller of the navigation controller. That way you can push and pop views all you want. UIViewController even has support for automatically pushing the tab bar off the screen when pushing a new view controller onto the stack.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery tmpl plugin The most annoying thing about tmpl is that you cant replace ${n} inside <> such as
<a href="details/?id=${id}">${name}</a>
the ${id} wouldnt get replaced..
Any ideas how to do that without having to use the <script> tags, cause that isnt a good way to do it.
or even how to check a checkbox..
My template looks like this
<table id="lvList" class="grid1">
<tr>
<th>Name</th>
<th>Number</th>
<th>Type</th>
<th>Account Manager</th>
</tr>
<!-- itemtemplate -->
<tr>
<td>{{html $item.href('details/?id=$id')}}</td>
<td>${id}</td>
<td>${type}</td>
<td>${accmgr}</td>
</tr>
<!-- itemtemplate -->
</table>
if you want to know how I got the template from the table, you can see this post
ItemTemplate
Using that template, this is what I came up with
var items = $.tmpl(this.itemtemplate, data, {
href: function (url) {
for (i in this.data)
{ url = url.replace("$" + i, this.data[i]); }
return "<a href=\"" + url + "\">" + this.data["name"] + "</a>";
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Allowing users to upload ANYTHING I'm building a file sharing site, and I'm thinking, I want my users to be able to upload and share anything.
Sounds dangerous, I know. But, is there a method to allow this to be possible? For example, forcing the download when the user requests the link with a mime type? Rather than "running" something on the page.
Any ideas how to allow any file type without the security issue.
Thanks
A: *
*Store the file on a location not accessible by the user through the browser. (so above the document root)
*when loading a file, use the readfile() function.
*Set correct headers, including these:
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=[INSERT FILENAME HERE]");
And also use the correct content-type header for each type of file
A: If you only want it to be dangerous to other users (as they will be sharing virus ridden files in no time), but provide some protection for your web server from code injection attacks, you might consider storing the uploads in a database BLOB field. That should at least make it harder to inject code that will run on the server.
A: You can allow users to upload anything by using a simple HTML multipart form along with PHP's $_FILES. Only issue I see is file size limits.
You than can simply post a link to any of these files. It's the user's browsers settings that determine if a file is executed or downloaded, not yours. So you can suggest that they right click on them, and select 'save to', but besides that it's limited.
A:
Any ideas how to allow any filetype without the security issue.
You say it yourself. It's like wanting to make scrambled eggs, without wanting to break the eggs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL Report 2005, How to sum within a specific time
Possible Duplicate:
How to average/sum data in a day in SQL Server 2005
I have a data base "Shift", where it is recorded every minute. I have to sum the data by shift.
And Night Shift starts from 7:15PM of the previous day to 7:15 AM of that day. I need to write it somehow that when someone select a day, it will pop up a sum/average data within that time frame.
Please Help. Thank you very much.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Converting Large Dollar Values in C# I have an application that manages project costs from as little as a million to billions of dollars. Initially, users enter an estimate of the project: called an 'appropriation amount'.
The Issue Is:
The original value is not converting as expected. Some examples include:
They enter-in: 111,222,333
It converts to: 111,222,336
They enter-in: 111,222,333,444
It converts to: 111,222,333,440
The Problem Occurrs Here:
The issue arises upon conversion in the following line of code...
project.AppropriationAmount = (!String.IsNullOrEmpty(txtAppropriationDollars.Text)) ? Convert.ToSingle(txtAppropriationDollars.Text) : 0;
NOTES:
project.AppropriationAmount is a float.
Thanks for the help!
A: You should use decimal instead of float for money.
From MSDN:
The decimal keyword indicates a 128-bit data type. Compared to
floating-point types, the decimal type has more precision and a
smaller range, which makes it appropriate for financial and monetary
calculations.
Using Convert.ToDecimal(..) and assigning to a decimal variable yielded the expected (correct) results for your examples.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Passing data in JavaScript Having a problem understanding what I will call a variable scope question for lack of a better description.
Say I have a page with two functions, one() and two(). The first function has a locally-scoped variable x with an object in it. This function builds an element, below, in the DOM and this element contains an onClick, which calls the second function, and needs to pass x to the second function as an argument. I.e. the second function needs access to the data that is scoped to the first function.
I have tried:
<something onClick="two(x);">
but this doesn't seem to work. I know that there is a way to make x global but I have found in my other languages that globally-scoped variables are discouraged as being dangerous.
A: How about using closure:
function one()
{
var x = Math.random();
var el = document.createElement('div');
el.innerHTML='Hi!';
el.addEventListener("click", function(){two(x)}, false);
document.getElementById('myDiv').appendChild(el);
}
function two(text)
{
alert(text);
}
one();
Demo
A: Using a global variable within a function is not necessarily bad, but it is considered bad practice to place variables in the window scope, which is assumed if you don’t wrap your variables inside a function or object.
Consider this example:
(function() {
var x = 1;
function callback() {
alert(x);
}
function bind() {
x++;
elem.onclick = callback;
}
}());
A: You should read up on variable scope.
The function closure of one() has access to x. But since it exists in one() and not outside other functions will not have access to it. So you are putting two(x); in your onClick, which will try to resolve the x to a global scope. And there is no global x
You can easily fix this by making x global. Just place var x beside your functions.
A: to make x global declare it outside of the method
var x = 0
function one()
x=1
function two()
print x
x will print 1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Update column if another column contains a string I have a table that contains three columns.
column1 column2 column3
mytestdata test
myotherdata test
I want to insert 'somestring' into column3 if column1 contains the value in column2
The result would look like:
column1 column2 column3
mytestdata test 'somestring'
myotherdata test
A: SQL Server:
UPDATE myTable
SET column3 = 'somestring'
WHERE column1 LIKE '%' + column2 + '%'
A: SQL Server:
UPDATE theTable SET column3 = 'somestring'
WHERE CHARINDEX (column2, column1) > 0
A: You have several options, depending on the RDBMS.
For both MySQL and Oracle:
UPDATE yourTable
set column3 = 'somestring'
where INSTR(column2, column1) > 0
For SQL Server:
UPDATE yourTable
set column3 = 'somestring'
where CHARINDEX(column1, column2) > 0
A: You could do something like below
UPDATE tmp
SET
column3 = (CASE WHEN tmp.column1 like '%' + tmp.column2 + '%' THEN 'something' ELSE tmp.column3')
FROM
tablename tmp
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Scaling entire screen in XNA Using XNA, I'm trying to make an adventure game engine that lets you make games that look like they fell out of the early 90s, like Day of the Tentacle and Sam & Max Hit the Road. Thus, I want the game to actually run at 320x240 (I know, it should probably be 320x200, but shh), but it should scale up depending on user settings.
It works kind of okay right now, but I'm running into some problems where I actually want it to look more pixellated that it currently does.
Here's what I'm doing right now:
In the game initialization:
public Game() {
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = 640;
graphics.PreferredBackBufferHeight = 480;
graphics.PreferMultiSampling = false;
Scale = graphics.PreferredBackBufferWidth / 320;
}
Scale is a public static variable that I can check anytime to see how much I should scale my game relative to 320x240.
In my drawing function:
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.NonPremultiplied, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone, null, Matrix.CreateScale(Game.Scale));
This way, everything is drawn at 320x240 and blown up to fit the current resolution (640x480 by default). And of course I do math to convert the actual coordinates of the mouse into 320x240 coordinates, and so forth.
Now, this is great and all, but now I'm getting to the point where I want to start scaling my sprites, to have them walk into the distance and so forth.
Look at the images below. The upper-left image is a piece of a screenshot from when the game is running at 640x480. The image to the right of it is how it "should" look, at 320x240. The bottom row of images is just the top row blown up to 300% (in Photoshop, not in-engine) so you can see what I'm talking about.
In the 640x480 image, you can see different "line thicknesses;" the thicker lines are how it should really look (one pixel = 2x2, because this is running at 640x480), but the thinner lines (1x1 pixel) also appear, when they shouldn't, due to scaling (see the images on the right).
Basically I'm trying to emulate a 320x240 display but blown up to any resolution using XNA, and matrix transformations aren't doing the trick. Is there any way I could go about doing this?
A: Render everything in the native resolution to a RenderTarget instead of the back buffer:
SpriteBatch targetBatch = new SpriteBatch(GraphicsDevice);
RenderTarget2D target = new RenderTarget2D(GraphicsDevice, 320, 240);
GraphicsDevice.SetRenderTarget(target);
//perform draw calls
Then render this target (your whole screen) to the back buffer:
//set rendering back to the back buffer
GraphicsDevice.SetRenderTarget(null);
//render target to back buffer
targetBatch.Begin();
targetBatch.Draw(target, new Rectangle(0, 0, GraphicsDevice.DisplayMode.Width, GraphicsDevice.DisplayMode.Height), Color.White);
targetBatch.End();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Flushing Perl STDIN buffer Is there any way to clear the STDIN buffer in Perl? A part of my program has lengthy output (enough time for someone to enter a few characters) and after that output I ask for input, but if characters were entered during the output, they are "tacked on" to whatever is entered at the input part. Here is an example of my problem:
for(my $n = 0; $n < 70000; $n++){
print $n . "\n";
}
chomp(my $input = <STDIN>);
print $input . "\n";
The output would include any characters entered during the output from that for loop. How could I either disable STDIN or flush the STDIN buffer (or any other way to not allow extra characters to be inserted into STDIN before calling it)?
A: It looks like you can accomplish this with the Term::ReadKey module:
#!perl
use strict;
use warnings;
use 5.010;
use Term::ReadKey;
say "I'm starting to sleep...";
ReadMode 2;
sleep(10);
ReadMode 3;
my $key;
while( defined( $key = ReadKey(-1) ) ) {}
ReadMode 0;
say "Enter something:";
chomp( my $input = <STDIN> );
say "You entered '$input'";
Here's what happens:
*
*ReadMode 2 means "put the input mode into regular mode but turn off echo". This means that any keyboard banging that the user does while you're in your computationally-expensive code won't get echoed to the screen. It still gets entered into STDIN's buffer though, so...
*ReadMode 3 turns STDIN into cbreak mode, meaning STDIN kind of gets flushed after every keypress. That's why...
*while(defined($key = ReadKey(-1))) {} happens. This is flushing out the characters that the user entered during the computationally-expensive code. Then...
*ReadMode 0 resets STDIN, and you can read from STDIN as if the user hadn't banged on the keyboard.
When I run this code and bang on the keyboard during the sleep(10), then enter some other text after the prompt, it only prints out the text I typed after the prompt appeared.
Strictly speaking the ReadMode 2 isn't needed, but I put it there so the screen doesn't get cluttered up with text when the user bangs on the keyboard.
A: I had the same problem and solved it by just discarding anything in STDIN after the processing like this:
for(my $n = 0; $n < 70000; $n++){
print $n . "\n";
}
my $foo=<STDIN>;
print "would you like to continue [y/n]: ";
chomp(my $input = <STDIN>);
print $input . "\n";
A: { local $/; <STDIN> }
This temporarily - limited to scope of the block - sets $/, the input record seperator, to be undef, which tells perl to just read everything instead of reading a line at a time. Then reads everything available on STDIN and doesn't do anything with it, thus flushing the buffer.
After that, you can read STDIN as normal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Can an array or function lvalue be converted to an rvalue? According to C++ Standard 2003:
An lvalue (3.10) of a non-function, non-array type T can be converted to an rvalue.
What does it mean that array and function cannot be converted to rvalue?
A: Both function and array types are covered by later clauses (4.2, 4.3).
An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to an rvalue
of type “pointer to T.” The result is a pointer to the first element of the array.
(...)
An lvalue of function type T can be converted to an rvalue of type “pointer to T.” The result is a pointer to
the function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to create a program that solves a Triangular Peg solitare - C++ / Java programming? Honestly, I only knew of such a game recently and I wonder how one can create a solving algorithm using the recursive search method?
There are 15 holes in total in the triangular board. Making that 14 pegs with a total of 13 moves.
I don't know where to start with this in C++ nor Java. I have studied C++ for an year before. So I'm familiar with the concepts of stacks, linked lists etc.
I just don't know how to start the code. The program firstly asks the user where they want to start (How is this done?)
Then once it solves it , a certain number of pegs more than just one will be left and the program will ask the user for a better solution (like this until the board is left to just one peg.)
I certainly cannot think of how to make the moves possible ( How do I write a code that "SHOWS" that one peg moves over a hole ,into another?)
I'd love some coding assistance here. It would really be appreciated.
A: Try treating the board a linked list of holes or positions. Each data field in a node would represent a hole. Each node would have a vector of links to other holes, depending on its position relative to the edge of the board.
To move a peg, iterate over the possible links.
This is just one method, there are probably better ones out there.
A: Take a look at my answer here: Timeout on a php Peg Puzzle solver. The 15-peg puzzle was the first program that I ever wrote (over 10 years ago), after just learning c++.
The posted solution is a re-write that I did several years later.
Since I was the answerer I can tell you that a triplet is a term that I made up for a move. There are three pegs involved in a move (a triplet). Each peg is represented by a bit. In order for a move to be legal two consecutive pegs (bits) need to be set and the other (the target location) needs to be clear.
The entire solution involves a depth first search using a 16-bit integer to represent the board. Simple bit manipulation can be used to update the board state. For example if you xor the current state with a move (triplet) it will make the move against the board. The same operation applied a second time against the board is an undo of the move.
A: To be successful as a programmer, you need to develop the skill of examining a problem, figuring out how it can be solved, and come up with a reasonable in-program representation that enables you to solve it.
For problems like this, I find it helpful to have the puzzle in front of me, so I can try it out by hand. Failing that, at least having a picture of the thing will help:
http://www.obsidiandesigns.com/pyramidsol.jpg
Here's another way to look at it, and possibly consider representing it in memory like this:
OXXXX
XXXX
XXX
XX
X
Each "X" is a peg. The "O" is a hole. One can change "OXX" to "XOO" by jumping the 3rd X over the middle one, into the hole. Also consider vertical and diagonal jumps.
Linked lists could make a lot of sense. You might actually want "2D" links, instead of the usual "1D" links. That is each "hole" instance could contain pointers to the two or three holes next to it.
Once you have a representation, you need a way to find valid moves. And to make valid moves.
For this "game," you may want to search the whole space of possible moves, so you'll probably want to either have each move produce a new board, or to have a way to "undo" moves.
A valid move is where one peg jumps over another peg, into an empty hole. The jumped peg is removed. You can't jump from "just anywhere" to anywhere, over any peg you wish -- the three holes have to be next to each other and in line.
The above should give you some hints that will help you get started.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: building c++ config file parser using lex and yacc I am trying to build config file parser (c++ application)from scratch using tools like lex and yacc. The parser will be able to parse files like
# Sub group example
petName = Tommy
Owner = {
pet = "%petName%"
}
Is there any step by step guide/link to articles on how to achieve this using tools like lex and yacc? The idea is I will write a class say Config (c++) with methods like getConfig(string propName). If I invoke like config.getConfig(Owner.pet), it will return me Tommy.
A: Boost Property Tree
It was designed for configuration files. It does reading, writing in the following formats:
*
*INI
*INFO
*XML
*JSON
Here is the five minute tutorial page which should give you a good idea:
*
*http://www.boost.org/doc/libs/1_47_0/doc/html/boost_propertytree/tutorial.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Passing HTML Form to JSP page via PHP/Curl... pass not happening I have an HTML form, being submitted to a PHP page. The PHP page needs to validate a captcha and then pass the form values to a JSP page. I have NO control over the JSP page. Captcha is working beautifully. Something is getting lost in my PHP page, as when it loads the information on the JSP page, the CSS and headers of the target page aren't loading and the form data isn't being passed. I do not have access to the JSP page. Any ideas?
BTW, Captcha validation is working fine and the HTML works fine if I pass it directly to the JSP page:
<?php
require_once('recaptchalib.php');
$privatekey = "privatekeyhere";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("<p align='center'>The reCAPTCHA wasn't entered correctly. Please go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")</p>");
} else {
$ipaddress = $_SERVER["REMOTE_ADDR"];
$fname = $_POST['fname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$h = curl_init();
curl_setopt($h, CURLOPT_URL, "//remote JSP page");
curl_setopt($h, CURLOPT_HEADER, true);
curl_setopt($h, CURLOPT_POST, true);
curl_setopt($h, CURLOPT_POSTFIELDS, array(
'fname' => '$fname',
'address' => '$address',
'city' => '$city',
'state' => '$state',
'zip' => '$zip',
'phone' => '$phone',
'email' => '$email',
));
curl_setopt($h, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($h);
echo $result;
}
?>
A: Problems I can spot right away:
*
*CURLOPT_POSTFIELD has to be a POST string, not an array.
*Even then, you're posting strings representing variable names (you should post the value instead.
For point 1, here's a simple cUrl tutorial by David Walsh, covering a case very similar to yours and containing a way to transform arrays in POST strings: http://davidwalsh.name/execute-http-post-php-curl
For point 2, strings inside 'single quotes' are not evaluated. To refer to a variable, you should use $var, not '$var'.
Bonus: anything in a POST/GET string should be urlencoded.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to list local commits difference in git I have a remote repository cloned locally, and over time, I have added local commits to that cloned repository.
Now, whenever I do git status, I see Your branch is ahead of 'origin/master' by xx commits message.
Q: How do I list only commits made locally, so that I can examine these commits into more detail, and eventually merge some of them into upstream?
A: You can do it by specifying the range to the log command:
git log origin/master..master
Use your branch name instead of master, of course.
You can read more for example here: What are the differences between double-dot ".." and triple-dot "..." in Git commit ranges?
Also, read man gitrevisions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: VS2008 Smart Device project to work with TFS 2010 I would like to check in my Visual Studio 2008 project (Smart Device Project) into TFS 2010.
Last time, I tried this grueling task, there were so many quirks and plugins and at the end of the day, it still failed to detect a change in the file....
so, at this day and age, is it possible to do?
Thank you!
A: May be the response is too late... but...
You will need to get VS2008 installed on the build agent server. Most of the job is done at this point.
I have managed to get TFS 2010 to deploy the unit tests in a device too.
I think general google search will help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android ActioBar Style What styles are available for ActionBar? ( OR I will have to define it) The one I am using the defautlt one (a line below all the tabs) Can I change color of that line?
A: Are you using the native ActionBar in Android 3.0+ (Honeycomb, tablets only), or are you using a library like ActionBarSherlock or Android-ActionBar? In at least the first two cases, this post from the official Android Developers blog should help you out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Node.js - Nested array in Jade view Using Mongoose, I have a model Page with an embedded model of Feeds. When i go to /pages, the page.title shows up for each page, but feeds data does not. how should i modify this code to properly display the data from the feeds array? thanks a million
db.pages exmaple:
{ "title" : "testing feeds", "_id" : ObjectId("123456"), "feeds" : [
{ "0" : { "name" : "twitter", "key" : "1234" },
"1" : { "name" : "flickr", "key" : "5678" },
}] }
web.js
app.get('/pages.:format?', function(req, res) {
Page.find({}, function(err, pages) {
switch (req.params.format) {
case 'json':
res.send(pages.map(function(d) {
return d.toObject();
}));
break;
default:
res.render('pages/index.jade', {
locals: {
title: 'ClrTouch | Pages',
pages: pages,
feeds: pages.feed,
}
});
}
});
});
view
- each page in pages
div.page
div.pagetitle= page.title
ul
- each feed in page.feeds
li.pagefeedname= feed.name
li.pagefeedkey= feed.key
with what i have, a list is generated in the view but the list items are empty. Thanks.
A: Is the model that you have here what you are also testing with? If so, then the reason your list is generated but nothing is displayed is because you do not currently have values in either.
li.pagefeedname=feed.name = "0" : { "name" : "", "key" : "" }
Try giving your feed name/keys some values and see how that plays out.
Otherwise what you have should work
A: tuddy,
I suggest you try like this:
Page.find().lean().exec(function(err,pages){
// TODO
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is relationship between App_Licenses.dll and licx? I am trying to understand how the licensing works in ASP.NET.
There is licx file, App_Licenses.dll file. And then there is a difference between how the licensing works for a WebSite and a WebApp project.
Any insight into these would be of great help.
Links, explanation are most welcome.
Thanks.
A: I'm not sure of any differences between WebSite and WebApp, but with a licx file, it is compiled into the app_Licenses.dll file. If its not generating for you - you can right click on your licx file and regenerate the dll.
As per MS -
http://connect.microsoft.com/VisualStudio/feedback/details/499908/app-license-dll-can-not-be-generated-automatically-in-asp-net-website
In a web application project, manually copy the .lic file to /bin folder. In a Website, this is done automatically.
At this pointm refresh the designer or rerun the project and the licensed control should work as expected.
Note: App_LICENSES.dll isn't required in a WAP. In Websites, App_LICENSES.dll is generated to contain the LICX as an embedded resource. In WAP, there is a project assembly which contains the embedded LICX resource, so a separate DLL is not necessary
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Bash regex finding and replacing I don't know if this is possible, but can you dynamically alter a find/replace?
Basically I have something like this
<3 digit number> <data>
and what I want to do is if data matches the pattern
<word>:<4 digit number>
replace all instances (in the entire file) of <word>: with the line's 3 digit number I.E:
020 Word
021 Word:0001
Replace with
020 021
021 0210001
Is this doable with AWK or Sed?
If not, is it doable in C?
A: I know this isn't what you asked, but I think the best way to solve this is with a simple Perl script.
#!/usr/bin/perl
$in= "input.txt";
$out= "output.txt";
# Buffer the whole file for replacing:
open(INFILE, $in);
@lines = <INFILE>;
open(INFILE, $in);
# Iterate through each line:
while(<INFILE>) {
# If the line matches "word:number", replace all instances in the file
if (/^(\d{3}) (\w+:)\d{4}$/) {
$num = $1; word = $2;
s/$word/$num/ foreach @lines;
}
}
open(OUTFILE, $out);
print OUTFILE foreach @lines;
It looks a lot longer than it really needs to be, because I made it nice and easy-to-read for you.
A: I hope this time I got you right.
try the stuff below:
#file name:t
kent$ cat t
020 Word
021 Word:0001
#first we find out the replacement, 021 in this case:
kent$ v=$(grep -oP "(\d{3})(?= Word:\d{4})" t|head -n1)
#do replace by sed:
kent$ sed -r "s/Word[:]?/$v/g" t
020 021
021 0210001
A: number=$(gawk --posix '/[0-9]{3} '${word}':[0-9]{4}/ { print $1; exit }' $file)
if [ "$number" != "" ]; then
sed -r "s/${word}:?/${number}/" $file
fi
A: This awk solution takes 2 passes through your file: once to find all the Words needing replacement, and once to actually do the replacing:
gawk '
NR == FNR {
if (match($2, /^([^:]+):[0-9][0-9][0-9][0-9]$/, a))
repl[a[1] ":?"] = $1
next
}
{
for (word in repl)
if ($2 ~ word) {
sub(word, repl[word], $2)
break
}
print
}
' filename filename > new.file
Requires gawk for capturing parentheses.
A: Here's another sed solution:
# sweep the file and make a lookup table variable
lookup=$(sed -nr 's/(.*) (.*:).*/\2\1/p' <source_file |tr '\n' ' ')
# append the lookup to each line and substitute using a backreference
# N.B. remove the lookup whatever!
sed -r "s/\$/@@${lookup}/;
s/^(... )(.*)$@@.*\2:(\S*).*/\1\3/;
s/^(... )(.*:)(.*)@@.*\2(\S*).*/\1\4\3/;
s/@@.*//" <source_file
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Onload timeout preventing to use Curl I am trying to retrieve the content of a web page via cURL (let's say http://www.foo.com/bar.php).
When I load the website in the browser, an animation appears while the page is loading, and the page eventually shows up.
But with cURL, here is what is retrieved :
<html>
<head>
<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=http://www.foo.com/bar.php">
<script type="text/javascript">
function waitLoad(){
setTimeout("showWaitingAnimation()", 50);
}
</script>
</head>
<body onload="waitLoad()">
Some stuff here
</body>
</html>
And when I try to perform a curl to the refresh url, it returns exactly the same thing.
Any suggestion ?
Cheers,
A.
A: Install the HttpFox Firefox Addon or a packet sniffer and inspect the requests and responses. Then try to emulate the same headers and parameters with curl.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: android pattern lock blocks internet access? My app transfers data to an internet server at regular intervals. It does this ok when locked with my phone which has the standard lock - no pin or pattern. I am testing with a friends phone which has a pattern lock and it seems that when locked with a pattern it does not have internet access. Is my suspicion correct? If so could someone point me towards a method to establish the internet connection even tho pattern locked?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I reverse an array in place in assembly? I am supposed to reverse an array in place. I have been working on it for a while and this is what I have. Can anyone tell me what I'm doing wrong?
.data
array BYTE 10h, 20h, 30h, 40h
.code
main PROC
mov esi, 0
mov edi, 0
mov esi, OFFSET array
mov edi, OFFSET array + SIZEOF array
mov ecx, SIZEOF array/2
l1: mov al, [esi]
mov bl, [edi]
mov [edi], al
mov [esi], bl
inc esi
dec edi
LOOP l1
call DumpRegs
call DumpMem
exit
main ENDP
END main
A: Try to declare two arrays, one intilized with your values and the other one could be like this using DUP operator 5 DUP (?)
And start moving values from first array to the second using a loop.
Example:
.data
myArr1 DWORD 5, 4, 3, 2, 1
myArr2 DWORD 5 DUP (?)
.code main proc
mov edi, offset myArr1
add edi, sizeof myArr1
mov esi, offset myArr2
mov ecx, lengthof myArr2
reverseLoop:
add ebx, [edi] mov[edi], ebx
sub edi, type myArr2
add esi, type myArr1
mov eax, [edi]
call writeint
LOOP reverseLoop
exit
main endp
end main
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Git: Changing to a Remote Branch From a Clone I've got a git workflow question, and I don't fully understand all the terms to know what to google for.
The short version: Is it possible to "switch" your local git directory to a branch from a remote repository, when your local repositories started as clones of the remote repository? I'm newish to git, so I'm still coming up to speed on the terminology here; if I've said something that seems off/wrong/making-an-assumption please let me know.
The long version.
I have a local repository that's a clone of "the central" repository. This repository has several branches, each of which is many revisions ahead of the original repository's master branch.
$ git branch
foo
* master
universal_imports
I know I can "switch" to one of my local branches by using git's checkout command
$ git checkout foo
$ git checkout universal_imports
etc.
I also have a few remotes
$ git remote
origin
upstream
The upsteam's master branch is our source of truth. It is the product, the aforementioned central repository. As previously stated, my local master repository started as a clone of this repository. (actually, my local repository is a clone of the origin remote, which is a github fork of the upstream's master branch. I'm unsure if that's relevant)
Here's the scenario I'm trying to solve. I've been doing new development on my branches. I'm many versions ahead of the original master. However, I've just received a request to fix something in production. My mental model here would be to
*
*Switch my local code so it matches the production code
*Do the fix and commit it
*Merge my local code into the source-of-truth branch
*Switch my local code back to my "real" branches, and continue new feature development
The goal is to avoid putting any of my new code into production before it's ready.
Short of re-cloning the central repository somewhere, is there a git workflow for this? Ideally I'd like something like i described "switch to a remote branch", but if that's nonsense talk is there a way I could have worked with git that would have allowed me to handle this situation. (blaze ahead on new work, but main the ability to work off a point further back in the history)
A: You can create a new branch to track a remote branch like this (here the local branch is called 'bugfix'):
git checkout -b bugfix upstream/master
Once you have a local branch tracking and synced with the desired remote branch, you can just make your changes, then git commit and git push, then checkout your original working branch.
Finally, after checking out your working branch again, you'll want to either merge your bugfix change into your working branch like this:
git merge bugfix
Or rebase it like this (rebasing creates a more clean history but can take more work in resolving conflifcts):
git rebase -i bugfix
You can go ahead and leave that branch there (in which case you'll probably want to call it something more permanent than 'bugfix', maybe something like 'upstream-master', or 'live-product', or whatever). Or you can delete the local branch if you don't want it anymore, like this:
git branch -D bugfix
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Temporarily Disabling Django Caching How do you disable Django caching on a per checkout basis?
Back before Django 1.3, I could disable caching for my local development checkout by specifying CACHE_BACKEND = None, in a settings_local.py imported by settings.py. The settings_local.py was ignored by SVN, so I could always ensure my local environment didn't cache, while not have to worry about modifying the cache params in settings.py.
Now, with Django 1.3, and the new CACHES = {...} structure, setting CACHES = None or CACHES['default']['BACKEND'] = None causes Django to choke, and setting CACHES = {} still seems to enable basic caching.
A: Dummy Caching (for development) - this implements the cache interface, but doesn't actually cache so you could have it on your development/testing site to reduce caching and also prevent errors from caching, if those should arise.
Finally, Django comes with a "dummy" cache that doesn't actually cache – it just implements the cache interface without doing anything.
This is useful if you have a production site that uses heavy-duty caching in various places but a development/test environment where you don’t want to cache and don’t want to have to change your code to special-case the latter. To activate dummy caching, set BACKEND like so:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
A: Solution for multiple caches, and you want to disable all of them:
if True:
CACHES = {
k : {'BACKEND': 'django.core.cache.backends.dummy.DummyCache',}
for k,v in CACHES.iteritems()
}
Solution if you want to disable some caches, may help:
if True:
disable_names = [ 'cache_name' ]
for name in disable_names:
CACHES[name] = {'BACKEND' : 'django.core.cache.backends.dummy.DummyCache',}
A: Whilst using DRF, on some views, I would enable caching using django.views.decorators.cache.cache_page. The accepted answer did not work for me and I resorted to clearing the cache on tear down
from django.core.cache import cache
from rest_framework.test import APITestCase
class SomeTestCase(APITestCase):
def tearDown(self):
cache.clear()
A: For that purpose you can use "dummy" cache backend. Django comes with a "dummy" cache that doesn't actually cache -- it just implements the cache interface without doing anything.
Here are the old style and new style configuration formats.
*
*old style
To activate dummy caching, set CACHE_BACKEND like so:
CACHE_BACKEND = 'dummy://'
*new style
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
A: I use this in my settings, so it's a bit more flexible i case I do want to test the usage of the deployed caching (in this case memcache)
TEST_MEMCACHE = False
if not DEBUG or TEST_MEMCACHE:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
else:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "43"
}
|
Q: How to retrieve resources from a dependency's bundle on iPhone? I've added the dependency project to my project. The dependency has a bundle with resources that I need. How to I get a path to those resources?
I tried the follow and get a NO. Any suggestions?
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *bundlePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Dendency.bundle"];
if ([fileManager fileExistsAtPath:bundlePath])
{
NSLog(@"YES");
}
else
{
NSLog(@"NO");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WIF - Federated Provider MVC application or does it have to be Web Forms? I'm building my own FP STS application. The Visual Studio STS add in builds an asp.net web forms web site.
Is it possible to make the STS site an MVC application?
We would like to use a bunch of master pages we already have in the MVC world.
A: Have a look at Identity Server. It's an MVC 3 STS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java JLabel text in middle of vertical axis I have a JLabel that contains variable text in a certain location in my GUI. The problem is that the text gets displayed at the bottom of the space where the JLabel is located. This does not convey to the end user the relevant information about the other contents of the GUI. Instead, I need the text of the JLabel to be printed in the middle of the vertical axis of the JLabel. A simplified version of my code is below. Can anyone show me how to alter it so that the text displays in the middle of the vertical axis instead of the bottom?
Main.java:
import java.awt.*;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Main");
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(new VerticalLabel("Hello"));
Dimension prefSize = new Dimension(400, 300);
frame.setPreferredSize(prefSize);
frame.setMinimumSize(prefSize);
frame.pack();
frame.setVisible(true);
}
}
VerticalLabel.java:
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EtchedBorder;
public class VerticalLabel extends JLabel {
public VerticalLabel(String labelText) {
Dimension myDim = new Dimension(15, 250);
this.setPreferredSize(myDim);
this.setHorizontalAlignment(LEFT);
this.setVerticalAlignment(CENTER);
this.setText(labelText);
this.setVerticalTextPosition(CENTER);
this.setUI(new VerticalLabelUI(false));
this.setBorder(new EtchedBorder());
}
}
A: Hardcoding a random preferred size is not a good idea.
You wrote a custom UI, so it is the responsibility of the UI to paint the text in the proper position.
Instead of creating a custom UI you can use the Text Icon approach to display vertical text. Create the label as follows:
JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
TextIcon labelIcon = new TextIcon(label, "Hello", TextIcon.Layout.VERTICAL);
label.setIcon( vIcon );
Add the label to the CENTER of a panel using a BorderLayout and the vetical text will be centered vertically and horizontally.
A:
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EtchedBorder;
public class VerticalLabel extends JLabel{
public VerticalLabel(String labelText){
this.setHorizontalAlignment(LEFT);
this.setVerticalAlignment(CENTER);
this.setText(labelText);
this.setVerticalTextPosition(CENTER);
//this.setUI( new VerticalLabelUI(false) );
this.setBorder( new EtchedBorder() );
}
public static void main(String[] args){
// should be done on the EDT.
JFrame frame = new JFrame("Main");
frame.getContentPane().setLayout( new GridBagLayout() );
frame.getContentPane().add(new VerticalLabel("Hello"));
Dimension prefSize = new Dimension(200,150);
frame.setPreferredSize(prefSize);
frame.setMinimumSize(prefSize);
frame.pack();
frame.setVisible(true);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I generate random numbers without rand() function? I want to generate (pseudo) random numbers between 0 and some integer. I don't mind if they aren't too random. I have access to the current time of the day but not the rand function. Can anyone think of a sufficiently robust way to generate these? Perhaps, discarding some bits from time of day and taking modulo my integer or something?
I am using c.
A: Look at implementing a pseudo-random generator (what's "inside" rand()) of your own, for instance the Mersenne twister is highly-regarded.
A: If you're after an ultra-simple pseudo-random generator, you can just use a Linear Feedback shift Register.
The wikipedia article has some code snippets for you to look at, but basically the code for a 16-bit generator will look something like this (lightly massaged from that page...)
unsigned short lfsr = 0xACE1u;
unsigned bit;
unsigned rand()
{
bit = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;
return lfsr = (lfsr >> 1) | (bit << 15);
}
A: #include <chrono>
int get_rand(int lo, int hi) {
auto moment = std::chrono::steady_clock::now().time_since_epoch().count();
int num = moment % (hi - lo + 1);
return num + lo;
}
A: For "not too random" integers, you could start with the current UNIX time, then use the recursive formula r = ((r * 7621) + 1) % 32768;. The nth random integer between 0 (inclusive) and M (exclusive) would be r % M after the nth iteration.
This is called a linear congruential generator.
The recursion formula is what bzip2 uses to select the pivot in its quicksort implementation. I wouldn't know about other purposes, but it works pretty well for this particular one...
A: The only "robust" (not easily predictable) way of doing this is writing your own pseudo-random number generator and seeding it with the current time. Obligatory wikipedia link: http://en.wikipedia.org/wiki/Pseudorandom_number_generator
A: You can get the "Tiny Mersenne Twister" here: http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/TINYMT/index.html
it is pure c and simple to use. E.g. just using time:
#include "tinymt32.h"
// And if you can't link:
#include "tinymt32.c"
#include <time.h>
#include <stdio.h>
int main(int argc, const char* argv[])
{
tinymt32_t state;
uint32_t seed = time(0);
tinymt32_init(&state, seed);
for (int i=0; i<10; i++)
printf("random number %d: %u\n", i, (unsigned int)tinymt32_generate_uint32(&state));
}
A: The smallest and simple random generator which work with ranges is provided below with fully working example.
unsigned int MyRand(unsigned int start_range,unsigned int end_range)
{
static unsigned int rand = 0xACE1U; /* Any nonzero start state will work. */
/*check for valid range.*/
if(start_range == end_range) {
return start_range;
}
/*get the random in end-range.*/
rand += 0x3AD;
rand %= end_range;
/*get the random in start-range.*/
while(rand < start_range){
rand = rand + end_range - start_range;
}
return rand;
}
int main(void)
{
int i;
for (i = 0; i < 0xFF; i++)
{
printf("%u\t",MyRand(10,20));
}
return 0;
}
A: If you're not generating your numbers too fast (*1) and your upper limit is low enough (*2) and your "time of day" includes nanoseconds, just use those nanoseconds.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int nanorand(void) {
struct timespec p[1];
clock_gettime(CLOCK_MONOTONIC, p);
return p->tv_nsec % 1000;
}
int main(void) {
int r, x;
for (;;) {
r = nanorand();
do {
printf("please type %d (< 50 quits): ", r);
fflush(stdout);
if (scanf("%d", &x) != 1) exit(EXIT_FAILURE);
} while (x != r);
if (r < 50) break;
}
puts("");
return 0;
}
And a sample run ...
please type 769 (< 50 quits): 769
please type 185 (< 50 quits): 185
please type 44 (< 50 quits): 44
(*1) if you're using them interactively, one at a time
(*2) if you want numbers up to about 1000
A: You can write your own rand() function. Like:
Method 1: Using the Concept of static variable:
example code:
int random_number_gen(int min_range, int max_range){
static int rand_number = 199198; // any random number
rand_number = ((rand_number * rand_number) / 10 ) % 9890;
return rand_number % (max_range+1-min_range) + min_range ;
}
Method 2. Using a random/unique value, for example, the current time in microseconds.
#include<time.h>
#include <chrono>
using namespace std;
uint64_t timeSinceEpochMicrosec() {
using namespace std::chrono;
return duration_cast<microseconds>(system_clock::now().time_since_epoch()).count();
}
int random_number_gen(int min_range, int max_range){
long long int current_time = timeSinceEpochMicrosec();
int current_time_in_sec = current_time % 10000000;
int rand_number = current_time_in_sec % (max_range+1-min_range) + min_range ;
return rand_number;
}
A: One of the simplest random number generator which not return allways the same value:
uint16_t simpleRand(void)
{
static uint16_t r = 5531; //dont realy care about start value
r+=941; //this value must be relative prime to 2^16, so we use all values
return r;
}
You can maybe get the time to set the start value if you dont want that the sequence starts always with the same value.
A: #include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
unsigned int x,r,i;
// no of random no you want to generate
scanf("%d",&x);
// put the range of random no
scanf("%d",&r);
unsigned int *a=(unsigned int*)malloc(sizeof(unsigned int)*x);
for(i=0;i<x;i++)
printf("%d ",(a[i]%r)+1);
free(a);
getch();
return 0;
}
A: import java.io.*;
public class random{
public static class p{
}
static long reg=0;
static long lfsr()
{
if(reg==0)
{
reg=145896027340307l;
}
long bit=(reg>>0^reg>>2^reg>>3^reg>>5)&1;
reg=reg>>1|bit<<62;
return reg;
}
static long getRand()
{
String s=String.valueOf(new p());
//System.out.println(s);
long n=0;
lfsr();
for(int i=0;i<s.length();i++)
{
n=n<<8|+s.charAt(i);
}
System.out.print(n+" "+System.currentTimeMillis()+" "+reg+" ");
n=n^System.currentTimeMillis()^reg;
return n;
}
public static void main(String args[])throws IOException
{
for(int i=0;i<400;i++)
{
System.out.println(getRand());
}
}
}
This is a random number generator where it is guaranteed that the sequence never repeats itself. I have paired time with object value (randomly put by java) with LFSR.
Advantages:
*
*The sequence doesn't repeat itself
*The sequence is new on every run
Disadvantages:
*
*Only compatible with java. In C++, new object that is created is same on every run.
*But there too time and LFSR parameters would put in enough randomness
*It is slower than most PRNGs as an object needs to be created everytime a number is needed
A: #include<time.h>
int main(){
int num;
time_t sec;
sec=time(NULL);
printf("Enter the Range under which you want Random number:\n");
scanf("%d",&num);
if(num>0)
{
for(;;)
{
sec=sec%3600;
if(num>=sec)
{
printf("%ld\n",sec);
break;
}
sec=sec%num;
}
}
else
{
printf("Please Enter Positive Value!\n");
}
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
}
|
Q: Netbeans + Scala + play-framework : index.html isn't found I've just netbeansified a plain play project with scala. Netbeans has no problems with opening or editing the project but if I try to run it this happens:
@68095ke10 Application.index action not found
Action not found Action Application.index could not be found. Error
raised is Controller controllers.Application not found
play.exceptions.ActionNotFoundException: Action Application.index not
found at
play.mvc.ActionInvoker.getActionMethod(ActionInvoker.java:588) at
play.mvc.ActionInvoker.resolve(ActionInvoker.java:85) at
Invocation.HTTP Request(Play!) Caused by: java.lang.Exception:
Controller controllers.Application not found ... 3 more
First I tried to rename and restructure the project so that index.html would be found. Yet I soon realized that this was no help at all. After undoing my changes I tried to start the app by play run on the console. Somehow this worked. Netbeans is version 7.0.1. Play is version 1.2.3 . Scala was installed by the typesafe-stack. Netbeans plugin is up to date with version 2.9.x. What is wrong ?
A: Add a path to the scala module lib folder to your project, and when you run the app, see if it says "Scala support is active" you'll notice this happens when running from the console, but not netbeans.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What aynchronous Ruby server to use? We're starting development of the new game project using Ruby. We decided to use one of the asynchronous Ruby servers, but we cannot decide which one to choose. Options are:
*
*Goliath
*Cramp + thin/rainbows
*rack-fiber_pool + rack + thin/rainbows
*eventmachine_httpserver
All of them seem to be working with HTTP requests. Cramp also supports Websockets and Server-Side events from the box.
Do you know any pros & cons of these servers?
A: I've used eventmachine_httpserver to expose a RESTful API in an EventMachine-based IRC bot and would definitely not recommend it for anything serious. It seems more like a minimal proof-of-concept than a serious web server, perhaps best illustrated by the parse_headers hack I had to use.
A: You may also want to look pub/sub services like nats.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Android NDK r6b Cross-compiling libfaac for android (linking libsupc++ problems) I'm trying to cross-compile libfaac to android for use with ffmpeg. I've gotten ffmpeg cross-compiled but libfaac is giving me major headaches.
This is the script I'm using to compile libfaac:
ANDROID_API=android-3
export ANDROID_NDK=${HOME}/android-ndk
export ANDROID_SDK=${HOME}/android-sdk
SYSROOT=$ANDROID_NDK/platforms/$ANDROID_API/arch-arm
ANDROID_BIN=$ANDROID_NDK/toolchains/arm-linux-androideabi-4.4.3/prebuilt/*-x86/bin/
CROSS_COMPILE=${ANDROID_BIN}/arm-linux-androideabi-
export PATH=$PATH:$ANDROID_SDK/tools:$ANDROID_SDK/platform-tools
export ARM_INC=$ANDROID_NDK/platforms/android-5/arch-arm/usr/include
export ARM_LIB=$ANDROID_NDK/platforms/android-5/arch-arm/usr/lib
CFLAGS=" -I$ARM_INC -fPIC -Wall -Wextra -Wno-unused -Wno-multichar -mthumb-interwork -ffunction-sections -funwind-tables -fno-rtti -fstack-protector -fno-short-enums -DANDROID -D__ARM_ARCH_5__ -D__ARM_ARCH_5T__ -D__ARM_ARCH_5E__ -D__ARM_ARCH_5TE__ -Wno-psabi -march=armv5te -mtune=xscale -msoft-float -mthumb -Os -fomit-frame-pointer -fno-strict-aliasing -finline-limit=64 -Wa,--noexecstack -MMD -MP -MF"
LDFLAGS=" -nostdlib -Bdynamic -Wl,--gc-sections -Wl,--no-undefined -Wl,-z,noexecstack -Wl,-z,nocopyreloc -Wl,-soname,/system/lib/libz.so -Wl,-rpath-link=$ARM_LIB,-dynamic-linker=/system/bin/linker -L$ANDROID_NDK/sources/cxx-stl/gnu-libstdc++/libs/armeabi -L$ANDROID_NDK/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86/arm-linux-androideabi/lib -L$ARM_LIB $ARM_LIB/crtbegin_dynamic.o $ARM_LIB/crtend_android.o -Wl,--start-group -lc -lm -ldl -lgcc $ANDROID_NDK/sources/cxx-stl/gnu-libstdc++/libs/armeabi/libstdc++.a $ANDROID_NDK/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86/arm-linux-androideabi/lib/thumb/libsupc++.a -Wl,--end-group"
FLAGS="--host=arm-androideabi-linux --enable-static --disable-shared --prefix=$HOME "
export CPPFLAGS="$CFLAGS"
export CFLAGS="$CFLAGS"
export CXXFLAGS="$CFLAGS"
export CXX="${CROSS_COMPILE}g++ --sysroot=${SYSROOT}"
export LDFLAGS="$LDFLAGS"
export CC="${CROSS_COMPILE}gcc --sysroot=${SYSROOT}"
export NM="${CROSS_COMPILE}nm"
export STRIP="${CROSS_COMPILE}strip"
export RANLIB="${CROSS_COMPILE}ranlib"
export AR="${CROSS_COMPILE}ar"
cd ../faac
./configure $FLAGS
make clean
make -j4 || exit 1
make install || exit 1
I'm very much a beginner when it comes to c++ code and cross-compiling, and I've build this script using many other scripts as reference so I may be doing some unnecessary or flat-out incorrect things.
Anyways, I'm getting literally hundreds of errors along the line of:
undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
undefined reference to `__cxa_end_cleanup'
undefined reference to `__cxa_throw'
undefined reference to `__gxx_personality_v0'
It seems the issue has to do with me not linking libsupc++ properly.
I tried doing what the person at this other stackoverflow question did, but I don't know if I did it right, I'm unfamiliar with the linking process.
What am I doing wrong? Thank you for any help.
EDIT:
It turns out I may or may not be wrong about libsupc++ causing the problems, the configure.log tells me the compiler can't create an executable, but I can't figure out what the problem is.
Here is a pastebin of the configure log
A: Well bizarrely enough the issue was actually that somehow libsupc++ was being linked multiple times, so when I removed some libraries and changed a few commands I got it working. Here's the compile script I use:
#!/bin/bash
ANDROID_API=android-3
export ANDROID_NDK=${HOME}/android-ndk
export ANDROID_SDK=${HOME}/android-sdk
SYSROOT=$ANDROID_NDK/platforms/$ANDROID_API/arch-arm
ANDROID_BIN=$ANDROID_NDK/toolchains/arm-linux-androideabi-4.4.3/prebuilt/*-x86/bin/
CROSS_COMPILE=${ANDROID_BIN}/arm-linux-androideabi-
export PATH=$PATH:$ANDROID_SDK/tools:$ANDROID_SDK/platform-tools
export ARM_INC=$ANDROID_NDK/platforms/android-3/arch-arm/usr/include
export ARM_LIB=$ANDROID_NDK/platforms/android-3/arch-arm/usr/lib
CFLAGS=" -I$ARM_INC -fpic -DANDROID -fpic -mthumb-interwork -ffunction-sections -funwind-tables -fstack-protector -fno-short-enums -D__ARM_ARCH_5__ -D__ARM_ARCH_5T__ -D__ARM_ARCH_5E__ -D__ARM_ARCH_5TE__ -Wno-psabi -march=armv5te -mtune=xscale -msoft-float -mthumb -Os -fomit-frame-pointer -fno-strict-aliasing -finline-limit=64 -DANDROID -Wa,--noexecstack -MMD -MP "
LDFLAGS=" -nostdlib -Bdynamic -Wl,--whole-archive -Wl,--no-undefined -Wl,-z,noexecstack -Wl,-z,nocopyreloc -Wl,-soname,/system/lib/libz.so -Wl,-rpath-link=$ARM_LIB,-dynamic-linker=/system/bin/linker -L$ANDROID_NDK/sources/cxx-stl/gnu-libstdc++/libs/armeabi -L$ANDROID_NDK/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86/arm-linux-androideabi/lib -L$ARM_LIB -lc -lgcc -lm -ldl "
FLAGS="--host=arm-androideabi-linux --enable-static --disable-shared --prefix=$HOME --enable-armv5e "
export CPPFLAGS="$CFLAGS"
export CFLAGS="$CFLAGS"
export CXXFLAGS="$CFLAGS"
export CXX="${CROSS_COMPILE}g++ --sysroot=${SYSROOT}"
export LDFLAGS="$LDFLAGS"
export CC="${CROSS_COMPILE}gcc --sysroot=${SYSROOT}"
export NM="${CROSS_COMPILE}nm"
export STRIP="${CROSS_COMPILE}strip"
export RANLIB="${CROSS_COMPILE}ranlib"
export AR="${CROSS_COMPILE}ar"
./configure $FLAGS
make clean
make -j4 || exit 1
make install || exit 1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Enabling Disabling button asp .net - using javascript Currently in my application I am having a button and a text box. The user types something in the textbox and then presses the button. What I want is that:
The search button should should stay disabled when the page loads for the first time. I can achieve that by setting it to disabled in the code behind file.
Now I want it to remain disabled when the user types upto 2 characters. The moment the user types third character the button should get enabled automatically.
The important thing is that it has to be done without asp .net AJAX since this website will be run from old mobile phones. So only pretty basic javascript or jquery is supported.
Any help will be appreciated.
Thanks
Varun
A: in order to use the document.getElementById in asp.net and not have to use the full name, you should let asp.net provide it. Instead of:
document.getElementById("ctl00_ctl00_phContent_phPageContent_btnSearch")
Try:
document.getElementById('<%= btnName.ClientID %>')
Where btnName is the asp:Button Id. The <%= code will generate the actual button id, fully qualified, so you don't have to worry about things changing with the hard coded id.
A: I got this to work with a HTML text box, I don't think you can do it with a asp.net text box:
<head>
<script type="text/javascript">
function TextChange() {
var t = document.getElementById("Text1");
var b = document.getElementById("Button1");
if (t.value.length > 2) {
b.disabled = false;
}
else {
b.disabled = true;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Text1" type="text" onkeyup="TextChange();" />
<asp:Button ID="Button1" runat="server" Text="Button" Enabled="False" />
</div>
</form>
</body>
A: If you're using jQuery, use
$(<selector>).val().length
to get the size, then you can set the button's disabled attribute with
$(<button selector>).attr('disabled',false).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Load the all css & js for the page before downloading the "big list of images" I have a website that displays a list of around 20 auto-played slideshows(each containing 4-5 images) in a page. Now the problem is that this is taking up a long time to load the website(& ofcourse it would, since so many images) but I am wanting to preferentially load all the neccessary css and js files at first, so that the other components on the page are properly rendered before the images begin to download.
So... Is there a way to set a preferential order of loading of the requested resources ?
A:
Is there a way to set a preferential order of loading of the requested resources
Yes - put them in that order in your HTML file!
I am wanting to preferentially load all the neccessary css and js files at first, so that the other components on the page are properly rendered before the images begin to download.
That's a different problem.
Your page components cannot be properly rendered until the dimensions of most elements are known. So, if you have other images in your page layout, those need to get loaded first, or have their width and height attributes specified in the markup.
Since your slideshow images would be mixed in with the rest of your layout if you used pure HTML to load them it sounds like you have little choice but to instead load all of your slide show images from Javascript, per other comments and answers.
A: Better way then using the dom to create elements have your divs or even img tags src be blank then load them with the images you want in an onload function using innerHTML:
function images(){
var place_to_put_image = document.getElementById("image_div");
place_to_put_image.innerHTML = "<img src=\"your_image_here\"></img>";
}
<body onload="images()>
<div id="image_div></div>
</body>
you could put your images in an array and assign the innerHTML of the div or whatever to the array as well if you want them all in the same place or you could put the onload in div or where ever you want the images to load.
A: There a few ways you can go about doing it but they all involve not actually putting the images in the HTML - at least not correctly. One way that I like to do it is to add the image src URLs to another property like the alt (not great for accessibility) or rel. Also, give all the images a class that will be used to hook into it with JS.
<img alt="images/foo.jpg" class="loadlater" />
Then in your JS, get all elements with class="loadlater" and set the source to the alt value.
img.src = img.alt;
You didnt mention jQuery. If you were using jQuery, the command to swap the attributes would look like this:
$('.loadlater').each(function() { this.src=this.alt; });
Then, wherever and whenever you call this, the images will be loaded. You will want to call it after your css and js finishes loading - probably the document.load function. Again, if you were using jQuery, it would look like this:
$(function()
{
$('.loadlater').each(function() { this.src=this.alt; });
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Approach for Automating localized Web application in Selenium using Java Bindings I am automating test cases for a web application using selenium 2.0 and Java. My application supports multiple languages. Some of the test cases require me to validate the text that appears in the UI like success/error messages etc.I am using a properties file to store whatever text I am referring in my tests from the UI, currently only english. For example there is locale_english.properties(see below) that contains all references in english. I am going to have multiple properties files like this for different locales like locale_chinese.properties,locale_french.properties and so on. For locales other than english, their corresponding properties file would have UTF-8 characters (e.g \u30ed) representing the native characters(see below). So If I want to test say Chinese UI, I would load "locale_chinese.properties" instead of "locale_english.properties". I am going to convert the native characters for non-english locale using perhaps native2ascii from JDK or some other way.I tested that Selenium API works well with UTF-8 characters for non-english locales
---locale_english.properties------
user.login.error= Please verify username/password
---locale_chinese.properties------
user.login.error= \u30ed\u30ef\u30eg\u30eh\u30ed
and so on.
The problem is that my locale_english.properties is growing and going out of control. It is becoming hard to manage a single properties file for one locale let alone for multiple locales. Is there a better way of handling localization in Java, particularly in situations like I am in?
Thanks!
A: You're right that there is a problem managing the files, but you're also right that this is the best approach. Some things are just hard :-(
Selenium (at least the Selenium RC API) does indeed support Unicode input and output, we have lots of tests that enter and confirm Cyrillic and Simple Chinese characters from C#. Since Java strings are Unicode at the core (just like C#), I expect you could simply create the file in a UTF-8-friendly editor like Notepad++ and read them straight into strings and use them directly in the Selenium API.
A: This is how I solved the issue for those who are interested.
A: a database would work better for many reasons, like growth, central location, kept outside of app and can be edited and maintained outside of app. We used a table with columns:
id (int) auto increment
id_text -- this and other columns are varchar ... except for date time for last 2
lang
translation
created_by
updated_by
created_date
updated_date
An id is a short english description of the text - like 'hello' or 'error1msg', the key in your map.
In java had a function to get the text for a particular text ... and a app level property - default language (usually en but good to keep it configurable)
Function would scan already loaded hashmap for language asked for - say "ch"
If corresponding translation was not found for this language we would return the default language translation and if that was not founf then we would return "[" + id "]" so the tester knows something is missing in data base - can go to web screen to edit translation table and add it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Adding and removing an element multiple times with jQuery I'm using jQuery to append a youtube video when a button is clicked.
onclick="$('#videogallery').append('<iframe width=725 height=398 src=http://www.youtube.com/embed/8Pi-dHJSkrk frameborder=0 allowfullscreen></iframe>');"
I'm then using jQuery again to remove it when another button is clicked.
onclick="$('iframe').remove();"
It works fine the first time around but If I add the video, remove it, and then try to add it again. It adds and removes itself instantly.
Why is this happening? It seems like the $('iframe').remove(); function is running constantly after the button is clicked.
EDIT
Here is the expanded version of the code.
<div class="product-media" id="product-media1">
<map name="submenu3" onclick="$('iframe').remove();">
<area shape="rect" coords="0, 0, 95, 25" onClick="swap3('product-media1','product-details1');">
<area shape="rect" coords="103, 0, 213, 25" onClick="swap3('product-media1','product-specs1');">
</map>
<img src="images/submenu3.jpg" alt="" border="0" usemap="submenu3" /><br /><br />
<p> </p>
<div id="videogallery">
<a rel="#voverlay" href="#" onclick="$('#videogallery').append('<iframe width=725 height=398 src=http://www.youtube.com/embed/8Pi-dHJSkrk frameborder=0 allowfullscreen></iframe>');">
<span class="thumb" onClick="swapvid"><img src="images/video.jpg" alt="" align="left" /></span><span></span>
</a><br />
Watch Scotch-Brite™ Radial Discs in action
</div>
</div>
A: This works fine: http://jsfiddle.net/YssHJ/
$('#add').click(function(){
$('#vid').append('<iframe width=725 height=398 src=http://www.youtube.com/embed/8Pi-dHJSkrk frameborder=0 allowfullscreen></iframe>');
});
$('#del').click(function(){
$('iframe').remove();
});
EDIT: fiddle using a map click http://jsfiddle.net/YssHJ/2/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Calculating the datetime for a future event timing I am creating a function that will set the date of an event, based on the current time.
I have an enumeration of events:
public enum EventTimings
{
Every12Hours, // 12pm and midnight
Weekly // sunday at midnight
}
public static DateTime CalculateEventTime(EventTimings eventTime)
{
DateTime time;
switch(eventTime)
{
case EventTimings.Every12Hours:
break;
}
return time;
}
So (Every12Hour event type) if the current time is 10am, then the eventdate will be the same day but at 12pm.
How should I write this?
I also have to make sure this works for December 31st and any other strange outlier date/time.
Is datetime the best for this scenerio?
A: If you want to be able to test anything, I would make the DateTime you are trying to "round" explicit, something like
public static DateTime RoundedDate(DateTime eventTime, EventTimings strategy)
{
switch (strategy)
case EventTimings.Weekly :
return WeeklyRounding(eventTime);
... etc ...
That way you can now write a specialized method for the 12-hour interval, the week interval, and test it for any input date possible, without depending on your computer clock.
A: I agree to keep it generic by making the reference date an input parameter instead of current datetime. However as you have asked about the logic for your eventTime values as well, this is how I would go about.
How should I write this?
For every12hours, check the hour property of the input date and check if it is less than 12. If so, then create a new TimeSpan for 12pm and add it to the datepart of the input date.
If not, add 1 day to the input date, create a TimeSpan for 12am and add it to the datepart of inputdate.
For weekly (Monday 12am), check the dayoftheweek of the inputdate and just add number of days to make it equal to the incoming Monday (Which is as simple as (8 - dayoftheweek)) and add a 12am TimeSpan to the date of the incoming Monday's date.
public enum EventTimings
{
Every12Hours, // 12pm and midnight
Weekly // sunday at midnight
}
public static DateTime CalculateEventTime(EventTimings eventTime, DateTime inputDate)
{
DateTime time = DateTime.Now;
switch (eventTime)
{
case EventTimings.Every12Hours:
time = inputDate.Hour > 12 ? inputDate.AddDays(1).Date + new TimeSpan(0, 0, 0) : inputDate.Date + new TimeSpan(12, 0, 0);
return time;
case EventTimings.Weekly:
int dayoftheweek = (int) inputDate.DayOfWeek;
time = inputDate.AddDays(8 - dayoftheweek).Date + new TimeSpan(0, 0, 0);
return time;
// other cases
}
}
Is datetime the best for this scenerio?
Yes. Your datetime calculations using DateTime and TimeSpan should take care of leap years, daylight savings or endofyear scenarios. Additionally you could try adding SpecifyKind to denote it is local time.
A: You could also try something like this, although it breaks down if you want to do something monthly (because months each have a different number of days.) Also, while this simplified method will ensure a returned date at 12 and midnight, the weekly offset would be every 7 days from the starting day... not necessarily on Sundays. You could easily accomodate that behavior with a switch statement, though. The overloaded method also allows you some flexibility to provide a custom offset.
Also, to answer your question, yes I would use System.DateTime and System.TimeSpan. They handle determining whether a year or month has "rolled over" for you.
public enum EventTimings : int
{
Default = 12, // Default every 12 hours.
NoonAndMidnight = 12, // Every 12 hours.
Weekly = 168, // 168 hours in a week.
ThirtyDays = 720 // 720 hours in 30 days.
}
public DateTime CalculateDateTime(DateTime starting, EventTimings timing)
{
return CalculateDateTime(starting, TimeSpan.FromHours((int)timing));
}
public DateTime CalculateDateTime(DateTime starting, TimeSpan span)
{
DateTime baseTime = new DateTime(starting.Year, starting.Month, starting.Day, starting.Hour >= 12 ? 12 : 0, 0, 0);
return baseTime.Add(span);
}
A: The algorithm I'd follow goes like this...
*
*Put noon on the day of eventTime into a variable
*Check if that variable is before eventTime
*If it's not, add 12 hours to it
*Return the variable
switch (strategy)
{
case EventTimings.Every12Hours:
//get noon for the event date
DateTime x = eventTime.Date.AddHours(12);
//check to see if x is after the eventTime
if (x < eventTime)
{
//if so, advance x by 12 hours to get midnight on the next day
x = x.AddHours(12);
}
return x;
break;
//other cases...
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Creating a String[] from Guava's Splitter Is there a more efficient way to create a string array from Guava's Splitter than the following?
Lists.newArrayList(splitter.split()).toArray(new String[0]);
A: Probably not so much more efficient, but a lot clearer would be Iterables.toArray(Iterable, Class)
This pretty much does what you do already:
public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) {
Collection<? extends T> collection = toCollection(iterable);
T[] array = ObjectArrays.newArray(type, collection.size());
return collection.toArray(array);
}
By using the collection.size() this should even be a tick faster than creating a zero-length array just for the type information and having toArray() create a correctly sized array from that.
A: How about
Iterables.toArray(splitter.split(), String.class);
since there's an Iterables.toArray() method
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
}
|
Q: SQL Server XML query using xquery with repeating relational data I have a questionnaire stored in a XML column that I want to store in a non-xml table format instead. The source table looks like this:
ID VERSION content
----------- ------- ---------------------------------------------------------------------
1211 96 <QS mg_id="1" locale_id="0" logoimg="inbox/FormImages/15/180.gif"...
1211 97 <QS mg_id="1" locale_id="0" logoimg="inbox/FormImages/15/180.gif"...
content:
<QS mg_id="1" locale_id="0" logoimg="inbox/FormImages/15/180.gif">
<PAGE id="1" topic="Demographics" progress="9" background="inbox/FormImages/15/176.gif" lastPage="false" flush_concepts="1">
<QUESTION id="2" type="dropdown" style="font-family:arial;font-size:12px;color:#086BB5;font-weight:bold;" value="What is your age?" defaultvalue="" listid="" conceptid="">
<OPTIONS>
<OPTION score="0" concept_value="1" value="I am under 18" url="" id="0" />
<OPTION score="0" concept_value="2" value="Between 18 and 30 years old" url="" id="1" />
<OPTION score="0" concept_value="3" value="Between 30 and 50 years old" url="" id="2" />
<OPTION score="0" concept_value="4" value="Between 50 and 70 years old" url="" id="3" />
<OPTION score="0" concept_value="5" value="Between 70 and 90 years old" url="" id="4" />
<OPTION score="0" concept_value="6" value="Over 90 years old" url="" id="5" />
</OPTIONS>
</QUESTION>
<QUESTION id="4" type="dropdown" style="font-family:arial;font-size:12px;color:#086BB5;font-weight:bold;" value="Do you have children?" defaultvalue="" listid="" tooltip="" usability="5">
<OPTIONS>
<OPTION score="0" concept_value="1" value="Yes" url="" id="0" />
<OPTION score="0" concept_value="0" value="No" url="" id="1" />
</OPTIONS>
</QUESTION>
</PAGE>
</QS>
And I want to get output of the form:
ID VERSION QuestionID QuestionValue OptionID OptionValue
----------- ------- ---------- ----------------- --------- -------------------------------
1211 96 2 What is your age? 1 I am under 18
1211 96 2 What is your age? 2 Between 18 and 30 years old
....
1211 96 4 Do you have children 1 Yes
....
1211 97 2 ...
Is there a way to do that using a select statement with SQL Server 2008?
A: Try this query:
SELECT
ID,
Version,
Q.value('(@id)[1]', 'int') AS 'QuestionID',
Q.value('(@value)[1]', 'varchar(50)') AS 'QuestionValue',
OPT.value('(@id)[1]', 'int') AS 'OptionID',
OPT.value('(@value)[1]', 'varchar(50)') AS 'OptionValue'
FROM
dbo.YourTableNameHere
CROSS APPLY
XmlCol.nodes('QS/PAGE/QUESTION') AS QS(Q)
CROSS APPLY
QS.Q.nodes('./OPTIONS/OPTION') AS OPTS(OPT)
You need to use two CROSS APPLY operators to
*
*get a list of all <QUESTION> nodes inside your XML
*get a sub-list of all <OPTION> nodes inside a given <QUESTION> to get the option information for each question
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to Incorporate ISA & GS Segment Values into EDI XML generated by BizTalk 2009 I have a receive port setup in BizTalk 2009 to accept & disassemble X12837 EDI Files. There is also a send port that picks up disassembled EDI from the receive port and converts into EDI XML files. The send port is associated with a Party, with the ISA & GS segment values associated with it.
My Issue is that BizTalk pulls out ISA & GS segments out of the disassembled EDI XML files.
How can I get BizTalk to populate the ISA & GS segments into the disassembled EDI XML generated?
A: BizTalk pulls out the ISA and GS segments and promotes some of the data to the message context provided you have a party configured with the appropriate ISA/GS data. You can subscribe send ports and orchestrations to the promoted data for message routing or you can reference the data within an orchestration expression shape if you need it for some other purpose.
Please clarify your requirements and I will be sure to respond with more specific details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does OpenFileDialog freeze WinForms app on a specific machine? I have a WinForms app deployed to multiple machines in the same office. Up until this Monday, all users in the office used the app without issue and used the OpenFileDialog to select files to import. One machine had lots of updates to other apps and now freezes when our app tries to show the OpenFileDialog. It shows the OpenFolderDialog fine; though I failed to try the SaveFileDialog. Just to repeat, it worked last week, our app was not updated, but it freezes on one machine this week whereas it works on all other machines in the office.
The machine in question has another .NET app installed and I verified the OpenFileDialog opens without issue in the other app.
Any ideas as to why the OpenFileDialog would freeze on one machine? Any ideas on how to fix this? We could try reinstalling without knowing the cause, but I figured it is better to investigate why to prevent it from happening again.
A: This machine may have connected to a network resource in the past, which is no longer available. OpenFileDialog could be waiting for the network resource to respond, which will take several minutes to timeout.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Return a pointer to an array Suppose you have a class with a private pointer to an array. How can you use a getter to access (or effectively copy the data) so you can access it in a different variable.
class MyClass
{
private:
double *x;
public:
myClass();
virtual ~MyClass();
double* getX() const;
void setX(double* input);
};
MyClass::MyClass()
{
double foo[2];
double * xInput;
foo[0] = 1;
foo[1] = 2;
xInput = foo;
setX(xInput);
}
void MyClass::setX(double * input)
{
x = input;
}
double * MyClass::getX() const;
{
return x;
}
int main()
{
MyClass spam(); // Construct object
double * bar = spam.getX(); // This doesn't work
}
In this case, bar[0] and bar[1] are equal to jibberish: -9.2559631349317831e+061.
A: MyClass spam(); // Construct object
That does not construct an object, that declares a function called spam that takes no arguments and returns a MyClass. This default constructs an object:
MyClass spam; // Construct object
For more information google the most vexing parse.
Update: As @Mark Ransom pointed out, there is another problem with your code. In your constructor you create an array, and then set x to point to such array. However the array lifetime ends once the constructor finishes execution, so further access to x would crash (if you are lucky enough).
A: Just a guess, the program is crashing or showing the wrong output. This is because the constructor is setting a pointer to a local array, which leaves scope and gets destroyed at the end of the constructor.
A: That should probably be *bar instead of bar[0].
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How Override Yii Framework's config/console.php with Local Console Configuration File? Yii framework's config/main.php file can be overwritten by a local.php configuration file via an array_merge. This allows me to set different database connections and other parameters specific to production, QA, and development environments.
Yii also allows me to run commands in the command line. It uses a config/console.php file. Is there a way I can set up a local console config file in the same way that will override the main console config depending on the environment?
A: Hmm, that's an interesting way of doing overriding the config. But it looks like you could just modify console.php in the same way you did the main.php (add local_config function to console.php and point it to console-local.php).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What are the benefits of using JSF2 resources? Should I use JSF2 resources instead of plain html like <link href... or url(image.png)? What are the benefits? For me this is a bit annoying when web-designer creates layout with XHTML, CSS and all that stuff and I need to spend time to replace plain HTML paths and tags to JSF resource tags like#{resource[...]}.
Is there any other way? Like to put all CSS/image files in web root and use normal links?
A: Your choice.
The major benefit is that you can declare them on a per-component basis. If you need to include them on every single page anyway, then the benefit is little. But if you need to include component-specific CSS/JS code in for example a composite component which is reused more than once in a single view, then for example an <h:outputScript> in a composite component would end up in it being included only once instead of that many times as the composite component is been used as would happen with <script>. The same applies to the @ResourceDependency annotation on real UIComponent classes.
Please note that you are not required to use JSF2 resources only. Just plain vanilla <img>, <link>, <script>, etc is also perfectly fine. It can even point to the JSF resources folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: aptana html highlighting not working well I just downloaded Aptana (v3.0.4) and I'm really liking it, much better for coding than Dreamweaver. The big problem I've found so far is that I can't get the HTML highlighting to work properly.
For example, I go to the Theme selector and choose one theme (in this case the Dreamweaver theme, since I'm already used to those colors). It works fine for php, javascript, css... but for HTML. It won't give different colors to the different html tags (like "a", "img", "form", etc). If I look at the colors palette, I can see that those tags have different colors assigned, but no matter what color they have in the palette, they take the color of the "html meta" element in the palette. So basically, ALL the tags have the same color, which is annoying.
Is there any way to fix this? I've even created a new theme copying the Dreamweaver one to make modifications, but still the same...
EDIT
It seems that this might have something to do with Scopes. The coloring rules work assigning a color to a certain scope (each coding element has one scope linked to it). In the colors palette, each of the html tags ("a","img",etc) has a different scope linked to it. However, if I use the Show Scope tool that Aptana has, all those elements show the same scope: text.html.basic meta.tag.block.any.html entity.name.tag.inline.any.html, instead of showing a different one each one. So since they all have the same scope, using the them editor you can't choose a different color for each one... Is there any other way to do it? Is it possible to change the assigned scope of an element?
A: These operations behave similar to CSS Selectors.
GO => entity.name.tag.inline.(form, img, p, etc.).html.
(1) OPEN the Preferences Theme Panel.
(2) ADD (+) a NEW element.
(3) SELECT your desired STYLES.
(4) PASTE your desired scope selector, e.g., "entity.name.tag.inline.form.html" INTO the Scope Selector FIELD… and CLICK 'Apply'.
(5) PRESTO CHANGE-O!
A: maybe check the default editor for html files in aptana?
Anyway, my aptana had always the same color for each tag.
A: All HTML tags currently have the same scope, so you can't (yet) do what you are asking. But please file a feature request so it can be added to the list.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: STL algorithm to delete all the objects in a container? Is there a STL utility/algorithm to do delete *the_object_iterator; on all the objects? So that I can clear() safely? The STL container is a set and the objects are pointers to C++ classes created with new.
Boost seems to be the best solution. My goal was to avoid copy-construction on noncopyable classes.
A: Boost pointer containers are the way to go.
Not only do they store the dynamically allocated objects. But the objects are accessible as references which makes using the standard algorithms on the the object that much easier.
boost::ptr_set<MyClass> setData;
setData.insert(new MyClass);
A: Use a smart pointer to hold the class pointers
std::set<std::unique_ptr<MyClass> > mySet;
A: As far as I know, there is no standard algorithm to delete all objects. However, you can build up one easily:
template< typename T > invoke_delete( T* ptr ){ delete ptr; }
std::for_each( set.begin(), set.end(), &invoke_delete< set_value_type > );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: how to prevent sprockets from caching a .erb file? Sprockets gem caches .erb files even though the ruby code in those might evaluate differently on every compilation
For example: foo.js.erb
var foo = <%= Kernel.rand %>;
evaluates it once and caches forever. How do you prevent certain files like this from being cached by sprockets?
A: You could separate your JavaScript into libraries (.js.erb or just .js) and configuration data (such as your var foo). Then leave all the library code in the hands of Sprocket and put your configuration into your normal ERB views (probably embedded in your layouts).
You could also serve the configuration data through a separate controller (/config.js perhaps) if that fits your architecture better.
This approach avoids your whole problem by separating static libraries from non-static data. Also, this approach fits nicely with the Rails 3.1 asset pipeline where you're supposed to pre-compile everything before your production deployments.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: AdMob banner above Tabs in TabsActivity I am trying to set the AdMob banner ABOVE the Tabs in a TabsActivity:
public class FundsReportTabsActivity extends TabsActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AdView adView = new AdView(activity, AdSize.BANNER, AD_UNIT_ID);
// Lookup your LinearLayout assuming it’s been given
// the attribute android:id="@+id/mainLayout"
// Add the adView to it
getTabHost().addView(adView, 0, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
AdRequest adRequest = new AdRequest();
adRequest.addTestDevice("E0154BC3F11C778234254195FA1164F");
adRequest.setTesting(true);
// Initiate a generic request to load it with an ad
adView.loadAd(adRequest);
}
However, the banner does not appear, even though I have this logcat:
09-29 22:23:09.755: INFO/Ads(16158): onReceiveAd()
and don't see any related warning/error.
Does anyone have an idea? Thanks!
A: Check your logcat for a warning or verbose saying no ads in inventory. Some times when you first sign up or are using admob it takes some time before the ads start appearing. Also make sure you have provided a linear layout for the ad. And if you watch the logcat file during the activity with the ad you will see a content containing items that pertain to the ad. I know i had trouble with admob at first. The same issue you are having. It just took some time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can an emulator instance send msgs to another machine? Will an Android utility that sends/listens to messages via sockets be able to connect to another machine on the network from the emulator? IOW, what I want to do is send and receive messages from one XP machine to another.
A: You have network access, so you should be able to setup TCP sockets.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: EF-Code first complex type with a navigational property My Model:
public class Country
{
public int CountryId { get; set; }
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class Location
{
public string Address { get; set; }
public virtual int CountryId { get; set; }
public virtual Country Country { get; set; }
}
public class User{
protected User()
{
Location = new Location();
}
public int UserId { get; set; }
public Location Location { get; set; }
}
When generating the database, I get:
One or more validation errors were detected during model generation:
System.Data.Edm.EdmEntityType: : EntityType 'Location' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet �Locations� is based on type �Location� that has no keys defined.
How do I have a navigational property inside a complex type? If I remove the country navigational property, it works fine.
A: EF wants to infer a primary key for Location, but can't.
Add a public int LocationId { get; set; } to the Location class and it should be happy.
If you want to use Location as a complex type, annotate it with a [ComplexType] attribute.
A: Navigation properties (refering to other entities) on a complex type are not supported. You must either make your Location an entity (with its own table) or remove the navigation property Country from Location (and add the [ComplexType] attribute as mentioned by Steve Morgan).
Edit
Reference: http://msdn.microsoft.com/en-us/library/bb738472.aspx
"Complex type cannot contain navigation properties."
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Parse Apache log in PHP using preg_match I need to save data in a table (for reporting, stats etc...) so a user can search by time, user agent etc. I have a script that runs every day that reads the Apache Log and then insert it in the database.
Log format:
10.1.1.150 - - [29/September/2011:14:21:49 -0400] "GET /info/ HTTP/1.1" 200 9955 "http://www.domain.com/download/" "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1"
My regex:
preg_match('/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) (\".*?\") (\".*?\")$/',$log, $matches);
Now when I print:
print_r($matches);
Array
(
[0] => 10.1.1.150 - - [29/September/2011:14:21:49 -0400] "GET /info/ HTTP/1.1" 200 9955 "http://www.domain.com/download/" "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1"
[1] => 10.1.1.150
[2] => -
[3] => -
[4] => 29/September/2011
[5] => 14:21:49
[6] => -0400
[7] => GET
[8] => /info/
[9] => HTTP/1.1
[10] => 200
[11] => 9955
[12] => "http://www.domain.com/download/"
[13] => "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1"
)
I get: "http://www.domain.com/download/" and same for user agent. How can I get rid of these " in the regex? Bonus (Is there any quick way to insert the date/time easily)?
Thanks
A: To parse an Apache access_log log in PHP you can use this regex:
$regex = '/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) "([^"]*)" "([^"]*)"$/';
preg_match($regex ,$log, $matches);
To match the Apache error_log format, you can use this regex:
$regex = '/^\[([^\]]+)\] \[([^\]]+)\] (?:\[client ([^\]]+)\])?\s*(.*)$/i';
preg_match($regex, $log, $matches);
$matches[1] = Date and time, $matches[2] = severity,
$matches[3] = client addr (if present) $matches[4] = log message
It matches lines with or without the client:
[Tue Feb 28 11:42:31 2012] [notice] Apache/2.4.1 (Unix) mod_ssl/2.4.1 OpenSSL/0.9.8k PHP/5.3.10 configured -- resuming normal operations
[Tue Feb 28 14:34:41 2012] [error] [client 192.168.50.10] Symbolic link not allowed or link target not accessible: /usr/local/apache2/htdocs/x.js
A: If you don't want to capture the double quotes, move them out of the capture groups.
(\".*?\")
Should become:
\"(.*?)\"
As alternative you could just post-process the entries with trim($str, '"')
A: your regexp are wrong.
you shoudl use correct regexp
/^(\S+) (\S+) (\S+) - \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) "([^"]*)" "([^"]*)"$/
A: As I've seen and done so many errneous log parsing, here is a hopefully valid regex, tested on 50k lines of logs without any single diff, knowing that:
*
*auth_user can have spaces
*response_size can be -
*http_start_line can at least one space (HTTP/0.9) or two
*http_start_line may contain double quotes
*referrer can be empty, have spaces, or double quotes (it's just an HTTP header)
*user_agent can be empty too, or contain double quotes, and spaces
*It's hard to distinguish between referrer and user-agent, let's just home the " " between both is discriminent enough, yet we can find the infamous " " in the referrer and in the user-agent, so basically, we're screwed here.
$ncsa_re = '/^(?P<IP>\S+)
\ (?P<ident>\S)
\ (?P<auth_user>.*?) # Spaces are allowed here, can be empty.
\ (?P<date>\[[^]]+\])
\ "(?P<http_start_line>.+ .+)" # At least one space: HTTP 0.9
\ (?P<status_code>[0-9]+) # Status code is _always_ an integer
\ (?P<response_size>(?:[0-9]+|-)) # Response size can be -
\ "(?P<referrer>.*)" # Referrer can contains everything: its just a header
\ "(?P<user_agent>.*)"$/x';
Hope that's help.
A: I've tried using a couple of the regexps here Jan 2015, and find that a bad bot is not getting a match in my apache2 log.
The bad bot apache2 line is a BASH hack attempt, and I haven't tried to figure out the regexp correction yet:
199.217.117.211 - - [18/Jan/2015:10:52:27 -0500] "GET /cgi-bin/help.cgi HTTP/1.0" 404 498 "-" "() { :;}; /bin/bash -c \"cd /tmp;wget http://185.28.190.69/mc;curl -O http://185.28.190.69/mc;perl mc;perl /tmp/mc\""
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
}
|
Q: Updating Deployed SSIS Package I have a deployed SSIS package, with a schedule and everything. Now, I have made changes to this package. Do I have to re-deploy it, and setup the schedule for it again, or is there a way for an already deployed SSIS package to be updated with the latest build?
A: Yes, you need to redeploy the package(s) to whatever location the scheduler expects to find the package(s).
You do not, however, need to recreate the job, configurations or any of that jazz, simply perform an in-place replacement of the dtsx package. If you stored it to the file system, copy the new version over it. If you stored it in SQL Server, use the command-line to replace it (approximately dtutil /file PkgName.dtsx /destserver thatdatabase /copy SQL;PkgName) or use the ssismanifest to deploy packages or my current favourite, use PowerShell for SSIS deployment and maintenance
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Loss of referenced dll in ClickOnce publish after signing main .exe I added a post-build step to use signtool on my executable using a pfx file. This happens successfully but something gets broken when I try to publish with ClickOnce. If I just build, my .exe.manifest will have an entry to install the reference. However, if I select publish (with ClickOnce), the .exe.manifest gets altered so that the reference isn't even mentioned. This does not happen if I do not run the signtool post-build step.
Update It seems that at the time of publish, ClickOnce scans the .exe file for dependencies and rebuilds the manifest. However, if the .exe is signed with signtool, ClickOnce is not able to properly pull all the details. The result is that the manifest has missing pieces. Yuck.
A: Why are you using signtool on the exe? If you want to sign the exe, you can specify that in the Signing tab (sign the assembly -- the strong naming option).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Binding NSPopUpButton to NSArray I'm a little lost with bindings on NSPopUpButton. I have a custom class that holds an array of items that I'd like to display in a pop up. These items are subclasses of NSManagedObjects and they are contained in an NSArray. I don't want to use an NSArrayController since I've had lots of trouble changing the selection programmatically and it feels like cluttering the implementation.
The problem is simply that I don't know how to bind the array properly to the pop up. All I have managed to do is list the array items on the pop up menu, but the titles are core data URIs. I believe I could use the description method to change the title, but this does not sound very advisable.
Any ideas how to bind NSArray to the NSPopUpButton properly?
A: I think I solved it. I simply created these bindings for NSPopUpButton:
*
*"Content" to the items property (of type NSArray*)
*"Selected Object" to selectedItem (of type Item*)
*Finally "Content Values" to items.name
For the third binding I implemented valueForKeyPath:
- (id)valueForKeyPath:(NSString *)keyPath
{
NSArray *components = [keyPath componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]];
if ([components count] == 2 && [components objectAtIndex:0] == @"items")
{
return [self.items valueForKey:[components objectAtIndex:1]];
}
return [super valueForKeyPath:keyPath];
}
The third binding could've been also a separate array for titles, but I this is much more flexible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Display Alert when element passes a certain left position? I have an element with a fixed position, it's animated with js and it's left position changes from 0 to 1000 randomly.
How can I display an alert each time the element crosses the 500px barrier?
I could only think of making an infinite loop that checks if leftpos < 500px and then using a variable to store whether he is right or left and display the alert when the variable changes but it seems over complicated though maybe it's the only solution.
Is there a better solution to doing this?
A: If you are using Javascript to move the element around you can add this check to the re-positioning code.
If it is somebody that drags and drops it, you could use the mouseup to to fire a javascript method to check location.
A: PHP is server-side code. That mean the code is executed on the server and the output is sent to the client. Therefor, PHP can't do what you want. You need JavaScript. Check out something like jQuery and its position API and maybe a alert plugin if you want to get fancy:
*
*Position
*Alert
Alternatively, you could just use a standard JavaScript alert.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Determine which bit is set, for a date, using complex bit masks I have a bit shift mask that represents days in a week:
Sunday = 1
Monday = 2
Tuesday = 4
...
Saturday = 64
I'm using a bitmask because several (at least one) days may be set to 1.
The problem
Then I get a date. Any date. And based on the date.DayOfWeek I need to return the first nearest date after it that is set in the bitmask. So my method can return the same day or any other day between date and date + 6.
Example 1
My bitmask defines all days being set to 1. In this case my method should return the same date, because date.DayOfWeek is set in the bitmask.
Example 2
My bitmask defines that only Wednesday is set to 1. If my incoming date is Tuesday, I should return date+1 (which is Wednesday). But if incoming date is Thursday I should return date+6 (which is again Wednesday).
Question
What is the fastest and most elegant way of solving this? Why also fastest? Because I need to run this several times so if I can use some sort of a cached structure to get dates faster it would be preferred.
Can you suggest some guidance to solve this in an elegant way? I don't want to end up with a long spaghetti code full of ifs and switch-case statements...
Important: It's important to note that bitmask may be changed or replaced by something else if it aids better performance and simplicity of code. So bitmask is not set in stone...
A possible approach
It would be smart to generate an array of offsets per day and save it in a private class variable. Generate it once and reuse it afterwards like:
return date.AddDays(cachedDayOffsets[date.DayOfWeek]);
This way we don't use bitmask at all and the only problem is how to generate the array the fastest and with as short code as possible.
A: I'd go about this with a bitmask, some shifting, and a bitscan. It's not a very obvious routine, but it should be fast, as it never branches:
original_date = Whatever //user input
bitmask = Whatever //user input
bitmask |= (bitmask << 7) //copy some bits so they don't get
//lost in the bitshift
bitmask >>= original_date.dayOfWeek() //assuming Sunday.dayOfWeek() == 0
return original_date + bitscan(bitmask) - 1 //the position of the least
//significant bit will be one greater
//than the number of days to add
Bitscan - especially yours, 'cause it only cares about seven bits - is easy to implement in a lookup table. In fact, if you did a custom table, you could call the LSB bit 0, and skip the subtraction in the return statement. I'd guess the slowest part of all of this would be the dayOfWeek() function, but that would depend on it's implementation.
Hope this helps!
Edit: An example bitscan table (that treats the lsb as index 1 - you'll probably want to treat it as zero, but this makes a better example):
int[128] lsb = {
0, //0 = 0b00000000 - Special case!
1, //1 = 0b00000001
2, //2 = 0b00000010
1, //3 = 0b00000011
3, //4 = 0b00000100
1, //5 = 0b00000101
2, //6 = 0b00000110
....
1 //127 = 0b01111111
};
Then, to use your table on mask, you'd just use:
first_bit_index = lsb[mask & 127];
The & lets you write a smallish table, 'cause you really only care about the seven lowest bits.
PS: At least some processors implement a bitscan instruction that you could use instead, but it seems unlikely that you could get at them with C#, unless there's a wrapper function somewhere.
A: You might hate this answer, but perhaps you'll be able to run with it in a new direction. You said performance is extremely important, so maybe it's best to just index all the answers up front in some data structure. That data structure might be somewhat convoluted, but it could be encapsulated in its own little world and not interfere with your main code. The data structure I have in mind would be an array of ints. If you allow Monday, Friday, and Saturday, those ints would be:
[1][0][3][2][1][0][0]
Ok weird right? This is basically the "days away" list for the week. On Sunday, there's "1 day until next allowed day of week". On Monday, there's 0. On Tuesday, it's 3 days away. Now, once you build this list, you can very easily and very quickly figure out how many days you need to add to your date to get the next occurance. Hopefully this helps??
Generating these offsets
This is the code that generates these offsets:
this.dayOffsets = new int[] {
this.Sundays ? 0 : this.Mondays ? 1 : this.Tuesdays ? 2 : this.Wednesdays ? 3 : this.Thursdays ? 4 : this.Fridays ? 5 : 6,
this.Mondays ? 0 : this.Tuesdays ? 1 : this.Wednesdays ? 2 : this.Thursdays ? 3 : this.Fridays ? 4 : this.Saturdays ? 5 : 6,
this.Tuesdays ? 0 : this.Wednesdays ? 1 : this.Thursdays ? 2 : this.Fridays ? 3 : this.Saturdays ? 4 : this.Sundays ? 5 : 6,
this.Wednesdays ? 0 : this.Thursdays ? 1 : this.Fridays ? 2 : this.Saturdays ? 3 : this.Sundays ? 4 : this.Mondays ? 5 : 6,
this.Thursdays ? 0 : this.Fridays ? 1 : this.Saturdays ? 2 : this.Sundays ? 3 : this.Mondays ? 4 : this.Tuesdays ? 5 : 6,
this.Fridays ? 0 : this.Saturdays ? 1 : this.Sundays ? 2 : this.Mondays ? 3 : this.Tuesdays ? 4 : this.Wednesdays ? 5 : 6,
this.Saturdays ? 0 : this.Sundays ? 1 : this.Mondays ? 2 : this.Tuesdays ? 3 : this.Wednesdays ? 4 : this.Thursdays ? 5 : 6
};
This one generates forward offsets. So for any given date you can get the actual applicable date after it by simply:
SomeDate.AddDays(this.dayOffsets[(int)SomeDate.DayOfWeek]);
If you need to get nearest past date you can reuse the same array and calculate it out by using this formula:
SomeDate.AddDays((this.dayOffsets[(int)SomeDate.DayOfWeek] - 7) % 7);
A: Here's an algorithm to populate the lookup table. You only have to do it once, so I'm not sure that it matters how efficient it is...
int[] DaysOfWeek = (int[])Enum.GetValues(typeof(DayOfWeek));
int NumberOfDaysInWeek = DaysOfWeek.Length;
int NumberOfMasks = 1 << NumberOfDaysInWeek;
int[,] OffsetLookup = new int[NumberOfDaysInWeek, NumberOfMasks];
//populate offset lookup
for(int mask = 1; mask < NumberOfMasks; mask++)
{
for(int d = 0; d < NumberOfDaysInWeek; d++)
{
OffsetLookup[d, mask] = (from x in DaysOfWeek
where ((1 << x) & mask) != 0
orderby Math.Abs(x - d)
select (x - d) % NumberOfDaysInWeek).First();
}
}
Then just use:
DateTime SomeDate = ...; //get a date
DateTime FirstDate = SomeDate.AddDays(OffsetLookup[SomeDate.DayOfWeek, DayOfWeekMask]);
A: Here is what I'd do, the variable dateDiff will be what you are looking for.
DoW mask = DoW.Wednesday | DoW.Friday;
DoW? todayDoW = null;
int dateDiff = 0;
do
{
DateTime date = DateTime.Today.AddDays(dateDiff);
todayDoW = (DoW)Enum.Parse(typeof(DoW), date.DayOfWeek.ToString());
if ((mask & todayDoW.Value) != 0)
{
todayDoW = null;
}
else
{
dateDiff++;
}
}
while(todayDoW.HasValue);
enum DoW
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
A: This should be pretty easy to do. Consider that DayOfWeek.Sunday == 0, Monday == 1, etc.
Your mask corresponds to to this. That is, in your mask:
Sunday = 1 << 0
Monday = 1 << 1
Tuesday = 1 << 2
Now, given a day of week, we can easily determine the day that will match your criteria:
[Flags]
enum DayMask
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
static DayOfWeek FindNextDay(DayMask mask, DayOfWeek currentDay)
{
DayOfWeek bestDay = currentDay;
int bmask = 1;
for (int checkDay = 0; checkDay < 7; ++checkDay)
{
if (((int)mask & bmask) != 0)
{
if (checkDay >= (int)currentDay)
{
bestDay = (DayOfWeek)checkDay;
break;
}
else if (bestDay == currentDay)
{
bestDay = (DayOfWeek)checkDay;
}
}
bmask <<= 1;
}
return bestDay;
}
For example, the day you want to match is Wednesday, but the mask contains only Monday. You can see that the algorithm will select Monday as the best day and then go through the rest of the days, not selecting anything.
If the mask contains Monday, Tuesday, and Thursday, the algorithm will select Monday as the best candidate, ignore Tuesday, and then select Thursday as the best candidate and exit.
This won't be as fast as a lookup table, but it should be pretty darned fast. And it'll use a lot less memory than a lookup table.
A lookup table would be much faster, and it wouldn't take but a kilobyte of memory. And given the FindNextDay method above, it's easy enough to construct:
static byte[,] LookupTable = new byte[128, 7];
static void BuildLookupTable()
{
for (int i = 0; i < 128; ++i)
{
DayMask mask = (DayMask)i;
for (int day = 0; day < 7; ++day)
{
LookupTable[i, day] = (byte)FindNextDay(mask, (DayOfWeek)day);
}
}
}
Now, to get the next day for any combination of mask and current day:
DayOfWeek nextDay = (DayOfWeek)LookupTable[(int)mask, (int)currentDay];
There's undoubtedly a faster way to generate the table. But it's fast enough and since it would be executed once at program startup, there doesn't seem much point in optimizing it. If you want startup to be faster, write a little program that will output the table as C# code. Something like:
Console.WriteLine("static byte[,] LookupTable = new byte[128,7] {");
for (int i = 0; i < 128; ++i)
{
Console.Write(" {");
for (int j = 0; j < 7; ++j)
{
if (j > 0)
{
Console.Write(",");
}
Console.Write(" {0}", LookupTable[i, j]);
}
Console.WriteLine(" },");
}
Console.WriteLine("};");
Then you can copy and paste that into your program.
A: I understand that you said performance is to be taken in consideration but I would start with a simple, easy to understand approach and verify if its performance is sufficient before jumping to a more complex method that can leave future maintainers of the code a bit lost.
Having said that, a possible solution using pre-initialized lookups:
[Flags]
enum DaysOfWeek
{
None = 0,
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
Assuming the previous enumeration:
private static Dictionary<DayOfWeek, List<DaysOfWeek>> Maps { get; set; }
static void Main(string[] args)
{
Maps = CreateMaps();
var date = new DateTime(2011, 9, 29);
var mask = DaysOfWeek.Wednesday | DaysOfWeek.Friday;
var sw = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
GetNextDay(date, mask);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
private static DaysOfWeek GetNextDay(DateTime date, DaysOfWeek mask)
{
return Maps[date.DayOfWeek].First(dow => mask.HasFlag(dow));
}
And finally the CreateMaps implementation:
private static Dictionary<DayOfWeek, List<DaysOfWeek>> CreateMaps()
{
var maps = new Dictionary<DayOfWeek, List<DaysOfWeek>>();
var daysOfWeek = new List<DaysOfWeek>(7)
{
DaysOfWeek.Sunday,
DaysOfWeek.Monday,
DaysOfWeek.Tuesday,
DaysOfWeek.Wednesday,
DaysOfWeek.Thursday,
DaysOfWeek.Friday,
DaysOfWeek.Saturday
};
foreach (DayOfWeek dayOfWeek in Enum.GetValues(typeof(DayOfWeek)))
{
var map = new List<DaysOfWeek>(7);
for (int i = (int)dayOfWeek; i < 7; i++)
{
map.Add(daysOfWeek[i]);
}
for (int i = 0; i < (int)dayOfWeek; i++)
{
map.Add(daysOfWeek[i]);
}
maps.Add(dayOfWeek, map);
}
return maps;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to use LINQ (or TSQL) to group dataset but include top item and counts I'm struggling with how to approach this. I have your basic dataset returned by a TSQL (SQL2005) query where the data contains a list of master and detail items. Pretty vanilla, you have your master table joined to your detail table so you might get mulitple rows back per master record.
Something like:
ID / Item Descr / Subitem Descr
1 / Jane Doe / shoes
1 / Jane Doe / hats
2 / John Smith / hats
What I'd like to get to do is "flatten" that out a bit. So something like:
ID / Item Descr / Count / Most Recent Subitem
1 / Jane Doe / 2 / shoes
2 / John Smith / 1 / hats
Any suggestions on the sql query, or perhaps a LINQ query that I could run on the dataset I get back from the initial sql query...?
A: var q = from i in Context.Items
group i by i.ItemDescr into g
select new
{
ID = g.FirstOrDefault().ID,
ItemDescr = g.Key,
Count = g.Count(),
MostRecentSubItem = g.FirstOrDefault().SubitemDescr // you don't show how to pick the "most recent"
};
A: Not quite sure what you mean by "top" but this is a start if you want to do it in SQL:
SELECT id, ItemDesc, COUNT(*), MAX(SubItemDesc)
FROM MyTable
GROUP BY id, ItemDesc
A: I ended up using a correlated sub-query, which always make me nervous from a performance perspective. I don't have numbers to back that up and am not great at reading Execution Plans, it's just a gut feeling.
Lot's of good stackoverflow examples on it that got me down that path(like: Advanced SQL query with sub queries, group by, count and sum functions in to SQLalchemy and Variant use of the GROUP BY clause in TSQL)
I was wondering if using any of the new windowing functions (row_number() or rank()) would have helped, but I didn't get very far down that line.
I still wonder if it would be better to just pull back all the master-detail rows, then "post process" them using LINQ would be better. Our SQL Server would throw back that dataset to the web server pretty darn fast, then "distribute" the work load by doing LINQ on the web server, finally binding it all up to my ASP.NET gridview and sending it the client. A lot of moving parts, but could be interesting...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to download a file returned "indirectly"(??) from html form submission? (python, urllib, urllib2, etc.) EDIT: Problem solve. Ultimately it turned out to be a matter of "http:" instead of "https:" in the url (just a stupid mistake on my part). But it was the nice clean code example from cetver that helped me isolate the problem. Thanks to all who offered suggestions.
Putting this url in firefox triggers the appropriate download and save-as dialog:
https://www.virwox.com/orders.php?download_open=Download&format_open=.xls
The above link is same as submitting form with a "download" button of form on the page https://www.virwox.com/orders.php.
Here is the relevant html for the form that generates the above url:
<form action='orders.php' method='get'><fieldset><legend>Open Orders (2):</legend>
<input type='submit' value='Download' name='download_open' />
<select name='format_open'>
<option value='.xls'>.xls</option>
<option value='.csv'>.csv</option>
<option value='.xml'>.xml</option></select>
</form>
But when I try the following python code (which I sort of expected would not work)...
# get orders list
openOrders_url = virwoxTopLevel_url+"/orders.php"
openOrders_params = urlencode( { "download_open":"Download", "format_open":".xml" } )
openOrders_request = urllib2.Request(openOrders_url,openOrders_params,headers)
openOrders_response = virwox_opener.open(openOrders_request)
openOrders_xml = openOrders_response.read()
print(openOrders_xml)
...openOrders_xml ends up just being the original page (https://www.virwox.com/orders.php).
How does firefox know there is also a file to be downloaded, and how do I detect and download this file in Python?
Please note that this is not a security/login issue, as I would not even be able to get the orders.php page if I was having authentication trouble.
EDIT: I am wondering if this has something to do with redirection (I am using the basic redirection handler) or maybe I should be using something liek urllib.fileretrieve().
EDIT: here is code for complete program, just in case is relevant...
import urllib
import urllib2
import cookielib
import pprint
from urllib import urlencode
username=###############
password=###############
virwoxTopLevel_url = "http://www.virwox.com/"
overview_url = "https://www.virwox.com/index.php"
# Header
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }
# Handlers...
# cookie handler...
cookie_handler= urllib2.HTTPCookieProcessor( cookielib.CookieJar() )
# redirect handler...
redirect_handler= urllib2.HTTPRedirectHandler()
# create "opener" (OpenerDirector instance)
virwox_opener = urllib2.build_opener(redirect_handler,cookie_handler)
# login
login_url = "https://www.virwox.com/index.php"
values = { 'uname' : username, 'password' : password }
login_data = urllib.urlencode(values)
login_request = urllib2.Request(login_url,login_data,headers)
login_response = virwox_opener.open(login_request)
overview_html = login_response.read();
virwox_json_url = "http://api.virwox.com/api/json.php"
getTest = urllib.urlencode( { "method":"getMarketDepth", "symbols[0]":"EUR/SLL","symbols[1]":"USD/SLL","buyDepth":1,"sellDepth":1,"id":1 } )
get_response = urllib2.urlopen(virwox_json_url,getTest)
#print get_response.read()
# get orders list
openOrders_url = virwoxTopLevel_url+"/orders.php"
openOrders_params = urlencode( { "download_open":"Download", "format_open":".xml" } )
openOrders_request = urllib2.Request(openOrders_url,openOrders_params,headers)
openOrders_response = virwox_opener.open(openOrders_request)
openOrders_xml = openOrders_response.read()
# the following prints the html of the /orders.php page not the desired download data:
print "******************************************"
print(openOrders_xml)
print "******************************************"
print openOrders_response.info()
print openOrders_response.geturl()
print "******************************************"
# the following prints nothing, i assume because without the cookie handler, fails to authenticate
# (note that authentication is by the php program, not html authentication, so no "authentication hangler" above
print urllib2.urlopen("https://www.virwox.com/orders.php?download_open=Download&format_open=.xml").read()
A: CODE BELLOW ISN'T TESTED
something like:
import urllib, urllib2,
HOST = 'https://www.virwox.com'
FORMS = {
'login': {
'action': HOST + '/index.php',
'data': urllib.urlencode( {
'uname':'username',
'password':'******'
} )
},
'orders': {
'action': HOST + '/orders.php',
'data': urllib.urlencode( {
'download_open':'Download',
'format_open':'.xml'
} )
}
}
opener = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
try:
req = urllib2.Request( url = FORMS['login']['action'], data = FORMS['login']['data'] )
opener.open( req ) #save login cookie
print 'Login: OK'
except Exception, e:
print 'Login: Fail'
print e
try:
req = urllib2.Request( url = FORMS['orders']['action'], data = FORMS['orders']['data'] )
print 'Orders Page: OK'
except Exception, e:
print 'Orders Page: Fail'
print e
try:
xml = opener.open( req ).read()
print xml
except Exception, e:
print 'Obtain XML: Fail'
print e
A: Looks like your question is already answered, but you might like to take a look at the Requests package. It is basically a nice wrapper around the standard lib tools. The following (probably) does what you want.
import requests
r = requests.get('http://www.virwox.com/orders.php',
allow_redirects=True,
auth=('user', 'pass'),
data={'download_open': 'Download', 'format_open': '.xls'})
print r.content
A: You may need a urllib2.HTTPPasswordMgr like this (untested since I dont have your uname/pw):
import urllib
import urllib2
uri = "http://www.virwox.com/"
url = uri + "orders.php"
uname = "USERNAME"
password = "PASSWORD"
post = urllib.urlencode({"download_open":"Download", "format_open":".xls"})
pwMgr = urllib2.HTTPPasswordMgr()
pwMgr.add_password(realm=None, uri=uri, user=uname, passwd=password)
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPDigestAuthHandler(pwMgr)))
req = urllib2.Request(url, post)
s = urllib2.urlopen(req)
cookie = s.headers['Set-Cookie']
s.close()
req.add_header('Cookie', cookie)
s = urllib2.urlopen(req)
source = s.read()
s.close()
Then, you can:
print source
to see if it contains the xml data you need.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to change the position of the Map controller in MapView in android? How to change the position of the Map controller (zoon in/out) in MapView in android other than the default position in the bottom ?
A: zoomView = (LinearLayout) mapView.getZoomControls();
zoomView.setLayoutParams(new ViewGroup.LayoutParams
(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
zoomView.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
mapView.addView(zoomView);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RoR 3.1 - Loading associated objects when querying child with a where phrase I have the following structure
class List < ActiveRecord::Base
has_many :global_lists
end
class GlobalList < ActiveRecord::Base
set_table_name :globals_lists
belongs_to :list
end
and the following:
gl=GlobalList.find(1) #works
gl.list #works
gm=GlobalList.where(:global_id => 23).includes(:list) #works
gm.list # doesn't work
How do I access the list when using a where for returning the object?
thx
edit: is there a way for me to flatten this and get all the lists that have this? I guess I could iterate through but have the feeling there might be some syntax that I'm not aware of
A: The problem is that GlobalList.find returns a single GlobalList object whereas your query with where returns an ActiveRecord::Relation object (which represents a whole set of objects). You want:
gm = GlobalList.where(:global_id => 23).includes(:list).first
A: This line:
gm = GlobalList.where(:global_id => 23).includes(:list)
returns a collection of models. You need to first the first to get the list.
gm.first.list
A: GlobalList.find_by_global_id(23).list
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jQuery chaining - Can I write cleaner code? i'm slowly getting my head around jQuery and learning more each day, however I wonder if I can create cleaner code. I have heard of 'chaining' but am not sure how I apply this.
Below is a piece of working jQuery i've written, but although it works, can I reduce it/make it cleaner by chaining any of it?
The script removes a class on button click and adds another class whilst simultaneously hiding another div. At the end I have added on keydown events to use as well as button presses.
<script type="text/javascript">
$('button').click(function(e) {
if ($(this).hasClass('grid')) {
$('#primary ul').removeClass('stylelist').addClass('grid');
$('#primary ul .single-style-text').hide();
}
else if($(this).hasClass('list')) {
$('#primary ul').removeClass('grid').addClass('stylelist');
$('#primary ul .single-style-text').show();
}
});
$(document).bind('keydown', function(e) {
if (e.which == 71) {
$('#primary ul').removeClass('stylelist').addClass('grid');
$('#primary ul .single-style-text').hide();
}
});
$(document).bind('keydown', function(e) {
if (e.which == 76) {
$('#primary ul').removeClass('grid').addClass('stylelist');
$('#primary ul .single-style-text').show();
}
});
</script>
A: There's one thing you can further chain in there:
$('#primary ul')
.removeClass('stylelist').addClass('grid')
.find('.single-style-text').hide();
But the one thing that would make your code better would be to move that functionality into a function (even though this removes a little chaining):
function switchView(view) {
var ul=$('#primary ul');
ul.removeClass('stylelist').removeClass('grid');
ul.addClass(view);
var singleStyleText=ul.find('.single-style-text');
singleStyleText.hide();
if(view=='stylelist') {
singleStyleText.show();
}
}
Then your event handlers could look like this:
$('button').click(function() {
if($('#primary ul').hasClass('grid')) {
switchView('stylelist');
}else{
switchView('grid');
}
return false;
});
$(document).bind('keydown', function(e) {
if(e.which == 71) {
switchView('grid');
}else if(e.which == 76) {
switchView('stylelist');
}
});
A: $('button').click(function(e) {
var ul = $('#primary ul');
if ($(this).hasClass('grid')) {
ul.removeClass('stylelist').addClass('grid').find('.single-style-text').hide();
} else if($(this).hasClass('list')) {
ul.removeClass('grid').addClass('stylelist').find('.single-style-text').show();
}
});
$(document).bind('keydown', function(e) {
var ul = $('#primary ul');
if (e.which == 71) {
ul.removeClass('stylelist').addClass('grid').find('.single-style-text').hide();
} else if (e.which == 76) {
$('#primary ul').removeClass('grid').addClass('stylelist').find('.single-style-text').show();
}
});
but if its just a list or a grid you want to toggle you can write it on two lines of code. (per event), like:
$('button').click(function(e) {
var isGrid = $(this).hasClass('grid');
$('#primary ul').removeClass(isGrid ? 'stylelist' : 'grid').addClass(isGrid ? 'grid' : 'list').find('.single-style-text')[isGrid ? 'hide' : 'show']();
});
A: A few cleanups...
To start, we can combine these two keydown events. There's really no need to have multiple calls, since what you're dealing with is a value from the event.
<script type="text/javascript">
$('button').click(function(e) {
if($(this).hasClass('grid')) {
$('#primary ul').removeClass('stylelist').addClass('grid');
$('#primary ul .single-style-text').hide();
}
else if($(this).hasClass('list')) {
$('#primary ul').removeClass('grid').addClass('stylelist');
$('#primary ul .single-style-text').show();
}
});
$(document).bind('keydown', function(e) {
if (e.which == 71) {
$('#primary ul').removeClass('stylelist').addClass('grid');
$('#primary ul .single-style-text').hide();
}
if (e.which == 76) {
$('#primary ul').removeClass('grid').addClass('stylelist');
$('#primary ul .single-style-text').show();
}
});
</script>
Now, you're doing a lot of repetitive work... How about minimizing that by wrapping that up in a function?
Now, I may have gotten a bit carried away...
<script type="text/javascript">
$('button').click( swapClasses() );
$(document).bind('keydown', function(e) {
if (e.which == 71) {
$('#primary ul').removeClass('stylelist').addClass('grid');
$('#primary ul .single-style-text').hide();
}
else if (e.which == 76) {
$('#primary ul').removeClass('grid').addClass('stylelist');
$('#primary ul .single-style-text').show();
}
});
swapClasses = function() {
$('#primary ul').toggleClass( 'stylelist' ).toggleClass( 'grid' );
$('#primary ul .single-style-text').toggle( showOrHide );
}
</script>
Looks a wee bit cleaner...
A: As far as chaining goes, i don't think there's much to change around. A few things that i would change though...
*
*Where is your document.ready ?
*Cache your selectors so they can be reused.
*Use more specific selectors. Instead of just button specify the class too.
<script type="text/javascript">
$(function(){
var primary = $('#primary ul');
var single_style_text = primary.find('.single-style-text');
$('button.grid','button.list').click(function(e) {
if ( $(this).hasClass('grid') ) {
primary.removeClass('stylelist').addClass('grid');
single_style_text.hide();
}
else if( $(this).hasClass('list') ) {
primary.removeClass('grid').addClass('stylelist');
single_style_text.show();
}
});
$(document).bind('keydown', function(e) {
if (e.which == 76) {
primary.removeClass('grid').addClass('stylelist');
single_style_text.show();
}
if (e.which == 71) {
primary.removeClass('stylelist').addClass('grid');
single_style_text.hide();
}
});
})
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: change header content-type in php I am using this code
$query = mysql_query("SELECT Image, Col2, Col3 FROM table ");
$row = mysql_fetch_array($query);
$content = $row['Image'];
header('Content-type: image/jpg');
echo $content;
echo $row['Col2'];
echo $row['Col3'];
The problem is that once i do 'Content-type: image/jpg' the other Col2 and Col3 do not show up. They are not images but just text rows. How can i display image and the text at same time?
A: The browser is expecting only image binary data when setting the header content type to image/jpg. Echoing out text with this content type will break the image binary and not display the text.
Without changing the header you could encode the image into an image tag:
echo '<img src="data:image/jpg;base64,' . base64_encode($content) . '" />';
echo $row['Col2'];
echo $row['Col3'];
A: You can't per se...
You are sending a content type of image data which means all the data you send is interpreted as bytes of data forming an image.
The only way you could see your data is use the header() function to sent abitrary data that is not useful for the browser. Then using firebug or wathever browser console you use, lookup the NETWORK tab and open up your request for the image and check the headers tab, you will see your data there but you can't show that data to the user.
header('mydata2: '.$row['Col2']);
header('mydata3: '.$row['Col3']);
header('Content-type: image/jpg');
echo $content;
The other weird way would be to print your text on the image using GD, but thats probably not waht you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jboss start up with clustering works in one order not the other I have two clustered jboss nodes for this example I will call them A and B.
If i start node B first and then node A everything works fine and the servers start up in <45 seconds. If I switch the order I have problems. First problem is that it takes Node B FOREVER (like 5 minutes) to get past the [service] Removing bootstrap log handlers. When it finally continues on it gets to the setting the clustered beans to the HA JNDI and it takes 1-2 minutes ber bean. Meanwhile on node A I continously get
ERROR [org.jboss.system.server.profileservice.repository.clustered.ClusteredDeploymentRepository] getModifiedDeployments() Cannot acquire local lock and then line above says Unable to acquire lock as it is held by Node B]
Any help is greatly appreciated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Verification function for HTML form data I've created a function in JavaScript to verify an html form data, my code as below:
function checkPetitionForm_ff() {
if (document.petition_form.petition_firstname.value == "FIRST NAME" || document.petition_form.petition_firstname.value == "") {
alert("Please enter your First Name!")
document.petition_form.petition_firstname.focus();
return false;
}
if (document.petition_form.petition_lastname.value == "LAST NAME" || document.petition_form.petition_lastname.value == "") {
alert("Please enter your Last Name!")
document.petition_form.petition_lastname.focus();
return false;
}
if (document.petition_form.petition_age.value == "AGE" || document.petition_form.petition_age.value == "") {
alert("Please enter your Age!")
document.petition_form.petition_age.focus();
return false;
}
if (document.petition_form.state.value == "Select State") {
alert("Please select your state!")
document.petition_form.state.focus();
return false;
}
if (document.petition_form.petition_address.value == "HOME ADDRESS" || document.petition_form.petition_address.value == "") {
alert("Please enter your address!")
document.petition_form.petition_address.focus();
return false;
}
if (document.petition_form.zip.value == "ZIP CODE" || document.petition_form.zip.value == "") {
alert("Please enter your Zipcode!")
document.petition_form.zip.focus();
return false;
}
if (document.petition_form.phone2.value == "PHONE" || document.petition_form.phone1.value == "" || isNumeric(document.petition_form.phone1.value) == false) {
alert("Please enter the complete phone No!")
document.petition_form.phone2.focus();
return false;
}
if (document.petition_form.phone1.value == "PHONE" || document.petition_form.phone1.value == "" || isNumeric(document.petition_form.phone1.value) == false) {
alert("Please enter the complete phone No!")
document.petition_form.phone1.focus();
return false;
}
if (document.petition_form.phone3.value == "PHONE" || document.petition_form.phone1.value == "" || isNumeric(document.petition_form.phone1.value) == false) {
alert("Please enter the complete phone No!")
document.petition_form.phone3.focus();
return false;
}
if (document.petition_form.level.value == "YOUR LEVEL OF EDUCATION") {
alert("Please select your level of education!")
document.petition_form.level.focus();
return false;
}
if (document.petition_form.degree.value == "DEGREE OF INTEREST") {
alert("Please select your degree!")
document.petition_form.degree.focus();
return false;
}
if (!(document.getElementById(edu).checked)) {
alert("Please select Education!")
document.petition_form.edu.focus();
return false;
}
else {
return true;
}
}
The verifications are working good until "phone2" field and will not complete the verification after this.
I'll do appreciate if you can help me and advise how to solve this.
A: It looks like a simple copy/paste error. Notice that the petition_form members referenced after phone2 are phone1... this does not make sense. Compare this line against your next validation where all of the members are phone1.
So, this line:
if (document.petition_form.phone2.value == "PHONE" ||
document.petition_form.phone1.value == "" ||
isNumeric(document.petition_form.phone1.value) == false) {
Should look like:
if (document.petition_form.phone2.value == "PHONE" ||
document.petition_form.phone2.value == "" ||
isNumeric(document.petition_form.phone2.value) == false) {
(Code is lined up in that manner to hilight the differences.)
A: In that line you're actually checking phone2 only in the first condition, the others are phone1.
document.petition_form.phone2.value=="PHONE" || document.petition_form.phone1.value=="" || isNumeric(document.petition_form.phone1.value)==false
Also be aware that you do the same for phone3.
A: I think you are getting an exception as isNumeric is not a JavaScript Global function. You need to define it in your page (check out Validate decimal numbers in JavaScript - IsNumeric() for a clean implementation of isNumeric).
Also you should surround your method call with exception handling to get better details of the exception.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: what is the latest Microsoft command line C/C++ compiler? What is the latest Microsoft command line C/C++ compiler?
Is it now free, what does it cost?
Looking for a link for it?
Thanks in advance,
Kevin Waite
A: Erm...
*
*download VS2010 Express
*install
*Launch VS2010 Command Line shell
*invoke cl.exe /? and profit
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why am I getting NullPointerException in the CompilationUnit instances returned from ASTParser.createASTs() I am working on an Eclipse JDT plugin that requires parsing large numbers of source files,
so I am hoping to use the batch method ASTParser.createASTs(). The parsing executes without errors, but within the CompilationUnit instances it produces, many of the org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding instances have had their scope field set to null. This setting to null is occurring in the CompilationUnitDeclaration.cleanUp() methods, which are invoked on a worker thread that is unrelated to my plugin's code (i.e., my plugin's classes do not appear on the cleanUp() method call stack).
My parsing code looks like this (all rawSources are within the same project):
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setResolveBindings(true);
parser.setStatementsRecovery(true);
parser.setBindingsRecovery(true);
parser.setIgnoreMethodBodies(false);
parser.setProject(project);
parser.createASTs(rawSources.values().toArray(new ICompilationUnit[0]), new String[0], this, deltaAnalyzer.progressMonitor);
Alternatively, I can execute the parsing this way, and no such problems occur:
for (ICompilationUnit source : rawSources.values())
{
parser.setResolveBindings(true);
parser.setStatementsRecovery(true);
parser.setBindingsRecovery(true);
parser.setIgnoreMethodBodies(false);
parser.setProject(project);
parser.setSource(source);
CompilationUnit ast = (CompilationUnit)parser.createAST(deltaAnalyzer.progressMonitor);
parsedSources.add(deltaAnalyzer.createParsedSource(source, ast));
}
This issue occurs in both Helios and Indigo (the very latest release build). I filed a bug in Eclipse Bugzilla, but if anyone knows of a way to work around this--or if I am using the API wrong--I would greatly appreciate your help.
Byron
A: Without knowing exactly what your exception is, I can still offer 2 suggestions:
*
*Have a look at org.eclipse.jdt.ui.SharedASTProvider. If you are not making any changes to ASTs, this class may provide a more robust way of getting the ASTs.
*Play around with some of the settings that you are using. Do you really need bindingsRecovery set to true? What about statementRecovery? Setting these to false may help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Hibernate: Using collection of complex objects throws exceptions I am looking into Hibernate and storing collections of complex types. But I run into exception.
I have the following persistent class:
public class Item {
private Long id;
private Set images = new HashSet();
private Collection<Data> data = new ArrayList<Data>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set getImages() {
return images;
}
public void setImages(Set images) {
this.images = images;
}
public Collection<Data> getData() {
return data;
}
public void setData(Collection<Data> data) {
this.data = data;
}
}
The Data class is as follows:
public class Data {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Data) )
return false;
Data d = (Data) obj;
if(d.firstName.equals(firstName) && d.lastName.equals(lastName))
return true;
return false;
}
@Override
public int hashCode() {
int result;
result = 17;
result = 31 * result + firstName.hashCode();
result = 31 * result + lastName.hashCode();
return result;
}
The mapping files are as follows:
For Item class:
<hibernate-mapping>
<class name="com.entities.Item" table="ITEM">
<id name="id" type="java.lang.Long">
<column name="ID" />
<generator class="identity" />
</id>
<set name="images" table="ITEM_IMAGE" inverse="false" lazy="true">
<key>
<column name="ID" />
</key>
<element type="string">
<column name="IMAGES" />
</element>
</set>
<bag name="data" table="DATA" inverse="false" lazy="true">
<key>
<column name="ID" />
</key>
<one-to-many class="com.entities.Data" />
</bag>
</class>
</hibernate-mapping>
For Data class:
<hibernate-mapping>
<class name="com.entities.Data" table="DATA">
<id name="firstName" type="java.lang.String">
<column name="FIRSTNAME" />
<generator class="assigned" />
</id>
<property name="lastName" type="java.lang.String">
<column name="LASTNAME" />
</property>
</class>
</hibernate-mapping>
In my code to save data to MySQL:
Transaction tx = session.beginTransaction();
Item item = new Item();
Set images = new HashSet();
images.add("C:\\");
images.add("D:\\");
item.setImages(images);
List<Data> data = new ArrayList<Data>();
Data a = new Data();
a.setFirstName("John");
a.setLastName("Smith");
data.add(a);
item.setData(data);
session.save(item);
tx.commit();//-->Exception here
session.close();
I get the following exception on tx.commit();
Hibernate: insert into ITEM values ( ) Hibernate: insert into
ITEM_IMAGE (ID, IMAGES) values (?, ?) Hibernate: insert into
ITEM_IMAGE (ID, IMAGES) values (?, ?) Hibernate: update DATA set ID=?
where FIRSTNAME=? Hibernate: update DATA set ID=? where FIRSTNAME=?
1454 [main] ERROR org.hibernate.jdbc.AbstractBatcher - Exception
executing batch: org.hibernate.StaleStateException: Batch update
returned unexpected row count from update [0]; actual row count: 0;
expected: 1 at
org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:85)
at
org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:70)
at
org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:90)
at
org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at
org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
at
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:188)
at
org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at
org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216) at
org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383) at
org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at com.entities.Main.main(Main.java:44)
Why do I get this exception?
If I remove the Collection<Data> data to store only the Set the code works and the data are saved in MySQL.
Note: The mapping files have been created by Eclipse Hibernate plugin.
A: Made the following changes to your code :
Transaction tx = session.beginTransaction();
Item item = new Item();
//added save here to attach the object to persistance context.
// (This might be optional)
session.save(item);
Set images = new HashSet();
images.add("C:\\");
images.add("D:\\");
item.setImages(images);
List<Data> data = new ArrayList<Data>();
Data a = new Data();
a.setFirstName("John");
a.setLastName("Smith");
//added save here to attach the object to persistance context.
//this is required without cascading settings
session.save(a)
data.add(a);
item.setData(data);
session.save(item);
tx.commit();//-->Exception here
session.close();
You could otherwise set appropriate the cascading options on the bag!
AFAIK you are getting the error since you are trying to persist an association without the other entity (Data) being in persistant state and the cascading options are set to none by default. Again I haven't tried out to run my piece of snippet but this will point you in the right direction.
UPDATE from the OP:
The problem is solved by using inverse="true", doing cascade and also I have to reference from Data to Item otherwise the FK column is not updated
A: Is it possibly due to the fact that you're adding a to the list data twice?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create thumbnail of Word doc when it doesn’t have one saved? I want to create a COM dll that will take any Word file and generate an image file of the first page of the document. I have already done this using the IExtractImage functionality of the Windows SDK, but this only works if there is a thumbnail saved with the file. (Since the Word user has to make an extra effort to save the thumbnail by going down into the Advanced options of the Prepare | Properties dialog, most Word docs don’t have a preview available.)
(Unfortunately I am stuck with using COM because I am integrating this solution with an existing ASP web app that does not interact well with .NET.)
One approach I am considering is using a PDF-generating SDK to generate a PDF of the file, or ideally a PDF of just the first page of the file, and then generate the preview image from the PDF. (I don’t have access to Adobe’s proprietary PDF SDK, but if it could be shown to work well for this solution, I would look into purchasing a license.)
Ideally I would like to be able to generate a preview of many other (non-image) file types besides just a Word doc.
I notice that Google now provides a preview of many kinds of files, and I am wondering what approach they have used.
Any thoughts, clues, suggestions, and/or insults are welcome.
Thanks.
A: The thumbnail from the old OLE-Automation property pages is a very small (not even anti-aliased) black & white Metafile that does not look any good these days. Within classic VB6 or VBA, you can trigger saving the thumbnail with a few lines of code (If I remember correctly). However, Winword, Excel etc. are automated by loading the Gui application invisibly and this does not always work in a (web) server context. Consider to thumbnail the documents while uploading / virus scanning but not from inside a DLL that gets loaded into the web server.
The google approach builds most-likely upon some open-source components that do not work under classic ASP either.
A: ASP? You could use 2JPEG. It support 275 formats (including Word, Excel, Publisher & Powerpoint files.) The vendor recommends calling 2JPEG as a scheduled background task so you don't impact performance.
Here's a couple of examples:
Command line syntax. You can start in from a batch file or from the Windows Task Scheduler:
2jpeg.exe -src "C:\In\*.*" -dst "C:\Out"
Launch command line from Visual C++ application:
ShellExecute(NULL, "open", "2jpeg.exe", "-src \"C:\\In\\*.*\" -dst \"C:\\Out\"", NULL, SW_HIDE)
From Visual Basic:
Shell ("""2jpeg.exe"" -src ""C:\In\*.*"" -dst ""C:\out""")
Delphi syntax:
ShellExecute(0, 'open', PChar('2jpeg.exe'), PChar('-src "C:\In\*.*" -dst "C:\Out"'), nil, 0);
PERL script on Windows server:
exec '2jpeg.exe -src C:\In\*.* -dst C:\out';
VB Script code example:
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run """2jpeg.exe"" -src ""C:\In\*.*"" -dst ""C:\Out""", 1, True
Set objShell = Nothing
JavaScript code example:
var objShell = new ActiveXObject("Shell.Application");
objShell.ShellExecute("2jpeg.exe", "-src \"C:\\In\\*.*\" -dst \"C:\\Out\"", "", "open", "1");
PHP code example:
<?php
echo exec('2jpeg.exe -src "C:\In\*.*" -dst "C:\Out" -oper Resize size:"800 600" -jpeg quality:50');
?>
Launch 2JPEG from C# application:
System.Diagnostics.Process.Start("2jpeg.exe", "-src \"C:\\In\\*.*\" -dst \"C:\\Out\"");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7603104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.