to retrieve k random numbers from an array of undetermined size we use a technique called reservoir sampling. Can anybody briefly highlight how it happens with a sample code??
What is a regex I can write in bash for parsing a line and extracting text that can be found between two | (so that would be ex: 1: |hey| 2: |boy|) and keeping those words in some sort of array?
Regex rx = new Regex(@"[+-]");
string[] substrings = rx.Split(expression);
expression = "-9a3dcbh-3bca-4ab4cf-3hc" //This is the iput string
I want to split that string between + or -.
My VS debugger shows substring array like this:
substrings[0] = null //???Why
substrings[1] = 9a3dcbh
substrings[2] = 3bca
substrings[3] = 4ab4cf
substrings[4] = 3hc
Why is the first element of arry null, is it because I am matching +-, and there is no + in my input string?
I have a simple question. Should I return a byte-array or simply base64 encode my binary data, when exposing it through a web service in .NET?
Is there any pros/cons with either method, which is mostly supported etc.
Hi everyone. I'm a long running fan of stackoverflow, first time poster. I'd love to see if someone can help me with this. Let me dig in with a little code, then I'll explain my problem. I have the following wrapper classes:
class mysqli_wrapper
{
private static $mysqli_obj;
function __construct() // Recycles the mysqli object
{
if (!isset(self::$mysqli_obj))
{
self::$mysqli_obj = new mysqli(MYSQL_SERVER, MYSQL_USER, MYSQL_PASS, MYSQL_DBNAME);
}
}
function __call($method, $args)
{
return call_user_func_array(array(self::$mysqli_obj, $method), $args);
}
function __get($para)
{
return self::$mysqli_obj->$para;
}
function prepare($query) // Overloaded, returns statement wrapper
{
return new mysqli_stmt_wrapper(self::$mysqli_obj, $query);
}
}
class mysqli_stmt_wrapper
{
private $stmt_obj;
function __construct($link, $query)
{
$this->stmt_obj = mysqli_prepare($link, $query);
}
function __call($method, $args)
{
return call_user_func_array(array($this->stmt_obj, $method), $args);
}
function __get($para)
{
return $this->stmt_obj->$para;
}
// Other methods will be added here
}
My problem is that when I call bind_result() on the mysqli_stmt_wrapper class, my variables don't seem to be passed by reference and nothing gets returned. To illustrate, if I run this section of code, I only get NULL's:
$mysqli = new mysqli_wrapper;
$stmt = $mysqli->prepare("SELECT cfg_key, cfg_value FROM config");
$stmt->execute();
$stmt->bind_result($cfg_key, $cfg_value);
while ($stmt->fetch())
{
var_dump($cfg_key);
var_dump($cfg_value);
}
$stmt->close();
I also get a nice error from PHP which tells me: PHP Warning: Parameter 1 to mysqli_stmt::bind_result() expected to be a reference, value given in test.php on line 48
I've tried to overload the bind_param() function, but I can't figure out how to get a variable number of arguments by reference. func_get_args() doesn't seem to be able to help either.
If I pass the variables by reference as in $stmt->bind_result(&$cfg_key, &$cfg_value) it should work, but this is deprecated behaviour and throws more errors.
Does anyone have some ideas around this? Thanks so much for your time.
Is it possible to read cookie expiration time with php ?
When I print_r($_COOKIE) it outputs:
Array
(
[PHPSESSID] => 0afef6bac83a7db8abd9f87b76838d7f
[userId] => 1232
[userEmail] => [email protected]
[firstName] => user
[lastName] => user
)
So I think $_COOKIE don't have the expiration time, is it possible with some other function?
Hi,
I have followed the Railscast episode 88 to implement a set of dependant drop down menus.
In the students-new view, when the student's year is selected, the javascript figures out which courses are available to that year and offers the selection in a new drop down menu.
My javascript erb file is here:
var courses = new Array();
<% for course in @courses -%>
<%for year in course.years -%>
courses.push(new Array(<%= year.year_id%>, '<%=h course.title%>', <%= course.id%>));
<%end -%>
<% end -%>
function yearSelected() {
year_id = $('student_year_id').getValue();
options = $('student_course_ids').options;
options.length = 1;
courses.each(function(course) {
if (course[0] == year_id) {
options[options.length] = new Option(course[1], course[2]);
}
});
if (options.length == 1) {
$('course_field').hide();
} else {
$('course_field').show();
}
}
document.observe('dom:loaded', function() {
yearSelected();
$('student_year_id').observe('change', yearSelected);
});
Any my view is as follows:
<% form_for(@student) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.label :cid, "CID" %><br />
<%= f.text_field :cid %>
</p>
<p>
<label for="student_year_id">Year:</label>
<%= collection_select(:student, :year_id, Year.all, :id, :title, {:prompt => true})%>
</p>
<p id="course_field">
<label for="student_course_ids">Course:</label>
<%= collection_select(:student, :course_ids, Course.find(:all), :id, :title, {:prompt => true}, {:multiple => true})%>
</p>
<p>
<%= f.submit 'Save' %>
</p>
<% end %>
What I would like to do is to add checkboxes instead of the drop down menu. Any suggestions? I previously was using this method, but was not able to get it to work with the new javascript.
Cheers
Hello, I have a 1d array containing Nd data, I would like to effectively traverse on it with std::transform or std::for_each.
unigned int nelems;
unsigned int stride=3;// we are going to have 3D points
float *pP;// this will keep xyzxyzxyz...
Load(pP);
std::transform(pP, pP+nelems, strMover<float>(pP, stride));//How to define the strMover??
Kind Regards,
Arman.
What is a regex I can write in bash for parsing a line and extracting text that can be found between two | (so that would be ex: 1: |hey| 2: |boy|) and keeping those words in some sort of array?
I am trying to do this but keep on failing.
I have a text box.
I have also an array of cities, and i want, while typing to display the cities that the user should be able to select.
Like if the user is typing : Mu the drop down should display Mumbai \n MuMu ... etc
Like the Tags below is doing !
Does someone have any ideas in how this can be accomplished ?
How do i explode and check if the array contains more than one value
this doesnt work
<b>{if $test->tester|explode|count>1}Vars:{else}Var:{/if}</b><br>
Hi, I was playing around with Drupal UC and installed a module called "Quoting / Estimate"
(http://drupal.org/project/quoting), I tried to run it and got this error:
**warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback, 'quoting_quote_clear_page' was given in /home/ergospec/public_html/d/includes/menu.inc on line 348**
Has anyone run into this problem?
Second question: anyone know of a good quotation module (where customer can request a price quote, not the brackets)? It doesn't have to be in Drupal.
Any help is appreciated.
Murtez
I am having trouble understanding how to use the indexOf() and substring() and compareTo() methods to flip people's first name with their last name in an array.
Using Symfony2 and PdfBundle to generate dynamically PDF files, I don't get to generate the files indeed.
Following documentation instructions, I have set up all the bundle thing:
autoload.php:
'Ps' => __DIR__.'/../vendor/bundles',
'PHPPdf' => __DIR__.'/../vendor/PHPPdf/lib',
'Imagine' => array(__DIR__.'/../vendor/PHPPdf/lib', __DIR__.'/../vendor/PHPPdf/lib/vendor/Imagine/lib'),
'Zend' => __DIR__.'/../vendor/PHPPdf/lib/vendor/Zend/library',
'ZendPdf' => __DIR__.'/../vendor/PHPPdf/lib/vendor/ZendPdf/library',
AppKernel.php:
...
new Ps\PdfBundle\PsPdfBundle(),
...
I guess all the setting up is correctly configured, as I am not getting any "library not found" nor anything on that way...
So, after all that, I am doing this in the controller:
...
use Ps\PdfBundle\Annotation\Pdf;
...
/**
* @Pdf()
* @Route ("/pdf", name="_pdf")
* @Template()
*/
public function generateInvoicePDFAction($name = 'Pedro')
{
return $this->render('AcmeStoreBundle:Shop:generateInvoice.pdf.twig', array(
'name' => $name,
));
}
And having this twig file:
<pdf>
<dynamic-page>
Hello {{ name }}!
</dynamic-page>
</pdf>
Well. Somehow, what I just get in my page is just the normal html generated as if it was a normal Response rendering.
The Pdf() annotation is supposed to give the "special" behavior of creating the PDF file instead of rendering normal HTML.
So, having the above code, when I request the route http://www.mysite.com/*...*/pdf, all what I get is the following HTML rendered:
<pdf>
<dynamic-page>
Hello Pedro!
</dynamic-page>
</pdf>
(so a blank HTML page with just the words Hello Pedro! on it.
Any clue? Am I doing anything wrong? Is it mandatory to have the alternative *.html.twig apart from the *.pdf.twig version? I don't think so... :(
How to load a binary file(.bin) of size 6 MB in a varbinary(MAX) column of SQL Server 2005 database using ADO in vc++ application.
This is the code I am using to load the file which I used to load a .bmp file
BOOL CSaveView::PutECGInDB(CString strFilePath, FieldPtr pFileData)
{
//Open File
CFile fileImage;
CFileStatus fileStatus;
fileImage.Open(strFilePath,CFile::modeRead);
fileImage.GetStatus(fileStatus);
//Alocating memory for data
ULONG nBytes = (ULONG)fileStatus.m_size;
HGLOBAL hGlobal = GlobalAlloc(GPTR,nBytes);
LPVOID lpData = GlobalLock(hGlobal);
//Putting data into file
fileImage.Read(lpData,nBytes);
HRESULT hr;
_variant_t varChunk;
long lngOffset = 0;
UCHAR chData;
SAFEARRAY FAR *psa = NULL;
SAFEARRAYBOUND rgsabound[1];
try
{
//Create a safe array to store the BYTES
rgsabound[0].lLbound = 0;
rgsabound[0].cElements = nBytes;
psa = SafeArrayCreate(VT_UI1,1,rgsabound);
while(lngOffset<(long)nBytes)
{
chData = ((UCHAR*)lpData)[lngOffset];
hr = SafeArrayPutElement(psa,&lngOffset,&chData);
if(hr != S_OK)
{
return false;
}
lngOffset++;
}
lngOffset = 0;
//Assign the safe array to a varient
varChunk.vt = VT_ARRAY|VT_UI1;
varChunk.parray = psa;
hr = pFileData-AppendChunk(varChunk);
if(hr != S_OK)
{
return false;
}
}
catch(_com_error &e)
{
//get info from _com_error
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
_bstr_t bstrErrorMessage(e.ErrorMessage());
_bstr_t bstrErrorCode(e.Error());
TRACE("Exception thrown for classes generated by #import");
TRACE("\tCode= %08lx\n",(LPCSTR)bstrErrorCode);
TRACE("\tCode Meaning = %s\n",(LPCSTR)bstrErrorMessage);
TRACE("\tSource = %s\n",(LPCSTR)bstrSource);
TRACE("\tDescription = %s\n",(LPCSTR)bstrDescription);
}
catch(...)
{
TRACE("Unhandle Exception");
}
//Free Memory
GlobalUnlock(lpData);
return true;
}
But when I read the same file using Getchunk funcion it gives me all 0,s but the size of the file I get is same as the one uploaded.
Your help will be highly appreciated.
Thanks in advance.
I have followed the zend instructions for implement my web Authentication using a database table.
It's exactly the same code, but when render the page, the following exceptions appears:
Zend\Authentication\Adapter\Exception\RuntimeException
File:
C:\xampp\htdocs\pfc\vendor\ZF2\library\Zend\Authentication\Adapter\DbTable.php
Mensaje:
The supplied parameters to DbTable failed to produce a valid sql statement, please
check table and column names for validity.
produced by this other:
Zend\Db\Adapter\Exception\InvalidQueryException
File:
C:\xampp\htdocs\pfc\vendor\ZF2\library\Zend\Db\Adapter\Driver\Mysqli\Statement.php
Mensaje:
Statement couldn't be produced with sql: SELECT `users`.*, (CASE WHEN `password` = ?
THEN 1 ELSE 0 END) AS `zend_auth_credential_match` FROM `users` WHERE `mail` = ?
Seems to be that Statement.php can not execute the sql of above, but I send the sql by phpmyadmin replacing the ? for strings and work ok.
I am sure that $dbAdapter works ok also because I have tested it and the columns name are
"mail" and "password".
This in my code, also I put the $dbAdapter test code.
$dbAdapter = new DbAdapter(array( //This DbAdapter Work ok sure!!
'driver' => 'Mysqli',
'database' => 'securedraw',
'username' => 'root',
'password' => ''
));
$fp = function($name) use ($dbAdapter) { return $dbAdapter->driver->formatParameterName($name);};
$sql = 'SELECT * FROM ' . $qi('users') . ' WHERE id = ' . $fp('id');
$statement = $dbAdapter->query($sql);
$parameters = array('id' => 1);
$sqlResult = $statement->execute($parameters);
$row = $sqlResult->current();
$mail = $row['mail'];
$password = $row['password']; //until here test $dbAdapter exitly!!
//Start the auth proccess!!
$authAdapter = new AuthDbTableAdapter($dbAdapter);
$authAdapter->setTableName('users')
->setIdentityColumn('mail')
->setCredentialColumn('password');
$authAdapter->setIdentity('josep')
->setCredential('josep');
$authResult = $authAdapter->authenticate(); //This is the fail method!!!
Hello, I'm trying to follow a standard reference for opening files but running into a constraint_error at the line when I call Ada.Text_IO.Create(). It says "range check failed". Any help appreciated, here's the code:
WITH Ada.Text_IO;
WITH Ada.Integer_Text_IO;
USE Ada.Text_IO;
USE Ada.Integer_Text_IO;
PROCEDURE FileManip IS
--Variables
Start_Int : Integer;
Stop_Int : Integer;
Max_Length : Integer;
--Output File
MaxName : CONSTANT Positive := 80;
SUBTYPE NameRange IS Positive RANGE 1..MaxName;
OutFileName : String(NameRange) := (OTHERS => '#');
OutNameLength : NameRange;
OutData : File_Type;
--Array
TYPE Chain_Array IS ARRAY(1..500) OF Integer;
Sum : Integer := 1;
BEGIN
--Inputs
Ada.Text_IO.Put(Item => "Enter a starting Integer: ");
Ada.Integer_Text_IO.Get(Item => Start_Int);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put(Item => "Enter a stopping Integer: ");
Ada.Integer_Text_IO.Get(Item => Stop_Int);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put(Item => "Enter a Maximum Length to search: ");
Ada.Integer_Text_IO.Get(Item => Max_Length);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put(Item => "Enter a output file name > ");
Ada.Text_IO.Get_Line(
Item => OutFileName,
Last => OutNameLength);
Ada.Text_IO.Create(
File => OutData,
Mode => Ada.Text_IO.Out_File,
Name => OutFileName(1..OutNameLength));
Ada.Text_IO.New_Line;
I would like to be able to read XMLHttpRequest that is sent to a PHP page. I am using prototype's Ajax.Request function, and I am sending a simple XML structure.
When trying to print the POST array on the PHP page, I don't get any output.
Any help appreciated.
Or maybe google is just not so friendly to me?
What I want is this simple thing:
constructor that accepts an array of menu item objects
Value get/set property that would set all the Checked properties right
bind to all Clicked events of the supplied items and provide One event
Working DataBind facilities
If you encountered such a nice thing around, please direct me. No need for manual do-it-in-your-form1.cs-class links, please. This I can do myself.
I am using google maps api v3 and have an array of arrays object:
MVCArray.<MVCArray.<LatLng>>
I want to iterate over this. I see that MVCArray has a method forEach which uses a call back, but I have no idea how to use this (I haven't done much js). The api defines this method as follows:
forEach(callback:function(*, number)))
Could somebody please show me an example of how to use this given an MVCArray of MVCArrays?
i'm using enums to replace String constants in my java app (jre 1.5).
is there a performance hit when i treat the enum as a static array of names, in a method that is called constatnly (e.g. when rendering the UI)?
my code looks a bit like this:
public String getValue(int col) {
return ColumnValues.values()[col].toString();
}
thanks, asaf :-)
A frequent issue in code reviews is whether a numeric value should be hard-coded in the code or not. Does anyone know of a nice regular expression that can catch 'magic numbers' in code like:
int overDue = 30;
Money fee = new Money(5.25D);
without also getting a ton of false positives like for loop initialization code?
for (int i = 0; i < array.length; i++) {
}
When calculating the load factor of a hashtable with an open-addressing array implementation I am using:
numberOfKeysInArray/sizeOfArray
however it occurred to me that since deleted entries must be marked as such (to distinguish them from empty spaces), it might make sense to include these in the number of keys.
My thinking is that as far as estimating the average number of probes to find an entry, deleted entries should count towards the load factor, but as far as inserting a new key they should not.
Which is the proper calculation: including deleted keys or not?