text:
Q: Is there an alternative to do iterative join in spark - scala The use case is to find the n max rows in a given column (these can be n number of columns) and once you have the n keys you join it back to the original dataset to get all the rows you need
val df = Seq(("12", "Tom", "Hanks"),
    ("13", "Meryl", "Streep"),
("12", "Tom", "Hardy"),
("12", "John", "Streep")
).toDF("age", "firstname", "lastname")
Lets say i want to join each column individually with a larger actors dataset which has all the three columns above.
val v1 = actors.join(df, Seq("id"), "inner")
val v2 =actors.join(df, Seq("firstname"), "inner")
val v3 =actors.join(df, Seq("lastname"), "inner")
val output = v1.union(v2).union(v3)

Is there any way to not to do this iteratively ? Also because the columns to be joined against can be dynamic. for eg sometimes it can only be id, or only be id and firstname.

A: You can try different approach, so you can achieve it this way:
actors.join(df).where(
actors("id") === df("id") ||
actors("firstname") === df("firstname") ||
actors("lastname") === df("lastname")
)

and for n-columns you can try it:
  val joinCols = Seq("id", "firstname", "lastname") // or actors.columns
  val condition = joinCols
    .map(s => (actors(s) === df(s)))
    .reduce((a, b) => a || b)

you will get below condition:
condition.explain(true)
(((a#7 = a#7) || (b#8 = b#8)) || (c#9 = c#9))

and finally use it:
   actors.join(df).where(condition)

A: I think doing a broadcast with the smaller dataset and an udf to check with the bigger dataset would solve the issue. i kept thinking in terms of joins!

A: @chlebek solution should work perfectly fine, this is one more approach in the case that you want to reproduce your initial logic:
val cols = Seq("id", "firstname", "lastname")

val final_df = cols.map{
     df.join(actors, Seq(_), "inner")
}
.reduce(_ union _)

First we generate one inner join per column then we union them.


text:
Q: Few Google Checkout Questions I am planning to integrate a Google Checkout payment system on a social networking website. The idea is that members can buy "tokens" for real money (which are sort of the website currency) and then they can buy access to some extra content on the website etc.
What I want to do is create a Google Checkout button that takes a member to the checkout page where he pays with his credit or debit card. What I want is the Google Checkout to notify notify my server whether the purchase of tokens was successful (if the credit/debit card was charged) so I can update the local database.
The website is coded in PHP/MySQL.
I have downloaded the sample PHP code from here: code.google.com/p/google-checkout-php-sample-code/wiki/Documentation
I know how to create a Google checkout button and I have also placed the responsehandlerdemo.php file on my server. This is the file the Google Checkout is supposed to send response to (of course I set the path to the file in Google merchant account).
Now in the response handler file there is a switch block with several case statements. Which one means that the payment was successful and I can add tokens to the member account in the local database?
  switch ($root) {
case "request-received": {
  break;
}
case "error": {
  break;
}
case "diagnosis": {
  break;
}
case "checkout-redirect": {
  break;
}
case "merchant-calculation-callback": {
  // Create the results and send it
  $merchant_calc = new GoogleMerchantCalculations($currency);

  // Loop through the list of address ids from the callback
  $addresses = get_arr_result($data[$root]['calculate']['addresses']['anonymous-address']);
  foreach($addresses as $curr_address) {
    $curr_id = $curr_address['id'];
    $country = $curr_address['country-code']['VALUE'];
    $city = $curr_address['city']['VALUE'];
    $region = $curr_address['region']['VALUE'];
    $postal_code = $curr_address['postal-code']['VALUE'];

    // Loop through each shipping method if merchant-calculated shipping
    // support is to be provided
    if(isset($data[$root]['calculate']['shipping'])) {
      $shipping = get_arr_result($data[$root]['calculate']['shipping']['method']);
      foreach($shipping as $curr_ship) {
        $name = $curr_ship['name'];
        //Compute the price for this shipping method and address id
        $price = 12; // Modify this to get the actual price
        $shippable = "true"; // Modify this as required
        $merchant_result = new GoogleResult($curr_id);
        $merchant_result->SetShippingDetails($name, $price, $shippable);

        if($data[$root]['calculate']['tax']['VALUE'] == "true") {
          //Compute tax for this address id and shipping type
          $amount = 15; // Modify this to the actual tax value
          $merchant_result->SetTaxDetails($amount);
        }

        if(isset($data[$root]['calculate']['merchant-code-strings']
            ['merchant-code-string'])) {
          $codes = get_arr_result($data[$root]['calculate']['merchant-code-strings']
              ['merchant-code-string']);
          foreach($codes as $curr_code) {
            //Update this data as required to set whether the coupon is valid, the code and the amount
            $coupons = new GoogleCoupons("true", $curr_code['code'], 5, "test2");
            $merchant_result->AddCoupons($coupons);
          }
         }
         $merchant_calc->AddResult($merchant_result);
      }
    } else {
      $merchant_result = new GoogleResult($curr_id);
      if($data[$root]['calculate']['tax']['VALUE'] == "true") {
        //Compute tax for this address id and shipping type
        $amount = 15; // Modify this to the actual tax value
        $merchant_result->SetTaxDetails($amount);
      }
      $codes = get_arr_result($data[$root]['calculate']['merchant-code-strings']
          ['merchant-code-string']);
      foreach($codes as $curr_code) {
        //Update this data as required to set whether the coupon is valid, the code and the amount
        $coupons = new GoogleCoupons("true", $curr_code['code'], 5, "test2");
        $merchant_result->AddCoupons($coupons);
      }
      $merchant_calc->AddResult($merchant_result);
    }
  }
  $Gresponse->ProcessMerchantCalculations($merchant_calc);
  break;
}
case "new-order-notification": {
  $Gresponse->SendAck();
  break;
}
case "order-state-change-notification": {
  $Gresponse->SendAck();
  $new_financial_state = $data[$root]['new-financial-order-state']['VALUE'];
  $new_fulfillment_order = $data[$root]['new-fulfillment-order-state']['VALUE'];

  switch($new_financial_state) {
    case 'REVIEWING': {
      break;
    }
    case 'CHARGEABLE': {
      //$Grequest->SendProcessOrder($data[$root]['google-order-number']['VALUE']);
      //$Grequest->SendChargeOrder($data[$root]['google-order-number']['VALUE'],'');
      break;
    }
    case 'CHARGING': {
      break;
    }
    case 'CHARGED': {
      break;
    }
    case 'PAYMENT_DECLINED': {
      break;
    }
    case 'CANCELLED': {
      break;
    }
    case 'CANCELLED_BY_GOOGLE': {
      //$Grequest->SendBuyerMessage($data[$root]['google-order-number']['VALUE'],
      //    "Sorry, your order is cancelled by Google", true);
      break;
    }
    default:
      break;
  }

  switch($new_fulfillment_order) {
    case 'NEW': {
      break;
    }
    case 'PROCESSING': {
      break;
    }
    case 'DELIVERED': {
      break;
    }
    case 'WILL_NOT_DELIVER': {
      break;
    }
    default:
      break;
  }
  break;
}
case "charge-amount-notification": {
  //$Grequest->SendDeliverOrder($data[$root]['google-order-number']['VALUE'],
  //    <carrier>, <tracking-number>, <send-email>);
  //$Grequest->SendArchiveOrder($data[$root]['google-order-number']['VALUE'] );
  $Gresponse->SendAck();
  break;
}
case "chargeback-amount-notification": {
  $Gresponse->SendAck();
  break;
}
case "refund-amount-notification": {
  $Gresponse->SendAck();
  break;
}
case "risk-information-notification": {
  $Gresponse->SendAck();
  break;
}
default:
  $Gresponse->SendBadRequestStatus("Invalid or not supported Message");
  break;

}
I guess that case 'CHARGED' is the one, am I right?
Second question, do I need an SSL certificate to receive response from Google Checkout? According to this I do: groups.google.com/group/google-checkout-api-php/browse_thread/thread/10ce55177281c2b0
But I don's see it mentioned anywhere in the official documentation.
Thank you.

A: I integrated this into my site over 6 months ago. It's very low volume, but works good so far.

The first thing that you should worry about is 'CHARGEABLE'. This means that the credit card has been approved for the transaction, but it will not actually charge the funds until you take action. In order to send the charge request, simply un-comment the two lines under CHARGEABLE. You can change your settings to make it automatically charge the card in 'settings' > 'preferences', but you might as well just un-comment the 2 lines and leave your options open.
Note that you might want to WAIT for the 'risk-information-notification' and determine if the risk check passed before approving the charge ($data[$root]['risk-information']['eligible-for-protection']['VALUE']). Although, seems you are talking about digital goods the possibility of chargebacks might not matter to you.
At some point, I'm sure you should also check that the request has sufficient information for you to link the funds to some account before you charge it, but maybe this is just my paranoia.

The other state that I use is 'charge-amount-notification'. It's completely possible that there is a way to use 'CHARGED', but I don't that 'CHARGED' provides an amount that was actually charged. ($amount_charged = $data[$root]['total-charge-amount']['VALUE'];)

As for the SSL, if you check the location where you enter the callback URL it states the following:
"Specify a URL for Google to notify you of new orders and changes in order state. You must provide the URL of a server running 128-bit SSLv3 or TLS"

Answer to your comment:
I do this under 'new_order_notification', not sure if you can do it elsewhere.

$items = get_arr_result( $data[$root]['shopping-cart']['items']['item'] );
foreach( $items as $item ) {
   if( !isset ( $item['merchant-item-id']['VALUE'] ) ) {
     //error
     return;
   }
   $request_item_id = $item['merchant-item-id']['VALUE'];
   //save your item id with corresponding google order id for further processing
}

A: Yes, "Chargeable" is the first thing you need to look at in a Google Checkout order. When you click "Chargeable", a window will pop up for you to actually charge the order BUT be sure that the "Eligible for Protection" is True before actually charging the order. This ensure you that the payment is covered by Google payment guarantee. You can actually see it in the "Buyer Credit Verification" section in Google Checkout.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I format Int32 numbers? What is the best way to get formatted Int32 numbers?
Let say I have this o function:
string o(int x);

This is the value that o need to return according to x
x = 0    =>    o = 00
x = 1    =>    o = 01
x = 5    =>    o = 05
x = 10   =>    o = 10
x = 31   =>    o = 31
x = 106  =>    o = 106

A: when int x
use
 x.ToString("00");
 String.Format("{0:00}",x);

A: string o(int x)
{
    return string.Format("{0:00}", x);
}

A: Can use PadLeft to a total padding width of 2 with the character '0'.
string o(int x) {
    return x.ToString().PadLeft(2, '0');
}


text:
Q: php smtp ssl html mail not working Can someone please advise I already looked online and tried everything I can think of my I am only getting plain text email...
Email part is working is only the HTML stuff not I get the $body (message) in raw code rather than html format.
Here is my code:
    <?php
 require_once "Mail.php";

 $from = "Home Calendar <calendar@home>";
 $to = "Me Yahoo <me@yahoo.co.uk>, Me Gmail <me@gmail.com>";
 $subject = "TESTING PHP EMAIL";
 $body = "

        <title>HTML email</title>

This email contains HTML Tags!

            Firstname
            Lastname

            Ricardo
            Wagemaker

";

 $host = "ssl://mail.domain.co.uk";
 $port = "465";
 $username = "name@domain.co.uk";
 $password = "password";

$headers = array (
        "MIME-Version: 1.0",
        "Content-type: text/html; charset=ISO-8859-1",
        'From' => $from,
        'To' => $to,
        'Subject' => $subject
        );

 $smtp = Mail::factory('smtp',
   array ('host' => $host,
     'port' => $port,
     'auth' => true,
     'username' => $username,
     'password' => $password));

 $mail = $smtp->send($to, $headers, $body, $from, $subject);

 if (PEAR::isError($mail)) {
   echo("
" . $mail->getMessage() . "
");
  } else {
   echo("\n\n
Message successfully sent!
\n\n");
  }
 ?>

Many Thanks

A: Well no help but I finally figured it out, it was all about the new line "rn" missing from my headers..
Here is the modification that worked.
$headers = array (
    'MIME-Version' => '1.0rn',
    'Content-Type' => "text/html; charset=ISO-8859-1rn",
    'From' => $from,
    'To' => $to,
    'Subject' => $subject
 );


text:
Q: Typescript. How to get enum item data as a type I have an enum type, for example Currency. I cant to change it because it automatically builds on a graphql schema. I want to use it for my data, but I dont know how to do.
enum Currency {
  rub = 'RUB',
  usd = 'USD',
  eur = 'EUR',
}

const data: { currency: Currency[keyof typeof Currency] } = {
  currency: 'RUB',
};

Errors
TS2339: Property 'eur' does not exist on type 'Currency'.
TS2339: Property 'rub' does not exist on type 'Currency'.
TS2339: Property 'usd' does not exist on type 'Currency'.

A: I'm not sure it's possible to do exactly what you're trying to do but most likely, you'd want to do something like this:
const data: { currency: Currency } = {
  currency: Currency.rub,
};

This is how enums are typically used (by always explicitly referencing the enum when getting one of its values).


text:
Q: chrome.tabs.executeScript|insertCss works off across through once I add styles and scripts to a certain site in the background.
chrome.tabs.onUpdated.addListener (function (tabId, changeInfo, tab) {
        console.log (tabId, changeInfo, tab);
        if (changeInfo.status === 'complete' && siteUrl.test (tab.url)) {
            insertCss (tab.id, '/css/bootstrap.min.css', function () {
                insertCss (tab.id, '/css/jquery.toast.min.css', function () {
                    insertCss (tab.id, '/css/content_style.css', function () {
                        executeScript (tab.id, '/js/utils/jquery-3.3.1.js', function () {
                            executeScript (tab.id, '/js/utils/js.cookie.js', function () {
                                executeScript (tab.id, '/js/utils/jquery.toast.min.js', function () {
                                    executeScript (tab.id, '/js/utils/sweetalert2.js', function () {
                                        executeScript (tab.id, '/js/core.js', function () {
                                            executeScript (tab.id, '/js/content_script.js', function () {
                                                console.warn ('FILES INJECTION COMPLETE');
                                            });
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        }
    });

When you go to the page everything is OK injected, but if you later update the page, the styles and scripts are inserted through the times - once you update nothing, once again, everything appears.
why is that?
If you write to manifest.json content_scripts, that also does not always work. It sometimes opens a page (does not restart) and nothing is loaded.


text:
Q: Textbox validation in jquery i am validating the text box value on following conditions

*

*It should be minimum of 3 characters

*It should contain only alphabets

*It should contain at least one vowel
If all the conditions get matches I am enabling the submit button.
If any of the above case are not matched I am setting an error message to div named error.
Here is my code
$document.ready(function(){

 $('.tbox').focus(); // cursor in text box
 $(':submit').attr("disabled",true); // disable generate button

    $('.tbox').focus(fucntion(){

        check_the_input()
    });

    });

function check_the_input()
{

    var value = $(this).val();

    $('.tbox').bind('keyup blur',function(){
    $(this).val( $(this).val().replace(/[^a-z]/g,'') ); }

    if(value.length > 3)
    {
        if(value.indexOf('a') == -1 && value.indexOf('e') == -1 && value.indexOf('i') == -1 && value.indexOf('o') == -1 && value.indexOf('u') == -1)
        {
            $('#error').text("*Input must contain atleast one vowel");
            $(':submit').attr("disabled",true);

        }
        else
        {
            $(':submit').attr("disabled",false);
        }

    }
    else
    {
        $('#error').text("*Input should be atleast 3 characters")
        $(':submit').attr("disabled",true);
    }

    setTimeout(check_the_input,100);
}

I am facing following issues here:

*

*If I type input as aa99 the input changes to aa , but still the generated button is enabled.

*I am not getting the error at the time I type the text. Only after pressing tab or clicking mouse outside the textbox I am getting error.

A: I would suggest rethinking the approach. Consider this simpler example:
HTML:
<form>
  <input type="text" id="myinput"/>
  <button id="submit" type="submit" disabled>Submit</button>

</form>

jQuery:
By using a function test and an object to store your validation filters your code becomes more obvious, more elegant and you get better performance and it's easier to maintain for example to add new filters or more inputs.
Demo: http://jsbin.com/ezatap/6/edit
var $input = $('#myinput');
var $error = $('.error');
var $submit = $('#submit');
var Filters = {
  min: {
    re: /.{3,}/,
    error: 'Must be at least 3 characters.'
  },
  char: {
    re: /^[a-z]+$/i,
    error: 'Must be only letters.'
  },
  vowel: {
    re: /[aeiou]/i,
    error: 'Must have at least one vowel.'
  }
};

function test(value, filters) {
  var isValid = false;
  for (var i in filters) {
    isValid = filters[i].re.test(value);
    $error.hide();
    $submit.prop('disabled', false);
    if (!isValid) {
      $error.show().text(filters[i].error);
      $submit.prop('disabled', true);
      break;
    }
  }
  return isValid;
}

test($input.val(), Filters);
$input.on('keyup blur', function() {
  test(this.value, Filters);
});

A: To the first question:
else
{
    $('#error').text("*Input should be atleast 3 characters")
}

=>
else
{
    $('#error').text("*Input should be atleast 3 characters");
    $(':submit').attr("disabled",true);
}

To the second question:
When the input is being edited, no callback will be called until the input lost its focus.
If you would like to change the style of the :submit when editing, you can setup a periodically called function that checks the input every few milliseconds. here's a simple example:
function check_the_input( )
{
   //routines check the input
   //...

   setTimeout( check_the_input, 100 ); //call me after 0.1 second
}

$(document).ready( function( ) { check_the_input( ) } );

of course there's more work to do if you want higher efficiency.
fix several error, see this: http://jsfiddle.net/4E7vv/2/


text:
Q: How to Execute stored procedure from SQL Plus? I have a stored procedure in oracle and want to test it from SQLPlus.
If I use
execute  my_stored_proc (-1,2,0.01)

I get this error
PLS-00306: wrong number or types of arguments in call to my_stored_proc

The beginning for the proc is this
create or replace PROCEDURE my_stored_proc
( a IN NUMBER,
  b IN NUMBER,
  c IN NUMBER,
  z out NUMBER
) AS ....

Do I need to provide the a var for the out parameter, is so how?  I tried:
var z  NUMBER;

But get this error when I try to run the proc
execute  my_stored_proc (-1,2,0.01,z)
PLS-00201: identifier 'Z' must be declared

Also when I  was in SQL-Developer it gave me the usage and it show the inputs in reverse order, that is:
execute my_stored_proc(z number,c number,b number,a number);

Do you provide them in reverse order or is that just something with SQL-Developer
I did not write the procedure and I don't normally deal with them so I could be missing something obvious.
Thanks

A: You have two options, a PL/SQL block or SQL*Plus bind variables:
var z number

execute  my_stored_proc (-1,2,0.01,:z)

print z

A: You forgot to put z as an bind variable.
The following EXECUTE command runs a PL/SQL statement that references a stored procedure:
SQL> EXECUTE -
> :Z := EMP_SALE.HIRE('JACK','MANAGER','JONES',2990,'SALES')

Note that the value returned by the stored procedure is being return into :Z


text:
Q: No CacheResolver specified, and no unique bean of type CacheManager found I am trying to use two Different types of Cache in my Spring boot application,based on Rest API called I hvae to store data in my cache. But during project deploy stage I am getting below error.
[main] ERROR o.s.boot.SpringApplication - Application startup failed
2020-06-30T11:15:17.05+0530 [APP/PROC/WEB/0] OUT java.lang.IllegalStateException: No CacheResolver specified, and no unique bean of type CacheManager found. Mark one as primary (or give it the name 'cacheManager') or declare a specific CacheManager to use, that serves as the default one.
Can I specify @Primary on one cache manager ?I hope it does not stop storing data into another cache . Or is their a better way of doing this?
CacheConfig.java
@Profile("cloud")
public class CacheConfig extends AbstractCloudConfig {

@Autowired
Environment env;

@Bean
public RedisConnectionFactory brRedisFactory() {
    return connectionFactory().redisConnectionFactory(env.getProperty("redis_cache"));
}

@Bean
public RedisTemplate<String, Object> brRedisTemplate() {
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
    redisTemplate.setConnectionFactory(brRedisFactory());
    return redisTemplate;
}

@Bean(name = "firstCacheMngr")
public CacheManager cacheManager() {
    RedisCacheManager cacheManager = new RedisCacheManager(brRedisTemplate());
    cacheManager.setUsePrefix(true);
    cacheManager.setTransactionAware(true);
    return cacheManager;
}

@Bean(name = "secondCacheMngr")
public CacheManager springCacheManager() {
    SimpleCacheManager cacheManager = new SimpleCacheManager();
    cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("secondCache")));
    return cacheManager;
}

}

This is how I am storing data in redis cache-
@Cacheable(value="redis-cache",key ="#customerId",cacheManager = "firstCacheMngr")
public CustomerInfo retriveCustomerdetails(String customerId
        String quarterEndDate)  {
     //Calling Rest API
    }
    return customerInfo;
}

A: you can put one as @Primary and inject the another one by using @Qualifier
@Bean(name = "firstCacheMngr")
public CacheManager cacheManager() {
    RedisCacheManager cacheManager = new RedisCacheManager(brRedisTemplate());
    cacheManager.setUsePrefix(true);
    cacheManager.setTransactionAware(true);
    return cacheManager;
}

@Bean(name = "secondCacheMngr")
@Primary
public CacheManager springCacheManager() {
    SimpleCacheManager cacheManager = new SimpleCacheManager();
    cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("secondCache")));
    return cacheManager;
}

and then use the redisCachManager as
    @Autowired
    @Qualifier("firstCacheMngr")
    private CacheManager cacheManager;


text:
Q: Controlling the terminal while in the middle of a pipe Say I have 3 commands linked through pipes:
A | B | C

I would like B to output error messages to stderr and some progress to the terminal. If stderr is the same as the terminal, then that is easy: Simply send the progress information to stderr. But what if stderr is redirected?
A | B 2>/tmp/file | C

Then I still want the progress information to go to the terminal, while error messages go to the file.
Can I now somehow identify the terminal that stderr would have ended up on had it not been redirected?
My initial idea would be to find the tty using tty and then opening that and writing to it. However, if I call tty from inside B tty says: not a tty, which I believe is because of the pipe between A and B.
I would like to do this from Perl.

A: Linux specific:
echo |perl -e '$p=getppid; `echo foo > /proc/$p/fd/2`'

If you here redirect stderr 'foo' is still printed on the terminal:
echo |perl -e '$p=getppid; `echo foo > /proc/$p/fd/2`' 2>/dev/null


text:
Q: Best way to pass model from partial view to controller using AJAX? I'm not sure exactly how to phrase this question but I've been working on a table sorter as a way of getting to grips with AJAX and JQuery in ASP.NET MVC.
So far it works, using this code:
Partial View:
@model IEnumerable<EH.SASS.TillStatus.Model.Models.TillTransactionsOnHold>
<link href="~/Content/Site.css" rel="stylesheet" />

                Till Network ID

                Transaction Type

                TID

                Transaction ID

                Card No.

                Receipt No.

                Scheme

                Amount

                Date

                Resolved

                Date Resolved

                Resolved by

                Date Created

            @foreach (var item in Model)
   {

                        @Html.DisplayFor(modelItem => item.Till.NetworkId)

                        @Html.DisplayFor(modelItem => item.TransactionType.Description)

                        @Html.DisplayFor(modelItem => item.TID)

                        @Html.DisplayFor(modelItem => item.TransactionId)

                        @Html.DisplayFor(modelItem => item.CardNo)

                        @Html.DisplayFor(modelItem => item.ReceiptNo)

                        @Html.DisplayFor(modelItem => item.SchemeType.Description)

                        @Html.DisplayFor(modelItem => item.Amount)

                        @Html.DisplayFor(modelItem => item.TransactionDate)

                        @Html.DisplayFor(modelItem => item.Resolved)

                        @Html.DisplayFor(modelItem => item.ResolvedDate)

                        @Html.DisplayFor(modelItem => item.User.EHLogin)

                        @Html.DisplayFor(modelItem => item.CreatedDate)

                        @Html.ActionLink("Edit", "Edit", "TransactionsOnHold", new { id = item.TillTransactionsOnHoldUid_PK }, null)
                        @if (!item.Resolved)
     {
                            @Html.ActionLink("Resolve", "Resolve", "TransactionsOnHold", new { id = item.TillTransactionsOnHoldUid_PK }, null)
     }

   }

JQuery/AJAX:
function sort(tableid, controllername, actionname) {
    $(tableid).find( 'th' ).click(function () {
        var sortBy = $( this ).data("attr");

        $.ajax({
            cache: false,
            url: "/"+controllername+"/"+actionname,
            data: "{ 'sortBy': '" + sortBy + "' }",
            dataType: "html",
            type: "POST",
            async: "true",
            contentType: "application/json; charset=utf-8",
            dataFilter: function (data) { return data; },
            success: function (data) {
                $("#tablediv").html('');
                $("#tablediv").html(data);
            },
            error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
        });
    })
}

Controller:
public PartialViewResult _heldTransactionTable(string sortBy)
{
        var tilltransactionsonhold =  db.TillTransactionsOnHold...

        if (sortBy == (string)Session["sortBy"])
        {
            switch (sortBy)
            {
                case "tillnetworkid":
                    tilltransactionsonhold = tilltransactionsonhold
                    .OrderBy(m => m.Till.NetworkId);
                    break;
                case "transactiontype":
                    tilltransactionsonhold = tilltransactionsonhold
                    .OrderBy(m => m.TransactionType.TransactionTypeUid_PK);
                    break;
                case "tid":
                    etc..etc..
            }
            Session["sortBy"] = "";
        }
        else
        {
            Session["sortBy"] = sortBy;
            switch (sortBy)
            {
                case "tillnetworkid":
                    tilltransactionsonhold = tilltransactionsonhold
                    .OrderByDescending(m => m.Till.NetworkId);
                    break;
                case "transactiontype":
                    tilltransactionsonhold = tilltransactionsonhold
                    .OrderByDescending(m => m.TransactionType.TransactionTypeUid_PK);
                    break;
                case "tid":
                    etc...etc...
            }
        }

        return PartialView(tilltransactionsonhold.ToList());
    }

You'll notice some of the code I removed to save reading time, and I also appreciate that it is not the best solution, it is a learning exercise, for which any bits of advice are welcome.
Filtering a brand new datamodel fresh from the database every time would suck in a widely used application, and it would be far more efficient to only filter the model itself.
My question is this: What would be a good way to pass the data model to the controller from the partial view without heavily modifying the existing code, so that I don't have to query the database as much?

A: Well, posting back an HTML representation of your data is worse than useless. There's nothing reasonable you can do with that. The way one would typically handle this sort of thing is to have a hidden input for each row that records it's "order" and a hidden input containing some identifier to be able to determine which object to apply that order to. You'd have to update this "order" input any time the sort changed, but any good library should have some callback for that.
Then, you would post these field values, which in AJAX would either be as a JSON object or as x-www-form-urlencoded (the name-value pair jazz you often see in URLs, e.g. foo=1&bar=2). In your post action, you would use the id values to look up the corresponding objects and then apply the order values to those objects. Then, save the updates back to your database.


text:
Q: This tab is not available on mobile Recently, our (published) app stopped working on mobile, with the above message, "This tab is not available on mobile". The app is a custom teams tab basically.
What can be causing this issue?
From our side, we have not changed anything (neither in the manifest nor in the hosting).
Are there some changes in the teams policy or maybe some new requirements or changes?
In the desktop/web client the app works like it did before. On the mobile, if you try to click a link to the app tab, it shows this notification tooltip "not available on mobile" instead of opening the tab.
Manifest version: 1.9
"@microsoft/teams-js": "^1.12.1",

Not sure, if the versions are related, the mobile client shows that tooltip without even trying to open the tab.
It looks like the problem appeared with some latest update of the Teams client. The app is still working fine with Teams client from June 2022, but starts showing this message "tab is not available on mobile" if the Teams mobile client is updated to the latest version.
I have noticed that now there is a button to "Add an app.." in the teams app on mobile. Are there some new requirements for existing apps because of this maybe (so that existing apps won't work on mobile unless adapted)?
Related observation: all app tabs created disappeared on "More..." tab after mobile teams client is updated
Appreciate any insights what might be causing the issue?

A: Posting the solution here from the linked issue if somebody else faces it. The message was appearing because websiteUrl property was not set in the tab configuration. It is now required for the tab to appear in the mobile client. Setting this property in the tab configuration resolves the issue.


text:
Q: How to share map with pushpins : Bing Maps, WP8.1, Map Control I'm working with MapControl from wp8.1 default controls. I can add different elements on map:
MapControl.MapElements.Add(polygonElement);
MapControl.MapElements.Add(mapIcon);

The question is, how to share this element to somebody? When I use Bing Maps browser app I can simply click on "share" button and get a link
http://binged.it/1zEKwlo
that will display all added data to anyone who has this link. Is there any way to share MapElements to another user?

A: Not really. If you want to share a map view you could capture a screenshot and send that, but that wouldn't be very interactive and I'm guessing not what you want. If you only want to share point based data then you can create a link to the Bing Maps consumer site which would cause the native maps app on Windows Phone to open (opens in browser for other apps). This would allow you to share a single point. If you want to share anything more than that I would recommend creating a mobile website that either loads data from the URL string, or from a database. If you are only sharing a little bit of data a URL might be enough. If you have enough data to make a URL longer than 2083 characters then you will need to look at a different solution. One option is to create a web service for saving the map view. This could generate a unique ID for the view and then you could pass that ID to a custom mobile website as a parameter in the URL. This process requires a decent amount of development but would remove most limitations you will encounter using other approaches. If you use this method I recommend taking a look at the Azure mobile services as you can quickly and easily create a web service that is connected to a database. You can even add authentication easily as well if you wanted.


text:
Q: How to get data from already fetched rtk-query I want to get already fetched data in Navbar from profileApi which used in profile component.
I want to display image on Navbar but image is available in profileApi and contains lots of user data, so i dont want to call same API for navbar just for image.
So is there any way to achieve this? or can we set data profileApi data to redux store somehow and get from there, like we do without rtk-query.
if somehow data set to redux store then how gonna access from rtk reducers?
const store = configureStore({
  reducer: {
    auth: AuthSlice.reducer,
    [UsersPostApi.reducerPath]: UsersPostApi.reducer,
    [ProfileApi.reducerPath]: ProfileApi.reducer,
  },
  // Adding the api middleware enables caching, invalidation, polling,
  // and other useful features of `rtk-query`.
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat([
      UsersPostApi.middleware,
      ProfileApi.middleware,
    ]),
});

for auth i can do
let { data } = useSelector((state) => state.auth);

But How to access ProfileApi to get data in any component?
Update: the route /api/profile/:id
im using params to get user data in profile
let { userbyname } = useParams();
const { data, error } = useGetProfileQuery(userbyname);

A: First, it's not recommended and suggested as no go pattern to have multiple api's in same app. You have injectEndpoints and enchanceEndpoints, more link
As for the question answer, after you do:
const { data, isLoading
, isError, error } = useProfileQuery(undefined)

You can do the same anywhere in your app, and get data from cache. You don't need to do anything more then that.
Note the undefined passed as args, this is used as key for accessing cached data when query doesn't have any args.


text:
Q: How to change tab bar item text color
How can I change the color of "More.." text in tabbar to match with its icon color.  (Right now Performance is selected in the tab bar)
I tried to set TitleTextAttributes.
[moreItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaLTStd-Roman" size:10.0f], NSFontAttributeName,  [UIColor yellowColor],NSForegroundColorAttributeName , nil]

But it the text color is always set to yellow. even when the item is selected. Like this

I am trying set to white when selected and when unselected it should match with icon color.
Thanks..
Any suggestions will be really helpful.

A: Code free way to do this:
If you are just using iOS 10 then you may change the Image Tint in your Tab Bar

If you are also supporting iOS 9 and lower, then you must also add tintColor to your user definer runtime attributes in each tab bar item

if you also wish to change your icon color make sure the correct color image is in your assest folder and change Render as to Original Image

A: Swift 5.1 + iOS 12.4 & iOS 13:
/// Subclass of `UITabBarController` that is used to set certain text colors for tab bar items.
class TabBarController: UITabBarController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let items = tabBar.items {
            // Setting the title text color of all tab bar items:
            for item in items {
                item.setTitleTextAttributes([.foregroundColor: UIColor.black], for: .selected)
                item.setTitleTextAttributes([.foregroundColor: UIColor.lightGray], for: .normal)
            }
        }
    }
}

A: This is the swift version :-
        for item in self.mainTabBar.items! {

          let unselectedItem: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()]
          let selectedItem: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()]
          item.setTitleTextAttributes(unselectedItem as? [String : AnyObject], forState: .Normal)
          item.setTitleTextAttributes(selectedItem as? [String : AnyObject], forState: .Selected)

        }

Or you can simply change in Appdelegate :-
 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blueColor()], forState: .Selected)
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blackColor()], forState: .Normal)
    // Override point for customization after application launch.
    return true
}

A: The accepted answer's code not work for me.
Here is code, that works:
    [[UITabBarItem appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor yellowColor] }
                                             forState:UIControlStateNormal];
    [[UITabBarItem appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] }
                                             forState:UIControlStateSelected];

A: Swift 4:
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.white], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.red], for: .selected)

A: For a swift solution, let type inference be your friend:
override func viewWillAppear(animated: Bool) {
  for item in self.tabBar.items! {
    let unselectedItem = [NSForegroundColorAttributeName: UIColor.blackColor()]
    let selectedItem = [NSForegroundColorAttributeName: UIColor.whiteColor()]

    item.setTitleTextAttributes(unselectedItem, forState: .Normal)
    item.setTitleTextAttributes(selectedItem, forState: .Selected)
  }
}

A: Swift version of @skywinder answer :
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.whiteColor()], forState: .Normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.whiteColor()], forState: .Selected)

A: Nowadays if your app supports version of iOS less than 13, you should set this colours different ways:
if #available(iOS 13, *) {
    let appearance = UITabBarAppearance()
    appearance.stackedLayoutAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: .red]
    tabBar.standardAppearance = appearance
} else {
    UITabBarItem.appearance().setTitleTextAttributes(UIColor.red, for: UIControl.State.selected)
}

In code example I set red text color for selected states of UITabBarItem, you may also need to change text color for normal state.

A: I found the answer for my own question.
We can set perforamceItem setTitleTextAttributes: for  two different states.

*

*forState:UIControlStateNormal

*forState:UIControlStateHighlighted
I added the following code
 [performanceItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaLTStd-Roman" size:10.0f], NSFontAttributeName,  [UIColor yellowColor], NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];

[performanceItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaLTStd-Roman" size:10.0f], NSFontAttributeName,  [UIColor whiteColor], NSForegroundColorAttributeName,nil] forState:UIControlStateHighlighted];

I need to replace the yellow color with the color of my ICONS. This is how they are looking now.
When More is selected

When Performance is Selected

A: This is easy , simply subclass UITabBarItem and assign it to be the class of your tab bar item in either storyboard or code. The below works perfectly for me.
import UIKit

class PPTabBarItem: UITabBarItem {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }
    override init() {
        super.init()
        commonInit()
    }

    func commonInit() {
        self.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFontOfSize(13), NSForegroundColorAttributeName:UIColor.blackColor()], forState: UIControlState.Normal)

        self.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFontOfSize(13), NSForegroundColorAttributeName:UIColor.yellowColor()], forState: UIControlState.Selected)
    }
}

skywinder's solution is good but it triggers global scope.

A: This works correctly..
 [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                        [UIColor redColor], NSForegroundColorAttributeName,
                                                       nil] forState:UIControlStateSelected];

    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                       [UIColor blackColor], NSForegroundColorAttributeName,
                                                       nil] forState:UIControlStateNormal];

A: You could set the tintcolor and unselectedItemTintColor of UITabBar to change it's appearance.
self.tabBar.tintColor = // Your colour
self.tabBar.unselectedItemTintColor = // Your unselected item colour

A: This worked for me on Swift 5.
In AppDelegate :
 UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.red], for: .selected)


text:
Q: Debug Pascal's Triangle Could someone please walk me through as to what I did incorrectly on Pascal's Triangle in Javascript? I saw a thread that already exists using recursion however, without copying verbatim, the code, in my eyes, looks too similar to decipher what I'm doing wrong. I could use some fresh eyes on what I've missed or could improve. Thank you

var pTri = [[1]]

function pascalTriangle(num, pTri) {

  if (num < 2) {
    return pTri;
  }

  var newRow = [1];
  var lastRow = pTri[pTri.length - 1];

  console.log(lastRow)

  for (var i = 1; i < lastRow.length; i++) {
    var addToNewRow = lastRow[i] + lastRow[i - 1];
    newRow.push(addToNewRow);
    }

  pTri.push(newRow);

 return pascalTriangle(num - 1, pTri);
}

pascalTriangle(2, pTri)

A: Just looks like you added a new array 'addToNewRow' by mistake.

var pTri = [[1]]

function pascalTriangle(num, pTri) {

  if (num < 2) {
    return pTri;
  }

  var newRow = [1];
  var lastRow = pTri[pTri.length - 1];

  console.log(lastRow)

  for (var i = 1; i < lastRow.length; i++) {
    newRow[i] = lastRow[i] + lastRow[i - 1];
  }

  newRow.push(1);

  pTri.push(newRow);

 return pascalTriangle(num - 1, pTri);
}

pascalTriangle(10, pTri)


text:
Q: Como guardar configurações do programa, banco de dados ou arquivo de configuração? Em meu aplicativo, o usuário administrador, pode fazer algumas configurações, por exemplo:

*

*Configurar se deseja utilizar modelos determinados de produtos, ou fica em aberto para o usuário final digitar.

*Configurar se deseja utilizar tabela TIPE, ou se o NCM ira ficar aberto para o usuário final digitar.

São configurações que afetarão todo o sistema, e muda a logica do processamento.
Hoje guardo esses set's, no app.config, mas estive me perguntando, seria a melhor maneira?
Talvez, gravar tais configurações no banco e ao executar a tarefa faço um SELECT antes para verificar como esta configurado?
Ou não, o app.config é realmente para isso, como o nome já diz? acho!
Vamos imaginar, uma aplicação que roda no servidor, não na maquina local.

A: O melhor para você nesse situação específica só você pode dizer.
O app.config é usado para configurações gerais do funcionamento da aplicação. Normalmente não deve ser usado para configurar funcionamento específico. Nem sempre é fácil determinar o que é um e o que é outro. Entenda que ele não foi feito para ter alterações frequentes.
Se tem um banco de dados eu acho que a maioria das configurações deveriam estar nele.
Até onde eu entendo essas informações são bem específicas e só são úteis se o banco de dados está disponível. Já fiz diversos sistemas assim e nunca sequer cogitei não colocar no banco de dados.
Não consigo imaginar nesse caso porque colocar isso no arquivo de configuração. Pode até ser que precise fazer algo só no banco de dados e sem elas dentro dele seria complicado realizar. Essas informações são de domínio específico e não da aplicação como um todo. É um erro colocar em app.config.
No geral
O que deve colocar na configuração fora do banco de dados:

*

*o que diz como acessar o banco de dados direta ou indiretamente, que por razões óbvias não pode estar dentro do próprio (pode ser informações de rede)

*informações que outras aplicações ou o ambiente de execução precisam acessar em algum momento

*outras situações que consiga dar uma boa justificativa para por lá.

No banco de dados você tem essa informação mais "protegida". E tem mais recursos, até mesmo para auditoria e versionamento.
Em alguns casos se não quiser colocar no banco de dados, precisa pensar se não é o caso de usar um arquivo de configuração separado. Acho raro precisar de algo assim.
Obviamente que se usar uma biblioteca que obrigue colocar configuração lá, não tem o que decidir, a não ser pensar em trocar de biblioteca :)
Se a aplicação não tem um banco de dados, claro que essa solução não é ideal.
Há quem use o SQLite como arquivo de configuração. Se for só para isso, a não ser que a configuração seja muito complexa, não acho viável. Mas se o SQLite já está lá por alguma razão, aí pode ser uma boa colocar nele.
Se só tem o banco de dados em outra máquina é possível que queria usar a aplicação mesmo desconectado. Aí é motivo para usar um arquivo de configuração. Ou um banco de dados local como o SQLite, se já o usa para alguma outra coisa.
Por outro lado se deseja que aquele usuário tenha suas configurações preservadas em todas máquinas que vá usar, colocar as configurações em um banco de dados centralizado é a única opção, ainda que possa existir uma forma híbrida para atender o casos desconectados.
É mais fácil fazer certo no banco de dados.
A regra básica é usar o banco de dados, e só optar por outra forma se tiver um bom motivo para fazê-lo. Mas só deve estar lá configurações que só são necessárias quando o banco de dados está disponível.

A: Em meu entendimento, tanto app.config no WinForms e o web.config no WebForms, devem ser usados para configurações para funcionamento do sistema, de forma que o sistema não funcione sem determinada configuração.
No seu caso, acredito que isso é parametrização. Parâmetros diferentes fazem o sistema "pensar" diferente. Nesse caso, eu colocaria tal informação no banco. Dessa forma você pode fazer tela para controlar tal parametrização sem precisar mexer nos arquivos físicos do sistema.
Eu faria dessa forma.


text:
Q: Converting date formats in PHP I have a date:
20-01-2013

I need it to be in a format for the database:
2013-01-20 20:39:39

So far I have this:
$originalDate = "20-01-2013";
$newDate = date("Y-m-d", strtotime($originalDate));

But how do I get the time added to the end? I just want it to be 00:00:00.
Thanks

A: Why don't you just do it like this?
$originalDate = "20-01-2013";
$newDate = date("Y-m-d", strtotime($originalDate)).' 00:00:00';

A: You are one step away from solution you just need to insert h:i:s in your date() function, so please try this:
$newDate = date("Y-m-d H:i:s", strtotime($originalDate));

or either append the string
$newDate = date("Y-m-d 00:00:00", strtotime($originalDate));

A: $newDate = date("Y-m-d H:i:s", strtotime($originalDate));
read more about date


text:
Q: Remove duplicate events in FullCalendar i have a FullCalendar where i generated a whole week with events.
From the database i got all events wich are blocked.
The blocked events could be same length or longer.
My problem is, after hours of trying, that i either delete the wrong events or no events.
My biggest problem is to compare the 2 events.
I work with moment.js and moment-range.js.
The goal is that the blocked events are not even more in the calendar and the time from the blocked event are empty.
I posted my code on http://cssdeck.com/labs/full/onipancb.
If you have any question feel free to ask.
Many thanks in advance.
Initialization
events = [];

var myCalendar = $('#calendar').fullCalendar({
    minTime: "08:00:00",
    maxTime: "19:00:00",
    firstDay: moment().format('e'),
    defaultView: 'agendaWeek',
    weekends: false,

  });

Fill Calendar with generated events
function fillCalendarWithEvents() {

    $('#calendar').fullCalendar('removeEventSources', events);
    var currentDate = moment.now();
    var beginOfWeek = currentDate.start;
    var endOfWeek = currentDate.end;
    var startDay = moment(beginOfWeek).set({
      'hour': 8,
      'minute': 0
    });

    var minutesOfBlock = 30;

    for (var day = 0; day < 14; day++) {

      for (var blocks = 0; blocks < 24; blocks++) {

        var startEvent = startDay.format();
        var endEvent = startDay.add(minutesOfBlock, 'm').format();

        if (isEventNotInPast(startEvent)) {

          events.push({
            title: 'Freier Termin',
            start: startEvent,
            end: endEvent,
            backgroundColor: '#66cdaa',
            url: ""
          });

        }

      }
      startDay.add(1, 'd').set({
        'hour': 8,
        'minute': 0
      });
    }
  }

Remove events if they are same like blockedEvents
  function removeBlockEvents(){
    for(var all = 0; all < events.length; all++){
      for(var blocked = 0; blocked < blockedEventsJSON.length; blocked++){
      const  range = moment.range(events[all].start, events[all].end);
        start = moment(blockedEventsJSON[blocked].begin);
        if(range.contains(start)){
          events.splice(all, 1);

        }
      }
    }
  }

$('#calendar').fullCalendar('addEventSource', events);

Example Data from blockedEvents
blockedEventsJSON = JSON.parse('[{"id":55,"status":0,"user":2,"begin":"2017-06-20 09:00:00","end":"2017-06-20 09:30:00","gcalenderstatus":0,"title":null,"description":"Termin von ","created_at":"2017-06-16 20:24:20","updated_at":"2017-06-16 20:24:20"}]')

In this picture is the calendar. The event which is
contemporaneous with a blocked event should be not shown


text:
Q: Order statistics probability Suppose that $X$, with a random sample $X_1, \ldots, X_n$, is a random variable with the following pdf: $f(x; t) = xte^{\frac{-x^2t}{2}}$ with the following support: $x \in [0, \infty)$, where $0 < t < \infty$ is unknown. If $Y_1, \ldots, Y_n$ are order statistics and $\hat{t} = 2\frac{n}{\sum_{j=1}^{n}X_j^2}$ is the maximum likelihood estimator for $t$ (done in part i, not shown here), find $P(Y_2 < \sqrt{\ln(9)t^{-1}} < Y_5)$.
My attempt:
This probability is equivalent to saying that between $2$ and $4$ (inclusive) of $X_j$'s (for $j = 1, \ldots, n$) are greater than $\sqrt{\ln(9)t^{-1}}$. Taking $W$ to be the number of $X_j$'s in this range, we can model this with a binomial distribution with $n$ and $p ={}$the percentile at which $\sqrt{\ln(9)t^{-1}}$ lies i.e. $p = F(\sqrt{\ln(9)t^{-1}})$ where $F$ is the cdf. But
$$F(x) = \int_0^x zte^{\frac{-z^2t}{2}} \,dz$$
$$p = F(\sqrt{\ln(9)t^{-1}}) = \int_0^{\sqrt{\ln(9)t^{-1}}} zte^{\frac{-z^2t}{2}} \,dz = \frac{2}{3}.$$
$W$ is binomial with $n$ and $p = \frac{2}{3}$ so
$$P\left(Y_2 < \sqrt{\ln(9)t^{-1}} < Y_5\right) = \sum_{k=2}^4 {}_nC_k \left(\frac{2}{3}\right)^k \left(\frac{1}{3}\right)^{n-k}$$
Is this correct? I do not know if I can go further, or find an exact value for the probability or if I am supposed to use the MLE. Any assistance is appreciated.

A: One more typo: "between 2 and 4 (inclusive) of the $X_j$ are less than $\sqrt{\ln(9)/t}$." (I am still confused why the problem statement mentions the MLE if it is irrelevant to the question.)
But otherwise I don't see any issues with your work. Since the answer involves a sum of 3 terms, you can expand it out as
$$\begin{align}\frac{1}{3^n}\left(\binom{n}{2} 2^2 + \binom{n}{3} 2^3 + \binom{n}{4} 2^4\right)
&= \frac{1}{3^n}\left[2n(n-1) + \frac{4}{3}n(n-1)(n-2)
+ \frac{2}{3} n(n-1)(n-2)(n-3)
\right]
\\
&=\frac{2}{3^{n+1}}n(n-1) \left[3 + 2(n-2) + (n-2)(n-3)\right]
\\
&=\frac{2}{3^{n+1}}n(n-1) (n^2 - 3n + 5)
\end{align}$$
which is the same as the expression in JimB's comment.


text:
Q: Create general purpose WinWaitActive in AutoIT I'm thinking of using the WinWaitActive function to play a sound file every time the currently active program finished a task (ie. After Effect finished rendering, Word finished saving, etc.).
From what I know about WinWaitActive, I'll need to write a script for each internal process of each application. That's a huge amount of automation scripts. Is there any way to make a single script that will work with all programs and processes?

A: Try something like this:
#include<array.au3>
Global $window_Array[1]

$window = "dokument - wordpad"
checkWin()

;ConsoleWrite(_ArrayToString($window_Array, @CR))

Func checkWin()
    Global $var = WinList()
    For $i = 1 To $var[0][0]
        If $var[$i][0] <> "" Then _ArrayAdd($window_Array, $var[$i][0])
        Next
    If _ArraySearch($window_Array, $window, 0, 0, 0) <> - 1 Then
        MsgBox(0, "", "Found!")
    Else
        MsgBox(0, "", "Not Found!")
    EndIf
EndFunc   ;==>checkWin


text:
Q: configure llvm fail. Host Clang must be able to find libstdcxx4.7 or newer my project depends on llvm+clang+cmake.I use ninja to make compile simple.
my OS is : OS X Yosemite(10.10.5).here is how the error occurs.
1) get llvm&clang
$ mkdir ~/clang-llvm && cd ~/clang-llvm
$ git clone http://llvm.org/git/llvm.git
$ cd llvm/tools
$ git clone http://llvm.org/git/clang.git
$ cd clang/tools
$ git clone http://llvm.org/git/clang-tools-extra.git extra

2) install CMake and  Ninja
$ cd ~/clang-llvm
$ git clone https://github.com/martine/ninja.git
$ cd ninja
$ git checkout release
$ ./bootstrap.py
$ sudo cp ninja /usr/bin/

$ cd ~/clang-llvm
$ git clone git://cmake.org/stage/cmake.git
$ cd cmake
$ git checkout next
$ ./bootstrap
$ make
$ sudo make install

3)compile ninja
$ cd ~/clang-llvm
$ mkdir build && cd build
$ cmake -G Ninja ../llvm -DLLVM_BUILD_TESTS=ON  # Enable tests; default is off.
$ ninja
$ ninja install

4)config clang
$ cd ~/clang-llvm/build
$ ccmake ../llvm

after that , I get into the advanced mode (by press t)
CMAKE_CXX_COMPILER:*I change it to  clang++*
CMAKE_C_COMPILER:*I change it to  clang*
LLVM_ENABLE_EH and  LLVM_ENABLE_RTTI: *I change it from OFF to ON*

and then I press c to configure. error happens.ERROR is :
**CMake Error at cmake/modules/HandleLLVMOptions.cmake:43 (message):
   Host Clang must be able to find libstdc++4.7 or newer!
 Call Stack (most recent call first):
   CMakeLists.txt:358 (include)**

Any ideas?
Thanks


text:
Q: How can I use a field as a filter from one graphql query to get a fluid image thats in a separate query? I have two graphql sources, one for fluid images and one for characters in a mongo database. I'm mapping the characters to the page and I need to use the character names (the name field in the "allMongodbMobileLegendsdevChamps") as a filter (using originalName filter possibly) to find the fluid img. So I have something like this

query MyQuery {
  allMongodbMobileLegendsdevChamps {
    nodes {
      name
    }
  }
  allImageSharp(filter: {fluid: {originalName: {eq: "characterName.jpg"}}}) {
    nodes {
      fluid {
        ...allImageSharpFluid
      }
    }
  }
}

const Index = ({ data }) => {
  const {
    allMongodbMobileLegendsdevChamps: { nodes: champs },
    allImageSharp: { nodes: fluid },
  } = data
  return (

      {champs.map(champ => {
        return (
          <Link to={`/champ/${champ.name}`}>
            <Image fluid={fluid.fluid} />

{champ.name}

          </Link>
        )
      })}

  )
}

If I wasnt using graphql, I'd just set the src in image to "champ.name" like this:

<Image src = `/path/to/img/${champ.name}.jpg` />

How can I filter my image query with the champ.name? Should I use Apollo for something like this?

A: This is Gatsby and currently it is not possible because you can't pass in variables to queries follow this GH issue https://github.com/gatsbyjs/gatsby/issues/10482
Supposing that passing variables was possible, I would make all characters as a page query that will allow me to restructure the name from props and then a static query to which I would pass in the name as filter.

A: I used this solution and adapted it slightly for my needs: Variables in graphQL queries
In a parent component I map all the champions and create a child component for each one, and pass it the champions name.
In the child component, I have a variable, name, that stores the correct node for the image I want to display by using the find method to match the champions name to the images relativePath (the images have the same exact name as the champion). I then call the function renderImage which consumes the variable "name" and finds the fluid image in node.childImageSharp.fluid, and creates my image component with the correct fluid image location.

import React from "react"
import { useStaticQuery, graphql } from "gatsby"
import { displayName } from "../../utils/championName"
import * as S from "../styled/ChampionGridCard"

const renderImage = file => {
  return <S.ChampionImage fluid={file.node.childImageSharp.fluid} />
}

const ChampionGridCard = props => {
  const data = useStaticQuery(graphql`
    {
      allFile(filter: { sourceInstanceName: { eq: "champImages" } }) {
        edges {
          node {
            extension
            relativePath
            childImageSharp {
              fluid {
                ...GatsbyImageSharpFluid
              }
            }
          }
        }
      }
    }
  `)

  const name = data.allFile.edges.find(
    image => image.node.relativePath === `ssbu/${props.champName}.jpg`
  )

  return (
    <S.ChampionGridCard to={`/champ/${props.champName}`}>
      <S.ChampionImageWrapper>{renderImage(name)}</S.ChampionImageWrapper>
    </S.ChampionGridCard>
  )
}

export default ChampionGridCard


text:
Q: XenServer 6.0 Advanced - Is it an add-on or part of initial install? I'm looking to purchase a new dedicated server and have XenServer 6.0 installed. There is an option to include XenServer 6.0 Advanced which has some additional features. However we don't need those additional features for a few months.
Is "Advanced" something you can add-on without a complete re-install of XenServer or must it be part of the original installation of XenServer?

A: Editions have to do with licenses only and the licenses can be applied and changed late without reinstall, if you initially only installed the free license.


text:
Q: Any way to restore 3D effect and/or shading to UIPopoverController? The recent release of iOS 7 includes a change to UIPopoverController where the popovers are now flat, with no shading underneath (none of the betas for iOS 7 included this change - the change only appeared with the GM release). Unfortunately this change is really not working with our iPad application; without the shading effect and the dark border, our popover is blending in with the underlying screen.
Do I have any options at all as far as customizing this effect or (even better) making popover look the way it used to look?

A: Take a look at popoverBackgroundViewClass. Not sure this will give you the result you are looking for, however. When a popover is displayed, the system dims the background view hierarchy, but there are no shadows underneath the popover. If this is not enough, you should look at implementing a custom popover controller or using an open source.


text: Q: Local IIS issue in Visual Studio 2013 for WEB I am developing an ASP.NET MVC 4 application on Visual Studio 2013 for WEB. Previously i was using the Visual Studio development server but now as i have selected the Local IIS Web Server i am having a problem which is when i run my code the browser (Chrome) show the URL "http://localhost/MVCDemo/" which is correct but the browser doesn't show any content. Its totally blank. I am running VS in administrator mode. I have checked the IIS which is working fine but the problem is i am not having anything display on the browser. When i am running the same code using the Visual Studio development server it is working absolutely fine and showing the content on the browser. Kindly if anyone knows where i am wrong. Need help regarding this.


text:
Q: How to assure that the Express response comes after the File System terminates the write stream? In an Express.js API I'm creating a zip file that stores a collection of PDFs that is intended to be passed as a download
I have created the zipfile using the yazl package following the README file, and it's pretty good, the problem comes when I use the pipe to create the createWriteStream, because I don't know how to properly wait until is finished.
Then in my Express route I want to send the file, but this code is executed before the write stream is finished...
This is a piece of code of a Promise function named renderReports inside my repository.js file, after I write the PDFs file I use a loop to added to the yazl's zipFile, then I proceed to create the zip with the fs.createWriteStream
const renderFilePromises = renderResults.map((renderedResult, index) =>
  writeFile(`./temporal/validatedPdfs/${invoices[index].id}.pdf`, renderedResult.content)
);
await Promise.all(renderFilePromises);
const zipfile = new yazl.ZipFile();
invoices.map((invoice, index) => {
  zipfile.addFile(`./temporal/validatedPdfs/${invoice.id}.pdf`, `${invoice.id}.pdf`)
});
zipfile.outputStream.pipe(fs.createWriteStream("./temporal/output.zip").on('close', () => {
  console.log('...Done');
}));
zipfile.end();
resolve();

And the following code is how I use the promise
app.post('/pdf-report', async (req, res, next) => {
  const { invoices } = req.body;
  repository.renderReports(reporter, invoices)
    .then(() => {
      res.sendFile('output.zip', {
        root: path.resolve(__dirname, './../../temporal/'),
        dotfiles: 'deny',
      }, (err) => {
      if (err) {
        console.log(err);
        res.status(err.status).end();
      }
      else {
        console.log('Sent:', 'output.zip');
      }
    });
  })
  .catch((renderErr) => {
    console.error(renderErr);
    res.header('Content-Type', 'application/json');
    return res.status(501).send(renderErr.message);
  });
});

I hope somebody can explain how to approach this

A: You need to store the write stream in a variable so you can access it. Then, on this variable, wait for the stream's finish event. This is emitted by Node.js once the stream is done with writing.


text:
Q: Firefox 22.0 vertical padding issue I'm having an issue in Firefox only (22.0) when using padding on a block element, the bottom padding is different of the top padding while the padding for both is the same in css.
CSS where #navigation is the element container:
nav#navigation {
  position: relative;
  margin: 0 0 25px;
  padding: 0;
  background-color: #2f2f2f;
  -webkit-border-radius: 8px;
  -moz-border-radius: 8px;
  border-radius: 8px;
}

nav#navigation ul.menu {
  float: left;
  position: relative;
  list-style: none;
  margin: 0;
}

nav#navigation a.my-element {
  float: left;
  display: block;
  padding: 6px 15px;
  line-height: 1;
  vertical-align: middle;
  font-size: 17px;
  font-weight: 300;
  text-decoration: none;
  background: #ff8833;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}

nav#navigation a.my-element span {
  display: block;
  padding-left: 20px;
  background: url("assets/img/icon-plus.png") no-repeat left center;
}

HTML:

list element

list element

list element

    Some Text

Here is a screenshot: http://postimg.org/image/wzypkwu2l/
Any fix for that?
Thanks


text:
Q: Set global snakemake variables from within a rule In snakemake, I can define global variables before declaring my rules. This is nifty when I have a list of files that I need to download via some tool - then I can ensure the name of those files are wildcards for my subsequent steps. For example, when I have a text file (srarunsacc.txt) containing lines of SRA111111,SRA111112,SRA111113 I can do the following (pseudocode):
def read_textfile(name):
....
SRAFILES=read_textfile("srarunsacc.txt")

rule download_srafiles:
    output:
        "%s{srafiles}_1.fastq" % "raw_samples/",
        "%s{srafiles}_2.fastq" % "raw_samples/"
    shell:
        "fasterq-dump {wildcards.srafiles} -O raw_samples"

This ensures that I can then process my downloaded files within snakemake, by linking input and output within rules. But suppose I do not start with the text file srarunsacc.txt and that it is instead generated within the snakemake process. Now I can't define my SRAFILES global variable up top, and I'm stumped at what to do. Ideally, I would be able to make a SRAFILES global variable from within one of my rules, but I haven't managed to do that.

I've created a dummy process meant to mimic my workflow :
rule create_textfile:
    output:
        "list_of_files.txt"
    run:
        files=[f"TESTFILE_{i}.test" for i in range(1,10)]
        files="\n".join(files)
        with open(output[0],"w") as out:
            out.write(files)

In rule create_textfile I create a .txt file that looks like this:
TESTFILE_1.test
TESTFILE_2.test
etc.

Normally, I won't know the exact name of those files, just their extension - which in this case is .test. The next step is :
rule create_files:
    input:
        "list_of_files.txt"
    output:
        "placeholder.plc"
    shell:
        """
        mkdir raw_samples
        cat {input} | parallel touch raw_samples/{{}} >> {output}
        """

In rule create_files I create an empty file from every line of my created .txt file, so the result is this:
raw_samples
    |____TESTFILE_1.test
    |____TESTFILE_2.test
     .etc

Now, in my "experiment", I won't know how the files are named, only their resulting extension, say .test. I want to use those created files as an input to my next rule. I've been using the log output trick to link my rules together. Now I want to process every created file separately. For example:
rule process_files:
input:
    plc="placeholder1.plc",
    sample="raw_samples/{sample}.test"
output:
    "placeholder2.plc"
shell:
    """
    echo {input.sample} >> {output}
    """

The above doesn't work, and gives the error:
Wildcards in input files cannot be determined from output files:'sample'

Which makes sense, as in nowhere above I define output as of raw_samples/{sample}.test
So I've tried modifying the rule create_files like this:
 output:
    plc="placeholder1.plc",
    sample="raw_samples/{sample}.test"

That didn't work, and the error was
Not all output, log and benchmark files of rule create_files contain the same wildcards. This is crucial though, in order to avoid that two or more jobs write to the same file.

Tl;dr - A bunch of files (names unknown prior to process, only their extension) is generated via one snakemake rule. I want to process those files with subsequent snakemake rules, but do not know how to link up input-output / set up wildcards.

A: You are missing a few pieces to get this working the way you want.  Snakemake primarily deals with files, so using the list_of_files.txt file is on the right track.
You will need to use a checkpoint on the rule you generate the list of files to determine the sample names.  There are lots of questions on checkpoints here you can use as inspiration.
For your "placeholder" outputs, you should change those to directories so snakemake can detect and clean up errors in intermediate steps.


text:
Q: In SQL, how to concatenate string with integer data type column I am trying to add string "Rs" with amount column.
The data type of amount is integer.
But Sql is not allowing me to concatenate string with int data type column.Image 1
Image 2

A: You need to explicitly convert the int to varchar before concatenating with any string
select 'RS'+cast(total_amount as varchar(100)),*
from yourtable

If you are sql server 2012+ then use CONCAT which does implicit conversion
select Concat('RS',total_amount),*
from yourtable


text:
Q: Replacing Filegroup Used in Last Partition Slice for RANGE LEFT-based Partition Scheme I have a simple date based partition function using RANGE LEFT...
CREATE PARTITION FUNCTION [PF_YEAR_LEFT](date) AS RANGE LEFT
    FOR VALUES (N'1992-12-31', N'1993-12-31', N'1994-12-31')
GO

CREATE PARTITION SCHEME [PS_YEAR_LEFT] AS PARTITION [PF_YEAR_LEFT]
    TO ([DATA_1992], [DATA_1993], [DATA_1994], [DATA_1995])
GO

In the above code, filegroup [DATA_1995] would retain the values beyond the last partition boundary. So, if I elect to add new filegroups and split the function for additional boundaries in this fashion...
ALTER PARTITION SCHEME [PS_YEAR_LEFT] NEXT USED [DATA_1995]
GO

ALTER PARTITION FUNCTION [PF_YEAR_LEFT]() SPLIT RANGE (N'1995-12-31')
GO

ALTER PARTITION SCHEME [PS_YEAR_LEFT] NEXT USED [DATA_1996]
GO

ALTER PARTITION FUNCTION [PF_YEAR_LEFT]() SPLIT RANGE (N'1996-12-31')
GO

The filegroup [DATA_1995] remains in the last partition position for values beyond the upper-most boundary.
Can this last filegroup be changed after the partition scheme is initially created or is the only way through creation of a new partition scheme and rebuilding all indexes utilizing the old scheme into the new scheme?

A:
Can this last filegroup be changed after the partition scheme is
  initially created or is the only way through creation of a new
  partition scheme and rebuilding all indexes utilizing the old scheme
  into the new scheme?

The last partition of a RANGE LEFT function is a permanent partition that cannot be removed nor can the first partition of a RANGE RIGHT function. This is one of the considerations detailed in my Table Partitioning Best Practices article and why I recommend a more intuitive RANGE RIGHT function for incremental temporal types along with explicit boundaries for data within the expected range.
You don't need to go so far as to rebuild the existing table and indexes to remediate the misnamed filegroup. If you add new partitions using your script  (taking care to ensure that the SPLIT partitions are empty), you'll end up with this scheme:
CREATE PARTITION SCHEME PS_YEAR_LEFT AS PARTITION PF_YEAR_LEFT TO (
      [DATA_1992]
    , [DATA_1993]
    , [DATA_1994]
    , [DATA_1995]
    , [DATA_1996]
    , [DATA_1995]
    );

You could create a new scheme with the last partition on a dummy filegroup (or PRIMARY), create a new aligned table, switch all partitions but the last one (which will be empty if you have no 1997+ data) into the new table, drop the old table, rename, etc. Example below.
CREATE PARTITION SCHEME PS_YEAR_LEFT_NEW AS PARTITION PF_YEAR_LEFT TO (
      [DATA_1992]
    , [DATA_1993]
    , [DATA_1994]
    , [DATA_1995]
    , [DATA_1996]
    , [PRIMARY]
    );
GO
CREATE TABLE dbo.YourTable(
    DateColumn date
) ON PS_YEAR_LEFT(DateColumn);
GO
CREATE TABLE dbo.YourTable_New(
    DateColumn date
) ON PS_YEAR_LEFT_NEW(DateColumn);
GO
DECLARE @Date date = '19921231';
WHILE @Date <= '19961231'
BEGIN
    ALTER TABLE dbo.YourTable
        SWITCH PARTITION $PARTITION.PF_YEAR_LEFT(@Date)
        TO dbo.YourTable_New PARTITION $PARTITION.PF_YEAR_LEFT(@Date);
    SET @Date = DATEADD(year,1,@Date);
END;
GO
--drop original table
--drop original partition scheme
--rename new table, constraints, indexes to original name
--update statistics


text:
Q: Getting arguments where they need to be, with the right scope, in nested piped functions I am trying to prepare a variety of summaries from the roughly nine million person records in the Current Population Survey. I have a data set, the CPS, a number of column names that I want to match columns in that data set, and also a vector of parameters; these are meant to enter into a piped series of dplyr transformations at various places along the pipeline. (pipechain? pipe sequence?)
In an effort to achieve the latter I have put the pipes that do the work into a subsidiary function, q_m. My primary function, q_means then calls q_m via do.call with a list of arguments containing the actual arguments of the primary, named with the names of the formals.
In this particular case, I am trying to take the weighted means of adj_inc by adj_inc quantile ranges for each year, but I am trying to understand how to construct this function as a template for calculating weighted grouped statistics in general. I am fairly new at this sort of metaprogramming and am having trouble getting arguments where they need to be with the right scope and state of evaluation.
At the moment I am getting the error message
" Error in grouped_df_impl(data, unname(vars), drop) : Column .grps is unknown ", but I have been working with this function for many hours and have achieved a startling diversity of error messages. I am pretty sure that something more fundamental is wrong with my approach, or perhaps several things.
Here is code for a small synthetic data set for reproduciblity:
set.seed(1776)
rand<- round(abs(rnorm(20, 1000, 50)))
test_dat <- tibble(year=rep(1:2, times=c(10,10)), adj_inc=30001:30020,
                   wtsupp=5 * rand)

Here are my functions and parameters:
q_m     <- function(.dt, .inc, .wts=NULL,
                    .probs=c(0, .25, .5, .75, 1), .grps){
    group_by(.grps)}                        %>%
    mutate(inc2 = .inc,
           inc_q_groups =
             cut(inc2, breaks = wtd.quantile(
               .inc, weights = wts., probs=.probs)))  %>%
      group_by(inc_q_groups, .grps)                          %>%
      summarise(inc_q_means = wtd.mean(
        .inc, weights = .wts)) ->  out
  out
}

var_lst <- with(data=test_dat, list(.inc=adj_inc,.wts=wtsupp,
                                      .probs=c(0, 0.5, 1)), .grps=year)

q_means <- function(data = test_dat, var_lst){
  out <- do.call(q_m, c(list(.dt = data), var_lst))
}

test_output  <- q_means(test_dat, var_lst)

The answers I expect, assuming non-interpolating versions of quantile, etc., are about 30007.9, 30003.0 for year 1 and 30018.0, 30013.0 for year 2.


text:
Q: Consider the function f : R-->R defined by f(x) =x^7+x+1. Show that f has an inverse We just started doing inverse functions so I'm not very familiar with this concept...

A: $f'(x)=7x^6+1>0$ implies that $f$ is strictly increasing thus injective. $lim_{x\rightarrow-\infty}f(x)=-\infty$, $lim_{x\rightarrow+\infty}f(x)=+\infty$ implies that $f$ is surjective since for every $n>0$, there exists $a<-n<n<b$ such that $f(x)=a$, $f(y)=b$ and $[a,b]$ is in the image of $f$ since $f$ is continue and the image of $R$ is connected.

A: $f(x)$ is a continuos function and the derivative $f'(x)=7x^6+1>0$ so the inverse function exists because the function is strictly increasing.


text:
Q: Ubuntu 16.10 "Search for files" in Gnome useless The search for files application in Ubuntu 16.10 (Gnome) is quite useless. It searches and finds files & folders successfully, but it won't open anything in the search results (Or do anything about them, for that matter): Double clicking on the files, right clicking and selecting "open" or "open with" or "open containing folder" doesn't do anything at all. No error, no result, no opened files, anything.
What is the point of this? Is this a bug? Alternatively, it there is a better search application that actually does what it is supposed to do?


text:
Q: User accounts authentication from Active Directory I'm looking into Active Directory user account authentications.The situation is like this.I have a Forest DC at data centre 1, and infrastructure child DC at some site.
I want the infrastructure servers administrative user accounts authenticated from the Forest DC, and the other user accounts at the site to be authenticated from the infrastructure child DC at the site.
My question is, is this a good approach, or it is better to have all accounts authenticated at the Forest DC.
The advantage I see with my approach is that in case WAN is down, the infrastructure child DC will be able to authenticate the local user accounts. In case all accounts are authenticated at Forest DC and WAN is down the accounts cannot be authenticated at all, unless I have AD replication of Forest DC at the site ?
Or is it that once the infrastructure child DC join the Forest they will have AD replication automatically ?
Could someone elaborate on this approach.
Thank You

A: Users authenticate to Domain Controllers in the domain to which they belong.
The Domain partition does not replicate to other domains in the Forest. Attributes marked for Global Catalog replication will replicate to all Global Catalog servers in the Forest, but user and computer accounts in the Domain partition do not replicate to other domains in the Forest.


text:
Q: Getting the height of the Compact Height of the Widget when it's in Expanded Mode How can I get the Compact Height when the widget is displayed in Expanded Mode? I would set the size of the Expanded mode of the widget double the size of the Compact Mode. Compact Size is Fixed for iPad and iPhones but it's different when it comes to iPad Pro.
Removing the Widget keeping the app in Expanded mode and When later adding the widget would appear on the screen with Expanded mode. OS maintains the state. So now I would not get the Compact size Since it's directly being loaded on the Expanded mode.
I don't wanna have static value for iPad Pro and For the other devices separately. This should be done generic, So in future this won't get affected if apple changes the FIXED compact mode size.

A: I located the solution for this.
CGSize siz = [self.extensionContext widgetMaximumSizeForDisplayMode:NCWidgetDisplayModeCompact];

This would give me the Compact Size.


text:
Q: Getting template error with symfony2 and sonata Admin bundle I have installed Sonata Admin bundle and Sonata Userbundle
When i go to
/admin/dashboard and click on list users i get this error

An exception has been thrown during the rendering of a template
  ("Route "homepage" does not exist.") in
  SonataUserBundle:Admin:Field/impersonating.html.twig at line 15.

What do i need to do
All other bundles Sonata page , news are working ok

A: if you have:
# app/config/routing.yml
...
sonata_user_impersonating:
    pattern: /
    defaults: { _controller: SonataPageBundle:Page:catchAll }

just add
# app/config/config.yml
...
sonata_user:
    impersonating_route:    sonata_user_impersonating

A: I'm not using this bundle but perhaps you have to implement your own homepage controller action with the name "homepage". Sonata probably used this route to go to your main page that you need to implement yourself !


text:
Q: Serilog custom outputTemplate I was looking for custom output template format for logging
sample output template : "{\"time\":\"+ \",\"severity\":\"{Level:u}\",\"machine\":\"{MachineName}\", \"x-Correlation-ID\":\"{CorrelationID}\"}"
It is always expecting first filed value as "+" value, if that filed not exists means it is not replacing next property value({Level:u}).
For above template output : {"time":"+ ","severity":"INFORMATION","machine":"xxxxxx", "x-Correlation-ID":"e5b9c851-de56-42d9-b414-9d7108d2ebcf"}
If first field value other than "+" value, output as follows : {"time":"test ","severity":"{Level:u}","machine":"xxxxxx", "x-Correlation-ID":"f6133a7e-ea4f-4bde-8200-798d5346d3ce"}
RollingFileAlternate sink used to log WriteTo.Async(w => w.RollingFileAlternate(logFilePath.ToString(), outputTemplate: logOutputTemplate, fileSizeLimitBytes: rollingFilesSize, retainedFileCountLimit: null))
how to remove first property with out effecting other output template properties.

A: You're probably going to have to implement a custom ITextFormatter that implements the logic that you need, in order to create the corresponding output you want.
You can see how the the default ones (CompactJsonFormatter.csand RenderedCompactJsonFormatter.cs) are implemented, and adapt the code to work how you need it.
public class YourCustomJsonFormatter : ITextFormatter
{
    public void Format(LogEvent logEvent, TextWriter output)
    {
        // ...
    }
}

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console(new YourCustomJsonFormatter())
    .CreateLogger();


text:
Q: Derivation of Properties of Associated Laguerre Polynomial 1.How to prove Rodrigues formula for Associated Laguerre Polynomial?
2.How to show they are orthonormal in the interval (0,infinity)?
Also I want to find normalization constant?
3.How to prove recurrence relation and series expansion?
4.I am also interested to learn the proof of generating function,orthonormality,recurrence relation and series expansion for Associated Legandre Polynomials.
   As I am learning Quantum Mechanics , these are important to me too much.I can't find any resource that explains these topics.Please somebody helps me by putting the mathematical derivation or by creating link which contains the answer.

A: How you prove it depends on what you're allowed to assume.
It could be that you're allowed to assume the Rodrigues formula and then show that $L_n^{\alpha}(x)$ solve the following differential equation:
$$xy'' + (\alpha + 1 - x)y' + ny = 0$$
This equation defines the associated Laguerre polynomials more than anything else, I'd think.
As for showing the recurrence relation you can start by calculating $L_0^{\alpha}(x)$ and $L_1^{\alpha}(x)$ and then use the Rodrigues relation and the differential equation to show the relation for $L_n^{\alpha}(x)$ in terms of $L_{n-1}^{\alpha}(x)$ and $L_{n-2}^{\alpha}(x)$.
The Wikipedia article on Laguerre polynomials (particularly the section with generalized Laguerre polynomials) should be a good start for you.


text:
Q: How to loop TreeNode of P:treetable data I want to Loop TreeTable object in Java code. Here is by Tree Creation code
public TreeNode getTreeData()
{

    lstTestProcessByRelease = testProcessBo.findAllTestProcessByReleaseGroupBy(getTestSuite(), getReleaseByTabName());
    List<TestProcess> lstTestScenario = new ArrayList<TestProcess>();
    int parentCount=0;

    root1 = new DefaultTreeNode(new TestProcess("TestScenario","TestCase",0,0),null);

    for(TestProcess tp : lstTestProcessByRelease)
    {
        parentCount = parentCount + 1;
        ExecutionParentOrderValue.put(parentCount, parentCount);
        TreeNode parent = new DefaultTreeNode(new TestProcess(tp.getTestScenarioName(), tp.getTestScenarioName(), 0, parentCount),root1);
        System.out.println("============"+ tp.getTestScenarioName() +"=================");
        System.out.println("Scenario Name (ROWKEY) :"+ parent.getRowKey());
        lstTestScenario = testProcessBo.findAllTestCasesByTestScenarioName(tp.getTestSuite(), tp.getReleaseName(), tp.getTestScenarioName());

        TreeNode child =null;
        int childCount=0;
        for(TestProcess tc : lstTestScenario)
        {
            childCount = childCount + 1;
            ExecutionChildOrderValue.put(childCount, childCount);
            child = new DefaultTreeNode(new TestProcess(tc.getTestScenarioName(), tc.getTestCaseName(), childCount, parentCount),parent);
            System.out.println("TestCase (ROWKEY) :"+ child.getRowKey());
            System.out.println("Scenario Name :" + tc.getTestScenarioName());
            System.out.println("TestCases Name : " + tc.getTestCaseName());
            System.out.println("   TestScenario ExecNo :" + tc.getTestScenarioExecNo());
            System.out.println("      TestCase ExecNo :" + tc.getTestCaseExecNo());
        }
        System.out.println("");
        System.out.println("");
    }

    return root1;
}

If i want to loop root1 object and print data in console, How to do ?
Actually, I want to loop through root1 and get the data from tree and wanted to store in db. But i am not getting and idea how to loop root1 object and get data printed on console.
Could anyone help me on this ?
Thanks
Neeraj


text:
Q: How to load result of a javascript function to a new tab I've got a function that does Ajax to load certain html portion. Sometimes I need the result to be displayed in a separate window (or a tab if you will). When I include that function call in an anchor element's href attribute I can get that behavior:
   <a href="javascript:viewInternalDocument('AF7GH209')" target="_blank">Related document</>

But if I try to do it manually by calling window.open, I just get blank tab:
 window.open("javascript:viewInternalDocument('AF7GH209')","_blank");

In fact, the new tab opens even if I omit the _blank argument.
If you wonder what my viewInternalDocument function does, then here's the internals of it:
    function viewInternalDoc(docID) {
    var url = "/Cabinet/ViewInternalDocument";
    var args = { docID: docID};
    $.get(url, args, function (html) {
        $('#divContentHierarchy').html(html);
    }).fail(function () {
        alert('Error loading selected document')
    });
}

When I try window.open('javascript:alert("Hello")'), I can get the alert in a new tab (again, omitted the "_blank"). So what is the problem with not displaying the result of my function?
EDIT: I just realized that function does not work with the anchor element either. I somehow confused. Sorry for that.

A: You can create a new window, get your content and then insert content into the window with jQuery:
  var w = window.open();
  $(w.document.body).html(viewInternalDocument('AF7GH209'));

or with vanillaJS:
var w = window.open();
w.document.body.innerHTML = viewInternalDocument('AF7GH209');


text:
Q: Which is the most lightweight way to make an asynchronous http call with Java?
Possible Duplicate:
How to make an make a web request in an async manner

A very lightweight way in Java to make a synchronous HTTP call is using HttpURLConnection.
Is there an equally easy way to make a non-blocking, 'asynchronous' HTTP call?
I have already looked into: Java NIO, Netty Http Client, Apache Commons HttpClient 4.0 but the solutions are either complex (Java NIO) or introduce a dependency, which I would like to avoid.

A: HTTP is a synchronous protocol. In this respect I don't think you should see any significant difference from the client side between these 2 cases. But this depends on also what you mean by lightweight


text:
Q: Getting seRious about time series with R If you think back, to when you first started with time series analysis. What tools, R packages and internet resources do you wish you had known about?
What I'm trying to ask is, where should one start? Specifically, are there any resources for R that really boil it down for one who is "new" to time series analysis with R.

A: For ecologists, Tree diversity analysis can be a first healthy step into the right direction. The book is free, it comes with an R package (BiodiversityR) and gives you a taste of other eco-packages (like vegan).

A: There is a Time Series Task View that aims to summarize all the time series packages for R. It highlights some core packages that provide some essential functionality.
I would also recommend the book by Shumway and Stoffer and the associated website, although it is not so good for forecasting.
My blog post on "Econometrics and R" provides a few other references that are useful.
Then there is my own book on forecasting using R: Forecasting principles and practice.

A: I've found the UseR! series book Introductory Time Series with R by Cowpertwait and Metcalfe very useful in translating my time series statistics textbooks into R-speak.


text:
Q: Flutter dart json Unhandled Exception: InternalLinkedHashMap' is not a subtype of type 'List I have this code from my other question (thanks to chunhunghan). I need to make a log in screen and im trying to validate user credentials against a response the server sends back to me but every time i try to run the code it gives me the "Unhandled Exception: InternalLinkedHashMap' is not a subtype of type 'List" error and im not sure how to fix it.
thats the model:
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
  Payload({
    this.version,
    this.encoding,
    this.subsonicResponse,
  });

  String version;
  String encoding;
  SubsonicResponse subsonicResponse;

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        version: json["version"],
        encoding: json["encoding"],
        subsonicResponse: SubsonicResponse.fromJson(json["subsonic-response"]),
      );

  Map<String, dynamic> toJson() => {
        "version": version,
        "encoding": encoding,
        "subsonic-response": subsonicResponse.toJson(),
      };
}

class SubsonicResponse {
  SubsonicResponse({
    this.status,
    this.version,
    this.xmlns,
    this.albumList,
  });

  String status;
  String version;
  String xmlns;
  AlbumList albumList;

  factory SubsonicResponse.fromJson(Map<String, dynamic> json) =>
      SubsonicResponse(
        status: json["status"],
        version: json["version"],
        albumList: AlbumList.fromJson(json["albumList"]),
      );

  Map<String, dynamic> toJson() => {
        "status": status,
        "version": version,
        "albumList": albumList.toJson(),
      };
}

class AlbumList {
  AlbumList({
    this.album,
  });

  List<AlbumsList> album;

  factory AlbumList.fromJson(Map<String, dynamic> json) => AlbumList(
        album: json["album"] == null ? null: List<AlbumsList>.from(json["album"].map((x) => AlbumsList.fromJson(x))),);

  Map<String, dynamic> toJson() => {
        "album": album == null ? null: List<dynamic>.from(album.map((x) => x.toJson())),
      };
}

class AlbumsList {
  AlbumsList({
    this.id,
    this.parent,
    this.isDir,
    this.title,
    this.album,
    this.artist,
    this.genre,
    this.coverArt,
    this.playCount,
    this.created,
    this.year,
  });

  String id;
  String parent;
  String isDir;
  String title;
  String album;
  String artist;
  String genre;
  String coverArt;
  String playCount;
  DateTime created;
  String year;

  factory AlbumsList.fromJson(Map<String, dynamic> json) => AlbumsList(
        id: json["id"],
        parent: json["parent"],
        isDir: json["isDir"],
        title: json["title"],
        album: json["album"],
        artist: json["artist"],
        genre: json["genre"],
        coverArt: json["coverArt"],
        playCount: json["playCount"],
        created: DateTime.parse(json["created"]),
        year: json["year"] == null ? null : json["year"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "parent": parent,
        "isDir": isDir,
        "title": title,
        "album": album,
        "artist": artist,
        "genre": genre,
        "coverArt": coverArt,
        "playCount": playCount,
        "created": created.toIso8601String(),
        "year": year == null ? null : year,
      };
}

here is the request:
Future <Payload>fetchResponse() async{
final authresponse = await http.get(authURL);
if (authresponse.statusCode == 200){
final jsondata = jsonDecode(authresponse.body);
return payloadFromJson(jsondata);
}else
throw Exception("Unable to connect to server, try again");
}

it gives me the error on the return line.
EDIT: i forgot to add the api response.
{
   "subsonic-response": {
      "status": "ok",
      "version": "1.15.0"
   }
}

this is the api response

A: change payloadFromJson to
Payload payloadFromJson (Map<String, dynamic>str) => Payload.fromJson(str);

fetch value from json if the json contains the key
 factory SubsonicResponse.fromJson(Map<String, dynamic> json) =>
      SubsonicResponse(
        status: json["status"],
        version: json["version"],
        albumList: json.containsKey("albumList")? AlbumList.fromJson(json["albumList"]):null,
      );


text:
Q: invoking createDisplay on android.view.SurfaceControl using reflection returns null I am trying to call createDisplay method on android.view.SurfaceControl using reflection but it is returning null on Marshmallow device. I Don't know why.
The reason to do is to create virtualdisplay without using MediaProjection API.
Following is the code.
Class surfaceControlClass = Class.forName("android.view.SurfaceControl");
Class cls = surfaceControlClass;
IBinder token = (IBinder) cls.getDeclaredMethod("createDisplay", new Class[]{String.class, Boolean.TYPE}).invoke(null, new Object[]{name, Boolean.valueOf(false)});

A: You need System Permission(android.permission.ACCESS_SURFACE_FLINGER) to do that, check your LogCat and you will find permission warning.
Actually you can't make it work unless you have the Platform Signature of your device.
But you can test it on emulator using the default AOSP signature.


text:
Q: SSLstrip with dnsmasq How to Use I believe this is an appropriate question for this SE but please move it if its not.
I have followed this to create an AP that re-routes all trafic to 10.0.0.1 where my own website is served. The problem is that because of HTTPS and SSL most sites will just fail to connect instead of showing my site.
So I installed sslstrip to avoid this. However, when I ran it, nothing changed. I am not really sure how to use it and the man pages did not help. I don't really know what port my server is on.
Here are my revelant configurations:
/etc/network/interfaces
auto lo
iface lo inet loopback
iface eth0 inet dhcp
iface wlan0 inet static address 10.0.0.1
netmask 255.255.255.0
broadcast 255.0.0.0
pre-up iptables-restore < /etc/iptables.rules

iptables
sudo iptables -F
sudo iptables -i wlan0 -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
sudo iptables -i wlan0 -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -i wlan0 -A INPUT -p udp --dport 53 -j ACCEPT
sudo iptables -i wlan0 -A INPUT -p udp --dport 67:68 -j ACCEPT
sudo iptables -i wlan0 -A INPUT -j DROP
sudo sh -c "iptables-save > /etc/iptables.rules"

/etc/dnsmasq.conf
log-facility=/var/log/dnsmasq.log
address=/#/10.0.0.1
interface=wlan0
dhcp-range=10.0.0.10, 10.0.0.250,12h
no-resolv
log-queries

A: SSLstrip only makes it so that if you're already on HTTP, you won't end up on HTTPS. If a connection starts out on HTTPS, SSLstrip can't do anything. Modern browsers have preloaded HSTS lists with many popular sites, pretty much for the sole reason of making it impossible to do the very thing you're trying to do.


text:
Q: exposing Azure DNS servers I have an Azure virtual machine with multiple web sites on it that I would like to expose to the Internet.  The VM has Active Directory and DNS installed on it.  I created the forward zone (xxx.cloudapp.net) on my server, and added the two web site names to the zone. On the Networks in the Management Portal, I added a DNS server(xxx.cloudapp.net) and gave it the public IP for my server.
So when I try a nslookup from outside of the VM, the names will not resolve.  I set the server in nslookup to either the public IP or the name, and it does not resolve.  I have logging turned on in the DNS server, but it does not seem to show any requests from my computer.
I must be doing something wrong.  Any suggestions?  This server is for a demo next week, and worst case, I can buy a couple of domain names.

A: Try the instance level public-ip address, you will get an ip address per virtual server: https://azure.microsoft.com/documentation/articles/virtual-networks-instance-level-public-ip/


text:
Q: New Tactics for Acquiring Link Backs As all SEOs know that google is trying its very best to kill SEO and linkbacks are quite a difficult task now. Although content is the key but my boss is still possessed with linkbacks. I can not do directory posting, link exchange, paid linking, web 2.0 and blog commenting as they are spam now. I do not see what other choice i have except forum posting and article posting. Can someone suggest new method to acquire link backs ? I know almost all traditional methods so don't say press release or etc. If you really have something out of the box or not very much common please share.

A: Google isn't killing SEO, they trying to banish practices that your boss is so intent on doing.
If you want to build a quality reputation - you need to start creating genuine and unique content aimed at your target audience. Research your market, offer your visitors information they want to read and share. Make sure what you create is geared towards Google.
Make it relevant, current, accurate and engaging.
Of course, this all takes time and considerable effort - if you or your boss can't devote the time needed, or at least employ someone to do it for you... the business is going to suffer online.

A: Buy the links. The majority of online marketing agencies do this as the primary way to increase Google rank.
Or go the natural way and produce so much fine content people will naturally share it.


text:
Q: Solve ODE by means of a Laplace transform The discontinuous function $g(t)$ is defined by $$g(t)=\begin{cases} 0, & \text{for } t<0\\1, & \text{for } t=0 \\ -1, & \text{for }t=\pi \\ 0, & \text{for } t>\pi \end{cases}$$
and satisfies the ODE $$g'(t)=g(\pi-t),$$ where $g(0)=1$ and $g(\pi)=-1.$
I want to consider this ODE using Laplace transforms. Here the Laplace transform is given by $$\bar{g}(s)=\int_0^\infty e^{-st} g(t)\, dt.$$
The Laplace transform of the LHS is given by $$s\bar{g}(s)-1.$$
For the RHS we have \begin{align*} \bar{g}(\pi-t)=\int_0^\infty e^{-st}g(\pi-t) \, dt.\end{align*}
Setting $y=\pi-t$ it follows that \begin{align*} \int_0^\infty e^{-st}g(\pi-t) \, dt & = -\int_\pi^{-\infty}e^{-s(\pi-y)}g(y) \, dy \\ & = -e^{-\pi s}\int_{\pi}^{-\infty} e^{sy}g(y) \, dy \end{align*}
I'm told that the Laplace transform of the ODE is given by $$s\bar{g}(s)-1=e^{-\pi s}+e^{-\pi s}\bar{g}(-s).$$
How do I get to this answer from where I am?