text:
Q: Re-evaluating sync source log entries when chainingAllowed = false We have recently upgraded our 3 member replica set from 3.0 to 3.2.9. Since the upgrade, we are seeing log entries like below periodically on one of the secondaries.
As per the rs.conf() output below, we having chainingAllowed = false and all secondaries are syncing from the primary so I would not expect to see these log entries.
Primary - mongodb01
Secondaries - mongodb02 & mongodb03
The log entries seem to show that the secondary mongodb02 is syncing from the other secondary mongodb03. So is the chainingAllowed setting being observed? Does anyone know why we are seeing these messages?
Thanks.
Log Entries
2016-09-06T08:51:12.029+0100 I REPL     [ReplicationExecutor] re-evaluating sync source because our current sync source's most recent OpTime is (term: -1, timestamp: Sep  6 08:50:35:1) which is more than 30s behind member mongodb03:27017 whose most recent OpTime is (term: -1, timestamp: Sep  6 08:51:11:1)
2016-09-06T08:51:12.029+0100 I REPL     [ReplicationExecutor] syncing from primary: mongodb01:27017
2016-09-06T08:51:12.034+0100 I REPL     [ReplicationExecutor] re-evaluating sync source because our current sync source's most recent OpTime is (term: -1, timestamp: Sep  6 08:50:35:1) which is more than 30s behind member mongodb03:27017 whose most recent OpTime is (term: -1, timestamp: Sep  6 08:51:11:1)
2016-09-06T08:51:12.034+0100 I REPL     [ReplicationExecutor] syncing from primary: mongodb01:27017
2016-09-06T08:51:12.041+0100 I REPL     [ReplicationExecutor] re-evaluating sync source because our current sync source's most recent OpTime is (term: -1, timestamp: Sep  6 08:50:35:1) which is more than 30s behind member mongodb03:27017 whose most recent OpTime is (term: -1, timestamp: Sep  6 08:51:11:1)
2016-09-06T08:51:12.042+0100 I REPL     [ReplicationExecutor] syncing from primary: mongodb01:27017
2016-09-06T08:51:12.049+0100 I REPL     [ReplicationExecutor] re-evaluating sync source because our current sync source's most recent OpTime is (term: -1, timestamp: Sep  6 08:50:35:1) which is more than 30s behind member mongodb03:27017 whose most recent OpTime is (term: -1, timestamp: Sep  6 08:51:11:1)
2016-09-06T08:51:12.049+0100 I REPL     [ReplicationExecutor] syncing from primary: mongodb01:27017

rs.conf()
mongodbrepl:SECONDARY> rs.conf()
{
        "_id" : "mongodbrepl",
        "version" : 32,
        "members" : [
                {
                        "_id" : 2,
                        "host" : "mongodb03:27017",
                        "arbiterOnly" : false,
                        "buildIndexes" : true,
                        "hidden" : false,
                        "priority" : 1,
                        "tags" : {

                        },
                        "slaveDelay" : NumberLong(0),
                        "votes" : 1
                },
                {
                        "_id" : 1,
                        "host" : "mongodb02:27017",
                        "arbiterOnly" : false,
                        "buildIndexes" : true,
                        "hidden" : false,
                        "priority" : 0,
                        "tags" : {

                        },
                        "slaveDelay" : NumberLong(0),
                        "votes" : 1
                },
                {
                        "_id" : 0,
                        "host" : "mongodb01:27017",
                        "arbiterOnly" : false,
                        "buildIndexes" : true,
                        "hidden" : false,
                        "priority" : 1,
                        "tags" : {

                        },
                        "slaveDelay" : NumberLong(0),
                        "votes" : 1
                }
        ],
        "settings" : {
                "chainingAllowed" : false,
                "heartbeatIntervalMillis" : 2000,
                "heartbeatTimeoutSecs" : 10,
                "electionTimeoutMillis" : 10000,
                "getLastErrorModes" : {

                },
                "getLastErrorDefaults" : {
                        "w" : 1,
                        "wtimeout" : 0
                }
        }
}

rs.status()
mongodbrepl:SECONDARY> rs.status()
{
        "set" : "mongodbrepl",
        "date" : ISODate("2016-09-06T08:24:13.763Z"),
        "myState" : 2,
        "term" : NumberLong(-1),
        "syncingTo" : "mongodb01:27017",
        "heartbeatIntervalMillis" : NumberLong(2000),
        "members" : [
                {
                        "_id" : 0,
                        "name" : "mongodb01:27017",
                        "health" : 1,
                        "state" : 1,
                        "stateStr" : "PRIMARY",
                        "uptime" : 412082,
                        "optime" : Timestamp(1473150251, 1),
                        "optimeDate" : ISODate("2016-09-06T08:24:11Z"),
                        "lastHeartbeat" : ISODate("2016-09-06T08:24:13.461Z"),
                        "lastHeartbeatRecv" : ISODate("2016-09-06T08:24:13.462Z"),
                        "pingMs" : NumberLong(0),
                        "electionTime" : Timestamp(1472738228, 1),
                        "electionDate" : ISODate("2016-09-01T13:57:08Z"),
                        "configVersion" : 32
                },
                {
                        "_id" : 1,
                        "name" : "mongodb02:27017",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 412280,
                        "optime" : Timestamp(1473150251, 1),
                        "optimeDate" : ISODate("2016-09-06T08:24:11Z"),
                        "syncingTo" : "mongodb01:27017",
                        "configVersion" : 32,
                        "self" : true
                },
                {
                        "_id" : 2,
                        "name" : "mongodb03:27017",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 412273,
                        "optime" : Timestamp(1473150251, 1),
                        "optimeDate" : ISODate("2016-09-06T08:24:11Z"),
                        "lastHeartbeat" : ISODate("2016-09-06T08:24:12.395Z"),
                        "lastHeartbeatRecv" : ISODate("2016-09-06T08:24:13.757Z"),
                        "pingMs" : NumberLong(0),
                        "syncingTo" : "mongodb01:27017",
                        "configVersion" : 32
                }
        ],
        "ok" : 1
}

A: It's hard to say without seeing all the logs, but I suspect you are seeing changes to your primary. The primary is listed in the log messages as primary: mongodb01 and it is (at the time syncing from mongodb03). It's the kind of thing I would expect to see if you were stepping down the primary (mongodb03), then locking it (or similar) that causes it to fall behind and mongodb02 notices and switches to the new primary (mongodb01).
Your status indicates that mongodb03 is once again the primary when you ran it, but the logs clearly show that mongodb01 has been the primary in the past.


text:
Q: Remove if the consecutive value appears at end in the group id I try to filter the group id which has at least two yes consecutively for the b column but it should be followed by at least one value in the column. I want to remove if the consecutive b==yes appears at end of b for the group id. The group id must start at first yes. for example in id 2, the first row must discard as its y value starts with no before two consecutive yes.
data<-data.frame(id=c(1,1,1, 1,2,2,2,3,3,3, 3,4,4,4, 5,5,5,5), a=c(1,1,1,1,1,2,1,1,2,2,1,1,1,2,1,1,1,2),
b=c("yes", "yes","no","no","no", "yes", "yes","no","yes","yes","no", "yes","yes","yes","yes","no","yes","yes" ))

Current output
-output:

   id a   b
  1 1 yes
  1 1 yes
  1 1  no
  1 1  no
  2 1  no
  2 2 yes
  2 1 yes
  3 1  no
  3 2 yes
  3 2 yes
  3 1  no
  4 1 yes
  4 1 yes
  4 2 yes
  5 1 yes
  5 1 yes
  5 1 no
  5 1 yes
  5 2 yes

The output should be:
   id a   b
  1 1 yes
  1 1 yes
  1 1  no
  1 1  no
  3 2 yes
  3 2 yes
  3 1  no
  4 1 yes
  4 1 yes
  4 2 yes

Current code attempt:
data1 <- data %>% group_by(id) %>%
  filter(any(with(rle(b == 'yes'), lengths[values] > 1)) ) %>%
  ungroup()

but I can't get the desired output.
anyone, please help me????????

A: I suggest the following:
library(dplyr)

data<-data.frame(id=c(1,1,1, 1,2,2,2,3,3,3, 3,4,4,4), a=c(1,1,1,1,1,2,1,1,2,2,1,1,1,2),
                 b=c("yes", "yes","no","no","no", "yes", "yes","no","yes","yes","no", "yes","yes","yes"))

data %>%
  group_by(id) %>%
  # create indicators for two consecutive 'yes'
  mutate(prev_b = lag(b, 1),
         two_yes = b == 'yes' & prev_b == 'yes') %>%
  # create indicators for starting 'no'
  mutate(ones = 1,
         position = cumsum(ones),
         prev_no = cumsum(ifelse(b == 'no', 1, 0)),
         leading_no = position == prev_no) %>%
  # create indicator for final record
  mutate(next_b = lead(b, 1),
         last_record = is.na(next_b)) %>%
  # combine indicators at group level
  mutate(group_end_two_yes = any(two_yes & last_record),
         group_leading_no = any(leading_no)) %>%
  # drop
  mutate(drop_group = group_end_two_yes & group_leading_no) %>%
  filter(!drop_group,
         !leading_no) %>%
  # select initial columns
  select(id, a, b)

redpajama_set_name: RedPajamaStackExchange


text:
Q: HazelCast: SqlPredicate issue I am new to using HazelCast. I have a map of key and value, value being a list of objects. I am trying to use SqlPredicate on the map to filter the values.
Code Snippet:
private void testHazelCast() {
    final Employee e1 = new Employee("A", 20, 30);
    final Employee e2 = new Employee("C", 25, 45);
    final Employee e3 = new Employee("B", 30, 35);
    final Employee e4 = new Employee("F", 35, 30);
    final Employee e5 = new Employee("E", 40, 40);
    final Employee e6 = new Employee(null, 40, 20);
    final Employee e7 = new Employee("F", 60, 55);

    List<Employee> employeeList_1 = new ArrayList<Employee>() {{add(e1);add(e2);}};
    List<Employee> employeeList_2 = new ArrayList<Employee>() {{add(e3);add(e4);add(e7);}};
    List<Employee> employeeList_3 = new ArrayList<Employee>() {{add(e5);}};
    List<Employee> employeeList_4 = new ArrayList<Employee>() {{add(e6);}};
    IMap<Integer, List<Employee>> map = hazelcast.getMap("employee");
    map.put(1, employeeList_1);
    map.put(2, employeeList_2);
    map.put(3, employeeList_3);
    map.put(4, employeeList_4);

    // EntryObject e = new PredicateBuilder().getEntryObject();
    // Predicate predicate_1 = e.get("name").equal("A");
    Predicate predicate = new SqlPredicate("name = A");
    Set<List<Employee>> employeeSet = (Set<List<Employee>>) map.values(predicate_1);
}

class Employee implements Serializable {
    String name;
    int age;
    int weight;

    public Employee(String name, int age, int weight) {
        this.name = name;
        this.age = age;
        this.weight = weight;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Name: " + name + ", ");
        sb.append("Age: " + age + ", ");
        sb.append("Weight: " + weight);
        return sb.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Employee employee = (Employee) o;

        if (age != employee.age) return false;
        if (weight != employee.weight) return false;
        if (!name.equals(employee.name)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = name.hashCode();
        result = 31 * result + age;
        result = 31 * result + weight;
        return result;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

}

While executing the above code, I am getting an exception:

Caused by: java.lang.IllegalArgumentException: There is no suitable accessor for 'name' on class 'class java.util.ArrayList'

Could you somebody let me know what exactly I am doing wrong. I understand that it's trying to find the "name" element in the List class.
Is there anyway that I can use SqlPredicate to filter the values ?
Thanks,
Rahul

A: A predicat is executed on each value of a map. In your example, your map has a Collection of Employee as values, so the predicat is executed on this collection.
Your predicat evaluate to "a collection with name = A" : This is not valid, because a collection doesn't have a name.
In Hazelcast 3.6, you have a notion of 'custom attribute' and ValueExtractor. You can :

*

*Create a class, which own a collection of employee

*Link this class to a ValueExtractor which collect the names of each employe in a custom attribute 'name'

see: http://docs.hazelcast.org/docs/3.6/manual/html-single/index.html#custom-attributes
Moreover, having a map of collection is not very efficient.


text:
Q: After creating Role with password in PostgreSQL, by default I am able to access some of the tables without granting select permission? Ex: I have tables Table_A, Table_B, Table_C
I have created Role(user) called Username
Create User username with password 'pwd'
Without granting select permission to username able to access some of the tables.

A: The tables (Table_A, Table_B, Table_C) which have created are in public schema, so without granting select permission we can able to access the tables.


text:
Q: Does Storybook support async imports? My Storybook is not scaling well with large numbers of components, so I was hoping I could asynchronously register stories with Storybook
The syntax I'd like to use is something like this
const storyRoot = storiesOf(`${CORE_COMPONENTS}/Charts`, module);

(async () => {
    const SomeComponent = await import('../SomeComponent.tsx');

    storyRoot.add('Area Chart', () => <SomeComponent data={data} />);
})();

But it tries to render the Promise, so you get an invariant violation and it crashes before it gets a chance to resolve.

A: You can lazy load components using the React Suspense API. However, it still gets loaded in the background. I'd prefer it only load the component when I click on the link in the sidebar. If anyone has a better solution, please post!
import React, {lazy, Suspense} from 'react';
const SomeComponent = lazy(() => import('./some-component'));
import { storiesOf } from '@storybook/react';

storiesOf('SomeComponent', module)
    .add('story', () => (
        <Suspense fallback={
Loading...
}>
            <SomeComponent />
        </Suspense>
    ));


text:
Q: CSS Gradient link text jumps on hover I am using gradient text color for my links on hover, however a strange jump effect is occurring ever since I added the css class. Whenever I hover the link it jumps like 2px-4px up.
When I remove the gradient color class all is normal again. Is there any fix to this? The custom code I added:
.bg-gradient-ligth {
  background-color: $white;
  background-image: linear-gradient(315deg, $white 0%, $ligth-grey 74%);
}

a {
  color:$green
}

a:hover {
  background: -webkit-linear-gradient($gradient1, $gradient2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.heading-gradient {
  background: -webkit-linear-gradient($gradient1, $gradient2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

The rest is just plain Bootstrap and theme CSS. Which worked fine before. By the way it also cuts off the text of a gradient h1 title at the bottom.


text:
Q: Using Google Maps API with AngularJS, map not show in center I am using Google Maps API in angularJS. I have multiple locations on the map.
Now I'm trying to view markers in the center of the map, but don't know where is I'm lacking the point.
Here is the code:
$scope.mapOptions = {
  zoom: 2,
  center: new google.maps.LatLng(29.3139962480007,47.9858316415248),
  mapTypeId: google.maps.MapTypeId.TERRAIN,
  styles:$scope.styles
}

$scope.map = new google.maps.Map(document.getElementById('modelmap'), $scope.mapOptions);
var infoWindow = new google.maps.InfoWindow();
$scope.markers = [];
$scope.infowindow = new google.maps.InfoWindow({
  content: '',
  maxWidth: 250
});
var createMarker = function (info){

  var marker = new google.maps.Marker({
    map: $scope.map,
    position: new google.maps.LatLng(info.latitude, info.longitude),
    title: info.address,
    icon: '/assets/Maps-Pin-Place-icon.png'
  });

  var content='

'+title+'

'+description+'
Address:'+info.address+'

Find out more
 '

  var compiledContent = $compile(content)($scope)

  google.maps.event.addListener(marker, 'click', (function(marker, content, scope) {
    return function() {
      scope.infowindow.setContent(content);
      scope.infowindow.open(scope.map, marker);
    };
  })(marker, compiledContent[0], $scope));

  $scope.markers.push(marker);
}
for (i = 0; i < data.length; i++){
  createMarker(data[i]);
}

Please help!

A: It seems you are looking for a fitBounds function to set a viewport, the following example shows how to center and zoom the map so that all markers are getting visible:
 var bounds = new google.maps.LatLngBounds();
 for (var i = 0; i < $scope.cities.length; i++) {
    var marker = createMarker(i);
    bounds.extend(marker.getPosition());
  }
  $scope.map.fitBounds(bounds);

Example

angular.module('map-example', [])
  .controller('MapController', function ($scope, $rootScope, $compile) {
    function initialize() {
      $scope.map = new google.maps.Map(document.getElementById('map'), {
        //zoom: 4,
        //center: { lat: -38.363, lng: 131.044 }
      });

      $scope.cities = [
        { title: 'Sydney', lat: -33.873033, lng: 151.231397 },
        { title: 'Melbourne', lat: -37.812228, lng: 144.968355 },
        {title: 'Perth', lat: -31.9546855,lng: 115.8350292},
        {title: 'Adelaide', lat: -34.9256374,lng: 138.583259}
      ];

      //create a single instance of Info  Window
      $scope.infowindow = new google.maps.InfoWindow({
        content: ''
      });
      //render markers
      var bounds = new google.maps.LatLngBounds();
      for (var i = 0; i < $scope.cities.length; i++) {
        var marker = createMarker(i);
        bounds.extend(marker.getPosition());
      }
      $scope.map.fitBounds(bounds);
    }

    var createMarker = function (idx) {
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng($scope.cities[idx].lat, $scope.cities[idx].lng),
        map: $scope.map,
        title: $scope.cities[idx].title
      });

      var content = '<button ng-click="showDetails(' + idx + ')" class="btn btn-primary"> Details</button>';
      var compiledContent = $compile(content)($scope)

      google.maps.event.addListener(marker, 'click', function () {
        $scope.infowindow.setContent(compiledContent[0]);
        $scope.infowindow.open($scope.map, marker);
      });

      return marker;
    };

    $scope.showDetails = function (index) {
      console.log(JSON.stringify($scope.cities[index]));
    };

    google.maps.event.addDomListener(window, 'load', initialize);
  });
html, body {
        height: 400px;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 400px;
      }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">


text:
Q: Nested transaction not rolling back I've got a nested transaction, where after an exception data ends up being in the database without it being committed by the outer transaction.
There are three insert statements, every time followed by an select statement. The second select statement throws the exception. And for some reason I currently can not explain the third statement ends up in the database.
If however the exception does not occur (either by removing the select statement or by removing the 0 in the input array) nothing is committed in the database which is the expected behavior.
First of all the small working example:
using (var transactionScope = new TransactionScope())
{
    var input = new[] {1, 0, 2 };

    foreach (var i in input)
    {
        using (SqlConnection cnn = new SqlConnection(connetionString))
        {
            cnn.Open();
            using (var tran = cnn.BeginTransaction())
            {
                var sql = "INSERT INTO [Test].[dbo].[Test] ([Timestamp] ,[Message]) VALUES ('" + DateTime.Now + "', 1 / " + i + ");";
                using (SqlCommand cmd = new SqlCommand(sql, cnn, tran))
                {
                    try
                    {
                        cmd.ExecuteNonQuery();
                        tran.Commit();
                    }
                    catch (Exception e)
                    {
                        tran.Rollback();
                    }
                }
            }
        }
    }
}

What am I missing?
I'm using SQL Server 2016 & C# 7


text:
Q: How to work with many to many relations in Zend\Db (Zend Framework 2) I have a ZF2 application that has database tables for posts and hash tags with a many-to-many relationship. The table definitions are:
CREATE TABLE `hash_tag` (
    `id` int(11) NOT NULL,
    `tag` varchar(255) NOT NULL
)

CREATE TABLE `post` (
    `id` int(11) NOT NULL,
    `text` varchar(255)NOT NULL,
    `addedOn` datetime NOT NULL
)

CREATE TABLE `post_hashtag` (
    `post_id` int(11) NOT NULL,
    `hashtag_id` int(11) NOT NULL
)

I've also created models following the patterns explained in the ZF2 documentation's user guide. The HashTag model is as follows:
namespace Application\Model;

use Application\Model\Post;

class HashTag
{
    public $id;
    public $tag;

    protected $posts = array();

    public function exchangeArray($data)
    {
        $this->id = empty($data['id']) ? null : $data['id'];
        $this->tag = empty($data['tag']) ? null : $data['tag'];
    }

    public function getPosts()
    {
        return $this->posts;
    }

    public function addPost(Post $post)
    {
        $this->posts[] = $post;
        return $this;
    }

}

While the guide gives a pretty good explanation of how to handle basic database models, I'm looking to do something a bit more complicated.
Basically, when I retrieve the hash tag records, I also want to retrieve their associated posts and somehow store them in each individual HashTag object. Doing a normal join query results in a new record for each hash tag AND its accompanying post, which doesn't really help. The documentation doesn't go into any detail about how to do this either, nor can I find anything on Google about it with any decent examples.
I've used Doctrine 2 in the past, and would normally continue to do so. However, I'm preparing for a new job, and my new employer uses Zend\Db. I'm basically doing this to get practice handling database operations without using Doctrine.

A: Had the same problem and i still dont know if my way is a good way to do but it works. I create a "Mapper"(Generic names ftw) for every Entity that need to work with m-m relations. Here some example:
class AddresseeMapper {

private $resultSet;

private $addresseeArray = array();
private $addreseeObjectsArray = array();

public function __construct($resultSet)
{
    $this->resultSet = $resultSet;
}

public function init()
{
    foreach($this->resultSet as $key => $result)
    {
        $addressee = array();

        if(!empty($this->addresseeArray[$result['AddresseeID']]))
        {
            $addressee = $this->addresseeArray[$result['AddresseeID']];
        }
        else
        {
            $addressee['id'] = $result['AddresseeID'];
            $addressee['documentID'] = $result['AddresseeDocumentID'];
            $addressee['communicationID'] = $result['AddresseeCommunicationID'];
            $addressee['addressID'] = (!empty($result['AddresseeAddressID'])) ? $result['AddresseeAddressID'] : null;
            $addressee['salutation'] = (!empty($result['AddresseeSalutation'])) ? $result['AddresseeSalutation'] : null;
            $addressee['tempEmail'] = (!empty($result['AddresseeTempEmail'])) ? $result['AddresseeTempEmail'] : null;

            if((!empty($result['ContactID'])) && $result['ContactID'])
            {
                $addressee['Contact'] = $this->setContact($this->resultSet);
            }

            if((!empty($result['MailingListID'])) && $result['MailingListID'])
            {
                $addressee['MailingList'] = $this->exchangeMailingList($result);
            }

        }
        $this->addresseeArray[$result['AddresseeID']] = $addressee;
    }
}

private function setContact($resultSet)
{
    $contactMapper = new ContactMapper($resultSet);
    $contactMapper->init();
    $contactMapper->serilizeObjects();

    return $contactMapper->getContact();
}

private function exchangeMailingList($result)
{
    $mailingList = new MailingList();
    $mailingList->exchangeArray($result);

    return $mailingList;
}

public function serilizeObjects()
{
    foreach($this->addresseeArray as $addresseeArray)
    {
        $addressee = new Addressee();
        $addressee = $this->loop($addresseeArray, $addressee);

        $this->addreseeObjectsArray[] = $addressee;
    }

}

private function loop($array, $object)
{
    foreach($array as $key => $value)
    {
        if(is_array($value) && is_object($object->$key))
        {
            $object->$key = $this->deepLoop($value, $object->$key);
        }
        elseif(is_array($object->$key))
        {
            foreach($value as $key2 => $value2)
            {
                array_push($object->$key, $value2);
            }
        }
        else
        {
            $object->$key = $value;
        }

    }

    return $object;
}

private function deepLoop($array, $object)
{
    foreach($array as $key => $value)
    {
        //var_dump($key);
        //var_dump($value);
        $object->$key = $value;
    }

    return $object;
}

public function getAddressees()
{
    return $this->addreseeObjectsArray;
}

public function getAddressee()
{
    foreach($this->addreseeObjectsArray as $addressee)
    {
        return $addressee;
    }

    return false;
}

}


text:
Q: Go Back button is not working when added a query param in ReactJs Let me introduce what I am doing which is causing the issue.
I have 3 routes in my React web application:

*

*"/" for home page.

*"/page2" for page2.

*"/page3" for page3.

Now what I am doing as soon as when I go on route "/page2", I push a query param in the URL to render the default tab in page2 making the URL as "/page2?activeTab=tabId". So in a brief, when I will try to go to "/page2" it will always make the URL as "/page2?activeTab=tabId".
Now the issue is when I land on Page2 for the first time and try to press back button on browser. I again and again re-renders page2. The reason is: Suppose I am on page2 for the first time and the URL will be as "/page2?activeTab=tabId". Now when I press back button, the browser removes the query param and renders the URL "/page2". So whenever the URL renders my code again turns it to "/page2?activeTab=tabId". Because of this I can't go back and stuck at the second page only.
I want help in this. How to eliminate or avoid this issue?

A: You can check the location search params, and if empty compute a new path URL and replace the current location in history.

*

*Check location search query

*If search query empty, construct new path URL with query string

*Redirect (replace) the current page so back button works

Using react-router-dom's useHistory and useLocation react hooks
const MyComponent = () => {
  const { replace } = useHistory();
  const { pathname, search } = useLocation();

  useEffect(() => {
    const tabId = <compute tab id>;
    const newPath = `${pathname}?activeTab=${tabId}`;
    if (!search) replace(newPath);
  }, [pathname, replace, search]);

  return (
    ...
  );
};

If not able to use the react hooks of react-router-dom, then you can decorate your component with the withRouter Higher Order Component and access the same values from the injected props.
const MyComponent = ({ history, location }) => {
  const { replace } = history;
  const { pathname, search } = location;

  useEffect(() => {
    const tabId = <compute tab id>;
    const newPath = `${pathname}?activeTab=${tabId}`;
    if (!search) replace(newPath);
  }, [pathname, replace, search]);

  return (
    ...
  );
};

export withRouter(MyComponent);

A: Using Redirect and Route you can solve this issue. Maybe following code snippet can help you.
  <Switch>
     <Redirect from='/page2' to='/page2?activeTab=tabId' />
     <Route path="/page2?activeTab=tabId" >
       <Page2 />
     </Route>
     //....
  </Switch>

Sandbox working example


text:
Q: Are driver global variables located in kernel process address space? Why can i access driver global varialbe both at kernel process(DriverEntry)
and in user processes (PreOperation io callbacks for instance).


text:
Q: Filter a List in Python With List Elements I have a following list
list = ['Bucket1', 'ranbuck0', 'ranbuck1', 'ranbuck2', 'ranbuck3', 'ranbuck4', 'ranbuck5', 'ranbuck6', 'ranbuck7', 'ranbuck8', 'ranbuck9']

Is there a way to filter this list and create a new list, where I have the  elements named with "ranbuck". I am not able to figure out the way how to iterate ranbuck1, ranbuck2 a append these in a list.
Thanks in Advance

A: You could use the list comprehension syntax of Python:
new_list = [_ for _ in list if 'ranbuck' in _]

Instead of the _s you could also introduce your own variable name for the temporary variable inside the list comprehension. Instead of 'ranbuck' in _ you could also write down another condition whether this element of the list should be in the new one or not.

A: You can use list comprehension as suggested by mxscho or filter:
source_list = ['Bucket1', 'ranbuck0', 'ranbuck1', 'ranbuck2',
               'ranbuck3', 'ranbuck4', 'ranbuck5', 'ranbuck6',
               'ranbuck7', 'ranbuck8', 'ranbuck9']

filtered_list = filter(lambda item: 'ranbuck' in item, source_list)

I renamed your initial 'list' to source_list, as list is a python builtin


text:
Q: How to solve S-IX deadlock without using the Snapshot isolation? Ok, I got an weird problem: I got two server-side api, one is to select data from A table; the Other one is to Insert new record to B table with part of the data and PK from first one. They should not have any problem to each other with the Usual actions.
Somehow, I detected someone which called my select and insert function at less than 0.005 sec on my SQL monitor, which caused S-IX deadlock. So I searched the Internet and found an solution that told me to enable the Snapshot isolation. But I tried it on my test DB(which its total size is about 223MB), that Alter Database command does not show any sight of finishing after 1 hour execution, so this is intolerable to execute it on the Production DB with such long Downtime(Which its data size is bigger than the Test one).
So my question is: Does anyone know the Other way to solve the S-IX deadlock?(Without lower the Throughput.)
P.S.: My DB is SQL Server 2008


text:
Q: How can I generate json specification file dynamically with open api in Angular? I have used Swgger ui like below code and now I want to create pet.json dynamically
export class AppComponent {
  ngOnInit() {
    SwaggerUI({
        domNode: document.getElementById('swagger-ui-item'),
        url: 'assets/pet.json'
      });
}

I have a list of APIs and when one of the APIs is selected, I want to display the Swagger page for that API only.

A: The url should point to an api definition like this: 'https://petstore.swagger.io/v2/swagger.json, or in case you host this one also in the angular app in assets, you could refer locally also.
check this out: https://stackblitz.com/edit/angular-swagger-ui-integration?file=src%2Fapp%2Fapp.component.ts


text: Q: prevent fabric from updating top/left after rotation Is it possible to keep fabric from updating an object's top/left after rotation? I have positioning code that depends on the objects top/left to be at the original coordinates. Would it be possible to have the object show as rotated and be selectable, but its movement based on an imaginary object at the position before rotation?


text:
Q: Brightness problem on Ubuntu 18.04 LTS I have read this question - Brightness problem on Ubuntu 18.04 and this is my set up -
 Linux gansub-OptiPlex-7050 4.15.0-38-generic #41-Ubuntu SMP Wed Oct 10 10:59:38 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

and this is my graphics card -
00:02.0 VGA compatible controller: Intel Corporation HD Graphics 630 (rev 04)

  *-display
   description: VGA compatible controller
   product: Intel Corporation
   vendor: Intel Corporation
   physical id: 2
   bus info: pci@0000:00:02.0
   version: 04
   width: 64 bits
   clock: 33MHz
   capabilities: pciexpress msi pm vga_controller bus_master cap_list rom
   configuration: driver=i915 latency=0
   resources: irq:126 memory:f6000000-f6ffffff memory:e0000000-efffffff ioport:f000(size=64) memory:c0000-dffff

Since yesterday I have screen flickering as well as screen dimness and occasional unable to boot problems. I did a diagnostics check and all tests turned out successful. What usually happens is that the screen starts to flicker, then dim itself and then dies. When I try to reboot it gets stuck. I did try
   ubuntu-drivers autoinstall

But the problem persists. Since there maybe so many approaches as per the answers available on this site I would like to know which approach I should take.
EDIT
I made the following change to /etc/default/grub and it is still flickering.
#GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_backlight=vendor"
GRUB_CMDLINE_LINUX=""

Based on this Q/A - Ubuntu 18.04 screen strobing here is the output of xrandr
Screen 0: minimum 320 x 200, current 1600 x 900, maximum 8192 x 8192
HDMI-1 disconnected (normal left inverted right x axis y axis)
DP-1 disconnected (normal left inverted right x axis y axis)
HDMI-2 disconnected (normal left inverted right x axis y axis)
DP-2 connected primary 1600x900+0+0 (normal left inverted right x axis y axis) 432mm x 236mm
 1600x900      60.00*+
 1280x1024     75.02    60.02
 1152x864      75.00
 1024x768      75.03    60.00
 800x600       75.00    60.32
 640x480       75.00    59.94
 720x400       70.08
 HDMI-3 disconnected (normal left inverted right x axis y axis)
 DP-3 disconnected (normal left inverted right x axis y axis)

So I am not sure whether I should change the refresh rate to stop the flickering.


text:
Q: Assert System.out/err in testcase I'm looking at porting an old junit4 extension to junit5 by creating an extension. One feature that I'm thus far failing on is to fail any test method that writes on System.out or System.err, and have the failure point to that specific test.
I tried using TestExecutionListener#reportingEntryPublished together with junit.jupiter.extensions.autodetection.enabled=true, and I get to that method, but it is AFAICT too late to actually change the status of the test to FAILED at this point. Or can I?
I started playing with BeforeAllCallback and AfterAllCallback and do redirects of out/err and assert on a string buffer instead. I could possibly be able to get that to work, but that seems like something that I would be likely to screw up and and up finding bugs years from now :) Our runner for junit4 does something like this, but it is really overcomplicated and I wouldn't wish it on anyone to try to maintain something similar.
Any way to do this nicely in junit5?

A: What I ended up doing was to create a class implementing BeforeEachCallback, AfterEachCallback and redirecting each of stderr/out during beforeEach to a custom printstream each that stores all the output received. Then during afterEach, I ask the printstream if it has received anything. If it has, then I throw AssertionError that the custom stream has generated based on a modified stacktrace from when the first print-call was made. Then resets out/err to the original streams.
This allows for some tricks to allow the output to be printed to the console without throwing an error and still flag the testcase as failed with a custom message about disallowing output.
There are some potential pitfalls in this solution as e.g. an error in one of my other extension classes that tries to call Logger will create some fishy cases. For our use case, it should be sufficient.
Due to my employer having a lot of hoops to jump through to be allowed to share code externally, I'm unfortunately unable to do so for anyone else needing to do the same thing, but should be able to figure out how to do it decently based on the above.


text:
Q: How to print another page with a button using ajax I wonder how to print another page without need to go the certain page that I need to print with a button.
I have a page called Receipts I already have Print button in it. On click to the print I want to print another page called Print.php which is there.
Here is my Ajax code:
        // Update bill status and print
        $(document).on('click', '.update_status', function(e){
            e.preventDefault();
            var ordernum=$(this).data("id");
            $.ajax({
                url:"pages/UpdateBillStatus.php",
                method:"POST",
                data:{ordernum:ordernum},
                success:function(data){
                    document.getElementById('status'+ordernum).innerHTML = data;

                    // This is the part that I wrote but it still open the Print.php page then print
                    var printWindow = window.open('http://localhost/LaLigaCafe/pages/Print.php?ordernum='+ordernum+'');
                    printWindow.print();
                }
            });
        });

So what I need is printing the page without need to going there just printing in my current page.
Thanks in advance guys.


text:
Q: Is npm install "--force" mandatory on latest version of node Context / Background :
I was using node version 16.10.0 using nvm . There was conflict between 2 packages so I resolved it with --force . Afterwards if just npm install was performed on same/other machine , it was working fine without throwing any conflict error.
Issue :
In the latest version of node . I am required to use npm install --force every time else it throws conflict error.
Right now I am trying to upgrade to latest node version (Tried with 18.12.1 / 18.13.0 / 19.6.0) . I performed above steps again  BUT here just npm install is not working , --force is required every time .
I tried to find the relevant doc to confirm "--force is must on every npm install" OR "conflicts resolution are not getting saved in package-lock.json" .


text:
Q: Visual editor not showing up I've faced one really annoying "bug" on my production website. I've recently migrated to a new hosting, things went fine, then this issue started showing up.
YES, I was googling for past 3 days in order to fix this issue, and not a single solution helped.
Problem:
When I try to edit some post, or try to add a new - I get no Visual editor, only the button Add Media is shown up.
I can not add text. Also, plain HTML editor doesn't work as well.
The whole thing looks like this:

What I've tried:

*

*Disabled plugins

*Switched theme Cleared cache & cookies

*Switched browser

*Repaired DB

*Enabled Debugging - no errors

*Checked logs - no issues with PHP

*Reinstalled the whole Control Panel

*Tried various solutions from WP forums -Nothing.

I believe it is somehow Control Panel related, because when I created a subdomain, ran the installation with the latest WP version - I faced the same issues.
Same version works with no prob's on my localhost.

*

*WP version: 4.7.2

*PHP 5.6

Any suggestion guys, I am really desperate..
EDIT:
For some reason - seems it is fixed now. I disabled all plugins, and enabled one by one while refreshing post page, checking does something breaks.
Not sure can this be considered as a fix, because I did the same couple of times.
Thanks for help!

A: I had the same problem and it was solved by following an advice found on https://wordpress.org/support/topic/visual-editor-missing-15/

*

*Go to the file wp-config.php

*Find the following line:

define('DB_HOST', 'xxxxxxxxxxxx');

*Right below the above line add this:

define('CONCATENATE_SCRIPTS', false);

A: Maybe you should change memory limit, because sometimes this give a White Screen as well. Often a problem when using woocommerce or lots of plugins.
Can be change this way, add rule to config.php
define( 'WP_MEMORY_LIMIT', '256M' );

A: Log into your WordPress dashboard. On the left-hand side, go to Users > Your Profile.
Uncheck the box beside "Disable the visual editor when writing". Click on "Save" at the bottom of the page.
If the check box was already disabled, check it and click on "Save" and the uncheck it and click on "Save".
This should solve the problem

A: First off, go to Users->Your Profile. And make sure that the box marked "Disable the visual editor when writing" at the top of the screen is not checked.
If that setting is correct, then your browser can help you identify JavaScript issues or conflicts. Do you have any Javascript errors in the console when looking at the editor page? This article can assist you in doing that diagnosis.

A: Please open your profile in your WordPress site dashboard and make sure that Disable the visual editor when writing checkbox is not checked.

A: 'Add Media' button is not working?
If you answer 'yes' take a look if jQuery is not loaded twice, if so, load one only or implement JQuery.noConflict().


text:
Q: bash script skipping section I have the following script:
#!/bin/bash

while true
  do "curl http://192.168.1.2/api/queue | grep -q $3"
    case ${PIPESTATUS[*]} in
      "0 1")
        echo "Queue is no longer in the queue." > /config/log.txt
        break;;
      "0 0")
        echo "Queue is still in the queue. Trying again in 5 minutes." > /config/log.txt
        sleep 5;;
      "7 1")
        echo "Server is unreachable. Trying again in 5 minutes." > /config/log.txt
        sleep 5m;;
    esac
  done

case $2 in
  testvalue1)
      curl -i --data "hashes=$3&category=testcat"  http://localhost:8082/command/setCategory
      ;;
  *)
      echo "Deleting $4." > /config/log.txt
      curl -i --data "hashes=$3" http://localhost:8082/command/deletePerm
      ;;
esac

There are two parts to the script. The first part queries a queue on on server and if the queue is empty moves on to the second part. The second part will check for a certain value and if it is there ti will issue a curl command, or if it is anything else it will issue another command.
The issue is that both the two sections of the script work fine as seperate scripts but not together. Once I combine them, the first part is skipped entirely, or so it seems. It is supposed to wait for the queue to be empty from the first part and then proceed to the second part but for some reason it is just going straight to the second part. I added those outputs to file and they never get created. Any ideas as to what is happening?


text:
Q: What's the difference between Abstract class and Virtual Class Hi I'm just confused on how to to use Abstract class and Virtual. Can't seem to find any difference between them and what are some scenarios where in it's applicable to use abstract or virtual.

A: tl;dr:
Practically speaking, there isn't much difference. Don't worry about it too much. I tend to use abstract more often.
long version
The difference has historically been quite subtle.

*

*Both virtual and abtract classes allow you to extend the class (i.e. create child classes that inherit non-private methods and variables)

*A virtual class can be instantiated directly, whereas an abstract class cannot

*Both virtual and abstract classes can contain virtual methods (virtual methods can have a default implementation that is inherited by child classes, whereas abstract methods can only be signatures, and must be implemented in child classes)

*Only abstract classes may contain abstract methods

In practice, I haven't seen much practical difference between the two. The abstract and virtual modifiers, in my mind, are more important for methods (as opposed to classes).
If you're going to use a class that's either abstract or virtual, I've found that I'm more likely to be using that class as more of a contract (i.e. when you use this class, we guarantee that variables a, b, and c will be available for use, along with methods x, y, and z), rather than a specialization that is used apart, distinctly, from its parent class.
This mostly comes down to the philosophy of object-oriented design that I have learned as part of my professional career. To put it into a single sentence: If you're relying on something having a specific implementation (i.e. you need to use a square or a rectangle instead of a more general parallelogram), then you can probably improve your solution.
The general idea is that by relying on contracts rather than implementations, your code is more resistant to change. Put another way, by relying on contracts, a change to a specific implementation of that contract is contained to one or two classes (as opposed to making a change in one class ending up requiring a change to many other classes).
So for that goal (relying on a contract more than an implementation), I find myself using abstract classes more often because I tend to want the consumers of my code to use specific, specialized implementations (to suit the task at hand) rather than a general "catch-all" implementation. To that end, abstract, with it's inability to be directly constructed, is more useful to me.

A: Abstract classes allow you to define "partial" classes. They implement some sort of algorithm that can be used by other classes, but do not represent a full implementation by themselves. For example, my AWS example provides a class that handles calculating parameters, etc (over 200 lines of default functionality), but does not directly do anything with AWS; the remainder is handled by child classes to connect to a specific service. Note that abstract classes could be implemented by interfaces or helper classes, but make the code more compact and generally legible.
Virtual classes allow you to define "full" classes. They implement all of the necessary functionality to operate on their own, but can be extended by child classes in order to allow customization of its behavior. This is far less common in every day Apex Code than abstract classes, but is useful when you have large classes that provide tons of default functionality, but may require overriding just one or two methods. In Java, these are used all over the place, for example, a WindowAdapter that can listen to about a dozen events, but can have just one method overridden so the developer doesn't have to write implementations for all of the methods.
Unlike interfaces and abstract methods, virtual classes allow you to override just one single method if you want, without having to implement all of the methods. For example, a Trigger Handler factory might use a virtual class to provide default methods (e.g. beforeInsert, afterInsert, beforeUpdate...), but allow the developer to override just one method instead of a dozen.

A: The Apex Class Definition resource from the Apex Developer Guide may provide some illumination.
In summary, virtual classes permits subclassing and method overriding. However, a virtual class does implement functionality itself and can be instantiated and used directly.
Conversely, abstract classes must be subclassed and have methods overridden to provide functionality. abstract classes cannot be instantiated or used themselves; they are more fully "abstract base classes".

A: I see that is quite an old thread, but I have some brief descriptions, which can be helpful for future use.
Interface

*

*To create an interface we need to use interface keyword.

*Interface can
provide a layer of abstraction to your code.

*Interface is an apex
the class that can contain only method signature, as a result, the body
of each method must be empty.

*An apex class that is using the
interface must implement all methods listed in the interface.

*Interface separates the specific method declaration from its
implementation. Therefore you can have different implementations for
the same method. The concept behind Interface is that you can change
the implementation without changing your whole code. Consequently, the method
signature (return type, parameters) is always the same.

*Interface
can be treated as a new data type. In Apex we have a few predefined
interfaces like String, Integer, Double, etc. In other words
implementation of those methods can be changed (by Salesforce) without
changes in our code – that's the power of interface! e.g.:
String.isBlank('Test'); We know method signature (public static
Boolean isBlank(String inputString)), but we don't know
implementation layer.

Abstract

*

*To create an abstract class, we need to use an abstract definition modifier.

*Allow extending the child's class.

*Abstract class can contain methods signed as abstract, to clarify, it is a method that has only a signature (body is not defined).

*Child class must implement all methods declared as abstract!

*Abstract class can also include other methods, which have logic.
To allow child class access those methods use protected or public keywords.

*Cannot be initialize directly: new TestAbstractClass();

*Abstract class can contain both virtual and abstract methods.

*Abstract class is some kind of "partial" class.
Therefore, some methods are implemented, and some needs to be implemented by the child class.

*virtual methods can be overridden, but this is not mandatory.

Virtual

*

*To create a virtual class, we need to use a virtual definition modifier.

*You can extend a class to provide more sophisticated behavior.

*Class that extends another class inherits all the methods and properties of the extended class.

*Methods declared as virtual can be overridden.
In other words, overriding a virtual method allows you to provide a different implementation for an existing method.

*A class can only extend one other class, but it can implement more than one interface.

*Virtual class can be initialize directly new TestVirtualClass();

*You can use virtual or regular methods.

*Virtual class is some kind of "full" class.
All methods are implemented but can be overridden by the child class.

Feature
Interface
Abstract
Virtual

Keyword
interface  e.g public interface MyInterface {}
abstract  e.g public abstract class MyAbstractClass {}
virtual  e.g public virtual class MyVirtualClass {}

How to use?
By implements  e.g public class MyChildClass implements MyInterface {}
By extends  e.g public class MyChildClass extends MyAbstractClass {}
By extends  e.g public class MyChildClass extends MyVirtualClass {}

Type of Methods
Only method signature  e.g String getFullName(String firstName, String lastName);
Can contains abstract, virtual and implements own methods.  e.g abstract String getFullName(String firstName, String lastName);  public virtual String getFullName(String firstName, String lastName);
Can contains only virual and implements onw methods  e.g public virtual String getFullName(String firstName, String lastName);

Implement Parent Mehthods
✅ All interface's methods needs to be implemented
✅ Only methods signed as abstract
❌ Cannot force child class to implements parent methods

Override Parent Methods
❌ Interface doesn't contain logic to override
✅ Only methods signed as virtual
✅ Only methods signed as virtual

Has basic logic?
❌ Interface contains only method signature
✅ Methods signed as virual and inner methods can contain basic logic
✅ Methods signed as virual and inner methods can contain basic logic

Can be initialized directly?
❌ new MyInterface();
❌ new MyAbstractClass();
✅ new MyVirtualClass();

Pros
✅ New layer of abstraction.  ✅ Interface can be treated as a new data type.  ✅ Logic behind the interface can be changed without changes in related classes.  ✅ We program to interfaces, not implementations. Code doesn't have reference to specific classes.  ✅ Child class is forced to implement the interface's method (Guarantee specific logic).  ✅ Child class can implement many interfaces.
✅ Abstract class can store common logic (avoid redundancy) ✅ Child class can be forced to implement some (signed as abstract) methods.  ✅ Child class can override some (signed as virtual) methods.  ✅ Basic logic can be provided by abstract class inner methods. (private, protected, public)  ✅ Easy to update common code for all child methods. Just update code in abstract class.
✅ virtual class can be treated as a base class with base logic, which should be accessed by all child classes.  ✅ Virtual class can be initialized direct  ✅ Child class can override some (signed as virtual methods)  ✅ Easy to update common code for all child method. Just update code in a virtual class.  Basic logic can be provided by abstract class inner methods. (private, protected, public)

Cons
❌ Hard to add or change the interface's methods, because all classes that implement the interface need to be changed as well.  ❌ Apex class needs to implement all interface methods even if it's not relevant.
❌ Cannot be initialized directly.  ❌ Apex class needs to implement all abstract methods even if it's not relevant.  ❌ Child class can be only extended by one parent class.
❌ Cannot force child class to implement parent method (abstract cannot be used)  ❌ Child class can be only extended by one parent class.

Goal
To create a new layer of abstraction
To provide a kind of "partial" class with common logic
To provide a kind of "full" class with base logic

More details, examples of usage, and use cases can find
https://beyondthecloud.dev/blog/abstract-virtual-interface-in-apex


text:
Q: OroCRM DataAudit: how to show properties labels instead of properties names in "Changes history" window? As i saw in examples and my custom bundles - there are only changed properties names and values in "Change history" modal window.
It looks terrible when user see "mainAdditionalContract" but not "Additional contract" (taken from the "crm.agreement.additional_contract.label" translation file)
Is there any solution to provide properties labels to dataAudit? Through annotations or any another way?

A: I doubt that this is still relevant, but for sake of others looking for the answer here's mine:
DataAudit relies heavily on __toString() implementation for setting AuditField names.
I believe you should implement __toString method in your entities in order for them to be correctly displayed in grid.


text:
Q: Display only content from one category in two rows / columns How do you get only certain entries to show from one category I want to have two columns with two sets of entries both from different categories, I'm also trying to get one to show 10 posts the other 5 any idea's?.
Here is my current code :
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

<?php if ( has_post_thumbnail() ) { /* loades the post's featured thumbnail, requires Wordpress 3.0+ */ echo '
'; the_post_thumbnail(); echo '
'; } ?>

<?php the_time('F j, Y'); ?>

<?php comments_popup_link('No Comments', '1 Comment', '% Comments'); ?>

<a href="<?php the_permalink() ?>" class="blue" title="<?php the_title(); ?>" rel="bookmark"><?php the_title(); ?>

<?php the_excerpt(); ?>

<?php endwhile; ?>

A: http://codex.wordpress.org/Template_Tags/get_posts
$args = array(
    'numberposts' => [5 or 10],
    'category' => [name, slug, whatever]
);

$posts = get_posts()
foreach($posts as $post){
    setup_postdata($post);
    // the rest of your code here
}


text:
Q: Git ignore all files except particular ones I have a lot of files in directory which i wouldn't like them to be tracked by git. So i want to ignore all files except .bashrc, .gitignore and .config/terminator/config for example.
I'm trying to do something like this in .gitignore:
*
!.gitignore
!.bashrc
!.config/terminator/config

.bashrc and .gitignore files are unignored now but still cannot get .config/terminator/config unignored. How can i do this in git?
I have one possible solution but is there more elegant one without specifying subdirectories?
*
!.gitignore
!.bashrc
!.gitconfig

!.config/
!.config/terminator/
!.config/terminator/config

A: The short version of the answer is that once Git has ignored some directory, it proceeds not to bother to look inside that directory unless something else already forces it to do so.1  To stop this, you must explicitly list the directory or directories that you don't want ignored, with ! entries:
*
!/.bashrc
!/.config
!.config/terminator
!.config/terminator/config
!/.gitignore

That is:
*

tells Git: ignore everything unless overridden.  Then the eventual:
!.bashrc

overrides the ignore rule for .bashrc, and so on.  But what Git does is that it starts by reading . to find all entries.  Suppose it finds them in alphabetical order: .bashrc, .config, .editorthing, .gitignore, .history, and so on; and suppose we have your original .gitignore file:

*

*Hm, I see .bashrc, let's check on it... ah, line 1 says ignore but 3 says don't, so don't ignore.  Result: not ignored.

*Now I see .config, let's check on that.  Line 1 says ignore, line 2 is about .gitignore, line 3 is about .bashrc, and line 4 says to keep .config/terminator/config. It's not any of those, so line 1 applies!  Result: ignored!

*Repeat as above.

Arguably, the action in step 2 is idiotic: it's clearly impossible to apply the long rule if the shorter .config is ignored, so the presence of .config/<something> as un-ignored ought to trigger Git to un-ignore .config.  And in fact, the newest versions of Git try to be more clever about this, but older ones don't: you must explicitly un-ignore .config (or /.config, which is better here for reasons I won't get into, but that's why I wrote it that way above2).
There is a more elegant trick but it causes Git to be much slower, so you may not want to use it.  The trick is to explicitly un-ignore all directories:
*
!*/
!/.bashrc

and so on.  But now if you have a directory a with millions of sub-directories and files within a, Git will scan all a and all its subdirectories, whereas before, it would skip it.

1Having a file within .config in the index forces Git to scan .config.  However, you'd then run into the same issue with .config/terminator unless the index contained a file within .config/terminator as well.
2OK, I will get into it a little bit.  It does not apply in this particular case, but assuming you are un-ignoring .bashrc, if Git were for some reason to scan a/, and a/ contained a file named .bashrc, Git would not ignore a/.bashrc.  We do not need the leading slash on .config/terminator, though, because that contains an embedded slash (one not at the end).  This makes the match on that name rooted, while matches on .bashrc are non-rooted and hence match a/.bashrc.


text:
Q: Why should I prefer HTTP REST over HTTP RPC JSON-Messaging style in conjunction with CQRS? Every time I read about how web service should communicate the first thing that comes up is:

Use REST, because it decouples client and server!

I would like to build a web service where each Query and Command is an Http-Endpoint. With REST I would have fewer endpoints, because of its nature of thinking of resources instead of operations (You typically have more operations than resources).

*

*Why do I have a stronger coupling by using RPC over REST?

*What is the benefit of using REST over RPC Json-Messaging style?

Additional information: With messaging I mean synchronous messaging (request/response)
Update: I think it would be also possible/better to only have one single Http endpoint that can handle a Query or Command depending on the given Http verb.

A: Before I get to the CQRS part, I'd like to spend a little time talking about the advantages and disadvantages of REST. I don't think it's possible to answer the question before we've established a common understanding of when and why to use REST.
REST
As with most other technology options, REST, too, isn't a silver bullet. It comes with advantages and disadvantages.
I like to use Richardson's Maturity Model, with Martin Fowler's additional level 0, as a thinking tool.
Level 0
Martin Fowler also calls level 0 the swamp of POX, but I think that what really distinguishes this level is simply the use of RPC over HTTP. It doesn't have to be XML; it could be JSON instead.
The primary advantage at this level is interoperability. Most system can communicate via HTTP, and most programming platforms can handle XML or JSON.
The disadvantage is that systems are difficult to evolve independently of clients (see level 3).
One of the distinguishing traits of this style is that all communication goes through a single endpoint.
Level 1
At level 1, you start to treat various parts of your API as separate resources. Each resource is identified by a URL.
One advantage is that you can now start to use off-the-shelf software, such as firewalls and proxy servers, to control access to various distinct parts of the system. You can also use HTTP redirects to point clients to different endpoints, although there are some pitfalls in that regard.
I can't think of any disadvantages, apart from those of level 0.
Level 2
At this level, not only do you have resources, but you also use HTTP verbs, such as GET, POST, DELETE, etc.
One advantage is that you can now begin to take more advantage of HTTP infrastructure. For instance, you can instruct clients to cache responses to GET requests, whereas other requests typically aren't cacheable. Again, you can use standard HTTP firewalls and proxies to implement caching. You can get 'web-scale' caching for free.
The reason that level 2 builds on level 1 is that you need each resource to be separate, because you want to be able to cache resources independently from each other. You can't do this if you can't distinguish various resources from each other, or if you can't distinguish reads from writes.
The disadvantage is that it may involve more programming work to implement this. Also, all the previous disadvantages still apply. Clients are tightly coupled to your published API. If you change your URL structure, clients break. If you change data formats, clients break.
Still, many so-called REST APIs are designed and published at this level, so in practice it seems that many organisations find this a good trade-off between advantages and disadvantages.
Level 3
This is the level of REST design that I consider true REST. It's nothing like the previous levels; it's a completely different way to design APIs. In my mind, there's a hard divide between levels 0-2, and level 3.
One distinguishing feature of level 3 is that you must think content negotiation into the API design. Once you have that, though, the reasons to choose this API design style become clearer.
To me, the dominant advantage of level 3 APIs is that you can evolve them independently of clients. If you're careful, you can change the structure, even the navigation graph, of your API without breaking existing clients. If you need to introduce breaking changes, you can use content negotiation to ensure that clients can opt-in to the breaking change, whereas legacy clients will keep working.
Basically, when I'm asked to write an API where I have no control over clients, my default choice is level 3.
Designing a level 3 REST API requires you to design in a way that's unusual and alien to many, so that's a disadvantage. Another disadvantage is that client developers often find this style of API design unfamiliar, so they often try to second-guess, or retro-engineer, your URL structure. If they do, you'll have to expend some effort to prevent them from doing that as well, since this will prevent you from being able to evolve the API.
In other words, level 3 APIs require considerable development effort, particularly on the server-side, but clients also become more complex.
I will, though, reiterate the advantage: you can evolve an level 3 REST API independently of clients. If you don't control clients, backwards compatibility is critical. Level 3 enables you to evolve APIs while still retaining compatibility. I'm not aware of a way you can achieve this with any of the other styles.
CQRS
Now that we've identified some advantages and disadvantages of REST, we can start to discuss whether it's applicable to CQRS.
The most fundamental agreement between Greg Young and Udi Dahan concerning CQRS is that it's not a top-level architecture.
In a nutshell, the reason for this is that the messages (commands and events) and queries that make up a CQRS system are sensitive to interpretation. In order to do something, a client must know which command to issue, and the server must know how to interpret it. The command, thus, is part of the system.
The system may be distributed across clients and servers, but the messages and data structures are coupled to each other. If you change how your server interprets a given message, that change will impact your clients. You can't evolve clients and servers independently in a CQRS architecture, which is the reason why it's not a top-level architecture.
So, given that it's not a top-level architecture, the transport architecture becomes fairly irrelevant. In a sense, the only thing you need in order to send messages is a single 'service bus' endpoint, which could easily be a level 0 endpoint, if all you need is interoperability. After all, the only thing you do is to put a message on a queue.
The final answer, then, is, as always: it depends.
Is speed of delivery the most important criterion? And can you control all clients and servers at the same time? Then, perhaps level 0 is all you need. Perhaps level 2 is fine.
On the other hand, if you have clients out of your control (mobile apps, hardware (IoT), business partners using your public API, etc.), you must consider how to deal with backwards and forwards compatibility, in which case level 3 is (IMO) required. In that case, though, I'd suggest keeping CQRS an implementation detail.

A: The best answer would probably be "it depends", but one of the big things about real REST is that it is stateless. And it being stateless means all sorts of things.
Basically, if you look at the HATEOAS constraint you have the reason for the decoupling 1
I think that RPC-JSON is not statefull per se, but it definately is not defined as stateless. So there you have the strongest argument of why the decoupling is very high with REST.
1: https://en.wikipedia.org/wiki/HATEOAS , http://restfulapi.net/hateoas/


text:
Q: What's wrong on passing this double pointer and get the value? I'm new/noob programmer of C++, and I've this problem. I want to pass a pointer of double to a function (which will process some data on it) and read (after the process) a fixed value of that "array". I've do this:
void ReadDoubles(double* samples, int size)
{
    for (int i=0; i < size; ++i)
    {
        *samples = i*10.1;
        samples++;
    }
}

int main()
{
    int size = 10;
    double *values=0;
    ReadDoubles(values, size);
    cout << *(values+3);
}

BUt of course it seems I can't init the pointer that way. I think I need to init the pointer allocating 10 values? Tried:
double *values[size];

but that's not the solution. How would you do this simple task?

A: You need to allocate the array at first. Here you are
#include <iostream>

void ReadDoubles( double* samples, size_t size )
{
    for ( size_t i = 0; i < size; ++i )
    {
        *samples = i*10.1;
        samples++;
    }
}

int main()
{
    size_t size = 10;
    double *values = new double[size];
    //               ^^^^^^^^^^^^^^^^

    ReadDoubles( values, size );

    std::cout << *(values+3) << std::endl;

    delete []values;
}

The program output is
30.3

If you don't want to use the operator new then there are two general approaches. Either you can declare an array as for example
int main()
{
    const size_t size = 10;
    //^^^^
    double values[size];
    //     ^^^^^^^^^^^^

    ReadDoubles( values, size );

    std::cout << *(values+3) << std::endl;
}

or you can use standard class std::vector<double>.In this case the function should be rewritten appropriately.
For example
#include <iostream>
#include <vector>

void ReadDoubles( std::vector<double> &samples, size_t size )
{
    samples.resize( size );

    for ( size_t i = 0; i < size; ++i )
    {
        samples[i] = i*10.1;
    }
}

int main()
{
    size_t size = 10;
    std::vector<double> values;

    ReadDoubles( values, size );

    std::cout << values[3] << std::endl;
}

A: If you are not allowed to change the RealDoubles function and you must have a function return the size then the following should work:
#include <string>
#include <iostream>
#include <math.h>
#include <cmath>

using namespace std;

void ReadDoubles(double* samples,int size)
{
    for (int i=0; i < size; ++i) {
        *samples = i*10.1;
        samples++;
    }
}

int get_size()
{
    return 10;
}

int main()
{
    int size = get_size(); // get size from function
    //double *values=0;
    double *values = new double[size] {0}; // Use new to allocate array. Optional: use {0} to init first element to 0, others default initialized to 0
    ReadDoubles(values,size);
    cout << *(values+3);
    delete[] values;
}

If you prefer to avoid new and delete then you can let a std::vector manage the container for you:
#include <string>
#include <iostream>
#include <math.h>
#include <cmath>
#include <vector>

using namespace std;

void ReadDoubles(double* samples,int size)
{
    for (int i=0; i < size; ++i) {
        *samples = i*10.1;
        samples++;
    }
}

int get_size()
{
    return 10;
}

int main()
{
    int size = get_size(); // get size from function
    //double *values=0;
    std::vector<double> value_container(size,0); // vector will do the new and delete for us
    double *values = value_container.data();
    ReadDoubles(values,size);
    cout << *(values+3);
} // vector destructor will do delete when it goes out of scope


text:
Q: Как обернуть цикл в условие? Лимит цикла Вроде бы простая задача но я буквально не вижу синтетических ошибок так как совсем юнец. Буду рад комментариям заранее.
Вот простой цикл:

*

*1.Берет список из текст файла.
2.Выбирает один элемент из списка.
3.Вставляет его в другой текст файл.

import pyautogui

f = open(r"C:\Users\Alphabets\Desktop\Python local\readme.txt", "r")

def func():
    pyautogui.click(1362, 476)
    for i in f:
        pyautogui.hotkey('enter')
        i = i.split(":")[0]
        pyautogui.typewrite(i)
        pyautogui.PAUSE = .5

func()

Нужно обернуть в условие которое остановит исполнение цикла. Например после 5 итераций.
Так выдает 3 итерации первого элемента.
Необходимо 3 раза по порядку списка
import pyautogui

f = open(r"C:\Users\Alphabets\Desktop\Python local\readme.txt", "r")

def func():
    pyautogui.click(1362, 476)
    count = 0
    for i in f:
        while count < 3:
            pyautogui.hotkey('enter')
            i = i.split(":")[0]
            pyautogui.typewrite(i)
            pyautogui.PAUSE = .5
            count += 1
func()

A: Можно использовать enumerate:
import pyautogui

f = open(r"C:\Users\Alphabets\Desktop\Python local\readme.txt", "r")

def func():
    pyautogui.click(1362, 476)
    for n, i in enumerate(f, 1):
        pyautogui.hotkey('enter')
        i = i.split(":")[0]
        pyautogui.typewrite(i)
        pyautogui.PAUSE = .5
        if n == 5:
            break

func()


text:
Q: Changing the BabbleTimeout and EndSilence Timeout in the Microsoft.ProjectOxford.SpeechRecognition Object I create the object like so:
Dim WithEvents m As Microsoft.ProjectOxford.SpeechRecognition.MicrophoneRecognitionClient

I load it like so:
m = SpeechRecognitionServiceFactory.CreateMicrophoneClient(SpeechRecognitionMode.LongDictation, "en-us", Key, Key2)

How do I adjust the silenceTimeout for the dictation?
It's default is like 15-20 seconds which is WAY too long.
Shortphrase doesn't work with what I'm looking to do which is to create a natural sounding conversation between the recognizer and the user.

A: Currently we do not have a way to do this in current SDK


text:
Q: How to get form data from HTML page using c++ How do I get form data from HTML page using c++, as far as the basics of post and get?
EDIT: CGI is using apache 2 on windows, I got c++ configured and tested with with apache already.

A: The easiest way to access form data from an HTTP request is via CGI. This involves reading environment variables which is done using the getenv function.

A: First of all take a look at webtoolkit.
You might want to use that to make your life easier.
Second you can read about network protocols.
Third take a look at your webserver docs, they might provide such interface to create a deamon that will allow you to read the HTTP socket and the data that is sent over it.
On another note next time you write a question try to elaborate as much as possible.
Explain the use case and provide a test case.

A: You may use CgiCC library that gives you want you are looking for. You may also try some C++ web framework like CppCMS.


text:
Q: Is EBS naturally CPU-hungry? We have an m1.medium EC2 instance with a small (15G) EBS drive, running both Rails 3 and a PostgreSQL server.  We've noticed CPU spikes at odd times, and finally realized that even simple, sustained EBS access seems to pin the CPU.  For instance, just grepping about 3G of logs resulted in 100% CPU usage - which means both cores, which should be impossible for grep!  Deleting a bunch of log files also used about 25% of the CPU, which is more than I'd expect. We're not swapping.
Is this normal? It's hard to Google for this, since "high CPU" is also the name of a type of EC2 instance.  I'll happily provide more details and benchmarks, but first I wanted to check if this was a thing.

A: Performance of EBS volumes can be affected by things like:

*

*New EBS volumes have a first-use penalty, even if they are created from an EBS snapshot. The first time you read or write to each block on the volume will take much longer than subsequent hits.

*When an EBS snapshot has been initiated, the EBS volume may experience high iowait when you try to write to a block that has not yet been copied to the S3 snapshot storage.

*EBS volumes use network bandwidth on the instance.  You may get better IO performance and reduced CPU iowait if you upgrade to a larger instance type.
Here's an article I wrote about the lazy-load of EBS volumes from snapshots:

Identifying When a New EBS Volume Has Completed Initialization From an EBS Snapshot
http://alestic.com/2010/03/ebs-volume-initialization-from-snapshot

Here's an article I wrote describing why we had to move our EBS snapshots to a slave database instead of running them on the master:

EBS Snapshots of a MySQL Slave Database on EC2
http://alestic.com/2009/08/ec2-mysql-slave-snapshot

A: It's likely that nearly all of the CPU time spent during the grep you mention was due to iowait. Run top in another terminal during the grep and watch the %wa value. That value is the amount of time being spent waiting for IO to complete.
It's a well-known and well-discussed fact that EBS volumes perform quite poorly when it comes to IO. This is why many organizations will bond several EBS vols together via RAID (usually RAID 0, but possibly other levels may be useful as well) to increase performance.


text:
Q: Problem with text extraction from pdf using nodejs server and reactjs webpage The following below is my code for textractUtils.js -
const _ = require("lodash");
const aws = require("aws-sdk");
const config = require("./config");

aws.config.update({
  accessKeyId: config.awsAccesskeyID,
  secretAccessKey: config.awsSecretAccessKey,
  region: config.awsRegion
});

const textract = new aws.Textract();

const getText = (result, blocksMap) => {
  let text = "";

  if (_.has(result, "Relationships")) {
    result.Relationships.forEach(relationship => {
      if (relationship.Type === "CHILD") {
        relationship.Ids.forEach(childId => {
          const word = blocksMap[childId];
          if (word.BlockType === "WORD") {
            text += `${word.Text} `;
          }
          if (word.BlockType === "SELECTION_ELEMENT") {
            if (word.SelectionStatus === "SELECTED") {
              text += `X `;
            }
          }
        });
      }
    });
  }

  return text.trim();
};

const findValueBlock = (keyBlock, valueMap) => {
  let valueBlock;
  keyBlock.Relationships.forEach(relationship => {
    if (relationship.Type === "VALUE") {
      // eslint-disable-next-line array-callback-return
      relationship.Ids.every(valueId => {
        if (_.has(valueMap, valueId)) {
          valueBlock = valueMap[valueId];
          return false;
        }
      });
    }
  });

  return valueBlock;
};

const getKeyValueRelationship = (keyMap, valueMap, blockMap) => {
  const keyValues = {};

  const keyMapValues = _.values(keyMap);

  keyMapValues.forEach(keyMapValue => {
    const valueBlock = findValueBlock(keyMapValue, valueMap);
    const key = getText(keyMapValue, blockMap);
    const value = getText(valueBlock, blockMap);
    keyValues[key] = value;
  });

  return keyValues;
};

const getKeyValueMap = blocks => {
  const keyMap = {};
  const valueMap = {};
  const blockMap = {};

  let blockId;
  blocks.forEach(block => {
    blockId = block.Id;
    blockMap[blockId] = block;

    if (block.BlockType === "KEY_VALUE_SET") {
      if (_.includes(block.EntityTypes, "KEY")) {
        keyMap[blockId] = block;
      } else {
        valueMap[blockId] = block;
      }
    }
  });

  return { keyMap, valueMap, blockMap };
};

module.exports = async buffer => {
  const params = {
    Document: {
      /* required */
      Bytes: buffer
    },
    FeatureTypes: ["FORMS"]
  };

  const request = textract.analyzeDocument(params);
  const data = await request.promise();

  if (data && data.Blocks) {
    const { keyMap, valueMap, blockMap } = getKeyValueMap(data.Blocks);
    const keyValues = getKeyValueRelationship(keyMap, valueMap, blockMap);

    return keyValues;
  }

  // in case no blocks are found return undefined
  return undefined;
};

It is working fine with images but not with pdf(neither single nor multi-page). The following is the error when I run it by importing pdf-
(node:2001) UnhandledPromiseRejectionWarning: UnsupportedDocumentException: Request has unsupported document format
    at Request.extractError (/home/<user>/textract-lab/node_modules/aws-sdk/lib/protocol/json.js:51:27)
    at Request.callListeners (/home/<user>/textract-lab/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
    at Request.emit (/home/<user>/textract-lab/node_modules/aws-sdk/lib/sequential_executor.js:78:10)
    at Request.emit (/home/<user>/textract-lab/node_modules/aws-sdk/lib/request.js:683:14)
    at Request.transition (/home/<user>/textract-lab/node_modules/aws-sdk/lib/request.js:22:10)
    at AcceptorStateMachine.runTo (/home/<user>/textract-lab/node_modules/aws-sdk/lib/state_machine.js:14:12)
    at /home/<user>/textract-lab/node_modules/aws-sdk/lib/state_machine.js:26:10
    at Request.<anonymous> (/home/<user>/textract-lab/node_modules/aws-sdk/lib/request.js:38:9)
    at Request.<anonymous> (/home/<user>/textract-lab/node_modules/aws-sdk/lib/request.js:685:12)
    at Request.callListeners (/home/<user>/textract-lab/node_modules/aws-sdk/lib/sequential_executor.js:116:18)
(node:2001) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:2001) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

The things I have tried are a non text containing image, text containing image, table containing image, a single page pdf and a multi page pdf. I also have a conceptual doubt that if I imported the aws-sdk already , why should I code for pdf as the aws-sdk for textract looks after the image of the form pdf , png, jpeg and jpg?
What changes do I have to make to textractUtils.js for it ot process th epdf files also?

A: The AnalyzeDocument API operation only supports images in PNG or JPEG format. From the Textract documentation:

Amazon Textract synchronous operations (DetectDocumentText and AnalyzeDocument) support the PNG and JPEG image formats. Asynchronous operations (StartDocumentTextDetection, StartDocumentAnalysis) also support the PDF file format.

You should use the asynchronous operations to process your PDF documents. Else, a work-around would be to convert the PDF document into images in your code and then use the synchronous API operations with these images to process the documents.


text:
Q: Uniqueness of morphism in definition of category theory product (etc) I'm trying to understand the categorical definition of a product, which describes them in terms of existence of a unique morphism that makes such-and-such a diagram commute. I don't really feel I've totally understood the motivation for this definition: in particular, why must that morphism be unique? What's the consequence of omitting the requirement for uniqueness in, say, Set?

A: This is a question which you will be able to answer yourself after some experience ... anyway:
The cartesian product $X \times Y$ of two sets $X,Y$ has the property: Every element of $X \times Y$ has a representation $(x,y)$ with unique elements $x \in X$ and $y \in Y$. This is the important and characteristic property of ordered pairs. In other words, if $*$ denotes the one-point set: For every two morphisms $x : * \to X$ and $y : * \to Y$ there is a unique morphism $(x,y) : * \to X \times Y$ such that $p_X \circ (x,y) = x$ and $p_Y \circ (x,y) = y$. But since we can do everything pointwise, the same holds for arbitrary sets instead of $*$: For every two morphisms $x : T \to X$ and $y : T \to Y$ (which you may think of families of elements in $X$ resp. $Y$, also called $T$-valued points in the setting of functorial algebraic geometry), there is a unique morphism $(x,y) : T \to X \times Y$ such that $p_X \circ (x,y) = x$ and $p_Y \circ (x,y) = y$. Once you have understood this in detail, this motivates the general definition of a product diagram in a category. After all, these appear everywhere in mathematics (products of groups, vector spaces, $\sigma$-algebras, topological spaces, etc.). Of course, the uniqueness statement is essential. Otherwise, the product won't be unique and in the case of sets you will get many more objects instead of the usual cartesian product. In general, an object $T$ satisfies the universal property of $X \times Y$ without the uniqueness requirement iff there is a retraction $T \to X \times Y$. So for example in the category of sets every set larger than the cartesian product will qualify.

A: Well, a set-map $f:X\to A\times B$ should be uniquely determined by its components $f_A:X\to A$ and $f_B:X\to B$, and conversely any two functions $X\to A$ and $X\to B$ should combine to a map $X\to A\times B$.
This is basically a tautology in terms of the ususal construction of the set-product: writing $f(x)=(a_x,b_x)$ yields the functions $x\mapsto a_x$ and $x\mapsto b_x$.
In other words $f\mapsto (f_A,f_B)$ should be a bijection
$$\text{Hom}(X,A\times B)\to \text{Hom}(X,A)\times \text{Hom}(X,B).$$
The uniqueness (resp. existence) part corresponds to injectivity (resp. surjectivity) of this map.
If you drop the uniqueness part, you will get many products. For example $A\times B\times Z$, for any set $Z$, will then be a product (with the projections to $A,B$). Indeed, the map
$$\text{Hom}(X,A\times B\times Z)\to \text{Hom}(X,A)\times \text{Hom}(X,B)$$
(sending a map to its $A,B$-projections) is surjective but highly non-injective: we are free to choose the $Z$-component.


text:
Q: Adding "email this wiki page" button on Enterprise wiki page I want to able to add a button on the EnterpriseWiki.aspx page with a certain javascript code that opens Outlook and has the wiki page ( the aspx file ) in attachment so users can easely share content trough email. I allready have a button that prints the entiry page so I assume it is possible to have a similar one to email the aspx file.
Thanks !
Kevin

A: You need a combination of mailto and the current URL which you should be able to get from document.URL using JS.


text:
Q: Mobile number field should not accept continous 1s, 2s etc I am trying to make a regexp for mobile number field such that, it would not accept the following type of inputs:

*

*0000000000

*1111111111

*2222222222

like wise continuous same 10 digits. How to avoid accepting continuous similar ten digits as input for mobile number field?

A: A simple regex solution would be to capture the first digit and check if it's repeated 9 times and then take necessary actions. As you haven't mentioned any other tag I will leave it up to you to apply necessary actions.
Regex: /(\d)\1{9}/g Captures the first digit and if it's repeated 9 times then it matches pattern.
Regex101 Demo

A: You can use NOT REGEXP_LIKE(MOBILE_NO,'(.)\1{9,}') like below to suppress the unwanted input. But as suggested by Joachim, it is better to avoid it from front end if possible. Check this query and let me know if you get any issue.
WITH TBL(MOBILE_NO) AS
( SELECT '1111111111' FROM DUAL UNION
 SELECT '1234444444' FROM DUAL UNION
 SELECT '2222222222' FROM DUAL
 )
SELECT * FROM TBL
where NOT REGEXP_LIKE(MOBILE_NO,'(\d)\1{9,}')

This will give output as 1234444444 and will skip other mobile_no, where there are 10 consecutive same numbers.
Referred this answer to get this.


text:
Q: Get the changeset number of a triggered build in TFS 2010 Can someone please tell me how I can get the changeset number, the current build of TFS 2010 was triggered for?
I want to extend the build worklfow if the build was triggered by a checkin and want to do some more processing for which I need the changesetnumber of the changeset that was created by the checkin.
Any ideas?

A: I found the Solution. The Changesetnumber for which the build is triggered is populated in the Variable:
BuildDetail.SourceGetVersion

A: Using an extension from http://msbuildtasks.tigris.org/, you can do this with the TfsVersion task in the Build project:
   <MSBuild.Community.Tasks.Tfs.TfsVersion LocalPath="$(SolutionRoot)">
      <Output TaskParameter="Changeset" PropertyName="Revision" />
    </MSBuild.Community.Tasks.Tfs.TfsVersion>


text:
Q: Why does Intellij show 'ghost' changes in a multi-modular git project? I'm working on a multi-module project with each module being contained in a separate git repo.
When I open the Commit Changes dialog in Intellij, alongside changes to java files I've made, I often see supposed changes to other modules which haven't in fact changed.
In the change-tree, underneath these unchanged modules, there will be an item with just the name of the git repository, with no file extension, and a question mark icon signifying that Intellij doesn't recognize the file type.

When I click on the item, the in-built diff viewer gives fatal: Not a valid object name followed by a 40 character hex string.

If I revert the changes on that module, it will reappear immediately.
Is there a reason this happens, and will it cause any problems?

A: This looks very similar to submodule objects, and the behavior will be like this if you have committed changes in the submodule, but the reference in the root repo has not changed.
Another possible reason is that git status outputs the folder as modified, which could happen in case of nested repositories which are not properly ignored in the root repo. In this case, make sure that .gitignore in the root repo contains folders of the nested repos.


text:
Q: How to find total number of friends groups I have a friendship graph as follows
I want to find all the possible group of friends. What is the best algorithm to find these grouping. For example in this graph , possible friendship groups are as follows: 1,2,3,4,12,13,23,123,14,143,124,1234
If I use brute-force algorithm (starting from each vertex and do this 4 times), it generates lots of duplicates.

A: According to the Wikipedia it's NP-complete so you can only use brute-force for detecting such sets. The problem is called Clique problem and is one of first identified NP-complete problems.


text:
Q: Maximal ideal in ring Z In wikipedia it says:
In the ring $\mathbb{Z}$ of integers the maximal ideals are the principal ideals generated by a prime number.
But I think $(2)\subsetneq(2)\cup(3)$, which means that $(2)$ is not maximal ideal?
What's wrong with my statement?

A: $(2)\cup (3)$ is not an ideal: $2+3\notin (2)\cup (3)$.

A: If by $(2)\cup(3)$ you mean $(2,3)=(2)+(3)$, i.e. the ideal generated by $2$ and $3$, notice that it is the whole ring $\mathbb{Z}$, since it contains $1$.


text:
Q: recipe with Makefile in subdirectory I'm writing a yocto recipe that uses a Makefile style package, not autotools.
I fetch the code from git correctly but the Makefile is not in the root folder, it's in a subfolder. I've tried the option:

EXTRA_OEMAKE += "-I${S}/include -C${MAKEFILE_FOLDER}"

but make doesn't find the target. Can anyone give me a hand on how to do this?
Thanks

A: Your question is not clear.  You should say what and where the file is that you are writing the above text in, and isolate that file to the smallest possible case that reproduces the problem.  You should quote what command you are using, from what directory, and what the error message is.
Through the process of isolation you will often come up with the solution yourself.
In any case, it seems you are confusing compiler options and Make options.
-C $(DIR) is an option for the make program
-I $(DIR) is an option for the compiler
You cannot generally give options to two different programs at once and hope that the first program will pass the second option to the second program.


text:
Q: Conversion of series to Dataframe Issue After using groupby on a Dataframe to group and sum column data into a series I then converted the result back to a Dataframe using .to_frame method which I then converted to html for output to a file. This appears to work well except that the header row has a zero in the last column which I am unable to delete - any ideas? - see here
0
Board Type NE Type Hardware Version Software Version

enter code here:

   NE_3 = NE_2.groupby(NE_2.columns.tolist(), as_index=False).size()
   NE_3 = NE_3.to_frame()

   NE_2 = NE_2.drop_duplicates()
   NE_3 = NE_3.drop(columns='NE Type') # This doesn't work due to the '0' corrupting the header row
   html_txt = NE_3.to_html()
   tfile.write(html_txt)
   tfile.write('<br/>')

A: Try - NE_2 = NE_2.drop([0], axis=1) if the name of last column is 0.
In case, the name of the last column is Version0, you could try this -
cols = NE_2.columns
cols = cols[:-1] + cols[-1].replace('0','')
NE_2.columns = cols

A: The easiest method is to write the Dataframe back as a csv file and then re-read it - this resolves the displacement in the header row. The '0' column can then be simply renamed -
NE_3 = NE_3.rename(columns={'0':'Total'})


text:
Q: Not able to view images in w3m I was playing around with w3m (command-line browser), and found that it was not able to display images when run from Terminator or gnome-terminal. But, when run from xterm, it is able to display images.
I have both w3m and w3m-img packages installed.
After searching around a bit, I found some references about enabling frame buffer and stuff and couldn't quite understand all the terminology.
What should I do to make terminator run w3m properly with image preview support?


text:
Q: Real time reporting software I have this problem and was wondering if anyone can help. I have a number of data feeds (CSV files, web APIs) that I would like to report on but can't find anything open source or paid that can do the job. Basically I want to be able to attach any data feed to this system and build a simple report (select fields, couple of aggregations) which are then distributed to my team. The system could either be a desktop app or web based, don't mind. Each member of my team would have different levels of access to this and the report would present the data in tabular formats, charts and pivots. I looked at Tableau and Qlikview but they are not ideal for real time reporting.
Any ideas if there is anything like that out there?

A: Altough not a reporting tool , theres an charting api called highcharts which has components for real time reporting, the only problem is that you will have to code everything.

A: Power BI has the option of creating link, and then the data get refreshed automatically. If you import it then it's not real time.

A: I think, you can use signalR. Here is the link : https://learn.microsoft.com/en-us/aspnet/signalr/overview/getting-started/introduction-to-signalr


text:
Q: Android Studio Firebase Здравствуйте у меня следующая проблема. При запуске приложения оно вылетает с ошибкой App has been stoped. По логам ошибка указывает на
firebaseAuth = FirebaseAuth.getInstance();
Перепробовал много вариантов - не помогает.
Вот лог ошибок
2019-03-26 22:36:48.960 8571-8571/com.example.sms E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.sms, PID: 8571
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sms/com.example.sms.MainActivity}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.sms. Make sure to call FirebaseApp.initializeApp(Context) first.
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.sms. Make sure to call FirebaseApp.initializeApp(Context) first.
        at com.google.firebase.FirebaseApp.getInstance(SourceFile:218)
        at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source:1)
        **at com.example.sms.MainActivity.onCreate(MainActivity.java:36)**
        at android.app.Activity.performCreate(Activity.java:7009)
        at android.app.Activity.performCreate(Activity.java:7000)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

MainActvity
   package com.example.sms;

import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button registration;
    private EditText mail;
    private EditText password;
    private ProgressDialog progressDialog;
    protected FirebaseAuth firebaseAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        firebaseAuth = FirebaseAuth.getInstance();
        progressDialog = new ProgressDialog(this);

        registration = (Button) findViewById(R.id.registration);
        mail = (EditText) findViewById(R.id.mail);
        password = (EditText) findViewById(R.id.password);

        registration.setOnClickListener(this);
    }

    private void registerUser(){
        String email = mail.getText().toString().trim();
        String pass = password.getText().toString().trim();

        if(TextUtils.isEmpty(email)){
            Toast.makeText(this, "Please,enter email",Toast.LENGTH_SHORT).show();
            return;
        }
        if(TextUtils.isEmpty(pass)){
            Toast.makeText(this, "Please,enter password",Toast.LENGTH_SHORT).show();
            return;

        }
        progressDialog.setMessage("Registrening...");
        progressDialog.show();

        firebaseAuth.createUserWithEmailAndPassword(email,pass)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if(task.isSuccessful()){
                            Toast.makeText(MainActivity.this, "Succefully", Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(MainActivity.this, "Try again", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        if(v==registration){
           registerUser();
        }
    }
}