text:
Q: Unable to query proxy "Automatically Detect Settings" on windows 7 I am trying to capture proxy setting ("Automatically Detect Settings"). My code works on XP and Vista.
But it is NOT working on Windows 7
Please see the details of target platform
Windows 7 Enterprise, IE 8.0.7600.16385, Wininet.dll 8.0.7600.16535
Please see the code snippet
INTERNET_PER_CONN_OPTION_LIST List;
INTERNET_PER_CONN_OPTION Option[1];

unsigned long nSize = sizeof(INTERNET_PER_CONN_OPTION_LIST);
Option[0].dwOption = INTERNET_PER_CONN_FLAGS;
List.dwSize = sizeof(INTERNET_PER_CONN_OPTION_LIST);
List.pszConnection = NULL;
List.dwOptionCount = 1;
List.dwOptionError = 0;
List.pOptions = Option;

if(!InternetQueryOption(NULL, INTERNET_OPTION_PER_CONNECTION_OPTION, &List, &nSize))
    AfxMessageBox(L"InternetQueryOption failed! (%d)\n");

TCHAR a[100];
swprintf(a, L"Flag value is : %d",Option[0].Value.dwValue, 80);
AfxMessageBox(a);

But on Windows 7, even if "Automatically Detect Settings" option in IE is checked, the program says that that flag is not set
I tried with WinHttp api also as shown below.
WINHTTP_CURRENT_USER_IE_PROXY_CONFIG stProxyConfig = {0};

WinHttpGetIEProxyConfigForCurrentUser(&stProxyConfig);

if (stProxyConfig.fAutoDetect == TRUE)
    AfxMessageBox(L"Auto proxy detection enabled");
else
    AfxMessageBox(L"Auto proxy detection disabled");

On Windows 7, above code also fails to capture the "Automatically Detect Settings" option.
Any input on this is highly appreciated.
Thanks
John

A: This is a new performance-optimizing feature introduced in IE8 called SmartWPAD.
WinINET keeps track of whether a given network has a WPAD server (e.g. what the Automatically Detect feature is used to look for). If the network does not have a WPAD server, then WinINET effectively "masks out" the "Use autodetect" bit when you do the InternetQueryOption so that your code doesn't waste a ton of time doing a proxy lookup that will return no proxy on this network.
If you MUST get the UI state (defeating the WinINET SWPAD feature) because, for instance, you plan to take this information and cache it for use on some other network, or something similar, then you must query for INTERNET_PER_CONN_FLAGS_UI first-- when you use this option, you will get back the UI state, independent of the SWPAD feature.
If this query fails, then the system is running a previous version of Internet Explorer and the client should query again with INTERNET_PER_CONN_FLAGS.

A: I have a C# code snippet where you can Check/Uncheck 'Automatically detect settings' check box of IE Connection Settings.  You can find what you are looking for in this snippet.
    public bool IsIEAutoDetectProxy(bool set)
    {
        // Setting Proxy information for IE Settings.
        RegistryKey RegKey = Registry.CurrentUser.OpenSubKey(@"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Connections", true);
        byte[] defConnection = (byte[])RegKey.GetValue("DefaultConnectionSettings");
        if (defConnection[8] == Convert.ToByte(9))
           return true;
        else
           return false;
    }


text:
Q: CQRS and events order I'm learning cqrs right now.
Problem
My concern is event ordering.
Assumption 1: user service is creating user and three events in order.
Each event was sent after each step was finished in write model.

*

*Event A: user ABC created

*Event B: changed email for user ABC to abc@mail

*Event C: change email for user ABC to abc2@mail

Assumption 2: I have 3 instances of same microservice read app that will handle this events.
Without ordering email can be changed before account was created
or even worse eventB can override eventC email value.
I found two things: vector clock and consuming history not event.
vector clock --> forces me to create complicated logic to handle that
and will decrease performance
consuming history not event --> not solve the problem. Consumer 1 can take
100 events ...-B but consumer 2 will take events C-... and still will try to
override email in non existing account.
Question:
What are best practices to handle this case?

A: This shouldn't come as a surprise to you, but complicated architectural patterns like CQRS and distributed systems aren't free. It is more effort to build a first version when using more complicated patterns than it is just to throw everything into a monolith and process everything sequentially - but it gives advantages in the longer term (in theory anyway. Quite possibly you ain't gonna need it).
If it is an issue for you that the solutions need you "to create complicated logic" then don't use this kind of solution.

A: I think you are confusing  CQRS and Event Sourcing.
in CQRS, you achieve distribution for your reads, but the writes all goto the same DB. Thus you can use transactions and other standard practices to keep the ordering of changes as they are all commands.
Event Sourcing usually requires as you say a vector clock, or simplified version of such, as the events are not processed in strictly chronological order or by the same machines.
However, some events are just going to clash and you will be forced to have a reject mechanism. ie. in your example even if you say C should be the last event due to chronological ordering, if both users have been presented with state A prior to making their change then both events have the same ancestral ordering and really one should be rejected. "Sorry your version of the record is out of date, please redo with the latest version"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Shopify - regular price not showing next to sale price if I put a product on sale, on the collections page, there is the crossed out normal price next to the sale price. However, on the product page, the sale price is only shown as if it would be the normal price and the regular price is just loaded for 1 second when you open the product page, and then dissapears. Can someone help please?

    {% if product.compare_at_price > product.price %}
      {{ 'products.product.sale_price' | t }}
    {% else %}
      {{ 'products.product.regular_price' | t }}
    {% endif %}

      {{ product.price | money }}

    {% if product.compare_at_price > product.price %}
      {{ 'products.product.regular_price' | t }}
      <s id="ComparePrice" class="product-single__sale-price">
        {{ product.compare_at_price_max | money }}
      </s>
    {% endif %}


text:
Q: Ошибка при преобразовании строки в массив jquery Есть код:
 <form id="myForm" method="post">

<textarea id=f13 name="field1"></textarea>

<input type="submit" value="Отправить">

  </form>

111

555

$(document).ready(function(){
 $('#myForm').submit(function(){

var str = $(this).serialize();
var str2 = $('#f13').val();
str2.split('\n');

srt2.forEach(function(item, i, srt2) { $('.result').html(item); });

$.ajax({
                type: "POST",
                url: "test.php",
                data: str,
                success:
                function(html){
         $("#content").html(html);
               }
            });
            return false;
        });

    });

И тут ошибка...
Необходимо, чтобы произошло создание массива, разделителем при котором будет новая строка, а далее выведен результат по очереди.

A:

var result = $('#result');
$('#f13').keypress(function(e) { //Будем реагировать на ввод новой строки
    var code = (e.keyCode ? e.keyCode : e.which);
    if(code == 13) {
        var text = $(this).val();
        var items = text.split('\n').map(function(item) { //Создаём массив, содержащий div для каждого строки
            return $('
' + item + '
');
        });
        result.html(items); //Заменяем содержимое #result
    }
});

<textarea id="f13"></textarea>


text:
Q: Last vs last for with time In the Moscow aeroexpress train to Domodedovo airport I heard an announcement, "The trip will last for 45 minutes" and I wonder if for is optional in announcements. Is it said the same way in London for instance? Is it a formal way?
I know we can say, "The trip will last 45 minutes". Is it any different from last for?

A: I tend to favour no "for", since last takes a timespan as a direct object, much like take does:

The trip will last 45 minutes.
A rose lasts only a little while.
A journey to Mars on the new shuttle would still take years.

However, you do hear last for X amount of time now and again, and it shows up in books, sometimes with more frequency and sometimes with less.
This usage with for is probably because last is also an intransitive verb. Any verb can have its duration specified in that way:

He played golf for five days straight.
She will go camping for three months.

Here, the amount of time is not objective, but adverbial.
(This would also explain why you can't say "It takes for an X amount of time": unlike last,  take has no intransitive variant.)


text:
Q: Counting from sqlite database cause error I'm trying to pass an int array from the MainActivity to the databaseadapter to run a count from the sqlite database. I got the code as follow without any errors from eclipse, but once it runs, it crashes.
Code as follows
for Mainactivity
            int one = 1;
            int  five = 5;

            int[] apple = {one, five};
            int numr = (int) myDb.getCount(apple);

            TextView textv = (TextView) findViewById(R.id.wds);
                   textv.setText("There are" + numr + "of entries");

For Databaseadapter, Datab,
        public int getCount(int[] apple) {
        int fir = apple[1];
        int sec = apple[2];

    int fin = (int) DatabaseUtils.longForQuery(db, "SELECT COUNT(*)
             FROM TABLE_NAME where  length >= " +fir + "and width >="
             + sec, null);
             return nfin;

And the logcat as follows
06-10 15:44:05.817: E/AndroidRuntime(1737): FATAL EXCEPTION: main
06-10 15:44:05.817: E/AndroidRuntime(1737): java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
06-10 15:44:05.817: E/AndroidRuntime(1737):     at com.example.pro.Datab.getCount(Datab.java:110)
06-10 15:44:05.817: E/AndroidRuntime(1737):     at com.example.pro.MainActivity.onItemSelected(Qus.java:237)
06-10 15:44:05.817: E/AndroidRuntime(1737):     at android.widget.AdapterView.fireOnSelected(AdapterView.java:892)
06-10 15:44:05.817: E/AndroidRuntime(1737):     at android.widget.AdapterView.access$200(AdapterView.java:49)
06-10 15:44:05.817: E/AndroidRuntime(1737):     at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:860)

As you probably can guess, I'm very new to Android/Java so I would appreciate any help I can get. Thanks in advance.

A: Apart that arrays start from 0, so your indexes should be:
int fir = apple[0];
int sec = apple[1];

Assuming that your table name is "TABLE_NAME", add a space before "and width..., so to read " and width....
Or the query can't be executed
It actually would result in something (not working) like:
SELECT COUNT(*)FROM TABLE_NAME where  length >= 10and width >=20

while it should be something (working) like:
SELECT COUNT(*) FROM TABLE_NAME where length >= 10 and width >= 20

A: Array indexes start from 0, but you've used index 1 and 2 from apple.  Index 2 is out of bounds, as noted in the error log:

java.lang.ArrayIndexOutOfBoundsException: length=2; index=2 06-10

Your error has nothing to do with the SQL.


text:
Q: error in building chat screen in flutter using firebase greeting to all,
I am learning to make chat in flutter app using firebase, and I got a code to understand it's working but it is showing errors and I am not able to understand the code well.
below is the screen that is showing error -:
import 'dart:async';
import 'dart:io';
import 'dart:core';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chat_app/widget/ChatMessageListItem.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:image_picker/image_picker.dart';

final googleSignIn = new GoogleSignIn();
final analytics = new FirebaseAnalytics();
final auth = FirebaseAuth.instance;
var currentUserEmail;
var _scaffoldContext;

class ChatScreen extends StatefulWidget {
  @override
  ChatScreenState createState() {
    return new ChatScreenState();
  }
}

class ChatScreenState extends State<ChatScreen> {

  final TextEditingController _textEditingController =
      new TextEditingController();
  bool _isComposingMessage = false;
  final reference = FirebaseDatabase.instance.reference().child('messages');

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text("Flutter Chat App"),
          elevation:
              Theme.of(context).platform == TargetPlatform.iOS ? 0.0 : 4.0,
          actions: <Widget>[
            new IconButton(
                icon: new Icon(Icons.exit_to_app), onPressed: _signOut)
          ],
        ),
        body: new Container(
          child: new Column(
            children: <Widget>[
              new Flexible(
                child: new FirebaseAnimatedList(
                  query: reference,
                  padding: const EdgeInsets.all(8.0),
                  reverse: true,
                  sort: (a, b) => b.key.compareTo(a.key),
                  //comparing timestamp of messages to check which one would appear first
// this itembuilder is showing error
                  itemBuilder: (_,DataSnapshot messageSnapshot, Animation<double> animation){
                    return new ChatMessageListItem(
                      messageSnapshot: messageSnapshot,
                      animation: animation,
                    );
                  },

                ),
              ),

              new Divider(height: 1.0),

              new Container(
                decoration:
                    new BoxDecoration(color: Theme.of(context).cardColor),
                child: _buildTextComposer(),
              ),
              new Builder(builder: (BuildContext context) {
                _scaffoldContext = context;
                return new Container(width: 0.0, height: 0.0);
              }),
            ],
          ),
          decoration: Theme.of(context).platform == TargetPlatform.iOS
              ? new BoxDecoration(
                  border: new Border(
                      top: new BorderSide(
                  color: Colors.grey[200],
                )))
              : null,
        ),
    );
  }

  CupertinoButton getIOSSendButton() {
    return new CupertinoButton(
      child: new Text("Send"),
      onPressed: _isComposingMessage
          ? () => _textMessageSubmitted(_textEditingController.text)
          : null,
    );
  }

  IconButton getDefaultSendButton() {
    return new IconButton(
      icon: new Icon(Icons.send),
      onPressed: _isComposingMessage
          ? () => _textMessageSubmitted(_textEditingController.text)
          : null,
    );
  }

  Widget _buildTextComposer() {
    return new IconTheme(
        data: new IconThemeData(
          color: _isComposingMessage
              ? Theme.of(context).accentColor
              : Theme.of(context).disabledColor,
        ),
        child: new Container(
          margin: const EdgeInsets.symmetric(horizontal: 8.0),
          child: new Row(
            children: <Widget>[
              new Container(
                margin: new EdgeInsets.symmetric(horizontal: 4.0),
                child: new IconButton(
                    icon: new Icon(
                      Icons.photo_camera,
                      color: Theme.of(context).accentColor,
                    ),
                    onPressed: () async {
                      await _ensureLoggedIn();
                      File imageFile = await ImagePicker.pickImage();
                      int timestamp = new DateTime.now().millisecondsSinceEpoch;
                      Reference storageReference = FirebaseStorage
                          .instance
                          .ref()
                          .child("img_" + timestamp.toString() + ".jpg");
                      var uploadTask =
                          storageReference.putFile(imageFile);

// this downloadUrl is also showing an error
                      Uri downloadUrl = (uploadTask.snapshotEvents).downloadUrl;
                      _sendMessage(
                          messageText: null, imageUrl: downloadUrl.toString());
                      }
                    ),
              ),
              new Flexible(
                child: new TextField(
                  controller: _textEditingController,
                  onChanged: (String messageText) {
                    setState(() {
                      _isComposingMessage = messageText.length > 0;
                    });
                  },
                  onSubmitted: _textMessageSubmitted,
                  decoration:
                      new InputDecoration.collapsed(hintText: "Send a message"),
                ),
              ),
              new Container(
                margin: const EdgeInsets.symmetric(horizontal: 4.0),
                child: Theme.of(context).platform == TargetPlatform.iOS
                    ? getIOSSendButton()
                    : getDefaultSendButton(),
              ),
            ],
          ),
        ));
  }

  Future<Null> _textMessageSubmitted(String text) async {
    _textEditingController.clear();

    setState(() {
      _isComposingMessage = false;
    });

    await _ensureLoggedIn();
    _sendMessage(messageText: text, imageUrl: null);
  }

  void _sendMessage({String messageText, String imageUrl}) {
    reference.push().set({
      'text': messageText,
      'email': googleSignIn.currentUser.email,
      'imageUrl': imageUrl,
      'senderName': googleSignIn.currentUser.displayName,
      'senderPhotoUrl': googleSignIn.currentUser.photoUrl,
    });

    analytics.logEvent(name: 'send_message');
  }

  Future<Null> _ensureLoggedIn() async {
    GoogleSignInAccount signedInUser = googleSignIn.currentUser;
    if (signedInUser == null)
      signedInUser = await googleSignIn.signInSilently();
    if (signedInUser == null) {
      await googleSignIn.signIn();
      analytics.logLogin();
    }

    currentUserEmail = googleSignIn.currentUser.email;

    if (await auth.currentUser == null) {
      GoogleSignInAuthentication credentials =
          await googleSignIn.currentUser.authentication;
// here sign in with google is also showing error.
      await auth.signInWithGoogle(
          idToken: credentials.idToken, accessToken: credentials.accessToken);
    }
  }

  Future _signOut() async {
    await auth.signOut();
    googleSignIn.signOut();
    Scaffold
        .of(_scaffoldContext)
        .showSnackBar(new SnackBar(content: new Text('User logged out')));
  }

}

i have pointed out in comments which part is showing error. please if anyone can help me out with this it would be great.
thank you.
below is the error -:

2nd error -:

3rd error -:

A: The FirebaseAnimatedList's itemBuilder function takes in 4 parameters but you only gave it 3.
The simple fix is to add another parameter, it needs to be an int.
itemBuilder: (_,DataSnapshot messageSnapshot, Animation<double> animation, int yourVariableName)
{
// Put your code here
}


text:
Q: How to make predictions with Mask R-CNN and python 3.10 My problem:
I have weights for a Mask R-CNN Model, which has been trained using python 3.7 and tensorflow 1.13.1. I can use this environment to make predictions.
I am able to reproduce those predictions using python 3.8 and loading the weights with the Mask R-CNN for tensorflow 2 and tensorflow 2.4.1.
When I use python 3.10 and tensorflow 2.9.1 the prediction process runs without any errors but the results do not make any sense. The class instances are just a view randomly distributed specks. The results look similar for python 3.8 and tensorflow 2.9.1.
Where I'm at
I need to use python 3.10, I don't care about the tensorflow version. I found requirements for an environment that should work for python 3.9 using tensorflow 2.7. But to my understanding for python 3.10 I need tensorflow 2.8 or higher.
What I need
I have no experience with tensorflow or Mask R-CNN so I don't really know where to start. Did someone already encounter this kind of problem, is it something typical and does it point into a certain direction?


text:
Q: Magnets on parallel strings Suppose you have two simple straight bar magnets,
each hanging by their north poles from the ceiling by a thread,
a distance d apart,
and let their south poles likewise be attached to the floor by two threads.
You thus have two straight bar magnets on two parallel lines a distance d apart.
They tend to repel each other with a force f in this configuration.
Now twist one thread rapidly in a positive sense and twist the other thread in a negative sense so that each magnet is spinning with its thread as its axis.
How does the force f change as a function of the speed of this twisting and why?

A: Minimally, if at all.  If the surface of the magnets was moving at the speed of sound in air, this would lead to a fractional change in the force of about one part in $10^{12}$.
A moving magnetic dipole $\vec{m}$ moving perpendicular to its axis will acquire an electric dipole moment given by $\vec{v}\times \vec{m}/c^2$.  Since the two magnets are counter-rotating, this will lead to them acquiring equal and opposite electric dipole moments in the laboratory frame;  these electric dipole moments will be given by $\vec{p} = \pm \alpha v \vec{m} /c^2$, where $v$ is the greatest linear speed of the magnets (at its surface) and $0< \alpha < 1$ is a geometric factor related to the fact that not all the points in the magnets will be moving at the same speed.
The magnetic moment of a moving dipole, meanwhile, is multiplied by $\gamma$.  So the magnetic force will change by something like $(\beta v)^2$, where $0< \beta < 1$ is another dimensionless factor depending on the geometry.
So to lowest relativistic order, the force between the magnets will become
$$
F = \frac{\mu_0}{4 \pi r^3} \gamma^2 m^2 - \frac{1}{4 \pi \epsilon_0 r^3} p^2 = \frac{\mu_0}{4 \pi r^3} m^2 \left(\gamma^2 - \frac{\alpha^2 v^2}{c^2} \right) \approx  \frac{\mu_0}{4 \pi r^3} m^2 \left(1 + (\beta^2 - \alpha^2) \frac{v^2}{c^2} \right)
$$
where we have used the fact that $c^2 = 1/\mu_0 \epsilon_0$.
This means that overall, we would expect the force between the two magnets to change (fractionally) by a factor on the order of $v^2/c^2$.  This would be a very small number;  for example, if $v$ was the speed of sound, then $v^2/c^2 \approx 10^{-12}$.  Whether or not the force would increase or decrease depends on the relative size of the factors $\alpha$ and $\beta$, which would require a bit of effort to determine.  It is possible that these two factors would be exactly equal, in which case the force might vary by factors of $\mathcal{O}(v^4/c^4)$ instead, which would be even smaller.


text:
Q: angular change property of scope by reference from ng-init I have an input and a button, I want when the button clicked, the value of input will be changed:
<input type="text" ng-model='myModel'>
<button ng-click="changeMyModel()">my button</button>

in the controller:
$scope.changeMyModel = function () {
   $scope.myModel = 'new value';
}

It works, but when I want to pass myModel into changeMyModel() function:
<input type="text" ng-model='myModel'>
<button ng-click="changeMyModel(myModel)">my button</button>

$scope.changeMyModel = function (myModel) {
   myModel = 'new value';
}

It does not work
I really want pass a property into a function because when I use ng-repeat, each loop, the model is different, and I can not declare n var in scope for n elements of an array when loop (I have $sope.objects):

            <input type="text" ng-model='object'>
            <button ng-click="changeMyModel(object )">my button</button>

A: You should define your variable as an object, as mentioned @shaunhusain,
I made an example for you
 function($scope){
       $scope.user = {};
        $scope.user.name = 'test'
       $scope.changeMyModel = function (myModel) {
          myModel.name = 'new value';
       }
    })

and also recommendation to read

A: That is really not cool that you can't treat a string property of an as an object by adding some modifier.
You want to do.
$scope.user = "name";

$scope.setthisscopevariable = function(scopevariable) {
    scopevariable = "newname";
}
$scope.setthisscopevariable($scope.user);

But that just evaluates to var scopevariable = "newname" because it passes in the string and not a reference to the scope. And there is no way to pass it in as a reference without changing $scope.user to an object with properties that you are going to set.
So you can do
$scope.user = "name";
$scope.setthisscopevariable = function(scopevariable) {
    /* not doing anything with scopevariable by you could */
    return "newname";
}
$scope.user = $scope.setthisscopevariable($scope.user);

Which is all good in your controller for using a function with no knowledge of the object to set a value.
Which when bound to a model it could look like this.
<input type="text" ng-model='myModel'>
<button ng-click="changeMyModel('myModel')">my button</button>

$scope.changeMyModel(modelName) {
    $scope[modelName] = "newname";
};

I didn't test that but I think it should work. It allows you to pass the $scope.myModel reference in as a string so you can then access that model in the $scope with Array syntax. This is not as clean as you want because your function still has to deal with the fact that there is an object and a child object as in the other answer, but it allows you to pass in the child object as a string instead of creating creeping children. If you want to take it a step further and have the function exist outside the controller in a library, you would still need to take into account that you need to pass an object in.
<input type="text" ng-model='myModel'>
<button ng-click="changeMyModel('myModel')">my button</button>

$scope.changeMyModel(modelName) {
    changeText($scope, modelName);
};

var changeText = function(obj, property) {
    obj[property] = "newname";
}

I can't answer it in abstract coding terminology, so I thought I just try with a laymen's example. :)

A:
In ng-repeat, it's OK to modify object, you could do something like this:

   <button ng-click="removeTask(task);">{{task.name}}</button>

In controller:
var app = angular.module('app', []);

function Ctrl($scope) {
  $scope.tasks = [{id:1,'name':'test1'}, {id:2,'name':'test2'}, {id:3,'name':'test3'}];

  $scope.removeTask = function(task){
        task.name = 'abc';
  };
}

Or you could pass your item index in the list to your function


text:
Q: Prove that $\inf _{n \geq k} (a_n + b_n) \geq \inf _{n \geq k} (a_n) + \inf _{n \geq k} (b_n) (\forall k)$ I understand that
$\inf _{n \geq k}  a_n \leq a_n (\forall n \geq k)$
$\inf _{n \geq k}  b_n \leq b_n (\forall n \geq k)$
Thus
$\inf _{n \geq k}  a_n + \inf _{n \geq k}  b_n \leq a_n + b_n (\forall n \geq k)$
I'm not too sure where to go from here.

A: Fix $k$. for any $N\ge k$, it holds that
$$\inf_{n\ge k}a_n+\inf_{n\ge k}{b_n}\le a_N+b_N.$$
So $\inf_{n\ge k}a_n+\inf_{n\ge k}{b_n}$ is a lower bound of the set $\{a_N+b_N:\, N\ge k\}$. Since $\inf$ is the ``best'' lower bound, it follows that
$$\inf_{n\ge k}a_n+\inf_{n\ge k}{b_n}\le\inf_{N\ge k}(a_N+b_N).$$

A: Your last line states that $\inf_{n\geq k}a_{n}+\inf_{n\geq k}b_{n}$ is a lower bound of the set $\{a_n+b_n\mid n\geq k\}$.
Then it is legal to conclude that it does not exceed the greatest lower bound of that set.
So in mathematical notation: $$\inf_{n\geq k}a_{n}+\inf_{n\geq k}b_{n}\leq\inf_{n\geq k}(a_n+b_n)\text{ QED}$$


text:
Q: IOS - How to resign an ipa file? I try to resign an .ipa file but I have some problems.
I archived the project and exported it for Ad Hoc Deployment then I followed this tutorial: https://sholtz9421.wordpress.com/2012/06/08/digitally-resigning-ipa/ .
During installation I had this error: "Application is missing the application-identifier entitlement." so I created an "entitlements.plist" file and I tried to resign with the argument --entitlements
codesign -f -v -s "MyIdentity" Payload/SampleApp.app --entitlements entitlements.plist
Now when I try to install the .ipa file I have this error: "Failed to verify code signature .. (The executable was signed with invalid entitlements)."
My entitlements.plist file is this:
<?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
   <plist version="1.0">
   <dict>
    <key>application-identifier</key>
    <string>{team-identifier}.{bundleId}</string>
    <key>aps-environment</key>
    <string>production</string>
    <key>beta-reports-active</key>
    <true/>
    <key>com.apple.developer.associated-domains</key>
    <string>*</string>
    <key>com.apple.developer.team-identifier</key>
    <string>{team-identifier}</string>
    <key>get-task-allow</key>
    <false/>
    <key>keychain-access-groups</key>
    <array>
       <string>{team-identifier}.*</string>
    </array>
    </dict>
    </plist>

Any idea of the problem? Any help is appreciated.

A: I have found a solution: I have used IReSign to resign .ipa file. The correct entitlements.plist file is this:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>application-identifier</key>
<string>{team-identifier}.{bundleId}</string>
<key>aps-environment</key>
<string>production</string>
<key>com.apple.developer.team-identifier</key>
<string>{team-identifier}</string>
<key>get-task-allow</key>
<false/>
<key>keychain-access-groups</key>
<array>
    <string>{team-identifier}.{bundleId}</string>
</array>


text:
Q: Use regex to validate angular expressions in a paragraph input I have a difficult user-input validation question (or at least it's difficult for me).  I'm trying to make sure users are inputting a pre-defined subset of allowed Angular expressions if they try to add angular to their input at all.
I'm currently using http://www.regexpal.com/ (the actual implementation is in an HTML webpage using javascript) to test my expression and the two following cases:
VALID
Any text, punctuation (except double-{), or numb3r5 {{model.variable|phone}} is valid
Any text, punctuation (except double-{), or numb3r5 {{model.variable}} is valid.
Stick with the format {{model.variable|zipcode}} and we remain valid.

INVALID
Any text, punctuation (except double-{), or numb3r5 {{model.variable|phone}} is valid
Any text, punctuation (except double-{), or numb3r5 {{model.variable}} is valid.
Any deviation from the format, e.g. {{model.variable|custom}} makes the entire input invalid.

I figured out the regex to identify the three angular blocks and un-match the "custom" one...
{{model\.[^}|]+(\|((ein)|(phone)|(zipcode)|(currency:'':0)){1})?}}

... but I can't get it to enforce that regex.  I tried lots of variations on lookaheads, and this is what I think I need, but it doesn't match the valid input, so obviously I'm off.
^(((.(?!({{)|(}})))*({{model\.[^}|]+(\|((ein)|(phone)|(zipcode)|(currency:'':0)){1})?}}))?)+$

Does anyone out there know how I might validate this input?

A: Nicely composed question. You described the problem and what you have tried.
Using Lookaheads is one solution but you may end up consuming the text for other purposes, so normal groups work fine here.
I would suggest:^((?:^|[^\r\n\{]*)(?:\{(?:[^{]|$)|(?:\{{2}model\.variable(?:\|(?:(ein)|(phone)|(zipcode)|(currency:'':0)))?\}{2}|$)))+$ (demo)
Be aware that visibly empty strings can pass this regex. I would do a .trim().length check if that is an issue. I didn't think it was appropriate to add more bloat to this regex.
^                         # Anchors to beginning of string or line,
                            # depending on multinline flag
(                         # Opens capturing group 1
  (?:                     # Opens noncapturing group
    ^                     # Anchors to the beginning of string or line
  |                       # or
    [^\r\n\{]*            # Any character but carriage return, new line, {, one or more times
  )                       # Closes noncapturing group
  (?:                     # Opens noncapturing group
    \{                    # Literal {
    (?:                   # Opens noncapturing group
      [^{]                # Any character but {
                            # to filter {{'ss
    |                     # or
      $                   # End of string or line
    )                     # Closes noncapturing group
  |                       # or
    (?:                   # Opens noncapturing group
      \{{2}               # {, twice
      model\.variable     # model.variable
      (?:                 # Opens noncapturing group
        \|                # Literal |
        (?:               # Opens noncapturing group
          (ein)           # ein as capturing group 2
        |                 # or
          (phone)         # phone as capturing group 3
        |                 # or
          (zipcode)       # zipcode as capturing group 4
        |                 # or
          (currency:'':0) # currency as capturing group 5
        )                 # closes non-capturing group
      )?                  # closes non-capturing group, iternates 0 or 1 times
      \}{2}               # }, twice
    |                     # or
      $                   # end of string or line, dependong on multiline
    )                     #
  )                       #
)+                        #
$                         #

Per: I'm going to run with this and see if I can get it to ignore the newlines/carriage returns when building the overall match for the entire input.

^((?:^|[^{]+)(?:\{(?:[^{]|$)|(?:\{{2}model\.variable(?:\|(?:(ein)|(phone)|(zipcode)|(currency:'':0)))?\}{2}|$)))+$ (demo)
I only needed to remove the single \r\n and remove the multiline flag.


text:
Q: Oozie sqoop task error: Cannot run program "hive": error=2 no such file or directory i created a oozie sqoop task to import data from mysql to hive. i have a namenode and 3 datanodes, which also have hive, oozie and sqoop installed on the namenode.
the sqoop import coommand has been tested var CLI on the namenode, but every time i create a oozie sqoop task, it also aways failed. below is the detail errors.

2017-08-11 11:27:40,787 [uber-SubtaskRunner] INFO  org.apache.hadoop.mapreduce.Job  -  map 0% reduce 0%
2017-08-11 11:27:40,787 [uber-SubtaskRunner] INFO  org.apache.hadoop.mapreduce.Job  -  map 0% reduce 0%
2017-08-11 11:27:44,833 [uber-SubtaskRunner] INFO  org.apache.hadoop.mapreduce.Job  -  map 25% reduce 0%
2017-08-11 11:27:44,833 [uber-SubtaskRunner] INFO  org.apache.hadoop.mapreduce.Job  -  map 25% reduce 0%
2017-08-11 11:27:45,837 [uber-SubtaskRunner] INFO  org.apache.hadoop.mapreduce.Job  -  map 75% reduce 0%
2017-08-11 11:27:45,837 [uber-SubtaskRunner] INFO  org.apache.hadoop.mapreduce.Job  -  map 75% reduce 0%
2017-08-11 11:27:46,844 [uber-SubtaskRunner] INFO  org.apache.hadoop.mapreduce.Job  -  map 100% reduce 0%
2017-08-11 11:27:46,844 [uber-SubtaskRunner] INFO  org.apache.hadoop.mapreduce.Job  -  map 100% reduce 0%
2017-08-11 11:27:46,856 [uber-SubtaskRunner] INFO  org.apache.hadoop.mapreduce.Job  - Job job_1502360348741_0041 completed successfully
2017-08-11 11:27:46,856 [uber-SubtaskRunner] INFO  org.apache.hadoop.mapreduce.Job  - Job job_1502360348741_0041 completed successfully
...
2017-08-11 11:27:46,932 [uber-SubtaskRunner] INFO  org.apache.sqoop.mapreduce.ImportJobBase  - Transferred 625 bytes in 12.0595 seconds (51.8263 bytes/sec)
2017-08-11 11:27:46,936 [uber-SubtaskRunner] INFO  org.apache.sqoop.mapreduce.ImportJobBase  - Retrieved 14 records.
2017-08-11 11:27:46,951 [uber-SubtaskRunner] INFO  org.apache.sqoop.manager.SqlManager  - Executing SQL statement: SELECT t.* FROM UserRole AS t WHERE 1=0
2017-08-11 11:27:46,952 [uber-SubtaskRunner] INFO  org.apache.sqoop.manager.SqlManager  - Executing SQL statement: SELECT t.* FROM UserRole AS t WHERE 1=0
2017-08-11 11:27:46,953 [uber-SubtaskRunner] WARN  org.apache.sqoop.hive.TableDefWriter  - Column updatedDate had to be cast to a less precise type in Hive
2017-08-11 11:27:46,960 [uber-SubtaskRunner] INFO  org.apache.sqoop.hive.HiveImport  - Loading uploaded data into Hive
2017-08-11 11:27:46,963 [uber-SubtaskRunner] ERROR org.apache.sqoop.tool.ImportTool  - Encountered IOException running import job: java.io.IOException: Cannot run program "hive": error=2,

here are my thoughts

*

*the mapper job is generated, so this script should be submitted and run on namenode. is this correct?

*i am all the env vars config well, so the error phase, which import tool to import data to the hive table should be launched on one of the datanode.

so should i install hive on every datanode of the cluster? or is there any config that i can do to resolve this issue?

A: *

*Ensure hive-site.xml is at place in the hdfs.

*Copy all hive libs shared folder to sqoop libs shared folder.


text:
Q: Use bash instead of sh as the shell of choice for python command namespace functions I need to use a commandline that is suited to bash style, e.g.
diff x  <(cat y | tail +2)

However, sh -c of the above line gives an error, hence commands.getoutput of the above line fails.
However, bash -c of the above does what I want to get done. Can somebody suggest how to make python use bash.
I understand I can get it done using subprocess, but I have a lot of command lines that I have to process and I want to use only commands.getoutput.
Thanks.

A: You can do commands.getoutput("bash -c 'diff x  <(tail +2 y)'"), perhaps (note that cat is unnecessary).
However: commands.getoutput('tail +2 y | diff x -') doesn't require Bash.


text:
Q: I want to change the key of an multidimensional array array (size=4)
  0 =>
    array (size=9)
      'ref_id' => string '11' (length=2)
      'ref_own' => string 'kevin' (length=5)
      'ref_nom' => string 'Herbert' (length=7)
      'ref_ape' => string 'Guzman' (length=6)
      'ref_tel1' => string '12345678' (length=8)
      'ref_tel2' => string '87654321' (length=8)
      'ref_tel3' => string '' (length=0)
      'ref_who' => string 'Daniel Quevedo' (length=14)
      'ref_fecha' => string '2014-12-03 10:16:10' (length=19)
  1 =>
    array (size=9)
      'ref_id' => string '12' (length=2)
      'ref_own' => string 'kevin' (length=5)
      'ref_nom' => string 'Afid' (length=4)
      'ref_ape' => string 'Rivas' (length=5)
      'ref_tel1' => string '12345678' (length=8)
      'ref_tel2' => string '32132121' (length=8)
      'ref_tel3' => string '' (length=0)
      'ref_who' => string 'Rick Delgadillo' (length=15)
      'ref_fecha' => string '2014-12-03 10:16:10' (length=19)

I want to changue this keys:
ref_id
ref_own
ref_nom
ref_ape
ref_tel1
ref_tel2
ref_tel3
ref_who
I try with array_push but nothing happend...
ideas?

A: You can change it like this
  <?php
  // your data
  $array =  array(array(
        'ref_id' =>  '11',
        'ref_own' =>  'kevin',
        'ref_nom' =>  'Herbert',
        'ref_ape' =>  'Guzman',
        'ref_tel1' =>  '12345678' ,
        'ref_tel2' =>  '87654321',
        'ref_tel3' =>  '',
        'ref_who' =>  'Daniel Quevedo',
        'ref_fecha' =>  '2014-12-03 10:16:10'),
        array(
        'ref_id' =>  '12',
        'ref_own' =>  'something',
        'ref_nom' =>  'data',
        'ref_ape' =>  'Guzman',
        'ref_tel1' =>  '12345678' ,
        'ref_tel2' =>  '87654321',
        'ref_tel3' =>  '',
        'ref_who' =>  'Daniel Quevedo',
        'ref_fecha' =>  '2014-12-03 10:16:10'));

  // new keys
  $newKeys = ['ref_id' => 'Reference ID',
              'ref_own'=> 'Reference Owner',
              'ref_nom' => 'Reference Number',
              'ref_ape' => 'Reference APE',
              'ref_tel1' => 'Reference Tel1',
              'ref_tel2' => 'Reference Tel2',
              'ref_tel3' => 'Reference Tel3',
              'ref_who' => 'Reference who',
              'ref_fecha' => 'Reference fecha'];

  foreach ($array as $key => $value) {
    foreach($value as $k => $v){
      $array[$key][$newKeys[$k]] = $v;
      unset($array[$key][$k]);
     }
  }
  var_dump($array);

output
  array (size=2)
    0 =>
      array (size=9)
        'Reference ID' => string '11' (length=2)
        'Reference Owner' => string 'kevin' (length=5)
        'Reference Number' => string 'Herbert' (length=7)
        'Reference APE' => string 'Guzman' (length=6)
        'Reference Tel1' => string '12345678' (length=8)
        'Reference Tel2' => string '87654321' (length=8)
        'Reference Tel3' => string '' (length=0)
        'Reference who' => string 'Daniel Quevedo' (length=14)
        'Reference fecha' => string '2014-12-03 10:16:10' (length=19)
    1 =>
      array (size=9)
        'Reference ID' => string '12' (length=2)
        'Reference Owner' => string 'something' (length=9)
        'Reference Number' => string 'data' (length=4)
        'Reference APE' => string 'Guzman' (length=6)
        'Reference Tel1' => string '12345678' (length=8)
        'Reference Tel2' => string '87654321' (length=8)
        'Reference Tel3' => string '' (length=0)
        'Reference who' => string 'Daniel Quevedo' (length=14)
        'Reference fecha' => string '2014-12-03 10:16:10' (length=19)


text: Q: Z factor to get the results in square meters and cubic meters? I have a DEM surface in WGS 1984.I want to calculate surface area and volume in different elevations.I wonder for example If I want to measure the area and volume below some height how shall I set the Plane Height and Z factor to get the results in square meters and cubic meters?


text:
Q: Failed to execute 'querySelectorAll' on 'Document': in javascript? I am trying convert below lines in javascript but getting below error
Error:
Failed to execute 'querySelectorAll' on 'Document': '.usuggest li[aria-selected!='true']'
Jquery code
$(".usuggest li[aria-selected!='true']").eq(0).attr('aria-selected', 'true');

javascript
document.querySelectorAll(".usuggest li[aria-selected!='true']")[0].setAttribute('aria-selected', 'true')

A: The reference at https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll mentions that the selector that you pass must be a valid CSS selector. In fact, if you look at the full error generated by your code, it gives the following:
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '.usuggest li[aria-selected!='true']' is not a valid selector.

Telling us that there is an issue with the selector.
Moving to the CSS selectors at https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors and attribute selectors at https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors, we see that to select an attribute, != is not a valid operator. From Can't find a "not equal" css attribute selector we can then see that we would need to prepend with :not to apply the inverse and then do an equality check.
This gives us the following updated JavaScript
document.querySelectorAll(".usuggest li:not([aria-selected='true'])")

Which should do what you want.
This then makes the entire query:
document.querySelectorAll(".usuggest li:not([aria-selected='true'])")[0].setAttribute('aria-selected', 'true');

Since the querySelectorAll may not return results, I would recommend doing the following:
const falseListItems = document.querySelectorAll(".usuggest li:not([aria-selected='true'])");

if (falseListItems.length > 0) {
    falseListItems[0].setAttribute('aria-selected', 'true');
}

If you can guarantee that the query will lead to a single result, then the extra if statement is not necessary of course.

A: You can split the command into 2-3 lines, to debug easily,
const element = document.querySelectorAll(".usuggest li[aria-selected!='true']");
// you can check value 0f element here: console.log(element);
element[0].setAttribute('aria-selected', 'true');
If this too cause error, please reply with output of  console.log(element);


text:
Q: How to write a better SQL for this scenario I have a table called "DEVICE" which contains these columns:
------------------------------------------
SN | User_ID |  State    | ...
------------------------------------------
1 |  1001   | deployed  | ...
2 |  1001   | deploying | ...
3 |  1002   | inventory | ...
4 |  1003   | deploying | ...
5 |  1001   | deploying | ...
6 |  1002   | synced    | ...
7 |  1002   | synced    | ...
8 |  1010   | synced    | ...
9 |  1008   | unsynced  | ...
---------------------------------------

As you can see, this table lists all the devices, which are belong to different user by their user_id. Also for all these devices, their state is one of these 5 types:
"inventory",
"deployed",
"deploying",
"synced"
"unsynced".

I need a SQL Query that returns back the user_id that holds the maximum devices of each individual State. For example, for the above set of data in the first table, the return would be:
-----------------------------------------------------------
User_ID     |    State    |   Maximum
-----------------------------------------------------------
1001        |    deployed |     1
1001        |    deploying|     2
1002        |    inventory|     1
1002        |    synced   |     2
1008        |    unsynced |     1
------------------------------------------------------------

The SQL I have created so far is like this:
SELECT
    STATE, ACCOUNT, CNT
from
( select account_id as ACCOUNT, state as STATE, count(*) as CNT
  from DEVICE group by account_id, state ) T1
where
    ( STATE, CNT )
IN
    ( select STATE, MAX(CNT)
from
( select account_id as ACCOUNT, state as STATE, count(*) as CNT
   from DEVICE group by account_id, state ) T2
Group by STATE
);

which is so ugly. Is there a better way to do that ?
Thanks,
Jack

A: You can create an intermediate summary table or a view like so:
drop table if exists device_summary;

create table device_summary as
    select user_id, state, count(*) as counter
    from device
    group by user_id, state;

Then, you can run a query like so to get your desired results:
select d.*
from device_summary d
inner join (
    select state, max(counter) as maxcounter
    from device_summary
    group by state
) d1 on d.state = d1.state and d.counter = d1.maxcounter;

Example: https://rextester.com/ZMZH93648

A: You can make use of ROW_NUMBER analytical function as follows:
SELECT
    B.USER_ID,
    B.STATE,
    B.CNT
FROM
    (
        SELECT
            ROW_NUMBER() OVER(
                PARTITION BY A.STATE
                ORDER BY
                    A.CNT DESC
            ) AS RN,
            A.USER_ID,
            A.STATE,
            A.CNT
        FROM
            (
                SELECT
                    USER_ID,
                    STATE,
                    COUNT(1) CNT
                FROM
                    DEVICE
                GROUP BY
                    USER_ID,
                    STATE
            ) A
    ) B
WHERE
    B.RN = 1

db<>fiddle demo
Cheers!!

A: Try this:
SELECT User_ID, State, count(*) AS Maximum
FROM DEVICE
GROUP BY User_ID, State
ORDER BY User_ID, State

A: You can use window functions, but only need one level of subquery is needed:
SELECT USER_ID, STATE, CNT
FROM (SELECT USER_ID, STATE, COUNT(*) as CNT,
             ROW_NUMBER() OVER (PARTITION BY state ORDER BY COUNT(*) DESC) as seqnum
      FROM DEVICE
      GROUP BY USER_ID, STATE
     ) us
WHERE seqnum = 1;

Note:  If there are ties, this returns an arbitrary user.  If you want all of them, use RANK() instead of ROW_NUMBER().
Note:  Window functions are only available in MySQL starting with version 8.


text:
Q: How to append a child div that wraps the inside content I'm trying to using pure JS (not jquery) to add a  insides the
 that wraps the text 'abc'
For practice purpose, i'm not allowed to innerHTML method, inline CSS, or jquery etc. plain js.

abc

my attempt.
const todo = document.querySelector('.todo')
const del = document.createElement('del')
todo.appendChild(del)

But this ended up with

abc
.
I'd like to have

abc
.

A: You can do a short trick to achieve this:
1) Add textContent of todo to del's textContent.
del.textContent = todo.textContent;

2) Remove the textContent of todo.
todo.textContent = "";

3) Append del as a child.
todo.appendChild(del)

const todo = document.querySelector('.todo')
const del = document.createElement('del')
del.textContent = todo.textContent;
todo.textContent = "";
todo.appendChild(del)

abc

A: You can use the innerText method

const todo = document.querySelector('.todo')
const del = document.createElement('del')
del.innerText = todo.innerText
todo.innerText = ""
todo.appendChild(del)

A: Move the content - saves blanking it

const todo = document.querySelector('.todo')
const del = document.createElement('del')
del.append(todo.firstChild)
todo.appendChild(del)

abc

Or simpler

const todo = document.querySelector('.todo')
todo.innerHTML = todo.textContent.strike()

abc


text:
Q: Which place do I set up DNS servers? On my computer or on the router? Or both? I know how set them on each, I just need to know which one, or if I really need to bother.

A: Well, it depends.
You should be using your ISP DNS servers, and that's automatically set if you use a dynamic ip address. If you can't or don't want to use them for some reason I'd set it on the router as then DNS server settings are network wide, but setting them per computer will overrule that. I'd then set them on any system you didn't want the DNS settings on the router to be in effect for


text:
Q: How to install Ubuntu on Toshiba Satellite c850-19z My computer is using UEFI and is running Windows 8.
I've tried install Ubuntu before but I only got as far as putting it on a USB
(using universal USB installer). But when I go to the boot manager on UEFI and put the USB port first before my hard-drive nothing happens and it just boots back into Windows 8.

A: This sounds like a case of Secure Boot, which is a security mechanism added by hardware vendors in collaboration with Microsoft to only allowed the system to boot from approved ISO images.
This mechanism can be a challenge when a user wants to install Ubuntu. Solutions depend on the UEFI in use, but it might entail disabling Secure Boot inside UEFI and then try again.
Be aware though that making changes in the BIOS is not without risk. If you decide to do it, it is a very good idea to write every changed setting down to be able to set it back afterwards.

A: As Zilvador says, this could be a Secure Boot issue; however, Ubuntu should support Secure Boot, so I suspect that one of two other things is happening:

*

*Improperly-created USB drive -- Assuming no changes to a stock computer, you'll need a USB drive with an EFI boot loader installed on it (including Ubuntu's Secure Boot tool, which is called Shim). Some tools for creating bootable USB drives won't copy these files, though, or will copy them only when certain options are set. Thus, you might need to try another tool, or change the options in the tool you're using.

*Wrong option selected in boot manager -- Most EFI boot managers (the displays you see when you hit a function key to choose what medium to boot) show two options for removable disks. One option includes the string "UEFI" and the other doesn't. These boot in EFI mode and in BIOS mode, respectively. Depending on firmware settings and how you prepared the disk, you might need to select one boot mode or the other -- EFI mode, if you want to install alongside Windows that's also in EFI mode. If you select the wrong mode, the disk might fail to boot, especially if it lacks the boot loader for the mode you chose (see the preceding point).

A: I recommend you to use this tool to create a bootable USB. Make sure to select GPT partition scheme for UEFI comuters on second field.


text:
Q: ProviderManifestToken '2008' is different from '2005' that was encountered earlier I'm working on ASP.NET 4 and with Visual Studio 2010. This project is using Entity Framework.
I'm using MS SQL Server 2008 (by mistake) and a colleague 2005.
I've accidentally clicke the "Update model from database" button and the DB (which is sql server 2005) took my 2008 db.
So, when my colleague tried to run the app in his computer, he got this error:

Entities.Model.ssdl(2,86) : error
  0169: All SSDL artifacts must target
  the same provider. The
  ProviderManifestToken '2008' is
  different from '2005' that was
  encountered earlier.

We know what it means, but we don't know how to make the app accept his model (which is sql server 2005) instead of mine (which is sql server 2008).

A: I encountered the problem described in this question only after I had updated the ProviderManifestToken in one of of two .edmx files in my project as described in this other question.  I got the "ProviderManifestToken is different than was encountered earlier" error because I had only updated one .edmx file in my project, and not both (or all) of them.

A: just open .emmx file and change ProviderManifestToken from "2008" to "2005"


text:
Q: PIG: Unable to open iterator for alias AliasName.Scalar has more than one row in the output I am new to pig and trying to learn on my own.
I have written a script to get the epoch time with a word that is reading from words.txt file.
Here is the script.
words = LOAD 'words.txt' AS word:chararray;
B = FOREACH A GENERATE CONCAT(CONCAT(A.word,'_'),(chararray)ToUnixTime(CurrentTime());
dump B;

But the issue is, if words.txt file have only one word it is giving proper output.
If it is having multiple words like
word1
word2
word3
word4

then it is giving the following error

ERROR 1066: Unable to open iterator for alias B
java.lang.Exception:
  org.apache.pig.backend.executionengine.ExecException: ERROR 0:
  Scalar has more than one row in the output. 1st : (word1 ), 2nd :(word2) (common cause: "JOIN" then "FOREACH ... GENERATE foo.bar"
  should be "foo::bar" ) at
  org.apache.hadoop.mapred.LocalJobRunner$Job.runTasks(LocalJobRunner.java:462)
  at
  org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:522)
  Caused by: org.apache.pig.backend.executionengine.ExecException: ERROR
  0: Scalar has more than one row in the output. 1st : (word1 ), 2nd
  :(word2) (common cause: "JOIN" then "FOREACH ... GENERATE foo.bar"
  should be "foo::bar" ) at
  org.apache.pig.impl.builtin.ReadScalars.exec(ReadScalars.java:122) at
  o

Please suggest me to solve this issue.
Thank you.

A: solved on my own.
just removed the A. from the inner CONCAT. It worked for me.
script:
words = LOAD 'words.txt' AS word:chararray;
B = FOREACH A GENERATE CONCAT(CONCAT(word,'_'),(chararray)ToUnixTime(CurrentTime());
dump B;


text:
Q: Castle Windsor Inheritance security rules violated while overriding member In my development environment, everything works fine, but when deployed to the server, I get the following error:

Inheritance security rules violated while overriding member:
  'Castle.MicroKernel.DefaultKernel.InitializeLifetimeService()'.
  Security accessibility of the overriding method must match the
  security accessibility of the method being overriden.
Description: An unhandled exception occurred during the execution of
  the current web request. Please review the stack trace for more
  information about the error and where it originated in the code.
Exception Details: System.TypeLoadException: Inheritance security
  rules violated while overriding member:
  'Castle.MicroKernel.DefaultKernel.InitializeLifetimeService()'.
  Security accessibility of the overriding method must match the
  security accessibility of the method being overriden.

The strange thing is, that on another site, the same Castle version doesn't raise an error.

A: I had the same issue with a .net web application that runs in a shared hosting environment. The thing that sorted it out for me was requesting full trust for the domain that the application was on from the hosting company. Bear in mind that putting the full trust setting in the web config only threw an error due to the restrictions on the server.


text:
Q: Spring-boot single sign-out using Keycloak Description
I created an application which uses Keycloak 12.0.1 as identity provider.
Single sign-on works fine, 'local logout' as well.
The Problem is the single sign-out.
I searched for documentations and issues in the web but found nothing much.
I have three failing scenarios described by logs below.
Questions in the end are:

*

*What am I doing wrong?

*How must I implement the backchannel logout in my App?

Example how I understand SSOut should work:

*

*User clicks 'logout' in App A

*App A ends the session

*App A notifies Keycloak

*Keycloak notifies App B via backchannel logout

*App B ends the session

Security configuration
The method keycloakCsrfRequestMatcher() frees library owned endpoints like "k_logout" from csrf protection but not my own url "/sso/logout". It might be possible to write my own Matchers but this is over my experience as developer.
import java.util.Arrays;
import java.util.List;

import javax.annotation.PostConstruct;

import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.keycloak.adapters.springsecurity.KeycloakSecurityComponents;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.keycloak.adapters.springsecurity.filter.KeycloakSecurityContextRequestFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter;

@Profile("KC")
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
class SecurityConfigurationKeycloak extends KeycloakWebSecurityConfigurerAdapter implements EnvironmentAware {

    private static final Logger LOG = LoggerFactory.getLogger(SecurityConfigurationKeycloak.class);

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
        // SimpleAuthorityMapper is used to remove the ROLE_* conventions defined by
        // Java so we can use only admin or user instead of ROLE_ADMIN and ROLE_USER
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
        auth.authenticationProvider(keycloakAuthenticationProvider);
    }

    @Bean
    public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }

    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

//      super.configure(http);

        http
            .csrf()
                .requireCsrfProtectionMatcher(keycloakCsrfRequestMatcher())
            .and()
                .sessionManagement()
                .sessionAuthenticationStrategy(sessionAuthenticationStrategy())
            .and()
                .addFilterBefore(keycloakPreAuthActionsFilter(), LogoutFilter.class)
                .addFilterBefore(keycloakAuthenticationProcessingFilter(), LogoutFilter.class)
                .addFilterAfter(keycloakSecurityContextRequestFilter(), SecurityContextHolderAwareRequestFilter.class)
                .addFilterAfter(keycloakAuthenticatedActionsRequestFilter(), KeycloakSecurityContextRequestFilter.class)
                .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
            /*
             * LOGOUT
             */
            .and()
                .logout()
                    .addLogoutHandler(keycloakLogoutHandler())
                    .logoutUrl("/sso/logout").permitAll()
                    .logoutSuccessUrl("/")

            .and()
                .authorizeRequests()

                /*
                 * ADMIN
                 */
                .antMatchers(
                        "/admin/**"
                    )
                .hasRole("ADMIN")

                /*
                 * PUBLIC
                 */
                .antMatchers(
                        "/webjars/**",
                        "/css/**",
                        "/img/**",
                        "/favicon.ico",
                        "/**")
                .permitAll();
    }

    @Override
    public void setEnvironment(Environment environment) {
        // TODO Auto-generated method stub
    }
}

Logs A
As we can see there is an CSRF error when KC tries to access the "/sso/logout" url.
But I don't know if this is the right endpoint to use in KC?
I found "/k_logout" in the used libraries, which seems to be some "internal redirect" url to me.
(Removed dates etc. for convenience.)
o.k.adapters.PreAuthActionsHandler       : adminRequest http://domain.tld/sso/logout
.k.a.t.AbstractAuthenticatedActionsValve : AuthenticatedActionsValve.invoke /sso/logout
o.k.a.AuthenticatedActionsHandler        : AuthenticatedActionsValve.invoke http://domain.tld/sso/logout
o.k.a.AuthenticatedActionsHandler        : Policy enforcement is disabled.
o.s.security.web.FilterChainProxy        : Securing POST /sso/logout
s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext
o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for https://domain.tld/sso/logout
o.s.s.w.access.AccessDeniedHandlerImpl   : Responding with 403 status code
w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request
o.s.security.web.FilterChainProxy        : Securing POST /error
s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext
o.k.adapters.PreAuthActionsHandler       : adminRequest https://domain.tld/error
o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
o.s.s.w.a.i.FilterSecurityInterceptor    : Authorized filter invocation [POST /error] with attributes [permitAll]
o.s.security.web.FilterChainProxy        : Secured POST /error
e.p.p.controller.CustomErrorController   : User was not authorized for requested site: /error
w.c.HttpSessionSecurityContextRepository : Did not store anonymous SecurityContext
s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request

Logs B
If I use the "/k_logout" endpoint in KC instead I get an JWT Parse error in my App.
I tried to debug it and it seems that in org.keycloak.jose.jws.JWSInput the encodedHeader is prefixed with "logout_token=" which seems to be the problem. At least to me. :-)
o.k.adapters.PreAuthActionsHandler       : adminRequest http://domain.tld/k_logout
o.k.adapters.PreAuthActionsHandler       : admin request failed, unable to verify token: Failed to parse JWT
o.k.adapters.PreAuthActionsHandler       : Failed to parse JWT

org.keycloak.common.VerificationException: Failed to parse JWT
    at org.keycloak.TokenVerifier.parse(TokenVerifier.java:402) ~[keycloak-core-12.0.1.jar:12.0.1]
    at org.keycloak.TokenVerifier.getHeader(TokenVerifier.java:423) ~[keycloak-core-12.0.1.jar:12.0.1]
    at org.keycloak.adapters.rotation.AdapterTokenVerifier.createVerifier(AdapterTokenVerifier.java:110) ~[keycloak-adapter-core-12.0.1.jar:12.0.1]
    at org.keycloak.adapters.PreAuthActionsHandler.verifyAdminRequest(PreAuthActionsHandler.java:210) ~[keycloak-adapter-core-12.0.1.jar:12.0.1]
    at org.keycloak.adapters.PreAuthActionsHandler.handleLogout(PreAuthActionsHandler.java:140) ~[keycloak-adapter-core-12.0.1.jar:12.0.1]
    at org.keycloak.adapters.PreAuthActionsHandler.handleRequest(PreAuthActionsHandler.java:80) ~[keycloak-adapter-core-12.0.1.jar:12.0.1]
    at org.keycloak.adapters.tomcat.AbstractKeycloakAuthenticatorValve.invoke(AbstractKeycloakAuthenticatorValve.java:177) ~[spring-boot-container-bundle-12.0.1.jar:12.0.1]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
Caused by: org.keycloak.jose.jws.JWSInputException: com.fasterxml.jackson.core.JsonParseException: Unexpected character ((CTRL-CHAR, code 150)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
 at [Source: (byte[])"��(���G��쉅����IL��؈�������耉)]P��������耉�
8�UL�ōYY����}=�!]�! �1]�}���1i���1]ጉ�"; line: 1, column: 2]
    at org.keycloak.jose.jws.JWSInput.<init>(JWSInput.java:58) ~[keycloak-core-12.0.1.jar:12.0.1]
    at org.keycloak.TokenVerifier.parse(TokenVerifier.java:400) ~[keycloak-core-12.0.1.jar:12.0.1]
    ... 19 common frames omitted
Caused by: com.fasterxml.jackson.core.JsonParseException: Unexpected character ((CTRL-CHAR, code 150)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
 at [Source: (byte[])"��(���G��쉅����IL��؈�������耉)]P��������耉�
8�UL�ōYY����}=�!]�! �1]�}���1i���1]ጉ�"; line: 1, column: 2]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1851) ~[jackson-core-2.11.3.jar:2.11.3]
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:707) ~[jackson-core-2.11.3.jar:2.11.3]
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:632) ~[jackson-core-2.11.3.jar:2.11.3]
    at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._handleUnexpectedValue(UTF8StreamJsonParser.java:2686) ~[jackson-core-2.11.3.jar:2.11.3]
    at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._nextTokenNotInObject(UTF8StreamJsonParser.java:865) ~[jackson-core-2.11.3.jar:2.11.3]
    at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:757) ~[jackson-core-2.11.3.jar:2.11.3]
    at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4664) ~[jackson-databind-2.11.3.jar:2.11.3]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4513) ~[jackson-databind-2.11.3.jar:2.11.3]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3529) ~[jackson-databind-2.11.3.jar:2.11.3]
    at org.keycloak.util.JsonSerialization.readValue(JsonSerialization.java:71) ~[keycloak-core-12.0.1.jar:12.0.1]
    at org.keycloak.jose.jws.JWSInput.<init>(JWSInput.java:56) ~[keycloak-core-12.0.1.jar:12.0.1]
    ... 20 common frames omitted

Logs C
If I disable csrf protection for the App completely by using .csrf().disable() the above error obviously is not there anymore. Instead the App can't map the logout request to a user.
o.k.adapters.PreAuthActionsHandler       : adminRequest http://192.168.178.31:8090/sso/logout
.k.a.t.AbstractAuthenticatedActionsValve : AuthenticatedActionsValve.invoke /sso/logout
o.k.a.AuthenticatedActionsHandler        : AuthenticatedActionsValve.invoke http://192.168.178.31:8090/sso/logout
o.k.a.AuthenticatedActionsHandler        : Policy enforcement is disabled.
o.s.security.web.FilterChainProxy        : Securing POST /sso/logout
s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext
o.k.adapters.PreAuthActionsHandler       : adminRequest http://192.168.178.31:8090/sso/logout
o.s.s.w.a.logout.LogoutFilter            : Logging out [null]
o.k.a.s.a.KeycloakLogoutHandler          : Cannot log out without authentication
o.s.s.web.DefaultRedirectStrategy        : Redirecting to /
w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request

Keycloak configuration for backchannel logout

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>tld.domain</groupId>
    <artifactId>artifact</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>name</name>
    <description></description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.1</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.keycloak.bom</groupId>
                <artifactId>keycloak-adapter-bom</artifactId>
                <version>12.0.1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


text:
Q: Need to tell users when update occurs I want to notify all the app users to update the app (through a popup in the app itself) whenever there is a new version deployed in the stores. Can someone suggest the best way to do that?

A: Let's say you want to notify the users about a new version of the app every time they open the application, then you should just trigger a simple GET call to retrieve the latest version info or use a third party lib to act accordingly.
0 cost simple solutions
One option would be to ask the API (if there is any) if a new version is available - basically delegate the problem to someone else. If there is no backend the app could do the check itself. There are different options from having a simple txt file hosted somewhere with the latest app version to scraping App Store and Play Store for the current published version of the app.
Existing solutions
https://appgrades.io/
https://github.com/ArtSabintsev/Siren
Use Push Notifications to notify your users
You will find more if you google it
Platform specific solutions
For iStuff (Apple) you could use iTunes Search API as mentioned here
Other platforms may have their own APIs
Depends on the specific case you can decide what will work better for you.
P.S.: Be sure to handle the versioning correctly by bumping the app version on each release.

A: Luckily, we do have solution for iOS app store
string url = "http://itunes.apple.com/lookup?bundleId=com.xxx.xxxxx";

HttpClient httpClient = new HttpClient();

Task<string> jsonString = httpClient.GetStringAsync(string.Format(

var lookup = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString.Result);

But Now I need to get the current version of App from Google Play Store?


text:
Q: Deploy Dockerized NodeJS application with the respective .env files I am working on a NodeJS application which is a containerized application. I use Jenkins to build and deploy it. I have an environment .env file and along with this, also have .env files based on environments.
For example: .env.DEV, .env.SQA, .env.STG and .env.PROD.
Each file has different values for the variables based on environments.

When I am deploying my application, it always fetches variables from the .env file instead of specific environment file i.e. .env.DEV (if deploying on DEV server).
How do we use specific environment file while doing the deployment on Jenkins?
Note: I followed this great content on dotenv library but I didn't find anything helpful for my use-case. I did some research on the web, but didn't find much on this.

A: You can use dotenv-flow which does exactly this, given the value of NODE_ENV environment value it will load the expected environment.
You also will need to make sure that the container receives the proper environment values from jenkins, this might help.


text:
Q: Selecting nvarchar 'like' in a left join - inner join combination I currently have a query that returns results based on a dynamic set of conditions
DataTable Items:
    ID   Title
    1    Some title
    2    Some other title
..etc..

.
DataTable Tags:
    ID   Tag
    1    'a1c'
    1    'a1d'
    2    'a2c'
..etc..

My current search Query:
select * from dbo.Items i
LEFT JOIN dbo.tags t
on i.ID = t.ID
INNER JOIN @input in
on (in.[input] = t.Tag or in.[input] is null)

An input would be something like:
DECLARE @input as inputTable_type
INSERT INTO @input VALUES ('a1c')

What I would like to do is use a value like 'a1%' as an input, but when I try that, I get no results (although I do know that a query such as the following does work):
select * from dbo.Items i
INNER JOIN dbo.tags t
on i.ID = t.ID
and t.Tag like ('a1%')

Unfortunately, I want to keep it a static query, and as far as I know, I need the LEFT JOIN - INNER JOIN combination that I have in order to be able to pass VALUES (NULL) into the stored procedure.
Thanks for any thoughts and help, and let me know if I can clarify anything!

A: Since you're already playing funny games with the outer joined table, why not extend the games?  The simplest version is to replace the equality with LIKE; the next simplest version is to add an OR term:
SELECT *
  FROM dbo.Items i
  LEFT JOIN dbo.tags t ON i.ID = t.ID
 INNER JOIN @input  in ON (t.Tag = in.[input] OR
                           t.Tag LIKE in.[input] OR
                           in.[input] IS NULL)

The next grade up in sophistication (or do I mean 'complication'?) is to add a second column to the @input table which indicates the comparison to perform:
SELECT *
  FROM dbo.Items i
  LEFT JOIN dbo.tags t ON i.ID = t.ID
 INNER JOIN @input  in ON ((in.[type] = '=' AND t.Tag = in.[input]) OR
                           (in.[type] = '%' AND t.Tag LIKE in.[input]) OR
                           in.[input] IS NULL)

I've chosen to call the extra column 'type' and the value in it is a single character, using '=' to indicate an equality join and '%' to indicate a LIKE join.

A: Rather than trying to store 'a1%' in your @input table, store just 'a1', then I think the (untested) code below will give you what you want.
select *
    from dbo.Items i
        LEFT JOIN dbo.tags t
            INNER JOIN @input in
                on in.[input] = left(t.Tag, len(in.[input]))
            on i.ID = t.ID
    where (t.ID is not null or not exists(select 1 from @input))


text:
Q: Solving differential equation n Which of the following is the solution for
$$u(x) = x + \int_0^x (t-x)u(t) dt \ ?$$
The answer says it is $u(x) = \sin x$. Could someone explain why?

A: Differentiating once gives
$$
u'(x)=1-\int_0^xu(t)dt
$$
and again
$$
u''(x)=-u(x)
$$
with initial conditions $u(0)=0$ and $u'(0)=1$ which is the classical mathematical oscillator equation.

In general, one knows from partial integration that
\begin{align}
u(x)&=u(0)+\int_0^xu'(t)dt\\
&=u(0)-\int_0^x(-1)·u'(t)dt\\
&=u(0)-[(x-t)u'(t)]_{t=0}^x+\int_0^x(x-t)·u''(t)dt\\
&=u(0)+x·u'(0)+\int_0^x(x-t)·u''(t)dt
\end{align}
which is the Taylor or MacLaurin formula of degree 1 with integral remainder term. Again comparing with the given formula one identifies $u''=-u$ and the initial conditions $u(0)=0$, $u'(0)=1$.

A: First we rewrite your equation:
$$u(x) = x + \int_0^x tu(t) dt-\int_0^x xu(t) dt = x + \int_0^x tu(t) dt-x\int_0^xu(t) dt $$
Now we apply the fundamental theorem of calculus (https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus) in combination with the product rule of differentiation.
$$u'(x)=1+xu(x)-\int_0^xu(t)dt+xu(x)=1-\int_0^xu(t)dt$$
Now, we differentiate this again using the fundamental theorem of calculus.
$$u'(x)=-u(x)$$
This is the differential equation, which has the general solution $u(t)=a\cos(x)+b\sin(x)$.

A: One way to see this is to plug in $u(x) = \sin x$ and see that it solves your equation, but this is not very illuminating.  A second way to see that $u(x) = \sin x$ is a solution, is to take your equation and differentiate both sides twice.  By the fundamental theorem of calculus, you obtain
\begin{align*}
u''(x) = -u(x).
\end{align*}
Moreover, from the equation you have $u(0) = 0, u'(0) = 1$.  The general solution to the above ODE is $u(x) = a\sin x + b \cos x$.  The initial conditions $u(0) = 0, u'(0) = 1$ imply that $a = 1, b = 0$ so that $u(x)
= \sin x$.  Finally, a third way to derive $u(x) = \sin x$ is via Picard iteration.  One can show that the integral equation
\begin{align*}
u(x) = x + \int_0^x ( t - x) u(t) dt,
\end{align*}
has a unique fixed point in $C([0,1])$ (via contraction mapping).  Moreover,
the sequence of functions defined by $u_0(x) = 0$,
\begin{align*}
u_n(x) = x + \int_0^x (t-x) u_{n-1}(t) dt, \quad n \geq 1,
\end{align*}
converges uniformly to the solution $u$ on $[0,1]$.  Doing the first few iterates, you see that
\begin{align*}
u_1(x) &= x, \\
u_2(x) &= x - \frac{x^3}{3!}, \\
u_3(x) &= x - \frac{x^3}{3!} + \frac{x^5}{5!},
\end{align*}
and so on, so that you get the Taylor series for $\sin x$.


text:
Q: Run Kafka and Kafka-connect on different servers? I want to know if Kafka and Kafka-connect can run on different servers? So a connector would be started on server A and send data from a kafka topic on server B to HDFS or S3 etc. Thanks

A: Yes, and for Production deployments this is typically recommended for resource reasons. Generally you'd deploy a cluster of Kafka Brokers (3+ for HA), and then a cluster of Kafka Cluster workers (as many as needed for throughput capacity / resilience) -- all on separate nodes.
For more details, see the Confluent Enterprise Reference Architecture.

A: Yes, you can do it.
I have my set of kafka servers and kafka connect applications are running in different machines and writing data in hdfs. you have to mention list of brokers in bootstrap.servers under worker properties file (config/connect-distributed.properties or config/connect-standalone.properties) instead of localhost:9092


text:
Q: httpServletResponse behavior in chrome and firefox I have a controller method in charge of an excel download:
@RequestMapping(value = "/report/user", method = RequestMethod.GET)
public void getUserReport(@RequestParam(value = "name", required = false) String user,
                          @RequestParam(value = "startdate", required = false) String startDate,
                          @RequestParam(value = "enddate", required = false) String endDate,
                          HttpServletResponse response) {

    List<Survey> userSurveys = surveyService.findUserSurveys(user, startDate, endDate);

    String userFileName = nameService.getUserFileName(user, startDate, endDate);
    Workbook userExcelReport = excelReportGenerator.createUserExcelReport(userSurveys);

    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setHeader("Content-Disposition", "attachment; filename=" + userFileName + ".xlsx");

    try {
        userExcelReport.write(response.getOutputStream());
    } catch (IOException e) {
        logger.error("The excel workbook could not write to the outputStream ", e);
    }

}

as you can see this controller mapping is tanking a excel workbook (done in apache poi) and setting the header and content type, in google chrome this works perfectly but in firefox the file is downloaded as a "file" with no extension (but the data is correct as if i open the file with excel all is there) and the name is built wrong, as in chrome this works completely fine i assume there is something wrong the way the response works in firefox, anyone has idea what could i be doing wrong?
example of downloaded files trough firefox
example of downloads using chrome

A: Please check this way to sent content type in response. It works for me.
resp.setContentType( "application/octet-stream" );

A: According RFC 6266 the filename value is either a token or a quoted-string.
A token must not contain separators. But white space is a separator. So you must using a quoted-string.
So try
response.setHeader("Content-Disposition", "attachment; filename=\"" + userFileName + ".xlsx\"");


text:
Q: Copy comma delimited values into two excel cells I have comma delimited values that look like :
17  ab  2880662,2880663
15  ab  2877244,2877247
21  ab  2874201
21  ab  2873876

When I copy this to Excel it should split the comma-delimited values into two cells, like this:
17  ab  2880662    2880663
15  ab  2877244    2877247
21  ab  2874201    (empty)
21  ab  2873876    (empty)

When I use copy as a text it doesn't work, so I need a genius idea please :)

A: *

*Paste the entire text into the first cell

*click on the icon that appears on the bottom of the paste and choose "use text import wizard"

*In step two of the wizard, choose both spaces and commas as delimiters

You should get exactly what you want. I tried this using your text and it worked. Not sure if Excel 2003 has this, but subsequent versions do.
Step 2:

Step 3:

A: You could first select a cell containing some text then choose:
Data > Text To Columns > Delimited > Next : Comma Check.
then just click Cancel to store these settings. If you copy and paste comma separated text from notepad now it should separate out into columns as required.
Note: with the default settings (Number format set to general) Excel tries to interpret some data values such as dates and numbers depending on your local settings. For example copying across "3/7" may be interpreted as an American or European date, or when copying numeric codes across leading zeros may be lost. To avoid any unwanted conversions, you can set the Number Format for the columns that data is going to be copied to as Text.

A: Save your data in a plain text editor like notpad as myfile.csv and open it with excel. There you can set the delimiter to comma.


text:
Q: Storage overhead of GridFS We have a MongoDB Cluster using GridFS. The fs.chunks table of gridfs is sharded over two replicasets. The usage of diskspace is very high. For 90GB of data we need more than 130GB of diskspace.
It seems like the fs.chunks table is needing the space. I did summarize the "length" field of fs.files showing the 90GB of space. The sum of the "size" field of both shards is 130GB. This is the real size of the payload data contained in the collection, right?
This means it has 40GB overhead? Is this correct? Where is it coming from? is it the BSON encoding? Is there a way to reduce overhead?
mongos> db.fs.chunks.stats()
{
    "sharded" : true,
    "ns" : "ub_datastore_preview.fs.chunks",
    "count" : 1012180,
    "numExtents" : 106,
    "size" : 140515231376,
    "storageSize" : 144448592944,
    "totalIndexSize" : 99869840,
    "indexSizes" : {
            "_id_" : 43103872,
            "files_id_1_n_1" : 56765968
    },
    "avgObjSize" : 138824.35078345748,
    "nindexes" : 2,
    "nchunks" : 2400,
    "shards" : {
            "ub_datastore_qa_group1" : {
                    "ns" : "ub_datastore_preview.fs.chunks",
                    "count" : 554087,
                    "size" : 69448405120,
                    "avgObjSize" : 125338.44887174758,
                    "storageSize" : 71364832800,
                    "numExtents" : 52,
                    "nindexes" : 2,
                    "lastExtentSize" : 2146426864,
                    "paddingFactor" : 1,
                    "systemFlags" : 1,
                    "userFlags" : 0,
                    "totalIndexSize" : 55269760,
                    "indexSizes" : {
                            "_id_" : 23808512,
                            "files_id_1_n_1" : 31461248
                    },
                    "ok" : 1
            },
            "ub_datastore_qa_group2" : {
                    "ns" : "ub_datastore_preview.fs.chunks",
                    "count" : 458093,
                    "size" : 71066826256,
                    "avgObjSize" : 155136.2414531547,
                    "storageSize" : 73083760144,
                    "numExtents" : 54,
                    "nindexes" : 2,
                    "lastExtentSize" : 2146426864,
                    "paddingFactor" : 1,
                    "systemFlags" : 1,
                    "userFlags" : 0,
                    "totalIndexSize" : 44600080,
                    "indexSizes" : {
                            "_id_" : 19295360,
                            "files_id_1_n_1" : 25304720
                    },
                    "ok" : 1
            }
    },
    "ok" : 1
}

A:
This is the real size of the payload data contained in the collection, right?

Yes.

This means it has 40GB overhead? Is this correct?

Kinda. But it seems unusually large.

Where is it coming from? is it the BSON encoding?

No, BSON encoding of data doesn't have that much of an overhead. But adding metadata sometimes does.
In mongo the main source for overhead is usually the metadata, but if you use the reference grids spec — it shouldn't be that big.
For example, in our storage we have:
db.fs.files.aggregate([{$group: {_id: null, total: { $sum: "$length"}}}])
{
    "result" : [
        {
            "_id" : null,
            "total" : NumberLong("4631125908060")
        }
    ],
    "ok" : 1
}

And
db.fs.chunks.stats()
{
    "ns" : "grid_fs.fs.chunks",
    "count" : 26538434,
    "size" : NumberLong("4980751887148"),
    "avgObjSize" : 187680.70064526037,
    "storageSize" : NumberLong("4981961457440"),
    "numExtents" : 2342,
    "nindexes" : 2,
    "lastExtentSize" : 2146426864,
    "paddingFactor" : 1,
    "systemFlags" : 1,
    "userFlags" : 0,
    "totalIndexSize" : 2405207504,
    "indexSizes" : {
        "_id_" : 1024109408,
        "files_id_1_n_1" : 1381098096
    },
    "ok" : 1
}

So, about 300 gb overhead on 4.8 tb of data.

A: The problem have been "orphaned chunks" from GridFS. GridFS first writes the chunks then the metadata, if something goes wrong the already written chunks stay as "orphaned chunks" and have to be cleaned manually.

A: You saved 90 GB of data but it consumed 130 GB of disk space.
That means approx 44% overhead.
As stated in this blog post, the storage overhead of GridFS is approximately 45%, which is almost the same in your case.


text:
Q: problem at the first launch RemoteConfig with conditions I am facing an issue with the RemoteConfig param which has conditions. Most of the time, I get the default value at the first app open. After that, I get the other condition values. My conditions are User in random percentile from 0 -> 10, 10 -> 20, 20 -> 30,...., 90 -> 100. As my opinion, it's should never be the default value (because the conditions cover 100% of user percentile). I did call fetchAndActive() and call mFirebaseRemoteConfig.getString() after task.isSuccessful(). Any idea?

A: I faced the same issue more than a week ago and after some googling the only similar thing I found was this question. Today I finally found the reason and implemented simple workaround.
Long story short there is a race condition in Firebase SDK initialization connected to 'FirebaseInstanceId' generation: during initial launch Firebase does remote config request before generating AppInstanceId. Because of this backend is not able to apply some conditions related to remote params, like 'user in random percentile'.
To fix this we need to generate app instance id before initializing the SDK. So the code may look like this:
FirebaseInstanceId.getInstance().getInstanceId()
    .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
    @Override
    public void onComplete(@NonNull Task<InstanceIdResult> task) {
        //init firebase remote config here
    }
});

Hope this will help.

A: after a lot of days on searching, but there's no clue about it, I had to do a dirty, tricky method to solve my issue: fetch and load the remote config after 1s on onCreate:
Observable.timer(1, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnNext(time ->{
                        fetchAndActiveRemoteConfig();
                    })
                    .subscribe();

P/s: it works but I dont know why it works.


text:
Q: (Casting) errors using extract_(relevant_)features from tsfresh Trying out Python package tsfresh I run into issues in the first steps. Given a series how to (automatically) make features for it? This snippet produces different errors based on which part I try.
import tsfresh
import pandas as pd
import numpy as np
#tfX, tfy = tsfresh.utilities.dataframe_functions.make_forecasting_frame(pd.Series(np.random.randn(1000)/50), kind='float64', max_timeshift=50, rolling_direction=1)
#rf = tsfresh.extract_relevant_features(tfX, y=tfy, n_jobs=1, column_id='id')
tfX, tfy = tsfresh.utilities.dataframe_functions.make_forecasting_frame(pd.Series(np.random.randn(1000)/50), kind=1, max_timeshift=50, rolling_direction=1)
rf = tsfresh.extract_relevant_features(tfX, y=tfy, n_jobs=1, column_id='id')

The errors are in the first case

""" Traceback (most recent call last):   File "C:\Users\user\Anaconda3\envs\env1\lib\multiprocessing\pool.py", line
  119, in worker
          result = (True, func(*args, **kwds))   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\tsfresh\utilities\distribution.py",
  line 38, in _function_with_partly_reduce
          results = list(itertools.chain.from_iterable(results))   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\tsfresh\utilities\distribution.py",
  line 37, in
          results = (map_function(chunk, **kwargs) for chunk in chunk_list)   File
  "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\tsfresh\feature_extraction\extraction.py",
  line 358, in _do_extraction_on_chunk
          return list(_f())   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\tsfresh\feature_extraction\extraction.py",
  line 350, in _f
          result = [("", func(data))]   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\tsfresh\feature_extraction\feature_calculators.py",
  line 193, in variance_larger_than_standard_deviation
          y = np.var(x)   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\numpy\core\fromnumeric.py",
  line 3157, in var
          **kwargs)   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\numpy\core_methods.py",
  line 110, in _var
          arrmean, rcount, out=arrmean, casting='unsafe', subok=False) TypeError: unsupported operand type(s) for /: 'str' and 'int' """

and in the second case

""" Traceback (most recent call last):   File
  "C:\Users\user\Anaconda3\envs\env1\lib\multiprocessing\pool.py", line
  119, in worker
      result = (True, func(*args, **kwds))   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\tsfresh\utilities\distribution.py",
  line 38, in _function_with_partly_reduce
      results = list(itertools.chain.from_iterable(results))   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\tsfresh\utilities\distribution.py",
  line 37, in
      results = (map_function(chunk, **kwargs) for chunk in chunk_list)   File
  "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\tsfresh\feature_extraction\extraction.py",
  line 358, in _do_extraction_on_chunk
      return list(_f())   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\tsfresh\feature_extraction\extraction.py",
  line 345, in _f
      result = func(data, param=parameter_list)   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\tsfresh\feature_extraction\feature_calculators.py",
  line 1752, in friedrich_coefficients
      coeff = _estimate_friedrich_coefficients(x, m, r)   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\tsfresh\feature_extraction\feature_calculators.py",
  line 145, in _estimate_friedrich_coefficients
      result.dropna(inplace=True)   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\pandas\core\frame.py",
  line 4598, in dropna
      result = self.loc(axis=axis)[mask]   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\pandas\core\indexing.py",
  line 1500, in getitem
      return self._getitem_axis(maybe_callable, axis=axis)   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\pandas\core\indexing.py",
  line 1859, in _getitem_axis
      if is_iterator(key):   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\pandas\core\dtypes\inference.py",
  line 157, in is_iterator
      return hasattr(obj, 'next')   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\pandas\core\generic.py",
  line 5065, in getattr
      if self._info_axis._can_hold_identifiers_and_holds_name(name):   File
  "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\pandas\core\indexes\base.py",
  line 3984, in _can_hold_identifiers_and_holds_name
      return name in self   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\pandas\core\indexes\category.py",
  line 327, in contains
      return contains(self, key, container=self._engine)   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\pandas\core\arrays\categorical.py",
  line 188, in contains
      loc = cat.categories.get_loc(key)   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\pandas\core\indexes\interval.py",
  line 770, in get_loc
      start, stop = self._find_non_overlapping_monotonic_bounds(key)   File
  "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\pandas\core\indexes\interval.py",
  line 717, in _find_non_overlapping_monotonic_bounds
      start = self._searchsorted_monotonic(key, 'left')   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\pandas\core\indexes\interval.py",
  line 681, in _searchsorted_monotonic
      return sub_idx._searchsorted_monotonic(label, side)   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\pandas\core\indexes\base.py",
  line 4755, in _searchsorted_monotonic
      return self.searchsorted(label, side=side)   File "C:\Users\user\Anaconda3\envs\env1\lib\site-packages\pandas\core\base.py",
  line 1501, in searchsorted
      return self._values.searchsorted(value, side=side, sorter=sorter) TypeError: Cannot cast array data from dtype('float64') to
  dtype('

np.version, tsfresh.version are ('1.15.4', 'unknown'). I installed tsfresh using conda, probably from conda-forge. I am on Windows 10. Using another kernel with np.version, tsfresh.version ('1.15.4', '0.11.2') lead to the same results.
Trying the first couple of cells from timeseries_forecasting_basic_example.ipynb yields the casting error as well.

A: Fixed it. Either the version on conda(-forge) or one of the dependencies was the issue. So using "conda uninstall tsfresh", "conda install patsy future six tqdm" and "pip install tsfresh" combined did the trick.