text:
Q: Can't get form to display mysql results I'm fairly new to MySQL and PHP and have been reading books and watching tutorials and trying examples but I'm stuck on getting this search query to work.
I have a simple search form:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 5</title>

Search

 <form name="search" method="post" action="process_search.php">
Seach for: <input type="text" name="find" />
 <input type="submit" name="submit" value="search"/>
 </form>

and here is the part of the php form that processes the search request that I'm having issues with
$db_path ="localhost"; //---Host name or path to database
$db_username ="root"; //-----------------------------MySQL database username
$db_password = "password"; //----------------------------MySQL database password
$db_name = "database"; //--------------------------------MySQL database name
$tbl_name = "stuff"; //---------------------------------MySQL database table

// Connect to server and select databse
 mysql_connect("$db_path", "$db_username", "$db_password")or die("cannot connect");
 mysql_select_db("$db_name")or die("cannot select DB");

//filtering input for xss and sql injection
$input = @$_GET['find'];
$input = strip_tags( $input );
$input = mysql_real_escape_string( $input );
$input = trim( $input );

$sql = mysql_query("select * from $tbl_name WHERE first_name = '". $input . "'");

while ($rows = mysql_fetch_array($sql)){

I'm following the example given but the query doesn't return any results, it will display the table headers as it should but nothing in the tables, I added mysql_error(); to my code and it reports no errors. What am I doing wrong?

A: You wanna change your query to...
$sql = mysql_query("select * from $tbl_name WHERE first_name LIKE '%". $input . "%'");

But you really shouldn't be using mysql_*, its deprecated, you should use PDO to connect to the database
EDIT...
Your form has a method of "post"
so you should have this instead...
$input = $_POST['find'];

I believe that will solve your problem! :)
EDIT 2...
Ok you need to find out why your form isnt posting the variable...
So just have this on the page...
 <form name="search" method="post" action="process_search.php">
  Seach for: <input type="text" name="find" />
  <input type="submit" name="submit" value="search"/>
 </form>

and on your php page have nothing but...
<?php var_dump($_REQUEST);?>

Tell me what you get....
I would chat with you but you don't have enough rep points to chat, so hence multiple edits.

A: Use this - I believe this works. If you still have no results, you may have another problem.
$db_path ="localhost"; //---Host name or path to database
$db_username ="root";  //-----------------------------MySQL database username
$db_password = "password"; //----------------------------MySQL database password
$db_name = "database"; //--------------------------------MySQL database name

// Connect to server and select databse
 mysql_connect("$db_path", "$db_username", "$db_password") or die("cannot connect");
 mysql_select_db("$db_name")or die("cannot select DB");

//filtering input for xss and sql injection
$input = mysql_real_escape_string(strip_tags(trim($_REQUEST['find'])));

$sql = mysql_query("SELECT * FROM stuff WHERE first_name='$input'");

while ($rows = mysql_fetch_array($sql)){


text:
Q: Get email attachment and save into oracle table in google app script I am trying to use google app script to retrieve email attachment,
below is my code to check if there any attachment in the email message
function testMail() {
var threads = GmailApp.getInboxThreads();
for (var i = 0; i < 10; i++) {
  var mess=threads[i].getMessages()[0];
  if (mess.getAttachments().length>0)
  {
    //var filename=mess.getAttachments()[0].
    Logger.log(mess.getSubject());
    Logger.log(mess.getAttachments()[0].getName());
    var conn = Jdbc.getConnection("jdbc:oracle:thin:@xxx.xxx.xxx.xxx/xxx.xxx.xxx", "xxx","xxxxxxx");
    conn.setAutoCommit(false);
    var stmt = conn.prepareStatement("insert into blob_table (filnname,blob_field) values (?,?)");
    stmt.setString(1, mess.getAttachments()[0].getName());

    stmt.setBlob(2, mess.getAttachments()[0]);
    var res = stmt.execute();
    conn.commit();
    conn.close();

    break;
  }
}
}

but the error "cannot find method setBlob prompt" when I run the script, I am able to save data to the table blob_table if I insert only the field filename, is there any special way to insert blob?
Thanks

A: If you look at the autocompletes or documentation you'll see that JDBC, unlike the rest of Apps Script, has its own notion of JdbcBlob which is not identical to Blob. (Every JdbcBlob is a Blob but not vice versa.) You can turn a regular Blob into a JDBC blob like this:
conn.createBlob().setBytes(0, myOriginalBlob)

where in this case myOriginalBlob is what you got from mess.getAttachments()[0])

A: jdbcBlob and Blob are two different things.
In the line stmt.setBlob(2, xxxx);
xxxx is a jdbcBlob. If you have a Blob, you need to convert it into jdbcBlob before saving in DB.
var jdbcBlob = conn.createBlob();
jdbcBlob.setBytes(1, blob);

In your example, the correct approach would be
var jdbcBlob = conn.createBlob();
jdbcBlob.setBytes(1, mess.getAttachments()[0]);
stmt.setBlob(2, jdbcBlob);

redpajama_set_name: RedPajamaStackExchange


text:
Q: New pages in Kentico not listing in googlesitemap.xml Here's the setup:

*

*Root site, set up to show in sitemap and is searchable.

*Page under it doesn't get listed in sitemap (in fact, no pages do).

*Create a new page with options to show in sitemap and is searchable but is not listed in sitemap xml file

In fact, nothing shows in our sitemap except the location of the robots file.
I understand that initially it only lists CMS.MenuItem objects (as per https://docs.kentico.com/k11/configuring-kentico/search-engine-optimization/google-sitemaps).
Is there a setting I'm missing to show pages in the sitemap?
In case it's important: kentico version is 10.

A: Make sure your custom page types are configured in the code file:
Either in code before ~/CMSPages/googlesitemap.aspx or code behind ~/CMSPages/googlesitemap.aspx.cs
Since it's similar to a repeater you can set the ClassNames property to identify the different page types you want it to use for rendering.
e.g. when in code before: ClassNames="CMS.MenuItem;CMS.News;Custom.Type"
Resulting in something like:

<cms:GoogleSitemap runat="server" ID="googleSitemap"
    TransformationName="CMS.Root.GoogleSiteMap" CacheMinutes="0"
    OrderBy="NodeLevel, NodeOrder, NodeName"
    ClassNames="CMS.MenuItem;CMS.News;Custom.Type" />


text:
Q: Issue with if else continue statement within foreach loop I have the following for loop.My question is, if I use continue statement for the first if statement then the second if statement (saveto) not working. From what I see , I assuming there is a logic error.
it would workflow like below :
-All parameter is null and SaveTo parameter is not null , attachment filter will execute and second if statement will execute.
-All parameter is not null and SaveTo parameter is not null , attachment filter won't execute and second if statement will execute.
foreach ($attachment in $attachments.value) {
    # weed out unwanted attachments
    # Use the All siwtch to include them
    If (!$All) {
        If ($attachment.Size -lt 100000 -and $attachment.contentType -like '*image*') {
            #images from less then 100kb
            continue
        } ElseIf ($attachment.contentType -eq 'application/octet-stream' ) {
            #bin files
            continue
            }
    }

    If ($SaveTo) {
        $timestamp = $attachment.DateTimeLastModified.Replace(':','')
        $path = "$SaveTo\$timestamp`_$($attachment.name)"
        #$path = "C:\path\" + $attachment.Name

        $Content = [System.Convert]::FromBase64String($attachment.ContentBytes)
        Set-Content -Path $path -Value $Content -Encoding Byte
    }

}

A: You are specifically instructing your code to skip the $saveto part if $all is not $null by using the Continue statement.

Continue
Return to top of a program loop, skip just this iteration of the loop.
In a For, ForEach or While loop you can add a continue statement to
  jump to the top of the innermost loop.
Example
Count to 10 but miss out the number 5:
$i =0
 while ($i -lt 10)
     {
       $i +=1
       if ($i -eq 5) {continue}
       Write-Host $i
     }

Source:SS64 - Continue statement

The only scenario where Continue can be used to not exit a loop is in a Switch statement. In this specific scenario, the Continue statement will indicate that you would like to skip remaining condition block and evaluate the next condition in the current Switch.
Reference
SS64 - Switch statement

A: That is what the continue statement is for: jump back to the start of the foreach loop and start with the next $attachment. Seel also here


text:
Q: AutoHotKey script activates only on numpad enter My script is only activating when I press the numpad enter, is it possible for it to work if I press the big enter?
Here is what I have, when I type test + numpad enter then it invokes ctr+shift+u
:*:test`n::test^+u
I need the other enter to work or both if possible.
Thanks

A: I tried this:
:*:test`n::bob

And it types bob no matter which enter key I push.  If you use n, that doesn't necessarily indicate that you are pushing anyenterkey - it just means you are inserting a carriage return - so eitherenter` key will do that.  But your text area must be able to receive and insert a carriage return.
That means, that if you are working in a single-line text box, it can't receive a carriage return, in which case, using `n won't work for you.
You might also assure that the active window is able to receive ^!u and do something with that.


text:
Q: How do I connect a scanner and scan a document on Windows Server 2019? I have a computer running Windows Server 2019 standard. I know that it isn't the typical use case for Windows Server, but I am trying to connect a Canon TR4520 printer/scanner so I can scan paper documents here in the lab. The printer is connected and can print, but I can't find any app/setting that will allow me to scan a document, and the printer can't find the computer when I try to scan from the printer's menu.
If I was on Windows 10, I'd just install Windows Scan, but I'm not aware of a way to install Windows Store apps on Windows Server.
It looks like I want to use DSM, but it was removed in the 2019 server release.
Most of my Google searches landed me on this question, which isn't quite relevant to me.

A: Since you have installed the Desktop Experience feature that includes
Windows Image Acquisition (WIA), and have verified that WIA is installed and running,
you only need an interface to the scanner.
For scanner software, check first if you installed the Windows Fax and Scan.
(I'm not sure if it's available in Windows Server 2019.)
For more options, see the article
12 Best Free Scanner Software For Windows 10 to Scan Documents
(although several only have paid versions).

A: According to this Canon support document, you need to make sure that "IJ Network Scanner Selector EX2" is running. To start it:

From the Start menu, click (All apps >) Canon Utilities > IJ Network
Scanner Selector EX2.

Once it is running, you can select your printer. While running, its icon will show in the System Tray area of the Taskbar.
To scan from the printer's front panel, follow the instructions on this page.


text:
Q: Is it better to store telephone numbers in some canonical format or "as entered"? Storing a telehone number in some kind of canonical format has several advantages from a programmers point of view, but it might confuse the user, if suddenly his entered numbers look a lot different.
What's the way to go?

A: Hopefully this is a more practical and applied answer to an old question.
Take a look at https://github.com/googlei18n/libphonenumber.
As @Gumbo alluded to, I would store the phone number as E.164, which the above library parses for you. It can be used from several different programming languages.
For DB storage you could in fact use E.164 as Base64 (since it ironically is valid base64), and decode Base64 as bytes. I believe the number of bytes from a string like that will fit a standard long. Personally I would just store the E.164 as a string in the database though.
Of course, you should probably also store what the user entered originally before parsing, but I highly recommend you enter in some canonical number like E.164 for future integration with other systems.

A: What's your userbase?
If they're going to be limited geographically (i.e., US-only) and you're going to validate numbers strictly, then format the number canonically for them -- i.e., strip out any formatting they used (like periods between numbers...) and put in the dashes (do not fail validation if they don't stick to your formatting... that's just mean).  I'd store that cleaned-up version in the DB as well, not a stripped number; it makes your life a bit easier when generating custom reports, etc..
If you might have users/numbers from all over the world, it might be better to save the formatting they used.  Also don't forget the case that sometimes US residents are currently traveling and using a foreign number: don't block them unintentionally.
Either way: make sure you DON'T define the column as numeric, or make it too small.  International numbers with formatting can easily be over 16 chars long.

A: Separation of Duties - Content and Rendering
Store the number in a canonical format and the display format mask.
Gains:

*

*Canonical format for consistency, quality, and ease of analysis

*Format retained from end-user perspective

*Format re-usable to display other phone numbers in end-user preferred method

*Other format masks can be used to display canonical number to other users with a need to see the phone number

Pains:

*

*Parsing the phone number to the canonical format

*Parsing out the display format mask (not too painful in combination with above bullet)

*Storing the display format as an end-user preference

A: The UK is a special case as we have variable length STD (area) codes and variable length subscriber number itself. The longer the STD code the shorter the number. Germany and a few other countries also have a similar system.
Numbers are mostly 10 digits after the 0 trunk (long distance) prefix, but several dozen areas also have some 9 digit numbers.

*

*020 2345 5678 (London) also Cardiff, Southampton, Portsmouth, Coventry and Northern Ireland

*0115 234 4567 (Nottingham) also Sheffield, Bristol, Leicester, Reading and Leeds

*0141 345 5678 (Glasgow) also Birmingham, Edinburgh, Tyneside, Manchester and Liverpool

*01332 234 456 (Derby) most other areas (about 580 areas) also use this format

*01750 45678   (Selkirk) and about 40 areas have some numbers that are a digit shorter

*017687 45678  (Keswick) also Langholm, Hornby, Hawkshead, Grange-over-Sands, Sedbergh, Wigton, Raughton Head, Brampton, Appleby, Pooley Bridge and Gosforth.

*016977 2345   (Brampton) The only place using "5+4" format.

*07812 123 456 (mobile numbers)

Beware that 0800 numbers can be different lengths, e.g. 0800 567 1234 or 0800 234 456.
The old 0500 numbers are also a digit shorter, e.g. 0500 456 456.
Additionally some people like to group their numbers 234 234 while others use 23 23 23 (depending on the actual digits).
There are arguments for storing as entered and storing in a single form:
If you store the number as just the sequence of numbers then you can output it in any way you want, either by taking into account user preferences or their locale and splitting the number up according to "rules" (what ever they may be).
If you store as entered then you'll always display it as the user expects, but you'll need to strip out non numeric values before using it, which if it's often could be expensive.

A: I would keep the original entered mess but would also insert a cleaned up form in the database. Which only kept the numbers less punctuation and spaces. Using the cleaned form would allow easy lookups without worrying about different possible entered styles.

A: The main difficulty in canonicalizing phone numbers is determining the correct canonical format.  Different countries have different ways of grouping numbers - and within a country, different numbers can be grouped differently.
It used (once upon a decade or more ago) to be that case that in the UK, you had 01-234-2345, 021-234-1234, 0334-234234, even 092324-213; things are different in the UK now - generally more digits, and I'm not sure about the groupings any more (absence makes one's knowledge less current).
Dealing with country prefixes and indicating the internal country dialling prefix is fun: +44 (0)1394-726629 is a UK number, country code 44; dialling from outside the UK, drop the 0; dialling inside the UK, do not include the international prefix but do include the 0. Do note that the form with (0) in it is in fact not valid if you follow the E.123 standard.
This is similar to the problem of canonicalizing mail addresses - not as complex, but still bad.
Also, as noted in my comment to HeavyWave's answer, forcing people to enter the phone number as a digit string with no punctuation is nasty.  It's fine to store it that way; just present the data in a human readable format.  There's far too much lazy web form programming out there.

A: Store it however you prefer, but turn it into human readable format before you show it to the user. And please don't force your users to enter phone numbers in a format of your choosing, let them just type it in however they like.
That's how I do it.

A: My gut instinct is to canonicalize according to the local standards of the entity, then render in the canonical representation modulus usability.

A: Let the user enter whatever format they are comfortable with, then validate it and store it in the database in a consistent format - preferably with the country code included.
When displaying the number, display it in the correct format for that number range, with correct spacing, and for national format numbers add parentheses around the area code if needed.
If displaying as an international number, be especially careful not to include any international access code as that varies from country to country, e.g. showing a French number as 011 33 55 66 77 88 (as dialled from the US and Canada) is of no use to UK readers because they will dial 00 33 55 66 77 88; always use the +33 55 66 77 88 format.
Also with the international format, never include the (0) trunk prefix. The international format should only include the digits that are dialled from abroad.

A: Validate the input but allow wide array of formats. Store it as user typed it and then reformat the output as needed.
Let's say user typed his number during registration to public phonebook application. So I would display it 'as user typed it' in the textfield on his 'edit my profile' page, for example. But I would display it reformatted to standard format on the public user phonebook list.

A: Useful resources:
List of UK area codes:  http://www.telephonenumbers.co.uk/Telephone-Area-Codes-UK/i=2 (dated July 2011).
List of number lengths/number formats for the UK (covers 01 and 02 numbers):  http://www.aa-asterisk.org.uk/index.php/01_numbers
Allocations in "Mixed" areas:  http://www.aa-asterisk.org.uk/index.php/Mixed_areas
Allocations in "ELNS" areas:  http://www.aa-asterisk.org.uk/index.php/ELNS_areas
UK prefix list with formatting information:  http://www.aa-asterisk.org.uk/index.php/Sabc.txt
Formatting UK numbers is certainly a LOT more complex than (01234) 567890, (0141) 234 5678 and (020) 3456 7890.

A: I usually like to store the number stripped and then format for display.  Since I don't usually build application for use worldwide, I don't generally have to worry about the format.  But in the case of an application for use all around the world, I would probably build a formatting module that formats according to the phone number's locale.


text:
Q: Orthogonal group acts on vector field I recently had an exam, yesterday acctually, and there was a question that stumped me.

The orthogonal group $O(n)$ acts on $\mathbb{R}^n$ by matrix multiplication, show that the orbit space is homeomorphic to $[0,\infty)\subset\mathbb{R}$

I could logically narrow $\mathbb{R}^n$ to positive coefficients by having a diagonal unit matrix where 1 is replaced by $-1$ and so on, I was very uncertain however how to collapse it down further in dimension so it became homeomorphic to $\mathbb{R}$
How would one go about this exacly?

A: Note that $O(n)$ preserves the norm of the vector being acted on. In fact any two vectors of the same norm are in the same orbit of the $O(n)$-action, and the orbits are spheres centered at the origin and the origin itself.


text:
Q: Removing parameter when differentiating parametric function gives a different result than direct application of chain rule Consider the function
$$f(x,y)=\sqrt{x^2+y^2}.$$
If we introduce the variables
$$\begin{align}
r&=x\cos\varphi-y\sin\varphi,\\
u&=y\cos\varphi+x\sin\varphi,
\end{align}$$
we'll get that
$$f(x,y)=\sqrt{x^2+y^2}=\sqrt{u^2+r^2}.$$
If we now fix $x$ and use $y$ as a parameter and consider a parametric function $(u(x,y),f(x,y))$ and try to differentiate $f$ with respect to $u$, we'll get:
$$\frac{\mathrm{d}f}{\mathrm{d}u}=\frac{\mathrm{d}f}{\mathrm{d}y}\bigg/\frac{\mathrm{d}u}{\mathrm{d}y}=\frac{y}{\sqrt{x^2+y^2}}\bigg/\cos\varphi=\frac{y}{f(x,y)\cos\varphi}.$$
But if we directly express $f$ in terms of $u$ and differentiate the resulting expression, we'll instead get:
$$\frac{\mathrm{d}f}{\mathrm{d}u}=\frac{\mathrm{d}}{\mathrm{d}u}\sqrt{u^2+r^2}=\frac{u}{\sqrt{u^2+r^2}}=\frac {y\cos\varphi+x\sin\varphi}{f(x,y)}.$$
These two results don't match, but I can't seem to spot the mistake.
So what am I doing wrong here? Why don't the results match?

A: The mistake is in the second method, where you treat $r$ as constant whereas it still contains the parameter $y.$
You're supposed to differentiate the function $$\sqrt{x^2+\left(\frac{u-x\sin\phi}{\cos\phi}\right)^2}$$ instead.


text:
Q: PDF looks different on Android My PDF does not look the same on the Android PDF reader as on my laptop. Many mathematical symbols (Greek letters, operators, ...) are not displayed correctly but replaced by something else.
Are there options when building the PDF to prevent this from happening?


text:
Q: Why does rowspan "3" delete one entire row and sets it to "2" I need help with rowspan, I set it to 3 and colspan to 3, but it deletes one entire row and sets it to 2.
I have 4 rows in my table but when I write the code it ends up to 3 rows. I don't understand why doesn't it span properly, thanks for the answer, here is the HTML code below.

td {
  text-align: center;
  border: 2px solid black;
}

    7

    8

A: That's really strange behaviour, but the reason obviously is that none of your columns actually contains four cells (three is the most) and all cells only have very little content (if at all), so the table is being reduced/compressed to three rows in height.
I would definitely call that a rendering or interpretation error of the browser. But...
The crucial point seems to be the second cell in the first row, which should be two rows high: If you actually put some more content into it, it will be two rows high, and the whole table will be displayed as desired. See my snippet below, where the only real difference to your code is the additional content in the second td:

table {
  border-collapse: collapse;
  table-layout: fixed;
  border: 2px solid black;
}

td {
  text-align: center;
  border: 2px solid black;
}

    A1
    A2 containing more text
    A3
    A4

    B1
    B2

    C1
    C2

    D1
    D2

P.S.: Note also this answer of mine to a very similar question.

A: I didn't get it with the table, but display: grid; exists now.
Here is the template with this solution :

.grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr 1fr;
  gap: 0px 0px;
  grid-template-areas:
    "a b b g i i i"
    "a b b h j j j"
    "a c d h j j j"
    "a e f h j j j";
  text-align: center;
  width: 100%;
}

.grid-container > div {
    border: 1px solid;
}
.a { grid-area: a; }
.b { grid-area: b; }
.c { grid-area: c; }
.d { grid-area: d; }
.e { grid-area: e; }
.f { grid-area: f; }
.g { grid-area: g; }
.h { grid-area: h; }
.i { grid-area: i; }
.j { grid-area: j; }

a

b

c

d

e

f

g

h

i

j


text:
Q: Code is not formatted in this answer This answer is not formatted even though it has 4 spaces identation.

A:  public void keyPressed(KeyEvent e) {
     int keyCode = e.getKeyCode();
     switch( keyCode ) {
         case KeyEvent.VK_UP:
             // handle up
             break;
         case KeyEvent.VK_DOWN:
             // handle down
             break;
         case KeyEvent.VK_LEFT:
             // handle left
             break;
         case KeyEvent.VK_RIGHT :
             // handle right
             break;
      }
 }

A: Weird.  It had 5 spaces of indentation and a single empty (except for the indentation) line at the beginning.  When I removed those, it fixed the formatting.

A: I don't know what was broken here nor when it got fixed, but it works correctly now (I tried Bill's answer on a dev build, and it renders correctly).


text:
Q: Why i am not able to choose manually the consumed quantity? I am using the Fiori launchpad for PEO to execute my shop floor orders and I cant choose the quantity to be consumed. I am expecting to have 10 out of 10 consumed. It is working for the single components but for the sub assemblies not

Do you know the source of this problem or is there anything missing in customizing?
Thank you!


text:
Q: Why is my game object going up when "jump" button is only pressed once (when gravity in rigidbody is turned off) in Unity? So I was trying to add jump button to my player in Unity and I was successful with it
But while test running the game, everything was fine until I switched off the gravity
I pressed the jump button once, and the player kept going up at const speed. I solved the problem by turning on the gravity again.
I just wanna know why did that happen?
This is my part of the "jump code" for reference:-
void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity = new Vector3(0,3,0); //rb : rigidbody object
            print("Jumped");
        }
    }


text:
Q: Can i test accelerometer effect in Xcode simulator? I am working on an app that manages the alpha property of image views. Alpha property can increase/decrease as the user moves the phone. I saw something on here about using a subclass of UIAccelerometer. Can anyone help me to do this so that I can test it on simulator?
Thanks

A: Yo cant test it using simulator, you should use real device for testing accelerometer.
Check here, it may help you.

A: You can "capture" accelerometer data coming from a real device.
You can purchase iSimulate
here:
http://bobueland.com/cocos2d/2011/how-to-install-isimulate/
..or
you can use a free solution: accelerometer-simulator
More about how to install or tutorial:

*

*http://builtby.me/2012/07/howto-use-the-accelerometer-in-the-iphone-simulator/

*http://builtby.me/2012/07/iphone-accelerometer-visualizer/

*http://myfirstiphoneapp.co.uk/2011/07/receiving-accelerometer-data/

A: You can't test Accelerometer feature on Xcode simulator.
For this, see following on apple's site.
Limitations of Testing in iOS Simulator


text:
Q: Kohana 3.1 ORM - Conditional Parameters I am trying to achieve a very simple goal, however it does not seem to be working. I wish to use Kohana's ORM and conditionally add certain parameters.
For instance:
$query = ORM::factory('user')
  ->where('foo', '=', 'bar');

if (isset($some_var))
  $query->where('field', '=', $some_var);

$query->find_all();

One would think this should work, but all I get from $query is a big fat nothing. Any suggestions I would greatly appreciate! Thanks.

EDIT:
The simple example on this Kohana page even shows a similar query:
http://kohanaframework.org/3.1/guide/orm/examples/simple
...But even when I create a 'user' model instance and then try to find_all() in a separate statement, I get nothing.
This works:
$query = ORM::factory('user')->find_all();

This doesn't work:
$query = ORM::factory('user');
$query->find_all();

Possible bug??

A: In your example that works, you are assigning the value returned from find_all() to $query. While in the example that is not working, you are not assigning the value returned by find_all() at all.
kohana framework
$query = ORM::factory('user');
$result = $query->find_all();
// you may now loop over $result

When you look over the api, you will see that find() and find_all() work differently.

A: Your code is perfectly fine, as ORM::where method returns ORM object, so there is no problem with method chaining. You should look for the errors in other place (perhaps your $some_var is set but may be empty, therefore your condition may look different then expected). I'd try with this small change:
if (!empty($some_var))
  $query->where('field', '=', $some_var);


text:
Q: How to fix unreadable selected text color in Eclipse Mars file properties dialog on Ubuntu? In Eclipse Mars (and also previous versions) on Ubuntu (any version) when I select some text in file properties dialog it becomes unreadable because of its color.
Unselected text is OK:

But selected text is unreadable:

What settings do I need to change in Eclipse, GTK3 config or anywhere else to make the selected text readable?

A: To answer my question:
The issue here is that GtkTextView widget that displays this text in Eclipse (identified by GTK Inspector) ignores background-color CSS property defined by the desktop theme, but color property is applied.
Therefore when the text is selected its color is correctly changed to grey based on the theme CSS but the background-color defined by the theme as blue, which would make the grey text readable, is ignored for some reason and the result is unreadable combination of grey text on grey background.
This is probably a defect in Eclipse, because GtkTextView widget in other applications applies the background-color correctly. The workaround is to select a theme that sets a selected text color to something readable on grey Eclipse dialog background or to change the selected text color only for GtkTextView  widget by adding this CSS style to the file:
~/.config/gtk-3.0/gtk.css
/* Selected text in eclipse file dialog and others.
Other css styles like background-color or font-weight do not seem to work*/
GtkTextView:selected,
GtkTextView:selected:focused,
GtkTextView:selected:backdrop,
GtkTextView:selected:focused:backdrop {
        color: #2ca5d8;

}

And the selected text is now readable:

A: @mmm Great I am also struggling to fix this issue.Thanks.
I am extending your answer little bit further.
Set background-color and color properties of GtkTextView so that selection should looks similarly like in other editors. I used the same color code for background-color which is same as @define-color selected_bg_color value in /usr/share/themes/Ambiance/gtk-3.0/gtk-main.css
Where Ambiance is my theme name.
~/.config/gtk-3.0/gtk.css
/* Selected text in eclipse file dialog and "Text Areas"others.*/
GtkTextView:selected,
GtkTextView:selected:focused,
GtkTextView:selected:backdrop,
GtkTextView:selected:focused:backdrop {
        background-color: #f07746;
        color: #ffffff;
}


text:
Q: What's the highest DPS Wizard rotation for a single-target fight? For some boss fights where the vast majority of the time you're simply beating on a single big baddie, what are the most effective spells (and runes) for the Wizard to use?  Such a build might not be the "best" as you're prone to dying, but it would be good to know where the top is as a baseline and perhaps build beefier from there.

A: Your new question is fairly dependent on a lot of factors, but you want to start you build by looking at a combination of Ray of Frost (either Snow Blast or Cold Blood).  Snow Blast is technically our highest DPS, but it takes time for it to ramp up.  If you are doing hit and run, then Cold Blood will serve you better and leave you more mana to work with.
Magic Missile with Charged Blast is going to be your best single target Primary unless you are trying to trigger a proc of some sort.  If you are, then Electrocute is were you want to look for that.  A good primary is important to keeping the damage up while you regen mana.
For raw damage increase, Force Weapon is an obvious buff worth taking.  Sparkflint will increase both your attacks and provide shots of its own.
Hydra is probably the best spell for adding additional single target damage for little mana.  The other Force and Conjuration spells are geared more towards AoE.  Conflagration will cause the Hydra to give you an additional 10% boost to your damage.
Slow time can be used to boost damage in several ways in addition to providing some defense.  Stretch time will provide a nice 10% increase to attack speed.
Arcane Dynamo, Conflagration, and Glass Cannon are going to be the passives you want to look at first.
So to sum it up, assuming single target with no worries about survival here is a good start:
Ray of Frost (Snow Blast or Cold Blood),
Magic Missile (Charged Blast),
Magic Weapon (Force Weapon),
Familiar (Sparkflint),
Slow Time (Stretch Time),
Hydra,
Arcane Dynamo,
Conflagration,
Glass Cannon

A: Ray of Frost is a great single target spell that starts around 200% weapon damage.  You can rune it so that it does more damage the longer it is on the target or to not cost any AP at all.  When the slow does effect a boss, it gives you more time before you have to move and has a quick casting animation.  Also combos well with some of the other abilities.

A: Ray of Frost is the best choice for the boss fights that have few adds involved, but to be honest, most bosses in D3 don't really allow you to just nuke them endlessly. You're better off trading some DPS for defensive/CC abilities. (In hell & inferno difficulties you won't have a choice in this.)
My single-target DPS uses Magic Missile (Charged Blast), Ray of Frost (Snow Blast or Cold Blood), Mirror Image (Mocking Demise), Frostnova (Bonechill or Cold Snap depending on whether you prefer higher DPS or more CC), Teleport (Fragmented), and Energy Armor (Pinpoint Barrier).
For passive skills, I took Prodigy, Conflagration to augment your Sparkflint's damage**, and Glass Cannon (beware Glass Cannon - nearly all bosses can potentially 1-shot you with this active).
The constant mirror images give the boss something else to fight while you nuke (yes, i said constant: your Teleport is giving you mirrors too now XD), and Frost Nova can aid in keeping the boss at a distance. The Mocking Demise mirrors do not provide particularly impressive DPS, but it's a free nuke from a defensive skill.
If you take Illusionist in this build, you will be doing a ridiculous amount of kiting but will still be free to pound the boss for long periods. So trading Conflagration or Glass Cannon for Illusionist may be preferable over the long run as you cannot deal out DPS when you are dead.
The most important thing to remember about rays is that you need to stand still to cast them, making you that much more vulnerable. Sometimes it is better to not think about a fight purely in terms of DPS unless you already have the means to keep the bad guy away from your face.


text:
Q: Reference Object Member By String Name? Sorry for the odd question name folks, I'm not sure I properly know how to phrase this question, but I am working with javascript, and would like to reference an objects member, but abstractly by string, is this possible in JavaScript? (or any language for that matter?) eg,..
The MemberName is determined when the function is run, could be 'Product Code' for example, but selected row will always represent a selected row in a grid. is this even possible? I am trying to create a generic function which will allow me to pass any grid to it, with the name of the column i want the value from - if that helps.
function GetSpecificColumnFromSelectedRow(SelectedRow, MemberName) {
    return SelectedRow.MemberName;
}

A: It's rather easy:
SelectedRow[MemberName]

And you don't need a function to do it, which is why I didnt include your original function wrapper.


text:
Q: PHP - getting key and value using checkbox     Documents     Original            Xerox
-------------------------------------------------
    ABC          <checkbox>          <checkbox>
    DEF          <checkbox>          <checkbox>
    XYZ          <checkbox>          <checkbox>

I have a checkbox structure, as you see it above.
But I am not sure, how am I suppose to implement it.
I know the working of a normal checkbox, as it has only one checkbox.
But in this case, for every document, there are 2 checkbox (original copy and xerox copy)
What I have in mind like, after the submit is clicked, I need to somehow get an array in a form like below
ABC -> [1][1]
DEF -> [0][1]
XYZ -> [1][0]

Where first [] is orginal, and second [] is xerox.
Where 1 denotes that it was checked, and 0 denotes unchecked.
I am not getting an idea how should I implement it.
This is my code...(It may be horribly wrong, i agree.. but i still i made an attempt.. but couldn't figure it out.)

  Aadhar
  <input type="checkbox" name="document[]" value="1"/>

  Pan Card
  <input type="checkbox" name="document[]" value="1"/>

  Address
  <input type="checkbox" name="document[]" value="1"/>

  Light Bill
  <input type="checkbox" name="document[]" value="1"/>

  <input type="submit" value="Submit" />

PHP
$documents = $_POST['document'];
$a = implode($documents);
echo $a;

So far, I am getting 1 (value) correctly.. But I also need the document (key) to which the '1'(value) belongs.
Can anyone help me out please.

A: Checkboxes only submit WHEN CHECKED, so you'll NEVER get a checkbox submitting a "0" value.
That said, you can know it's NOT checked by simply asking PHP if it was set, like so: isset($_POST['document']['aadhar'][1]) -- if that returns true, it was checked, if not, it was not checked.
One thing to note: You're going to want to specify indexes for your second dimension of the array, so this:
<input type="checkbox" name="document[aadhar][]" value="1"/>

Becomes this:
<input type="checkbox" name="document[aadhar][original]" value="1"/>

That way you can track the "column" of which checkbox was selected by asking isset().
Here is a working example: http://myingling.com/random/random/44476276/
Here is the HTML from that example:
<form action='post.php' method='post'>

      Aadhar
      <input type="checkbox" name="document[aadhar][col1]" value="1"/>
      <input type="checkbox" name="document[aadhar][col2]" value="1"/>

      Address
      <input type="checkbox" name="document[light][col1]" value="1"/>
      <input type="checkbox" name="document[light][col2]" value="1"/>

      <input type="submit" value="Submit" />

</form>

Here is the PHP from the post.php:
<?php
echo "
";
var_dump($_POST);
echo "
";


text:
Q: Redacting phone numbers I need to hide phone numbers and other contact details in user generated content to make possible an online introduction service. Input is random classifieds style adverts, therefore I'd be looking to replace anything that looks like a phone number (e.g.: string of 3 or more numbers) with (phone number hidden), and also perhaps remove some exotic notations of e-mail addresses.
What is the best way to do this?
def redact_contact_details(s):
    # redact phone numbers
    ...
    # redact e-mail addresses
    ...
    # redact web addresses
    ...

Edit: Some of what I learned and coded to solve this type of problem is out and open source https://github.com/fmalina/django-reveal

A: In Python, to replace three or more digits with three dots in string s:
import re
s = re.sub(r'\d{3,}', '...', s)

"Exotic notations of e-mail addresses" is hard for me to parse; maybe you mean s/thing like
s = re.sub(r'[\w.]+@[\w.]+', '<email redacted>', s)

A: By web addresses I'm guessing you mean URLs. You could create an array that contains all possible domains (".ca",".com",".uk"....). You can then run a regex replace on any 'word' that contains one of the domains.
To do the replacement you can use Alec Martelli's code and instead of putting the '@' in your replacement put the join of the array of domains. The join function is explained on this site.
If in perl I would do the match like :
my $domainsString = join("|", @arrayOfPossibleDomains);
$s =~ s/\w+[$domainString]\w+/......./g;

A: You can create a simple function that just replaces any alphanumeric character with a "." or any other character you want.
For example:
function HideInput($input) {
    $input = preg_replace("([a-zA-Z0-9])", "*", $input);
    return $input;
}


text:
Q: favicon is not working SharePoint Online site using HTML master page I'm using HTML master page for SharePoint online site. To show favicon i have included the below code in HTML master page,
<link rel="shortcut icon" href="https://siteurl/favicon.ico" type="image/x-icon"/>

But is not showing any icon in the browser.
Thanks in advance

A: Try to do the following:

*

*Upload your icon to Site Assets

*In your Master Page file locate the tag bellow:
<SharePoint:SPShortcutIcon runat="server" IconUrl="/_layouts/15/images/favicon.ico?rev=23" />

*Replace it with:
<SharePoint:SPShortcutIcon runat="server" IconUrl="/SiteAssets/favicon.ico" />

*Save and Check-In.

Note: In SharePoint online, Microsoft recommends to don't modify the
  default master page but it didn't stop you from doing it if you want
  to do. So, if you need to change the icon without changing the master
  page try to  create a delegate control as mentioned at
  Best approach to use new .ico image for my sharepoint online site collections without the need to modify the seatle.master

A: Remove shortcut from rel. It is non-conforming and may be causing the line of code to get kicked out on render. Design Manager is picky about clean code.
<link rel="icon" href="https://siteurl/favicon.ico">


text:
Q: Transformation to unit sphere I read a book on harmonic analysis where there is the following transformation, which I don't understand:
$$\lim\limits_{\varepsilon\to 0}\int_{\varepsilon <|y|<1}\frac{\Omega(y')}{|y|^n}\mathrm{d}y=\lim\limits_{\varepsilon\to 0}\int_{{S^{n-1}}}\Omega(y')\mathrm{d}\sigma(y')
\cdot \log(1/\varepsilon)$$
Where $\sigma$ is the Lebesgue measure on the unit sphere and $y':=y/|y|$ and $\Omega$ defined on the unit sphere in $\mathbb{R}^n$ is integrable.
I tried to work with the transformation theorem and the transformation function  $\phi:x\mapsto x^n/|y|^n$. What confuses me is what is happening with $y'$ and why there is a $\log(1/\epsilon)$. If someone could explain me this step, it would be greatly appreciated.

A: Use the parametric representation
$$(r,y')\mapsto y:=r\>y'\qquad(\epsilon\leq r\leq1, \quad y'\in S^{n-1})$$
of the given domain of integration. Then $|y|=r$ and $${\rm d}(y)=r^{n-1}{\rm d}\omega(y')\>dr\>,$$ whereby ${\rm d}\omega$ denotes the surface element on $S^{n-1}$. It follows that
$$\int_{\epsilon\leq|y|\leq 1}{\Omega(y')\over|y|^n}\>{\rm d}(y)=\int_\epsilon^1\int_{S^{n-1}}\Omega(y')\>{\rm d}\omega(y'){1\over r}\>dr=\log{1\over\epsilon}\int_{S^{n-1}}\Omega(y')\>{\rm d}\omega(y')\ .$$

A: Edit: Below I had the idea to use Fubuni's Theorem, but I think since the area we integrate over is not in the style of $X \times Y$, this is not possible. Instead we need to use polar coordinates. See Integration of radial functions? ... Note that $\frac{\Omega(y')}{|y|}$ is a radial function. So
$\int_{\varepsilon <|y|<1}\frac{\Omega(y')}{|y|^n}\mathrm{d}y=\\
\int_{\varepsilon}^1\frac{\Omega(y')}{r^n}r^{n-1}\mathrm{d}r\\
$
And then you are back at the calculation that gives you $log(1/\varepsilon)$

oldpost:
It think this makes sense if it's $|y|$ instead of $|y|^n$ on the left hand side. Let $\varepsilon > 0$ then:
$\int_{\varepsilon <|y|<1}\frac{\Omega(y')}{|y|}\mathrm{d}y=\\
\int_{\varepsilon}^1\int_{|y|=r}\frac{\Omega(y')}{|y|}\mathrm{d}y\mathrm{d}r=\\
\int_{S^{n-1}}\Omega(y')\int_{\varepsilon}^1\frac{1}{r}\mathrm{d}r\mathrm{d}\sigma (y')=\\
\int_{{S^{n-1}}}\Omega(y')\mathrm{d}\sigma(y')
\cdot (\log(1) - \log(\varepsilon)) = \\
\int_{{S^{n-1}}}\Omega(y')\mathrm{d}\sigma(y')
\cdot \log(1/\varepsilon)
$
Is that calculation somewhat clear?


text:
Q: Minimum hardware requirements for gitlab-runner How can I determine what is the minimum hardware requirement for install the gitlab-runner on a host?
I want a specific runner which will run tests, build docker images, and deploy the apps.

A: Gitlab documentation gives some advices and put focus on memory :

Depending on how you decide to configure GitLab Runner and what tools you use to exercise your application in the CI environment, GitLab Runner can consume significant amount of available memory.

After that, it's really depending the type of application you want to test/build/deploy. Test and build job will be the largest resource consumers. You can also set limits on cpu/memory for docker runner.


text:
Q: BREAKING DOWN AN INCEMENTAL COLUMN IN SQL I have an Employee table with the following columns EmpId, Emp_Name and Emp_Salary. So the Emp_Salary is an incremental column where each cell is that particular employer's salary plus preceding salaries.
Example: Emp_Salary (1000, 3000, 4000, 7000, 8000)
How do I write code to get a new column which gives the individual salaries (1000, 2000, 1000, 3000, 1000), which doesn't sum previous salaries.
Expected output:

Emp_Salary
Individual_Salary

1000
1000

3000
2000

4000
1000

7000
3000

8000
1000

A: You didn't tag your database but this would work with many of them (ie: postgreSQL, MS SQL server ...):
select
emp_salary - lag(emp_salary,1,0) over (order by emp_salary)
from employees;

However, I must note that your table definition doesn't make any sense.


text:
Q: Extent reports v5 features customization similar to Allure-reports I wanted my report to show the steps in detail for each test case, say,
test001() has
Login to application,
Provide Username and Password,
Click Signup button etc
Verify INbox
Verify Outbox
Verify Sent
Verify Draft.
test002()
Search with a keyword
Display result
Click on result
etc..
Similar to Allure-report test case descriptions. [See allure report screen shot below ]
enter image description here
How do I achieve this using extent report TestListener TestNG?
Appreciate your help.
Thanks
Renjith
tried getMethod(), but didnt find details to display the test body.


text:
Q: Django view doesn't contain a HTTP_REFERRER header I'm testing a view that is accessing request.META where I want to get the HTTP_REFERRER header. The purpose being that I want to redirect to a previous page in case the queryset within the search_list view returns empty. A referring page happens to contain a form which is submitted through a GET request. The cleaned data is then passed to search_list as a query string.
When testing the view, all test assertions pass. However when I python manage.py runserver and simulate the test case I get an error: KeyError at /minerals/search; 'HTTP_REFERRER'. I'm trying to understand why I'm getting a KeyError when running the server?
I tried using HTTP_REFERER and HTTP_REFERRER for keys but both fail.
Also noting this:
Internal Server Error: /minerals/search/
"GET /minerals/search/?query=Kryptonite HTTP/1.1" 500

test_views.py
class SearchFormResults(TestCase):

    def test_user_search_query_fail(self):
        response = self.client.get(
            reverse("minerals:search_list"), data={'query': 'Kryptonite'},
            HTTP_REFERRER=reverse(
                "minerals:letter_list", kwargs={'query': 'N'}
            ), follow=True
        )
        self.assertRedirects(response, reverse(
                "minerals:letter_list", kwargs={'query': 'N'}
            )
        )
        self.assertTemplateUsed("minerals/list.html")
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "No minerals exist with the provided search.")

views.py
def search_list(request):
    search_query = request.GET.get('query')
    matched_minerals = Mineral.objects.filter(
        Q(name__icontains=search_query)|
        Q(image_caption__icontains=search_query)|
        Q(category__icontains=search_query)|
        Q(formula__icontains=search_query)|
        Q(strunz_classification__icontains=search_query)|
        Q(crystal_system__icontains=search_query)|
        Q(unit_cell__icontains=search_query)|
        Q(color__icontains=search_query)|
        Q(crystal_symmetry__icontains=search_query)|
        Q(cleavage__icontains=search_query)|
        Q(mohs_scale_hardness__icontains=search_query)|
        Q(luster__icontains=search_query)|
        Q(streak__icontains=search_query)|
        Q(diaphaneity__icontains=search_query)|
        Q(optical_properties__icontains=search_query)|
        Q(group__icontains=search_query)
    )

    if not matched_minerals:
        messages.info(request, "No minerals exist with the provided search.")
        previous_page = request.META["HTTP_REFERRER"]
        return HttpResponseRedirect(previous_page)
    else:
        search_form = SearchForm()
        return render(
            request, 'minerals/list.html',
            {'minerals': matched_minerals, 'form': search_form}
        )


text:
Q: JSON service is not getting in controllers I don't know what wrong with my code.
<body ng-app="MyApp">

Please check this url http://jsfiddle.net/9budtfmo/1/
The JSON response is not getting in my controllers. If I have added the json data in the variable 'users' without using $http.get() method, it will work perfectly. But I didn't get response when I am using http.
Please help me. Thanks.

A: if you open console you can see

Error 404
We're truly sorry, but there is no such page.

which means your json file not exist


text:
Q: Apex 4.2 capture filepath using file browse item Apex 4.2 : I want to capture the filepath after browsing and selecting a file  using item File browse (WWV_FLOW_FILES). The file is uploaded as a BLOB but all info regarding its original location is missing, as it is replaced by f.i. F12457/<name doc>.docx.  When using File Browse (browsing for a document and selecting) however the complete path (f.i. L:\abc\def\document.docx) is shown in the field (although its value then is already F999999/document.docx).

A: Browser security stops JavaScript from accessing this information
How to get full path of selected file on change of <input type='file'> using javascript, jquery-ajax?
eg:
$('#P6_FILE').val()

"C:\fakepath\12c_notes.txt"

A: declare
v_doc varchar2(100);
begin
select :P_DOCUMENT into v_doc from dual;
:P59_DOCNAME := v_doc;
end;


text:
Q: C# how to refactor class by adding template I want to refactor this class to handle more types of objects
public class MyClass : IMyClass
{
  public void method()
  {
    IT obj= new ConcreteObject();
    //Some code
  }
}

Into this:
public class MyClass<T> : IMyClass
  where T: IT, new()
{
  public void method()
  {
    IT obj= new T();
    //Some code
  }
}

Because now more functionality is available in the new ConcreteObject.
The problem is that a lot of projects use MyClass and I don't want them to change or even know there was a change.
I just want the default value of T to be the ConcreteObject.
How this should be handled?

A: You can make the generic version of MyClass an intermediate of the non-generic version. As long as you are careful in your refactoring process, the class interface of the non-generic class will stay the same:
public class MyClass<T> : IMyClass
  where T: IT, new()
{
  public void method()
  {
    IT obj= new T();
    //Some code
  }
}

public class MyClass : MyClass<ConcreteObject>
{
}


text:
Q: Will Ubuntu run well on this low-spec Lenovo IdeaPad 110-15IRB My mom recently bought a new laptop it came with windows 10 and runs like S***. I think it's probably because of windows 10 and all the bloatware shipped with the pc. (really it's packed)
Here are the specs
Intel Celeron n3060
2gb of ram
500gb hdd
I'm hoping to get Ubuntu up an running on it, but wondering if Fedora or Elementary OS might be a better option. Anyway will Linux run well on here? And if so which flavor would you suggest?

A: Ubuntu will definitely run better than windows on your machine. However, I've had issues with it being slow on my old netbook with 1gb of ram, but 2gb should be fine!
If you install Ubuntu and it does run a little slow, you can always find a more light weight flavor (version) of Ubuntu.


text:
Q: How to save the user registration date [rails] When I save an user through a registration, I want to save the day in which this registration is made. I've tried using Date.today, but it doesn't work.
What's the best solution?

A: Time.now should work. Also, if your model has timestamps you could use the created_at attribute.
To convert a datetime to a date you can use Time.now.to_date or created_at.to_date. Depends on what you end up using.

A: I highly recommend that you use devise.  You'll get created_at and updated_at fields built-in to a user model, which will automatically track the user registration date and most recent change date, respectively.
A single line in your user model will insert devise-based authentication and get you a lot of features with little or no programming effort on your part:
devise :database_authenticatable, :registerable, :confirmable, :recoverable


text:
Q: pushing to a multi-dimensional array in foreach using preg-match I am having some difficulties constructing a multi dimensional array using preg_match.
I am trying to break a paragraph down into sentences.
then for each section/ sentences of the paragraph, I'd like to break down every words and punctuation points into another level of the array.
@Toto yesterday helped me with preg-match to explode the string whilst retaining the punctuation points as elements.
However, I have been struggling to then construct the array I want.
Consider a paragraph like this:
First section. This section, and this. How about this section? And a section; split in two.

Desired Output
And in return for the results to look like this:
Array ( [0] =>
     Array ( [0] => First [1] => section [2] => . )
Array ( [1] =>
     Array ( [0] => This [1] => section [2] => , [3] => and [4] => this [2] => . )
Array ( [2] =>
     Array ( [0] => How [1] => about [2] => this [3] => section [4] => ? )
Array ( [3] =>
     Array ( [0] => And [1] => a [2] => section [3] => ; [4] => split
     [5] => in [6] => two [7] => . )
)))

My code so far/ what I have tried
It does not work. I am not quite sure how I would go about deleting the content of $s once I have constructed the second dimension but right now I am more puzzled by the array duplicating every sections and adding them to Array [0]??
$m = '    First section. This section, and this. How about this section? And a section; split in two.'

$s = preg_split('/\s*[!?.]\s*/u', $m, -1, PREG_SPLIT_NO_EMPTY);

foreach ($s as $x => $var) {
    preg_match_all('/(\w+|[.;?!,:]+)/', $var, $a);
    array_push($s, $a);
}

print_r($s);

A: You were almost near, I just added PREG_SPLIT_DELIM_CAPTURE and changed the regex for preg_split. So you can use in this way:
$str = 'First section. This section, and this. How about this section? And a section; split in two.';

$matchDelim = preg_split("/([^.?!]+[.?!]+)/", $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

$finalArr = [];

foreach ($matchDelim as $match) {
    preg_match_all('/(\w+|[.;?!,:])/', $match, $matches);
    $finalArr[] = $matches[0];
}

print_r($finalArr);

Result:
Array
(
    [0] => Array
        (
            [0] => First
            [1] => section
            [2] => .
        )

    [1] => Array
        (
            [0] => This
            [1] => section
            [2] => ,
            [3] => and
            [4] => this
            [5] => .
        )

    [2] => Array
        (
            [0] => How
            [1] => about
            [2] => this
            [3] => section
            [4] => ?
        )

    [3] => Array
        (
            [0] => And
            [1] => a
            [2] => section
            [3] => ;
            [4] => split
            [5] => in
            [6] => two
            [7] => .
        )

)


text:
Q: What is an openFileDescriptor mode? Why are there fileDescriptor modes (r,w,rw) and what are they for?
   contentResolver.openFileDescriptor(uri, "w")

They are described in the documention like this:

If opening with the exclusive "r" or "w" modes, the returned ParcelFileDescriptor could be a pipe or socket pair to enable streaming of data. Opening with the "rw" mode implies a file on disk that supports seeking. If possible, always use an exclusive mode to give the underlying ContentProvider the most flexibility.

A: These are nothing but modes in which you can open file descriptor.

*

*"r" Read only mode. cannot be used for writing

*"w" Write only mode. cannot be used for reading.

*"rw" for read-and-write.

*"rwt" for truncating or overwriting existing file contents.


text:
Q: sessionFactory returns null I am trying to do batch insert with GORM and I try to clear session after every 50 insert. and I try this for get sessionFactory
def sessionFactory

but when I try to use sessionFactory.currentSession it returns Null Pointer Exception because sessionFactory is null. Do u know why is that?

A: i believe Burt's reply on a similar question will help you with this.
by the way, you can subscribe to grails turkey group :)


text:
Q: Newsletter ads are misformatted in iPad Safari A screenshot for your consideration:

This is in Safari on an iPad running iOS 10.3. It's happening on all sites I've visited so far to spot-check, including some beta SE sites and some SE sites with their own designs.


text:
Q: If $0 \leq A \leq B$, can I conclude that $(A \otimes I) \leq (B \otimes I)$? Let $A \in \mathbb{R}^{n \times n}, B\in \mathbb{R}^{n \times n}$ are two positive semi-definite matrices and $A \leq B$ means $B - A$ is positive semi-definite. Also let $I \in \mathbb{R}^{m \times m}$ be the identity matrix. And $\otimes$ denotes the Kronecker product of matrix.
If $0 \leq A \leq B$, can I conclude that $(A \otimes I) \leq (B \otimes I)$?

A: Let $A \geq 0$. It is enough to show that
$$
  A \otimes 1_{\mathbb{R}^{m \times m}} \geq 0.
$$
The following two approaches are based on https://math.stackexchange.com/q/1316606, where it has been shown that, for $B \in \mathbb{R}^{n \times n}$, we can identify $B \otimes 1_{\mathbb{R}^{m \times m}}$ with the $m \times m$ diagonal matrix with $B$ on the diagonal, which will be denoted by $\tilde{B}$.

*

*Let $v \in (\mathbb{R}^{n})^{m}$. Then we have
$$
  \langle \tilde{A} v, v\rangle = \langle \begin{pmatrix} Av_{1}\\ \vdots \\ Av_{m}\end{pmatrix}, v\rangle = \sum_{i=1}^{m} \langle A v_{i}, v_{i}\rangle \geq 0,
$$
since $A \geq 0$. Hence, $\tilde{A} \geq 0$ and therefore also $A \otimes 1_{\mathbb{R}^{m \times m}} \geq 0$.

*We also can use the fact that
$$
  \det(B \otimes 1_{\mathbb{R}^{m \times m}}) = \det(\tilde{B}) = \det(B)^{m}
$$
for all $B \in \mathbb{R}^{n \times n}$. With
$$
  \det(B \otimes 1_{\mathbb{R}^{m \times m}} - \lambda (1_{\mathbb{R}^{n \times n}} \otimes 1_{\mathbb{R}^{m \times m}})) = \det(\tilde{B} - \lambda 1_{(\mathbb{R}^{n \times n})^{m \times m}}) = \det(B-\lambda 1_{\mathbb{R}^{n \times n}})^{m}
$$
for all $B \in \mathbb{R}^{n \times n}$ and $\lambda \in \mathbb{C}$ we see that $A \otimes 1_{\mathbb{R}^{m \times m}}$ and $A$ have the same eigenvalues. Hence, $A \otimes 1_{\mathbb{R}^{m \times m}}$ is positive. (Here we used the fact that a matrix is positive semidefinit if and only if all eigenvalues are non-negative.)


text:
Q: How to loop through a text file in append mode I have a text file called 'file.txt' that I want to loop through and remove any line that contains the word 'test'
so I opened the file in 'append' mode:
h = open('file.txt', 'a+')
for l in h:
    print('something') #to check if loop works
    if 'test' in l:
        h.write(l)

But nothing happens and if I try opening it in 'read' mode, i get an error
io.UnsupportedOperation: not writeable
On line 5


text:
Q: How can we display an image (offline) as an action from QR Code scanning? QS- I am an unable to create an QR CODE which will display an image as a result of QR code scanning (Without Internet or external link). I am able to  to create link,show business card,call a phone number etc as result of QR code in PHP or android. Is it possible show an image directly ?

A: If you write your own client scanner; that would be possible by base64-encoding the image and decode it in the client.
If you rely on third party scanners; I don't know if there's a standard for it but I haven't seen it before.


text:
Q: SSH ask password once, reuse password until timeout finishes How can I solve this problem?
I have a bash script (under Ubuntu Server), doing several SSH connections, executes some remote transfers, like rsync multiple times.
My problem is, that I would like to avoid entering password multiple times.
But I don't want to use SSH public key exchange, because if anybody has the key, will be able to connect the remote computer.
I would like the following:

*

*SSH should ask password when I start the bash script

*reuse password, so don't ask password again until timeout

*when timeout is over, ask password again.

Something similar, how sudo is working, just with ssh.
Any idea how to solve this?
EDIT1:
I found a new SSH feature named ssh multiplexing. Maybe using this I can reach the goal I want.
https://unix.stackexchange.com/questions/50508/reusing-ssh-session-for-repeated-rsync-commands
Would this work?

A: (Reposting my comment as an answer per request from klor).
It's not what you want to hear, but this is what key-based authentication is for. So long as you put a passphrase on your private key, it's no less secure than password authentication.
You can use ssh-agent to avoid needing to enter the passphrase every time, and the -t option to ssh-agent will give you the timeout behavior you're after.
# start a shell under ssh-agent with a 5-minute timeout for keys loaded with ssh-add
ssh-agent -t 300 /bin/bash

# add your key(s) to the agent; ssh-add will prompt for passphrase, if one is set
ssh-add

# do some stuff
ssh remote.server cat /some/file
rsync file1 file2 klor@remote.server:/some/directory

# after 300 seconds, timeout reached, run ssh-add again to re-add your keys
ssh-add

Your script will need some logic to determine when the timeout occurs. One way would be to run ssh and rsync with -o BatchMode=yes, which will prevent interactive authentication methods, so if the key is no longer usable, ssh will exit instead of prompting for a password. You can use the exit code to determine if you need to run ssh-add again; $? should be set to 255 in this case.
You'll still need to work out how to feed the passphrase to ssh-add, because it doesn't provide a way to accept it programmatically. Unless your script will prompt you to enter it by hand, you'll probably need to use expect for that part, and that will mean hard-coding the passphrase somewhere.

A: It seems I found the perfect solution for my needs:
Reusing ssh session for repeated rsync commands
#!/bin/bash

# Create ssh-mux (SSH multiplex) dir only if not exists
[[ ! -d dir ]] || mkdir ~/.ssh/ssh-mux

apache_site_path_source="/var/www/source_site"
apache_site_path_target="/var/www/target_site"

# Solution: Start SSH multiplexing session (works fine)
# https://unix.stackexchange.com/questions/50508/reusing-ssh-session-for-repeated-rsync-commands
sudo ssh -nNf -o ControlMaster=yes -o ControlPath="~/.ssh/ssh-mux/%L-%r@%h:%p" root@192.168.0.1

sudo rsync -av --progress -e 'ssh -l root -p 22 -o "ControlPath=~/.ssh/ssh-mux/%L-%r@%h:%p"' 192.168.0.1:${apache_site_path_source}/. ${apache_site_path_target}/;
printf "\n\n\n\n\n\n"
sudo rsync -av --progress -e 'ssh -l root -p 22 -o "ControlPath=~/.ssh/ssh-mux/%L-%r@%h:%p"' 192.168.0.1:${apache_site_path_source}/. ${apache_site_path_target}/;
printf "\n\n\n\n\n\n"
sudo rsync -av --progress -e 'ssh -l root -p 22 -o "ControlPath=~/.ssh/ssh-mux/%L-%r@%h:%p"' 192.168.0.1:${apache_site_path_source}/. ${apache_site_path_target}/;
printf "\n\n\n\n\n\n"

# Finish SSH multiplexing session
sudo ssh -O exit -o ControlPath="~/.ssh/ssh-mux/%L-%r@%h:%p" root@192.168.0.1

This solution asks password only once, then doing rsync 3 times without asking password again. Each rsync reuses the SSH connection using SSH multiplexing.
Could be possible to change the SSH config, and store the SSH multiplexing settings, but using this solution there is no need to change the server config, the script works as is.

A: If you're using a keyfile, you can use the AddKeyToAgent option (OpenSSH>=7.2).

ssh(1): Add an AddKeysToAgent client option which can be set to 'yes', 'no', 'ask', or 'confirm', and defaults to 'no'.  When enabled, a private key that is used during authentication will be added to ssh-agent if it is running (with confirmation enabled if set to 'confirm').

So your script might look like this.
# make sure the ssh agent is running (may not be necessary on some systems)
eval "$(ssh-agent -s)"

# ssh commands.  only the first command needs AddKeysToAgent option
ssh -o AddKeysToAgent=yes user@host "echo hello"
ssh user@host "echo world"
...

A: Implementation of James Sneeringer's comment as a profile script.
# This script must be sourced to be useful. For example, if you name this script
# ~/.bash_autossh, at the end of .bashrc, source $HOME/.bash_autossh
# Tested in bash & zsh
# MIT license, if you need a license.

# An absolute path to a private key:
AUTOLOADSSHID=$HOME/.ssh/id_ecdsa
# Timeout is in seconds, optional:
SSHID_TIMEOUT=60

auto_init_ssh_agent() {
  if [ "${SSH_AGENT_PID}x" = "x" ] || \
     [ "${SSH_AUTH_SOCK}x" = "x" ] || \
     ps -p "${SSH_AGENT_PID}" >& /dev/null || \
     [ ! -e "${SSH_AUTH_SOCK}" ]; then
    # There are problems with the agent, initialize a new agent.
    # Agents started this way should be manually stopped with ssh-agent -k
    source <(ssh-agent -s)
  fi
  if ! ssh-add -l | grep "${AUTOLOADSSHID}" >/dev/null; then
    # The autoload key is not present, try to load it.
    SSH_ADDTL_ARGS=()
    if [ "${SSHID_TIMEOUT}x" != "x" ]; then
      SSH_ADDTL_ARGS+=( -t "${SSHID_TIMEOUT}" )
    fi
    # This may ask for a password, as appropriate
    ssh-add "${SSH_ADDTL_ARGS[@]}" "${AUTOLOADSSHID}"
    unset SSH_ADDTL_ARGS
  fi
}

_autossh() {
  args=( "$@" )
  auto_init_ssh_agent
  ssh "${args[@]}"
}

alias autossh=_autossh

Then you can run the command autossh myserver and it will auto-initialize an agent if one isn't available.  The alias is to prevent accidentally calling an interactive function from a script.
Problematically, on systems that don't automatically start an agent with the WM session, this may litter your machine with ssh-agent processes, you may need to ssh-agent -k to end it, or killall ssh-agent. Some additional scripting may be required if you want to share a single ssh-agent across an entire login session or across multiple process sessions.

A: I'd normally tell you to try expect, but in this case I think it's beter to use sshpass, it is very easy to install and to use, here I post some use cases
sshpass -p<pass> ssh <args>
sshpass -pfoobar ssh -o StrictHostKeyChecking=no user@host command_to_run
have fun :)
EDIT 1
on a script
#!/bin/bash
read -p "give me the password" pass
sshpass -p"$pass" ssh -o StrictHostKeyChecking=no user@host command_to_run


text:
Q: How can combine this two tables and create a new table? How to combine two tables and create a new table
first table :
ExitDate      |   fullname     | outputnumber
------------------------------------------------
2012/01/01         a              10
2012/01/06         b              2
2012/01/08         c              3
2012/01/12         d              4

second table
inputnumber   |   date
-------------------------------
  100              2012/01/05
  150              2012/01/07
  200              2012/01/10

the answer table
ExitDate      |   fullname     | outputnumber    |   inputnumber   |   date

-------------------------------------------------------------------------------
2012/01/01         a              10                      -             -
     -             -              -                       100          2012/01/05
2012/01/06         b              2                       -               -
      -            -              -                       150          2012/01/07
2012/01/08         c              3                       -             -
    -              -              -                       200         2012/01/10
2012/01/12         d              4                       -             -

note : the date and location is important  and i using sql server

A: If I correctly understand, you need union all. Something like this  :
select * from (
    select ExitDate, fullname, outputnumber, NUll as inputnumber, NUll as [date] from first_table
    union all
    select NUll as ExitDate, NUll as fullname, NUll as outputnumber, inputnumber, [date] from second_table
) t
order by coalesce(ExitDate, [date])

Then entire result is sorted by combined dates from ExitDate and  date columns
rextester demo

A: I think you can have a better table like this:
select *
from (
    select fullname, 0 as io, outputnumber as number, ExitDate as date
    from table1
    union all
    select '-', 1, inputnumber, date) t
order by date, io;

fullname | io | number | date
---------+----+--------+-------------
a        | 0  | 10     | 2012/01/01
-        | 1  | 100    | 2012/01/05
b        | 0  | 2      | 2012/01/06
-        | 1  | 150    | 2012/01/07
c        | 0  | 3      | 2012/01/08
-        | 1  | 200    | 2012/01/10
d        | 0  | 4      | 2012/01/12

A: You can get the exact output you want using full outer join:
select t1.*, t2.*
from t1 full outer join
     t2
     on 1 = 0
order by coalesce(t1.exitdate, t2.date);


text:
Q: OpenCV C++ Keypoints and descriptors transform with homography of warped images I have created a stitching program that can stitch any number of images together into a single mosaic. The efficiency of the program needs work which I am trying to improve. My goal is to create a list of the already found keypoints and descriptors so the program doesn't need to re do work it has already done and this way memory isn't overloaded if there are too many images. To do this I need to have the keypoints and descriptors transformed along side the actual images themselves. Here is the code I camp up with ( I think i am getting mixed up with warpPerspective() and perspectiveTransform()) .
std::tuple<Mat, std::vector<KeyPoint>, Mat>  stitchMatches(Mat image1,Mat image2, Mat homography, std::vector<KeyPoint> kp1, std::vector<KeyPoint> kp2 , Mat desc1, Mat desc2){
    Mat result, destination, descriptors_updated;
    vector<Point2f> fourPoint;
    std::vector<KeyPoint> kp1New, kp2New, keypoints_updated;

    //-Get the four corners of the first image (master)
    fourPoint.push_back(Point2f (0,0));
    fourPoint.push_back(Point2f (image1.size().width,0));
    fourPoint.push_back(Point2f (0, image1.size().height));
    fourPoint.push_back(Point2f (image1.size().width, image1.size().height));
    perspectiveTransform(Mat(fourPoint), destination, homography);

    //- Get points used to determine Htr
    double min_x, min_y, tam_x, tam_y;
    float min_x1, min_x2, min_y1, min_y2, max_x1, max_x2, max_y1, max_y2;
    min_x1 = min(fourPoint.at(0).x, fourPoint.at(1).x);
    min_x2 = min(fourPoint.at(2).x, fourPoint.at(3).x);
    min_y1 = min(fourPoint.at(0).y, fourPoint.at(1).y);
    min_y2 = min(fourPoint.at(2).y, fourPoint.at(3).y);
    max_x1 = max(fourPoint.at(0).x, fourPoint.at(1).x);
    max_x2 = max(fourPoint.at(2).x, fourPoint.at(3).x);
    max_y1 = max(fourPoint.at(0).y, fourPoint.at(1).y);
    max_y2 = max(fourPoint.at(2).y, fourPoint.at(3).y);
    min_x = min(min_x1, min_x2);
    min_y = min(min_y1, min_y2);
    tam_x = max(max_x1, max_x2);
    tam_y = max(max_y1, max_y2);

    //- Htr use to map image one to result in line with the alredy warped image 1
    Mat Htr = Mat::eye(3,3,CV_64F);
    if (min_x < 0){
        tam_x = image2.size().width - min_x;
        Htr.at<double>(0,2)= -min_x;
    }
    if (min_y < 0){
        tam_y = image2.size().height - min_y;
        Htr.at<double>(1,2)= -min_y;
    }

    result = Mat(Size(tam_x*2,tam_y*2), CV_8UC3,cv::Scalar(0,0,0));
    warpPerspective(image2, result, Htr, result.size(), INTER_LINEAR, BORDER_TRANSPARENT,   0);
    warpPerspective(image1, result, (Htr*homography), result.size(), INTER_LINEAR, BORDER_TRANSPARENT,0);

    // transform perspective of keypoints and descriptros of kp1 and desc1
    perspectiveTransform(kp2, kp2New, (Htr));
    perspectiveTransform(kp1, kp1New, (Htr*homography));
    perspectiveTransform(desc2, desc2, (Htr));
    perspectiveTransform(desc1, desc1, (Htr*homography));

    //create new vector of keypoints containing the thranformed kp1 and kp2
    keypoints_updated.reserve(kp1New.size() + kp2New.size());
    keypoints_updated.insert(keypoints_updated.end(), kp1New.begin(), kp1New.end());
    keypoints_updated.insert(keypoints_updated.end(), kp2New.begin(), kp2New.end());

    //create a new Mat including the descriports from desc1 and desc2
    descriptors_updated.push_back(desc1);
    descriptors_updated.push_back(desc2);

    //------------TEST TO see if keypoints have moved

    Mat img_keypoints;
    drawKeypoints( result, keypoints_updated, img_keypoints, Scalar::all(-1), DrawMatchesFlags::DEFAULT );

    imshow("Keypoints 1", img_keypoints );
    waitKey();
    destroyAllWindows();

    return {result, keypoints_updated, descriptors_updated};
}


text:
Q: Stop screen tearing with JavaFX AnimationTimer In JavaFX, it seems appropriate to me to use AnimationTimer for frequently updating Canvas Nodes; that is, for rasterized animations instead of vector animations. I'm running into an issue, which may be VSync related. I have a singular Canvas on my Scene which contains 2D data that changes frequently (the rest of the program is done with Nodes). I tend to get a tearing down the middle of the screen when I do this, which implies that the AnimationTimer may be falling out of sync with the monitor refresh rate.
This (simplified) code shows the error in detail. Note that I have no idea whether it's display hardware dependent, and the exact position of the tear may shift slightly.
import javafx.application.*;
import javafx.animation.*;
import javafx.scene.*;
import javafx.scene.canvas.*;
import javafx.stage.*;
import javafx.event.*;
import javafx.scene.input.*;
import javafx.scene.paint.*;

public class BugDemo extends Application {

    public static void main(String...args) {
        launch(args);
    }

    private Canvas background = new Canvas();
    private Color bgColor = Color.rgb(0, 0, 0);

    @Override
    public void start(Stage primaryStage) throws Exception {
        Group root = new Group();

        startLoops(root);
        Scene scene = new Scene(root);

        initUserControls(scene);
        background.widthProperty().bind(scene.widthProperty());
        background.heightProperty().bind(scene.heightProperty());
        root.getChildren().add(background);

        primaryStage.setScene(scene);

        primaryStage.setTitle("Bug Demo");

        primaryStage.setMaximized(true);
        primaryStage.show();
    }

    /**
     * Initializes all running control managers for game field
     * @param scene primary scene of game
     */
    protected void initUserControls(Scene scene) {
        EventHandler<MouseEvent> handler = new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {
                bgColor = Color.rgb((int)((event.getX() / background.getWidth()) * 255),
                        (int)((event.getY() / background.getHeight()) * 255),
                        255);
            }};
        scene.getRoot().setOnMouseMoved(handler);
        scene.getRoot().setOnMouseDragged(handler);
    }

    /**
     * Starts all game loops, which will at the beginning of the simulation and often for the extent
     * of it.
     * @param parent Root node
     */
    protected void startLoops(Parent parent) {
        GraphicsContext gc = background.getGraphicsContext2D();

        new AnimationTimer() {

            @Override
            public void handle(long now) {
                drawBackground(gc);
            }}.start();
    }

    protected void drawBackground(GraphicsContext gc) {
        gc.setFill(bgColor);
        gc.fillRect(0, 0, background.getWidth(), background.getHeight());
    }

}

Moving the mouse cursor over the scene will cause the canvas to shift in background color. As you move the mouse, you will notice (presumably) a tearing in the frame.
It is quite possible that I'm simply being a N00B at JavaFX, and there's a perfectly friendly .sync()-ish method I'm supposed to call somewhere; but I haven't found it yet. I've found bugs submitted to Oracle that look similar to this. My answer may simply be dodging using Canvas and AnimationTimer for animations. All the same, even if there isn't a solution at this time, if someone has a workaround, I would love to hear about it!
Thanks!

A: Found the issue (thank you to @VGR for pointing out the lack of system behavioral congruity)! Seems that it wasn't Java at all; it was Marco. I switched Desktop Windowing Managers, to Compiz specifically; and the tearing is now gone.
Evidently this isn't a bug in Java at all; it's a trade-off for using Marco. This is a relief!


text:
Q: Is Xubuntu as power-efficient as Ubuntu? I'm wondering if Xubuntu has the same features as Ubuntu 12.04
Particularly I'm trying to get the most battery life out of my laptop. Does Xubuntu 12.04 feature the same improvements to power management that come default in Ubuntu 12.04?
In general, is the difference between Xubuntu and Ubuntu simply the DE? Is all the underlying improvements available in both distros?

A: Xubuntu uses the same kernel as Ubuntu, as well as the same low-level power management utilities (hdparm, etc.), so yes, it has the same power management capabilities as Ubuntu.
But, Xubuntu may be more power-efficient than Ubuntu on your laptop, primarily because it's a "lightweight" desktop environment; it places somewhat less load on both your CPU and GPU compared to Ubuntu (Unity 3D). Whether it saves power over Ubuntu (and how much) depends on your specific hardware and use patterns.


text:
Q: Создать массив дженериков public abstract class CarFactory <T extends Car> {
T[] allCars;

CarFactory(int arraySize){
    this.allCars =  new T[arraySize];
}

abstract T getCar(String model, int yearOfIssue, String color, double price, String registrationNumber);

}
IDE ругается на строку (на тип Т)
this.allCars =  new T[arraySize];
Подскажите, как исправить ситуацию.

A: Думаю как то так
public abstract class CarFactory <T extends Car> {
 List<T> allCars;

 CarFactory(int arraySize){
    this.allCars =  new ArrayList<T>(arraySize);
 }

 abstract T getCar(String model, int yearOfIssue, String color, double price, String registrationNumber);
}

В основе ArrayList лежит array. Можете посмотреть исходники ArrayList и посмотреть реализацию данного класса. Может и найдете подсказки для вашей исходной задачи.


text:
Q: How to get data from nested JSON? Here's my code:
public class Parser {
private static final String PATH = "try.json";

public static void main(String[] args) throws IOException, ParseException {

    String req = FileUtils.readFileToString(new File(PATH), StandardCharsets.UTF_8);

    Bean data = new Gson().fromJson(req, Bean.class);

public class Bean{
    private List<Data> data;

    public List<Data> getData() {
        return data;
    }

public class Data {

    private List<String> urls;
    private String name;
    private String type;
    private String picture;

    public List<String> getUrls() {
        return urls;
    }

    public String getName() {
        return name;
    }

    public String getType() {
        return type;
    }

    public String getPicture() {
        return picture;
    }

}

Here's dummy-JSON:
{
    "data": [
      {
            "urls": [
            "https://google.com",
            "https://googl.com"
            ],
            "name": "Google",
            "type": "corp",
            "picture": "https://google.img"
      },
      {
            "urls": [
            "https://yandex.ru"
            ],
            "name": "Yandex",
            "type": "corp",
            "picture": "https://yandex.jpg"
      }
    ]
}

So main mission here - create the individual objects from json with "name" field and "urls" ArrayList in them, so then I'll add them in another list and get the info by index.
But I just can't understand, how can I make that. Response, for example, for first object probably should looks like that:
Google
"https://google.com",
"https://googl.com"

A: Well if the use of GSON is not mandatory for you, you could use Jackson.
With the use of @JsonProperty annotation, you could get the nested fields, you coudl also add some aliases with @JsonAlias if needed.
Here is a short example:
    import com.fasterxml.jackson.annotation.JsonProperty;

    public class Data {

    private List<String> urls;
    private String name;
    private String type;
    private String picture;

    public List<String> getUrls() {
        return urls;
    }

    public String getName() {
        return name;
    }

    public String getType() {
        return type;
    }

    public String getPicture() {
        return picture;
    }

}
    @JsonProperty("ParentObject") //Here it looks like the parent object is an element of the array Data, so i would treat you Json object as a list of objects and iterate over each.
    private void getFieldNestedValues(Map<String, String> field) {
        urls = field.get("nestedField1"); //nestedField1 would be urls in your case
        name = field.get("nestedField2"); // nestedField2 could be the name for instance
    }

I'm pretty sure you could do the same with Gson, hope this sample gives you an idea, of how you could make it work.
EDIT: Forgot to mention that I would use an ObjectMapper from the Jackson library, to parse and build the object:
 JsonNode rootNode = objectMapperProvider.buildSureObjectMapper().readTree(jsonBody);

 YourObject yourObject= objectMapperProvider.buildSureObjectMapper().readValue(rootNode.toString(), YourObject.class);

With a custom ObjectMapper for instance:
 public ObjectMapper buildSureObjectMapper() {
    return new ObjectMapper()
            .registerModule(new ParameterNamesModule())
            .registerModule(new Jdk8Module())
            .registerModule(new JavaTimeModule())
            .registerModule(new GuavaModule())
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
            .setSerializationInclusion(NON_ABSENT);
}

A: If I understood correctly, you want a loop
 Bean data = new Gson().fromJson(req, Bean.class);
 for (Data d : data.getData()) {
   System.out.println(d.getName());
   for (String u : d.getUrls()) {
     System.out.println(u);
   }
 }

Otherwise, you can already access things by index
Data first = data.getData().get(0);
System.out.println(first.getName()); // google


text:
Q: i want to count firestore collections that have a same field value and count them in a table? i have a list of users in the firestore
each user have his own Country
i want to count the number of users that have a same country and list them in a table like this
for example i have 3 users have Tunisia as a country, 1 user have Germany,

Country Name
Total users

Tunisia
3

Germany
1

my flutter code:
child: Container(
      width: double.infinity,
      height: 500,
      decoration: BoxDecoration(),
      child: DataTable(
        columns: [
          DataColumn(label: Text(
              'Country',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
          )),
          DataColumn(label: Text(
              'Total',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
          )),
        ],
        rows: [
          DataRow(cells: [
            DataCell(Text('Stephen')),
            DataCell(Text('Actor')),
          ]),
          DataRow(cells: [
            DataCell(Text('John')),
            DataCell(Text('Student')),
          ]),
        ],
      ),
    ),


text:
Q: Drupal node_type_get_type() and hook_uninstall() I have a module job_post which installs job_post content type.
In this module I have hook_unistall() which calls for node_type_delete() function which removes my content type.
After unistalling process I have errors from Drupal's core module comment which fires from node_type_delete() after module_invoke_all('node_type_delete', $info).
Error is the following and repeats 8 times (because of the loop in comment_node_type_delete()):
Notice: Trying to get property of non-object in comment_node_type_delete()
(line 343 of ....\comment.module).

I have this error because $info variable in node_type_delete() function is false.
My question is, why when my module is installed and when I'm printing var_dump(node_type_get_type('job_post')) on any page, I have an object, but when I'm trying to print the same code in my unistall function I get false and this error?
job_post.install
/**
 * Implements hook_install().
 */
function job_post_install() {
  node_types_rebuild();

  $types = node_type_get_types();
  node_add_body_field($types['job_post']);

  $body_instance = field_info_instance('node', 'body', 'job_post');
  $body_instance['type'] = 'text_summary_or_trimmed';

  field_update_instance($body_instance);
}

/**
 * Implements hook_uninstall().
 */
function job_post_uninstall() {
  $instances = field_info_instances('node', 'job_post');
  foreach ($instances as $instance_name => $instance) {
    field_delete_instance($instance);
  }

  // Force rebuild of the node type cache
  // as Clive suggested didn't help
  // _node_types_build(TRUE);

  node_type_delete('job_post');

  field_purge_batch(1000);
}

job_post.module
/**
 * Implements hook_node_info() to provide our job_post type.
 */
function job_post_node_info() {
  return array(
    'job_post' => array(
      'name' => t('Job Post'),
      'base' => 'job_post',
      'description' => t('Use this content type to post a job.'),
      'has_title' => TRUE,
      'title_label' => t('Job Title'),
      'help' => t('Enter the job title and job description')
    )
  );
}

/**
 * Implement hook_form() with the standard default form.
 */
function job_post_form($node, $form_state) {
  return node_content_form($node, $form_state);
}

Note: This module example was taken from Pro Drupal 7 Development book (page 141) with minor changes and it was given errors even with original.

A: Hi by referring to documentation an core modules of Drupal 7. There is a usage problem.
hook_node_info defines a content type automatically. The content types which are created in this way, uninstalled-disable automatically.
Core blog module defines hook_node_info but does not operate any node_type_delete on hook_uninstall
http://api.drupal.org/api/drupal/modules%21blog%21blog.module/function/blog_node_info/7
When you call node_type_delete('job_post');  on hook_uninstall, node type info has already gone. Because of that comments module raises error.
Normally you should only remove any data related to your content type. And let the rest to be done by core.
Additionally if you really want create/delete your content type, you may not use hook_node_info. You can manually create/delete content type on install/uninstall hook.
Sample uninstall here:
http://public-action.org/content/drupal-7-field-api-drupal-7-adding-custom-content-type-custom-fields-field-api

A: It seems like the node type cache hasn't been built fully for some reason, try forcing the rebuild before you call node_type_delete() and all node types should be made available:
// Force rebuild of the node type cache
_node_types_build(TRUE);

// Delete our content type
node_type_delete('job_post');


text:
Q: jQuery center specific table columns I have a host of legacy code that I need to adapt but don't have the time to fully modify.
Is it possible to have jQuery 'center' the contents of a table column if they don't have an id, name or class.

Text	Col2	Col3

Text	Col2	Col3

Text	Col2	Col3

What I was wondering was if it were possible to center the contents of the 2nd and 3rd columns, parent/ child for example but I'm not sure if it is possible.
I could go and recode all the tables (which are hard coded on the .php page) but that would take hours!

A: Try this:
$('tr').each(function() {
  var tds = $(this).find('td');
  var len = tds.length;
  for (var i = 1; i < len; i++) {
    $(tds[i]).css('text-align', 'center');
  }
});

A: how about:
var row = 1;//row number
var column = 1;//column number
$('table tr:nth-child(' + row + ') td:nth-child(' + column + ')').css('text-align', 'center');


text:
Q: How to use tesseract in heroku? I wanna know how to use pytesseract in Heroku, I installed using pip install but when, I put path it gives error. I tried using Build packs too but I can't get path. please help me.

A: Option 1: with build packs
The build pack executables are in the $INSTALL_DIR directory.
Take a look at this question Heroku buildpacks - installing executables that are used by Python packages to customize your path in a build pack (just clone the build pack git and change your PATH).
Option 2: With custom docker image
Another option is to build your own docker image with based in the official python docker image (ie python:3.8-buster) and install tesseract.
You can use this dockerfile:
FROM python:3.8-buster

RUN apt-get update && apt-get install -y software-properties-common && add-apt-repository -y ppa:alex-p/tesseract-ocr
RUN apt-get update && apt-get install -y tesseract-ocr-all

RUN mkdir /home/work
WORKDIR /home/work

Once you have this docker image, you can push it to heroku private docker registry and use it to run your dynos.


text:
Q: Downloads, Documents, Pictures Folders gone missing When I try to open Documents or Pictures folders I get the below error message.

Unable to find the requested file. Please check the spelling and try again.

Following is the output of cat .config/user-dirs.dirs
> XDG_DESKTOP_DIR="$HOME/"
> XDG_DOWNLOAD_DIR="$HOME/"
> XDG_TEMPLATES_DIR="$HOME/Templates"
> XDG_PUBLICSHARE_DIR="$HOME/"
> XDG_DOCUMENTS_DIR="$HOME/"
> XDG_MUSIC_DIR="$HOME/"
> XDG_PICTURES_DIR="$HOME/"
> XDG_VIDEOS_DIR="$HOME/Videos"

read few suggestions on creating new folders and linking them through config but I don't understand whether those steps can restore the data. Please suggest if there is any way to bring back those folders and data.
EDIT: Output of ls $HOME
> Dropbox  'Screenshot from 2018-09-08 12-30-11.png'   soq.png
> Videos  NewDocuments  'Screenshot from 2018-09-08 12-31-57.png'
> Templates  rtlwifi_new    snap
> Testproj


text:
Q: How to open the modal popup using a link, instead of button with passing id to retrieve data How do I pop open the modal using a link, instead of a button? I don't want the action to be a button, I want it to be a  href link, The code is provided below. Buttons suck, links rule.
As of right now, I have the code as a button to open the modal, I have two tables, the first one is services category and the second one is services, when I select services category i want to open modal and view the services that have the same category. I just want to open the modal using a regular link that I have for my main menu, so as you can see, I don't want to put a button in the main menu, because the main menu has links that are styled for the menu.
<?php
        $query = "SELECT  * FROM services_categories
        ORDER BY `services_categories`.`services_category_id` Desc ";
        $count=$dbo->prepare($query);
        $count->execute();
        $no=$count->rowCount();
        if($no > 0 ){
            echo "

Service Name
";
            foreach ($dbo->query($query) as $row){
            echo "
$row[services_category_id]	$row[services_category_name]
                     <input type='button' name='view' value='view' id=' $row[services_category_id]' class='btn btn-info btn-xs view_data' />

";
                }
            echo "
";
            }else {
            echo " No records found ";
                }
         ?>

<button type="button" class="close" data-dismiss="modal">×
</button>

Service

<button type="button" class=""
data-dismiss="modal">Close</button>

<?php include("db_connect.php"); header('Content-Type:text/html;
charset=utf-8');
if(isset($_POST["services_category_id"]))
{
 $output = '';
 $query = "SELECT  * FROM services  left JOIN services_categories
 ON (services.services_category_id =
 services_categories.services_category_id)
 WHERE services.services_category_id
 ='".$_POST["services_category_id"]."'";
 $result = mysqli_query($conn, $query);

 $count=$dbo->prepare($query);
        $count->execute();
        $no=$count->rowCount();
        if($no > 0 ){
            echo "

                  services

";
            foreach ($dbo->query($query) as $row){
            echo "
$row[service_name]

";
                }
            echo "
";
            }else {
            echo " No records found ";
                }
 }
 ?>

A: The modal opens when any element with the view_data class is clicked.
If I understood you correctly all you would need to do is replace:
<input type='button' name='view' value='view' id=' $row[services_category_id]' class='btn btn-info btn-xs view_data' />

With:
Whatever text you want


text:
Q: how to close a running thread after a new one was created I am trying to create a price ticker which refreshes every 2 seconds.
how to cancel the previous thread after a new one was created (a new one is created after the run_worker() was called)
I was trying to access somehow the self._flag from outside to close the thread, but how to access the currently running one and close it ?
def run_worker(self):
    print("run_worker")
    symbol = str(self.ui.pair_combo.currentText())
    worker = Worker(self.execute_this_fn, symbol)
    worker.signals.result.connect(self.print_output)
    worker.signals.finished.connect(self.thread_complete)
    self.threadpool.start(worker)

class WorkerSignals(QObject):
    finished = pyqtSignal()
    error = pyqtSignal(tuple)
    result = pyqtSignal(object)

class Worker(QRunnable):
    def __init__(self, fn, *argv, **kwargs):
        super(Worker, self).__init__()
        self.fn = fn
        self.argv = argv
        self.kwargs = kwargs
        self.signals = WorkerSignals()

        self.c = Client(api_key="account-xxx", api_secret="xxx", sandbox=True)

    @pyqtSlot()
    def run(self):
        asset = self.argv[0]
        self._flag = True
        try:
            while self._flag:
                # The price of the LAST executed trade on the exchange
                result = list(self.c.get_ticker(asset).values())[3]
                print("result " + result)
                time.sleep(2)
                if not self._flag:
                    break
            else:
                self._flag = False
        except:
            traceback.print_exc()
            exctype, value = sys.exc_info()[:2]
            self.signals.error.emit((exctype, value, traceback.format_exc()))
        else:
            self.signals.result.emit(result) # Return the result of the processing
        finally:
            self.signals.finished.emit() #done

everytime the run_worker function is called (depending on the currentText in the combo box) a new thread is produced.


text:
Q: Getting property from array and replace I have this array:
object(stdClass)#458 (2) {
  ["1"]=>
  object(stdClass)#456 (3) {
    ["title"]=>
    string(3) "Test Product 1"
    ["quantity"]=>
    int(1)
    ["price"]=>
    int(1221)
  }
  ["shipping"]=>
  object(stdClass)#457 (3) {
    ["quantity"]=>
    int(1)
    ["title"]=>
    string(13) "Free Delivery"
    ["price"]=>
    int(0)
  }
}

I'm displaying this on the page like this.
@foreach($order->getOrderData($order->order_details) as $itemId =>
     <?php $total += ($item->price * $item->quantity); ?>

{{ $item->title }}

      {{ $item->quantity }}
      ${{ $item->price * $item->quantity }} / €{{ $order['total_eur'] }}
@endforeach

So far everything works perfect except the addition value which I call from database $order['total_eur']. This value is saved when order is placed so I then show total in USD and total in EUR.
The problem here is that ${{ $item->price * $item->quantity }} contain also shipping and when shipping is Free e.g. $ 0 is shown on page
Test Product 1   $122 /  €113
Free Delivery    $0 / €113

What I'm trying to do is to replace somehow when the delivery is free e.g. ["shipping"]=>["price"] = 0 to show 0 instead. to be like this:
Test Product 1   $122 /  €113
Free Delivery    $0 / €0

I can access it like this
<?php $shipping = $order->getOrderData($order->order_details)->shipping->price; ?>

But I can't figured it out how can I change it in the foreach loop.
I hope I explained this clear and understandable. Can anyone suggest something that may work?
Update: I've tried this simple if inside foreach but still showing both eur price on both
${{ $item->price * $item->quantity }}
  @if( ! $order->getOrderData($order->order_details)->shipping)
      {{ $order->getOrderData($order->order_details)->shipping->price }}
  @else
      €{{ $order['total_eur'] }}
  @endif

A: @foreach($order->getOrderData($order->order_details) as $itemId => $item)
     <?php $total += ($item->price * $item->quantity); ?>

{{ $item->title }}

      {{ $item->quantity }}
      @if ($itemId == "shipping" && $item->price == 0)
        $0 / €0
      @else
        ${{ $item->price * $item->quantity }} / €{{ $order['total_eur'] }}
      @endif
@endforeach

Here we are checking the array whether it is shipping item and price is set to zero. If so we are displaying zero €, else we are displaying the actual cost.