text:
Q: How do I access a cell in Excel Interop when using filtered ranges? I originally had a code segment that iterated through rows of an Excel spreadsheet using the UsedRange as such:
           range = ws.UsedRange;
           for (int row = 3; row <= range.Rows.Count; row++)
            {
                Object nObj = ((Excel.Range)ws.Cells[row, "N"]).Text;
            }

But I needed to only get the rows that remained after I applied a filter so (after viewing How can I get the Range of filtered rows using Excel Interop?) I changed the code as such:
    range = ws.UsedRange.SpecialCells(Excel.XlCellType.xlCellTypeVisible, Type.Missing);
    foreach (Excel.Range area in range.Areas)
    {
        foreach (Excel.Range row in area.Rows)
            //for (int row = 3; row <= range.Rows.Count; row++)
            {
                Object nObj = ((Excel.Range)ws.Cells[row, "N"]).Text;
            }
    }

Except now I'm getting type mismatch errors.  What fundamental thing am I missing here?

A: I believe you are getting a type mismatch at the call to ws.Cells[row, "N"]. In the original code, row is an int. In the modified code, row is an Excel.Range.
Given that, in the modified code, row is a single row (multiple column) range, all you should need to do is index into the cell in that row which corresponds to column N. Assuming your range starts in column A, this will be the cell in 14th column.
E.g.
Object nObj = ((Excel.Range)row.Cells[1, 14]).Text;


text:
Q: How to get json_encode() to work with ISO-8859-1 (åäö) json_encode() wont work for me when I'm using åäö. Why? And how can I get it to work?
The php:
echo json_encode($arr);

The javascript:
var theResponse = JSON.parse(xmlHttp.responseText);

When I alert() the response, and the response contains å, ä or ö, the response is = NULL
Please, help me out...

A: As Greg mentioned, I had to encode åäö to UTF-8. But I did't use iconv or mbstring. When I utf8_encode() all values before putting the values to the array the problem was solved.

A: This function will cast the correct data type for the JSON output and utf8_encode the strings.
    /* Change data-type from string to integar or float if required.
     * If string detected then utf8_encode() it. */
    function cast_data_types ($value) {
      if (is_array($value)) {
        $value = array_map('cast_data_types',$value);
        return $value;
      }
      if (is_numeric($value)) {
        if(strpos('.', $value)===false) return (float)$value;
        return (int) $value;
      }
      return utf8_encode((string)$value);
    }

json_encode (cast_data_types($data));

A: JSON defines strings as Unicode!
JSON Definition
You have to encode you ISO to UTF-8

A: Old question, but figured I'd put this here in case someone needs to log data using json_encode but keep the data untouched, intact for inspection later.
You can encode the data raw using base64_encode, then it will work with json_encode. Later after running json_decode, you can decode the string with base64_decode, you'll get the original data unmodified.

A: It says in the json_encode() documentation:

This function only works with UTF-8 encoded data.

You should convert it to utf-8 with iconv or mbstring first.

A: As of PHP 5.4.0:
Convert your strings in your array to into utf-8 using utf8_encode($str) function.
Then json_encode with JSON_UNESCAPED_UNICODE option:
$arr = json_encode($array, JSON_UNESCAPED_UNICODE);

A: Using the standard method when reading from MySQL:
$resultArray = array();
while($obj = MySQL_fetch_object($res)) {
 $resultArray[] = $obj;
}
$result = json_encode($resultArray);

The encoding can be done using the following:
$resultArray = array();
while($obj = MySQL_fetch_object($res)) {
 foreach($obj as $key => $value) {
  if (!is_null($value)) {
   $obj->$key = utf8_encode($value);
  }
 }
 $resultArray[] = $obj;
}
$result = json_encode($resultArray);

The if is_null has to be included so that null fields (e.g., DateTime fields) remain null in the output.

A: The $data (in my case) is an array with text values as ISO-8859-1. The trick below prepares $data to be used with json_encode.
function toUtf8(&$v, $k) {
    $v = utf8_encode($v);
}
array_walk_recursive($data, 'toUtf8');

redpajama_set_name: RedPajamaStackExchange


text:
Q: Paypal MPL login button disabled on device I have gone through several questions with similar problem but could not find any solution for it. I have followed steps given working in sandbox mode.. after following code i get paypal window.
[[PayPal getPayPalInst] checkoutWithPayment:payment];

In paypal window i can login using email and password. which works on simulator but on device log in button remains disabled after giving valid credentials.

Thanks in advance
i am able to run there demo example. but when i change bundle identifier and check then log in button is not enable in paypal window
Now i found out that its disabled for my particular bundle identifier as when i use different profile with its bundle identifier its working.
Do we have to register our bundle identifier? or any particular reason for it.
I am using Paypal MPL version 2.1.0.

A: please double check the seller account "sunny.g-faciliator@intelgain.com" (receiverEmail) - I guess it should be "sunny.g-facilitator@intelgain.com" (a "t" is missing in "facilitator") and this might cause the issue.

A: -(void)ChainPayment
{
[PayPal getPayPalInst].shippingEnabled = TRUE;

//optional, set dynamicAmountUpdateEnabled to TRUE if you want to compute
//shipping and tax based on the user's address choice, default: FALSE
[PayPal getPayPalInst].dynamicAmountUpdateEnabled = FALSE;

//optional, choose who pays the fee, default: FEEPAYER_EACHRECEIVER
[PayPal getPayPalInst].feePayer = FEEPAYER_EACHRECEIVER;

//for a payment with multiple recipients, use a PayPalAdvancedPayment object
PayPalAdvancedPayment *payment = [[PayPalAdvancedPayment alloc] init] ;
payment.paymentCurrency = @"USD";

//receiverPaymentDetails is a list of PPReceiverPaymentDetails objects
payment.receiverPaymentDetails = [NSMutableArray array];

//NSArray *nameArray = [NSArray arrayWithObjects:@"Frank's", @"Robert's", @"Julie's",nil];

for (int i = 1; i <= 2; i++)
{
    PayPalReceiverPaymentDetails *details = [[PayPalReceiverPaymentDetails alloc] init];

    details.description = @"Bear Components";
    if(i==1)
    {
        details.recipient =[[[_emailDictionary valueForKey:@"secondary"] valueForKey:@"1"] valueForKey:@"email"];//[NSString stringWithFormat:@"example-merchant-%d@paypal.com", 4 - i];
    }
    if(i==2)
    {
        details.recipient =[[_emailDictionary valueForKey:@"primary"] valueForKey:@"email"];// [NSString stringWithFormat:@"example-merchant-%d@paypal.com", 4 - i];

    }
    details.merchantName = [NSString stringWithFormat:@"merchant  name"];

    /*unsigned long long order, tax, shipping;
     order = i * 100;
     tax = 0.0;
     shipping =0.0;
     primary =     {
     email = "m,b@rew.com";
     "first_name" = aj;
     "last_name" = Shar;
     plan = Free;
     "profit_percent" = 68;
     "reffer_from" = "<null>";
     };
     secondary =     {
     1 =         {
     email = "pushnd@gmail.com";
     "profit_percent" = 32;
     };
     };
     }

     //subtotal of all items for this recipient, without tax and shipping
     details.subTotal = [NSDecimalNumber decimalNumberWithMantissa:order exponent:-2 isNegative:FALSE];

     //invoiceData is a PayPalInvoiceData object which contains tax, shipping, and a list of PayPalInvoiceItem objects
     details.invoiceData = [[PayPalInvoiceData alloc] init];
     details.invoiceData.totalShipping = [NSDecimalNumber decimalNumberWithMantissa:shipping exponent:-2 isNegative:FALSE];
     details.invoiceData.totalTax = [NSDecimalNumber decimalNumberWithMantissa:tax exponent:-2 isNegative:FALSE];

     //invoiceItems is a list of PayPalInvoiceItem objects
     //NOTE: sum of totalPrice for all items must equal details.subTotal
     //NOTE: example only shows a single item, but you can have more than one
     details.invoiceData.invoiceItems = [NSMutableArray array];
     PayPalInvoiceItem *item = [[PayPalInvoiceItem alloc] init];
     NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:_price];

     details.subTotal=number;
     item.totalPrice = details.subTotal;
     item.name = @"Audio";
     [details.invoiceData.invoiceItems addObject:item];*/

    //the only difference between setting up a chained payment and setting
    //up a parallel payment is that the chained payment must have a single
    //primary receiver.  the subTotal + totalTax + totalShipping of the
    //primary receiver must be greater than or equal to the sum of
    //payments being made to all other receivers, because the payment is
    //being made to the primary receiver, then the secondary receivers are
    //paid by the primary receiver.
    if (i == 2)
    {
        details.isPrimary = TRUE;
        details.merchantName = [NSString stringWithFormat:@"mercahnt name or app name"];
        NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:_price];
        details.subTotal=number;

    }
    else
    {

        float secondaryPrice=[_price floatValue];
        secondaryPrice=(secondaryPrice*[[[[_emailDictionary valueForKey:@"secondary"] valueForKey:@"1"] valueForKey:@"profit_percent"] integerValue])/100;
        NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
        [fmt setMaximumFractionDigits:2];
        NSString *stringPrice=[fmt stringFromNumber:[NSNumber numberWithFloat:secondaryPrice]];
        NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:stringPrice];
        details.subTotal=number;
    }

    [payment.receiverPaymentDetails addObject:details];
}
[[PayPal getPayPalInst] advancedCheckoutWithPayment:payment];
   }


text:
Q: Is the Twitter client for Android using OAuth? Since basic auth has been deprecated, is the official android twitter app using OAuth?
It still asks for my userid & password & I'm wondering how they are retrieving the oauth token ?

A: Sounds like they could be using xAuth - http://dev.twitter.com/pages/xauth. It's an alternate method of authenticating via OAuth. xAuth access is restricted to approved applications, you can't use it unless Twitter says you can.

A: Android client is using oAuth for twitter for example.
User must login to twitter at least once through your app and get a key.
It can be used several times and you dont need to get a key again.


text:
Q: AngularJS ng-repeat not working with $http.get So I have a basic page, which I can define json data manually in scope, and everything works fine.
Example:
<!DOCTYPE html>

<scrip src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.15/angular.js"></scrip>

Recent Orders

Order Date
Stock Description
Order #
Order Value

        [[item.oh_statusdate]]
        [[item.ol_stockdesc]]
        [[item.oh_orderno]]
        [[item.oh_ordervalue]]

 <scrip>

// register the app
var ordersApp = angular.module('ordersApp', []);
// alllow [[var]] instead of {{var}} for jinja2
this.ordersApp.config(function($interpolateProvider) {
          $interpolateProvider.startSymbol('[[');
          $interpolateProvider.endSymbol(']]');
        });
// create a controller inside the app
ordersApp.controller('orderCtrl', function ($scope) {
    // assign the json data
  $scope.orders = [
              {"ol_stockdesc": "EALANT",
              "oh_statusdate": "2014-07-02",
              "oh_custaccref": "416",
              "oh_ordervalue": null,
              "oh_orderno": 449605},

              {"ol_stockdesc": " BAG 25kg A",
              "oh_statusdate": "2014-07-04",
              "oh_custaccref": "416",
              "oh_ordervalue": null,
              "oh_orderno": 449824},

              {"ol_stockdesc": "BOTTLE B",
              "oh_statusdate": "2014-07-04",
              "oh_custaccref": "416",
              "oh_ordervalue": null,
              "oh_orderno": 449824},

              {"ol_stockdesc": "CREDIT CARD ADMIN & SURCHARGE",
              "oh_statusdate": "2014-07-04",
              "oh_custaccref": "416",
              "oh_ordervalue": null,
              "oh_orderno": 449824}
              ];
});
</scrip>

The above works fine, however if I try doing the following:
// register the app
var ordersApp = angular.module('ordersApp', []);
// alllow [[var]] instead of {{var}} for jinja2
this.ordersApp.config(function($interpolateProvider) {
          $interpolateProvider.startSymbol('[[');
          $interpolateProvider.endSymbol(']]');
        });
ordersApp.controller("orderCtrl", function($scope, $http) {
  $http.get('http://0.0.0.0:6543/orders.json?customer=416').
    success(function(data, status, headers, config) {
      $scope.orders = data;
    }).
    error(function(data, status, headers, config) {
      // log error
    });
});

It doesn't work, I can inspect the request with dev tools and see the data request is made successfully, and also inspect $scope and my data is in there, the console also doesn't log any errors. If anyone can shed some light on this it would be greatly appreciated. Please note due to my firewall I cannot post  tags, so my example code is shown as "scrip" instead of "script".

A: Can you please try to surround your $scope change with $apply? Like this:
$scope.$apply($scope.orders = data);

The reason could be that once in your clojure, the $scope scope don't have the same meaning.
A way to avoid doing this is to use $resource instead of $http as it would use a future and will populate nicely your array at the end of the request

A: As per Andy Gaskell's comment, I triple checked my JSON and the server was adding extra quotes and backslashes in one place, I swiftly fixed this and now my old code works perfectly.


text:
Q: Sharepoint custom list limit number of choices I've created a custom list in my SharePoint to allow users select a table reservation for our Christmas dinner.
My columns are just; "Name" and "Table Choice", "Table Choice" field has 16 different tables to select.
But 1 table can only have 10 person max so I'd like to Show a warning message if a user tries to reserve an already filled table.
Thanks in advance.

A: I can think of a couple ways to handle this scenario.

*

*Setup a workflow to handle when the a table is full to remove it from the options table.

*Use some jQuery and add it to the new and edit forms to check if a table is full when they select a value. Then you could display a message.

A: Idea based on Mike's suggestion. You can use "enforce unique values" feature to prevent users from duplicating data.

*

*Create a "Seat Choice" column for 10 seats.

*Create a text column named "Your Seat".

*Using JavaScript to set seat ("Table Choice" value and "Seat Choice" value) to "Your Seat" and make it read-only. Or, using InfoPath form to set the default value.

*Enforce "Your Seat" on unique values. The "enforce unique values" feature prevents users from duplicating data.

When user is trying to create duplicate data (the Table-Seat has already be selected), the error message will display and the item cannot be created successfully.


text:
Q: How to create a Unit test that should exclude extraneous dto properties?

class SampleDTO {
    public readonly code: string
    public readonly name: string
    public readonly type: string
}

const sampleBodyRequest = {
    code: 'NZD',
    name: 'New Zealand dollar',
    type: 'fiat',
    color: 'white'
}

describe('validate', () => {

    it('should exclude extraneous dto properties', () => {

    })
})

Is there a simple way to create this assertion?
Need to be mocha and sinon only. Thanks in advance

A: Something like this:
const assert = require('assert');
...
describe('validate', () => {

    it('should exclude extraneous dto properties', () => {
       const expected = Object.getOwnPropertyNames(new SampleDTO());
       const actual = Object.getOwnPropertyNames(theFunctionUnderTestThatConvertsTheInputToDTO(sampleBodyRequest));
       assert.deepStrictEqual(actual, expected);
    })
})


text:
Q: Salesforce files unable to access document with partner user We have the following scenario:
- Partner user as access to Campaign record
- An internal user add a File related to this Campaign Record
Partner user is not able to access the content document, and file is not visible when accessing the campaign record within Community.
Instead, on the other way around, when partner user adds a file, internal users can access it through the campaign record.
We have tried by adding a new ContentDocumentLink with LinkedEntityId = "User or Group Id", but we get below error:

INVALID ACCESS ON CROSS REFERENCE ENTITY

Someone has got more info about "how to share files related to a sObject"?

With a Partner User Profile the visibility is set "All Users" and ShareType= "V", but if shared file with a not Partner User profile, the visibility is set "Internal Users" and ShareType= "V" Or "I"


text:
Q: Download excel(NPOI) by write data to response from dynamic webapi I use .net core2  ASP.NET Boilerplate.
Because my webapi is dynamic created from application. In application architecture there is no "return File()" method because of not inherit from .net core mvc controller.
So I want implement downloadFile by Writing data to HttpContext Response.
In .net4.x, I use this code writing data to response, and it work well. but when I use it in .netcore, it does not work.
    public static void WriteWorkBookToResponse(this IWorkbook book, HttpContext httpContext, string fileName)
    {
        var response = httpContext.Response;

        using (var exportData = new MemoryStream())
        {
            response.Clear();
            book.Write(exportData);
            response.ContentType = "application/vnd.ms-excel";
            response.Headers.Add("Content-Disposition", $"attachment;filename={fileName}.xls");
            response.Body.Write(exportData.GetBuffer());
        }
    }

In logs,this is a error "System.InvalidOperationException: StatusCode cannot be set because the response has already started".  "at Abp.AspNetCore.Security.AbpSecurityHeadersMiddleware.Invoke(HttpContext httpContext) in D:\Github\aspnetboilerplate\src\Abp.AspNetCore\AspNetCore\Security\AbpSecurityHeadersMiddleware.cs:line 26".
I read .net core mvc source code and edit my code. like below:
    public static async void WriteToResponse2(this IWorkbook book, HttpContext httpContext, string templateName)
    {
        var response = httpContext.Response;

        using (var exportData = new MemoryStream())
        {
            book.Write(exportData);
            // response.ContentLength = exportData.GetBuffer().Length;
            response.ContentType = "application/vnd.ms-excel";
            SetContentDispositionHeader(httpContext, templateName);
            await StreamCopyOperation.CopyToAsync(exportData, response.Body, count: null, bufferSize: 64 * 1024, cancel: httpContext.RequestAborted);
        }
    }

    private static void SetContentDispositionHeader(HttpContext httpContext, string fileName)
    {
        if (!string.IsNullOrEmpty(fileName))
        {
            var contentDisposition = new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            contentDisposition.SetHttpFileName(fileName);
            httpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
        }
    }

Then the api return "406 Error:Not Acceptable", the file downloaded can not open, is damaged.
I need help, I will be thankful for you helping me.

A: change the WriteToResponse2 method to be :
public static void WriteToResponse2(this IWorkbook book, HttpContext httpContext, string templateName)
{
    var response = httpContext.Response;
    response.ContentType = "application/vnd.ms-excel";
    SetContentDispositionHeader(httpContext, templateName);
    book.Write(response.Body);
}

When used in an action method , be careful not to modify the response again .
public void Test2() {
    var newFile = @"newbook.core.docx";
    using (var fs = new FileStream(newFile, FileMode.Create, FileAccess.Write))
    {
        IWorkbook workbook = CreateBook();
        workbook.WriteToResponse2(contextAccessor.HttpContext,"ss.xlsx");
    }
}

Here's the screenshot it works :


text:
Q: Многократно запрашивается поиск по DOM'у одних и тех же элементов Есть проблемы с производительностью подписки на всплытие событий через jQuery. IE9 и IE11 указывают, что при клике 80% времени тратится на выполнение querySelectorAll. Анализ привёл в функцию $.event.dispatch (jQuery 1.8.1, в более новой версии (1.11.3) эта функциональность вынесена в $.event.handlers), которая содержит такой код:
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {

  // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
  if ( cur.disabled !== true || event.type !== "click" ) {
    selMatch = {};
    matches = [];
    for ( i = 0; i < delegateCount; i++ ) {
      handleObj = handlers[ i ];
      sel = handleObj.selector;

      if ( selMatch[ sel ] === undefined ) {
        selMatch[ sel ] = jQuery( sel, this ).index( cur ) >= 0;
      }
      if ( selMatch[ sel ] ) {
        matches.push( handleObj );
      }
    }
    if ( matches.length ) {
      handlerQueue.push({ elem: cur, matches: matches });
    }
  }
}

Обращаю внимание на следующие строки:
// Для каждого элемента от кликнутого наверх
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
    // Обнуляем кэш результатов поиска
    selMatch = {};

    // Для каждого из подписчиков
    for ( i = 0; i < delegateCount; i++ ) {
      // Берем селектор очередного подписчика
      sel = handleObj.selector;

      // Если такого селектора нет в кеше
      if ( selMatch[ sel ] === undefined ) {
        // Выполняем поиск всего соответствующего селектору
        // И запоминаем, есть ли просматриваемый внешним циклом элемент среди найденного
        selMatch[ sel ] = jQuery( sel, this ).index( cur ) >= 0;

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

Но это не всё. Я посмотрел реализацию в актуальной версии 1.11.3. В ней по-прежнему делается такое же количество запросов, но строка изменяется.
Вот что было в 1.8.1:
selMatch[ sel ] = jQuery( sel, this ).index( cur ) >= 0;

и вот что стало в 1.11.3:
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;

Здесь уже такая модификация кэширования кажется сомнительной.

Итак, вопросы:

*

*По какой причине код мог быть написан именно таким неоптимальным способом.

*Как лучше поступить, чтобы избежать проблем с производительностью?

Следующий сниппет показывает проблему множественных вызовов поиска:
Надо открыть консоль браузера и нажать на Click me to get a lot of searches!.
В консоль будет 21 раз выведено
qsa [id='sizcache041783330822363496'] section .smth
gbc smth-other

По поводу куска [id='sizcache041783330822363496'] есть родственный вопрос - эта форма убирает необходимость экранирования. Недавно в Sizzle было внесено изменение по этому поводу, но даже актуальная версия jQuery его не содержит.

$(function () {
  $("body")
  .on("click", "section .smth", function () { console.log("clicked", "section .smth") })
  .on("click", ".smth-other", function () { console.log("clicked", ".smth-other") });

  $("h1").text("Click me to get a lot of searches!");

  var qsa = Element.prototype.querySelectorAll, gbc = Element.prototype.getElementsByClassName;
  Element.prototype.querySelectorAll = function(s) { console.log('qsa', s); return qsa.apply(this, arguments) };
  Element.prototype.getElementsByClassName = function(s) { console.log('gbc', s); return gbc.apply(this, arguments) };
});
body { counter-reset: lev 1; }
div { counter-increment: lev; }
h1, h2 { cursor: pointer; }
h1:hover, h2:hover { background: silver; }
h1:after { content: " (" counter(lev) ")"; }

  Loading...

I'm smth and i'm waiting for a click

I'm smth other and i'm waiting for a click

В следующий сниппет помещён код функции dispatch из jQuery 1.8.1 (сниппет нужен для получения сворачиваемого спойлера, пытаться его запускать бесполезно):

dispatch: function( event ) {

  // Make a writable jQuery.Event from the native event object
  event = jQuery.event.fix( event || window.event );

  var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,
    handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
    delegateCount = handlers.delegateCount,
    args = [].slice.call( arguments ),
    run_all = !event.exclusive && !event.namespace,
    special = jQuery.event.special[ event.type ] || {},
    handlerQueue = [];

  // Use the fix-ed jQuery.Event rather than the (read-only) native event
  args[0] = event;
  event.delegateTarget = this;

  // Call the preDispatch hook for the mapped type, and let it bail if desired
  if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
    return;
  }

  // Determine handlers that should run if there are delegated events
  // Avoid non-left-click bubbling in Firefox (#3861)
  if ( delegateCount && !(event.button && event.type === "click") ) {

    for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {

      // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
      if ( cur.disabled !== true || event.type !== "click" ) {
        selMatch = {};
        matches = [];
        for ( i = 0; i < delegateCount; i++ ) {
          handleObj = handlers[ i ];
          sel = handleObj.selector;

          if ( selMatch[ sel ] === undefined ) {
            selMatch[ sel ] = jQuery( sel, this ).index( cur ) >= 0;
          }
          if ( selMatch[ sel ] ) {
            matches.push( handleObj );
          }
        }
        if ( matches.length ) {
          handlerQueue.push({ elem: cur, matches: matches });
        }
      }
    }
  }

  // Add the remaining (directly-bound) handlers
  if ( handlers.length > delegateCount ) {
    handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
  }

  // Run delegates first; they may want to stop propagation beneath us
  for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
    matched = handlerQueue[ i ];
    event.currentTarget = matched.elem;

    for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
      handleObj = matched.matches[ j ];

      // Triggered event must either 1) be non-exclusive and have no namespace, or
      // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
      if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {

        event.data = handleObj.data;
        event.handleObj = handleObj;

        ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
            .apply( matched.elem, args );

        if ( ret !== undefined ) {
          event.result = ret;
          if ( ret === false ) {
            event.preventDefault();
            event.stopPropagation();
          }
        }
      }
    }
  }

  // Call the postDispatch hook for the mapped type
  if ( special.postDispatch ) {
    special.postDispatch.call( this, event );
  }

  return event.result;
},

PS: Этот же вопрос на английском

A: Перенёс строку с сохранением кэша выше:
if ( delegateCount && !(event.button && event.type === "click") ) {
    selMatch = {};

И вынес index из кэширования в проверку:
if ( selMatch[ sel ] === undefined ) {
    selMatch[ sel ] = jQuery( sel, this );
}
if ( selMatch[ sel ].index( cur ) >= 0 ) {
    matches.push( handleObj );
}


text:
Q: Angular2 how to set templateUrl base path In Angular2, I have something like templateUrl = 'templates/app.component.html' during development. But in deployment, i need the url to be something like templateUrl = '/static/angular_templates/app.component.html'. It bites to have to change the url at every single place. Is there an easy way to set a base url and do something like
templateUrl = BASE_TEMPLATE_PATH+ '/app.component.html'

so i only need to update BASE_TEMPLATE_PATH when switching from development to production? Thanks!

A: With TypeScript you can use static variables, like :
export class AppTemplateConstants {

    public static get BASE_TEMPLATE_PATH(): string { return 'YOUR_PATH_HERE'; }

}

To import this :
import { AppTemplateConstants } from '../shared/constants/AppTemplateConstants';

To use this :
templateUrl: AppTemplateConstants.BASE_TEMPLATE_PATH + 'app/path/component.html'

A: You can achieve the desired effect without changing the templateUrl all over your code base by using UrlResolver, available since 2.0.0-alpha.36.
import {UrlResolver} from '@angular/compiler';
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';

let MyApp: any;

@NgModule({
  imports: [BrowserModule],
  providers: [{provide: UrlResolver, useValue: new UrlResolver("http://localhost/app")}],
  bootstrap: [MyApp]
})
class AppModule {
}

export function main() {
  platformBrowserDynamic().bootstrapModule(AppModule);
}

This will bootstrap your application with a custom instance of UrlResolver that has a base url that you specify. You can even have finer control over resolving the paths by extending the UrlResolver class:
class MyUrlResolver extends UrlResolver {
  resolve(baseUrl: string, url: string): string {
    // Serve CSS files from a special CDN.
    if (url.substr(-4) === '.css') {
      return super.resolve('http://cdn.myapp.com/css/', url);
    }
    return super.resolve(baseUrl, url);
  }
}

@NgModule({
  imports: [BrowserModule],
  providers: [{provide: UrlResolver, useClass: MyUrlResolver}],
  bootstrap: [MyApp]
})
...

(source)
Note: for this to work, you most likely need to use component-relative paths by providing moduleId: module.id, in your component definition, e.g.:
@Component({
    moduleId: module.id,  // use component-relative paths
    selector: 'dialogs',
    templateUrl: './dialogs.html',
})

A: I use DependencyInjection to pass around an EnviromentSettings object where I store environment variables such as BASE_TEMPLATE_PATH.
Kind of simple and nice mechanism in my opinion.
I hope it helps

A: You should define a constant in your build environment, using webpack, for example, you can use the webpack.DefinePlugin: Passing environment-dependent variables in webpack

A: you can use one common class/service in which you can store all your global variables and inject that class at the time of bootstrapping by doing so that class is now available to all another classes/components throughout the app and also now you can easily change your variable value by just changing at one place instead of making changes in all components here is example of same -
import {Component, Injecable} from 'angular2/core';

@Injecable()
export class GlobalService {
public BASE_TEMPLATE_PATH: string;

    constructor() {
        this.BASE_TEMPLATE_PATH = "Your Path Goes Here";
    }
}

and just register this service class in bootstrap like this -
bootstrap(AppComponent, [
  HTTP_PROVIDERS,GlobalService , XYZ...
]);

Now this GlobalService class is available to all another classes,
also now no need to register this class in the list of providers every time when you use because angular itself initialize this to all components, Now use these global variables/function in any class like this -
import {GlobalService} from './GlobalService';
...// stuff here
templateUrl: GlobalService.BASE_TEMPLATE_PATH + 'app/path/component.html'


text:
Q: Dropzone in foreach blade laravel not working I have  foreach loop of product
products in basket can get many of photos from user
users upload photo to product(sell farm's photo)
modal is in foreach loop
when modal is open dropzone not working and get this error:
dropzone.js:1 Uncaught Error: Dropzone already attached.
My modal

pivot->id}}" role="dialog" aria-labelledby="productmultiplephoto" aria-hidden="true">

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

                       <input type="hidden" name="original_name[]" id="product-photo">
                       <input name="product_id"  value="{{$product->id}}" type="hidden"  id="product_id" >
                       <input name="product_pivot"  value="{{$product->pivot->id}}" type="hidden"  id="product_pivot" >
                       <input name="cartproduct_id"   type="hidden"  id="cartproduct_id"value="{{$product->pivot->id}}" >

                       upload
                       <input type="hidden" name="original_name[]" id="product-photo">

My script

My button modal
@foreach($cart->products as $product)
     <button  type="button" data-toggle="modal" data-target="#productmultiplephoto-{{$product->pivot->id}}" class="btn-primary-multiple btn-primary-cm btn-with-icon">

        upload
    </button>
   @endforeach

Include modal part
@include('front::products.partials.add-multiple-photo')

A: Update your div like this :

for each iteration of the loop, you should also generate a new hidden input element with a unique name attribute for each product so that when uploading the file, you can know to which product the file is being added
<input type="hidden" name="product_id_{{$product->pivot->id}}" id="product_id" value="{{$product->id}}">

Full JS :

Update your modal div like this :

pivot->id}}" role="dialog" aria-labelledby="productmultiplephoto" aria-hidden="true">


text:
Q: In ICollectionOnSTLImpl implementation, can't access m_T or item object's members I'm trying to implement a collections of objects via VC6 that can be accessed by a VB6 programs.  I haven't been able to make it come together.
I have defined _CopyVariantFromAdaptItf and _CopyItfFromAdaptItf (from "ATL internals").
Here are my defines to be used in my collections definitions:
#define CComEnumVariantOnListOfItemInterface(ItemInterface) \
    CComEnumOnSTL<IEnumVARIANT, &IID_IEnumVARIANT, VARIANT,_CopyVariantFromAdaptItf<ItemInterface>,vector< CAdapt< CComPtr<ItemInterface> > > >

#define ClassInterfaceCollImpl(ContainerInterface,ItemInterface) \
    ICollectionOnSTLImpl< IDispatchImpl< ContainerInterface, &__uuidof(ContainerInterface) >,\
    vector< CAdapt< CComPtr<ItemInterface> > >,ItemInterface*,_CopyItfFromAdaptItf<ItemInterface>,\
    CComEnumVariantOnListOfItemInterface(ItemInterface) >

#define ContainerInterface      IFields
#define ContainerClass          CFields
#define ContainerClsid          CLSID_Fields
#define ItemInterface           IField
#define DllRegID                IDR_FIELDS

typedef std::vector< CAdapt< CComPtr<ItemInterface> > > ContainerType;

and this the preamble for the container class:
class ATL_NO_VTABLE ContainerClass :
    public ClassInterfaceCollImpl(ContainerInterface,ItemInterface),
    public ISupportErrorInfo,
    public CComObjectRoot,
    public CComCoClass<ContainerClass,&ContainerClsid>
{
public:
    ContainerClass();
BEGIN_COM_MAP(ContainerClass)
    COM_INTERFACE_ENTRY(IDispatch)
    COM_INTERFACE_ENTRY(ContainerInterface)
    COM_INTERFACE_ENTRY(ISupportErrorInfo)
END_COM_MAP()
//DECLARE_NOT_AGGREGATABLE(CFields)
// Remove the comment from the line above if you don't want your object to
// support aggregation.

DECLARE_REGISTRY_RESOURCEID(DllRegID)
// ISupportsErrorInfo
    STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);

// IFields
private:
    int GetIndex( BSTR name );

etc....
and in my attempted implementation, I'm trying to scan the included objects for a matching name that is accessed in the object's function pName().  Note that I'm showing two different approaches that I have tried:
int CFields::GetIndex( BSTR name )
{

    long count = 0;
#if (1)
    Count(&count);
    for (unsigned int i=0; i<count; i++)
        if (wcscmp( name, m_coll.m_T->pName())
            return (i);
#else
    std::vector<CAdapt<CComPtr<IField> > >::iterator itr;
        for (itr = m_coll.begin(); itr != m_coll.end(); itr++)
            if (wcscmp( name, itr->m_T->pName()))
                count++;
            else
                return (count);

#endif
    throw E_INVALIDARG_13;
}

If I try the #if (1), I get an error that m_T is not a member of "vector<...".
If I try m_coll->m_T, I get an error that "vector<..." does not have overloaded ->, which I would expect.
If I try the #if (0), I get an error that pName() is not a member of '_NoAddRefReleaseOnCComPtr
Thanks in advance for any help you can give me!
Vance

A: I know I'm talking to myself, but I'm hoping to help someone else in case I stumble across a CORRECT answer.
Ok, I have a working system and based on the response to another question How to retrieve object pointer from ATL collection of objects?, this is what I ended up with.  I added the line:
COM_INTERFACE_ENTRY_IID(CLSID_Fields, CFields)

between the
    BEGIN_COM_MAP(CFields)
and
    END_COM_MAP()
lines so that getItemObjectPtr would work.
I changed the ItemInterface back to IField and changed the GetIndex method to:
    long count = 0;
    ContainerType::iterator itr;
for (itr = m_coll.begin(); itr != m_coll.end(); itr++)
    if (wcscmp( name, getItemObjectPtr( itr->m_T )->pName()) == 0)
        count++;
    else
        return (count);
    throw (HRESULT)E_INVALIDARG_13;

and the method getItemObjectPtr is defined as:
CFields * CrecordSet::getItemObjectPtr( IFields *ppFields )
{
    CComQIPtr<CFields, &CLSID_Fields> pFields = ppFields;
    return (pFields);
}


text:
Q: ios google sign in not getting profile scope I implemented a while ago google sign in on my app. everything was working. Im requesting a google profile and email scopes and when calling https://www.googleapis.com/oauth2/v3/tokeninfo?id_token= with the token i received in the app and i got the user profile.
today i run the code and i get the token without the profile only email and email verified. log in via android and via web return with profile. the only problem is with the ios. i can see also that the idtoken in ios is smaller then the one i received via android/web
 GIDSignIn.sharedInstance().delegate = self
    GIDSignIn.sharedInstance().uiDelegate = self
    GIDSignIn.sharedInstance().clientID = kClientId

    GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/plus.login")
    GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/plus.me")

    GIDSignIn.sharedInstance().signInSilently()

A: GIDSignIn.sharedInstance().delegate=self
GIDSignIn.sharedInstance().uiDelegate=self
GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/plus.me")
GIDSignIn.sharedInstance().signIn()

This is my button on click and it is perfectly working for me.


text:
Q: Syntax error, unexpected 'form' (T_STRING), expecting ')' I tried to make a form inside a modal with Bootstrap but I get errors.

Facade\Ignition\Exceptions\ViewException syntax error, unexpected
  'form' (T_STRING), expecting ')' (View:
  C:\xampp\htdocs\invuya\resources\views\petambak\index.blade.php)

http://localhost/invuya/public/petambak
This is the source code of the error:

Form Petambak

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

            </form action="{{route('petambak.store)}}" method="post">

                    Nama
                    <input type="text" class="form-control" name="Nama" id="name">

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Simpan</button>

A: Maybe problem is in line </form action="{{route('petambak.store)}}" method="post"> because of missin pair quote after petambak.store?
Also localhost is available only from your machine


text:
Q: What determines the sign of a separation constant? I am studying the method of separation of variables for the heat equation.  I am struggling to understand why the separation constant takes on a positive or negative value.  For instance if we apply the method of separation of variables to this equation.
$$\frac{\partial u}{\partial t}= \frac{k}{r} \frac{\partial}{\partial r} (r \frac{\partial u}{\partial r} )
$$
looking for product solutions $u(r,t)=\phi(r)h(t)$ then dividing by $\phi h $ yields...
$$\frac{1}{kh}\frac{dh}{dt}=\frac{1}{r \phi} \frac{d}{dr} (r \frac{d \phi}{dr})=-\lambda$$
But the following problem ends up with a positive separation constant.
$$\frac{\partial u}{\partial t}= k \frac{\partial^4}{\partial x^4}
$$
looking for product solutions $u(x,t)=\phi(x)h(t)$ then dividing by $k \phi h $ yields...
$$\frac{1}{kh}\frac{dh}{dt}=\frac{1}{\phi} \frac{\partial^4}{\partial x^4}=\lambda$$
Why does the first problem end up with a negative constant and the second gets  a positive one?
Edit: Does it have something to do with this question Why can we assume the separation constant??


text:
Q: How to find cause and of the SocketException with message that an established connection was aborted by the software in your host machine? I know the similar question may have been asked many times, but I want to represent the behavior I'm seeing and find if somebody can help predict the cause of this.
I am writing a windows service which connects to other windows service over TCP.
There are 100 user entities of this, and 5 connections per each. These users perform their tasks using their individual connections.
The application goes on withough seeing this problem for 1 or 2 days. Or sometimes show the problem right after starting (-rarely). The best run I had was like 4 to 5 days without showing this exception. And after that application died or I had to stop it for various reasons.
I want to know what can be causing this?
Here is the stacktrace.
System.IO.IOException: Unable to write data to the transport connection: An established connection was aborted by the software in your host machine. ---> System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine
   at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   --- End of inner exception stack trace ---
   at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.Security._SslStream.StartWriting(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security._SslStream.ProcessWrite(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.Write(Byte[] buffer, Int32 offset, Int32 count)

A: Did you find a solution to this? Perhaps you can come closer to a solution if you add network tracing to your app.config?
<?xml version="1.0"?>
<configuration>
    <system.diagnostics>
        <sources>
            <source name="System.Net.Sockets">
                <listeners>
                    <add name="Sockets"/>
                </listeners>
            </source>
        </sources>
        <switches>
            <add name="System.Net.Sockets" value="31"/>
        </switches>
        <sharedListeners>
            <add name="Sockets" type="System.Diagnostics.TextWriterTraceListener" initializeData="c:\socketdump.log"/>
        </sharedListeners>
        <trace autoflush="true"/>
    </system.diagnostics>
</configuration>

Also, perhaps you could setup logging for TLS/SSL. Add the following DWORD and set it to 7, to your registry, reboot and watch all schannel events in the System Event Log:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\EventLogging

Hope that help, but it might be lots of punches in the dark I guess...


text:
Q: Boo in Visual Studio? Is there a way to use boo in my msvs? I would like my form to call some boo code instead of C#.

A: I'm using Boo to replace an old database-driven clunky rules engine, and it's working great.
Start here: Boo Interactive Interpreter
// One-line Boo interpreter in C#
InteractiveInterpreter2 interpreter = new InteractiveInterpreter2();

If you mean defining your forms and actually coding Boo in VS .NET, look into BooLangStudio.

A: We've been working on a plug-in for a while, it sorta works but you should really use SharpDevelop or MonoDevelop at this point. The VS plugin might get revitalized since the new VS plugin architecture for VS2010 is so much better but it's really a lot of work and we have all been pretty busy.

A: Visual Boo (source code) is a more recent project adding support for Boo in VS2010.

A: You can have your Boo script pop-up a source-readable VS debugger by inserting:
System.Diagnostics.Debugger.Launch()

or
System.Diagnostics.Debugger.Break()

A: If by msvs you mean visual studio, you would have to write a language plugin for boo (assuming one does not exist) using the Visual Studio Extendability framework.
Here is such a plugin :
http://www.codinginstinct.com/2008/05/boo-in-visual-studio.html


text:
Q: Finding where a variable or object was declared Netbeans In Netbeans PHP if you control + mouse1 click on an object or variable it will go to the initial declaration, if it's in the same script.
But is there any way to make it go to the initial declaration if it was made inside a previously included script?

A: There may be a better way to do this, but this is my work around:

*

*Select or highlight the variable.

*Right click > Refactor > Rename...

*Change the name.

*Click the Preview button

Netbeans will then list all the occurrences of the variable within your project. From this list, you should be able to find where you initialized it.
Be sure to click the Cancel button, if you do not mean to rename the variable.
For the same results without refactoring, you can also use Edit > Find Usages.


text:
Q: What can be the event similar to onpopstate that works across documents? From mozilla docs:

A popstate event is dispatched to the window every time the active
  history entry changes between two history entries for the SAME
DOCUMENT.

Which window event should i use if i need to listen to 'session history changes' ACROSS DOCUMENTS in a browsing context?
I am writing a js library that helps tracking navigation when user use back/forward browser buttons. The library would record when user is navigated from page B to page A (backwards) or page A to page B(forward). I've achieved the tracking for the pages that use hashes using the 'popstate' event but when user navigate from page A to page B this event doesn't work.
I've looked at pageshow/pagehide events but they fires on simple page loads as well and not just when the 'session history' changes (ie page fetched from history).
What should i be looking at to know "browser has looked into session history to fetch the current page"?

A: You're going to have to handle the Window's beforeunload event, and also put code on whichever page loading event is appropriate for your use case.
Note that for beforeunload, you don't have time to write something server-side.  You'll have to track this in LocalStorage.

A: There is something weird in your requirements:
You say you are writing a js library, but for this library to work across different documents, for a start, it would at least have to be executed on every documents navigated by the user.
And even if it were the case, there wouldn't be any solid way to do what you want.
Browsers' behavior regarding history navigation vary a lot:
For instance, FF will keep in memory its current state, and will not reload the page per se, but simply reactivate its saved state (i.e you won't even be able to know that the user came back to this page (apart from ugly polling of performance.navigation.type, which despite what MDN says is only absent in Safari).

So all in all, what you want to make is a job for a browser extension, not for a web-library.


text:
Q: Why queryset returns value instead of instance in Django Views? My Problem
I have a queryset in Django View. That queryset should return an instance. But instead of that it returns a value
Models.py
class Author(models.Model):
    name = models.CharField(max_length=250, unique=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('authors:author_detail', args=[str(self.id)])

    class Meta:
        verbose_name = 'Author'
        verbose_name_plural = 'Authors'

Projects URLS.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('author/', include('authors_app.urls', namespace='authors')),
]

authors_app ULRS.py
from .views import *

app_name = 'authors'

urlpatterns = [
    path('<int:pk>/', AuthorDetail.as_view(), name='author_detail'),
]

Views.py
class AuthorDetail(ListView):
    model = Book
    context_object_name = 'author_books'
    template_name = 'author-detail.html'
    queryset = Book.objects.all().order_by('bookinfo__bestseller')
    paginate_by = 36

    def get_queryset(self, **kwargs):
        author_id = Author.objects.get(pk = self.kwargs['pk'])
        print(author_id)
        qs = super().get_queryset(**kwargs)
        return qs.filter(author = author_id)

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super().get_context_data(**kwargs)
        # Add in a QuerySet
        context['author'] = Author.objects.get(pk = self.kwargs['pk'])
        # context['image'] = f"/mnt/HDD/wiki/parser/images/photos/10.png"
        return context

Traceback
Traceback (most recent call last):
  File "/mnt/HDD/tibrains.test/titest-env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/mnt/HDD/tibrains.test/titest-env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/mnt/HDD/tibrains.test/titest-env/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/mnt/HDD/tibrains.test/titest-env/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch
    return handler(request, *args, **kwargs)
  File "/mnt/HDD/tibrains.test/titest-env/lib/python3.8/site-packages/django/views/generic/list.py", line 142, in get
    self.object_list = self.get_queryset()
  File "/mnt/HDD/tibrains/08/titest_project/authors_app/views.py", line 17, in get_queryset
    return qs.filter(author = author_id)
  File "/mnt/HDD/tibrains.test/titest-env/lib/python3.8/site-packages/django/db/models/query.py", line 941, in filter
    return self._filter_or_exclude(False, args, kwargs)
  File "/mnt/HDD/tibrains.test/titest-env/lib/python3.8/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
  File "/mnt/HDD/tibrains.test/titest-env/lib/python3.8/site-packages/django/db/models/query.py", line 968, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "/mnt/HDD/tibrains.test/titest-env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1393, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/mnt/HDD/tibrains.test/titest-env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1412, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "/mnt/HDD/tibrains.test/titest-env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1320, in build_filter
    self.check_related_objects(join_info.final_field, value, join_info.opts)
  File "/mnt/HDD/tibrains.test/titest-env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1147, in check_related_objects
    self.check_query_object_type(value, opts, field)
  File "/mnt/HDD/tibrains.test/titest-env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1128, in check_query_object_type
    raise ValueError(
ValueError: Cannot query "Lawrence Gilman": Must be "Author" instance.

When I open authors page - mysite.com/author/51/
I've got an Error:
Cannot query "Lawrence Gilman": Must be "Author" instance.
Question
How can I get an instance in that queryset?

A: You can filter with the author_id itself, and thus obtain a get_queryset with:
from django.shortcuts import get_object_or_404

class AuthorDetailView(ListView):
    # …

    def get_queryset(self, **kwargs):
        return super().get_queryset(**kwargs).filter(author_id=self.kwargs['pk'])

    def get_context_data(self, **kwargs):
        return super().get_context_data(
            **kwargs, author=get_object_or_404(Author, pk=self.kwargs['pk'])
        )

A: I think this is the problem:
author_id = Author.objects.get(pk = self.kwargs['pk'])

use filter instead of get:
author_id = Author.objects.filter(pk = self.kwargs['pk'])


text:
Q: Implementing N choose K recursively in Java I am new to Java and am I trying to implement a recursive method for finding "n choose k".
However, I've run into a problem.
public class App {
public static void main(String[] args) throws Exception {
    int n = 3;
    int k = 2;
    int result = combRecursion(n, k);
    System.out.println(result);
}

private static int combRecursion(int n, int k) {
    if (k == 0) {
        return 1;
    } else {
        return (combRecursion(n - 1, k - 1) + combRecursion(n - 1, k));
    }
}

Output:
many repetitions of this line:
at App.combRecursion(App.java:14)

A: It's possible to pick k items from the set of n items only if n is greater or equal to k.
You need to cut off fruitless branches of recursion spawn by the call combRecursion(n - 1, k) which doesn't reduce the number of item in the sample.
When you need to create a recursive method, it should always contain two parts:

*

*Base case - that represents a set of edge-cases, trivial scenarios for which the result is known in advance. If the recursive method hits the base case (parameters passed to the method match one of the conditions of the base case), recursion terminates. In for this task, the base case will represent a situation when the source list was discovered completely and position is equal to its size (invalid index).

*Recursive case - a part of a solution where recursive calls are made and where the main logic resides.
Your recursive case is correct: it spawns two recursive branches of execution (one will "pick" the current item, the second will "reject" it).
But in the base case, you've missed the scenario mentioned above, we need to address these situations:

*

*n isn't large enough (k > n), so that is not possible to fetch k item. And the return value will be 0 (or instead of returning a value, you might throw an exception).

*k == 0 result should be 1 (it's always possible to take 0 items, and there's only one way to do it - don't pick anything).

*When k == n - there's only one way to construct a combination, as @akuzminykh has pointed out. And the return value will be 1
Note that because your goal is to get familiar with the recursion (I'm pretty sure that you're doing it as an exercise) there's no need to mimic the mathematical formula in your solution, use pure logic.
Here is how you can implement it:
private static int combRecursion(int n, int k) {
    if (k > n) return 0;  // base case - impossible to construct a combination
    if (n == k || k == 0) return 1; // base case - a combination was found

    // recursive case
    return combRecursion(n - 1, k - 1) + combRecursion(n - 1, k);
}

main() - demo
public static void main(String[] args) {
    System.out.println(combRecursion(3, 2));
    System.out.println(combRecursion(5, 2));
}

Output
3  // pick 2 item from the set of 3 items
10 // pick 2 item from the set of 5 items

A: Your base case ought to include both n == k || k == 0 for "n choose k" to be implemented correctly. That way, both calls will eventually terminate (even though your current implementation is rather inefficient as it has exponential runtime). A better implementation would use the formula n!/k!/(n-k)! or the multiplicative formula to run in linear time:
int factorial(int n) {
    int res = 1;
    for (; n > 1; n--) {
        res *= n;
    }
    return res
}
int choose(int n, int k) {
    return factorial(n)/factorial(k)/factorial(n-k);
}

further optimizing this is left as an exercise to the reader (hint: a single for loop suffices).


text:
Q: Filtrar vlans de un comando conf= "sh run int Eth102/1/32\r\r\n\r\n!Command: show running-config interface Ethernet102/1/32\r\n!Time: Tue Apr  9 12:49:55 2013\r\n\r\nversion 5.2(1)N1(9b)\r\n\r\ninterface Ethernet102/1/32\r\n  description CD1SW-BBTACCN5K-1\r\n  switchport mode trunk\r\n  switchport trunk allowed vlan 500,556,650,827,848\r\n  spanning-tree port type edge trunk\r\n  speed 1000\r\n  duplex full\r\n  no snmp trap link-status\r\n\r\n\rCD1SW-SSTACC3NK-1# "

Como podría sacar solo estos números de esta variable? y tenerlos en una lista.
500,556,650,827,848
Siempre estará después de switchport trunk allowed vlan. Lo he intentado con re.findall pero no se sido capaz... También podría ser que viniera así
500-550 y deneria coger de inicio a fin

A: Con re.findall() puedes extraer toda secuencia de números separados por comas o guiones que aparezca tras las palabras "switchport trunk allowed vlan" mediante la siguiente expresión regular:
import re
resultado = re.findall(r"(?:switchport trunk allowed vlan *)([\d, -]+)", conf)

En este caso lo que va dentro del (?:) es un "grupo de no-captura. Buscamos que aparezcan esas palabras, pero no queremos capturarlas. El siguiente grupo entre paréntesis ([\d,-]+) es lo que queremos capturar, que representa una secuencia de uno o más caracteres de la categoría dígitos, coma, espacio, o guión.
El resultado será una lista, con tantos elementos como veces haya aparecido el grupo "switchport trunk allowed vlan" seguido de números. En tu cadena de ejemplo aparece una sola vez, por lo que el resultado tendrá un solo elemento.
Ese elemento es el trozo de cadena que contiene ya solamente los números, comas y guiones. En este caso:
>>> resultado
['500,556,650,827,848']

Ahora deberías iterar por esa lista y para cada elemento, que es una cadena, dividirlo por las comas. Y para cada uno de los elementos resultantes (que será un número o un rango separado por guiones), convertirlo a un entero o secuencia de enteros, para finalmente recogerlos todos en una lista.
Esta parte es muy similar a otra pregunta que hiciste hace un tiempo, y se puede reaprovechar parte de mi respuesta:
def traducir_rangos(lista):
  for elemento in lista:
    if "-" not in elemento:
      yield int(elemento)
    else:
      inicio, fin = elemento.split("-")
      yield from range(int(inicio), int(fin)+1)

lista_final = []
for caso in resultado:
  lista_final.extend(traducir_rangos(caso.split(",")))

Y en lista_final tendrías:
[500, 556, 650, 827, 848]

Otro ejemplo creado artificialmente para ver que funciona si la cadena contiene varios grupos en los que haya encajado y algún grupo contiene rangos separados por guiones, sería:
conf= "switchport trunk allowed vlan 200-204,303; mas cosas y otro switchport trunk allowed vlan 403, 500-510 y mas cosas"

Y el código anterior produciría ahora lo siguiente en resultado:
['200-204,303', '403, 500-510 ']

y lo siguiente en lista_final:
[200, 201, 202, 203, 204, 303, 403, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510]


text:
Q: Could not find method storeFile() for arguments [C:/Users/tienn/key.jks] on SigningConfig_Decorated I built release app bundle with this error, I don't know where I am wrong.
Could not find method storeFile() for arguments [C:/Users/tienn/key.jks] on SigningConfig_Decorated{name=release, storeFile=null, storePassword=null, keyAlias=key, keyPassword=***, storeType=jks, v1SigningEnabled=true, v2SigningEnabled=true} of type com.android.build.gradle.internal.dsl.SigningConfig.

This is my app_dir/android/app/build.gradle file:
signingConfigs {
    release {
        keyAlias keystoreProperties['keyAlias']
        keyPassword keystoreProperties['keyPassword']
        storeFile keystoreProperties['storeFile']
        storePassword keystoreProperties['storePassword']
    }
}

buildTypes {
    release {
        signingConfig signingConfigs.release
    }
}

This is my app_dir/android/key.properties
storePassword=***
keyPassword=***
keyAlias=key
storeFile=C:/Users/tienn/key.jks

Many thanks!

A: The function takes a file as an argument, so you should use this instead
signingConfigs {
    release {
        keyAlias keystoreProperties['keyAlias']
        keyPassword keystoreProperties['keyPassword']
        storeFile file(keystoreProperties['storeFile']) //<-----file here
        storePassword keystoreProperties['storePassword']
    }
}

buildTypes {
    release {
        signingConfig signingConfigs.release
    }
}


text:
Q: How can resize the image with user defined names with user defined folder in typo3 I have a typo3 site.
Where i need to resize the  images with user defined names and then store it in a folder
Any idea how can we do this ?

A: Maybe this TypoScript option helps:
config.meaningfulTempFilePrefix = 1

Now when resizing an image and by this storing the resulting file in typo3temp the filename won't be gibberish only but still containing the original filename.
http://wiki.typo3.org/TSref/CONFIG


text:
Q: How to dynamically change HTML content of a page with information from a PHP file? So, I have a php file called db.php to replicate some sort of database. This is basically a file with some multidimensional associative arrays:
<?php
$arrShowcases = array(
    "1"=>array("title"=>"Landing Page", "descr"=>"Welcome!", "img"=>"actions-landing.jpg", "polygon"=>array(
        0=> array(
                "points"=>"1338,4,1338,50,1272,50,1272,4",
                "link"=>"69",
                "modalbody"=>"This button lets you Signup on the webapp",
                "modaltitle"=>"Signup Button"
            ),
        1=> array(
                "points"=>"1246,12,1249,44,1206,44,1204,14",
                "link"=>"2",
                "modalbody"=>"This button redirects you for the login form",
                "modaltitle"=>"Login Button"
            )
    )),
    "2"=>array("title"=>"Login page", "descr"=>"Make your login", "img"=>"actions-login.jpg", "polygon"=>array(
        0=> array(
            "points"=>"1338,4,1338,50,1272,50,1272,4",
            "link"=>"69",
            "modalbody"=>"This button lets you Signup on the webapp",
            "modaltitle"=>"Signup Button"
            ),
        1=> array(
            "points"=>"1246,12,1249,44,1206,44,1204,14",
            "link"=>"69",
            "modalbody"=>"This button redirects you for your dashboard",
            "modaltitle"=>"Login Button"
            )
    ))
);
?>

Then, I have a html page with a section element where I need to change page header title, subtitle, image and some polygon points:

          <?php include cfgPath."/includes/menu.html"; ?>

 Landing page

// Lorem ipsum...

              <img id="pageScreenshot" src="<?php echo cfgRoot; ?>/assets/images/actions-landing.jpg" class="img-responsive" alt="Landing Page"/>
              <svg id="svgImageMap" width="1366" height="768">
                <polygon points="1338,4,1338,50,1272,50,1272,4" data-originalpoints="1338,4 1338,50 1272,50 1272,4" data-id="0"/>
                <polygon points="1246,12,1249,44,1206,44,1204,14" data-originalpoints="1246,12 1249,44 1206,44 1204,14" data-id="1"/>
                <polygon points="378,43,446,42,445,11,377,9" data-originalpoints="378,43 446,42 445,11 377,9" data-id="2"/>
                <polygon points="196,10,367,10,366,42,195,43" data-originalpoints="196,10 367,10 366,42 195,43" data-id="3"/>
                <polygon points="121,16,120,35,164,39,164,17" data-originalpoints="121,16 120,35 164,39 164,17" data-id="4"/>
                <polygon points="14,15,13,40,95,43,95,12" data-originalpoints="14,15 13,40 95,43 95,12" data-id="5">
              </svg>

            <a class="btn btn-success btn-sm btn-block" href="<?php echo cfgRoot; ?>/app/showcase/showcaseView.php">Go Back

As you can see on the above html for the section element, I wrote by hand all the information. However, my goal is to change that info with stuff provided from the db.php file.
I want something like this nameofthepage.php?id=1 (and all the info provided in the position 1 of the array goes to the html) or this: nameofthepage.php?id=2 (and all the info provided in the position 2 of the array goes to the html). Any advice or tip to get this behavior?
So far, I tried to do echos like this:
<?php echo $arrShowcases[positions-that-i-want]["information-that-i-want"]; ?>

to change the hardcoded html but that doesn't get me the dynamic behavior I need.

A: I hope you'll get the point.
<?php
    //-----------------------------
    // If id is not sent then stop with page execution. You can redirect or something else.
    if(!isset($_GET["id"])) {
        die("ID not received.");
    }
    // Get that received id because at this point we are sure that id is received because page execution did not stopped before.
    $id = $_GET["id"];
    //-----------------------------
    // Import your "database".
    require_once "db.php";
    //-----------------------------
    // If there is no page with that id, stop page execution.
    if(!isset($arrShowcases[$id])) {
        die("page does not exists.");
    }
    // If there is a page then store it in a variable.
    $page = $arrShowcases[$id];
    //-----------------------------
?>

          <?php include cfgPath."/includes/menu.html"; ?>

              <?= $page['title']; ?> // Echo page title.

<?= $page['descr']; ?>
 // Echo page description.

              <img id="pageScreenshot" src="<?php echo cfgRoot; ?>/assets/images/<?= $page['img']; ?>" class="img-responsive" alt="<?= $page['title']; ?>"/> // Echo image filename and page title.
              <svg id="svgImageMap" width="1366" height="768">
                // For each polygon, echo it's points and key as an index (0, 1, 2, 3...)
                <?php foreach ($page["polygon"] as $key => $value) { ?>
                    <polygon points="<?= $value['points']; ?>" data-originalpoints="<?= $value['points']; ?>" data-id="<?= $key; ?>"/>
                <?php } ?>
              </svg>

            <a class="btn btn-success btn-sm btn-block" href="<?php echo cfgRoot; ?>/app/showcase/showcaseView.php">Go Back

A: When you enter an URL in the browser, you are making a GET HTTP request.
That request can take variables in the form of parameters, by adding ? to the end of your URL and then all the parameters you need, separated by &, like this(based on your example):
nameofthepage.php?id=1&another=2
In PHP, you can catch those parameters using the superglobal $_GET, like this:
$id = $_GET['id'];
By now you should understand @Spectarion answer, that solves your problem.
I don't think any answer should be marked as correct, because these are the basics of working with HTTP with PHP, but that is up to you.


text:
Q: Ссылка в tkinter не работает в самом меню, подскажите что не так from tkinter import *
import webbrowser

def callback(event):
    webbrowser.open_new(r"https://www.google.ru")

root = Tk()
root.geometry('230x110')
root.title('тест')
root.resizable(width=False, height=False)

main_menu = Menu()

Help_menu = Menu(tearoff=0)
Help_menu.add_command(label="тык", command=callback)

main_menu.add_cascade(label="Help", menu=Help_menu)

root.config(menu=main_menu)
m2 = Button(root, text="google", padx="72", pady="5", command=callback)
m2.place(x=15, y=60)
m2.bind("<Button-1>", callback)
root.mainloop()

Exception in Tkinter callback
Traceback (most recent call last):
 File "C:\Users\AlexTrask\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
   return self.func(*args)
TypeError: callback() missing 1 required positional argument: 'event'


text:
Q: Заполнение массива значениями из БД Из базы данных надо получить и сохранить значения в двумерный массив Object[][] data. В нём должно быть (как и в таблице в БД) 4 столбца.
Я сделал так:
    try {
            con = DriverManager.getConnection(url, user, password);
            stmt = con.createStatement();
            rs = stmt.executeQuery(query);

            count = 0;

            while(rs.next()) {
                count++;
            }

            Object[][] data = new Object[count][4];
            count = 0;

            while(rs.next()) {
                data[count][0] = rs.getString(1);
                data[count][1] = rs.getString(2);
                data[count][2] = rs.getString(3);
                data[count][3] = rs.getString(4);

                count++;
            }

        } catch (SQLException e1) {
            e1.printStackTrace();
        } finally {
            try { con.close(); } catch(SQLException se) {}
            try { stmt.close(); } catch(SQLException se) {}
            try { rs.close(); } catch (SQLException se) {}
        }

Но JAVA выдаёт NullPointerExeption! Мои проверки выявили что значения в массиве все равны NULL.

A: Добавьте данную строчку перед вторым циклом. При каждом вызове next() указатель смещается на следующий элемент и потому в конце он указывает в никуда и его необходимо сбросить в начало.
   rs.beforeFirst()


text:
Q: multiple (uneven row numbers) csv files into a matrix in R Overall I want to make a heatmap in R using gplots. So I need to combine the csv files into a matrix. I have tried varoius attempts but I keep running into the problem of uneven row length.
Such as when I tried this approach from code I got
num.el <- sapply(a, length)
res <- cbind(unlist(a), rep(1:length(a), num.el))

I get error
  Error in structure(res, levels = lv, names = nm, class = "factor") :
  'names' attribute [24] must be the same length as the vector [2]

I have 40+ csv files with uneven row numbers. I inclused two samples below
test1.csv
ark,
Actinocyclus actinochilus,7
Asterionella formosa,4
Aulacodiscus orientalis,1
Aulacoseira granulata,3
Chaetoceros radicans,1
Corethron hystrix,6
Coscinodiscaceae,1
Dactyliosolen fragilissimus,32
Diadesmis gallica,1
Diatoma hyemalis,1
Synedropsis hyperboreoides,4
Trigonium formosum,4
Urosolenia eriensis,2

test2.csv
ant,
Actinocyclus actinochilus,55
Asterionella formosa,3
Aulacoseira granulata,5
Chaetoceros radicans,7
Dactyliosolen fragilissimus,5
Diatoma hyemalis,5
Stephanopyxis turris,1
Striatella unipunctata,1
Synedropsis hyperboreoides,28
Trigonium formosum,3
Urosolenia eriensis,2

As you can see there is overlap in the name but the files are not exact matches. What would be the best way to over come the missing data for the heatmap to be built?

A: The problem is you only have one "row" in the first column, so R doesn't know what to do with the names of your data.
Here we create a list of all the .csv files in the folder:
z <- list.files(pattern = ".*csv")

Then read in each file using readLines, then uses only the 2:end of the data for the read.table, and take the first row as a name of the column:
data <- lapply(z, function(x) {temp <- readLines(x);
           read.table(text = temp[2:length(temp)], sep = ",", col.names = c("Species", temp[1]))})

Now your data should be a list of data frames.
I'm assuming you want to merge them:
Reduce(function(x, y) merge(x, y, all=TRUE), data)

Which gives me the following from your example data:
                       Species ark. ant.
1    Actinocyclus actinochilus    7   55
2         Asterionella formosa    4    3
3      Aulacodiscus orientalis    1   NA
4        Aulacoseira granulata    3    5
5         Chaetoceros radicans    1    7
6            Corethron hystrix    6   NA
7             Coscinodiscaceae    1   NA
8  Dactyliosolen fragilissimus   32    5
9            Diadesmis gallica    1   NA
10            Diatoma hyemalis    1    5
11  Synedropsis hyperboreoides    4   28
12          Trigonium formosum    4    3
13         Urosolenia eriensis    2    2
14        Stephanopyxis turris   NA    1
15      Striatella unipunctata   NA    1


text:
Q: How long does Sonatype staging take to sync my artifacts with Maven central I have successfully deployed my Maven artifacts (release) into Sonatype's staging repository with Maven.
Uploading address is https://oss.sonatype.org/service/local/staging/deploy/maven2/
I would like to know how long will it take before I can see them in the central repository?

A: From my last experience, the artifact that I released, it was synced with the Central Repository in ~8 hours.

A: Provided you have followed the steps to activate the sync, it should take about 2 hours.

9 Activate Central Sync
The first time you promote a release, you need to comment on the OSSRH JIRA ticket you created in Section 3 so we can know you are ready to be synced. We will review your promoted artifacts. If no problem found, we will activate Central Sync for you and close your JIRA ticket.
After Central Sync is activated, your future promotion will be synced automatically. The sync process runs roughly every 2 hours.

A: In case others are seeing this question, here's an excerpt from the email received by Central OSSRH (Sonatype) after releasing the first artifact for a new project:

Central sync is activated for your.domain.artifact. After you successfully release, your component will be published to Central https://repo1.maven.org/maven2/, typically within 30 minutes, though updates to https://search.maven.org can take up to four hours.

A: After a successful release the artifact will be published to Central, typically within 10 minutes. However updates to search.maven.org can take up to two hours.


text:
Q: pyenv install -l does not show the version I need to install For a project I need Python version 3.6.8 and I used pyenv install -l
 to list all the version available to install but could not find it.
After I tried several times including: use brew upgrade pyenv,  tried uninstall  pyenv,  tried brew update brew upgrade and then update pyenv, still no luck to find the version I need.
Any suggestion?
Thanks.

A: After many searches, found answer here:
Why is python 3.6.1. not available in pyenv?
pyenv update did the trick.

A:
See all available versions with `pyenv install --list'.
If the version you need is missing, try upgrading pyenv:

cd ~/.pyenv/plugins/python-build/../.. && git pull && cd -

A: I have tried multiple things after going from one SO page to another. The only thing that worked for me was upgrading pyenv. However, pyenv update did not resolve the issue as I installed pyenv on my Mac via Homebrew, so I had to upgrade it via brew:
brew upgrade pyenv

So I think the answer is: you have to upgrade pyenv but, how you have to upgrade it depends on how you installed it.
If you installed it via https://github.com/pyenv/pyenv-installer then yes - pyenv update is going to work for you


text:
Q: Create indeterminate JProgressBar Popup/modal dialog How can I create a popup window/modal dialog with an indeterminate progressbar running ?
I can´t even manage to create a indeterminate progressbar that isn´t running all the time in a simple window...
Thats the best result I´ve got so far:
JProgressBar progressBar = new JProgressBar();
panel_3.add(progressBar);

A: To such a vague question I can only give some guidelines as an answer.
The JProgressBar has a method setIndeterminate(Boolean);, which you can use.
Now the bigger problem you face with progressbars is that to be able to see the progress animation the long-running operation that is done while progressbar is shown must be run in a non-gui thread. I will have to refer you to read about Concurrency in Swing.
The basic steps for the modal dialog with a progressbar are

*

*Create a JDialog

*Set it modal (read the JDialog API)

*Give it a Layout

*Insert the progressbar as is, or inside for example a JPanel that has a suitable Layout. Here are your options.

*Launch your long-running task in a new thread with a SwingWorker or something else


text:
Q: Convert from ZPL code to IPL code In my application I have some Zebra printer's and Intermec printer's (PD41). The code is in ZPL language, so my Zebra printer's is working, but my Intermec printer's dont. I need to write this code in IPL language to my Intermec understand the command.
Please, anyone help me!

A: The two languages are fundamentally different. You will probably end up having to rewrite the label manually if you truly need it in IPL -- there's no easy way to translate between them automatically, per se.
However, many Intermec printers have a feature called ZSim which allows you to print ZPL from your Intermec printer. I'm not sure if the PD41 supports this, but it's something to check out.


text:
Q: How to count the number of event based on JSON field structure in Splunk I want to count the number of occurrence of a specific JSON structure. For example in my event there is a field called data which its value is JSON . but this field can have a variety of structures. like:
data = {a: "b"}
data= {d: "x", h: "e"}
...

now I want to know how many event has data with each JSON structure and I don't care about values only keys are matter.

A: Try one of these 2:
index=ndx sourcetype=srctp data=*
| stats dc(data) as unique_data

Or
index=ndx sourcetype=srctp data=*
| stats values(data) as data_vals


text:
Q: How to put self.navigationItem.titleView with title after replace it with searchbar in swift I have searchbar , when click image, it will create searchbar at top navigation , replace with title. Then when tap outside searchbar , the title don't show again , it still with searchbar (textfield), how to show again title if tap or click outside from searchbar ?
this is code to create searchBar at top navigation , replace with title.
func createSearchBar(){
    searchBar.sizeToFit()
    searchBar.showsCancelButton = false
    searchBar.placeholder = "Enter key"
    searchBar.delegate = self
    self.navigationItem.titleView = searchBar
}

This is code when tap outside searchbar
extension ViewCon {
func hideKeyboardWhenTappedAround() {
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewCon.dismissKeyboard))
    view.addGestureRecognizer(tap)
}

func dismissKeyboard() {
    self.searchBar.resignFirstResponder()
 self.navigationController?.navigationBar.topItem?.title="Title List"
}

}
But how i want show title on top navigation again ?

A: you need to set the to nil
self.navigationItem.titleView = nil

see: https://developer.apple.com/reference/uikit/uinavigationitem/1624935-titleview


text:
Q: how to separate name and add according to it? Table called Product and columns are ID, Pname, Profit, Loss, Month. Total
first six month Total=Sum(Profit)-Sum(Loss), in one column called Col1 and last six month Total=Sum(Profit)-Sum(Loss) in one column called Col2 separated by their Pname.
Sample Input:
ID  PName  Month  Profit  Loss
--  -----  -----  ------  ----
1   A      JAN    5       2
2   B      FEB    4       2
3   A      MAR    10      3
4   B      Nov    5       2

Expected Output
PName  Col1  col2
-----  ----  ----
A      10    0
B      2     3

What will be the way to do this in SQL Server?

A: This seems to do the job:
declare @t table (ID int not null,PName char(1) not null,Month char(3) not null,
                  Profit int not null,Loss int not null)
insert into @t(ID,PName,Month,Profit,Loss) values
(1,'A','JAN',5,2),
(2,'B','FEB',4,2),
(3,'A','MAR',10,3),
(4,'B','Nov',5,2)

;With Halves as (
    select PName,
        CASE WHEN Month in ('Jan','Feb','Mar','Apr','May','Jun') THEN 1
            ELSE 2 END as Half,
        Profit - Loss as Net
    from @t
)
select PName,
    COALESCE([1],0) as Col1,
    COALESCE([2],0) as Col2
from Halves pivot (SUM(Net) for Half in ([1],[2])) p

I'd usually recommend against having a column called Month (since it's a keyword) and would more normally expect it to be e.g. a date column fixed on the 1st of the appropriate month (and either have a relevant year or be for a fixed year also)
I've taken one simplifying step that SUM(Profit) - SUM(Loss) is the same as SUM(Profit - Loss)


text:
Q: Telerik's RadGridView + WCF Data Services + Entity Framework = Terrible performance We have a simple LOB application that:

*

*pulls data from EF

*serves data across the wire with WCF Data Services

*renders that data on Telerik's RadGridView
This works really well in the default scenario as users are able to filter data by using the built-in Telerik filter control which presents all the options they want.
The problem happens when re-constructing the query sent from WCF Data Services when the 'Contains' operator is used:

*

*WCF Data Services adds a bunch of "IIF" lambda expressions which,

*EF then expands into T-SQL CASE statements

This takes a query that should look like:
SELECT TOP (25)
[Project1].[TaskID] AS [TaskID],
[Project1].[ProductSubmissionID] AS [ProductSubmissionID],
...
FROM ( SELECT
    [Extent1].[TaskID] AS [TaskID],
    [Extent1].[ProductSubmissionID] AS [ProductSubmissionID],
    ...
FROM     [dbo].[Task] AS [Extent1]
    LEFT OUTER JOIN [dbo].[OperationDataProduct] AS [Extent2] ON [Extent1].[ProductID] = [Extent2].[ProductID]
    LEFT OUTER JOIN [dbo].[vProductOwnership] AS [Extent3] ON [Extent1].[ProductID] = [Extent3].[ProductID]
    LEFT OUTER JOIN [dbo].[User] AS [Extent4] ON [Extent2].[ChannelManagerID] = [Extent4].[UserID]
    LEFT OUTER JOIN [dbo].[User] AS [Extent5] ON [Extent2].[ProductOwnerID] = [Extent5].[UserID]
    WHERE [Extent1].Type IN ('Content','Concept','Financial') AND [Extent1].MarketplaceName LIKE '%prod%'

Into one that looks like this:
SELECT TOP (25)
[Project1].[TaskID] AS [TaskID],
[Project1].[ProductSubmissionID] AS [ProductSubmissionID],
...
FROM ( SELECT
    [Extent1].[TaskID] AS [TaskID],
    [Extent1].[ProductSubmissionID] AS [ProductSubmissionID],
    ...
FROM     [dbo].[Task] AS [Extent1]
    LEFT OUTER JOIN [dbo].[OperationDataProduct] AS [Extent2] ON [Extent1].[ProductID] = [Extent2].[ProductID]
    LEFT OUTER JOIN [dbo].[vProductOwnership] AS [Extent3] ON [Extent1].[ProductID] = [Extent3].[ProductID]
    LEFT OUTER JOIN [dbo].[User] AS [Extent4] ON [Extent2].[ChannelManagerID] = [Extent4].[UserID]
    LEFT OUTER JOIN [dbo].[User] AS [Extent5] ON [Extent2].[ProductOwnerID] = [Extent5].[UserID]
    WHERE (CASE WHEN (CASE WHEN (((CASE WHEN (CASE WHEN ([Extent1].[MarketplaceName] IS NULL) THEN CAST(NULL AS varchar(1)) ELSE LOWER([Extent1].[MarketplaceName]) END IS NULL) THEN CAST(NULL AS bit) WHEN (CASE WHEN ([Extent1].[MarketplaceName] IS NULL) THEN CAST(NULL AS varchar(1)) ELSE LOWER([Extent1].[MarketplaceName]) END LIKE N'%prod%') THEN cast(1 as bit) WHEN ( NOT (CASE WHEN ([Extent1].[MarketplaceName] IS NULL) THEN CAST(NULL AS varchar(1)) ELSE LOWER([Extent1].[MarketplaceName]) END LIKE N'%prod%')) THEN cast(0 as bit) END) = 1) AND ([Extent1].[SubmissionOrTaskType] IN (N'Content',N'Concept',N'Financial'))) THEN cast(1 as bit) WHEN ( NOT (((CASE WHEN (CASE WHEN ([Extent1].[MarketplaceName] IS NULL) THEN CAST(NULL AS varchar(1)) ELSE LOWER([Extent1].[MarketplaceName]) END IS NULL) THEN CAST(NULL AS bit) WHEN (CASE WHEN ([Extent1].[MarketplaceName] IS NULL) THEN CAST(NULL AS varchar(1)) ELSE LOWER([Extent1].[MarketplaceName]) END LIKE N'%prod%') THEN cast(1 as bit) WHEN ( NOT (CASE WHEN ([Extent1].[MarketplaceName] IS NULL) THEN CAST(NULL AS varchar(1)) ELSE LOWER([Extent1].[MarketplaceName]) END LIKE N'%prod%')) THEN cast(0 as bit) END) = 1) AND ([Extent1].[SubmissionOrTaskType] IN (N'Content',N'Concept',N'Financial')))) THEN cast(0 as bit) END IS NULL) THEN cast(0 as bit) WHEN (((CASE WHEN (CASE WHEN ([Extent1].[MarketplaceName] IS NULL) THEN CAST(NULL AS varchar(1)) ELSE LOWER([Extent1].[MarketplaceName]) END IS NULL) THEN CAST(NULL AS bit) WHEN (CASE WHEN ([Extent1].[MarketplaceName] IS NULL) THEN CAST(NULL AS varchar(1)) ELSE LOWER([Extent1].[MarketplaceName]) END LIKE N'%prod%') THEN cast(1 as bit) WHEN ( NOT (CASE WHEN ([Extent1].[MarketplaceName] IS NULL) THEN CAST(NULL AS varchar(1)) ELSE LOWER([Extent1].[MarketplaceName]) END LIKE N'%prod%')) THEN cast(0 as bit) END) = 1) AND ([Extent1].[SubmissionOrTaskType] IN (N'Content',N'Concept',N'Financial'))) THEN cast(1 as bit) WHEN ( NOT (((CASE WHEN (CASE WHEN ([Extent1].[MarketplaceName] IS NULL) THEN CAST(NULL AS varchar(1)) ELSE LOWER([Extent1].[MarketplaceName]) END IS NULL) THEN CAST(NULL AS bit) WHEN (CASE WHEN ([Extent1].[MarketplaceName] IS NULL) THEN CAST(NULL AS varchar(1)) ELSE LOWER([Extent1].[MarketplaceName]) END LIKE N'%prod%') THEN cast(1 as bit) WHEN ( NOT (CASE WHEN ([Extent1].[MarketplaceName] IS NULL) THEN CAST(NULL AS varchar(1)) ELSE LOWER([Extent1].[MarketplaceName]) END LIKE N'%prod%')) THEN cast(0 as bit) END) = 1) AND ([Extent1].[SubmissionOrTaskType] IN (N'Content',N'Concept',N'Financial')))) THEN cast(0 as bit) END) = 1
)  AS [Project1]
ORDER BY [Project1].[TaskID] ASC

My question is: has anyone bumped into this problem before and is there a low cost solution?
I can see re-writing the EF QueryProvider to be a solution, but it's not exactly low cost.
TIA

A: We wound up writing a QueryProvider to fix this issue.  It wound up being lower cost than originally expected, but still adds quiet a bit of unnecessary complexity.  The IQToolkit has some decent examples of how to begin this.


text:
Q: Delete every week all files except some folders (but not the files into these) I'm using this bash script to delete all files and folders located in a directory every week except three folders and the files contained into these.
But how can I now modify the script so that only these three foldres remain but not the files contained?
These 3 folders are necessary to a workflow but not the files contained (after 7 days).
find /Path/Folder/* -type d -mtime +7 ! -path "/Path/Folder/NODELETE1"  ! -path "/Path/Folder/NODELETE2"  ! -path "/Path/Folder/NODELETE3" -exec rm -rf {} \;

What I want is
Before
Path/NODELETE1/files
Path/NODELETE2/files
Path/NODELETE3/files
Path/FOLDERS
Path/files

After
Path/NODELETE1
Path/NODELETE2
Path/NODELETE3

EDIT:
find /path/Folder/* -and -not -path "/path/Folder/DELEGATE*" -mtime +7 ! -regextype posix-egrep ! -regex ".*/path/Folder/(DOCUMENTS|WORK|PENDING)$" -delete

A: well, first of all you don't need anymore the -type d if you want to delete files. you can use regex with find to deal with this case; a regex that matches everything that doesn't end with NODELETE[1-3]:
find path/folder/* -regextype posix-egrep ! -regex ".*path/folder/NODELETE[1-3]$"

this will match, for example:
$ find path/folder/* -regextype posix-egrep ! -regex ".*path/folder/NODELETE[1-3]$"
path/folder/asd
path/folder/asd/will_delete
path/folder/bleeegh
path/folder/NODELETE1/eraseme
path/folder/NODELETE2/a_folder
path/folder/NODELETE2/a_folder/delete_me

also, instead of -exec rm -rf {} you can use -delete:
$ find path/folder/* -regextype posix-egrep ! -regex ".*path/folder/NODELETE[1-3]$" -delete
$ tree
.
└── path
    └── folder
        ├── NODELETE1
        ├── NODELETE2
        └── NODELETE3

5 directories, 0 files

so, the folders remain, other folder and files are gone, and the files and folders inside NODELETE[1-3] are also gone.
don't forget to add -mtime +7! (i obviated it because it's not necessary to demonstrate the case)

if you want to keep other folders you can use an OR in the regex which won't delete the folders but will delete files inside them:
find path/folder/* -regextype posix-egrep ! -regex ".*path/folder/(NODELETE[1-3]|DOCUMENTS|WORK|DELEGATE)$" -delete

and if you want to keep the files of some folder you can specify another filter for find:
find [...] -and -not -path "path/folder/DOCUMENTS*"

notice that the * at the end will match not only the folder itself but all files inside it.


text:
Q: SP 13 Unable to open PDF in Chrome I have a SharePoint 13 site that has PDF documents. In Chrome, I want to be able to click the link for the document and it open in Chrome. Currently, the link is unclickable in every single browser besides IE. How can this be possible? It's just an a tag.
Is there a site setting I need to select to enable use of links to documents in other browsers?
Any help would be much appreciated.

A: you can try to donwloand and install the IE tab for Chrome
https://chrome.google.com/webstore/detail/ie-tab/hehijbfgiekmjfkfjpbkbammjbdenadd?hl=en


text:
Q: How to use public or internal class in JavaScript in Asp.Net? I'm working on asp.net web application. I want to use a class in javascript.
in asps.cs file we can easily use this like
ABC obj = new ABC();
obj.name = "John";

Can I use class in same manner in javascript?
If Yes then please tell me How to use public or internal class of same solution in JavaScript Code?

A: JavaScript doesn't really have classes in the classic sense. There are several workarounds available. A short overview:

*

*Using a function

*Using object literals

*Singleton using a function

Note there won't really be a way of doing scope modifiers (public/internal/private etc).
You might look into TypeScript and CoffeeScript both compile down to JavaScript, and supports classes. @asawyer pointed out the CoffeeScript idea.
It's worth noting that ECMAScript 6 standard will include support for classes, however the specifications are still a work in progress.

A: Javascript does have prototype support that can be used as classes as you know from the C# world.
// define a constructor of a class called "ABC"
function ABC() {
    this.name = null;
}

// create an instance of a class
var obj = new ABC();

// check instance property value
console.log(obj.name); // outputs "null"

// set instance property value
obj.name = "something";

// some more checks
console.log(obj.name); // outputs "something"
console.log(obj); // outputs whole object

And about public and internal/private classes they may be simulated within function scope (as Javascript only has function scope where C# has block scope as well).
Developers usually put their client logic inside a function, so they create a private scope and avoid any public name clashing or visibility of internal functionality. These scopes can then publicise whathever is required for the general public scope.
Any widely used client library is a great example of such pattern. jQuery or maybe even better AngularJS. It has a lot of internal business logic but just a handful of publically accessible functionality (variable angular being the main one).


text:
Q: How to check if column is string How to check in hive whether the column is holding string character. My column is string datatype and has values like below
my_col string
000001234
0001111

A: One way to check, whether string character is present is following:
SELECT
my_col,
CASE WHEN HEX(LOWER(my_col)) <> HEX(UPPER(my_col)) then 'char present' else 'no char' END char_check
FROM my_table;

We convert value to lower case and upper case and cast it to hexadecimal.
HEX('1a') produces 3161
HEX('1A') produces 3141
And that's how we know that a character is present which can be converted to upper or lower case.
It's a quick workaround, otherwise I would create UDF with Java.


text:
Q: Install update in android app from my website I am currently checking the application version in background every 24 hours once in my web server not in android market. If update available that it prompt the user to download the new apk.
Uri uri = Uri.parse(downloadURL);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);

The above code open the user browser and start downloading.
I want without opening the browser i need to download the apk file or i need to install the latest apk directly without opening and other application (like browser)

A: Do something like this
// First you need to download apk file.
    String extStorageDirectory =        Environment.getExternalStorageDirectory().toString();
        File folder = new File(extStorageDirectory, "APPS");
        folder.mkdir();
        File file = new File(folder, "AnyName."+"apk");
        try {
                file.createNewFile();
        } catch (IOException e1) {
                e1.printStackTrace();
        }
        /**
         * APKURL is your apk file url(server url)
         */
         DownloadFile("APKURL", file);

// the DownloadFile function is
      public  void DownloadFile(String fileURL, File directory) {
       try {

            FileOutputStream f = new FileOutputStream(directory);
            URL u = new URL(fileURL);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            //c.setDoOutput(true);
            c.connect();
            InputStream in = c.getInputStream();
            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = in.read(buffer)) > 0) {
                    f.write(buffer, 0, len1);
            }
            f.close();
    } catch (Exception e) {
        System.out.println("exception in DownloadFile: --------"+e.toString());
            e.printStackTrace();
    }

and after downloading the apk file write this code
       Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new   File(Environment.getExternalStorageDirectory() + "/APPS/" + "AnyName.apk")), "application/vnd.android.package-archive");
            startActivity(intent);

// and give permission in manifest
     <uses-permission android:name="android.permission.INTERNET"/>
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

it might help you, i used this for same as your need.


text:
Q: Sound synthesis with C# Is there some possibility to generate sounds in C#? I mean not just beep or open and play wave-file. I mean build the signal using different kinds of waves (sin, saw, etc.) and their options (frequencies, amplitudes, etc.)

A: Here's a blog post I wrote about how to create a sine wave with NAudio. Obviously that's just a first step to making a full blown synthesizer as you will also want to create other waveforms, ADSR envelopes, filters etc, but it should at least get you started.

A: Check out NAudio on GitHub.

NAudio is an open source .NET audio and MIDI library, containing dozens of useful audio related classes intended to speed development of audio related utilities in .NET. It has been in development since 2001 and has grown to include a wide variety of features. While some parts of the library are relatively new and incomplete, the more mature features have undergone extensive testing and can be quickly used to add audio capabilities to an existing .NET application.

You could either use the library directly, or check out its source code to find out how it works at a low level.

A: I highly recommend that you look at the platform VST .Net. This would allow you to create your own VSTs in .Net. If you want to do synthesis, you will probably find that is easier to create a VST and host it in your DAW of choice rather than create a once off app. This is because if you create a VST, you don't have to worry about dealing with the audio interface drivers or ASIO etc.
https://vstnet.codeplex.com/
Also, you'll also need a set of controls for the user interface. The standard Windows Forms, or WPF controls might do the trick, but synth enthusiasts usually like to see nicely skinned controls. I recently released these controls which behave like normal WPF controls, but are designed for synthesis:
https://bitbucket.org/MelbourneDeveloper/vst-controls-.net/

A: You can use FLooping. It is a library written in F#, providing common building blocks for audio synthesis like oscillators, envelopes, filters, etc. It is currently in an experimental state.
Disclosure: I am the developer of FLooping.


text:
Q: ggplot won't display in R shiny I am trying to develop my first r shiny dashboard. I am facing problem with displaying ggplot. When I am running ggplot code separately in rmd it is working. But when I am trying to run in r shiny the plot is not getting displayed. I have tried to implement in few different ways but still there is no success. Any help much appreciated.
Image
[![enter image description here][1]][1]
  [1]: https://i.stack.imgur.com/C3S5f.png

Full code below:
options(encoding = 'UTF-8')

library(shiny)
library(tidyverse)
library(elo)
library(plotly)
library(shinydashboard)
library(DT)

shinyUI(fluidPage(
    headerPanel(title = "Project 1"),
    sidebarLayout(
        sidebarPanel(
            selectInput("Jahr", "Select Year", c("Year" = "Jahr", "Date" = "Datum", "Datebase" = "Datenbank"))
            ),

    mainPanel(
        tabsetPanel(type = "tab",
                    tabPanel("Data", DT::dataTableOutput("df1_omit")),
                    tabPanel("Summary", verbatimTextOutput("summ")),
                    tabPanel("Plot", plotOutput("Plot"))
        ))
)))

options(encoding = 'UTF-8')

library(shiny)
library(datasets)
library (ggplot2)
library(DT)

shinyServer(function(input, output){
    # Return the formula text for printing as a Patienten Daten
    output$df1_omit <- DT::renderDataTable({

        df1_omit

    })
    output$summ <- renderPrint({
        summary(df1_omit)
    })

    output$plot <- renderPlot({
        Jahr_fr <- df1_omit %>% group_by(Jahr) %>% summarise(Freq=n())

        g <- ggplot(Jahr_fr, aes(x = Jahr, y = Freq))
        g <- g + geom_bar(stat = "sum")
        plot(g)
    })

})

A: Try this. Your output name for renderPlot were wrong in tabsetPanel.
options(encoding = 'UTF-8')

library(shiny)
library(tidyverse)
library(elo)
library(plotly)
library(shinydashboard)
library(DT)

df1_omit <- iris

ui <- shinyUI(fluidPage(
  headerPanel(title = "Project 1"),
  sidebarLayout(
    sidebarPanel(
      selectInput("Jahr", "Select Year", c("Year" = "Jahr", "Date" = "Datum", "Datebase" = "Datenbank"))
    ),

    mainPanel(
      tabsetPanel(type = "tab",
                  tabPanel("Data", DT::dataTableOutput("df1_omit")),
                  tabPanel("Summary", verbatimTextOutput("summ")),
                  tabPanel("Plot", plotOutput("plot")) #wrong output name, correct is plot
      ))
  )))

server <- shinyServer(function(input, output){

  output$df1_omit <- DT::renderDataTable({

    df1_omit

  })
  output$summ <- renderPrint({
    summary(df1_omit)
  })

# out put name here is plot not Plot
  output$plot <- renderPlot({
    Jahr_fr <- df1_omit %>% group_by(Species) %>% summarise(Freq=n())

    g <- ggplot(Jahr_fr, aes(x = Species, y = Freq))
    g <- g + geom_bar(stat = "sum")
    g
  })

})

shinyApp(ui= ui, server = server)