text:
Q: The attachable property "ThemeDictionaries" was not found in type "ResourceDictionary" The following code is within app.xaml on a Windows Phone 8 application. It receives the error The attachable property "ThemeDictionaries" was not found in type "ResourceDictionary". Likewise, it does not set the background. I'm trying to set the background across the entire application with the option to change it using (App.Current.Resources["BackgroundImage"] as ImageBrush).ImageSource = imgSrc;  through c# code.
<Application
    x:Class="MyApp.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">
     <Application.Resources>
          <ResourceDictionary>
           <ResourceDictionary.ThemeDictionaries>
              <ResourceDictionary x:Key="Default">
                    <ImageBrush x:Key="BackgroundImage" ImageSource="Assets/BackgroundDefault.jpg" Stretch="UniformToFill" />
              </ResourceDictionary>
              <ResourceDictionary x:Key="Dark">
                    <ImageBrush x:Key="BackgroundImage" ImageSource="Assets/BackgroundDark.jpg" Stretch="UniformToFill" />
              </ResourceDictionary>
           </ResourceDictionary.ThemeDictionaries>
            <local:LocalizedStrings xmlns:local="clr-namespace:MyApp" x:Key="LocalizedStrings"/>
            <DataTemplate x:Key="SmallPanoramaTitle">
                <ContentPresenter>
                    <TextBlock Text="{Binding}" FontSize="25" Margin="0,30,0,0" />
                </ContentPresenter>
            </DataTemplate>
        </ResourceDictionary>
      </Application.Resources>
      <Application.ApplicationLifetimeObjects>
        <!--Required object that handles lifetime events for the application-->
        <shell:PhoneApplicationService
            Launching="Application_Launching" Closing="Application_Closing"
            Activated="Application_Activated" Deactivated="Application_Deactivated"/>
       </Application.ApplicationLifetimeObjects>
</Application>

A: ResourceDictionary.ThemeDictionaries not available in windows phone silverlight applications.
You can use the ThemeManager library to mange your themes in WP silverlight. This is an excellent library and its available in nuget also.
See this page to understand how to use ThemeManager . You can also load custom theme files


text:
Q: XCode Derived Data is being generated recursively because of script I try to create universal framework for Swift on XCode there I applied a aggregate framework script to "Build Phases -> Run Script".
It seems script is recursively in infinite loop and generate Derived Data recursively.
What I want is only to kill script so that derived data is generated no more. I clear and remove derived data, yet, it is generated again and allocate all the storage i have.
Here is a screenshot :
xcode-swift-objective-c-recursion-ios-universal-framework

redpajama_set_name: RedPajamaStackExchange


text:
Q: Form::password in Laravel Blade Templates I was trying to create a password field in the form in Laravel Blade templates but the output doesn't let me enter anything and it's not showing any placeholder either. The code doesn't cause any error.
Form:
{{ Form::open(array('class'=> 'forming')) }}
     {{ Form::text('username','Username',array('class' => 'insi')); }}<br>
     {{ Form::password('password',array('placeholder'=>'Password','class' => 'insi')); }}
{{ Form::close() }}

and the output is like that. Any help?

Second Input form is for password.

A: We are not seeing your generated HTML, but usually those problems are related to your HTML. For instance, you are using a CSS class 'insi', which may not letting you see the password characters.
To do a test remove/disable your CSS files from your main HTML and it probably will work fine.


text:
Q: What should I check/test when I want to generalize from a sample to the population? How do I ensure that I'm allowed to generalize findings from a sample to the population? So far, I'm only aware of the standard error. Is this (alone/itself) sufficient or even valid?
As the CI is connected to that, do I need both of them respectively is the standard error meaningless without its CI?
Are there other tests, quantities and so on?

A: Here is an example showing that you
could easily mistake a sample of size $n=100$
from $\mathsf{Gamma}(\mathrm{shape}=50,\mathrm{rate}=5)$ as
a sample from $\mathsf{Norm}(\mu = 10, \sigma=\sqrt{2}).$
Use R to sample $n=100$ observations at random
from the gamma distribution above, and summarize
the sample:
set.seed(2022)
x = rgamma(100, 50, 5)
summary(x);  sd(x)
    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   7.182   9.182   9.947   9.979  10.903  14.278
[1] 1.301298  # sample SD

A Shapiro-Wilk normality test fails to reject
the null hypothesis that the population has a
normal distribution (P-value $0.46 > 0.05 = 5\%.)$
shapiro.test(x)

        Shapiro-Wilk normality test

data:  x
W = 0.98733, p-value = 0.4602

Also, a normal probability plot (Q-Q plot) of the 100 observations is very nearly linear, as plots of a normal distribution should be.
qqnorm(x); qqline(x, col="blue")

Moreover, (falsely) assuming normality, a 95%
t confidence interval based on the sample
is $(9.72,\, 10.24),$ which includes $\mu=10.$
t.test(x)$conf.int
[1]  9.720308 10.236719
attr(,"conf.level")
[1] 0.95

Also, a 95% chi-squared CI for the population variance is $(1.3,\, 2.3),$ which includes
$\sigma^2 = 2.$
99*var(x)/qchisq(c(.975,.025),99)
[1] 1.305417 2.285194

Finally, a histogram of the 100 observations
seems consistent with a sample from
$\mathsf{Norm}(\mu=10,\sigma=\sqrt{2}).$
hist(x, prob=T, col="skyblue2")
 curve(dnorm(x, 10, sqrt(2)), add=T, col="brown", lwd=2)
  curve(dgamma(x, 50, 5), add=T, lty="dotted")

The solid brown curve is the density function
of $\mathsf{Norm}(\mu=10,\sigma=\sqrt{2}).$
Even if someone suggested that the population
might be gamma distributed, the density function (dotted) of $\mathsf{Gamma}(50,5)$ does not seem an obviously better fit
to the histogram.
Note: The inability to distinguish between
$\mathsf{Norm}(10,\sqrt{2})$ and $\mathsf{Gamma}(50,5)$ does not detract
from the practical use of either distribution in applied probability modeling. Normal distributions are familiar and often used. However, on theoretical grounds it may be preferable to use a corresponding gamma distribution in practice--especially if negative values are
impossible or if one needs to accommodate to occasional high outliers.

A: BruceET has a great answer.  I'd like to add some flavor based on a comment you've made:

I mean no matter how often you measure something, you never can be sure, then..?

Correct, this is just how inductive inference works.  I don't know that the sun will rise tomorrow, but it probably will.
Which leads me to my point.  We can't say anything for certain, but we can make probabilistic statements about phenomena. The Higgs boson is a particularly good example because it was accompanied by such a probabalistic statement (see $5\sigma$ as explained here https://blogs.scientificamerican.com/observations/five-sigmawhats-that/).  The p value, for all its faults, seeks to be such a statement: "Assuming all assumptions are met, and there is no bias in our estimation, there is a $p$ percent chance that we would see a test statistic at least as large were the null to be true."
Generally then, how can we generalize from sample to population?  That's a really hard job because we have to fight against a myriad of things, including but not limited to: sampling variability, internal and external validity, assumptions about the data generating mechanism which may or may not be appropriate, and so on.  Much of your confidence in making the generalization will not come from a single number such as the standard error, but will come from your contextual understanding of the measurement process, how the study was designed etc etc.  As I like to say "Statistics is not an algorithmic truth generating process" and so you'll never be able to test/compute something to tell you if you can generalize.


text:
Q: Progress indicator in table cell while app fetches and parses data I have an app that displays a table of places, that when a cell is tapped, it fetches data from a web API and parses it. However, sometimes this request takes 3-5 seconds to process. I've tried to display a spinning progress indicator in the content view of the cell, but I haven't been able to get it totally correct.
I was able to get the indicator to appear when the cell was tapped, however when I return to the table, the indicator is still visible. What's the best way to do do this?

A: Here is one way to approach this issue:

*

*when the cell is clicked, store the indexPath (or some other reference) so you know which cell was clicked

*add the spinner

*make an async call to get the data from your data source

*when the async call returns, update the appropriate data in your array (or wherever you store the data for the table)

*call reloadRowsAtIndexPaths to reload just the cells that changed, and remove your spinner.


text:
Q: JSOM SharePoint 2013 Error while getting WorkflowSubscription I was following the instruction from msdn to get WorkflowSubscriptionService over JSOM.
Working with the SharePoint 2013 Workflow Services Client Side Object Model:
http://msdn.microsoft.com/en-us/library/office/dn481315(v=office.15).aspx
var clientContext = SP.ClientContext.get_current();
var workflowServicesManager = SP.WorkflowServices.WorkflowServicesManager.newObject(clientContext, clientContext.get_web());
var workflowSubscriptionService = workflowServicesManager.getWorkflowSubscriptionService();

These three lines always throw a error:
TypeError: Object [object Object] has no method 'get_context'
message: "Object [object Object] has no method 'get_context'"
stack: (...)
get stack: function () { [native code] }
set stack: function () { [native code] }
proto: Error
I can't find a mistake. Is this a known bug?

A: Those errors occur since the specified objects have not been loaded.
In order to use SharePoint 2013 Workflow Services Client Side Object Model the following  JSOM libraries should be loaded:

*

*SP.js

*SP.Runtime.js

*SP.WorkflowServices.js

You could use, for example, SP.SOD.executeFunc (SharePoint JavaScript Library) or jQuery.getScript() (jQuery ibrary) to ensure that the specified file has been loaded.
Example:
var scriptbase = _spPageContextInfo.webAbsoluteUrl + "/_layouts/15/";
$.getScript(scriptbase + "SP.js", function () {
    $.getScript(scriptbase + "SP.Runtime.js", function () {
        $.getScript(scriptbase + "SP.WorkflowServices.js", function () {

            var clientContext = SP.ClientContext.get_current();
            var workflowServicesManager = SP.WorkflowServices.WorkflowServicesManager.newObject(clientContext, clientContext.get_web());
            var workflowSubscriptionService = workflowServicesManager.getWorkflowSubscriptionService();

            //...

        });
    });
});

A: Make sure you verify that CSOM has loaded before trying to get the context. Here's an example of how to validate your code is executing after SharePoint's JS has loaded. In this case I'm also logging to a div that CSOM has loaded using jQuery.
$(document).ready(function()
{
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function()
    {
        $('div#log').append("SharePoint Client Object Model Loaded<br/>");
    });
});


text:
Q: where is the index physically located in MySQL database Just wondering where is the index info physically located in MySQL database if I have indexed a table with ALTER TABLE contacts ADD KEY (columnName); ?

*

*it will stay with that table and add a new spacial column to it;

*stay separately from that table;

I think the #2 is the correct answer.
Can we index columns from more than one tables? how?

A: For the MyISAM engine, a table's indexes are stored in the .MYI file (in the data directory, along with the .MYD and .frm files for the table).
For InnoDB engine, the indexes are stored in the tablespace, along with the table. If innodb_file_per_table option is set, the indexes will be in the table's .ibd file along with the .frm file.
No, it's not possible to create an index that references more than one table. An index is specific to a table.

A: Using MySQL, all table information, including keys, are located in the INFORMATION_SCHEMA database.
For a more detailed answer, you might want to ask on Database Administrators.


text:
Q: CQRS/EventStore - Modelling and storing hierarchical tree I was wondering if anyone has tackled the issue of using CQRS and Event-Sourcing (Event-Store) with hierarchical trees?
We hope to have 10s of 1000s of nodes and childs in the tree and I am concerned whether CQRS with Event sourcing is not a good match for this problem. I have yet to look at snap shots which could be used on the event-store side.
Also from a DDD perspective, would I model it as a composite design pattern in my model or should it be more reflective of how the data is stored in my read model (i.e. SQL server in this case).

A: I tend to agree with the comments, that there really isn't an advantage to CQRS for your application.  It's a poor fit.
To answer your original question for someone else's benefit, I am building an application for Provisioning that uses CQRS & EventSourcing that has what are basically hierarchical trees.  I am using a graphing database [ Neo4J ] to handle the hierarchy...  [ Lots of groups at 6 - 8 different levels ].
The Domain reflects the relationships bottom up, while Neo4J will handle both direction.  That way the eventStore can update very quickly, and for those handlers which need to traverse the tree/graph [ in order to create lists of accessible nodes ], they can use the Graphing Database for that.
CQRS is actually a pretty good fit for this application, and I was actually fairly surprised that there was no push back at all to my approach with this.  Everyone seemed to agree that this was a much better alternative to a more traditional CRUD approach.
The system I am replacing stores these relationships in SQL, and that's where are having HUGE performance issues!   This should be dramatically better.


text:
Q: What does it mean: "your focus determinates..."? I've a problem with understanding following "quote" :

your focus determines your reality

How does "focus" can determinate something ? May it be about focus of view or something like this ? Can somebody explain it please ?

A: I've found answer in the dictionary:

*(often foll by: on) to fix attention (on); concentrate

Therefore:

Your "fixed attention on" determi....

Sounds entirely clean for me.

A: It means that what you choose to give your attention to, attracts what shows up in your life.
For example, if a person with only one leg focuses on how awful that is, how powerless and sad they feel, then they may spend their life feeling unhappy, as a cripple in a wheelchair. Their condition is unlikely to improve.
However if that same person focused on how grateful they were for their good leg and otherwise healthy body, they might get a replacement leg and become an athlete in the disabled olympic games.  Their condition improves.
The concept being described is known as The Law of Attraction, by the way, if you want to look it up:
'In the New Thought philosophy, the law of attraction is the belief that by focusing on positive or negative thoughts a person brings positive or negative experiences into their life.
https://en.wikipedia.org/wiki/Law_of_attraction_(New_Thought)


text:
Q: How can I normalize a dataset relative to data already given previously? Some scientific libraries, like Scikit-Learn for Python are able to create normalizing/standardizing functions based on data that is previously given. Looking at the documentation for Normalize[] and Standardize[], I don't see any type of functionality for creating a normalizing or standardizing function.
Is there any way that I can use Normalize[] or Standardize[] without needing to load all of the previously used data, in the effort to make my program more efficient?
To clarify, I would like to provide data for these functions that is (hopefully) representative of the other data I will be feeding the functions, and then use the result to create a function that normalizes/standardizes any new data that is sent in. Thanks!

A: The following applies JimB's suggestion; it would work if you have enough data to be representative of the "old" distribution:
ClearAll[standardizeTo]
standardizeTo[oldData_, newData_] :=
 Module[
   {oldMean, oldStdev},
   {oldMean, oldStdev} = Through[{Mean, StandardDeviation}[oldData]];
   oldStdev Standardize[newData] + oldMean
 ]

Let's create some play data from two normal distributions with markedly different parameters:
old = RandomVariate[NormalDistribution[10, 3], 100];
new = RandomVariate[NormalDistribution[12000, 1000], 100];

Apply the function to obtain an appropriately standardized data set from your second one:
restandardized = standardizeTo[old, new];

Check that the descriptors of the re-standardized data are indeed similar to the ones of the old data set:
Through[{Mean, StandardDeviation}[restandardized]]
(* Out: {9.85804, 2.75594} *)


text:
Q: Redirect from plugin created page I have a multilingual plugin that translates the pages. For example, after I press the language button the URL changes from example.com/products to example.com/en/products. My problem is that I want to redirect from the page example.com/en/products to another page but this page doesn't exist in my Pages list because it is created by the plugin. And 301 redirect plugins can't find this page.
How to handle such cases?

A: What you can do is save the ID of page you programatically created in options table.
add_option( 'my_plugin_dynamic_page_id', YOUR_PAGE_ID_HERE);

Now you can get the page you created easily anytime you want. Following way.
$pageID = get_option( 'my_plugin_dynamic_page_id', true);

Then you can get the permalink to the page once you get the page ID. And redirect user to the permalink.
$permalink = get_permalink($pageID);
wp_redirect( $permalink );
exit;


text:
Q: How to fix 0 value inserted in the database in the second request on Ajax? I have problem regarding inserting the last insert ID in the second request of Ajax, when I view the column all inserted items are 0 value. So now I want to insert each table row with having own unique ID
I have two table:

*

*wish_list_menu_order

*wish_list_menu_belong_condiments
The first insert was on wish_list_menu_order, so in the success function of first insert, I have second request which the url was wish_list_menu_belong_condiments.
First Request:
public function insert_wish_list_menu_order(Request $request)
{
    $customer_id = $request->get('customer_id');
    $append_customer_noun_order = $request->get('append_customer_noun_order');
    $append_customer_noun_order_price = $request->get('append_customer_noun_order_price');
    $now = new DateTime();

    for ($count = 0; $count < count($append_customer_noun_order); $count++) {

        DB::insert('INSERT INTO wish_list_menu_order (customer_id,wish_list_menu_name,wish_list_total_price,wish_created_at)
        VALUES(?,?,?,?) ', [

            $customer_id,
            $append_customer_noun_order[$count],
            $append_customer_noun_order_price[$count],
            $now,
        ]);
    }
}

Second Request:
public function insert_wish_list_menu_belong_condiments(Request $request)
{
    $Qty = $request->get('Qty');
    $Item = $request->get('Item');
    $Cost = $request->get('Cost');

    $now = new DateTime();

    $last_id_insert = DB::select('SELECT LAST_INSERT_ID() as id FROM wish_list_menu_order');

    foreach ($last_id_insert as $result) {
        $id_last_inserted = $result->id;
    }

    for ($count = 0; $count < count($Item); $count++) {

        DB::insert('INSERT INTO wish_list_menu_belong_condiments (wish_menu_id,belong_condi_name,belong_condi_qty,belong_condi_price,belong_condi_created)
        VALUES(?,?,?,?,?) ', [

            $id_last_inserted,
            $Item[$count],
            $Qty[$count],
            $Cost[$count],
            $now,
        ]);
    }

    return response()->json('Successfully Inserted');
}

My Ajax:
$('button#add_to_cart').on('click', function () {

    var customer_id = $('#hidden_customer_id').val();

    var parent_item = [];
    var parent_amount = [];

    //child
    var child_item = [];
    var child_quantity = [];
    var child_amount = [];

    //this is for parent item and amount
    $('#noun_chaining_order').find('tr.condimentParent td.parent_item').each(function () {
        parent_item.push($(this).text());
    });

    $('#noun_chaining_order').find('tr.condimentParent td.total').each(function () {
        parent_amount.push($(this).text());
    });

    //end

    //this is for child item,amount and quantity
    $('#noun_chaining_order').find('tr.editCondiments td.child_item').each(function () {
        child_item.push($(this).text())
    });

    $('#noun_chaining_order').find('tr.editCondiments td.total').each(function () {
        child_amount.push($(this).text());
    });

    $('#noun_chaining_order').find('tr.editCondiments td.condiments_order_quantity').each(function () {
        child_quantity.push($(this).text());
    });

    $.ajax({

        url: '/insert_wish_list_menu_order',
        type: 'post',

        data: {
            customer_id: customer_id,
            append_customer_noun_order: parent_item,
            append_customer_noun_order_price: parent_amount,
            Qty: child_quantity,
            Item: child_item,
            Cost: child_amount
        },

        success: function (response) {
            console.log(response);

            $.ajax({

                url: '/insert_wish_list_menu_belong_condiments',
                type: 'post',

                data: {
                    Qty: child_quantity,
                    Item: child_item,
                    Cost: child_amount
                },

                success: function (response) {
                    console.log(response);
                },

                error: function (response) {
                    console.log(response);
                }
            });
        },
        error: function (response) {
            console.log(response);
        }
    });
});

This is how I append the menu items in the table.
$("tr#productClicked").click(function () {

      var menu_name = $(this).closest("tr").find(".menu_name").text();
      var menu_price = $(this).closest("tr").find(".menu_price").text();
      var chain_id =  $(this).closest("tr").find(".chain_id").text();
      var menu_image = $(this).closest("tr").find(".menu_image").attr('src');
      var menu_cat_id =  $(this).closest("tr").find(".menu_id").text();
      var customer_id = $('#hidden_customer_id').val();

      if(chain_id == 0)
      {
         $("tbody#tbody_noun_chaining_order").
          append("
\
          	"+menu_name+"	"+menu_price+"	\
          <button class='removeorderWithOutCondi btn btn-danger form-control'>\
          </button>
");

          //computation of total click without chain
          var sum_sub_total_price = 0;
          $('td.total').each(function () {
            sum_sub_total_price += parseFloat($(this).text());
          });
          var with_decimal_subprice = parseFloat(sum_sub_total_price).toFixed(2);
          $('.append_customer_noun_order_price').text(with_decimal_subprice);
      }
      else
      {
          $("tbody#tbody_noun_chaining_order").
          append("
\
          	"+menu_name+"	"+menu_price+"	\
          <button class='removeorderWithOutCondi btn btn-danger form-control'>\
          </button>
");

          //after displaying the parent item get the condiments
          $.ajax({
            url:'/get_noun_group_combination',
            type:'get',
            data:{chain_id:chain_id},
            success:function(response){

              var noun_chaining = response[0].noun_chaining;
              $.each(noun_chaining, function (index, el) {

                var stringify_noun_chaining = jQuery.parseJSON(JSON.stringify(el));

                var Qty = stringify_noun_chaining['Qty'];
                var Condiments = stringify_noun_chaining['Condiments'];
                var Price = stringify_noun_chaining['Price'];
                var allow_to_open_condiments = stringify_noun_chaining['allow_to_open_condiments'];
                var condiments_section_id = stringify_noun_chaining['condiments_section_id'];

                $("tbody#tbody_noun_chaining_order").
                append("
\
                "+Qty+"	\
                *"+Condiments+"	"+Price+"	\
                "+allow_to_open_condiments+"	\
                "+condiments_section_id+"	\

");

              });

            }
          });
      }

});

Table 1.

Table 2.

$('button#add_to_cart').on('click',function () {

    var customer_id = $('#hidden_customer_id').val();

    var parent_item =[];
    var parent_amount =[];

    //child
    var child_item =[];
    var child_quantity =[];
    var child_amount = [];

    //this is for parent item and amount
    $('#noun_chaining_order').find('tr.condimentParent td.parent_item').each(function(){
        parent_item.push($(this).text());

    });

    $('#noun_chaining_order').find('tr.condimentParent td.total').each(function(){
        parent_amount.push($(this).text());

    });

    //end

    //this is for child item,amount and quantity
    $('#noun_chaining_order').find('tr.editCondiments td.child_item').each(function(){
        child_item.push($(this).text());

    });

    $('#noun_chaining_order').find('tr.editCondiments td.total').each(function(){
        child_amount.push($(this).text());

    });

    $('#noun_chaining_order').find('tr.editCondiments td.condiments_order_quantity').each(function(){
        child_quantity.push($(this).text());

    });

    $.ajax({

      url: '/insert_wish_list_menu_order',
      type: 'post',

      data: {
        customer_id: customer_id,
        append_customer_noun_order: parent_item,
        append_customer_noun_order_price: parent_amount,
        Qty: child_quantity,
        Item: child_item,
        Cost: child_amount
      },

      success:function(response){
        console.log(response);

        $.ajax({

          url: '/insert_wish_list_menu_belong_condiments',
          type: 'post',

          data: {
            Qty: child_quantity,
            Item: child_item,
            Cost: child_amount
          },

          success:function(response){
            console.log(response);

          },
          error:function(response) {
              console.log(response);
          }

        });

      },
      error:function(response) {
          console.log(response);
      }

    });

});
<!DOCTYPE html>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <title></title>

    <input type="hidden" name="" value="" id="hidden_customer_id">

        Qty
        Items
        Price
        Action

        $5.00 Extra Crispy 2 Piece Box
        5.00
        <button class="removeorderWithCondi btn btn-danger form-control">Delete</button>

        2
        *Standard
        0.00
        Yes
        3

        2
        *Individual Fries
        0.00
        Yes
        2

        1
        *Buttery Bread
        0.00
        No
        4

        1
        *Chocolate Chip Cookie
        0.00
        No
        5

        1
        *355ml Pepsi
        0.00
        No
        6

              	BIG CRUNCH Sandwich	7.29	              <button class="removeorderWithOutCondi btn btn-danger form-control">              </button>

    <button type="button" class="btn btn-primary" style="background-color:#3D0081; border-color:#3D0081;" id="add_to_cart">Click to process the order</button>

A: Taken from the MySQL documentation:

"The ID that was generated is maintained in the server on a per-connection basis."

In your code the two requests - the first inserting the parent record into wish_list_menu_order, the second inserting the child records into wish_list_menu_belong_condiments might run on different MySQL connections are not necessarily run in sequence. Instead of querying for LAST_INSERT_ID() on the second call, you should call it after inserting the record into the database and return it as part of the AJAX response.
In your current code, all records would be added to the wish_list_menu_order in sequence and after this finishes the child elements would be added. In your best case - only if just one MySQL connection is used - you might get the last inserted ID of the parent table and would use this ID for all inserts into wish_list_menu_belong_condiments.
Possible solution

*

*for each insert into wish_list_menu_order, perform one AJAX call and return the LAST_INSERT_ID().

*for each child element, perform another AJAX call inside the outer "parent" loop, providing the result of the previous AJAX call as a parameter.

Back-end code:
Inserts to wish_list_menu_order:
public function insert_wish_list_menu_order(Request $request)
{
    $customer_id = $request->get('customer_id');
    $append_customer_noun_order = $request->get('append_customer_noun_order');
    $append_customer_noun_order_price = $request->get('append_customer_noun_order_price');
    $now = new DateTime();

    DB::insert('INSERT INTO wish_list_menu_order (customer_id,wish_list_menu_name,wish_list_total_price,wish_created_at)
    VALUES(?,?,?,?) ', [

        $customer_id,
        $append_customer_noun_order,
        $append_customer_noun_order_price,
        $now,
    ]);

    $last_id_insert = DB::select('SELECT LAST_INSERT_ID() as id FROM wish_list_menu_order');
    return response()->json($last_id_insert);
}

Insert into wish_list_menu_belong_condiments:
public function insert_wish_list_menu_belong_condiments(Request $request)
{
    $Qty = $request->get('Qty');
    $Item = $request->get('Item');
    $Cost = $request->get('Cost');
    $ParentId= $request->get('ParentId');

    for ($count = 0; $count < count($Item); $count++) {

        DB::insert('INSERT INTO wish_list_menu_belong_condiments (wish_menu_id,belong_condi_name,belong_condi_qty,belong_condi_price,belong_condi_created)
        VALUES(?,?,?,?,?) ', [

            $ParentId,
            $Item[$count],
            $Qty[$count],
            $Cost[$count],
            $now,
        ]);
    }

    return response()->json('Successfully Inserted');
}

Front-end code:
// just for fiddle demo
var orderNumber = 358;
var customer_id = $('#hidden_customer_id').val();

$('#add_to_cart').on('click', function() {

  // reset
  var orders = [];
  var menu;

  $('#tbody_noun_chaining_order').children('tr').each(function() {
    $row = $(this);
    if ($row.hasClass('condimentParent')) {

      // store a previous menu to the orders array if exists.
      if (menu !== undefined) {
        orders.push(menu);
      }
      menu = {
        'total': $row.find('.total').text(),
        'name': $row.find('.parent_item').text(),
        'condiments': {
          'Item': [],
          'Qty': [],
          'Total': []
        }
      };

    } else if ($row.hasClass('editCondiments')) {
      // row is a condiment, append elements to the previous "menu" variable
      menu.condiments.Item.push($row.find('.child_item').text());
      menu.condiments.Qty.push($row.find('.condiments_order_quantity').text());
      menu.condiments.Total.push($row.find('.total').text());
    }
  });
  if (menu) {
    orders.push(menu);
  }
  storeOrder(orders);
});

function storeOrder(orders) {

  for (var num in orders) {

    // simulate storing the order
    $.ajax('/echo/json', {
      type: 'POST',
      // as the call is asynchronous, make sure to provide all required reference data along with the call.
      context: orders[num].condiments,
      data: {
        'json': '"' + (orderNumber++) + '"',
        'customer_id': customer_id,
        'append_customer_noun_order_price': orders[num].total,
        'append_customer_noun_order': orders[num].name,
      },
      success: function(orderNumber) {
        if (!isNaN(orderNumber)) {
          $.ajax('/echo/json', {
            context: orderNumber,
            type: 'POST',
            data: {
              'ParentId': orderNumber,
              'Item': this.Item,
              'Qty': this.Qty,
              'Total': this.Total,
              'json': '{"condimentsCount": ' + this.Item.length + '}'
            },
            success: function(result) {
              $('#result').append('Stored ' + result.condimentsCount + ' condiments for order ' +
                this + '
');
            }
          }); // End of condiments save procedure
        }
      }
    }); // End of menu save procedure
  }
}

Fiddle showing the mocked front-end part:
https://jsfiddle.net/Moonbird_IT/qbhnctre/
General advise:

*

*don't trust any data you receive from the user: a clever user might simply change the price of the condiments or menus inside the HTML before sending it to the server. Load the prices for each item on the server-side instead.

*check your Browser's Web Developer Tools' Console. This will give you early warnings if you are having JS mistakes

*also use the Developer Tools to scan the HTML code your JavaScript creates.


text:
Q: Pulling multiple rows from the same table from a JOIN table in MySQL I have a join table for a schedule (weeks 1, 2, 3, etc) that connects users. Each week in the join table has IDs for two separate users, User A and User B. But there are also multiple rows for each week. So it looks like this:
Schedule Table:
-----------------------------------
| week_id |  userA_id  | userB_id |
-----------------------------------
|    1    |     1      |   2      |
|    1    |     2      |   3      |
----------------------------------

I also have a user table which stores all the information about a user, pretty basic stuff. So, for instance:
User Table:
-----------------------------------
|    id   |    Name    | Nickname |
-----------------------------------
|    1    |    jason   |   jay    |
|    2    |    billy   |   bill   |
----------------------------------

What I'd like to do is query my schedule table based on the Week ID and then return a series of users for each Week. So for instance, give me all the users from week 1 in a series of objects, something like [ { UserA.name: jason, UserB.name: billy }, { UserA.name : billy, UserB.name: jane } ], etc.
I have a sneaking suspicion that this will include multiple JOIN statements, but I can't seem to get it working. Does anyone know how to structure this MySQL statement?

A: One option here is just to join the Schedule table twice to the User table, one join for each user in the relationship.
SELECT u1.Name,
       u2.Name
FROM Schedule s
INNER JOIN User u1
    ON s.userA_id = u1.id
INNER JOIN User u2
    ON s.userB_id = u2.id
WHERE s.week_id = 1


text:
Q: Carregar DataTable com Jquery e MVC 5 Bom dia!,
Li alguns artigos sobre o DataTables.net, por exemplo:
DataTables.net - Exemples index
Carregar tabelas com json usando DataTables
Usando jquery DataTables com o ASP.net MVC 5
porém não consigo fazer carregar os dados na view:
Class ClienteX
public class ClienteX
{
    public int ID { get; set; }
    public string Nome { get; set; }
    public int Idade { get; set; }
}

ACTION
public ActionResult Index()
    {
        return View();
    }

    public JsonResult AjaxHandler()
    {
        var model = new List<ClienteX>(){
            new ClienteX{ID=1, Nome="João", Idade=42}
        };

        var Resultado = new
        {
            sEcho = "1",
            iTotalRecords = 1,
            iTotalDisplayRecords = 1,
            aaData = model
        };
        return Json(Resultado, JsonRequestBehavior.AllowGet);
    }

VIEW index.cshtml

DataTable - Ajax

<button type="button" id="btnEnviar">Enviar</button>

            ID
            Nome
            Idade

<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" />

O evento click do botão Enviar funciona:
$("#btnEnviar").click(function () {...

mas o código seguinte que chama o método JsonResult e que deveria popular a tabela não é executado, por quê ?
$("#btnEnviar").click(function () {

            $("#myDataTable").dataTable({
                "bServerSide": true,
                "sAjaxSource": "DOMDataSource/AjaxHandler",
                "bProcessing": true,
                "aoColumns":
                    [
                        {
                            "sName": "ID",
                            "mData": "ID"
                        },
                        {
                            "sName": "Nome",
                            "mData": "Nome"
                        },
                        {
                            "sName": "Idade",
                            "mData": "Idade"
                        }
                    ]
            });
    });

Tela com o botão Enviar

A: Adriano, usei seus códigos como exemplo e funcionou, não sei como está sua estrutura do projeto. se você utilizou o template padrão do VS, então provavelmente você está referenciando duas vezes o arquivo do jquery.
Segundo problema, como voce adicionou os códigos javascript e referencias extras dentro do html da view, se você reparar no código fonte apos renderização no navegador vai reparar que eles ficaram acima da referencia nativa do jquery do templete do JS.
Então recomendo usar seus códigos javascript assim:
@section scripts
{

    <link href="//cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet"/>

}

ds


text:
Q: What is a simple, correct and secure way of executing code stored in database?, that is also sandboxed Webhooks can be a very powerful thing when you try to automate or integrate software, however, handling their deployment in a controlled environment can suck in terms of security and deployment alone.
I need a way of allowing anybody in the company —anybody that can be trusted with API access, that is— to be able to create, deploy, use (and perhaps even share) webhooks without requiring access to a server.
I have thought that a way of doing this is to create a small application that can store, route and run scripts. The best way I can think to implement such a thing is by taking code stored in a database and creating a temporary file to then run a system command for the given language.
However, I think there would be nothing that would prevent that code from, say, shutting down the machine, downloading and executing external dangerous code, etc.
Then I thought about Linux containers, but I would preferably want a portable solution. I looked for an equivalent in Windows and apparently the technology does not exist yet:
http://www.theregister.co.uk/2014/10/16/windows_containers_deep_dive/
http://www.theregister.co.uk/2014/11/18/windows_docker_client/
Is there a simpler approach that can still be regarded as secure?, I would want to at least be able to execute php, python, ssj and shell scripts.
P.S.: Free downvotes for whoever suggests PHP eval

A: What it sounds to me like you are describing is what package managers do: they take files from a repository, copy them to the target machine, and run scripts within them. This is usually done for the purpose of installation of software, but it doesn't have to be, so long as you are OK with their idempotency. They typically use a remote filesystem full of compressed archive files instead of a database for the repository, but that's really just an implementation detail.
What it sounds like you want beyond this is safety and portability. As you mention, safety is best achieved with containers or virtual machines. You are correct to note that there is nothing preventing, say, a Debian package's postinst script from running rm -rf / as root. You are also correct that Docker is a great example of containers, but it requires all applications it manages to be 'dockerized'. Portability is a bit trickier, as some software is inherently portable (like basic web services), while other is not (like performance monitors), and some platforms support containers better than others.
It sounds like you would want something that creates a generic container and then installs/runs arbitrary code within it. To achieve this, you could create the container yourself by setting up chroots, cgroups, etc., but it might be easier to let Docker do most of the work for you: In your database (or whatever repository you choose), store the script, a command to invoke it, a base Docker image, and whatever interpreter dependencies you need. For convenience, all this could be stored under a simple identifier. You then write a script that pulls down the needed files and data and builds a Docker container on the fly and then runs it. Docker provides primitives for copying files from host to guest, and specifying the command to invoke when the container starts up.
Admittedly, since Windows doesn't yet support containers compatible with Docker, you might need to do something different there. I've been away from Windows for some time now, but I recall it has a lot of support for access control lists and other security features with which you (or someone) could create something like a container. Sorry I can't give you more here. When Windows eventually supports proper containers, your repository might need to have custom base Docker images for Windows and Linux, for example, which could be selected automatically at runtime by your master script.


text:
Q: ASM get value position in the code dll function asm code:
10123148 68 C4 26 32 10              push    offset aSurfaceprop ; "$surfaceprop"
1012314D 8B CF                       mov     ecx, edi
1012314F FF D2                       call    edx
10123151 80 7D FF 00                 cmp     [ebp+var_1], 0
10123155 74 33                       jz      short loc_1012318A
10123157 8B 10                       mov     edx, [eax]
10123159 8B C8                       mov     ecx, eax
1012315B 8B 42 18                    mov     eax, [edx+18h]
1012315E FF D0                       call    eax
10123160 8B 0D B0 70 61 10           mov     ecx, dword_106170B0
10123166 8B 11                       mov     edx, [ecx]
10123168 89 45 D8                    mov     [ebp+var_28], eax
1012316B 50                          push    eax
1012316C 8B 42 0C                    mov     eax, [edx+0Ch]
1012316F FF D0                       call    eax
10123171 66 89 46 6C                 mov     [esi+6Ch], ax
10123175 8B 0D B0 70 61 10           mov     ecx, dword_106170B0
1012317B 8B 11                       mov     edx, [ecx]
1012317D 8B 45 D8                    mov     eax, [ebp+var_28]
10123180 8B 52 0C                    mov     edx, [edx+0Ch]
10123183 50                          push    eax
10123184 FF D2                       call    edx
10123186 66 89 46 6E                 mov     [esi+6Eh], ax
1012318A
1012318A                         loc_1012318A: ; CODE XREF: sub_10122A50+705j
1012318A 8B 07                       mov     eax, [edi]
1012318C 8B 50 2C                    mov     edx, [eax+2Ch]
1012318F 6A 00                       push    0
10123191 8D 4D FF                    lea     ecx, [ebp+var_1]
10123194 51                          push    ecx
10123195 68 9C 29 32 10              push    offset aSurfaceprop2 ; "$surfaceprop2"
1012319A 8B CF                       mov     ecx, edi
1012319C FF D2                       call    edx
1012319E 80 7D FF 00                 cmp     [ebp+var_1], 0
101231A2 74 1B                       jz      short loc_101231BF
101231A4 8B 10                       mov     edx, [eax]
101231A6 8B C8                       mov     ecx, eax
101231A8 8B 42 18                    mov     eax, [edx+18h]
101231AB FF D0                       call    eax
101231AD 8B 0D B0 70 61 10           mov     ecx, dword_106170B0
101231B3 8B 11                       mov     edx, [ecx]
101231B5 50                          push    eax
101231B6 8B 42 0C                    mov     eax, [edx+0Ch]
101231B9 FF D0                       call    eax
101231BB 66 89 46 6E                 mov     [esi+6Eh], ax

I don't have a source code, but I managed to get a pseudocode for this function:
if ( !(unsigned __int8)(*(int (__thiscall **)(int))(*(_DWORD *)v63 + 168))(v63) )
{
    v64 = (*(int (__thiscall **)(int, _DWORD, char *, _DWORD))(*(_DWORD *)v63 + 44))(v63,"$surfaceprop",&v140,0);
    if ( v140 )
    {
        v65 = (*(int (__thiscall **)(int))(*(_DWORD *)v64 + 24))(v64);
        v66 = *(_DWORD *)dword_106170B0; //physprop
        v131 = v65;
        *(_WORD *)(v54 + 108) = (*(int (__stdcall **)(int))(v66 + 12))(v65);
        *(_WORD *)(v54 + 110) = (*(int (__stdcall **)(int))(v66 + 12))(v131); //v131 == v65;
    }
    v67 = (*(int (__thiscall **)(int, _DWORD, char *, _DWORD))(*(_DWORD *)v63 + 44))(v63,"$surfaceprop2",&v140,0);
    if ( v140 )
    {
        v68 = (*(int (__thiscall **)(int))(*(_DWORD *)v67 + 24))(v67);
        *(_WORD *)(v54 + 110) = (*(int (__stdcall **)(int))(*(_DWORD *)dword_106170B0 + 12))(v68); // physprop == *(_DWORD *)dword_106170B0
    }
    }

Variables v64 v65 v67 v68 contain pointers that I needed to know.
So, my question: where the variables (v64 v65 v67 v68) are stored in the assembly code (lines and register names) ? I do not understand assembly code, if there is savvy people, help please.

A: These are the lines where those variables should be stored:
...
10123157 mov  edx, [eax]         ; edx -> v64, after executing this instruction
...
10123168 mov  [ebp+var_28], eax  ; eax -> v65
...
101231A4 mov  edx, [eax]         ; edx -> v67, after executing this instruction
...
101231B5 push eax                ; eax -> v68
...

you can set breakpoints at these addresses to check the value, make sure you check the registers after the executions of the instruction in the first and the third.


text:
Q: Python Pandas max value of a column depending on shared condition I have a table that looks like this:

I am trying to figure out what the "first_stop" and "last_stop" is for each "id" based on the "sequence".  I have the first_stop done, but I can't figure out the last stop. So I need an additional column that says if it is the max sequence number for each ID. I have tried so many ways and they all end up failing or giving me some errors. I've wasted too much of my day trying to solve this and I know you all will be able to help me out super quick. Thanks for your help.
for index, row in df.iterrows():
    first_mask = df['sequence'] == 0
    last_mask = df['sequence'] == ???
    df['first_stop'] = np.where(first_mask, 'Y', 'N')
    df['last_stop'] = np.where(last_mask, 'Y', 'N')
print(df[['id', 'sequence', 'first_stop', 'last_stop']])

The sequence is the order of the stops, so I want the lowest sequence number (first_stop) for each ID, and the highest sequence number (last_stop) for each ID. The lowest sequence number is easy, it's always 0. But how do I calculate the highest sequence number for each ID?

A: Alright, I solved it myself, so here is what I did. It's pretty simple and I feel stupid for not figuring it out earlier.
Let me know if anyone else has a better solution.
I created a row that counts the total stops:
df['stop_count'] = df.groupby('id')['id'].transform('count') - 1

Then I checked to see if the sequence number matches the stop_count:
last_mask = df['sequence'] == df['stop_count']

A: Given that your DataFrame appears to already be sorted by ['id', 'sequence'] you just need to shift as was pointed out in the comments to check for the last row where the id changes.
df['last_stop'] = df.id != df.id.shift(-1)

Outputs:
    id  sequence  last_stop
0    2         0      False
1    2         1       True
2    3         0      False
3    3         1      False
4    3         2      False
5    3         3       True
6    4         0      False
7    4         1       True
8    5         0      False
9    5         1       True
10   6         0       True
11   7         0       True
12   8         0      False
13   8         1       True

If it is not sorted, you can sort before and apply the same logic. Otherwise a single transform will take care of it:
df['last_stop'] = df.groupby('id').sequence.transform(lambda x: x == max(x))


text:
Q: Toy example of a segfault in Fortran What is an example of code that deliberately causes a segfault in Fortran?  I tried the following in msys, but all I got was a warning and the naughty access of the baddata array just printed 0.
I need this for learning purposes but also as a test case for writing code to handle gracefully when things like this happen when calling an external Fortran function
program segfault

  implicit none

  real, dimension(10) :: baddata
  integer i

  do i=1,10
     baddata(i) = 1.0
  end do

  print *, baddata(1)
  print *, baddata(1024)

end program segfault

compiled with: gfortran segfault.f90 -o sefault yields:
(base) C:\Coding\Fortran>gfortran segfault.f90 -o segfault
segfault.f90:13:19:

   13 |   print *, baddata(1024)
      |                   1
Warning: Array reference at (1) is out of bounds (1024 > 10) in dimension 1

(base) C:\Coding\Fortran>segfault
   1.00000000
   0.00000000

A: As a general rule, you cannot do this "within Fortran".
Segmentation faults come from attempting to access parts of memory without permission.  The Fortran language is specified in such a way that if you try to access a lump of memory without permission (such as accessing an array element not within bounds) then you don't have a valid Fortran program.  That's part of the "not within Fortran".  Another part is that if you have a (valid Fortran) program which correctly references things, then the processor is required to ensure that the program is treated in a correct way (which doesn't involve segmentation faults).
Any "toy example" with a segmentation fault is going to depend on specific behaviour of a particular compiler, operating system, and so on.  These could vary depending on versions, compile- and run-time options.
For example, in this question we see how a simple attempt to access out-of-bounds access is detected by the compiler and even when running doesn't result in a segmentation fault.  Other cases are in other questions, such as this one.  More detail on when an array access results in a segmentation fault can be found in a related answer.
Why is this detection important?  Well, if the compiler detects that you are attempting out-of-bounds access, then it could just as correctly, under the Fortran language, treat your
  print *, baddata(1024)

as though you'd written
  print *, -1231.516, "<- I hope you like this value I made up for you"

Perhaps your best bet would be to try the classic null dereference:
  integer, pointer :: i=>null()
  i=0
end

But this isn't a Fortran program.  You may need to do a lot more work to get a reliable segmentation fault.  This could move you well beyond a "toy" example.
Alternatively, if you can generate a SIGSEGV (again, this wouldn't be a Fortran thing), perhaps with a procedure not defined by Fortran, then you may find that easier.


text:
Q: html link to facebook won't work My code:

 Facebook:

Our current lesson is on frames.
I have left and right frames. Where in the left frame, there's a menu, and one of which is "social networking sites". When I click on that, a list(pictures) of my sns will appear on the right frame. One is Facebook.
I'm trying to figure out how to link my Facebook page and make it appear on my right frame also.

A: From this code you get Correct Facebook page . apart from that if you are facing issue please post CSS code as well

 Facebook:


text:
Q: Can NSDataDetector be made to detect URLs but not email addresses? I've implemented NSDataDetector to detect URLs, but it includes email addresses as well. Is there an easy way to make it not detect emails, but all other URLs?

A: Well, email addresses are not URLs. mailto:someone@some.where.com is a URL which contains an email address. So, to answer your question: Check whether your URL begins with mailto:. If it does, ignore it. If for some reason you're picking up email addresses as URLs, you probably have some parsing bug...
See here about regular expressions for URLs.


text:
Q: Android does not accept root CA certificate I have an android app that talk to my internal server with https. The server uses a certificate from my companies' root CA. I have installed the root certificate in my store. When I access the API on my Windows machine the certificate is shown as valid.
I don't want to disable the certificate validation and I don't want to abstain from using SSL.
The error I receive is: Failed to validate the certificate chain, error: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

A: You have to specify network security config by a reference from your application's block in the manifest. Check it out.
If I remember well, starting from Android N it became necessary to specify trusted certificates groups explicitly in manifest.
Windows just trusts all certificates that through a chain of trust point to any root trusted certificate. Android has it's own opinion about that.


text:
Q: How to delete/destroy/make nil any object with ARC? Every time I show some subView with this code, clearImage creates every time, and after 10 executions there are 10 images!
How to delete this image after removeFromSuperview?
- (IBAction)nextTutorial:(id)sender {
    UIImageView *clearImage = [[UIImageView alloc] initWithFrame:CGRectMake(270, 0, 50, 50)];
    clearImage.image = [UIImage imageNamed:[settings objectAtIndex:7]];

    UIImageView *helpImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    helpImage.image = [UIImage imageNamed:[settings objectAtIndex:8]];

    UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(60, 7, 200, 30)];
    slider.value = 0.5;

    if (hintnumber == 1) {
        self.hintLabel.text = [settings objectAtIndex:1];
        [self.view addSubview:slider];
        hintnumber = 2;
    } else if (hintnumber == 2) {
        self.hintLabel.text = [settings objectAtIndex:2];
        [self.view addSubview:clearImage];
        hintnumber = 3;
    } else if (hintnumber == 3) {
        self.hintLabel.text = [settings objectAtIndex:3];
        [self.view addSubview:helpImage];
        [self.nextButton setTitle:[settings objectAtIndex:5] forState:UIControlStateNormal];
        hintnumber = 4;
    } else if (hintnumber == 4) {
        hintnumber = 1;
        [slider removeFromSuperview];
        [clearImage removeFromSuperview];
        [helpImage removeFromSuperview];
        slider = nil;
        clearImage = nil;
        helpImage = nil;

        [self.view removeFromSuperview];
    }

A: UPDATE based on new code:
If hintNumber is 4, you are creating an object, never adding it to a view, and then removing it from a view that it isn't in.  You need to remove the object that was added previously from it's superview, and not the one that you just created using something like [[self.view viewWithTag:99] removeFromSuperview]; and set the tag number of clearView to 99 when you create it.
As an aside, you should only create the new objects when you need them.

A: First: remove from superview
Second: set clearImage to nil ;)

A: Call [clearImage removeFromSuperview] before setting clearImage to nil. :)


text:
Q: How to print an incremented number after every loop in Python? I'm very new to python, but I've made a lot of progress over the last few days. The below script works fine, but I just can't figure out how implement code that would print an incremented number every time 'avail' is equal to NO. I'd like to have it print something like 'None Available 1' on the first loop, then 'None Available 2' on the second loop, then 'None Available 3' on the third loop, etc..
import requests
import time
import subprocess
from bs4 import BeautifulSoup

def get_page(url):
    response = requests.get(url)
    if not response.ok:
        print('Server responded:', response.status_code)
    else:
        soup = BeautifulSoup(response.text, 'lxml')
    return soup

def get_detail_data(soup):
    avail = soup.find('span', id='availability').text.strip()
    if avail == "YES":
        return True
    elif avail == "NO":
        print('None Available')
        return False
    else:
        print("Unexpected value")
        return None

def main():
    url ='https://www.blahblah.com'

    while True:
        is_available = get_detail_data(get_page(url))
        if is_available:
            subprocess.call(["C:\\temp\\filename.bat"], shell=False)
            break
        time.sleep(2)

if __name__ == '__main__':
    main()

A: The following would probably work, but there might be a better way to structure it.
_not_avail_counter = 0
def get_detail_data(soup):
    avail = soup.find('span', id='availability').text.strip()
    if avail == "YES":
        return True
    elif avail == "NO":
        _not_avail_counter += 1
        print('None Available ' + str(_not_avail_counter))
        return False
    else:
        print("Unexpected value")
        return None

A: I would suggest changing your while True loop into a for loop on an itertools.count iterator. You can pass the value from the count to the get_detail_data function with an argument.
import itertools

def get_detail_data(soup, count):         # take the count as an argument
    avail = soup.find('span', id='availability').text.strip()
    if ...
        # ...
    elif avail == "NO":
        print('None Available', count)    # include count here (and anywhere else you want)
        # ...

def main():
    url ='https://www.blahblah.com'

    for c in itertools.count():           # produce the count in a loop
        is_available = get_detail_data(get_page(url), c)

        # ...

Note that itertools.count starts counting a zero. If you want to start at 1 (like a human usually would when counting things), you may want to pass 1 as the start argument: for c in itertools.count(1).


text:
Q: Переотправка сообщения обратно в очередь в RabbitMQ Как RabbitMQ настроить так, чтобы переотправка сообщения из очереди, скажем queue, в случае неудачной обработки снова попало в очередь queue и обработалось через определенное время ?

A: Как вам уже сообщали, через плагин отложенных сообщений данную концепцию можно реализовать. Но, скажу как человек использующий данный плагин в продакшен. Сделайте систему мониторинга целостности данных. Потому как есть болезнь у этого плагина. Сообщения могут не возвращаться после истечения времени и накапливаться в обменнике. Лечится перезагрузкой реббита, но с потерей сообщений в обменнике


text:
Q: How to maintain Alpakka/Akka Streams source state across application restarts? I am new to Alpakka and am considering using it for system integration. What would be the ideal way to maintain the state of the Akka Streams sources across application restarts ?
For example: let's assume I'm using something as follows to continuously read some input data and dump it somewhere. What if it runs for like 4h, then the full JVM crashes and restarts (e.g. k8s restarts my pod or so):
someSource
    .via(someTransformation)
    .via(someOtherTransformation)
    .toMap(...)
    .run()

I understand that if someSource is a Kafka source or Kinesis source or some other stateful source, they can keep track of their offset or checkpoint and restart more or less where they left off.
However, many other sources have no such concept, e.g. the Cassandra source, the File source or the RDBMs source. For example, if I shutdown and restart the code provided in the rdms example, it will restart from the top each time.
Am I understanding correctly that there is no mechanism to address that out of the box, s.t. we have to handle it manually ? I would have imagined that this feature would be desired so commonly that it would be handled somehow. If not, how do people typically address that ? Do you use Akka persistence to store some cursors in a few actors? Or do you store the origin offset together with the output data and re-read it on startup?
Or am I looking at all this the wrong way?

A: It is a feature that is extremely commonly desired, for the reason you suggest.
However, the only generic, reliable way to implement this would be using akka persistence which is probably the single heaviest (e.g. it requires choosing a database) dependency in the Akka ecosystem.  Beyond that, it's going to be somewhat source specific.  Some (e.g. Kafka, Kinesis) have a means of doing this that's going to fit the bill in nearly every scenario, but for the others, the details of how to store the state of consumption are something on which there will be a lot of differences of opinion.  Akka and Alpakka in general tend to shy away from opinionation.


text:
Q: What's the optimal way to create complex Mongoose/Mongo queries involving multiple filters, sorting and limiting? I'm trying to construct a complex query to fetch data using multiple filter criteria. While my code was working fine for small tests, as I'm scaling to more users and data queries are becoming unacceptably slow (eg 20-30 seconds to complete a request). I'm not sure if there's a way I should be using indexes or if they don't apply in complex queries like this, or if I should use multiple separate queries, or I need to totally restructure the queries or the data. The code below is an example query, say finding users whose user ID is in a given array but not in others, and who's preferences match certain filter criteria, and who are in a given geography. I'm pretty sure I'm breaking some cardinal rules here, but am a relative newb so any help is greatly appreciated! In particular, if an index is what's needed, it'd help to have an example of how to use one in this example case. Thank you!
User.find({
  $and: [
    { userid: {$in: array1} },
    { userid: {$nin: array2} },
    { userid: {$nin: array3}},
    { userPref1: {$ne: userPref} },
    { userPref2: {$ne: userPref2} },
    { latlon : {"$within" :
            {"$center" : [userlocation , distance ]}
          } }
          ]},
    .sort('-hasAccount -hasActions')
    .limit(max)
    .exec(function(...){});

A: *

*"finding users whose user ID is in a given array but not in others"
Merge "{ userid: {$in: array1} },{ userid: {$nin: array2} },{ userid: {$nin: array3}}" into one. Get userid who are in array1 but not array2&array3 into array4, then use { userid: {$in: array4} }

*"who's preferences match certain filter criteria"
If there are only 2 userPref, build compound index will be ok. But if there are dozens... no way. You have to leave unimportant userPref without index, which will definitly make the query slow.

*"who are in a given geography"
2d index is necessary.
Summary:
if(num of userPrefs < M) // I would set M = 3
    build index: {loc:"2d", userid:1, userPref1:1, userPref2:1} or
    build index: {loc:"2d", userid:1, userPref1:1};
    sort({loc:"2d", userid:1, userPref1:1});
else
    reduce num of userPrefs;

BTW: sort by other order instead of {loc:"2d", userid:1, userPref1:1} will also slow the query.


text:
Q: SQL Query performance that use subquery and joins I need to speed execution time for the following query as it take too long time to execute and i think the sub query is the problem
SELECT WFApplication.*,
       WorkflowIncidentType.TypeName ProcessCategory,
       WFProcess.WFProcessName ProcessName,
       LUTAppStatus.EnglishName AppStatus
FROM WFApplication
INNER JOIN LUTAppStatus ON WFApplication.ApplicationStatus = LUTAppStatus.Id
INNER JOIN WorkflowIncidentType ON WorkflowIncidentType.TypeID = WFApplication.ApplicationIncidentType
INNER JOIN WFProcess ON WFProcess.WFProcessId = WFApplication.ApplicationProcess
LEFT OUTER JOIN IBSCustomer ON IBSCustomer.RIM = WFApplication.RIM
LEFT OUTER JOIN Reschedule ON Reschedule.RescheduleId = WFApplication.ProcessId
WHERE WFApplication.ProcessId IN
    (SELECT ProcessId
     FROM WFProcessInstanceLog)
  AND WFProcessInstanceId IN (28251,
                              28345,
                              28773,
                              28774,
                              28846,
                              29309, .....)

A: Okay, here's the basics of SQL Performance Optimizing for queries.
First step: Display the Actual Execution Plan.  In the 'Query' menu, check 'Include Actual Execution Plan'.  Then, when you run the query, an extra tab will appear in the results pane, for 'Execution Plan'.
Second Step: Look at the right-most nodes in the tree.  There will generally be four possibilities:

*

*Table Scan.  Basically, this is bad.  It's indicating that the full table had to be looked through to find what it was looking for - no indexes used at all.  If the table is small, that might not matter much; if the table is large, you've probably got a problem.

*Clustered Index Scan.  Also bad.  Clustered Indexes are the table, so if SQL is scanning through one, it means its scanning through the whole table.

*Index Scan - Nonclustered.  Semi-bad.  Basically, it was able to use an index to help look through the data (better than a full table) but it wasn't able to use Binary Finds to quickly narrow down the data it was looking for.

*Index Seek (either Nonclustered or Clustered) - What you're after.  This means SQL was able to binary-find its way quickly to the data its looking for.

Now, what causes SQL to choose one option over another?  The first big thing is your indexes.  Often, the 'Execution Plan' will alert you to missing indexes that'd improve the performance of your query.  But you can manually look - if it's going through "Table A" using a full scan... why?  What column is it looking up, searching on, or matching against?  Chances are, that column needs to have an index so the engine can quickly match against it.
But there are other reasons.  Lets say the table isn't that big, and you're matching lots of entries against the table.  It might be faster for SQL to just look through the whole table.
Another reason that's often overlooked: you've got indexes on the relevant columns, but they don't narrow down the data enough to make them worthwhile - or, alternatively, it's looking through so many different indexes that trying to wrangle them all up against the original table is slower than just using the large table.  If this is the case, the solution is to create indexes with multiple columns in the index.
One good way to diagnose a problem like this is to omit some of the tables/data and see if the execution plan changes.  For example, try this query out:
SELECT WFApplication.*
FROM WFApplication
WHERE WFProcessInstanceId IN (28251,
                          28345,
                          28773,
                          28774,
                          28846,
                          29309, .....)

Does the execution plan change?  If the plan in the above statement is bad, it probably means that you're missing an index on WFProcessInstanceId or that your table isn't big enough to justify 5000 references against the main table.
But if it uses an Index Seek on that query, but switches to a Scan op when you add other tables, it might be a sign that you need to add those additional lookup columns to a separate index, so that it doesn't have to try to coordinate multiple indexes.

A: If it is the subquery you could instead do an inner join between wfapplication and wfprocessingstancelog.There isn't a good reason to use a subquery for this:
SELECT WFApplication.*,
       WorkflowIncidentType.TypeName ProcessCategory,
       WFProcess.WFProcessName ProcessName,
       LUTAppStatus.EnglishName AppStatus
FROM WFApplication
Inner Join WFProcessInstanceLog WPL on WPL.ProcessID = WFApplicaiton.ProcessId
INNER JOIN LUTAppStatus ON WFApplication.ApplicationStatus = LUTAppStatus.Id
INNER JOIN WorkflowIncidentType ON WorkflowIncidentType.TypeID = WFApplication.ApplicationIncidentType
INNER JOIN WFProcess ON WFProcess.WFProcessId = WFApplication.ApplicationProcess
LEFT OUTER JOIN IBSCustomer ON IBSCustomer.RIM = WFApplication.RIM
LEFT OUTER JOIN Reschedule ON Reschedule.RescheduleId = WFApplication.ProcessId
WHERE WFProcessInstanceId IN (28251,
                              28345,
                              28773,
                              28774,
                              28846,
                              29309, .....)


text:
Q: Define row of data based on search criteria in Google Apps Script I am trying to set a row as a range based on a search criteria.  I know which column I want to search and based on that I want that specific row to be the data range.  Once the data range is set I format it as a table and send an email with the table in it.  The code I have is pretty messed up by all the different attempts I have made so I don't have any to post. Below is just a sample of the row and column N is what I am searching on.  Then I want that row with D - Y as my range.  So search for MLS/MRL Weekend which is row 89 and set range D89:Y89 as the range based off of the search.  This is not pretty.. I am learning as I go and this really new territory for me.
    function rowOf(team1, dataRange) {
 var ss = SpreadsheetApp.openById("spreadsheetid");
 var sheet1 = ss.getSheetByName("Stats1");
 var dataRange = sheet1.getSheetValues(1,14,150,1);
 var ss1 = SpreadsheetApp.openById("otherspreadsheetid");
 var sheet = ss1.getSheetByName("Form Responses 1");
 var data = sheet.getRange(sheet.getLastRow(), 1, 1, sheet.getLastColumn()).getValues();
 var email = data[0][2];
 var team1 = data[0][1];
 var subject = team1 +" Team Stats";
 var outRow = null;

 for (var i = 0; i < dataRange.length; i++)
 {
   if (dataRange[i][0] == team1)
   {
     outRow = i+1;
     break;
   }
 }
 var Header = sheet1.getRange('d1:y1').getValues();
 var u13gneongoalsg1 = sheet1.getRange(outRow,4).getValues();
 var u13gneonshotsg1 = sheet1.getRange(outRow,5).getValues();
 var u13gneontopg1 = sheet1.getRange(outRow,6).getValues();
 var u13gneontop1g1 = sheet1.getRange(outRow,7).getValues();
 var u13gneonfirstg1 = sheet1.getRange(outRow,8).getValues();
 var u13gneonpassesg1 = sheet1.getRange(outRow,9).getValues();
 var u13gneonpasscompg1 = sheet1.getRange(outRow,10).getValues();
 var u13gneonnumpassstringg1 = sheet1.getRange(outRow,11).getValues();
 var u13gneonavgpassstringg1 = sheet1.getRange(outRow,12).getValues();
 var u13gneonlongpassstringg1 = sheet1.getRange(outRow,13).getValues();
 var u13gneonogoalsg1 = sheet1.getRange(outRow,16).getValues();
 var u13gneonoshotsg1 = sheet1.getRange(outRow,17).getValues();
 var u13gneonotopg1 = sheet1.getRange(outRow,18).getValues();
 var u13gneonotop1g1 = sheet1.getRange(outRow,19).getValues();
 var u13gneonofirstg1 = sheet1.getRange(outRow,20).getValues();
 var u13gneonopassesg1 = sheet1.getRange(outRow,21).getValues();
 var u13gneonopasscompg1 = sheet1.getRange(outRow,22).getValues();
 var u13gneononumpassstringg1 = sheet1.getRange(outRow,23).getValues();
 var u13gneonoavgpassstringg1 = sheet1.getRange(outRow,24).getValues();
 var u13gneonolongpassstringg1 = sheet1.getRange(outRow,25).getValues();

 //if (game1choice(team)) {
 var message = '
';
 message +=   '
';
 message +=   '
U13G Neon	Game Totals	'+team1+ '
';
 message +=   '
' +u13gneongoalsg1+ '	Goals	' +u13gneonogoalsg1+ '
';
 message +=   '
' +u13gneonshotsg1+ '	Shots	' +u13gneonoshotsg1+ '
';
 message +=   '
'+u13gneontopg1 +'	Time of Possession	'+u13gneonotopg1 +'
';
 message +=   '
'+u13gneontop1g1 +'	Time of Possession %	'+u13gneonotop1g1 +'
';
 message +=   '
'+u13gneonfirstg1 +'	First Touches	'+u13gneonofirstg1 +'
';
 message +=   '
'+u13gneonpassesg1 +'	Passes	'+u13gneonopassesg1 +'
';
 message +=   '
'+u13gneonpasscompg1 +'	Pass Completion %	'+u13gneonopasscompg1 +'
';
 message +=   '
'+u13gneonnumpassstringg1 +'	Number of Pass Strings	'+u13gneononumpassstringg1 +'
';
 message +=   '
'+u13gneonavgpassstringg1 +'	Average Pass String Length	'+u13gneonoavgpassstringg1 +'
';
 message +=   '
'+u13gneonlongpassstringg1 +'	Longest Pass String	'+u13gneonolongpassstringg1 +'
';
 message +=   '
';
 message +=   '

';
 message += '';

 MailApp.sendEmail(email, subject, "", {htmlBody: message});
 return outRow;
 }

A: Here is the code that I got to work for me.
    function rowOf(team1, dataRange) {
 var ss = SpreadsheetApp.openById("sheetid");
 var sheet1 = ss.getSheetByName("Stats1");
 var dataRange = sheet1.getSheetValues(1,14,300,1);
 var dataRange2 = sheet1.getSheetValues(1,2,300,1);
 var ss1 = SpreadsheetApp.openById("othersheetid");
 var sheet = ss1.getSheetByName("Form Responses 1");
 var data = sheet.getRange(sheet.getLastRow(), 1, 1, sheet.getLastColumn()).getValues();
 var email = data[0][2];
 var team1 = data[0][1];
 var magellan = data[0][3];
 var subject = team1 +" Team Stats";
 var outRow = null;
 var outRow2 = null;

  for (var i = 0; i < dataRange.length; i++){

  if (dataRange[i][0] == team1){

     outRow = i+1;

    }
  }

 var Header = sheet1.getRange('d1:y1').getValues();
 var u13gneongoalsg1 = sheet1.getRange(outRow,4).getValues();
 var u13gneonshotsg1 = sheet1.getRange(outRow,5).getValues();
 var u13gneontopg1 = sheet1.getRange(outRow,6).getValues();
 var u13gneontop1g1 = sheet1.getRange(outRow,7).getValues();
 var u13gneonfirstg1 = sheet1.getRange(outRow,8).getValues();
 var u13gneonpassesg1 = sheet1.getRange(outRow,9).getValues();
 var u13gneonpasscompg1 = sheet1.getRange(outRow,10).getValues();
 var u13gneonnumpassstringg1 = sheet1.getRange(outRow,11).getValues();
 var u13gneonavgpassstringg1 = sheet1.getRange(outRow,12).getValues();
 var u13gneonlongpassstringg1 = sheet1.getRange(outRow,13).getValues();
 var u13gneonogoalsg1 = sheet1.getRange(outRow,16).getValues();
 var u13gneonoshotsg1 = sheet1.getRange(outRow,17).getValues();
 var u13gneonotopg1 = sheet1.getRange(outRow,18).getValues();
 var u13gneonotop1g1 = sheet1.getRange(outRow,19).getValues();
 var u13gneonofirstg1 = sheet1.getRange(outRow,20).getValues();
 var u13gneonopassesg1 = sheet1.getRange(outRow,21).getValues();
 var u13gneonopasscompg1 = sheet1.getRange(outRow,22).getValues();
 var u13gneononumpassstringg1 = sheet1.getRange(outRow,23).getValues();
 var u13gneonoavgpassstringg1 = sheet1.getRange(outRow,24).getValues();
 var u13gneonolongpassstringg1 = sheet1.getRange(outRow,25).getValues();

  var message = '
';
 message +=   '
';
 message +=   '
U13G Neon	Game Totals	'+team1+ '
';
 message +=   '
' +u13gneongoalsg1+ '	Goals	' +u13gneonogoalsg1+ '
';
 message +=   '
' +u13gneonshotsg1+ '	Shots	' +u13gneonoshotsg1+ '
';
 message +=   '
'+u13gneontopg1 +'	Time of Possession	'+u13gneonotopg1 +'
';
 message +=   '
'+u13gneontop1g1 +'	Time of Possession %	'+u13gneonotop1g1 +'
';
 message +=   '
'+u13gneonfirstg1 +'	First Touches	'+u13gneonofirstg1 +'
';
 message +=   '
'+u13gneonpassesg1 +'	Passes	'+u13gneonopassesg1 +'
';
 message +=   '
'+u13gneonpasscompg1 +'	Pass Completion %	'+u13gneonopasscompg1 +'
';
 message +=   '
'+u13gneonnumpassstringg1 +'	Number of Pass Strings	'+u13gneononumpassstringg1 +'
';
 message +=   '
'+u13gneonavgpassstringg1 +'	Average Pass String Length	'+u13gneonoavgpassstringg1 +'
';
 message +=   '
'+u13gneonlongpassstringg1 +'	Longest Pass String	'+u13gneonolongpassstringg1 +'
';
 message +=   '
';
 message +=   '

';
 message += '';

 MailApp.sendEmail(email, subject, "", {htmlBody: message});
 return outRow;
 }


text:
Q: CSS Animation Is Not Staying I have a page that has an input field and a "next" button. When the user clicks next, I want to shrink the input field and remove the "next" button. I have it mostly working as seen in this Bootply. My CSS animations look like this:
    .default {
        transition: all 1.0s ease;
    }

    .exit {
        padding-left:5rem;
        padding-right:5rem;
    }

    .remove-button {
        animation: animate-remove-button 1.0s;
    }

    @keyframes animate-remove-button {
        from {
            transform:scaleX(1.0);
            opacity: 1.0;
        }

        to {
            transform:scaleX(0);
            opacity: 0;
        }
    }

The animation runs. However, after the animation has completed, the button reappears. In addition, I basically want the width of the button to shrink all the way to 0 so that the text field grows. But, as you can see in the Bootply, that's not really happening, even though it kind of looks like it is.
What am I missing?

A: .remove-button {
  animation: animate-remove-button 1.0s;
  animation-fill-mode: forwards;
}

animation fill mode: forwards tell to keep the last state of animation.
Documentation: https://developer.mozilla.org/en/docs/Web/CSS/animation-fill-mode


text:
Q: looping a ffmpeg command that joins two files Command ffmpeg -i file-1.mp4 -vf ass=file-1a.ass burned-1.mp4
works to burn file-1a.ass subtitles on file-1.mp4 video.
But each time I have to reiterate the same command on over 40 different videos and subtitles and each time I have to wait for rendering the output.
So perhaps there is a way to automatically reiterate the same command on all the files.
Looking for a reply found the loop command
for f in *; do ffmpeg $f;
But I am confused how to use it with 2 files, the .mp4 and the .ass file, and also the output file which should have the same number
I imagine should put the same name on each couple of files, such as:
1.mp4    1.ass
2.mp4    2.ass
3.mp4    3.ass
etc
and then
for f in *; do ffmpeg -i $f.mp4 -vf ass=$f.ass $f-output.mp4
But I have no clear idea

A: You have the right idea. But it won't work if the loop executes with f == 1.mp4, then again with f == 1.ass, and so on.
So you want to modify the loop to only iterate over .mp4 files. Then you want to strip the .mp4 extension from the value of f, that is, strip the last 4 characters from the value of f, using ${f:0: -4} (this means "get a substring of f, starting at character 0 and ending at 5 characters before the end").
You obviously want to terminate the loop with done. I also suggest wrapping the parameters in quotes, to prevent word splitting (that is, if the filenames contain certain characters, they might be split into multiple arguments to ffmpeg).
Putting it all together:
for f in *.mp4; do f=${f%.*}; ffmpeg -i "$f.mp4" -vf ass="$f.ass" "$f-output.mp4"; done
Of course, once you have run this, you need to get rid of all the output files before you can run it again. Or you can just put the output files in a different directory to begin with.

Edit: Another user posted an answer, which seems to have been deleted. It was a good answer but lacked explanation. It was basically the same as my answer, except that it used ${f%.mp4} to strip the .mp4 extension. My answer is probably slightly more complex but slightly more efficient, so it's basically a matter of personal preference.

Edit 2: Based on the link provided by llogan's comment, I have made these changes:

*

*Remove the quotes in the assignment, as assignments are not subject to word splitting (this is also stated in the bash man page).

*Use ${f%.*} to strip the extension. This strips a dot followed by any sequence of characters from the end. It looks for the shortest possible match, so it's really looking for a dot followed by any sequence of non-dot characters at the end.


text:
Q: servlet filter login not work right I have a login project with servlet.
my java classes are:
LoginServlet:
package two;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "admin";
private final String password = "password";

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    // get request parameters for userID and password
    String user = request.getParameter("user");
    String pwd = request.getParameter("pwd");

    if (userID.equals(user) && password.equals(pwd)) {
        HttpSession session = request.getSession();
        session.setAttribute("user", "Pankaj");
        // setting session to expiry in 30 mins
        session.setMaxInactiveInterval(30 * 60);
        Cookie userName = new Cookie("user", user);
        userName.setMaxAge(30 * 60);
        response.addCookie(userName);
        response.sendRedirect("loginSuccess.jsp");
    } else {
        RequestDispatcher rd = getServletContext().getRequestDispatcher(
                "/login.html");
        PrintWriter out = response.getWriter();
        out.println("Either user name or password is wrong.");
        rd.include(request, response);
    }

}

}

LogoutServlet:
package two;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
* Servlet implementation class LogoutServlet
*/
@WebServlet("/LogoutServlet")
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    Cookie[] cookies = request.getCookies();
    if(cookies != null){
    for(Cookie cookie : cookies){
        if(cookie.getName().equals("JSESSIONID")){
            System.out.println("JSESSIONID="+cookie.getValue());
            break;
        }
    }
    }
    //invalidate the session if exists
    HttpSession session = request.getSession(false);
    System.out.println("User="+session.getAttribute("user"));
    if(session != null){
        session.invalidate();
    }
    response.sendRedirect("login.html");
}

}

AuthenticationFilter:
package two;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebFilter("/AuthenticationFilter")
public class AuthenticationFilter implements Filter {

private ServletContext context;

public void init(FilterConfig fConfig) throws ServletException {
    this.context = fConfig.getServletContext();
    this.context.log("AuthenticationFilter initialized");
}

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    String uri = req.getRequestURI();
    this.context.log("Requested Resource::" + uri);

    HttpSession session = req.getSession(false);

    if (session == null
            && !(uri.endsWith("html") || uri.endsWith("LoginServlet"))) {
        this.context.log("Unauthorized access request");
        res.sendRedirect("login.html");
    } else {
        // pass the request along the filter chain
        chain.doFilter(request, response);
    }

}

public void destroy() {
    // close any resources here
}

}

RequestLoggingFilter:
package two;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * Servlet Filter implementation class RequestLoggingFilter
 */
@WebFilter("/RequestLoggingFilter")
public class RequestLoggingFilter implements Filter {

private ServletContext context;

public void init(FilterConfig fConfig) throws ServletException {
    this.context = fConfig.getServletContext();
    this.context.log("RequestLoggingFilter initialized");
}

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    Enumeration<String> params = req.getParameterNames();
    while (params.hasMoreElements()) {
        String name = params.nextElement();
        String value = request.getParameter(name);
        this.context.log(req.getRemoteAddr() + "::Request Params::{" + name
                + "=" + value + "}");
    }

    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            this.context.log(req.getRemoteAddr() + "::Cookie::{"
                    + cookie.getName() + "," + cookie.getValue() + "}");
        }
    }
    // pass the request along the filter chain
    chain.doFilter(request, response);
}

public void destroy() {
    // we can close resources here
}

}

web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>ServletPractice</display-name>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>resources.application</param-value>
</context-param>
<context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<description>
This parameter tells MyFaces if javascript code should be allowed in
the rendered HTML output.
If javascript is allowed, command_link anchors will have javascript code
that submits the corresponding form.
If javascript is not allowed, the state saving info and nested parameters
will be added as url parameters.
Default is 'true'</description>
<param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<description>
If true, rendered HTML code will be formatted, so that it is 'human-readable'
i.e. additional line separators and whitespace will be written, that do not
influence the HTML code.
Default is 'true'</description>
<param-name>org.apache.myfaces.PRETTY_HTML</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<description>
If true, a javascript function will be rendered that is able to restore the
former vertical scroll on every request. Convenient feature if you have pages
with long lists and you do not want the browser page to always jump to the top
if you trigger a link or button action that stays on the same page.
Default is 'false'
</description>
<param-name>org.apache.myfaces.AUTO_SCROLL</param-name>
<param-value>true</param-value>
</context-param>
<listener>
<listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
</listener>

<filter>
<filter-name>RequestLoggingFilter</filter-name>
<filter-class>two.RequestLoggingFilter</filter-class>
</filter>
<filter>
<filter-name>AuthenticationFilter</filter-name>
<filter-class>two.AuthenticationFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>RequestLoggingFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>two/LoginServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/two/LoginServlet</url-pattern>
</servlet-mapping>

</web-app>

login.html:
<!DOCTYPE html>

<meta charset="US-ASCII">
<title>Login Page</title>

<form action="LoginServlet" method="post">

Username: <input type="text" name="user">

Password: <input type="password" name="pwd">

<input type="submit" value="Login">
</form>

loginSuccess.jsp:
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>

<%
    //allow access only if session exists
    String user = (String) session.getAttribute("user");
    String userName = null;
    String sessionID = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("user"))
                userName = cookie.getValue();
            if (cookie.getName().equals("JSESSIONID"))
                sessionID = cookie.getValue();
        }
    }
%>

    Hi
    <%=userName%>, Login successful. Your Session ID=<%=sessionID%>

 User=<%=user%>

Checkout Page
<form action="LogoutServlet" method="post">
    <input type="submit" value="Logout">
</form>

RequestLoggingFilter:
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>

<%
    //allow access only if session exists
    String user = (String) session.getAttribute("user");
    String userName = null;
    String sessionID = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("user"))
                userName = cookie.getValue();
            if (cookie.getName().equals("JSESSIONID"))
                sessionID = cookie.getValue();
        }
    }
%>

    Hi
    <%=userName%>, Login successful. Your Session ID=<%=sessionID%>

 User=<%=user%>

Checkout Page
<form action="LogoutServlet" method="post">
    <input type="submit" value="Logout">
</form>

when I submit in login page , it give 404 error:
 The requested resource (/ServletPractice/two/LoginServlet) is not available.
and my browser addressBar change to : localhost:9090/ServletPractice/two/LoginServlet
please help me. thankes

A: This initial problem looks like it's with the HTML Login form.  I'm assuming, based on the address bar that you receive, you are using localhost:9090/ServletPractice/two/login.html as the login page.
The form <form action="LoginServlet" method="post">...</form> will post to "LoginServlet" at the same level as the HTML page containing the form, but given that you've mapped the login servlet to "/LoginServlet" rather than "/two/LoginServlet" it's not found at the location.
I would therefore try changing the form to be:
<form action="/ServletPractice/LoginServlet" method="post">...</form>

or maybe
<form action="/LoginServlet" method="post">...</form>


text:
Q: Regex - matching patterns without brackets for example I have this string :
ABCDFFFE[_]XXX[_]O0[_]%[TT]__

What I want do achive is, match/change all _ into ?, and % into *, but NOT ! those inside brackets. The last thing is to remove bracket, but I could make it by string replace.
So my output after regex should be like this :
ABCDFFFE[_]XXX[_]O0[_]*[TT]??

and after string replace (or maybe it could be done with regex too)
ABCDFFFE_XXX_O0_%TT__

Thanks in advance

A: Since the [...] texts cannot be nested, you can use the following regex:
(\[[^][]*])|[_%]

See the regex demo
It will capture [...] subtexts into Group 1 (so that we can restore them in the replacement result later) and just matches _ or %.
Use it in the code like this:
var s = "ABCDFFFE[_]XXX[_]O0[_]%[TT]__";
var result = Regex.Replace(s, @"(\[[^][]*])|[_%]", m =>
            m.Groups[1].Success ? m.Groups[1].Value : m.Value == "_" ? "?" : "*");

The m match evaluator block checks if the Group 1 was matched, and if yes, we insert m.Groups[1].Value. If not, we check the m.Value: if it is _, replace with ? (see m.Value == "_" ? "?"), if not - replace with *.
UPDATE
To obtain Result #2, the string without [ and ], you can use
var result = Regex.Replace(te, @"(\[([^][]*)])|[_%]", m =>
            m.Groups[1].Success ? m.Groups[2].Value : m.Value == "_" ? "?" : "*");

The pattern (\[([^][]*)])|[_%] will capture the whole [...] into Group 1 and the contents inside it into Group 2. If Group 1 matches, Group 2 is initialized and we can refer to it with m.Groups[2].Value.
See IDEONE demos for both solutions

A: If you already know that each opening bracket has a closing bracket (brackets are balanced), you can test if a closing bracket doesn't follow with a negative lookahead:
var result = Regex.Replace(s, @"[_%](?![^\]\[]*\])", m => m.Value == "_" ? "?" : "*");


text:
Q: What is the most ethically or morally questionable sysadmin task you have been given? In the recent past I was asked to set up a reporting facility for upper management so they can spy on what web sites users are visiting. This was done without any notice given to users. Unfortunately, I have a good friend with some rather unusual tastes who I knew would be caught! He also knew I set up the reporting...
To me, the lack of user notification was unethical. What similar experiences have you had that haven't "felt right" and left you questioning what to do? How did you deal with it?

A: While not exactly a task I was given, I had to recover from forced downtime.
I used to be the SA for a rather large financial site.
We knew our systems inside and out, had centralized logging and great tools to sift through them.
All of a sudden (naturally very close to a deadline), all the cellphones go crazy with alert messages. Check to see that the site is down, and all SA staff drop what they're doing and start investigating.
Apache logs were fine, database wasn't throwing any errors and the caches were spinning just fine. Plenty of spare resources, network was fine and no recent deployments.
10 minutes later, I find out that one of the developer had gotten access to the site and added a die(); in an obscure module related to page generation.
In other words, the software did what it was told to do, and there was no log information that would've helped.
The GM for the company that ran the site came up with a huge grin and said he wanted to clock us.
I told him to screw off, not touch my production servers, that we did have great disaster recovery plans, but his developer's incompetence made sure none of those plans kicked into gear.
If he wanted to check our response time, he should at the very least have discussed it with the CTO and asked if he could do it "some time today" or "this week". That way nobody would have been pissed off, and we wouldn't have wasted any time arguing about it.
The whole event was one of the most unprofessional ones I've encountered so far.

A: 'Spying' on employee's web activity is par for the course.  The only thing unethical here is if it's not stated anywhere in the employee handbook or other signed disclosures at time of hire.  The long and short of it is the business owns the network and its data, not the user.  As they say in my line of business, "There is no expectation of privacy".

A: I had to ask a new graphic designer (in a former position) to install his cracked copies of photoshop and a few other tools because our boss didn't want to pay for them.
It infected our servers with a virus, which I think was appropriate :)

A: I used to work for a company where management didn't like paying for software. I managed to convince them to buy legal copies of WinXP Pro and Office 2003, but they tried everything to save money. The boss bought a laptop that came with Office Student and Teacher edition, and he discovered the clause about installing on up to three computers. He ignored the part about not for commercial use and told me to use it on a few systems. I told him it was not legal but he didn't care. I begrudgingly proceeded under the hopes that I did my due diligence and wouldn't be at fault should the company get audited. Looking back, I wish that I had reported them.

A: I've been asked to find a way to send copies of every email a user sends and receives to their boss. The person in question was suspected of violating their terms of employment. This kind of Big Brother investigation makes me sick to my stomach. Thankfully, the issue was resolved with out me having to look into this.

A: I Think it is managements right to monitor the network/internet Activity. However i think they should be notifying users that something like this is in place. Irrespective of that as a user working in a Corporate environment i think we should be always just presume that we are being monitored.

A: I was asked by a coworkers wife (also coworker in past but at home now because of pregnancy) to monitor/report his 'strange' activities in e-mal/ICQ/web chats/etc..

A: I was asked by my boss to customize a Linux distribution, brand it with the companies logo and other stuff and then we will sell it with out providing the source. When only 10% code was developed by my company he marketed the whole product as company's own and sold it to customers without providing the source code.
This was the only unethical thing, I am still confused if this was unethical on my part to customize the distribution as I was not part of the marketing and sale of the distribution.
Just went through this, so I thought to post my incident too. :)

A: I was asked to hack the mail password for a co-worker's ex.
'nuff said.