text:
Q: Subforms not scrolled fully up on open This is a very simple problem I just can't seem to figure it out. When I open my form all of the subforms that I have on it are scrolled down nearly halfway. I do have headers on them but they are hidden and I have already tested to see if they are the problem. Thank you for your help sorry if this is so simple.

A: You'll have to find out what is causing this.

*

*Check the form header and footer sections for the main form and all the subforms. These are displayed in full (unless hidden) and they will reduce the height of Details Sections if necessary.

*Hint: Reduce the heights of these sections as much as possible. If this fixes the issue then you can progressively re-instate some of their heights.

*On the main form, check the occupied area of all the controls, particularly the subforms. Ctrl-A is a good way to check this (click on the form area before pressing this).

*Use Ctrl-A on the subforms as well to check these.

*Look for any controls that appear further to the right as well.

*Controls overlapping (even by a pixel) can sometimes cause unusual positioning.

I cannot be more specific based on the screenshot, but these are the steps that I would go through.


text:
Q: How to make different rules in yii2, depends on the radiobutton value? I'm a begginer so sorry if it's obvious. So, I would like different rules depends on what the user select. I have an update form:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

<?= $form->field($model, 'news_title')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'news_content')->textarea(['rows' => 6]) ?>

<?= $form->field($model, 'check')->label('Picture update:')
        ->radioList(
                [ 2 => 'Yes', 1 => 'No', 0 => 'Delete']) ?>

<?= $form->field($model, 'file')->fileInput() ?>

<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

And only if the radioList has a value '2' I would like to require the fileInput. I mean if the user select 1 => 'No', or 0 => 'Delete' the fielInput can be empty.
public function rules() {
    return [
        [['news_content'], 'string'],
        [['news_content'], 'required'],
        [['created_at', 'updated_at'], 'safe'],
        [['news_title', 'news_picture', 'created_by', 'updated_by'], 'string', 'max' => 255],
        [['news_title'], 'required'],
        [['news_picture'], 'required'],
        [['file'], 'file', 'skipOnEmpty' => $this->checkRadio(), 'extensions' => 'png, jpg',],
        [['check'], 'required', 'message' => 'Please ....'],
    ];
}
public function checkRadio() {
    if ($this->check == 2) {
        return false;
    } else {
        return true;
    }
}

I tried to write a function in the model but the $check variable always has a 0 value and I don't really understand why. Is there any solution in Yii2 for this?

A: Here is the documentation which is quite straight forward but something like this should be sufficient
[
    'file', 'required',
    'when' => function ($model) {
        return $model->check == 2;
    },
    'whenClient' => "function (attribute, value) {
                return $('#signupform-check-2').is(':checked');
    }",
    'message' => 'Please....'
]

As long as you have client validation enabled, you always have to do two checks. backend and front end.

A: ***********  Your Controller Like This ***********************

 public function actionCreate(){
    $model = new Model();
    if(Yii::$app->request->post())
    {
     if($model->check ==2)
       {
        $model->scenario ='fileInputRequired';
       }
        else{
           $model->scenario ='fileInputNotRequired';
            }
    }
   if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
 }

********** Your Model Like This *****************

public function rules() {
    return [

        [['news_content','news_title','news_picture','check'], 'required'],
        [['news_content'], 'string'],
        [['created_at', 'updated_at'], 'safe'],
        [['news_title', 'news_picture', 'created_by', 'updated_by'], 'string', 'max' => 255],
        [['file'], 'file', 'on' =>'fileInputRequired', 'extensions' => 'png, jpg',],
       ];
}
 function scenario()
{
    return [
        'fileInputRequired' => ['news_content', 'news_picture', 'news_title','file','check'];
        'fileInputNotRequired' => ['news_content', 'news_picture','news_title','check'];
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need to populate an email referencing the latest data in a data extension I'd like to insert content based on a user's last entry within a Data Extension; that is, if a user looked at five products over five days, I want to use the most recent product to insert content.   The Data Extension is a transactional DB in that all the records are present - so how do I write the AMPscript to review all the rows but only action on the most recent one?

A: I'm going with the assumption you have a field in your Data Extension that has a date data type. I'll call it ViewDate
You'll need to use the LookupOrderedRows AMPscript Function and do something like this:
%%[

SET @rowset = LookupOrderedRows("MYDENAME, 1,"ViewDate Desc","SubscriberKey", SubscriberKey)

IF RowCount(@rowset) > 0 THEN

SET @productName = FIELD(ROW(@rowset, 1), "ProductName")

ENDIF

]%%

I'm looking up the Data Extension and retrieving only 1 row, where the SubscriberKey matches and the latest ViewDate. I'm then creating a variable that will be populated with the Product's name.


text:
Q: When trying to count the rows in a sheet colum inside excell by PyCharm(pandas), the column cant be found? I can print specific Excel sheets on PyCharm (pandas) with no problem. But when trying to count rows inside column (Sample):
import pandas as pd

x = pd.read_excel(r"C:\Users\nan\PycharmProjects\giraffe\GENERA.xlsx", sheet_name=["Sample Info"], engine="openpyxl")

split_values = x["Sample"].unique()

print(split_values)

I get:
  warn(msg)
Traceback (most recent call last):
  File "C:/Users/nan/PycharmProjects/giraffe/genera1.py", line 8, in <module>
    split_values = x["Sample"].unique()
KeyError: 'Sample'

What am I doing wrong?


text:
Q: SQL WHERE - Column (value) does not exist I'm attempting to do the most basic WHERE statement in psql and I'm getting a strange error:
ERROR:  column "rom_tut" does not exist
LINE 1: SELECT * FROM pg_roles WHERE rolname="rom_tut";

Why is it complaining that the value isn't a column?

A: use single quote for string value because double quote means column name
SELECT * FROM pg_roles WHERE rolname='rom_tut'


text:
Q: What is the group $SO^*(12)$? Table 5 of this preprint refers to a group $SO^\star(12)$ but gives no reference for the name. Does anybody have a reference on it?

A: The notation $\textrm{SO}^*(2 \ell)$ sometimes denotes the (semisimple, real, connected) subgroup of matrices in $\textrm{SO}(2 \ell, \Bbb C)$ that preserve a skew-Hermitian form on the standard representation, $\Bbb C^{2\ell}$. One can always choose a (complex) basis $(z_1, \ldots, z_{2 \ell})$ with respect to which the form is
$$-z_1 \overline w_{\ell + 1} + z_{\ell + 1} \overline w_1 - \cdots - z_\ell \overline w_{2\ell} + z_{2\ell} \overline w_{\ell} ,$$
and as a matrix group, written with respect to such a basis, $\textrm{SO}^*(2\ell)$ comprises exactly the $2\ell \times 2 \ell$ block matrices
$$\pmatrix{A & B\\-\bar{B}&-\bar{A}}$$
for which $A$ is a skew complex matrix and $B$ is a Hermitian complex matrix.
These groups are respectively real forms of $D_{\ell} = \mathrm{SO}(2\ell, \Bbb C)$ and so have (real) dimension $\ell (2 \ell - 1)$; their behavior depends mildly on the parity of $\ell$. The groups with $\ell \leq 4$ are isogenous to more familiar groups, and in that sense the smallest "new" group in this family is $\mathrm{SO}^*(10)$.
$$\begin{array}{rl}
\hline
\mathfrak{so}^*(2) &\cong &\mathfrak{u}(1) \cong \mathfrak{so}(2) \\
\mathfrak{so}^*(4) &\cong &\mathfrak{su}(2) \oplus \mathfrak{su}(1, 1) \cong \mathfrak{so}(3) \oplus \mathfrak{so}(1, 2)\\
\mathfrak{so}^*(6) &\cong &\mathfrak{su}(1, 3)\\
\mathfrak{so}^*(8) &\cong &\mathfrak{so}(2, 6)\\
\hline
\end{array}$$
For more, see, e.g., Helgason's Differential Geometry and Symmetric Spaces, $\S$IX.4, which does not give this group a descriptive name. Harvey's Spinors and Calibrations, $\S$1, calls this group the skew-unitary group and denotes it by the (I think, unusual) notation $\textrm{SK}(\ell, \mathbb H)$. See also Quaternionic Orthogonal Group.

A: I found the answer here.
"The star indicates the projective group, that is the factor group of its center $\epsilon_n\cdot $ with n-th roots of unity $\epsilon_n$."
The orthogonal group is $SO(n)$, and the star group is $SO^*(n)$.


text:
Q: how to install gmagick extension of php on windows vista gmagick is newer version of imagemagick with more set of features it is less resource intensive and fast but the problem is there is very few discussion about this wonderful tool on web i recently came across this on
 http://devzone.zend.com/1559/manipulating-images-with-php-and-graphicsmagick/
 but i could not install it on windows machines cos phpize did not work so i tried some other way and some how managed to get on phpinfo page but i could not make it work further i colud not even open a single image with gmagick
    this is code i used
     <?php
     $path="gallery/img1.jpg";
     // initialize object
     $image = new Gmagick($path);
     echo $image;
    // read image file
   $file = 'gallery/img1.jpg';
   $image->readImage($file);
   echo '
';
   ?>

i used this code to instanstiate gmagick class and open image but i am geeting very big error as follows
    Fatal error: Uncaught exception 'GmagickException' with message 'Unable to open file (gallery/img1.jpg)' in C:\xampp\htdocs\junk\imgproc\imgproc1.php:4 Stack trace: #0 C:\xampp\htdocs\junk\imgproc\imgproc1.php(4): Gmagick->__construct('gallery/img1.jp...') #1 {main} thrown in C:\xampp\htdocs\junk\imgproc\imgproc1.php on line 4

A: A) To answer the question in your headline (that might lead other readers here):
Windows builds of the GraphicsMagick extension for PHP can be obtained here:
http://valokuva.org/builds/
Check whether you need the thread-safe version or not by looking at a phpinfo(); output of your webserver. Look for the entry Thread Safety. In the entry PHP Extension Build you should also find the VC version that you need, e.g. API20090626,TS,VC9 for VC9.
Download the latest build that matches your conditions, put it into your PHP/ext directory and add it to your php.ini like this:
extension=php_gmagick_ts.dll

Remember to correct the name of the dll if you use the non-TS version.
Restart Apache and check phpinfo();. There should be a gmagick block now..
B) To correct the problem with your code:

*

*The Gmagick constructor does not expect a path as a parameter, but a full image filename (may include a path). Most often it is better to leave it empty and provide the file in the readImage() call.

*Try a full $path (starting at root) and use it in readImage() and writeImage():

Here is an example of a working piece of code:
<?php
// assuming this is the path to your code and to your image files
$path = 'C:\xampp\htdocs\junk\imgproc\';

$image = new Gmagick();
$file = 'img1.jpg';
$image->readImage($path.$file);

// The rest of your code does not make any use of the GM instance,
// so I add something functional here: create a grayscale version and show it
$fileOut= 'img1_GRAY.jpg';
$image->setImageType(Gmagick::IMGTYPE_GRAYSCALE);
$image->writeImage($path.$fileOut);
$image->destroy();
echo "";
?>

It should show a grayscale version of your image file.


text:
Q: S3 get object is better to partition or single file in spring So i need download a file from S3 in my Spring service, i was wondering whether it would be better to split the file or a single large file size of 15Mb would work.
Im thinking more of network connectivity issues.
im using
ResponseInputStream<GetObjectResponse> s3Object = client.getObject(getObjectRequest);

byte[] content = s3Object.readAllBytes();


text:
Q: Setting Membership provider's database at runtime...? We're using ASP.Net membership providers (the SQL Server provider), and I want to be able to change only the database name in the class . To do this, I need the ASP.Net membership provider configured so that my installer can use it
i used code as
public class CodeFirstMembershipProvider : SqlMembershipProvider
    {
      public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
      {
          base.Initialize(name, config);

          // hard coded for testing
          string connectionString = @"server=localhost;database=masterdb;uid=master;pwd=password";

          // Set private property of Membership provider.
          FieldInfo connectionStringField = GetType().BaseType.GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
          if(connectionStringField != null)
            connectionStringField.SetValue(this, connectionString);
      }
}

in above code i need to enter and change the full connection string values..
it too works fine .....
but my query is to change only the database name only of the current connection string mentioned in web.config file..
So is there a way to switch the databse name through an ASP.Net membership through code ?


text:
Q: Get Class name without package from StackTraceElement I have this ste.getClassName() which return a String like this pack.age.Foo.
ste is StackTraceElement.
How I could get only Foo? Or the only way is to do a method which extract Foo from that string?

A: There isn't a built in method for that. You could break up the string like @Naya and @Daniel Perez suggested, or let Class to the heavy lifting for you:
String simpleName = Class.forName(ste.getClassName()).getSimpleName();

A: String fullClassName = stackTraceElement.getClassName();
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);

A: String[] parts = ste.getClassName.split(".");

parts[2] will be the Foo value.
.split allows you to choose a value for which the string will be divided into an array depending on the position of the divider.


text:
Q: Ag-Grid + ngrx - Grid gets rendered at data update Setup
html
<ag-grid-angular
  class="ag-theme-alpine"
  [gridOptions]="gridOptions"
  [rowData]="rowData$ | async"
  [getRowNodeId]="getRowId"
  [pagination]="true"
  [paginationAutoPageSize]="true">
</ag-grid-angular>

ts
config
defaultColDef = {
    // make every column use 'text' filter by default
    filter: 'agSetColumnFilter',
    sortable: true,
    rowSelection: "single",
  };

  columnDefs: ColDef[] = [
    { field: 'idTask', width: 320 },
    { field: 'status', width: 90 },
    { field: 'stammNr', width: 115 },
    { field: 'fassungsNr', width: 130 },
    { field: 'aktion', width: 95 },
    { field: 'user', width: 300, floatingFilter: true },
    { field: 'workflow', width: 130 },
    { field: 'erstellt', width: 240, initialSort: "desc" },
    { field: 'retry', width: 240 }
  ];

  gridOptions = {
    defaultColDef: {
      sortable: true,
      filter: true,
    },
    columnDefs: this.columnDefs,
    animateRows: true,
  };

rowData
this.rowData$ = this.store.select(store => store.doctrans.entities);

getRowId
  getRowId = (params) => {
    return params.idTask;
  }

What works
The table works fine. The rows get updated as the data in ngrx gets updated.
Problem
When i use a filter it gets resetted as soon as the data is updated. Seems the whole grid gets rendered when the rowData$ Observable changes
Question
What to change to the filter options stay?
Update 1
As statet here: Column filter lost when updating row data in ag-grid
the gridOption "deltaRowDataMode: true" should be used. And it works.
But in the comment it says it deprecated and https://www.ag-grid.com/javascript-data-grid/immutable-data/ should be used. But this seems to be deprecated too.
Solution
Solved my problem.
As stated here: https://www.ag-grid.com/javascript-data-grid/data-update-row-data/, if you provide a row-id only the rows who changed should be updated. This didnt work for me and now i know why.
Here: https://ag-grid.com/changelog/?fixVersion=27.1.0 if you search for immutable you find "27.1.0
Replace getRowNodeId() with getRowId() to make a) immutable data the default and b) provide more info in params".
I installed my ag-grid-community bevor 15.03 (version 27.1) and so getRowId() didnt work.
I updated to version 27.1.0 and everything works now. I just need to set the rowId with:
gridOptions = {
    // other options
    getRowId: (params) => params.data.idTask,
  };

and the grid just updated the rows which have changed.


text:
Q: How do I access Windows Media Player Library programmatically in C#/WPF? I need to access and present the information from Windows Media Player library, from my C#/WPF application.
How do I do this programmatically in C#/WPF?

A: This is a bit of a cop out ...
The SDK is a huge subject ... how about a sample ?
EDIT : 1 of 2 :
This is what im talking about as a starting point:
The documentation for the "Windows Media Player SDK" refers you to download the "Windows SDK" and then consume some key interfaces ...
Here's the list of interfaces:
http://msdn.microsoft.com/en-us/library/dd563069(v=VS.85).aspx
The download can be started here:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=6B6C21D2-2006-4AFA-9702-529FA782D63B
That links you to an installer app that basically goes and gets the files for you (similar to say the silverlight or flash installer)
EDIT 2 of 2:
Once the WMP SDK isdownloaded and installed add a reference to "WMPLib" its listed under com in the dialog if like everyone else you happen to be using visual studio :)
Once you have your reference you can do this ...
WMPlib.WindowsMediaPlayer wmpInstance = new WMPlib.WindowsMediaPlayer();
IWMPMediaCollection lib = wmpInstance.mediaCollection;

From here on out its simply a case of using that reference to the library ...
lib.GetAll() returns everything in your media library :)
...
And thats how its done :) !!!


text:
Q: want to print a json mutable dictionary in table cells I have a json parsed value that I stored in a dictionary.
Now I want to print the values of that dictionary in a table cell.
This is my dictionary:
    "": {
        "activity_type": "friend accept",
        "owner_id": "33",
        "owner_first_name": "Girija",
        "owner_last_name": "S",
        "photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/sites/default/files/pictures/picture-33-6361851323080768.jpg",
        "activity_id": "35340",
        "activity_details": "a:2:{s:4:\"html\";s:51:\"!user_fullname and !friend_fullname are now friends\";s:4:\"type\";s:10:\"friend_add\";}",
        "time": "1302496707"
    },
    "1": {
        "activity_type": "friend accept",
        "owner_id": "412",
        "owner_first_name": "Siva Shankara",
        "owner_last_name": "Nainar Bernadsha",
        "photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/sites/default/files/pictures/picture-412249965611.jpg",
        "activity_id": "35339",
        "activity_details": "a:2:{s:4:\"html\";s:51:\"!user_fullname and !friend_fullname are now friends\";s:4:\"type\";s:10:\"friend_add\";}",
        "time": "1302332540"
    },
    "2": {
        "activity_type": "status_update",
        "activity_id": "35338",
        "user_id": "1",
        "user_first_name": "Chandra Bhusan",
        "user_last_name": "Pandey",
        "photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/sites/default/files/pictures/picture-1627435117.jpg",
        "activity_details": "Hi",
        "time": "1302183038"
    },
    "boolean": "1"
    }

Now I want print

    {
        "activity_type": "friend accept",
        "owner_id": "33",
        "owner_first_name": "Girija",
        "owner_last_name": "S",
        "photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/sites/default/files/pictures/picture-33-6361851323080768.jpg",
        "activity_id": "35340",
        "activity_details": "a:2:{s:4:\"html\";s:51:\"!user_fullname and !friend_fullname are now friends\";s:4:\"type\";s:10:\"friend_add\";}",
        "time": "1302496707"
    }

These values in a single cell and similarly the other cells hold the iterated values.
Can anyone help me out?

A: If you have the NSDictionary which contains all these values and you want to display all of them on the table cell then I think its better if you create custom UITableViewCell for the cells of your table view. You can get a lot of tutorial for this. Here are some samples
Tutorial 1
Tutorial 2


text:
Q: typing "android" in firefox opens a apache2 Ubuntu Default Page Whenever I search for the word android through firefox' address bar, a page titled Apache2 Ubuntu Default Page opens up.

What is this page all about and what does it have to do with Ubuntu?
BTW I'm running Ubuntu 14.04 and Mozilla Firefox 36.0.4
EDIT: Here is the output of  nmap android
Starting Nmap 6.40 ( http://nmap.org ) at 2015-03-27 22:05 IST
Nmap scan report for android (127.0.53.53)
Host is up (0.00041s latency).
Not shown: 997 closed ports
PORT    STATE SERVICE
80/tcp  open  http
139/tcp open  netbios-ssn
445/tcp open  microsoft-ds

Nmap done: 1 IP address (1 host up) scanned in 1.60 seconds

A: I concur with Eric Carvalho's comment. I assume you're typing android in the URL bar vs the top-right search box? It seems a PC is named android on your network. You can try ping, nslookup PC-NAME to identify it. You could use a port scanner (nmap or telnet PC-NAME 80) to see if its got apache (a web server) installed on it

A: It is the android device used for usb tethering which shows up as a server on the network.
The page is shown because apache is installed on the computer, and it thinks that android, located at 127.0.55.55 is a website. As the so called website(the phone) does not have any webpage, apache shows the default page instead.
As Apache is not needed on a desktop, uninstalling it fixes the problem.
To uninstall apache, you can use
sudo apt-get remove apache2


text:
Q: Executing Mojo failed with `java.lang.NoSuchMethodError` org.codehaus.plexus.util.DirectoryScanner.setFilenameComparator I have created 2 Mojos and recently decided to upgrade all my versions usign the maven version plugin.
Now, an executing one of my Mojos, I get this exception:
An API incompatibility was encountered while executing com.mycompany:spi2jars-maven-plugin:1.0-SNAPSHOT:spi2jars:

 java.lang.NoSuchMethodError: 'void org.codehaus.plexus.util.DirectoryScanner.setFilenameComparator(java.util.Comparator)

I know what this errors means, and I retrieve the full stacktrace by running with -X
Caused by: java.lang.NoSuchMethodError: 'void org.codehaus.plexus.util.DirectoryScanner.setFilenameComparator(java.util.Comparator)'
    at org.codehaus.plexus.components.io.resources.PlexusIoFileResourceCollection.getResources (PlexusIoFileResourceCollection.java:250)
    at org.codehaus.plexus.archiver.AbstractArchiver$1.hasNext (AbstractArchiver.java:560)
    at org.codehaus.plexus.archiver.zip.AbstractZipArchiver.createArchiveMain (AbstractZipArchiver.java:221)
    at org.codehaus.plexus.archiver.zip.AbstractZipArchiver.execute (AbstractZipArchiver.java:199)
    at org.codehaus.plexus.archiver.AbstractArchiver.createArchive (AbstractArchiver.java:1042)
    at org.apache.maven.archiver.MavenArchiver.createArchive (MavenArchiver.java:676)
    at com.mycompany.Spi2Jars.createJarForLine (Spi2Jars.java:81)
    at com.mycompany.Spi2Jars.execute (Spi2Jars.java:47)

So it seems the MavenArchiver is at fault, or maybe a missing jar or incompatible versions.. But how do I check this?
[Update]
I found different versions of the underlying jars using
mvn dependency:tree -Dverbose

For example:
\- org.apache.maven:maven-archiver:jar:3.5.0:compile
[INFO]    +- (org.apache.maven:maven-artifact:jar:3.0:compile - omitted for conflict with 3.6.0)
[INFO]    +- (org.apache.maven:maven-model:jar:3.0:compile - omitted for conflict with 3.6.3)
[INFO]    +- (org.apache.maven:maven-core:jar:3.0:compile - omitted for conflict with 3.6.3)
[INFO]    +- (org.apache.maven.shared:maven-shared-utils:jar:3.2.1:compile - omitted for duplicate)
[INFO]    +- commons-io:commons-io:jar:2.5:compile
[INFO]    +- org.codehaus.plexus:plexus-archiver:jar:4.2.0:compile
[INFO]    |  +- (org.codehaus.plexus:plexus-utils:jar:3.3.0:compile - omitted for conflict with 3.2.1)
[INFO]    |  +- org.codehaus.plexus:plexus-io:jar:3.2.0:compile
[INFO]    |  |  +- (org.codehaus.plexus:plexus-utils:jar:3.3.0:compile - omitted for conflict with 3.2.1)
[INFO]    |  |  \- (commons-io:commons-io:jar:2.6:compile - omitted for conflict with 2.5)
[INFO]    |  +- org.apache.commons:commons-compress:jar:1.19:compile
[INFO]    |  +- org.iq80.snappy:snappy:jar:0.4:compile
[INFO]    |  \- org.tukaani:xz:jar:1.8:runtime
[INFO]    +- (org.codehaus.plexus:plexus-utils:jar:3.3.0:compile - omitted for conflict with 3.2.1)
[INFO]    \- (org.codehaus.plexus:plexus-interpolation:jar:1.25:compile - omitted for conflict with 1.11)

It would be so awesome if the most recent maven plugins played nice together... It seems they don't. How do I resolve this nicely?

A: I had a similar issue (same error message).
I could solve this isse by declaring the following direct dependency in our custom plugin:
    <dependency>
        <groupId>org.codehaus.plexus</groupId>
        <artifactId>plexus-utils</artifactId>
        <version>3.3.0</version>
    </dependency>


text:
Q: Difference between "while" loop and "do while" loop What is the difference between while loop and do while loop. I used to think both are completely same.Then I came across following piece of code:
do {
        printf("Word length... ");
        scanf("%d", &wdlen);
    } while(wdlen<2);

This code works perfectly. It prints word length and tascans the input. But when I changed it to
while(wdlen<2){
        printf("Word length... ");
        scanf("%d", &wdlen);
    }

It gives a blank screen. It do not work. So there is some functional difference between both loops. Can anybody explain it?
Is there any other difference in these two?

A: The do while loop executes the content of the loop once before checking the condition of the while.
Whereas a while loop will check the condition first before executing the content.
In this case you are waiting for user input with scanf(), which will never execute in the while loop as wdlen is not initialized and may just contain a garbage value which may be greater than 2.

A: do {
    printf("Word length... ");
    scanf("%d", &wdlen);
} while(wdlen<2);

A do-while loop guarantees the execution of the loop at least once because it checks the loop condition AFTER the loop iteration. Therefore it'll print the string and call scanf, thus updating the wdlen variable.
while(wdlen<2){
    printf("Word length... ");
    scanf("%d", &wdlen);
}

As for the while loop, it evaluates the loop condition BEFORE the loop body is executed. wdlen probably starts off as more than 2 in your code that's why you never reach the loop body.

A: do while in an exit control loop.
while is an entry control loop.

A: While:

*

*entry control loop

*condition is checked before loop execution

*never execute loop if condition is false

*there is no semicolon at the end of while statement
Do-while:

*

*exit control loop

*condition is checked at the end of loop

*executes false condition at least once since condition is checked later

*there is semicolon at the end of while statement.

A: The difference is in when the condition gets evaluated. In a do..while loop, the condition is not evaluated until the end of each loop. That means that a do..while loop will always run at least once. In a while loop, the condition is evaluated at the start.
Here I assume that wdlen is evaluating to false (i.e., it's bigger than 1) at the beginning of the while loop, so the while loop never runs. In the do..while loop, it isn't checked until the end of the first loop, so you get the result you expect.

A: While : your condition is at the begin of the loop block, and makes possible to never enter the loop.
Do While : your condition is at the end of the loop block, and makes obligatory to enter the loop at least one time.

A: Do while loop will be executed atleast once.......but while loop will check the condition first and then it may or may not get executed depending on the condition.
In your example wdlen may assume any garbage value which is > 2 so while loop will never get executed.
whereas do while loop will be ececuted and will tell u to enter the value and check that value in terminating condition

A: while(wdlen<2){
  ...
 }

If wdlen (assuming it's a stack variable) is not initialized or assigned a value before the while loop is entered, it will contain whatever was in that space in memory before (i.e. garbage). So if the garbage value is < 2, the loop executes, otherwise it doesn't.
do{
 ...
}while(wdlen<2)

will execute once and then checks on condition to run loop again, and this time it might succeed if by chance wdlen which is uninitialized is found to be less than 2.

A: Probably wdlen starts with a value >=2, so in the second case the loop condition is initially false and the loop is never entered.
In the second case the loop body is executed before the wdlen<2 condition is checked for the first time, so the printf/scanf is executed at least once.

A: while test the condition before executing statements within the while loop.
do while test the condition after having executed statement within the loop.
source: let us C

A: while test the condition before executing statements in the while loop.
do while test the condition after having executed statement inside the loop.

A: In WHILE first check the condition and then execute the program
In DO-WHILE loop first execute the program at least one time then check the condition

A: The difference between do while (exit check) and while (entry check) is that while entering in do while it will not check but in while it will first check
The example is as such:
Program 1:
int a=10;
do{
System.out.println(a);
}
while(a<10);

//here the a is not less than 10 then also it will execute once as it will execute do while exiting it checks that a is not less than 10 so it will exit the loop

Program 2:
int b=0;
while(b<10)
{
System.out.println(b);
}
//here nothing will be printed as the value of b is not less than 10 and it will not let enter the loop and will exit

output Program 1:
10
output Program 2:
[nothing is printed]
note:
output of the program 1 and program 2 will be same if we assign a=0 and b=0 and also put a++; and b++; in the respective body of the program.

A: While Loop:
while(test-condition)
{
      statements;
      increment/decrement;
}

*

*Lower Execution Time and Speed

*Entry Conditioned Loop

*No fixed number of iterations

Do While Loop:
do
{
      statements;
      increment/decrement;
}while(test-condition);

*

*Higher Execution Time and Speed

*Exit Conditioned Loop

*Minimum one number of iteration

Find out more on this topic here: Difference Between While and Do While Loop
This is valid for C programming, Java programming and other languages as well because the concepts remain the same, only the syntax changes.
Also, another small but a differentiating factor to note is that the do while loop consists of a semicolon at the end of the while condition.

A: The difference between a while constructs from Step 1 versus a do while is that any expressions within the do {} will be running at least once regardless of the condition within the while() clause.
println("\nStep 2: How to use do while loop in Scala")
var numberOfDonutsBaked = 0
do {
  numberOfDonutsBaked += 1
  println(s"Number of donuts baked = $numberOfDonutsBaked")
} while (numberOfDonutsBaked < 5)

Here is detail explaination: Explanation
Visit: coderforevers

A: The most important difference between while and do-while loop is that in do-while, the block of code is executed at least once, even though the condition given is false.
To put it in a different way :

*

*While- your condition is at the begin of the loop block, and makes possible to never enter the loop.

*In While loop, the condition is first tested and then the block of code is executed if the test result is true.


text:
Q: Why my code consumes too much memory even after clearing list? So i'm trying to solve this problem and the question goes like this
Probably, You all Know About The Famous Japanese Cartoon Character Nobita and Shizuka. Nobita Shizuka are very Good friend. However , Shizuka Love a special kind of string Called Tokushuna.
A string T is called Tokushuna if
The length of the string is greater or equal then 3 (|T| ≥ 3 )
It start and end with a charecter '1' (one)
It contain (|T|-2) number of '0' (zero)
here |T| = length of string T . Example , 10001 ,101,10001 is Tokushuna string But 1100 ,1111, 0000 is not.
One Day Shizuka Give a problem to nobita and promise to go date with him if he is able to solve this problem. Shizuka give A string S and told to Count number of Tokushuna string can be found from all possible the substring of string S . Nobita wants to go to date with Shizuka But You Know , he is very weak in Math and counting and always get lowest marks in Math . And In this Time Doraemon is not present to help him .So he need your help to solve the problem .
Input
First line of the input there is an integer T, the number of test cases. In each test case, you are given a binary string S consisting only 0 and 1.
Subtasks
Subtask #1 (50 points)
1 ≤ T ≤ 100
1 ≤ |S| ≤ 100
Subtask #2 (50 points)
1 ≤ T ≤ 100
1 ≤ |S| ≤ 105
Output
For each test case output a line Case X: Y where X is the case number and Y is the number of Tokushuna string can be found from all possible the substring of string S
Sample
Input
3
10001
10101
1001001001
Output
Case 1: 1
Case 2: 2
Case 3: 3
Look, in first case 10001 is itself is Tokushuna string.
In second Case 2 Substring S[1-3] 101 and S[3-6] 101 Can be found which is Tokushuna string.
What I've done so far
I've already solved the problem but the problem is it shows my code exceeds memory limit (512mb). I'm guessing it is because of the large input size. To solve that I've tried to clear the list which holds all the substring of one string after completing each operation. But this isn't helping.
My code
num = int(input())
num_list = []
for i in range(num):
  i = input()
  num_list.append(i)

def condition(a_list):
  case = 0
  case_no = 1
  sub = []
  for st in a_list:
    sub.append([st[i:j] for i in range(len(st)) for j in range(i + 1, len(st) + 1)])
    for i in sub:
        for item in i:
            if len(item) >= 3 and (item[0] == '1' and item[-1] == '1') and (len(item) - 2 == item.count('0')):
                case += 1

        print("Case {}: {}".format(case_no, case))
        case = 0
        case_no += 1
        sub.clear()

condition(num_list)

Is there any better approach to solve the memory consumption problem?

A: Have you tried taking java heap dump and java thread dump? These will tell the memory leak and also the thread that is consuming memory.

A: Your method of creating all possible substrings won't scale very well to larger problems. If the input string is length N, the number of substrings is N * (N + 1) / 2 -- in other words, the memory needed will grow roughly like N ** 2. That said, it is a bit puzzling to me why your code would exceed 512MB if the length of the input string is always less than 105.
In any case, there is no need to store all of those substrings in memory, because a Tokushuna string cannot contain other Tokushuna strings nested within
it:
1       # Leading one.
0...    # Some zeros. Cannot be or contain a Tokushuna.
1       # Trailing one. Could also be the start of the next Tokushuna.

That means a single scan over the string should be sufficient to find them all.
You could write your own algorithmic code to scan the characters and keep track
of whether it finds a Tokushuna string. But that requires some tedious
bookkeeping.
A better option is regex, which is very good at character-by-character analysis:
import sys
import re

# Usage: python foo.py 3 10001 10101 1001001001
cases = sys.argv[2:]

# Match a Tokushuna string without consuming the last '1', using a lookahead.
rgx = re.compile(r'10+(?=1)')

# Check the cases.
for i, c in enumerate(cases):
    matches = list(rgx.finditer(c))
    msg = 'Case {}: {}'.format(i + 1, len(matches))
    print(msg)

If you do not want to use regex, my first instinct would be to start the algorithm by finding the indexes of all of the ones: indexes = [j for j, c in enumerate(case) if c == '1']. Then pair those indexes up: zip(indexes, indexes[1:]). Then iterate over the pairs, checking whether the part in the middle is all zeros.
A small note regarding your current code:
# Rather than this,
sub = []
for st in a_list:
    sub.append([...])    # Incurs memory cost of the temporary list
                         # and a need to drill down to the inner list.
    ...
    sub.clear()          # Also requires a step that's easy to forget.

# just do this.
for st in a_list:
    sub = [...]
    ...


text:
Q: Using Google Service's FusedLocationProviderClient in a Tablet Emulator I need to emulate an Android Application on a tablet. I'm currently running Android Studio 3.0.
The problem is that the application uses Google Service API's FusedLocationProviderClient (Documentation), which, as far as I understand, requires Google Services 11 as minimum. The current SDK tools for Android Studio seems to only update Google Play Services to 10.9.*, and it seems that no pre-configured Tablet emulators come pre-installed with Google Play Store, meaning I can't simply update it through the settings page the same way that you can with the new phone emulators that has play store pre-installed.
I've tried to find ways to manually update Google Play Services to the newest one available, however almost all previously accepted answers on here seems to simply suggest downgrading build.gradle dependencies to whatever the emulator supports. That doesn't work in this case however, as I need features specifically in the newer versions :/
Is there any way that one can manually update Google Play Services on an emulator?

A: No mention of what you're saying in the link you provided. However, it was announced here that if you're going to use Google Play Services 11.2.0, your app's compileSdkVersion must be at least 26.
I would suggest that you go to Android SDK Manager and update your API package there. It often includes the System Image for emulators.
You can see on this screenshot that I'm able to use the Android emulator with Android 27 installed because I downloaded it first in the SDK Manager.
I'm able to use API 27 because I installed the system image in SDK Manager:

from SDK Manager, API 27 package is downloaded and installed, hence it's available on the emulator:

You can also check this SO post for additional reference.


text:
Q: Google Analytics Profile Filtering with Ecommerce I have a two different sites that checkout on the same eCommerce site. There's sitea.com siteb.com and checkout.com. They are set up like this:
    siteb.com --> sitea.com --> checkout.com

Most traffic is on stiea.com and customers checkout directly from there to checkout.com. Those using siteb shop and build a cart on siteb and then when they checkout they go sitea which then takes them to checkout.com. I have cross domain and ecommerce tracking up and working perfectly for sitea.com and checkout.com and so setting it up for siteb.com isn't an issue. Where this issue comes is that I want to be able to look at the traffic on just siteb.com AND the eCommerce for siteb and just siteb, basically excluding all the eCommerce from stiea. When I test it out I get all of sitea's traffic as well as siteb's. I've looked everywhere but can't find any kind of solution. Anybody have any ideas?

A: Near as I can figure, there's no way to setup a segment or filter that only includes pages whose first page was on siteb.com.  One idea is to set a session/visit scoped custom variable on the first page of visit, with a value of for example "siteb" if starting on siteb.com, or 'sitea" if on sitea.com.  Then you should be able to go to your custom variable report and go to the siteb.com entry and break down by all pages.


text:
Q: Debugging managed app crash I'm trying desparately to debug an application I'm trying to release. It was created on Win7 x64, and also runs fine on Win x32, but not on XP (Don't have Vista to test).
I've created a dump file by setting the _NT_SYMBOL_PATH to the directory of the application in XP, then run the debugger with:
  adplus -crash -pn launchmenot.exe
This creates a dump file which I've opened in Visual Studio 2008 (Having specified the directory of the application's PDBs and the MS symbol servers in VS. After VS downloads all of the symbols I just get 'There is no source code available for the current location'.
I have a feeling it could be from using the Interop.IWshRuntimeLibrary from Win7 on XP, but I really don't know.
The dump file is 107Mb, but the app itself is online here (compiled in debug mode). Could anyone point me in the right direction for finding the cause or fixing the error please?
Much appreciated. :)

A: Does this error message mean anything to you:

Cannot convert string
  'pack://application:,,,/Resources/icon.ico'
  in attribute 'Icon' to object of type
  'System.Windows.Media.ImageSource'.
  The image format is unrecognized.
  Error at object
  'LaunchMeNot.WinUnhandledException' in
  markup file
  'LaunchMeNot;component/winunhandledexception.xaml'
  Line 10 Position 46.

Edit: this last exception is actually being thrown from the unhandled exception filter and becomes fatal. There're two inner exceptions that describe the problem in more detail.
It all starts off with this trace:
0012e44c 7c812afb [HelperMethodFrame: 0012e44c]
0012e4f0 54fc6b82 System.Windows.Media.PixelFormat.GetPixelFormat(System.Windows.Media.SafeMILHandle)
0012e534 547ca498 System.Windows.Media.Imaging.BitmapSource.UpdateCachedSettings()
0012e56c 547ca431 System.Windows.Media.Imaging.BitmapSource.set_WicSourceHandle(System.Windows.Media.Imaging.BitmapSourceSafeMILHandle)
0012e598 547ca198 System.Windows.Media.Imaging.BitmapFrameDecode.FinalizeCreation()
0012e5c8 54fc6e86 System.Windows.Media.Imaging.BitmapSource.CompleteDelayedCreation()
0012e5f4 547cb3a8 System.Windows.Media.Imaging.BitmapSource.get_PixelWidth()
0012e600 56290f1f MS.Internal.AppModel.IconHelper.GetBestMatch(System.Collections.ObjectModel.ReadOnlyCollection`1<System.Windows.Media.Imaging.BitmapFrame>, Int32, Int32, Int32)
0012e678 5629168f MS.Internal.AppModel.IconHelper.GetIconHandlesFromBitmapFrame(System.Object, System.Windows.Media.Imaging.BitmapFrame, IconHandle ByRef, IconHandle ByRef)
0012e698 565df5fd System.Windows.Window.UpdateIcon()
0012e6b0 55c8ed3a System.Windows.Window.SetupInitialState(Double, Double, Double, Double)
0012e854 55c266c8 System.Windows.Window.CreateSourceWindowImpl()
0012e8d0 55c264b9 System.Windows.Window.SafeCreateWindow()
0012e8dc 55c263c1 System.Windows.Window.ShowHelper(System.Object)
0012e904 55c8e3b8 System.Windows.Window.Show()
0012e910 562076e7 System.Windows.Window.ShowDialog()
0012e984 00f70556 LaunchMeNot.App.OnStartup(System.Windows.StartupEventArgs)
0012e9f8 55bed4b9 System.Windows.Application.<.ctor>b__0(System.Object)
0012ea08 578461fa System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Boolean)
0012ea2c 578460ea System.Windows.Threading.ExceptionWrapper.TryCatchWhen(System.Object, System.Delegate, System.Object, Boolean, System.Delegate)
0012ea74 578442b4 System.Windows.Threading.Dispatcher.WrappedInvoke(System.Delegate, System.Object, Boolean, System.Delegate)
0012ea94 5784912d System.Windows.Threading.DispatcherOperation.InvokeImpl()
0012eac0 578490b8 System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(System.Object)
0012eac8 792f5681 System.Threading.ExecutionContext.runTryCode(System.Object)
0012eef0 79e71b4c [HelperMethodFrame_PROTECTOBJ: 0012eef0] System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode, CleanupCode, System.Object)
0012ef58 792f5577 System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
0012ef74 792e01c5 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
0012ef8c 57848ff3 System.Windows.Threading.DispatcherOperation.Invoke()
0012efc4 57843957 System.Windows.Threading.Dispatcher.ProcessQueue()
0012f0a0 57843c43 System.Windows.Threading.Dispatcher.WndProcHook(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)
0012f0ec 578463de MS.Win32.HwndWrapper.WndProc(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)
0012f138 5784630a MS.Win32.HwndSubclass.DispatcherCallbackOperation(System.Object)
0012f148 578461fa System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Boolean)
0012f16c 578460ea System.Windows.Threading.ExceptionWrapper.TryCatchWhen(System.Object, System.Delegate, System.Object, Boolean, System.Delegate)
0012f1b4 578442b4 System.Windows.Threading.Dispatcher.WrappedInvoke(System.Delegate, System.Object, Boolean, System.Delegate)
0012f1d4 57843411 System.Windows.Threading.Dispatcher.InvokeImpl(System.Windows.Threading.DispatcherPriority, System.TimeSpan, System.Delegate, System.Object, Boolean)
0012f218 57843360 System.Windows.Threading.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority, System.Delegate, System.Object)
0012f23c 57845a4c MS.Win32.HwndSubclass.SubclassWndProc(IntPtr, Int32, IntPtr, IntPtr)
0012f3b4 0036217b [NDirectMethodFrameStandalone: 0012f3b4] MS.Win32.UnsafeNativeMethods.DispatchMessage(System.Windows.Interop.MSG ByRef)
0012f3c4 57843a57 System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame)
0012f414 57843129 System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame)
0012f420 578430cc System.Windows.Threading.Dispatcher.Run()
0012f42c 55bed47e System.Windows.Application.RunDispatcher(System.Object)
0012f438 55bec77f System.Windows.Application.RunInternal(System.Windows.Window)
0012f45c 55bd3a96 System.Windows.Application.Run(System.Windows.Window)
0012f46c 55bd3a59 System.Windows.Application.Run()
0012f478 00f700bc LaunchMeNot.App.Main()

which clearly indicates a problem with an image resource.
The embedded exceptions are:

Exception from HRESULT: 0x88982F07

wrapped in:

The image format is unrecognized.

After a bit of googling I came across this post which details a similar finding. Looks like an icon in a unrecognized format. The post goes on to suggest to remove the icons. My guess is that you could try and redo them in a compliant editor.

A: You might have a bit more luck in wndbg -- download from the Debugging Tools for Windows page.  Load the crash dump, set the symbol path and run !analyze -v to get detailed information on the crash.  If you are still having problems finding the correct symbols try running !sym noisy and also the !itoldyouso command

A: Use WinDebug to analyse the dump - it can also used for managed code.
See the blog entries by Tess Ferrandez for more info.


text:
Q: How to execute page methods when using custom route handlers? When the path refers to the actual folder structure and points to the page it's not a problem, i.e. "/Default.aspx/MyMethod", however if "/" brings up "Default.aspx", then "/MyMethod" means something different. Is it even possible at all?
A possible solution, and probably a better one, is to use a web service, which is what I'm using at the moment.

A: You can add the following:
PageMethods.set_path('/yourpage.aspx');

I found this solution here


text:
Q: Get comma separated values from an xml in SQL I am calling Scalar UDF from a stored procedure to get a column value. Inside the scalar UDF I have an xml and I have to get the comma separated values of a particular node. I used Cross apply but it caused huge performance bottleneck because stored procedure is actually used to fetch reports.
There is a table [Traveler] which has a field ID, BookingID(can be duplicate) and FareDetails. Inside the FareDetails we are storing the xml.
The logic inside UDF is as follows :
1st Solution , Using Cross Apply :
 ALTER FUNCTION [dbo].[GetBookingInfo] (@BookingID bigint, @InfoID smallint) RETURNS VARCHAR(1024) AS
        BEGIN
            DECLARE @InfoCSV VARCHAR(1024)

            --
            -- Fare Basis: InfoID = 1
            --
            IF @InfoID = 1
            BEGIN

                    SELECT @InfoCSV = (SELECT
                        (PTSD.PSTDNode.value('(FBC)[1]', 'VARCHAR(1024)')  + ',') [text()]
                    FROM
                        [Traveler]
                        CROSS APPLY [FareDetails].nodes('/AirFareInfo/PTSDPFS/PTSD') PTSD(PSTDNode)
                    WHERE
                        [BookingID] = @BookingID
                    ORDER BY
                        ID ASC
                    FOR XML PATH (''))

                IF @InfoCSV IS NOT NULL AND LEN(@InfoCSV) > 0
                    SET @InfoCSV = LEFT(@InfoCSV, LEN(@InfoCSV) - 1)
            END

            RETURN @InfoCSV

2nd solution , without cross apply :
  ALTER FUNCTION [dbo].[GetBookingInfo] (@BookingID bigint, @InfoID smallint) RETURNS VARCHAR(1024) AS
        BEGIN
            DECLARE @InfoCSV VARCHAR(1024)

            --
            -- Fare Basis: InfoID = 1
            --
            IF @InfoID = 1
            BEGIN

                  SELECT @InfoCSV = (SELECT TOP 1 REPLACE(FareDetails.query(N'data(/AirFareInfo/PTSDPFS/PTSD/FBC)').value('(text())[1]','nvarchar(100)'),' ',',')
        FROM [Traveler]
        WHERE
                [BookingID] = @BookingID)

                IF @InfoCSV IS NOT NULL AND LEN(@InfoCSV) > 0
                    SET @InfoCSV = LEFT(@InfoCSV, LEN(@InfoCSV) - 1)
            END

            RETURN @InfoCSV

The 2nd solution is saving lot of time , but when we have duplicate booking ID's then it is not concatenating all the values of FBC .
e.g. :
1)If BookingID is unique and we have FareDetail xml as follows then output should be  be AP,AP
2)If BookingID is not unique(coming twice) and we have FareDetail xml as follows then output should be  be AP,AP,AP,AP corresponding to both BookingID.
The xml is as follows :
<AirFareInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" IPFA="false">
  <PT>Flight</PT>
  <FPMID>0</FPMID>
  <PTID>1</PTID>
  <FS>
    <CID>2</CID>
    <Value>0</Value>
  </FS>
  <TF>
    <CID xsi:nil="true" />
    <Value>0</Value>
  </TF>
  <VF>
    <CID>2</CID>
    <Value>0</Value>
  </VF>
  <VD>
    <CID>2</CID>
    <Value>0</Value>
  </VD>
  <VCR xsi:nil="true" />
  <VC>
    <CID>2</CID>
    <Value>0</Value>
  </VC>
  <VFC>
    <CID>2</CID>
    <Value>0</Value>
  </VFC>
  <VST />
  <VIT />
  <AAPFVDR xsi:nil="true" />
  <CC>
    <CID>2</CID>
    <Value>0</Value>
  </CC>
  <D>
    <CID>2</CID>
    <Value>514.15</Value>
  </D>
  <PD>
    <CID>2</CID>
    <Value>0</Value>
  </PD>
  <EBF>
    <CID>2</CID>
    <Value>0</Value>
  </EBF>
  <CST>
    <DL>
      <ATRID>13</ATRID>
      <OB>
        <CID>2</CID>
        <Value>74.04</Value>
      </OB>
      <OC>
        <CID>2</CID>
        <Value>0.00</Value>
      </OC>
      <OS>
        <CID>2</CID>
        <Value>0.00</Value>
      </OS>
      <OF>
        <CID>2</CID>
        <Value>50.83</Value>
      </OF>
      <OP>
        <CID>2</CID>
        <Value>0.00</Value>
      </OP>
      <C>
        <CID>2</CID>
        <Value>0</Value>
      </C>
      <IBF>false</IBF>
      <D>2014-06-09T14:57:53.521Z</D>
    </DL>
  </CST>
  <CIT />
  <CRMR xsi:nil="true" />
  <CRM>
    <CID>2</CID>
    <Value>0</Value>
  </CRM>
  <TL ATC="Tax" PC="" DEN="User Development Fee - Arrival (UDF)">
    <TID xsi:nil="true" />
    <Amount>
      <CID>2</CID>
      <Value>75.00</Value>
    </Amount>
  </TL>
  <TL ATC="Tax" PC="" DEN="Passenger Service Fee">
    <TID xsi:nil="true" />
    <Amount>
      <CID>2</CID>
      <Value>146.00</Value>
    </Amount>
  </TL>
  <TL ATC="Tax" PC="" DEN="User Development Fee - Departure (UDF)">
    <TID xsi:nil="true" />
    <Amount>
      <CID>2</CID>
      <Value>1681.00</Value>
    </Amount>
  </TL>
  <TL ATC="Tax" PC="" DEN="Cute Fee">
    <TID xsi:nil="true" />
    <Amount>
      <CID>2</CID>
      <Value>50.00</Value>
    </Amount>
  </TL>
  <TL ATC="Tax" PC="" DEN="Government Service Tax">
    <TID xsi:nil="true" />
    <Amount>
      <CID>2</CID>
      <Value>151.00</Value>
    </Amount>
  </TL>
  <TL ATC="Tax" PC="" DEN="User Development Fee - Arrival (UDF)">
    <TID xsi:nil="true" />
    <Amount>
      <CID>2</CID>
      <Value>833.00</Value>
    </Amount>
  </TL>
  <TL ATC="Tax" PC="" DEN="Passenger Service Fee">
    <TID xsi:nil="true" />
    <Amount>
      <CID>2</CID>
      <Value>1132.00</Value>
    </Amount>
  </TL>
  <TL ATC="Tax" PC="" DEN="User Development Fee - Departure (UDF)">
    <TID xsi:nil="true" />
    <Amount>
      <CID>2</CID>
      <Value>76.00</Value>
    </Amount>
  </TL>
  <TL ATC="Tax" PC="" DEN="Government Service Tax">
    <TID xsi:nil="true" />
    <Amount>
      <CID>2</CID>
      <Value>148.00</Value>
    </Amount>
  </TL>
  <PTSDPFS>
    <PTSD IO="false">
      <FBC>AP</FBC>
      <ACD RBD="" ACCID="1" MCT="Super Sale Fare(AP)" INC="false" />
      <ATSID xsi:nil="true" />
    </PTSD>
  </PTSDPFS>
  <PTSDPFS>
    <PTSD IO="false">
      <FBC>AP</FBC>
      <ACD RBD="" ACCID="1" MCT="Super Sale Fare(AP)" INC="false" />
      <ATSID xsi:nil="true" />
    </PTSD>
  </PTSDPFS>
  <RuleDetails>
    <TRS xsi:nil="true" />
    <PP xsi:nil="true" />
    <II xsi:nil="true" />
    <LTD xsi:nil="true" />
  </RuleDetails>
</AirFareInfo>

Please suggest how it can be done keeping performance in mind.

A: This is a fully working example.
You told us, that performance matters, so do not use scalar UDF!
Try it like this (next time it's your job to create a (reduced!!!) MCVE:
CREATE DATABASE testDB;
GO
USE testDB;
GO
CREATE TABLE Booking(BookingID INT CONSTRAINT PK_Booking PRIMARY KEY
                    ,SomeBookingData VARCHAR(100));
INSERT INTO Booking VALUES(1,'Booking 1'),(2,'Booking 2');

CREATE TABLE BookingInfo(BookingID INT CONSTRAINT FK_BookingInfo_BookingID FOREIGN KEY REFERENCES Booking(BookingID)
                        ,SomeOtherInfo VARCHAR(100)
                        ,FareDetails XML);
INSERT INTO BookingInfo VALUES
 (1,'First row for ID=1, returns AP,AP'
 ,N'<AirFareInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" IPFA="false">
  <PTSDPFS>
    <PTSD IO="false">
      <FBC>AP</FBC>
    </PTSD>
  </PTSDPFS>
  <PTSDPFS>
    <PTSD IO="false">
      <FBC>AP</FBC>
    </PTSD>
  </PTSDPFS>
</AirFareInfo>')
,(1,'Second row for ID=1, returns XY,MN'
 ,N'<AirFareInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" IPFA="false">
  <PTSDPFS>
    <PTSD IO="false">
      <FBC>XY</FBC>
    </PTSD>
  </PTSDPFS>
  <PTSDPFS>
    <PTSD IO="false">
      <FBC>MN</FBC>
    </PTSD>
  </PTSDPFS>
</AirFareInfo>')
,(2,'row with ID=2, returns AA,BB'
 ,N'<AirFareInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" IPFA="false">
  <PTSDPFS>
    <PTSD IO="false">
      <FBC>AA</FBC>
    </PTSD>
  </PTSDPFS>
  <PTSDPFS>
    <PTSD IO="false">
      <FBC>BB</FBC>
    </PTSD>
  </PTSDPFS>
</AirFareInfo>');
GO

--This is the function. It returns as table and is fully inlined (no BEGIN...END!)
CREATE FUNCTION dbo.CreateBookingInfoCSV(@BookingID INT)
RETURNS TABLE
AS
RETURN
SELECT STUFF(
(
    SELECT ','+REPLACE(FareDetails.query(N'data(/AirFareInfo/PTSDPFS/PTSD/FBC)').value(N'.',N'nvarchar(max)'),' ',',')
    FROM BookingInfo AS bi
    WHERE bi.BookingID=@BookingID
    FOR XML PATH('')
),1,1,'') AS BookingInfoCSV;
GO

--Hint the trick with XQuery data() function will break, if your values contain blanks!
--The following SELECT calls all rows from Booking-table and gets the fitting details
SELECT b.BookingID
      ,b.SomeBookingData
      ,A.BookingInfoCSV
FROM Booking AS b
OUTER APPLY dbo.CreateBookingInfoCSV(b.BookingID) AS A;
GO

--Clean up (carefull with real data!)
USE master;
GO
DROP DATABASE testDB;

--The result
BookingID   SomeBookingData BookingInfoCSV
1           Booking 1       AP,AP,XY,MN
2           Booking 2       AA,BB


text:
Q: How to send @user.password by email for "Forgot password?" if using has_secure_password I'm trying to send an email through ActionMailer for users who forget their passwords. They type in their email and press submit, and it's supposed to send them an email with their password in the email. However, since I have has_secure_password I'm guessing that the password_digest is not allowing me to extract the password. I received an email that said:
Your login information:

Email: edmai@syr.edu

Password:

So it looks like rails is doing something to stop me from taking out the password. Here are my files:
email template:
Dear <%= @user.name %>,

    You recently made a request for a lost password. Please remember to keep your passwords recorded in a safe place.

    Your login information:

    Email: <%= @user.email %>

    Password: <%= @user.password %>

    Sincerely,

    Pholder Staff

user model
class User < ActiveRecord::Base

has_secure_password
attr_accessible :email, :name, :password, :password_confirmation, :profilepic
validates_presence_of :password, :on => :create

let me know if you need any more of my files

A: has_secure_password hashes your users password with bcrypt. This is so that a plain text password is not stored in your database (something which should never, ever happen). Some info on the method is here: http://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html
Like @apneadiving said, you need to reset the password and send the user a password reset link.
Watch these two Railscasts in order, they might help you out:

*

*http://railscasts.com/episodes/270-authentication-in-rails-3-1

*http://railscasts.com/episodes/274-remember-me-reset-password


text:
Q: Why spring transaction management's propagation level `REQURIES_NEW` not working? I am bit confused about spring transaction management's propagation mechanism specially about REQUIRES_NEW. As documentation here

PROPAGATION_REQUIRES_NEW, in contrast to PROPAGATION_REQUIRED, uses a completely independent transaction for each affected transaction scope. In that case, the underlying physical transactions are different and hence can commit or roll back independently, with an outer transaction not affected by an inner transaction's rollback status.

What I understood is when any method annotated with @Transactional(propagation=Propagation.REQUIRES_NEW), always new physical transaction is created and if it rollbacks it will not effect outer transaction.
Now I have below scenario where I am calling two transactional methods one is with default propagation level and other with requires new propagation. Now when I throw RuntimeException from second method It should rollback only that transaction instead It is rolling back the whole transaction. Below is the sample code.
@Service
public class UserService {

@Autowired
private UserRepository userRepository;

@Transactional
public void firstTransaction() {
    User user = new User();
    user.setFirstname("Monica");
    user.setLastname("Galler");

    userRepository.save(user);

    secondTransaction();
}

@Transactional(propagation=Propagation.REQUIRES_NEW)
public void secondTransaction() {
    User user = new User();
    user.setFirstname("Rachel");
    user.setLastname("Green");

    userRepository.save(user);

    throw new RuntimeException("thown exception!!");
}

}

and class from where I am calling this method
@Component
public class TxHandler {

@Autowired
private UserService userService;

public void handleTransaction() {
    userService.firstTransaction();
}

}

Please let me know am I missing something here ?
Here are the logs printed for transaction manager
2018-06-17 13:37:52.553 DEBUG 903 --- [           main] o.s.orm.jpa.JpaTransactionManager        : Creating new transaction with name [com.example.SpringTutorial.service.UserService.firstTransaction]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2018-06-17 13:37:52.554 DEBUG 903 --- [           main] o.s.orm.jpa.JpaTransactionManager        : Opened new EntityManager [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for JPA transaction
2018-06-17 13:37:52.561 DEBUG 903 --- [           main] o.s.orm.jpa.JpaTransactionManager        : Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@2e766822]
2018-06-17 13:37:52.582 DEBUG 903 --- [           main] o.s.orm.jpa.JpaTransactionManager        : Found thread-bound EntityManager [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for JPA transaction
2018-06-17 13:37:52.582 DEBUG 903 --- [           main] o.s.orm.jpa.JpaTransactionManager        : Participating in existing transaction
2018-06-17 13:37:52.674 DEBUG 903 --- [           main] o.s.orm.jpa.JpaTransactionManager        : Found thread-bound EntityManager [SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.example.SpringTutorial.entity.User#26]],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=1} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for JPA transaction
2018-06-17 13:37:52.674 DEBUG 903 --- [           main] o.s.orm.jpa.JpaTransactionManager        : Participating in existing transaction
2018-06-17 13:37:52.680 DEBUG 903 --- [           main] o.s.orm.jpa.JpaTransactionManager        : Initiating transaction rollback
2018-06-17 13:37:52.680 DEBUG 903 --- [           main] o.s.orm.jpa.JpaTransactionManager        : Rolling back JPA transaction on EntityManager [SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.example.SpringTutorial.entity.User#26], EntityKey[com.example.SpringTutorial.entity.User#27]],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=2} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
2018-06-17 13:37:52.683 DEBUG 903 --- [           main] o.s.orm.jpa.JpaTransactionManager        : Closing JPA EntityManager [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] after transaction


text:
Q: What does it mean for a sequence of sheaves to be exact Let $F, G, H$ be sheaves on a topological space $X$, and let $$F \xrightarrow{\alpha} G \xrightarrow{\beta} H $$ be morphisms of sheaves.  By definition,  $\textrm{Ker } \beta$ is the subpresheaf $U \mapsto \textrm{Ker}(\beta(U))$ of $G$, and it is in fact a sheaf.  If $O$ is the subpresheaf of $G$ given by $U \mapsto \textrm{Image}(\alpha(U))$, then $\textrm{Im } \alpha$ is defined to be any sheafification of $O$.  Let $\theta: O \rightarrow \textrm{Im } \alpha$ be a morphism of presheaves such that the pair $(\textrm{Im } \alpha, \theta)$ satisfies the universal property for sheafification.
I've seen the definition that the sequence above is exact if $\textrm{Ker } \beta = \textrm{Im } \alpha$, but I'm confused as to what this really means.  I am aware that the sheafification $(\textrm{Im } \alpha, \theta)$ may be chosen to literally be a subsheaf of $G$ (from the fact that $\theta$ preserves an isomorphism on the stalks, and a morphism of sheaves is injective on the sections if and only if it is injective on the stalks).  But even so, any sheafification of $O$ which is a subsheaf of $G$ need not be uniquely determined (as far as I can see).  Can anyone clarify what it means for a sequence of sheaves to be exact?

A: The image of a map is defined to be the sheafification of $Im^{pre}$. By the universal property of the sheafification this sheaf is unique up to unique isomorphism. Now as you already mentioned there is a natural injection $i: Im(\alpha) \rightarrow G$. We can now define the above sequence to be exact if $i(Im(\alpha))=Ker(\beta)$.
Edit: To see why this works assume the two sheafs $Im(\alpha)$ and $Im(\alpha)^{'}$ are both sheafifications of the sheaf $Im^{pre}(\alpha)$(with natural maps $\theta$ and $\theta ^{'}$). If $j:Im^{pre}(\alpha)\rightarrow G$ is the inclusion map and $\phi: Im(\alpha)) \rightarrow Im(\alpha))'$ the unique isomprhism, then $i \theta=j$. But since $i^{'} \theta ^{'}=j$ and $\theta ^{'}=\phi \theta$, by uniqueness we have $i{'} \phi=i$. Thus $i(Im(\alpha))=i'(Im(\alpha '))$.

A: Let's take an example, a piece of the Poincare sequence on a smooth manifold $M$
$$ \Omega^k_M \overset{d_k}{\to}\Omega^{k+1}_M \overset{d_{k+1}}{\to} \Omega^{k+2}_M$$
It is exact at the term $\Omega^{k+1}(M)$. This means two things:
First, $d_{k+1}\circ d_k=0$.
Second, for every open subset $U$ of $M$ and $\omega \in \Omega^{k+1}_M(U)$ a $k+1$-differential form with $d \omega = 0$, there exists a covering $V_i$ of $U$ and $\eta_i \in \Omega^k_M(V_i)$ so that
$d_k(\eta_i)= \omega_{|V_i}$ ( any closed form is ${\it locally}$ exact).


text:
Q: create .deb package by python setup.py i want create .deb package for my python program. i create setup.py and it works well, but when I want to create a debian package using setup.py and stdeb I get an error.
the commands I use to create .deb:
first:
python3.4 setup.py sdist

then:
python3.4 setup.py --command-packages=stdeb.command bdist_deb

but get error
dpkg-buildpackage: warning: build dependencies/conflicts unsatisfied;  aborting
dpkg-buildpackage: warning: (Use -d flag to override.)

Traceback (most recent call last):
File "setup.py", line 19, in <module>
install_requires=['setproctitle', 'psycopg2', 'psutil']
File "/usr/lib/python3.4/distutils/core.py", line 148, in setup
dist.run_commands()
File "/usr/lib/python3.4/distutils/dist.py", line 955, in run_commands
self.run_command(cmd)
File "/usr/lib/python3.4/distutils/dist.py", line 974, in run_command
cmd_obj.run()
File "/usr/local/lib/python3.4/dist-packages/stdeb/command/bdist_deb.py", line 48, in run
util.process_command(syscmd,cwd=target_dirs[0])
File "/usr/local/lib/python3.4/dist-packages/stdeb/util.py", line 183, in process_command
check_call(args, cwd=cwd)
File "/usr/local/lib/python3.4/dist-packages/stdeb/util.py", line 46, in check_call
raise CalledProcessError(retcode)
stdeb.util.CalledProcessError: 3

I use these options in setup.py:
packages=['myapp', 'myapp.models', 'myapp.classes', 'myapp.functions'],
package_data={'': ['myapp.conf']},
data_files=[('/usr/local/bin/', ['myapp/myapp_run.py']),
            ('/usr/local/etc/myapp', ['myapp/myapp.conf'])],
install_requires=['setproctitle', 'psycopg2', 'psutil']

and my project directory is like:
|  setup.py
|- myapp
        |  __init__.py
        |- classes
                  | __init.py
                  | ...
        | ...
        | myapp_run.py
        | myapp.conf

A: first try running this:
    apt-get install python3-stdeb fakeroot python-all
followed by:
python3.4 setup.py sdist

reference link: Use stdeb to make Debian packages for a Python package

A: check out debpackager, its a cli tool for creating deb packages out of any project, including python projects.


text:
Q: How to get values selectively from python dictionary I read a JSON file and created a dictionary and trying to make a properties file with key=value format with just couple of attributes (found and location) from it. From below dictionary, I need to create a file with content
found=bike.tar.gz
location=china

Content of the dictionary below, it will be in same format and will have only one "found" item always.
>>> pprint(zdict)
{
 'found': {
    'bike.tar.gz': {
           'imported': False,
           'used': True,
           'location': 'china'
            }
     }
}

I tried:
>>> dict(list(zdict.values())[0]).keys()
dict_keys(['bike.tar.gz'])

couldn't move beyond this.

A: The complex part is to get the key value, since it's a special case: there is one key as a value of the dictionary. So convert to list and take the first element.
Then use this key to find the location.
zdict = {
 'found': {
    'bike.tar.gz': {
           'imported': False,
           'used': True,
           'location': 'china'
            }
     }
}

bike = list(zdict["found"])[0]
print("found={}".format(bike))
print("location={}".format(zdict["found"][bike]["location"]))

prints:
found=bike.tar.gz
location=china

but this format is probably designed to have several dicts under the "found" key, so use a loop to print them all (also works with your example and avoids to crash if the list is empty):
for bike,items in zdict["found"].items():
    print("found={}".format(bike))
    print("location={}".format(items["location"]))


text:
Q: Miss calculation of change value from scrape data Im doing a scrape project from api url, scraping value(datetime,open,close,high,low) and write to mysql database
code
startTime_source = "https://api.binance.com/api/v1/klinesstartTime=0&symbol=btcusdt"&interval=1h&limit=1000"
startTime_source_get = requests.get(startTime_source)

startTime_source_json = json.loads(startTime_source_get.text)

#timestamp now
import time;
tsnw = time.time()*1000.0
tsnw = (int(tsnw))

for y in range(startTime_source_json[0][0],tsnw,3600000000): #scrape data from start to end

   data = "https://api.binance.com/api/v1/klines?startTime=" + str(y) + "&symbol="+coin[x]+"&interval=1h&limit=1000"
   data_get = requests.get(data)

   #convert class response to json list
   data_list = json.loads(data_get.text)

   #loop for convert timestamp to datetime
   for z in range(0,len(data_list)):

   #delete all feature except dt_ which is after id=5
   del data_list[z][5:]

   #assign dt_ as timestamp which is id=1
   timestamp = data_list[z][0]

   #convert msec to sec
   timestamp = time.localtime(timestamp / 1000.0)

   #convert timestamp to datetime
   dt = time.strftime("%Y-%m-%d %H:%M:%S", timestamp)

   #replace value timestamp as dt
   data_list[z][0] = dt

   #seperate each feature
   dt_ = [data_list[z][0]] #datetime
   open_ = [data_list[z][1]] #open price
   close_ = [data_list[z][4]] #close price
   high_ = [data_list[z][2]] #high price
   low_ = [data_list[z][3]] #low price

   #cal the value of change and write to mysql database
   num_1 = float(data_list[z-1][4])
   num_2 = float(data_list[z][4])

   #calculator formula
   cal_change = ((num_2 - num_1) / num_1)*100
   #round for 2 digit decimal ex 0.00
   change_ = [round(cal_change,2)]

   data_to_insert = [dt_+open_+close_+high_+low_+change_]

   try:
       #insert value
       write_data = "INSERT INTO" + " " + coin[x] + "(dt_,open_,close_,high_,low_,change_) VALUES (%s,%s,%s,%s,%s,%s)"
       mycursor.executemany(write_data,data_to_insert)

   #it show error for multiple times
   except mysql.connector.Error as err :
       if err.sqlstate == "23000":
          print('error')
          pass

The problem is multiple rows has wrong calculation, example below dttime 2020-03-10 18:00:00 and the change value should be 0.33 not -18.21, why is that? help please, thank you.


text:
Q: Tangent line $l$ through $(a,a^2)$ on $y=x^2 $, to make the area $S$ enclosed by $l$ and $y=-x^2+4x-1$ smallest. Find $l$ and $S$
Draw a tangent line $l$ through $(a,a^2)$ on $y=x^2 $, to make the area $S$ enclosed by $l$ and $y=-x^2+4x-1$ smallest. Find $l$ and $S$.

I was doing this:
$l$ : $y-a^2=2a(x-a)\Rightarrow y=2ax-a^2$
Supose $l$ intersect  $y=-x^2+4x-1$ at $(x_1,y_1)$ and $(x_2,y_2)$. Then
$$S=\int_{x_1}^{x_2}\Big(-x^2+4x-1-(2ax-a^2)\Big) dx$$
But $x_{1,2}$ is too complex make $S$ more complex. So I don't how to simply it also I was wondering is there more convenient way to do this problem.

A: Since $x_1$ and $x_2$ are solution to $$x^2+x(2a-4)+1-a^2 =0$$ we have (by Vieta)
$$ x_1+x_2 = 4-2a\;\;\;\; {\rm and}\;\;\;\;\;x_1x_2 = 1-a^2\;\;\;\;\;{\rm and}\;\;\;\;\;x_2-x_1=2\sqrt{2a^2-4a+3}$$
So
$$
\begin{eqnarray}
S(a)&=&\Big|\int_{x_1}^{x_2}(x^2+x(2a-4)+1-a^2) dx\Big|\\
 &=& \Big|{x^3\over 3}+x^2(a-2)+(1-a^2)x\Big{|}_{x_1}^{x_2}\;\;\Big|\\
 &=& \Big|(x_2-x_1)\Big({x_1^2+x_1x_2+x_2^2\over 3}+(x_2+x_1)(a-2)+(1-a^2) \Big)\Big|\\
&=& \Big|2\sqrt{2a^2-4a+3}\cdot {-4a^2+8a-6\over 3}\Big| \\
&=& 4\sqrt{2a^2-4a+3}\cdot {2a^2-4a+3\over 3}\\
\end{eqnarray}
$$
Put $t = \sqrt{2a^2-4a+3}\geq 1$ for all $a$.  So $$S = {4\over 3}t^3\geq {4\over 3}$$
So $S_{\min} = 4/3$

A: You solve the equation:
$$y=-x^2+4x-1=2ax-a^2=l \iff \\
x^2+2(a-2)x+1-a^2=0 \Rightarrow \\
x_1=2-a-\sqrt{2a^2-4a+3}; \ \ \ x_2=2-a+\sqrt{2a^2-4a+3}.$$
So:
$$\begin{align}x_1+x_2&=4-2a; \\
x_2-x_1&=2\sqrt{2a^2-4a+3};\\
x_1x_2&=1-a^2.\end{align}$$
The required area is:
$$S(a)=\int_{x_1}^{x_2}-x^2+4x-1-(2ax-a^2) dx=\\
\left(-\frac{x^3}{3}+(2-a)x^2+(a^2-1)x\right)\big{|}_{x_1}^{x_2}=\\
-\frac{x_2^3-x_1^3}{3}+(2-a)(x_2^2-x_1^2)+(a^2-1)(x_2-x_1)=\\
-\frac{(x_2-x_1)((x_2+x_1)^2-x_1x_2)}{3}+(2-a)(x_2-x_1)(x_2+x_1)+(a^2-1)(x_2-x_1)=\\
(x_2-x_1)\left[-\frac13((4-2a)^2-(1-a^2))+(2-a)(4-2a)+(a^2-1)\right]=\\
2\sqrt{2a^2-4a+3}\left[-\frac13(15-16a+5a^2)+8-8a+2a^2+a^2-1\right]=\\
2\sqrt{2a^2-4a+3}\left[\frac43a^2-\frac{8}{3}a+2\right].$$
To minimize this area function, you can set its derivative equal to zero:
$$S'(a)=\frac{4a-4}{\sqrt{2a^2-4a+3}}\left(\frac43a^2-\frac83a+2\right)+2\sqrt{2a^2-4a+3}\left(\frac83a-\frac83\right)=0 \Rightarrow \\
(4a-4)\left(\frac43a^2-\frac83a+2\right)+2(2a^2-4a+3)\left(\frac83a-\frac83\right)=0 \Rightarrow \\
(a-1)\left(\frac{16}{3}a^2-\frac{32}{3}a+8+\frac{32}{3}a^2-\frac{64}{3}a+16\right)=0 \Rightarrow \\
(a-1)(16a^2-32a+24)=0 \Rightarrow \\
8(a-1)(2a^2-4a+3)=0 \Rightarrow \\
a=1; \\
S(1)=\frac43.$$
Here is the graph (with $l=2x-1$):
$\hspace{2cm}$


text:
Q: firebase realtime database mark data as read In My project I want user to read a data from firebase realtime data at same time he will mark data as locked until he finishes some operations, during this time other users cannot read this data.
Anther scenario if the lock is not possible is once he read he at same time write some data to indicate that data as locked. If anther user read this data he knows its locked.
I am not sure if this is possible some how in fire base.
Is there any Idea how to use this with firebase realtime db.

A: There isn't any out-of-the-box solution for your use case (set a lock that restrict read/write access rights) but you could easily built such a system. Since you didn't indicate which language you are using, I describe below a generic approach with links corresponding to the JS SDK:

*

*You first define a Security Rule that allows users to read/write to a database node under two conditions: (a) A specific "readWriteLock" field (i.e. a sub-node) has the value "all" -> All users can read from & write to the DB node, OR (b) The "readWriteLock" field has a value corresponding to the uid of a specific user -> Only the user with this uid can read from & write to the DB node.

*Then, when you want to lock a specific DB node, you first need to write to the desired document in order to set the value of the "readWriteLock" field to the user's uid. This should be done in a Transaction.

*Then you fetch the document (only the user who locked it can read it)

*Then, when the "operations" you mention ("mark data as locked until he finishes some operations") are finished, you set back the value of the "readWriteLock" field to "all"


text:
Q: Password protect Grub2, but still allow normal boot I have seen this link  , but I don't have grub.conf in the first place. His situation is the inverse from mine though.
This link  explains quite a fair bit on Grub2, but I am still clueless as to how to do it. I am not technical-savvy enough I guess..
I am using LinuxMint 16.
Everything that I have tried so far still requires a password for booting. I want a password to be requested only when a user is trying to edit the boot options.

A: just add "--unrestricted" to the "class" line in /etc/grub.d/10_linux as described here:  https://bugzilla.redhat.com/show_bug.cgi?id=840204#c53
 then regenerate your grub config with "grub-mkconfig -o /boot/grub/grub.cfg" or whatever is appropriate for your install.
if you already have your password setup prior to this you will now have the grub config you were seeking.This seems to be an issue/regression with the upstream grub project and not so much fedora as i'm using arch and i had the same problem. neither the arch wiki nor the grub docs really address this situation, as far as i could tell.
I'm guessing i'll need to backup my /etc/grub.d/10_linux and/or set it as immutable so that maybe it will break grub updates as a reminder as to what i've done, until this is fixed upstream.

A: You should not add but replace the --users with the --unrestricted:
sudo vim /etc/grub.d/10_linux +127
   echo "menuentry '$(echo "$title" | grub_quote)' ${CLASS} --unrestricted  '' \$menuentry_id_option 'gnulinux-$version-$type-$boot_device_id' {" | sed "s/^/$submenu_indentation/"
  else
      echo "menuentry '$(echo "$os" | grub_quote)' ${CLASS} --unrestricted  '' \$menuentry_id_option 'gnulinux-simple-$boot_device_id' {" | sed "s/^/$submenu_indentation/"

sudo update-grub

**kubuntu14.04 example shown


text:
Q: How to accept only number in the input field using js How to make the input box accept only numbers in the input field using js event listener.
  <form action="#">
     <label for="value">Value:</label>
     <input type="text" name="value" id="value" />
     <button type="submit">Convert</button>
     <button type="reset">Clear</button>
  </form>

<script>
    form.addEventListener(`submit`, function(event){
        event.preventDefault();
    });
</script>

A: You can parse the input to a number and then check if it is a number or something else like NaN.
if(typeof parseInt(input) ==="number"){
  console.log("number!");
}

Please note that anyone can bypass this using the dev tools so don't forget to implemnt server-side validation.(Thx for the tip @samathingamajig)


text:
Q: FragmentManager Showing Error in android studio.what i did wrong here? public class MainActivity extends AppCompatActivity implements Communicator{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void respond(String data) {

        FragmentManager manager=getFragmentManager();
        FragmentB f2=manager.findFragmentById(R.id.fragment2);
        f2.changetext(data);

    }
}

A: You need to use getSupportFragmentManager() in your code, not getFragmentManager() - see here for more details.
OR
Use getSupportFragmentManager(), or change the import for FragmentManager from what you have (android.support.v4.app.FragmentManager) to android.app.FragmentManager.

A: When your Activity extends AppCompatActivity, which in turn extends FragmentActivity, you have to use getSupportFragmentManager() instead of getFragmentManager() as stated here.


text:
Q: How to add Javascript addEventListener on window scroll So, I have a nav that when I hover the icon, shows/hide, which is working great! Now, I want to hide the menu when the user scrolls down the widown, then the show/hide on hover functionality takes place again. Below is my working code:
byClass('nav-toggle')[0].addEventListener('mouseover', showNav);
byClass('nav-wrap')[0].addEventListener('mouseleave', hideNav);

I try to add something like this:
  byClass('nav-wrap')[0].addEventListener('scroll', hideNav);

.. but it didn't work. I guess its because I have to specify that I want to hide when the "window" is scrolled down?
Any help would be very appreciated.

A: You have to listen for scroll start and hide the nav. And you also have to know when user stops scrolling. There is no separate event for that, so we can use timeout to show your nav in 150 ms if the scroll has finished.
var timer = null;
window.addEventListener('scroll', function() {
    if(timer !== null) {
        clearTimeout(timer);
    } else {
        hideNav();
        timer = setTimeout(function() {
          showNav();
        }, 150);
    }
}, false);

A: This is a sample to hide menu on scroll

var content = document.getElementById('two');

content.addEventListener('scroll', hideMenu);

function hideMenu()
{
    var menu = document.getElementById('one');
    menu.style.display = 'none';
}
section {
    width: 80%;
    height: 200px;
    background: aqua;
    margin: auto;
    padding: 10px;
}
div#one {
    width: 15%;
    height: 200px;
    background: red;
    float: left;
}
div#two {
    height: 200px;
    background: black;
    color: white;
    overflow-y: scroll;
}

 SCROLL TO HIDE MENU
 shows/hide, which is working great! Now, I want to hide the menu when the user scrolls down the widown, then the show/hide on hover functionality takes place again. Below is my working code:

byClass('nav-toggle')[0].addEventListener('mouseover', showNav);
byClass('nav-wrap')[0].addEventListener('mouseleave', hideNav);
I try to add something like this:

  byClass('nav-wrap')[0].addEventListener('scroll', hideNav);
.. but it didn't work. I guess its because I have to specify that I want to hide when the "window" is scrolled down?

Any help would be very appreciated.So, I have a nav that when I hover the icon, shows/hide, which is working great! Now, I want to hide the menu when the user scrolls down the widown, then the show/hide on hover functionality takes place again. Below is my working code:

byClass('nav-toggle')[0].addEventListener('mouseover', showNav);
byClass('nav-wrap')[0].addEventListener('mouseleave', hideNav);
I try to add something like this:

  byClass('nav-wrap')[0].addEventListener('scroll', hideNav);
.. but it didn't work. I guess its because I have to specify that I want to hide when the "window" is scrolled down?

Any help would be very appreciated.So, I have a nav that when I hover the icon, shows/hide, which is working great! Now, I want to hide the menu when the user scrolls down the widown, then the show/hide on hover functionality takes place again. Below is my working code:

byClass('nav-toggle')[0].addEventListener('mouseover', showNav);
byClass('nav-wrap')[0].addEventListener('mouseleave', hideNav);
I try to add something like this:

  byClass('nav-wrap')[0].addEventListener('scroll', hideNav);
.. but it didn't work. I guess its because I have to specify that I want to hide when the "window" is scrolled down?

Any help would be very appreciated.So, I have a nav that when I hover the icon, shows/hide, which is working great! Now, I want to hide the menu when the user scrolls down the widown, then the show/hide on hover functionality takes place again. Below is my working code:

byClass('nav-toggle')[0].addEventListener('mouseover', showNav);
byClass('nav-wrap')[0].addEventListener('mouseleave', hideNav);
I try to add something like this:

  byClass('nav-wrap')[0].addEventListener('scroll', hideNav);
.. but it didn't work. I guess its because I have to specify that I want to hide when the "window" is scrolled down?

Any help would be very appreciated.


text:
Q: Double linked List java reverse function Error My double link list is have a problem as the tail is being output wrong by the console! i have narrowed it down to what i think is an error in my reverse function! if anyone could take a look and give me some guidance on what i am doing wrong or how i can setup my tail so it reports the right variable! Thank you very much! probably a simple mistake i missed like normal!
import java.util.*;
import java.lang.*;
public class DLList<E> implements List<E> {
    //Your implementation
    private DNode<E> head;
    private DNode<E> tail;
    private int size = 0;

    public DLList(E item){
        tail = head = new DNode<E>(item);
        size++;

    }

    public DLList(){
        head = tail = null;
        size = 0;
    }

  /** Remove all contents from the list, so it is once again
      empty. */
  public void clear(){
    head = tail = null;
    size = 0;
  }

  /** Insert an element at the given location.
    * allows you to insert after the tail
    * @param item The element to be inserted.
    */
    public void insert(int index, E item){
    if(index < 0 || index > size){
        throw new IndexOutOfBoundsException(Integer.toString(index));
    }
    if(index == 0) {
        addFirst(item);

    }
    else if(index == size){
        add(item);
    }
    else{
        DNode<E> node = getNode(index -1);
        addAfter(node, item);
    }

    }

    public void addFirst(E item){
        if(size == 0) {
            tail = head = new DNode<E>(item);
        }
        else{
            DNode<E> newNode = new DNode<E>(item, null, head);
            head.setPrev(newNode);
            head = newNode;
        }
        size++;
    }

    public void addAfter(DNode<E> node, E item){
        DNode<E> newNode = new DNode<E>(item, node, node.getNext());
        node.getNext().setPrev(newNode);
        node.setNext(newNode);
        size++;
    }

  /** Append an element at the end of the list.
   *  @param item The element to be appended.
   */
  public void add(E item){
      if(size == 0){
          tail = head = new DNode<E>(item);
      }
      else{
          DNode<E> newNode = new DNode<E>(item, tail, null);
          tail.setNext(newNode);
          tail = newNode;
      }
      size++;
  }

  /**
  * Remove the  element at the given location.

  */
  public void remove(int index){
    if(index < 0 || index > size){
        throw new IndexOutOfBoundsException(Integer.toString(index));
    }
    if(index == 0) {
        removeFirst();
    }
    else if(index == size){
        removeLast();
    }
    else{
        DNode<E> node = getNode(index -1);
        removeAfter(node);
    }
  }

    public void removeFirst(){
        /*
    if(head == null){
        throw new NoSuchElementException("List is empty");
    }
    else if(head == tail){
        head = tail = null;
    }
    else{
        head= head.getNext();
        head.prev(item) = null;
    }

    */

    //setPrev
    DNode<E> temp = head;
    head = head.getNext();

    }

    public void removeLast(){
        /*
        if(head == null) {
            throw new NoSuchElementException("List is empty");
        }
        else if(head == tail){
            //RemoveFirst code
        }
        else{
            tail = tail.prev();
            tail.getNext() = null;
        }
        size--;
        */
        DNode<E> temp = tail;
        tail =  tail.getNext();
    }

  public void removeAfter(DNode<E> node){
      /*
    if(size == 0) {
            throw new IndexOutOfBoundsException(Integer.toString(index));
        }
        else if(head == tail){
            heal = tail = null;
        }
        else{
            head = head.getNext();
            head.prev = null;
        }
        size--;
        */

    DNode<E> temp = node.getNext();
  //Make sure value is  valid
  if (temp != null)
  {
    node.setNext(temp.getNext());
    size--;

  }
  }

    public DNode<E> getNode(int index){
      if(index < 0 || index > size){
        throw new IndexOutOfBoundsException(Integer.toString(index));
    }
    DNode<E> node = head;
    for(int i = 0; i < index; i++) {
        node = node.getNext();
    }
      return node;
  }

  /**
  * Get the element in the position to one step left.
  * @return element in the node to the left of the node at the index,
  * null if at the head.
  */
  public E prev(int index){

      if (index < 0 || index >= size) {
    throw new IndexOutOfBoundsException(Integer.toString(index));
  }

  DNode<E> node = getNode(index-1);
      return node.getElement();
  }

  /** Get the element in the position one step right.
  * @return the element in the node to the right of
  * the node at the index, null if at the end.
  */
  public E next(int index){
     if (index < 0 || index >= size) {
    throw new
        IndexOutOfBoundsException(Integer.toString(index));
  }
  DNode<E> node = getNode(index+1);
      return node.getElement();
  }

  /** @return The number of elements in the list. */
  public int length(){
      return size;
  }

   /** Turn the contents of the Nodes to a string in order from head to end.
   * @return The String representation of the
   * elements in the list from head to end.
   */
   //Copy and past prev but change symbol!
   public String toString(){
        DNode<E> node = head;
       String result = "";
       while(node != null) {
           result = result + node.getElement().toString();
           if(node.getNext() != null){
               result = result + " <==> ";
           }
           node = node.getNext();
       }
       return result;
   }

   /** Reverse the content of the list.
    * if list is A => B => C it becomes C => B => A
    */
  public void reverse(){
      /*
      head.prev = head.getNext();
      head.getNext() = null;

      while(head.prev != null){
          head = head.prev;
          DNode<E> temp = head.getNext();
          head.getNext() = head.prev;
          head.prev = temp;
      }
      */
       DNode<E> node = head;
      if(node == null || node.getNext() == null){
          return;

      }

      DNode<E> prev = node.getNext();
      DNode<E> curr = prev.getNext();
        prev.setNext(node);
        node.setNext(null);
      while (curr != null) {
         DNode<E> next = curr.getNext();
        curr.setNext(prev);
        prev = curr;
        curr = next;
      }
      head = prev;

  }

  public E setprev(int index){
      if (index < 0 || index >= size) {
    throw new
        IndexOutOfBoundsException(Integer.toString(index));
  }
  DNode<E> node = getNode(index-1);
        return node.getElement();
  }

   /** @return The  element at given position. */
   public E getValue(int index){
       if (index < 0 || index >= size) {
        throw new
            IndexOutOfBoundsException(Integer.toString(index));
      }
      DNode<E> node = getNode(index);
      return node.getElement();
   }

   /**inserts the given list after the given index
   *Check if getNext is null
   *if(temp != null){
       (then set prev)
       {
 else{
       set tail list last value
   }
*/
    public void insertList (DLList list, int index){
        if (list.getHead() != null && (index >= 0 && index <size)){

            DNode<E> head = list.getHead();
            DNode<E> tail = list.getLast();

            DNode<E> position = getNode(index);
            DNode<E> temp= position.getNext();

            position.setNext(head);
            tail.setNext(temp);

            size = list.length()+ size;
        }

    }

    public DNode<E> getHead(){
        return head;
    }
    public DNode<E> getLast(){
        return tail;
    }

}

A: Got this code from geeks for geeks you just need to modify it for your variable names and class names for the node.
 void reverse() {
    Node temp = null;
    Node current = head;

    /* swap next and prev for all nodes of
     doubly linked list */
    while (current != null) {
        temp = current.prev;
        current.prev = current.next;
        current.next = temp;
        current = current.prev;
    }

    /* Before changing head, check for the cases like empty
     list and list with only one node */
    if (temp != null) {
        head = temp.prev;
    }
}

If you have any questions please feel free to ask.


text:
Q: Which datatypes to use with CoreData/SQL to minimize conversions The folowing problem:
I have a mobile User Interface that for examples lets the user enter values like Date,Name,Age,Height,Distance.
I want to store these values in a Core Database.
AS I want to be able to make calculations with these values it probably makes sense to use the appropiate values in CoreData
like
Date: NSDate
Name: String
Age: Int16
Height: Double
Distance: Double

Now I also want to store these data in a remote SQL Database and so far I always have used varchar(100) fields.
Which now becomes a problem as I start to have to do a lot of really ugly conversions like
let entry =  CoreDataObjectFromSQLNetwork()
let entry.age = NSNumber(integer: (dictionary["age"] as! String).toInt()!)
let entry.height = NSNumber(double: (dictionary["height"] as! String).toDouble()!)

So what is the best way or which types would you use dealing with Swift/CoreData/MySQL and you need like the typical types (String, Date, Integer, Double, Boolean)

A: The best way is to use appropriate data types on both sides instead of just treating every possible data type as if it were a 100 character string. If that's not an option then you'll have to convert at some point.
If possible, the second-best way is to have your server API make appropriate conversions to/from varchar so that it actually provides numeric types to mobile clients. Your server will have a lot more CPU and electrical power than people's phones, so do the conversion there. Then just use the appropriate data types on the phones.
If that's not possible, well, you've kind of outlined your remaining option. You might be able to optimize things based on your projections of how much data there will be vs. how often you want to do numeric calculations on that data. You could convert all data to numeric types as soon as you receive it (which is what you describe). Or you could leave everything as strings and convert to numeric types only when you need to do a calculation. Which is best depends on your app. I'd prefer the former, but if there's lots of data and comparatively few calculations, that might not be best.


text:
Q: Cloning in Java class Person implements Cloneable {

    String firstName;

    public String getFirstName() {
        return firstName;
     }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public Person clone() throws CloneNotSupportedException {
            return (Person) super.clone();
        }
   }

    Person p1 = new Person();
    p1.setFirstName("P1 Sara");

    Person p3 = new Person();
    try {
        p3 = (Person) p1.clone();
    } catch (CloneNotSupportedException e) {
    }

    p3.setFirstName("cloned Sara");
    System.out.println("P3 : " + p3.getFirstName());
    System.out.println("P1: " + p1.getFirstName());

I have read that clone() method is actually a shallow copying.
So, I assumed that when the value of a field in P3 is changed, the one in P1 would change too.
But, that didn't happen.
What am I missing here?

A: clone() method is actually a shallow copying.
Here's what happens in your example:

*

*person1 has a reference to name. Let's call this reference A. reference A point to some place in the heap memory.

*After you copy person1 to person3, the name reference in person3 (let's call it reference B) points to the same place in the heap memory. But it is not the same reference. It's 2 different references pointing to the same place in the heap memory.

*When you call p3.setFirstName("cloned Sara"), reference B is updated to point to another place in the heap memory. There is no reason for that to change the value of where reference A is pointing.


text:
Q: Htaccess for redirecting escaped characters Somehow php urldecode is not working - hence looking for an alternate way through htaccess for redirecting
Which is the best way to redirect
Wrong url
http://www.example.com/index.php%3Foption%3Dcom_toys%26view%3Dproduct%26Itemid%3D2%26id%3D8%26vid%3D175

Htaccess Code - it somehow redirecting to 404 page
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+/)*index\.php\%3[fF]option\%3[dD]([^\ ]+)\ HTTP/
RewriteRule ^index\.php http://www.example.com/index.php?option=%2 [R=301,L]

by giving final output URL as
 http://www.example.com/index.php?option=com_toys%2526view%253Dproduct%2526Itemid%253D2%2526id%253D8%2526vid%253D175

Desired URL is
http://www.example.com/index.php?option=com_toys&view=product&Itemid=2&id=8&vid=175

A: Use this function to decode your url:
<?php
  function utf8_urldecode($str) {
    $str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($str));
    return html_entity_decode($str,null,'UTF-8');;
  }
$current_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$decode = utf8_urldecode($real_url);
echo $decode;
?>

Then you should have no problems at all.