Allow only a-Z, 0-9 using preg_match, preg_replace - preg-replace

Could somebody please help out with this line? How to modify it so it only allows a-Z, 0-9?
Thanks.
if (preg_match('~[<>&"\'=\\\]~', preg_replace('~&#(?:\\d{1,7}|x[0-9a-fA-F]{1,6});~', '', $context['checked_username'])) != 0 || $context['checked_username'] == '_' || $context['checked_username'] == '|' || strpos($context['checked_username'], '[code') !== false || strpos($context['checked_username'], '[/code') !== false)
$context['valid_username'] = false;

following code checks [[:alnum:]] (alnum stands for alpha numeric)
if (!preg_match("/^[[:alnum:]]+$/", $context['checked_username']))
{
$context['valid_username'] = false;
}

Related

Identify whether I've received an HttpRequest or HttpResponse?

I have a netty server that listens on a port. It can either receive HttpResponses or HttpRequests on this port. How can I set up a pipeline to handle both and distinguish between the two? Is this possible? Connections are initiated to this server and not from it.
Thank you!
You could use the isHttp method from the PortUnification example. It examines the first two unsigned bytes of a received message to determine if it is likely an HTTP verb, therefore identifying the message as an HTTP request. You might need to modify it slightly, depending on the likely content of any responses.
private static boolean isHttp(int magic1, int magic2) {
return
magic1 == 'G' && magic2 == 'E' || // GET
magic1 == 'P' && magic2 == 'O' || // POST
magic1 == 'P' && magic2 == 'U' || // PUT
magic1 == 'H' && magic2 == 'E' || // HEAD
magic1 == 'O' && magic2 == 'P' || // OPTIONS
magic1 == 'P' && magic2 == 'A' || // PATCH
magic1 == 'D' && magic2 == 'E' || // DELETE
magic1 == 'T' && magic2 == 'R' || // TRACE
magic1 == 'C' && magic2 == 'O'; // CONNECT
}

mismatched input '.' in rule

I am new to drools .I am writing a new rule.But i am getting Error as follow:
mismatched input '.' in rule "StopTextRule" in pattern
My rule is
package com.******.*****;
import java.lang.Number;
rule "StopTextRule"
dialect "mvel"
salience 20
lock-on-active true
when
RoutingData( messageBody != null && (
(messageBody.trim().equalsIgnoreCase("stop") || messageBody.trim().equalsIgnoreCase("\"stop\"") || messageBody.trim().equalsIgnoreCase("stop.") || messageBody.trim().equalsIgnoreCase("\"stop.\""))
|| (messageBody.trim().equalsIgnoreCase("quit")|| messageBody.trim().equalsIgnoreCase("\"quit\"") || messageBody.trim().equalsIgnoreCase("quit.")|| messageBody.trim().equalsIgnoreCase("\"quit.\""))
|| (messageBody.trim().equalsIgnoreCase("cancel")|| messageBody.trim().equalsIgnoreCase("\"cancel\"") || messageBody.trim().equalsIgnoreCase("cancel.")|| messageBody.trim().equalsIgnoreCase("\"cancel.\""))
|| (messageBody.trim().equalsIgnoreCase("UNSUBSCRIBE")|| messageBody.trim().equalsIgnoreCase("\"UNSUBSCRIBE\"") || messageBody.trim().equalsIgnoreCase("UNSUBSCRIBE.")|| messageBody.trim().equalsIgnoreCase("\"UNSUBSCRIBE.\"")))
&& incomingMessageProtocol != null && incomingMessageProtocol.trim().equalsIgnoreCase("X"))
routingResp : RoutingRuleResponse( isStop == false )
then
modify( routingResp ) {
setIsStop( true )
}
end
This compiles using Drools 6.4.0. I think that you are using an older version where Java expressions had to be enclosed in eval.
It would be simpler in any case to rewrite this pattern like so:
rule x
when
X( messageBody != null &&
messageBody matches "\\s*(\"?)(?i:stop|quit|cancel|unsubscribe)\\.?\\1\\s*" &&
incomingMessageProtocol != null &&
incomingMessageProtocol matches "\\s*(?i:X)\\s*") )
then
// ...
end

Syntax error when map() returns LIST

This works,
print map { $_." x" => $_ } 1..5;
print map { ("$_ x" => $_) } 1..5;
print map { ("$_ x") => $_ } 1..5;
but this throws syntax error,
print map { "$_ x" => $_ } 1..5;
Is this documented bug, undocumented bug, or I can't see why this should not compile?
Why perl thinks this should be map EXPR, LIST instead of map BLOCK LIST
From perlref
Because curly brackets (braces) are used for several other things including BLOCKs, you may occasionally have to disambiguate braces at the beginning of a statement by putting a + or a return in front so that Perl realizes the opening brace isn't starting a BLOCK. The economy and mnemonic value of using curlies is deemed worth this occasional extra hassle.
To make your intentions clearer and to help the parser,
Say +{...} to unambiguously specify a hash reference
#list_of_hashrefs = map +{ "$_ x" => $_ }, 1..5;
Say {; ...} to unambiguously specify a code block
%mappings = map {; "$_ x" => $_ } 1..5;
Why perl thinks this should be map EXPR, LIST instead of map BLOCK LIST?
The relevant section of code is in toke.c, Perl's lexer (the below is from Perl 5.22.0):
/* This hack serves to disambiguate a pair of curlies
* as being a block or an anon hash. Normally, expectation
* determines that, but in cases where we're not in a
* position to expect anything in particular (like inside
* eval"") we have to resolve the ambiguity. This code
* covers the case where the first term in the curlies is a
* quoted string. Most other cases need to be explicitly
* disambiguated by prepending a "+" before the opening
* curly in order to force resolution as an anon hash.
*
* XXX should probably propagate the outer expectation
* into eval"" to rely less on this hack, but that could
* potentially break current behavior of eval"".
* GSAR 97-07-21
*/
t = s;
if (*s == '\'' || *s == '"' || *s == '`') {
/* common case: get past first string, handling escapes */
for (t++; t < PL_bufend && *t != *s;)
if (*t++ == '\\')
t++;
t++;
}
else if (*s == 'q') {
if (++t < PL_bufend
&& (!isWORDCHAR(*t)
|| ((*t == 'q' || *t == 'x') && ++t < PL_bufend
&& !isWORDCHAR(*t))))
{
/* skip q//-like construct */
const char *tmps;
char open, close, term;
I32 brackets = 1;
while (t < PL_bufend && isSPACE(*t))
t++;
/* check for q => */
if (t+1 < PL_bufend && t[0] == '=' && t[1] == '>') {
OPERATOR(HASHBRACK);
}
term = *t;
open = term;
if (term && (tmps = strchr("([{< )]}> )]}>",term)))
term = tmps[5];
close = term;
if (open == close)
for (t++; t < PL_bufend; t++) {
if (*t == '\\' && t+1 < PL_bufend && open != '\\')
t++;
else if (*t == open)
break;
}
else {
for (t++; t < PL_bufend; t++) {
if (*t == '\\' && t+1 < PL_bufend)
t++;
else if (*t == close && --brackets <= 0)
break;
else if (*t == open)
brackets++;
}
}
t++;
}
else
/* skip plain q word */
while (t < PL_bufend && isWORDCHAR_lazy_if(t,UTF))
t += UTF8SKIP(t);
}
else if (isWORDCHAR_lazy_if(t,UTF)) {
t += UTF8SKIP(t);
while (t < PL_bufend && isWORDCHAR_lazy_if(t,UTF))
t += UTF8SKIP(t);
}
while (t < PL_bufend && isSPACE(*t))
t++;
/* if comma follows first term, call it an anon hash */
/* XXX it could be a comma expression with loop modifiers */
if (t < PL_bufend && ((*t == ',' && (*s == 'q' || !isLOWER(*s)))
|| (*t == '=' && t[1] == '>')))
OPERATOR(HASHBRACK);
if (PL_expect == XREF)
{
block_expectation:
/* If there is an opening brace or 'sub:', treat it
as a term to make ${{...}}{k} and &{sub:attr...}
dwim. Otherwise, treat it as a statement, so
map {no strict; ...} works.
*/
s = skipspace(s);
if (*s == '{') {
PL_expect = XTERM;
break;
}
if (strnEQ(s, "sub", 3)) {
d = s + 3;
d = skipspace(d);
if (*d == ':') {
PL_expect = XTERM;
break;
}
}
PL_expect = XSTATE;
}
else {
PL_lex_brackstack[PL_lex_brackets-1] = XSTATE;
PL_expect = XSTATE;
}
Explanation
If the first term after the opening curly is a string (delimited by ', ", or `) or a bareword beginning with a capital letter, and the following term is , or =>, the curly is treated as the beginning of an anonymous hash (that's what OPERATOR(HASHBRACK); means).
The other cases are a little harder for me to understand. I ran the following program through gdb:
{ (x => 1) }
and ended up in the final else block:
else {
PL_lex_brackstack[PL_lex_brackets-1] = XSTATE;
PL_expect = XSTATE;
}
Suffice it to say, the execution path is clearly different; it ends up being parsed as a block.

Big Entity Framework Query, How to pregenerate, or precompile this query

I Have a Big Linq-to-entity Query and it's seem to be very long to convert that linq query into SQL.
How can I Precompiled this query.
Is there a way to do that?.
here is my query.
var ListLocation = from s in repLocation.GetLocationByPermision()
.Where(p => (ViewModel.BaseSearchViewModel.IsActive == -1 || p.IsActive == bIsActive) &&
(ViewModel.LocationTypeID < 0 || ViewModel.LocationTypeID == p.LocationTypeID) &&
(ViewModel.ListUsageID.Count() == 0 || p.Premises.Select(gs => gs.UsageID).Intersect(ViewModel.ListUsageID).Any()) &&
(ViewModel.BaseSearchViewModel.City == null || p.Address.City.CityName.Contains(ViewModel.BaseSearchViewModel.City)) &&
(ViewModel.BaseSearchViewModel.ListCountryID.Count() == 0 || ViewModel.BaseSearchViewModel.ListCountryID.Any(pl => pl == p.Address.City.Province.Country.CtryID)) &&
(ViewModel.BaseSearchViewModel.ListStateID.Count() == 0 || ViewModel.BaseSearchViewModel.ListStateID.Any(pl => pl == p.Address.City.Province.PrvID)) &&
(ViewModel.BaseSearchViewModel.Street == null || p.Address.Street.Contains(ViewModel.BaseSearchViewModel.Street)) &&
(ViewModel.BaseSearchViewModel.CivicNumber == null || p.Address.CivicNumber.Contains(ViewModel.BaseSearchViewModel.CivicNumber)) &&
(ViewModel.BaseSearchViewModel.ListGrpDescID1.Count() == 0 || p.GroupLocations.Select(sg => sg.GrpDescID).Intersect(ViewModel.BaseSearchViewModel.ListGrpDescID1).Any()) &&
(ViewModel.BaseSearchViewModel.ListGrpDescID2.Count() == 0 || p.GroupLocations.Select(sg => sg.GrpDescID).Intersect(ViewModel.BaseSearchViewModel.ListGrpDescID2).Any()) &&
(ViewModel.BaseSearchViewModel.ListGrpDescID3.Count() == 0 || p.GroupLocations.Select(sg => sg.GrpDescID).Intersect(ViewModel.BaseSearchViewModel.ListGrpDescID3).Any()) &&
(ViewModel.BaseSearchViewModel.ListGrpDescID4.Count() == 0 || p.GroupLocations.Select(sg => sg.GrpDescID).Intersect(ViewModel.BaseSearchViewModel.ListGrpDescID4).Any())
)
select new LocationViewModel()
{
LocationID = s.LocationID,
LocationTypeID = s.LocationTypeID,
Long = s.Address.Longitude,
Lat = s.Address.Latitude,
FileNumber = s.LocationFile,
State = s.Address.City.Province.PrvName,
City = s.Address.City.CityName,
Address = s.Address.CivicNumber + " " + s.Address.Street,
Status = s.LocationType.LocationTypeTexts.FirstOrDefault(p => p.LangID == lang).Txt,
DefaultImgPath = s.LocationPictures.FirstOrDefault(p => p.IsDefault == true && p.IsActive == true).FilePath,
Location = s,
HasPremises = s.Premises.Any(p => p.IsActive == true && p.IsDelete == false),
ListGrpDescID = s.GroupLocations.Select(g => g.GrpDescID)
};
What you want is to pre-compile the linq. There is a decent MSDN article on the topic here:
http://msdn.microsoft.com/en-us/magazine/ee336024.aspx
I've found the process a little cumbersome, and find myself reverting to Stored Procedures for the handfull of queries I need to write that rise to your level of complexity.
The guidance on pre-compiling views from Microsoft is probably your best bet:
How to: Pre-Generate Views to Improve Query Performance

Zend Framework - how to upload a file

How can i upload a file? Stackoverflow i cant page codes so please check this link: http://pastebin.org/386639
Thanks in advance
LATER:
Later i updated this as following, because ZF is not friendly, they keep still everything top secret! :P
public static function mvUploadFile()
{
//
// $_GET/_POST/FILE what ever
//
$fname = basename( $_FILES['attachment']['name']);
$_fname = strtolower (end(explode('.',$fname) ) );
Zend_Debug::dump( $_FILES );
//
// Filter the file
//
switch($_fname)
{
case ($_fname == 'jpg' ||
$_fname == 'jpeg' ||
$_fname == 'gif' ||
$_fname == 'bmp' ||
$_fname == 'png' ||
$_fname == 'html' ||
$_fname == 'pdf' ||
$_fname == 'doc' ||
$_fname == 'docx' ||
$_fname == 'xls'
):
$target_path = APPLICATION_PATH . "/../public/files/textual_translation_attachment/";
//chmod("../up" , 0777);
$target_path = $target_path . basename( $_FILES['attachment']['name']);
if(move_uploaded_file($_FILES['attachment']['tmp_name'], $target_path)) {
//echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
//$_sql = "insert into a (huis,image) values ('$_app','$_file')";
// send the file name only .....
//echo $fname ;
}else{
//echo "error ";
}
break;
}
return $fname;
}
If you
Zend_Debug::dump($_FILES);
Do you see your file?
If you are using jQuery, you may want to try Uploadify. This can be done using the
Zend Framework Uploadify Extension
http://gondo.webdesigners.sk/zend-framework-uploadify-extension/